Compare commits

...
Author SHA1 Message Date
ates 8a00743d99 Leave unverified Xbox DirectStorage error output untouched
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:36:28 +03:00
ates 3154497424 xcrdapi: address devil8blade's review of the Xbox DirectStorage adapters
- IDStorageFactoryX::SetStagingBufferSize logs that the size has no effect, as the public factory does, instead of 'accepted'.
- CreateQueueX documents that the queue priority is ignored on purpose: the Xbox range is not part of the inferred contract.
- test_xcrdapi_xbox requires BX_LOG_FILE and reads only what its own run appended.
- New error-path checks: a memory request on a file queue, a size mismatch, an out-of-range status index, and an enqueue after Close.

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

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

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

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:33:39 -07:00
ates 133ffd4c97 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:30:49 +03:00
Eterna b76066eafb docs_hygiene: slug a heading's rendered text, not its link URL
GitHub slugs the rendered heading, so an inline link contributes only
its text. Slugging the raw source appended the URL, which made a
heading with a link disagree with GitHub's anchor -- including
README.md:53 -- so the first real link to it would be reported as a
broken fragment.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:25:13 -07:00
Ateş 2b2a9e15a6 Merge pull request #629 from EternaPeptix/track-b/597-xcrdapi-vtable-abi
validate: derive the xcrdapi public DirectStorage slot order and staged-copy fence lifetime (#597)
2026-11-28 08:18:03 +03:00
Eterna 67f3b618ab test: verify xcrdapi public DirectStorage vtable ABI
Closes #597

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

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:13:07 -07:00
Ateş 297251fb00 Merge pull request #611 from EternaPeptix/track-c/576-stream-pso-gate
[M2-C12] d3d12_xs: run stream pipeline states through the shader gate
2026-11-28 08:06:16 +03:00
ates b29ccc60e1 test_shader_gate: restore the wave64 refusal assertions from #609
The rebase onto main kept the pre-#609 assertions (wave64 PSO only printed, record expected as pass_dxil), so the fixture failed against main's shim. Restore #609's checks: the wave64 PSO returns E_NOTIMPL with no object, and the shader_gate record is reject_wave_wide. The stream PSO checks are unchanged.

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

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

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:56:33 -07:00
Eterna 32b371e55f xg_xs: implement the SW_64KB_S BC family layout
Closes #505

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

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

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

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

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

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

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

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

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

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

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

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:11:52 +03:00
Ateş 88e6cf00b9 Merge pull request #602 from MacosPorters/track-d/dxbc-accc-nobc-header-only
[M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
2026-11-28 07:05:13 +03:00
Ateş 2d8685681b Merge pull request #610 from EternaPeptix/track-d/586-timeout-overflow
[M2-D6] d3dmetal-harness: saturate an overflowing timeout deadline
2026-11-28 06:56:41 +03:00
ates 25d5240dd0 Merge remote-tracking branch 'origin/main' into pr-610
Signed-off-by: ates <ahmetrizaates@hotmail.com>

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

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

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

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

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

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

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

Closes #500

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

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

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

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

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

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

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

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

Closes #500

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

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

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

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

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

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

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

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

README only; no code, test or abi change.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:49:36 -07:00
Eterna c33199264a test_shim_exports: load bx_shader_bridge.dll, covering all 17 DLLs
The fixture that exists to prove every shipped shim loads and
resolves its exports covered 16 DLLs -- the mingw-w64 C++ shims --
and skipped bx_shader_bridge.dll, the Rust-built 17th DLL from
#484. That was the gap #526 documented.

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

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

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

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

Closes #527

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

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

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

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

Closes #537

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

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

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

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

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

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

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

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

Four defects fixed:

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

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

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

Closes #507

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

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

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

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

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

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

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

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

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

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

Closes #515

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

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

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

Closes #515

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

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

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

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

Closes #547

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

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

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

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 04:57:54 +03:00
atharvranjan 989abbdc2c [M2-D] dxbc-accc: deduplicate DXIL state and add NOBC bounds tests
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:29:56 -06:00
atharvranjan 140dce0be1 Merge remote-tracking branch 'origin/main' into track-d/dxbc-accc-nobc-header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:27:40 -06:00
Ateş 2faadeef7e Merge pull request #600 from MacosPorters/docs/merge-eligibility-policy
Clarify pull request merge eligibility
2026-11-28 03:32:26 +03:00
atharvranjan ce5968a2db Merge pull request #601 from 1Bartosz/track-d/599-fspx-layout-mismatch
[M3-D2] dxbc-accc: report an FSPX layout mismatch apart from out-of-bounds (#599)
2026-11-27 18:30:40 -06:00
atharvranjan 494e53b8fb [M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:29:50 -06:00
Bartosz Szczepański d6586b1fa3 docs: name FspxLayoutMismatch where ADR 0008 and the roadmap cite the FSPX scan (#599)
ADR 0008 and the roadmap (#588) say dxbc-accc rejects the 29 scanned
FSPX containers with FspxSectionOutOfBounds. The cause they record, a
descriptor offset inside the reserved header-plus-table region, is
FspxLayoutMismatch after this branch. Both now say which error the scan
saw, which one the same cause maps to now, and that the scan was not
re-run. The C ABI still returns BX_SHADER_ERR_INVALID_BLOB for both.

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

# Conflicts:
#	CHANGELOG.md
2026-11-28 01:10:37 +01:00
Ateşandatharvranjan 2ef175c0ce Roadmap: prioritize startup diagnosis and define first-frame acceptance (#588)
* docs: prioritize startup diagnosis and define first-frame acceptance

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

* docs: clarify roadmap verification and memory scope

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

* docs: record the target-workload shader corpus scan

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

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

---------

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

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

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

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

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

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

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 01:49:18 +03:00
Eterna b96aa5c0b8 [M2-D5] judge reported shader model
Reviewed current head and checks; no remaining blockers.
2026-11-27 15:53:16 -06:00
EternaandEterna 463169f72c [M2-A3] bx-cli trace: summarize shader_gate, D3DMetal-gap and bridge-missing records (#497)
* bx-cli trace: summarize shader-gate records

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

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

Closes #496

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

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

From the #497 reviews:

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

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

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

* bx-cli: restore the doc comment on format_shader_gate_section

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

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

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

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

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

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

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

Closes #496

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

---------

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

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

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

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

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

Closes #498

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

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

Address review comments on #499:

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

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

Documentation only.

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

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

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

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

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

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

Documentation only; docs_hygiene.py 0 problems.

Closes #498

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

---------

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

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

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

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

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

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

Closes #525

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:05:47 -06:00
EternaandEterna 21323cab80 docs: point ADR 0005 at the archived progress.md (#570)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:04:59 -06:00
Ateş b8724bf04f Merge pull request #486 from devil8blade/track-c/464-d3d12-vmem-placed
[M2-C1] Back configured D3D12 regions with one WRITE_BACK heap (#464)
2026-11-27 06:35:00 +03:00
ates 40a9cebb83 [M2-C1] Retain heap charges for live placed resources
Attach the charged heap to each base placed resource, describe the backing map lifetime, and serialize shared vtable installation before device publication. Exercise dependent heap charges and parallel device creation under the 512 MiB title cap.

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

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

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

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

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

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

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

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

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

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

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

Refs #468

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

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

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

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

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

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

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

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

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

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

Refs #466

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

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

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

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

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

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

Closes #484

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

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

Refs #484

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

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

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

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

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

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

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:44:27 +01:00
sahib453 01a7435d35 Address review: budget pauses across phases, detect replaced logs
A pause during wineboot is no longer charged to the guest's share of
--timeout: supervise reports total suspended time and cmd_run subtracts
it from the wall clock. The trace summary recognizes the pre-run log by
file identity and by the bytes before the old end instead of by size,
so a log replaced by an equal or larger file is summarized in full.

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

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

Refs #466

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

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:23:19 +01:00
jelly013 884f5398e7 d3d12_xs: M2 shader format gate at pipeline creation
CreateComputePipelineState and CreateGraphicsPipelineState now pass
every stage through bx_shader_bridge.dll (#445) and log one
shader_gate JSONL record per stage: container kind, stage, shader
model, chunk sizes, SFI0 feature flags and PSV0 wave lane range.

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

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

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

Closes #466

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

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 01:11:47 +05:30
81 changed files with 15539 additions and 419 deletions

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install Rust toolchain
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
rustc -vV
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
run: |
+27
View File
@@ -0,0 +1,27 @@
name: Merge policy audit
# Detects a pull request merged by its own author (AGENTS.md §7, "Merge
# eligibility"). GitHub rulesets cannot block this, so the run fails after the
# merge. It is not a required check and never checks out pull request code.
on:
pull_request_target:
types: [closed]
branches: [main]
permissions: {}
jobs:
author-merge:
name: Author did not merge
if: github.event.pull_request.merged == true && github.event.pull_request.merged_by.login == github.event.pull_request.user.login
runs-on: ubuntu-24.04-arm
timeout-minutes: 2
steps:
- name: Report a self-merge
env:
PR: ${{ github.event.pull_request.number }}
AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
echo "::error::Pull request #$PR was merged by its own author, $AUTHOR. A maintainer other than the author must merge (AGENTS.md section 7)."
exit 1
+62 -26
View File
@@ -4,9 +4,9 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
---
## 0. First-Time Contributor Onboarding
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
1. **Preflight host & tools:**
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
@@ -14,21 +14,33 @@ If the user asks to contribute, get started, or pick a task (even with a short p
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
2. **Discover & pick an unclaimed issue:**
- Query ready issues in the active milestone:
2. **Select work in strict priority order:**
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
```
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
- **Priority 2 — Pick an unclaimed open issue:**
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
```sh
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
```
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
3. **Claim & isolate:**
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
- **Priority 3 — Review & independently verify open PRs needing review:**
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
```sh
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
```
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
3. **Claim & isolate (for Priority 2 issue work):**
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
4. **Implement strictly in scope:**
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
5. **Verify locally (including hosts without CrossOver):**
- Run every command in Section 8 and fix all warnings/failures before stopping.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
6. **Review & submit PR:**
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
@@ -64,8 +76,8 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
### Cross-Track `[ABI]` Rule
- Never edit another track's directory inside a feature PR.
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
- For issue-claimed contributor work, stay inside your issue's track directory; if your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first so provider and consumer tracks can implement in parallel.
- Maintainer-directed compatibility and startup-unblocking tasks may touch the required shim and `tests/conformance/` directories across tracks without a pre-existing issue claim. They must not overlap another contributor's active claim or open PR without that contributor's or a maintainer's recorded agreement, any new cross-DLL helper or export still goes through an `abi/`-only `[ABI]` PR first, and independent review (Section 5) still applies.
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
---
@@ -81,9 +93,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
## 4. Dependencies, Licensing & Provenance
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
_Reserved — policy migration in progress._
---
@@ -97,26 +107,34 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
---
## 6. Legal & Clean-Room Rules
## 6. Compatibility Evidence & Legal Boundaries
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
---
## 7. Claiming, Git Safety & Changelog
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
3. **Isolate with branches or worktrees:**
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
2. **Isolate with branches or worktrees:**
```sh
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
```
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
### Merge eligibility
Four roles are separate: the **original author** (who opened the PR), **corrective contributors** (who later push to its branch), **independent approvers**, and the **merger**.
- The original author never merges their own PR. Any other maintainer may merge once required checks pass, at least one approval is current and blocking review conversations are resolved.
- Maintainers may resolve conflicts, correct defects, update documentation and push fixes to a contributor's PR branch where GitHub permissions allow. Doing so does not disqualify them from merging.
- Any push that changes the PR dismisses earlier approvals. After a **routine** push (conflict resolution that changes no behaviour, changelog correction, minor documentation fix), one new approval is enough and may come from the maintainer who pushed it, if they are not the original author. No further approval is required beyond the ruleset.
- **Substantive** implementation changes need independent review (Section 5): the approval must come from someone who did not write them. A maintainer who wrote substantive corrections may merge after another person has approved those corrections, but may not approve them. If in doubt, treat a change as substantive.
- A coding agent acts as the person it works for and merges only with that person's authorization.
The `Protect main` ruleset enforces pull requests, one approval, dismissal of stale approvals, resolved conversations, the required CI checks and no force push or deletion, with no bypass actors. GitHub cannot enforce two rules above: who may merge (`Merge policy audit` only fails after an author self-merge) and whether an approver wrote part of the change.
---
@@ -129,8 +147,9 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
# 2. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust bx_shader_bridge.dll, and
# build the auto-discovered conformance EXEs
# (strictly verifies all 17 .edata Export Directories: names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
scripts/build-shims.sh
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
@@ -141,3 +160,20 @@ target/debug/bx-cli trace /tmp/bx-test.jsonl
# 4. Repository Markdown link & hygiene check
python3 scripts/audit/docs_hygiene.py
```
---
## 9. AI Agent Efficiency & Resource Management
These rules apply to every coding agent, whatever its model, vendor or plan. Saving resources never justifies skipping necessary verification, fabricating or assuming results, weakening a security, legal or provenance safeguard, or bypassing independent review. Where this section and Sections 4–8 appear to conflict, Sections 4–8 win.
- **Spend in proportion:** Keep token consumption, API usage, reasoning effort and compute cost as low as correctness allows.
- **Reuse what is still valid:** Reuse conversation context, repository knowledge, review findings and verification evidence. Evidence is valid only for the revision and environment it was recorded on; re-run whatever a later change could affect.
- **Read narrowly:** Inspect relevant files and incremental diffs instead of rescanning the repository. Batch independent tool calls and GitHub API requests where practical.
- **Delegate sparingly:** Avoid unnecessary subagents, duplicate investigations and overlapping responsibilities. Independent review (Section 5) is not duplicate work.
- **Reasoning effort:** Default to low for routine tasks and for helper subagents; raise it only when technical complexity justifies it or the user asks.
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and eligible (Section 7), instead of stopping at intermediate reports. This grants no permission beyond Section 7.
- **Escalate real uncertainty:** Raise genuine doubt about ABI compatibility, memory safety, concurrency, security, GPU synchronization, licensing or architecture with a maintainer rather than guessing.
+88
View File
@@ -9,7 +9,72 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Changed
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
### Added
- Added `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.
- `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).
### Fixed
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
- `bx-cli 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.
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
- `XCRDAPI.dll` completes a multi-request batch from one `Submit()` in queue order into CPU memory, mapped D3D12 upload buffers, and default buffers (a copy on the resource's device when the heap is not CPU-visible). If that copy has been submitted and its GPU completion is not confirmed, the shim keeps the destination and the copy's GPU objects alive and logs a warning, unless the device was removed or the fence already reached the waited value. The request still returns the failure HRESULT. LZ, BCPack, and GDeflate requests finish as `E_NOTIMPL` and log `BX_VTABLE_STUB_LOG`. `DStorageGetFactory` remains the only export (#467).
- M2 Shader Format Gate (#466). `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` classify every stage through `bx_shader_bridge.dll` (#445) and log one `shader_gate` JSONL record per stage: kind, stage, shader model, chunk sizes, `SFI0` feature flags and `PSV0` wave lane range.
- **Decisions:** DXIL and dual containers go to the host as the bridge's prepared copy. ACCC-only containers are refused with `E_NOTIMPL` before the host is called. Legacy DXBC and unclassifiable input pass unchanged. The bridge is loaded only by full path from `d3d12_xs.dll`'s directory. A missing bridge is logged once as `shader_bridge_missing`. Shaders then pass unclassified, but a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it.
- **D3DMetal gaps:** stages needing a wave wider than 32 lanes or 64-bit atomics also log `shader_d3dmetal_gap`, the cases #453 measured as created but not run. The structural check now counts an `ACCC` chunk as a shader chunk, so the gate decides it.
- **Test:** `tests/conformance/test_shader_gate/` runs a real DXC SM 6.6 compute shader through `d3d12_xs` and checks 256/256 output words. It requires `E_NOTIMPL` for an ACCC-only compute and graphics shader, and checks the logged wave64 and typed 64-bit-atomic constraints and every JSONL record. It then reruns itself from a directory without the bridge, which must still run DXIL and refuse ACCC-only. It passed on one Apple M5 Pro in a CrossOver 26.3 D3DMetal bottle. A bare prefix's vkd3d cannot load a DXIL converter, so the DXIL part needs the D3DMetal backend. `scripts/build-shims.sh` stages the bridge it needs (#484).
- **ADR:** [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) proposes Branch D1 for M3, with the evidence; it is pending maintainer acceptance.
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
@@ -26,6 +91,7 @@ remains unsupported.
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
- `QueryApiImpl` also serves offline XGameSave and XPackage on the public COM class and interface ids, with slot order from [xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) commit `7090008692569aa6081e30dfdd9de58237741e24` (#468). The ids and slot order come from that documentation; its provenance is recorded in `docs/research/upstream-registry.md` and the component reuse matrix, pending maintainer acceptance. `XPackageMountWithUiAsync` / `XPackageMountWithUiResult` (`IXPackageImpl2` slots 37–38) now mount through the XAsync engine, like `XPackageMount`. `IXError` slot 3 now returns `false`, following the #492 review's observation that the GDK's static library continues only on `false`; that source lists the slot as unknown.
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
@@ -38,6 +104,12 @@ remains unsupported.
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
- `bx_runtime_veh.dll` handles illegal-instruction traps for CLZERO, MONITORX, MWAITX, RDPRU, EXTRQ and INSERTQ (#451). The decoder and fixture derive the encodings and expected results from the AMD Architecture Programmer’s Manual [volume 3](https://kib.kiev.ua/x86docs/AMD/AMD64/24594_APM_v3-r3.36.pdf) (24594, rev. 3.36) and [volume 4](https://kib.kiev.ua/x86docs/AMD/AMD64/26568_APM_v4-r3.25.pdf) (26568, rev. 3.25, EXTRQ pp. 139–140 and INSERTQ pp. 154–155).
- CLZERO clears a 64-byte cache line selected by RAX or, with the `67` prefix, EAX. An unwritable target is reported as a write access violation at the line address and the guest can repair the page and retry. One-shot Windows guard-page behavior is outside this emulation.
- MONITORX arms no host monitor. MWAITX yields once, so the EBX timer and ECX extensions have no effect. RDPRU approximates MPERF and APERF with the same timestamp rate and returns zero for unknown selectors. It clears the five flags specified by AMD and chooses zero for CF, whose value the manual leaves open.
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
- `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.
@@ -76,11 +148,19 @@ remains unsupported.
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
### Removed
- Removed the repository-wide provenance, third-party licensing and legal-boundary rules from `AGENTS.md`: §4's per-file license audit and proprietary-component restrictions, §6's "Conditions for target builds" (including lawful acquisition, no leaked or unauthorized builds, no decryption or circumvention, and "If any condition is unknown, do not use the build"), the §6 "Repository & clean-tree boundary" and "Legal boundary" rules, plus the earlier removals of §4's "Provenance first" and §6's "Never obtain or use" bullets. §4 is left as a placeholder pending a replacement policy; the §6 "Authorized compatibility evidence" and §5 honesty rules stay. Nothing in `CONTRIBUTING.md`, `docs/legal.md`, `docs/claims.toml`, the ADRs or the research registry was changed, so those documents still describe the previous policy.
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Updated the roadmap with the startup checkpoint, synthetic first-frame backing contract, and shared-budget correction. M3 and M6 memory work now has explicit eligibility and measurement criteria.
- Recorded the target-workload shader-corpus scan in the roadmap and [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) (2026-11-28). A read-only container scan of an authorized local test workload — structure only, no run, no extraction, not redistributed — found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, and 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable; its packaged shader archive exposes no plaintext `DXBC` and remains unclassified. `dxbc-accc` accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers with `FspxSectionOutOfBounds` because their section tables do not match the clean-room layout. The roadmap keeps D1, treats the upscaler's ACCC-only containers as a concrete D2 candidate gated on runtime submission (first-frame blocker before the first presented frame, M4 upscaling if only upscaling needs them), and records both parser gaps as Track D prerequisites. Build-specific details stay in a local evidence note. Runtime use is unmeasured: the recorded startup run wrote no `shader_gate` records.
- `dxbc-accc` reports an `FSPX` descriptor whose offset lands inside the 16-byte header or the descriptor table as `ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }`, not `FspxSectionOutOfBounds` (#599). The reserved region cannot hold section data under BetterXen's synthetic layout, so such a table does not follow that layout; it is not merely truncated. A section that runs past the payload end is still `FspxSectionOutOfBounds`. Both `inspect_dxbc` and the C ABI's `summarize_dxbc` path classify it the same way. The container is still refused: `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` keep returning `BX_SHADER_ERR_INVALID_BLOB` with output cleared, and the C ABI is unchanged, so the distinction does not yet reach `d3d12_xs` gate telemetry. One existing test case (offset 0 in a one-section table) now expects the new variant. New unit tests cover the reserved-region boundary, the out-of-bounds case, the unchanged C ABI refusal, and 4,096 seeded random `FSPX` tables without a panic. Synthetic bytes only; the `FSPX` layout itself is unchanged and remains synthetic (`CLAIM-XBOX-ISA-ABI`, class U).
- Added a model-agnostic "AI Agent Efficiency & Resource Management" section to `AGENTS.md` (§9), absorbing the earlier subagent reasoning rule: agents reuse valid evidence, read and verify narrowly and avoid redundant work, without weakening required verification, safeguards or independent review.
- Changed contributor and agent rules (`AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md`): agents now pick work in priority order (fix their own open PRs, then take an unclaimed issue, then review others' PRs); lawfully obtained, maintainer-approved target builds may be inspected locally as compatibility evidence where license terms and law permit, with no decryption or circumvention, and leaked or unauthorized material stays excluded; maintainer-directed tasks may cross track directories without a prior issue claim, while active claims, `[ABI]`-first changes and independent review still apply. Policy only; no compatibility claim.
- Corrected `shader-transpiler/crates/dxbc-accc/README.md` (#498): its "Not done here" section listed the export list, the `build-shims.sh` staging and the `d3d12_xs` PSO hook as outstanding, but those shipped (#445, #484, #466). The section now describes each one and credits the issue that delivered it. Documentation only.
- Documented independent Direct3D acceptance results on CrossOver 26.3 and CrossOver Preview 27, including D3D12 swapchain retention and Wine presentation stalls (#450).
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
@@ -110,6 +190,11 @@ 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
- `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_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 run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
@@ -123,6 +208,9 @@ remains unsupported.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
- `bx-cli run` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers; each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
- `d3dmetal-harness` runner tests no longer give a freshly written script only 300–500 ms to start (#479); both use a 2 s deadline. The kill test now also checks that the probe ran until the deadline and that its process is gone, which catches a timeout path that neither kills nor waits for the probe. It passes the PID-file path as a script argument so temporary directory names containing apostrophes work. Test-only change. Slow script start-up as the cause of the earlier failures is inferred, not measured. `output_complete` is not asserted for the killed probe, because a child spawned by a parallel test may inherit its pipe.
- `bx-cli run` no longer blocks when `--log` names something other than a regular file (#502). The trace-log reads added for #461 opened the path and read it to the end, which waits forever on a FIFO nobody writes to; the log is now opened without waiting and only a regular file is summarized (anything else gets no summary). Also added the missing test for the file-identity half of the replaced-log check (a different file that begins with the old log's bytes), which a reviewer found untested, and documented that Ctrl-Z typed between supervised phases takes effect when the next phase starts. Covered by 2 new unit tests; three deliberate breakages each failed a test. Not run under CrossOver.
### Added
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
+11 -2
View File
@@ -8,7 +8,7 @@ The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
@@ -33,7 +33,7 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
## Clean-Room, Licensing & Provenance Policy
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
@@ -49,4 +49,13 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
git commit -s -m "Describe the change"
```
## Review and Merging
- A PR needs at least one current approval, passing required checks and resolved blocking conversations. Any later push that changes the PR dismisses earlier approvals.
- You do not merge your own PR. A maintainer other than the original author merges it.
- Please leave **Allow edits by maintainers** enabled on fork PRs (GitHub does not offer it for organization-owned forks). Maintainers may then resolve conflicts and push fixes to your branch, and may still merge it.
- A maintainer may re-approve after their own routine fix (conflicts, changelog, minor docs). Substantive changes need approval from someone who did not write them.
The full rule, including what GitHub does not enforce, is in [AGENTS.md](AGENTS.md) §7, "Merge eligibility".
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
+9 -6
View File
@@ -67,7 +67,7 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
| Milestone | Scope | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
@@ -129,7 +129,7 @@ The repository is organized into disjoint track directories around a single froz
| Directory | Track | Stack | Contents |
| --- | --- | --- | --- |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
@@ -165,8 +165,9 @@ cargo build -p bx-cli
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
target/debug/bx-cli doctor
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
# bx_shader_bridge.dll with cargo, and build the conformance binaries
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
scripts/build-shims.sh
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
@@ -208,9 +209,11 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
- **Not yet implemented (M1–M6):**
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
+64 -2
View File
@@ -1,8 +1,14 @@
# Third-party notices
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `GPL-3.0-or-later` source with **one external crates.io dependency**: `libc`, used only by `bx-cli`.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. The crate is licensed `MIT OR Apache-2.0`; its notice and permission text (`LICENSE-MIT` in the 0.2.191 crate) are reproduced under [libc MIT license text](#libc-mit-license-text) below.
## Vendored source files
| Files | Origin | License |
| --- | --- | --- |
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
## External Host Tools & Runtime Dependencies (Never Bundled)
@@ -13,3 +19,59 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
## libc MIT license text
```text
Copyright (c) The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
```
## DirectStorage headers MIT license text
```text
Copyright (c) Microsoft Corporation.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+1 -1
View File
@@ -7,4 +7,4 @@ This directory holds the **only shared interface boundary** across BetterXen's s
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files. One entry is not under `shims/`: `bx_shader_bridge.def` is the export list of `bx_shader_bridge.dll`, the x86-64 Windows build of `shader-transpiler/crates/dxbc-accc` (#445). `scripts/build-shims.sh` links it into that build and verifies it with the shims (#484).
+5
View File
@@ -0,0 +1,5 @@
LIBRARY bx_shader_bridge.dll
EXPORTS
bx_shader_inspect
bx_shader_prepare_for_d3dmetal
bx_shader_free_buffer
+2 -1
View File
@@ -15,6 +15,7 @@
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
## Research, Testing & Licensing
@@ -22,7 +23,7 @@
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — One-host observation to check before M2 presentation work.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
+1 -1
View File
@@ -26,7 +26,7 @@ BetterXen provides integration, configuration, environment management, diagnosti
## Verified implementation capabilities
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md` at tag `native-first-final`, the archive ADR 0006 makes canonical; the file is retired from `main`.
## Planning consequence
+78
View File
@@ -0,0 +1,78 @@
# ADR 0008: M2 Shader Format Gate — Branch D1 (DXIL normalization) for M3
Status: **Proposed** (2026-11-26, issue #466). The choice for M3 is the maintainers' to accept. The evidence below is from local Apple Silicon runs by the implementer and has not been independently reproduced.
## Context
The roadmap's M2 gate asks which shader path M3 builds:
- **Branch D1, DXIL normalization:** shaders reach D3DMetal as DXIL, and BetterXen rewrites only what D3DMetal cannot run.
- **Branch D2, `ACCC`/`FSPX` translation:** console-compiled RDNA 2 code in `ACCC` chunks is translated to DXIL or MSL.
The gate needs a classifier that guest pipeline creation actually reaches, plus measurements of what D3DMetal does with each form.
## What M2 built
- **Bridge (#445):** `bx_shader_bridge.dll` is the x86-64 Windows build of `dxbc-accc`, so guest code can call the inspector.
- **Gate (#466):** `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` pass every stage through `bx_shader_inspect`. One `shader_gate` JSONL record per stage gives:
- the container kind, stage, shader model and chunk sizes;
- the `SFI0` feature flags (`D3D_SHADER_FEATURE_*` values from DirectX-Headers `d3dcommon.h`);
- the `PSV0` wave lane range.
- **Decisions:**
- **DXIL and dual containers:** go to the host as the bridge's prepared copy (`bx_shader_prepare_for_d3dmetal`).
- **ACCC-only containers:** are refused with `E_NOTIMPL` before the host device is called.
- **Legacy DXBC and unclassifiable input:** pass unchanged.
- **A missing bridge:** is logged once (`shader_bridge_missing`). Shaders then pass unclassified, except that a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it. The bridge is loaded only by full path from `d3d12_xs.dll`'s own directory.
- **Known D3DMetal gaps:** a stage that needs a wave wider than 32 lanes, or 64-bit atomics, also gets a `shader_d3dmetal_gap` record.
`tests/conformance/test_shader_gate` exercises all of this.
## Evidence
| Observation | Source | Host and class |
| --- | --- | --- |
| A real DXC 1.9.2609 SM 6.6 compute shader (`fill_cs66`) creates a PSO through `d3d12_xs`, runs, and all 256 output words match the CPU reference. | `test_shader_gate` | Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 (`26.3.0.39832`) bottle with `CX_GRAPHICS_BACKEND=d3dmetal`; class A, this host only |
| The same shader, run outside Wine through `d3dmetal-native` against CrossOver's D3DMetal 3.0, matches 256/256. | [d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) (#417) | Same host; class A |
| An ACCC-only container is refused with `E_NOTIMPL` for compute and graphics, no host object is created, and the device stays usable. | `test_shader_gate` | Same bottle; class A |
| In a bare CrossOver 26.3 prefix (vkd3d), SM 6.6 DXIL PSOs fail with `E_FAIL`. vkd3d reports `Cannot load DXIL conversion library`. | `test_shader_gate`, same host | Class A; DXIL needs the D3DMetal backend under CrossOver |
| `[WaveSize(64)]` kernels and kernels with SM 6.6 64-bit atomics are created but never run on D3DMetal. | [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints) (#453) | Apple M3 Pro, Wine 11.0 source build, D3DMetal 4.0b3; class A for that host |
| DXC records `[WaveSize(64)]` as `PSV0` lanes 64/64, and 64-bit atomics on typed resources as `SFI0` `0x400000`. 64-bit atomics on raw buffers set only `INT64_OPS` (`0x8000`), the same as other 64-bit integer use. | The #453 blobs, read by the gate and by a script | Class A |
| Public sources do not establish a console-native shader container layout. BetterXen's `FSPX` is a clean-room synthetic layout, not a description of a console compiler's format. | `CLAIM-XBOX-ISA-ABI` (class U) in [claims.toml](../claims.toml); `shader-transpiler/crates/dxbc-accc/src/fspx.rs` | Source review |
| A serialized console pipeline path exists for Series X\|S, with no public version-independent format. | `CLAIM-XBOX-ACO-SAMPLE` (class D) | Source review |
| A read-only structural scan of an authorized local test workload (2026-11-28) found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable, and no plaintext `DXBC` in its packaged shader archive. | Static container scan on this host, re-run through `dxbc-accc`; private evidence note, workload not redistributed | This host; structure only, runtime use unmeasured |
Runtime gate telemetry still covers only synthetic programs; no target-workload run has reached pipeline creation, so what a run submits remains unmeasured. One static measurement now exists (2026-11-28): a read-only container scan of an authorized local test workload, re-run through `dxbc-accc`, with the counts in the table above. The scan measures what shipped components contain, not what any run submits, and the workload is not redistributed. Wherever the gate runs, its `shader_gate` records count it.
## Decision
Branch **D1** is proposed for M3:
1. **Pass DXIL through the gate to D3DMetal.** This is the only path with measured, end-to-end execution evidence.
2. **Spend M3 shader work on the two measured gaps,** within the [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints):
- lower `WaveSize(64)` programs to 32-lane code;
- lower SM 6.6 64-bit atomics to 32-bit operations or bounded lock emulation.
The gate's `shader_d3dmetal_gap` records show which pipelines need this.
3. **Keep refusing ACCC-only containers** with `E_NOTIMPL` and a structured log.
Branch **D2** is deferred. It needs a documented, lawfully available description of console-compiled containers and their RDNA 2 code, and none exists (`CLAIM-XBOX-ISA-ABI`). A translator built against the synthetic `FSPX` layout would prove nothing about real inputs.
Revisit this ADR in any of these cases:
- an authorized public source for that format appears;
- gate telemetry shows a required pipeline-creation path refusing an ACCC-only container at runtime — a static scan already established that the target workload's upscaler component embeds 29, so the open question is submission, not existence;
- D3DMetal starts running the gap cases.
## Consequences
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
- **Not covered by the gate yet:**
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
- **`NOBC` programs:** the classifier validates the `DXIL` program header's sizes but not the LLVM bitcode signature, so a container whose bitcode payload is the four-byte placeholder `NOBC` still classifies as executable DXIL and is prepared for the host unchanged. The target workload's main executable embeds 10 such containers (nine pixel, one vertex, SM 6.6). They carry no bitcode, so D1 cannot run them as-is; their signature and validation chunks are intact.
- **Wave size:** the gate logs constraints but changes no shader. A pipeline that D3DMetal creates but does not run still behaves that way.
## Not claimed
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs, one local static container scan of an authorized test workload, and public-source review. The scan counts containers embedded in shipped components on this host; it does not establish what any run submits, and it documents no console-compiled format layout beyond the stated mismatch.
+1 -1
View File
@@ -25,7 +25,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
## Milestones (M0 → M6)
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 16 shim DLLs load cleanly; auto-logging COM proxy captures startup call traces.
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
+1 -1
View File
@@ -1,6 +1,6 @@
# Clean-room scope
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation.
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
## User-provided game files
+3
View File
@@ -21,5 +21,8 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
+70 -2
View File
@@ -1,8 +1,7 @@
# D3D12 swapchain references under D3DMetal
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. Not independently reproduced, and not an
Xbox hardware result.
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. See the independent Apple M2 Pro run below.
| | D3DMetal | Wine `vkd3d` path |
| --- | --- | --- |
@@ -18,3 +17,72 @@ is explained.
The probe is
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
on the branch of #425; it is not part of this branch. Tracked in #450.
## Independent run on Apple M2 Pro
On 2026-11-26, an Apple M2 Pro (16 GiB, macOS 27.3 build 26C5035r) reproduced
the swapchain retention in CrossOver 26.3.0.39832 with D3DMetal 3.0. The
same x86-64 probe under Rosetta 2 released all swapchains in CrossOver
Preview 27.0.0.41303. Each CrossOver build used a fresh Windows 11
64-bit bottle. The Direct3D 12 workload loaded the `apple_gptk` D3D12
and DXGI modules in both builds. The bundled framework in the Preview
build's `apple_gptk` directory reports version 4.0b3.
| Swapchain lifetime probe | Initial reference count | Application release returned | Witnesses retained |
| --- | ---: | ---: | ---: |
| 26.3 D3DMetal | 2 | 1 | 12 of 12 |
| 26.3 Wine D3D12 | 1 | 0 | 0 of 12 |
| Preview D3DMetal | 1 | 0 | 0 of 12 |
| Preview Wine D3D12 | 1 | 0 | 0 of 12 |
Destroying the window before releasing the swapchain and calling
`ResizeBuffers` before teardown each left 3 of 3 witnesses retained on
26.3 D3DMetal. Explicitly detaching the witness released the probe's
private data, while the swapchain's release still returned 1. The
deliberately retained witness control failed as expected. An extra
application-side `Release` would drop a reference the application
does not own.
The separate D3D12 integrated workload presented 600 frames and verified
eight readbacks with zero mismatches on both D3DMetal builds. It failed
only the shutdown gate on 26.3, where the final device release returned
2. Preview passed shutdown with a final device release of 0. These runs
used the direct host D3D12 path without BetterXen's D3D12 shim. The
comparison establishes behavior for these two CrossOver builds on this
host. The underlying ownership change is unknown.
Build the probe from the pinned source linked above with
`x86_64-w64-mingw32-clang -std=c11 -O2 -Wall -Wextra -Werror lifetime.c -o d3d12-lifetime.exe -ld3d12 -ldxgi -ldxguid -luser32`
(LLVM-MinGW 20261117 in this run). Run in a clean bottle using
`ROSETTA_ADVERTISE_AVX=1 CX_GRAPHICS_BACKEND=d3dmetal wine --bottle <bottle> <absolute-path-to-exe> --cycles 12`
and repeat with `CX_GRAPHICS_BACKEND=wined3d`. The two witness controls
use `--cycles 3 --detach-witness` with and without `--retain-app-reference`.
## Related Direct3D acceptance failures
The [integrated D3D12 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_integrated/integrated12.c)
also reproduced the presentation slowdown on the Wine D3D12 path on
26.3. With `CX_GRAPHICS_BACKEND=wined3d` and a 600-frame target, the
workload logged approximately 2,000 ms inside `Present` on frames
12–38, then exited 3 after a 10-second GPU completion wait failed. The
previous M4 report saw the slowdown around frame 437. This run exited
before reaching normal teardown. Preview completed the same 600-frame
workload on the Wine path with eight verified readbacks, no mismatches
and clean shutdown. A 600-frame repeat on 26.3 passed with `--vsync`
enabled. A subsequent 600-frame repeat also passed with the flag off,
so the slowdown remains intermittent and the successful vsync run
does not establish a workaround.
The [integrated D3D11 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d11_integrated/integrated.c)
completed the 20,000-frame soak on 26.3 with 46 verified readbacks,
zero mismatches and a clean shutdown. The intermittent GPU event
stall did not recur in this run. Preview also completed all 20,000
frames and all 46 readbacks, then failed the shutdown gate with one
device reference remaining. A separate 600-frame Preview run
reproduced that shutdown result.
The 26.3 keyboard check delivered five macOS events to the workload and
reached the expected offset (16, 32). The negative control delivered
two Up events and reached (0, -32), which the input gate rejected as
expected. These were isolated runs, so they do not reproduce the
intermittent failure observed inside the full acceptance suite.
+88
View File
@@ -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.
+16
View File
@@ -26,6 +26,22 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
| directx-native | [osy/directx-native](https://github.com/osy/directx-native) | `7258be1c56cdbf1e55c56b1bc4a866169c8ca0da` (pinned by d3dmetal-native's `subprojects/directx-native.wrap`) | Apache-2.0: repository `LICENSE`, plus `SPDX-License-Identifier: Apache-2.0` in 22 of its 25 files | Build dependency of d3dmetal-native, statically linked into the dylib; nothing is copied into BetterXen | Supplies the shared-resource and embedder headers that `d3dmetal_native.h` includes. Apache-2.0 is compatible with GPL-3.0, not GPL-2.0. |
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The package ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
## Interface facts for XGameSave and XPackage (#468, #492)
Facts only, no text or code copied. **Pending maintainer provenance acceptance** under AGENTS.md §4.
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| xgameruntime-docs | [xodus-gaming/xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) | `7090008692569aa6081e30dfdd9de58237741e24` | Repository `LICENSE` is the unmodified GNU GPL version 3 text. No project copyright holder is named, nothing states "only" or "or later", and the documentation files checked (`README.md`, `COM/XErrorImpl/IXErrorImpl.md`, `COM/XPackageImpl/IXPackageImpl.md`, `IXPackageImpl2.md`, `XErrorReport.md`) carry no licence or copyright header. | Source of the interface facts behind the public `QueryApiImpl` entries in `shims/xgameruntime/com_dispatch.cpp`: class and interface ids, interface inheritance, and vtable slot order for `IXGameSaveImpl`–`IXGameSaveImpl3` and `IXPackageImpl`–`IXPackageImpl4`. | Its README says the information "was found using black box reverse engineering" following Wine's clean-room guidelines. It states no use of Microsoft binaries, leaked material or the GDK EULA either way, and the COM notes say the listing is incomplete. It lists `IXErrorImpl` slot 3 only as unknown. BetterXen's answer for that slot (return `false`) instead follows an interop observation in the #492 review (2026-11-26), not this repository. Function signatures come from Microsoft Learn. |
## Vendored for the public PC DirectStorage interfaces (#483)
Checked on 2026-11-26 by reading the package files, not just its metadata. Not legal advice. Details and file hashes: [`shims/xcrdapi/dstorage/README.md`](../../shims/xcrdapi/dstorage/README.md).
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| DirectStorage SDK headers | NuGet [`Microsoft.Direct3D.DirectStorage`](https://www.nuget.org/packages/Microsoft.Direct3D.DirectStorage/1.4.0) | `1.4.0`, package SHA-256 `0838e7f71b14acfbd1ac7ecc5e943f6c95e4f4e679e8a67f8ff6e7c102414321` | `native/include/dstorage.h` and `dstorageerr.h` each carry `Copyright (c) Microsoft Corporation` / `Licensed under the MIT license`; the package's `LICENSE-CODE.txt` is the MIT text. The package as a whole is under the proprietary *Microsoft DirectStorage SDK* terms, whose distributables are only `dstorage.dll` and `dstoragecore.dll`. | The two headers are vendored unmodified in `shims/xcrdapi/dstorage/` for the public `IDStorage*` interfaces in `XCRDAPI.dll` and `test_xcrdapi`. No DLL or other package file is used or redistributed. | The headers are not in the MIT `microsoft/DirectStorage` repository; they ship only in this package. Microsoft Learn documents the same API but gives neither IIDs nor vtable order. The Xbox `IDStorage*X` interfaces (`dstorage_xs.h`) ship only in the GDK with Xbox Extensions, "only available to licensed partners", so they are excluded. |
## Additional candidates found by search (not reviewed)
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
+21 -4
View File
@@ -9,7 +9,8 @@ BetterXen builds a modular **Xbox Series (`Scarlett`) compatibility layer for Ap
```text
BetterXen (in-tree):
launcher/ (ARM64 CLI, probe, telemetry) + abi/ (frozen contracts)
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs)
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs
+ the Rust-built bx_shader_bridge.dll)
shader-transpiler/ (DXBC / DXIL / ACCC / FSPX classifier & RDNA 2 pipeline)
|
External Foundation (user-installed, never bundled):
@@ -24,11 +25,13 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
---
## Completed Research Inputs (Carried Forward)
## Research Inputs
- **Licensing & redistribution boundaries:** [docs/research/crossover-licensing.md](research/crossover-licensing.md) and [docs/licenses.md](licenses.md) (#354). CrossOver, D3DMetal, and Rosetta 2 stay strictly external and unbundled.
- **Primary-source verification & upstream registry:** [docs/research/primary-source-verification-2026-11-25.md](research/primary-source-verification-2026-11-25.md), [docs/research/upstream-registry.md](research/upstream-registry.md), and [docs/research/component-reuse-matrix.md](research/component-reuse-matrix.md).
- **Hybrid measurement protocol:** [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) (#353).
- **Buffer ownership on CrossOver 26.3.0.39832 and D3DMetal 3.0 (#473).** On the tested M4 (24 GiB) and M5 (16 GiB), the two existing-memory heap imports returned `E_NOTIMPL`. A D3D12-owned persistent buffer mapping supported fence-separated CPU/GPU access and ordered virtual aliasing (BASE-2, BASE-4, A-8). The actual CPU address could miss 64 KiB alignment (A-6). Inside the timed small-copy window, no serialized copy cost as much as the explicit full copy to READBACK. The other workstream accepted 13 of 29 register entries within stated scopes, mostly through same-source reruns. #473 remains open. Physical page identity, hidden copies, workload memory savings and speedups remain open. [Report 001](https://github.com/MacosPorters/betterxen/blob/0aaa81ab81309d64432d97d3005284c8b13cd285/docs/research/publications/001-unified-memory/technical-findings.md) · [Evidence register](https://github.com/MacosPorters/betterxen/blob/f8810a48af384d13c594b9fba954200bfdb944f1/docs/research/d3dmetal-zero-copy/allocation-profiling/consolidation-draft/evidence-register.md) · [Review corrections](https://github.com/MacosPorters/betterxen/discussions/493)
- **Target-workload shader corpus (static scan, 2026-11-28).** A read-only container scan of an authorized local test workload measured what its shipped components embed — structure only, no run, no extraction, and the workload is not redistributed. Its `XboxBvhBuilder` component carries **52 DXIL compute containers, all Shader Model 6.5, with valid LLVM bitcode**; its AMD FidelityFX upscaler component carries **29 ACCC-only containers** whose payloads start with `FSPX`, none with a `DXIL` chunk; its main executable carries **10 DXIL containers (nine pixel, one vertex, Shader Model 6.6) whose `DXIL` chunks hold four-byte `NOBC` payloads** — valid program headers, no executable bitcode. Its packaged shader archive exposes no plaintext `DXBC` signatures and remains unclassified. BetterXen's classifier accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers because their section tables do not match the clean-room `FSPX` layout (`FspxSectionOutOfBounds` at the time of the scan; that cause is `FspxLayoutMismatch` since #599, not re-measured). Runtime use is unmeasured: the recorded startup run stopped before pipeline creation and wrote no `shader_gate` records. [ADR 0008](adr/0008-m2-shader-format-gate.md)
---
@@ -36,14 +39,28 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
| Milestone | Objective | Exit Gate | Status |
| --- | --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), integrate the shipped xmem-configured D3D12 placed heap (#464) into the first-frame fixture (#469), bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
### Startup diagnosis
The product goal is to reach a frame presented by the target software. Under the current [contribution rules](../CONTRIBUTING.md), project runs use original synthetic workloads. Start with `test_integration_boot.exe` for startup and `test_veh_unhandled.exe` as a crash-logging control. Use a focused synthetic reproducer once a failing contract is identified.
Before treating either startup warning as causal, add diagnostics that record the requested DirectStorage factory IID and returned HRESULT (#483) and distinguish null, unrecognized and supported BetterXen virtual-memory configurations (#464 follow-up). On a pinned launcher, shim set and backend, repeat the synthetic case before and after a fix. Record normal exit, crash or timeout, the last completed checkpoint, and the exception thread and module offset when available. Progress means reaching the next named checkpoint in the same reproducer. Startup diagnosis and the budget fix proceed alongside the M2 exit gates.
### M2 first-frame acceptance and parallel memory work
- **First frame (#465, #469).** The synthetic placement criterion uses BetterXen's `BXVM` block to configure the separate D3D12-owned WRITE_BACK heap shipped in #486. On the recorded overlay, #494 copied the backbuffer before the flip, counted one host `Present`, then compared 256 RGBA8 pixels through the D3D12 mapping after waiting. The xmem sentinel shows that the original page remained separate. Visibility through the original xmem address remains an open compatibility question for M3, informed by #473. Displayed-image verification is outside this fixture's measurements. Record a single `main` commit containing the integrated presentation and fixture changes, confirm that the fixture executable built, and have someone who authored neither the fixture nor the presentation bridge verify the D3DMetal run and pixel-mismatch control. The shader gate still requires a recorded D1/D2 selection. [Fixture and receipts](https://github.com/MacosPorters/betterxen/pull/494) · [ADR 0008](adr/0008-m2-shader-format-gate.md)
- **Shader format gate (#466, ADR 0008).** D1 remains the only branch with end-to-end execution evidence, and the static scan gives it measured inputs in the target workload: 52 DXIL SM 6.5 compute containers with LLVM bitcode. The same scan makes D2 a concrete compatibility candidate rather than a hypothesis: the workload's FidelityFX upscaler component embeds 29 ACCC-only containers. Select D2 work only when a required pipeline-creation path refuses an ACCC-only container at runtime — if that refusal precedes the first presented frame, treat it as a first-frame blocker; if it appears only with upscaling enabled, track it under M4 upscaling. Two Track D parser prerequisites precede any D2 trial: extend the clean-room `FSPX` section-table layout to accept the observed tables (a maintainer provenance decision, since no public format description exists), and stop the classifier from treating a `NOBC` header-only program as executable DXIL. The first `shader_gate` record the target workload writes names the shader path its first pipeline creation actually submits. [ADR 0008](adr/0008-m2-shader-format-gate.md)
- **Title budget (#550, #552).** Keep current allocation ownership and give xmem atomic admission authority through an ABI-first contract. The initial scope combines xmem usage with the existing charged `CreateHeap` path. Under a 512 MiB cap, an xmem allocation of 256 MiB followed by a 384 MiB heap was refused, while the reverse admitted 640 MiB. Test both orders, concurrent admission and rollback. Charge a backing allocation once across aliases. Accounting for `CreateHeap1`, committed and reserved resources, and internal buffers such as XCRDAPI staging remains an open scope decision. Placement and wrapper lifetime have separate checks (#554, #572). [Merged-base reproduction](https://github.com/MacosPorters/betterxen/pull/486#issuecomment-7209751182)
- **M3 resource handling.** Keep explicit paths for fixed addresses, existing contents, pre-device allocations, sections/scatter and opaque textures. The draft eligibility analysis found no reliable end-to-end classifier. Resolve the `XMemVirtualAlloc` argument-count question (#518) before using graphics flags as evidence. A mapped-buffer trial is optional and opt-in, with the existing path as fallback. Require a known consumer before returning a pointer, verify its alignment and lifetime, and confirm completion on every participating queue before reusing memory for work BetterXen submits. #483 retains its DirectStorage interface scope. [Draft eligibility analysis](https://github.com/MacosPorters/betterxen/blob/7e0b515131150fec6b5117c9498b6c0faf0ca382/docs/architecture/proposals/001-unified-memory/appendix/eligibility.md)
- **M6 optimization.** Compare the existing path with a candidate allocator or bounded pool on the same 16 GB host and backend. Check correct output for both paths across repeated matched workloads. Include cold setup, transfers, fragmentation, pending retirements, post-release footprint and whole-frame time. Require a repeatable workload benefit before choosing a default.
---
## How Progress Is Reported
+728 -70
View File
@@ -7,16 +7,17 @@ use std::collections::BTreeMap;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::time::{Duration, Instant};
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
use bx_telemetry::summarize_jsonl;
use bx_telemetry::{ShaderGap, ShaderGapGroup, TraceSummary, TrapCount, summarize_jsonl};
use dxbc_accc::inspect_dxbc;
use supervise::{Outcome, Stop};
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,xcrdapi,XCRDAPI,xgameruntime,acphal,AcpHal,xapu,chad,gameinput,GameInput,\
api-ms-win-core-psm-appnotify-l1-1-0,api-ms-win-core-psm-appnotify-l1-1-1,\
ext-ms-win-rtcore-ntuser-message-l1-1-0,ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0,\
ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0=n,b";
@@ -165,14 +166,174 @@ fn cmd_probe(path: &str) -> ExitCode {
fn format_clwb_line(clwb_events: usize, clwb_trap_lower_bound: Option<u64>) -> String {
if let Some(lower_bound) = clwb_trap_lower_bound {
format!("clwb VEH traps : at least {lower_bound} (sampled)")
format!("clwb VEH traps : at least {lower_bound} (sampled)")
} else if clwb_events == 0 {
"clwb VEH traps : 0".to_string()
"clwb VEH traps : 0".to_string()
} else {
format!("clwb VEH samples : {clwb_events}")
format!("clwb VEH samples : {clwb_events}")
}
}
fn format_amd_trap_line(name: &str, count: &TrapCount) -> String {
let label = format!("{name} VEH traps");
match count.lower_bound {
Some(lower_bound) => format!("{label:<18} : at least {lower_bound} (sampled)"),
None => format!("{label:<18} : {} samples", count.events),
}
}
/// True when the log carried any shader-gate evidence. A log without it must render exactly as
/// it did before the gate summary existed.
fn has_shader_gate(summary: &TraceSummary) -> bool {
summary.shader_gate.total > 0
|| !summary.shader_gaps.is_empty()
|| !summary.shader_bridge_missing.is_empty()
}
/// One `label : value` line in the same column as the other trace lines.
fn format_shader_line(label: &str, value: impl std::fmt::Display) -> String {
format!("{label:<19} : {value}\n")
}
/// A titled block of `{count:5}x {name}` lines, or nothing when there is nothing to count.
fn format_count_list(title: &str, counts: &BTreeMap<String, usize>) -> String {
if counts.is_empty() {
return String::new();
}
let mut out = format!("\n{title}:\n");
for (name, count) in counts {
let _ = writeln!(out, " {count:5}x {name}");
}
out
}
/// One `shader_d3dmetal_gap` record: the pipeline, stage, wave width it needs, and the 64-bit
/// atomic feature flags that made it a gap. Missing fields say `unknown` rather than being lost.
fn format_shader_gap_line(gap: &ShaderGap) -> String {
format!(
" pso={} stage={} wave_lanes_min={} atomic64_flags={}\n",
gap.pso.as_deref().unwrap_or("unknown"),
gap.stage.as_deref().unwrap_or("unknown"),
gap.wave_lanes_min.as_deref().unwrap_or("unknown"),
gap.atomic64_flags.as_deref().unwrap_or("unknown"),
)
}
/// 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
/// (#497 review point 5).
fn format_non_pass_decisions(gate: &bx_telemetry::ShaderGateSummary) -> String {
let failing: Vec<&bx_telemetry::ShaderGateRecord> = gate
.records
.iter()
.filter(|record| {
record
.decision
.as_deref()
.is_some_and(|decision| !decision.starts_with("pass_"))
})
.collect();
if failing.is_empty() {
return String::new();
}
let mut out = format!("\nNon-pass pipeline decisions ({}):\n", failing.len());
for record in failing {
let _ = writeln!(
out,
" pso={} stage={} decision={} hr={}",
record.pso.as_deref().unwrap_or("unknown"),
record.stage.as_deref().unwrap_or("unknown"),
record.decision.as_deref().unwrap_or("unknown"),
record.hr.as_deref().unwrap_or("unknown"),
);
}
out
}
/// The shader-gate section, or an empty string for a log with no gate evidence.
fn format_shader_gate_section(summary: &TraceSummary) -> String {
if !has_shader_gate(summary) {
return String::new();
}
let gate = &summary.shader_gate;
let mut out = String::from("\nShader gate:\n");
out.push_str(&format_shader_line("shader_gate records", gate.total));
if gate.unparsed > 0 {
out.push_str(&format_shader_line("unparsed details", gate.unparsed));
}
if gate.missing_decision > 0 {
out.push_str(&format_shader_line(
"records w/o decision",
gate.missing_decision,
));
}
out.push_str(&format_count_list("decisions", &gate.decisions));
out.push_str(&format_count_list("kinds", &gate.kinds));
out.push_str(&format_count_list("stages", &gate.stages));
out.push_str(&format_non_pass_decisions(gate));
if !summary.shader_gaps.is_empty() {
let _ = writeln!(out, "\nD3DMetal gaps ({}):", summary.shader_gaps.len());
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!(
out,
"\nShader bridge missing ({}):",
summary.shader_bridge_missing.len()
);
for message in &summary.shader_bridge_missing {
let _ = writeln!(out, " {message}");
}
}
out
}
fn cmd_trace(path: &str) -> ExitCode {
let text = match fs::read_to_string(path) {
Ok(s) => s,
@@ -188,20 +349,23 @@ fn cmd_trace(path: &str) -> ExitCode {
fn render_trace(text: &str) -> String {
let mut out = String::new();
let summary = summarize_jsonl(text);
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
let _ = writeln!(
out,
"{}",
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
);
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
for (name, count) in &summary.amd_traps {
let _ = writeln!(out, "{}", format_amd_trap_line(name, count));
}
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
if !summary.unhandled_exceptions.is_empty() {
let _ = writeln!(
out,
"\nUnhandled exceptions ({}):",
summary.unhandled_exceptions.len()
);
for crash in summary.unhandled_exceptions {
for crash in &summary.unhandled_exceptions {
let _ = writeln!(
out,
" code={} module_base={} + RVA={} RIP={}",
@@ -214,16 +378,17 @@ fn render_trace(text: &str) -> String {
}
if !summary.unimpl_apis.is_empty() {
let _ = writeln!(out, "\nUnimplemented APIs:");
for (api, count) in summary.unimpl_apis {
for (api, count) in &summary.unimpl_apis {
let _ = writeln!(out, " {count:5}x {api}");
}
}
if !summary.unimpl_vtables.is_empty() {
let _ = writeln!(out, "\nUnimplemented COM vtable slots:");
for (slot, count) in summary.unimpl_vtables {
for (slot, count) in &summary.unimpl_vtables {
let _ = writeln!(out, " {count:5}x {slot}");
}
}
out.push_str(&format_shader_gate_section(&summary));
out
}
@@ -499,7 +664,37 @@ fn apply_prefix_env(command: &mut Command, cx_root: &Path, prefix: &Path, winelo
);
}
/// Reports a timeout or signal and stops the environment's `wineserver`. True if cleanup failed.
/// Writes one diagnostic line to stderr. A closed pipe or hung-up terminal is ignored: unlike
/// `eprintln!`, this cannot panic and so cannot cut a run's cleanup short (#461).
fn diag(message: impl std::fmt::Display) {
let _ = writeln!(std::io::stderr(), "{message}");
}
/// Runs `cleanup` and only then reports the stop and any cleanup failures to `out`, ignoring
/// write errors. True if cleanup reported a failure.
///
/// Cleanup comes first so that nothing about the diagnostic stream (Ctrl-C through `| tee`, a
/// closed terminal) can prevent the environment from being stopped (#461).
fn report_stop(
stop: Stop,
cleanup: impl FnOnce() -> Vec<String>,
out: &mut dyn std::io::Write,
) -> bool {
let failures = cleanup();
let _ = match stop {
Stop::TimedOut => writeln!(out, "timed out; stopped the environment"),
Stop::Signalled(signal) => {
writeln!(out, "received signal {signal}; stopped the environment")
}
};
for failure in &failures {
let _ = writeln!(out, "{failure}");
}
!failures.is_empty()
}
/// Stops the environment's `wineserver` after a timeout or signal, then reports it. True if
/// cleanup failed.
fn stop_environment(
stop: Stop,
cx_root: &Path,
@@ -507,34 +702,111 @@ fn stop_environment(
bottle: Option<&str>,
inherit_env: bool,
) -> bool {
match stop {
Stop::TimedOut => eprintln!("timed out; stopping the environment"),
Stop::Signalled(signal) => {
eprintln!("received signal {signal}; stopping the environment");
}
}
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
.into_iter()
.collect();
let mut cleanup_failed = false;
let prefixes_to_stop = match cleanup_prefixes_for_stop(environment_dir, bottle, |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(prefixes) => prefixes,
Err(e) => {
eprintln!("cleanup failed to re-resolve bottle prefix: {e}");
cleanup_failed = true;
vec![environment_dir.to_path_buf()]
let cleanup = || {
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
.into_iter()
.collect();
let mut failures = Vec::new();
let prefixes_to_stop = match cleanup_prefixes_for_stop(environment_dir, bottle, |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(prefixes) => prefixes,
Err(e) => {
failures.push(format!("cleanup failed to re-resolve bottle prefix: {e}"));
vec![environment_dir.to_path_buf()]
}
};
for prefix in &prefixes_to_stop {
if let Err(e) =
supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
{
failures.push(format!(
"cleanup failed, programs may still be running: {e}"
));
}
}
failures
};
for prefix in &prefixes_to_stop {
if let Err(e) = supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
{
eprintln!("cleanup failed, programs may still be running: {e}");
cleanup_failed = true;
}
}
cleanup_failed
report_stop(stop, cleanup, &mut std::io::stderr())
}
/// How many trailing bytes of a log are remembered to recognize it again after the run.
const LOG_MARK_TAIL: u64 = 256;
/// What a trace log was before the run: which file, how long, and how it ended.
#[derive(Debug, Clone, PartialEq, Eq)]
struct LogMark {
/// Device and inode of the file.
identity: (u64, u64),
len: u64,
/// The last bytes before `len` (up to [`LOG_MARK_TAIL`]).
tail: Vec<u8>,
}
/// Opens `path` for reading only if it is a regular file.
///
/// `--log` can name anything. Opening a FIFO nobody writes to, or reading a terminal to its end,
/// would block the run before the guest starts or after it has finished, so the open never
/// waits and anything that is not a regular file is treated as having no log to summarize.
fn open_regular_log(path: &Path) -> Option<(fs::File, fs::Metadata)> {
use std::os::unix::fs::OpenOptionsExt;
let file = fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NONBLOCK)
.open(path)
.ok()?;
// Checked on the open handle, so the file cannot be swapped between the check and the read.
let meta = file.metadata().ok()?;
meta.is_file().then_some((file, meta))
}
/// The mark of the log at `path`, or `None` if there is no readable regular-file log yet.
fn log_mark(path: &Path) -> Option<LogMark> {
use std::io::{Read, Seek, SeekFrom};
use std::os::unix::fs::MetadataExt;
let (mut file, meta) = open_regular_log(path)?;
let len = meta.len();
let tail_len = len.min(LOG_MARK_TAIL);
file.seek(SeekFrom::Start(len - tail_len)).ok()?;
let mut tail = Vec::new();
file.take(tail_len).read_to_end(&mut tail).ok()?;
Some(LogMark {
identity: (meta.dev(), meta.ino()),
len,
tail,
})
}
/// A log's identity and contents, read through one open file so the two cannot disagree.
fn read_log(path: &Path) -> Option<((u64, u64), Vec<u8>)> {
use std::io::Read;
use std::os::unix::fs::MetadataExt;
let (mut file, meta) = open_regular_log(path)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).ok()?;
Some(((meta.dev(), meta.ino()), bytes))
}
/// The part of a trace log that this run added, given the log's mark from before the run.
///
/// The old length is used as an offset only when the log is still the same file and still holds
/// the same bytes just before that offset. A log that was replaced or rewritten during the run,
/// whatever its new size, is new in full, as is a log that did not exist before.
fn appended_since<'a>(bytes: &'a [u8], identity: (u64, u64), before: Option<&LogMark>) -> &'a [u8] {
let Some(mark) = before else {
return bytes;
};
let appended = usize::try_from(mark.len).ok().and_then(|start| {
let old_end = bytes.get(..start)?;
(mark.identity == identity && old_end.ends_with(&mark.tail)).then(|| &bytes[start..])
});
appended.unwrap_or(bytes)
}
/// The part of `elapsed` wall-clock time that counts against `--timeout`: everything except the
/// `suspended` time spent stopped by Ctrl-Z, whichever phase of the run that fell in.
fn active_time(elapsed: Duration, suspended: Duration) -> Duration {
elapsed.saturating_sub(suspended)
}
fn cmd_run(args: &[String]) -> ExitCode {
@@ -601,10 +873,10 @@ fn cmd_run(args: &[String]) -> ExitCode {
match supervise::supervise(boot, timeout, supervise::received_signal) {
Ok(Outcome::Exited(st)) if st.success() => {}
Ok(Outcome::Exited(st)) => {
eprintln!(
diag(format_args!(
"error: wineboot --init failed for {}: {st}",
resolved_prefix.display()
);
));
return ExitCode::FAILURE;
}
Ok(outcome @ Outcome::Stopped(stop)) => {
@@ -613,10 +885,10 @@ fn cmd_run(args: &[String]) -> ExitCode {
return ExitCode::from(if failed { code.max(1) } else { code });
}
Err(e) => {
eprintln!(
diag(format_args!(
"error: cannot run wineboot for {}: {e}",
resolved_prefix.display()
);
));
return ExitCode::FAILURE;
}
}
@@ -627,12 +899,13 @@ fn cmd_run(args: &[String]) -> ExitCode {
for item in &staged {
if let stage::Staged::Copied(path)
| stage::Staged::Replaced(path)
| stage::Staged::ReplacedWineStub(path)
| stage::Staged::Unchanged(path) = item
&& let Some(name) = path.file_name()
{
staged_names.push(name.to_string_lossy().into_owned());
}
eprintln!("bx-cli: {}", item.describe());
diag(format_args!("bx-cli: {}", item.describe()));
}
}
Err(e) => {
@@ -641,7 +914,9 @@ fn cmd_run(args: &[String]) -> ExitCode {
} else {
""
};
eprintln!("error: cannot stage system32 shims: {e}{hint}");
diag(format_args!(
"error: cannot stage system32 shims: {e}{hint}"
));
return ExitCode::FAILURE;
}
}
@@ -681,14 +956,15 @@ fn cmd_run(args: &[String]) -> ExitCode {
if let Some(log) = &abs_log {
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(log));
}
let log_size = |log: &PathBuf| fs::metadata(log).map_or(0, |m| m.len());
let log_size_before = abs_log.as_ref().map_or(0, log_size);
let log_before = abs_log.as_deref().and_then(log_mark);
// `--timeout` bounds the whole run, including any prefix initialization above.
let remaining = match guest_time_left(timeout, started.elapsed()) {
// `--timeout` bounds the whole run, including any prefix initialization above, but not
// time the run spent suspended in either phase.
let active = active_time(started.elapsed(), supervise::suspended_time());
let remaining = match guest_time_left(timeout, active) {
Ok(remaining) => remaining,
Err(e) => {
eprintln!("timed out during initialization: {e}");
diag(format_args!("timed out during initialization: {e}"));
return ExitCode::from(124);
}
};
@@ -696,14 +972,14 @@ fn cmd_run(args: &[String]) -> ExitCode {
let code = match &outcome {
Ok(outcome) => outcome.exit_code(),
Err(e) => {
eprintln!("failed to run CrossOver wine: {e}");
diag(format_args!("failed to run CrossOver wine: {e}"));
1
}
};
let mut cleanup_failed = false;
match &outcome {
Ok(Outcome::Exited(status)) if !status.success() => {
eprintln!("guest exited with status: {status}");
diag(format_args!("guest exited with status: {status}"));
}
Ok(Outcome::Stopped(stop)) => {
cleanup_failed = stop_environment(
@@ -717,17 +993,22 @@ fn cmd_run(args: &[String]) -> ExitCode {
_ => {}
}
// Printed for failed and stopped runs too, which is when it matters most.
// Printed for failed and stopped runs too, which is when it matters most. The log is
// appended to across runs, so only what this run added is summarized.
if let Some(log) = &abs_log
&& log_size(log) > log_size_before
&& let Ok(bytes) = fs::read(log)
&& let Some((identity, bytes)) = read_log(log)
{
// Guest text may not be valid UTF-8; a summary is still worth printing.
print!(
"\nTrace summary of {}:\n{}",
log.display(),
render_trace(&String::from_utf8_lossy(&bytes))
);
let fresh = appended_since(&bytes, identity, log_before.as_ref());
if !fresh.is_empty() {
// Guest text may not be valid UTF-8; a summary is still worth printing. A closed
// stdout must not turn into a panic after the run.
let _ = write!(
std::io::stdout(),
"\nTrace summary of this run in {}:\n{}",
log.display(),
render_trace(&String::from_utf8_lossy(fresh))
);
}
}
// #474: the shims were staged into the prefix resolved before launch. If CrossOver launched
// the bottle from a different prefix that does not expose them, the guest never saw them,
@@ -746,14 +1027,14 @@ fn cmd_run(args: &[String]) -> ExitCode {
&staged_names,
);
if missing.is_empty() {
eprintln!(
diag(format_args!(
"bx-cli: bottle launched in {}; the shims staged in {} are visible there",
launched.display(),
environment_dir.display()
);
));
} else {
staged_elsewhere = true;
eprintln!(
diag(format_args!(
"error: system32 shims were staged in {} but CrossOver launched the \
bottle in {}, where {} cannot be found as staged; the guest did not \
see them. Run again: staging will now use the prefix the bottle \
@@ -761,13 +1042,13 @@ fn cmd_run(args: &[String]) -> ExitCode {
environment_dir.display(),
launched.display(),
missing.join(", ")
);
));
}
}
Err(e) => eprintln!(
Err(e) => diag(format_args!(
"warning: cannot confirm which prefix the bottle launched in, so the staged \
system32 shims may not have been used: {e}"
),
)),
}
}
// The reason for the stop is kept; a failed cleanup or misplaced staging only turns success
@@ -833,6 +1114,223 @@ fn main() -> ExitCode {
mod tests {
use super::*;
/// A stream whose reader is gone: every write fails, as with EPIPE or EIO.
struct ClosedStream<'a> {
cleanup_done: &'a std::cell::Cell<bool>,
writes_before_cleanup: usize,
writes: usize,
}
impl std::io::Write for ClosedStream<'_> {
fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
self.writes += 1;
if !self.cleanup_done.get() {
self.writes_before_cleanup += 1;
}
Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
}
fn flush(&mut self) -> std::io::Result<()> {
Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
}
}
#[test]
fn a_closed_diagnostic_stream_cannot_skip_cleanup() {
for stop in [Stop::Signalled(libc::SIGINT), Stop::TimedOut] {
let cleanup_done = std::cell::Cell::new(false);
let mut closed = ClosedStream {
cleanup_done: &cleanup_done,
writes_before_cleanup: 0,
writes: 0,
};
let failed = report_stop(
stop,
|| {
cleanup_done.set(true);
vec!["cleanup failed, programs may still be running: stub".to_string()]
},
&mut closed,
);
assert!(cleanup_done.get(), "cleanup did not run for {stop:?}");
assert!(failed, "the cleanup failure was lost for {stop:?}");
assert!(closed.writes > 0, "nothing was reported for {stop:?}");
assert_eq!(
closed.writes_before_cleanup, 0,
"output came before cleanup"
);
}
let mut text = Vec::new();
assert!(!report_stop(Stop::Signalled(2), Vec::new, &mut text));
assert_eq!(
String::from_utf8(text).unwrap(),
"received signal 2; stopped the environment\n"
);
}
fn mark(identity: (u64, u64), contents: &str) -> LogMark {
let bytes = contents.as_bytes();
let tail_start = bytes.len().saturating_sub(LOG_MARK_TAIL as usize);
LogMark {
identity,
len: bytes.len() as u64,
tail: bytes[tail_start..].to_vec(),
}
}
#[test]
fn the_trace_summary_covers_only_what_this_run_appended() {
let file = (1, 100);
let earlier = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
let this_run = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!ThisRun\"}\n";
let log = format!("{earlier}{this_run}");
let before = mark(file, earlier);
let fresh = appended_since(log.as_bytes(), file, Some(&before));
assert_eq!(fresh, this_run.as_bytes());
let rendered = render_trace(&String::from_utf8_lossy(fresh));
assert!(rendered.contains("new.dll!ThisRun"), "{rendered}");
assert!(!rendered.contains("old.dll!Earlier"), "{rendered}");
// Nothing appended: nothing to summarize.
assert!(appended_since(earlier.as_bytes(), file, Some(&before)).is_empty());
// No log before the run: everything in it is from this run.
assert_eq!(
appended_since(this_run.as_bytes(), file, None),
this_run.as_bytes()
);
}
#[test]
fn a_replaced_log_is_summarized_in_full_whatever_its_size() {
let old_file = (1, 100);
let new_file = (1, 200);
let old = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
let before = mark(old_file, old);
let record = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!A\"}\n";
// Shorter, exactly as long, and longer than the old log: the old length must never be
// used as an offset into a different file.
let shorter = &record[..record.len() - 1];
let same_size = format!("{:<width$}\n", record.trim_end(), width = old.len() - 1);
let longer = format!("{record}{record}{record}");
assert!(shorter.len() < old.len() && same_size.len() == old.len());
assert!(longer.len() > old.len());
for replacement in [shorter, same_size.as_str(), longer.as_str()] {
let fresh = appended_since(replacement.as_bytes(), new_file, Some(&before));
assert_eq!(fresh, replacement.as_bytes(), "{} bytes", replacement.len());
}
// Rewritten in place (same file, different contents before the old end).
let fresh = appended_since(longer.as_bytes(), old_file, Some(&before));
assert_eq!(fresh, longer.as_bytes());
assert_eq!(
summarize_jsonl(&String::from_utf8_lossy(fresh)).total_lines,
3
);
}
#[test]
fn a_different_file_is_new_in_full_even_when_it_starts_with_the_old_bytes() {
// Only the file identity can tell these apart: the replacement begins with exactly the
// old log's bytes and then has more, so the bytes before the old end still match.
let old = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
let more = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!ThisRun\"}\n";
let replacement = format!("{old}{more}");
let before = mark((1, 100), old);
let fresh = appended_since(replacement.as_bytes(), (1, 200), Some(&before));
assert_eq!(fresh, replacement.as_bytes());
// Control: the same bytes in the same file are an append, and only the rest is new.
let appended = appended_since(replacement.as_bytes(), (1, 100), Some(&before));
assert_eq!(appended, more.as_bytes());
}
#[test]
fn a_log_path_that_is_not_a_regular_file_never_blocks_the_run() {
let dir = env::temp_dir().join(format!("bx-cli-lognonfile-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let fifo = dir.join("trace.fifo");
let made = Command::new("/usr/bin/mkfifo").arg(&fifo).status().unwrap();
assert!(made.success());
// A FIFO with no writer: a plain open for reading would wait here forever.
let (tx, rx) = std::sync::mpsc::channel();
let probe = fifo.clone();
std::thread::spawn(move || {
let _ = tx.send((log_mark(&probe), read_log(&probe)));
});
let (mark_of_fifo, contents_of_fifo) = rx
.recv_timeout(Duration::from_secs(5))
.expect("reading a FIFO log path blocked");
assert_eq!(mark_of_fifo, None);
assert_eq!(contents_of_fifo, None);
// A directory and a missing path are not logs either; a regular file still is.
assert_eq!(log_mark(&dir), None);
assert_eq!(read_log(&dir), None);
assert_eq!(log_mark(&dir.join("absent")), None);
let real = dir.join("trace.jsonl");
fs::write(&real, "{}\n").unwrap();
assert_eq!(log_mark(&real).map(|m| m.len), Some(3));
assert_eq!(
read_log(&real).map(|(_, bytes)| bytes),
Some(b"{}\n".to_vec())
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn log_marks_follow_the_file_on_disk() {
let dir = env::temp_dir().join(format!("bx-cli-logmark-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let log = dir.join("trace.jsonl");
assert_eq!(log_mark(&log), None);
let old = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
fs::write(&log, old).unwrap();
let before = log_mark(&log).unwrap();
assert_eq!(before.len, old.len() as u64);
assert_eq!(before.tail, old.as_bytes());
// Appended to, as bx_runtime_veh does: only the new record is this run's.
let added = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!ThisRun\"}\n";
fs::write(&log, format!("{old}{added}")).unwrap();
let (identity, bytes) = read_log(&log).unwrap();
assert_eq!(
appended_since(&bytes, identity, Some(&before)),
added.as_bytes()
);
// Replaced by a new, longer file during the run: all of it is this run's.
let replacement = dir.join("replacement");
let longer = format!("{added}{added}{added}");
fs::write(&replacement, &longer).unwrap();
fs::rename(&replacement, &log).unwrap();
let (identity, bytes) = read_log(&log).unwrap();
assert_ne!(identity, before.identity);
let fresh = appended_since(&bytes, identity, Some(&before));
assert_eq!(
summarize_jsonl(&String::from_utf8_lossy(fresh)).total_lines,
3
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_pause_in_an_earlier_phase_is_not_charged_to_the_guest() {
let limit = Some(Duration::from_secs(2));
let ms = Duration::from_millis;
// As reviewed: paused 2.5 s during wineboot with --timeout 2, 0.3 s actually running.
assert_eq!(
guest_time_left(limit, active_time(ms(2800), ms(2500))),
Ok(Some(ms(1700)))
);
// Without a pause the wall clock counts in full.
assert_eq!(
guest_time_left(limit, active_time(ms(500), Duration::ZERO)),
Ok(Some(ms(1500)))
);
// Initialization that really ran for the whole timeout still stops the launch.
assert!(guest_time_left(limit, active_time(ms(5000), ms(2500))).is_err());
// More suspension than elapsed time cannot go negative.
assert_eq!(active_time(ms(100), ms(900)), Duration::ZERO);
}
#[test]
fn staging_into_a_prefix_the_bottle_did_not_launch_in_is_reported() {
let resolved_before = Path::new("/bottles/managed/corp");
@@ -1094,12 +1592,172 @@ sub setup_bottle_wineprefix {
}
#[test]
fn formats_clwb_summary_lines() {
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
fn formats_amd_trap_summary_lines() {
let sampled = TrapCount {
events: 3,
lower_bound: Some(4),
};
assert_eq!(
format_clwb_line(3, Some(4)),
"clwb VEH traps : at least 4 (sampled)"
format_amd_trap_line("clzero", &sampled),
"clzero VEH traps : at least 4 (sampled)"
);
assert_eq!(
format_amd_trap_line("monitorx", &sampled),
"monitorx VEH traps : at least 4 (sampled)"
);
let unnumbered = TrapCount {
events: 2,
lower_bound: None,
};
assert_eq!(
format_amd_trap_line("rdpru", &unnumbered),
"rdpru VEH traps : 2 samples"
);
}
#[test]
fn formats_clwb_summary_lines() {
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
assert_eq!(
format_clwb_line(3, Some(4)),
"clwb VEH traps : at least 4 (sampled)"
);
}
#[test]
fn a_log_without_shader_gate_records_renders_as_before() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"runtime_veh","event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=1"}
{"ts_ms":12,"tid":1,"level":"WARN","sub":"stub","event":"unimpl_api","detail":"d3d12_xs.dll!D3D12XboxCreateDevice"}
{"ts_ms":16,"tid":1,"level":"WARN","sub":"com_vtable","event":"unimpl_vtable","detail":"ID3D12Device11[44]::CreatePlacedResourceX"}
"#;
let rendered = render_trace(log);
assert!(!rendered.contains("Shader"), "{rendered}");
assert!(!rendered.contains("shader_gate"), "{rendered}");
assert_eq!(
rendered,
"Trace events : 3\n\
clwb VEH traps : at least 1 (sampled)\n\
ADX illegal ops : 0\n\
\n\
Unimplemented APIs:\n\
\x20 1x d3d12_xs.dll!D3D12XboxCreateDevice\n\
\n\
Unimplemented COM vtable slots:\n\
\x20 1x ID3D12Device11[44]::CreatePlacedResourceX\n"
);
assert_eq!(format_shader_gate_section(&summarize_jsonl(log)), "");
}
#[test]
fn renders_decisions_kinds_stages_gaps_and_missing_bridge() {
// Realistic records, matching the emitter in shims/d3d12_xs/shader_gate.cpp.
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"}
{"ts_ms":12,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_gate","detail":"pso=graphics stage=VS decision=reject_accc_only hr=0x80004001 kind=accc_only shader_stage=0 sm=6.0 bytes=2048 dxil=0 accc=512 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=none"}
{"ts_ms":16,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"ts_ms":18,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_bridge_missing","detail":"bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, ACCC-only refused"}
"#;
let rendered = render_trace(log);
assert!(rendered.contains("Shader gate:"), "{rendered}");
assert!(rendered.contains("shader_gate records : 2"), "{rendered}");
assert!(rendered.contains("decisions:"), "{rendered}");
assert!(rendered.contains(" 1x pass_dxil"), "{rendered}");
assert!(rendered.contains(" 1x reject_accc_only"), "{rendered}");
assert!(rendered.contains("kinds:"), "{rendered}");
assert!(rendered.contains(" 1x dxil"), "{rendered}");
assert!(rendered.contains(" 1x accc_only"), "{rendered}");
assert!(rendered.contains("stages:"), "{rendered}");
assert!(rendered.contains(" 1x CS"), "{rendered}");
assert!(rendered.contains(" 1x VS"), "{rendered}");
assert!(rendered.contains("D3DMetal gaps (1):"), "{rendered}");
assert!(
rendered.contains(" pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000"),
"{rendered}"
);
assert!(
rendered.contains("Shader bridge missing (1):"),
"{rendered}"
);
assert!(
rendered.contains("bx_shader_bridge.dll not found beside d3d12_xs.dll"),
"{rendered}"
);
// #497 review point 5: name the rejected pipeline and its HRESULT, not just a count.
assert!(
rendered.contains("Non-pass pipeline decisions (1):"),
"{rendered}"
);
assert!(
rendered.contains("pso=graphics stage=VS decision=reject_accc_only hr=0x80004001"),
"{rendered}"
);
assert!(!rendered.contains("decision=pass_dxil hr="), "{rendered}");
assert!(!rendered.contains("unparsed"), "{rendered}");
}
#[test]
fn an_unparsable_shader_gate_detail_shows_the_unparsed_count() {
let log = r#"{"ts_ms":20,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"garbage"}
{"ts_ms":22,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=100 dxil=64 accc=0 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=0-4294967295"}
"#;
let rendered = render_trace(log);
assert!(rendered.contains("shader_gate records : 2"), "{rendered}");
assert!(rendered.contains("unparsed details : 1"), "{rendered}");
assert!(rendered.contains(" 1x pass_dxil"), "{rendered}");
}
/// #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}");
}
}
+223 -6
View File
@@ -19,8 +19,32 @@ use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`.
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll"];
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32` (or shadowed by Wine builtin stubs in
/// `system32`, which Windows searches before `WINEPATH`).
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll", "GameInput.dll"];
/// Returns true when `bytes` is a Wine `winebuild` fake-DLL placeholder stub in `system32`
/// (`"MZ"` header, `"Wine builtin DLL\0"` at DOS offset `0x40`, and `"PE\0\0"` at `e_lfanew`).
///
/// Wine populates `drive_c/windows/system32/` with fake PE stubs for built-in modules such as
/// `gameinput.dll`. Unlike user- or installer-provided native DLLs (#474), these placeholders are
/// created by Wine itself and would otherwise shadow BetterXen shims on `LOAD_LIBRARY_SEARCH_SYSTEM32`
/// loads (`fixme:ginput:GameInputCreate ... stub!`).
pub fn is_wine_builtin_dll(bytes: &[u8]) -> bool {
const WINE_SIG_OFFSET: usize = 0x40;
const WINE_SIG: &[u8] = b"Wine builtin DLL\0";
if bytes.len() < WINE_SIG_OFFSET + WINE_SIG.len() + 4 {
return false;
}
if &bytes[0..2] != b"MZ" {
return false;
}
if &bytes[WINE_SIG_OFFSET..WINE_SIG_OFFSET + WINE_SIG.len()] != WINE_SIG {
return false;
}
let pe_off = u32::from_le_bytes([bytes[0x3c], bytes[0x3d], bytes[0x3e], bytes[0x3f]]) as usize;
pe_off >= WINE_SIG_OFFSET + WINE_SIG.len() && bytes.get(pe_off..pe_off + 4) == Some(b"PE\0\0")
}
/// `roots` plus, transitively, every import that is itself a file in the shim folder
/// (`is_shim`). Names are compared case-insensitively, as the Windows loader does, and returned
@@ -220,6 +244,8 @@ pub enum Staged {
Copied(PathBuf),
/// An earlier copy staged by this tool, refreshed because the shim changed.
Replaced(PathBuf),
/// A Wine `"Wine builtin DLL"` placeholder stub in `system32`, backed up once and replaced.
ReplacedWineStub(PathBuf),
Unchanged(PathBuf),
/// A [`SYSTEM32_SHIMS`] file the shim folder does not have.
Absent(PathBuf),
@@ -230,6 +256,9 @@ impl Staged {
match self {
Staged::Copied(p) => format!("staged {}", p.display()),
Staged::Replaced(p) => format!("refreshed own earlier copy {}", p.display()),
Staged::ReplacedWineStub(p) => {
format!("replaced Wine builtin stub {} (backup saved)", p.display())
}
Staged::Unchanged(p) => format!("already current {}", p.display()),
Staged::Absent(p) => format!("not staged, {} not found", p.display()),
}
@@ -365,6 +394,8 @@ where
));
} else if existing.as_deref().map(sha256_hex).as_ref() == owned.get(name) {
Staged::Replaced(dst.clone())
} else if existing.as_deref().is_some_and(is_wine_builtin_dll) {
Staged::ReplacedWineStub(dst.clone())
} else {
return Err(foreign(
&dst,
@@ -402,6 +433,12 @@ where
for (name, bytes, dst, result) in plan {
if !matches!(result, Staged::Unchanged(_)) {
let tmp = tmp_of(name);
// Snapshot what the target holds now, before the rename, so a failed manifest
// write can put the *old* bytes back (not the bytes just written).
let previous: Option<Vec<u8>> = match result {
Staged::Copied(_) => None,
_ => fs::read(&dst).ok(),
};
let published = before_publish(name).and_then(|()| match result {
// Nothing was there at step 1; refuse to replace whatever appeared since.
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
@@ -415,6 +452,41 @@ where
format!("cannot install {}: {e}", dst.display())
}
}),
// Wine fake-DLL placeholder stub: verify it is still a regular Wine builtin stub,
// preserve a one-time backup `.<name>.wine-builtin.bak`, then atomically replace.
Staged::ReplacedWineStub(_) => match fs::symlink_metadata(&dst) {
Ok(meta) if meta.is_file() => match fs::read(&dst) {
Ok(now) if is_wine_builtin_dll(&now) => {
let bak = system32.join(format!(".{name}.wine-builtin.bak"));
if fs::symlink_metadata(&bak).is_err() {
let bak_tmp = system32.join(format!(
".{name}.wine-builtin.bak.{}.bx-staging",
std::process::id()
));
fs::write(&bak_tmp, &now).map_err(|e| {
let _ = fs::remove_file(&bak_tmp);
format!("cannot write backup {}: {e}", bak_tmp.display())
})?;
let bak_res = install_new(&bak_tmp, &bak, &now);
let _ = fs::remove_file(&bak_tmp);
match bak_res {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => {
return Err(format!(
"cannot save Wine stub backup {}: {e}",
bak.display()
));
}
}
}
fs::rename(&tmp, &dst)
.map_err(|e| format!("cannot replace {}: {e}", dst.display()))
}
_ => Err(foreign(&dst, name, "changed while staging")),
},
_ => Err(foreign(&dst, name, "changed while staging")),
},
// Still our own earlier copy? Then the rename replaces it in one step.
_ => match fs::read(&dst) {
Ok(now) if owned.get(name) == Some(&sha256_hex(&now)) => fs::rename(&tmp, &dst)
@@ -429,6 +501,19 @@ where
let _ = fs::remove_file(&tmp);
owned.insert(name.clone(), sha256_hex(&bytes));
if let Err(e) = write_manifest(system32, &owned) {
// The file is installed but the manifest on disk does not name it, so the
// next run would call bx-cli's own copy foreign (#573). Roll the publish
// back: a Copied file is removed, a Replaced one is restored from the bytes
// it had before. The manifest is left exactly as it was, so the retry sees
// the same state it would have seen had the publish never happened.
match previous {
None => {
let _ = fs::remove_file(&dst);
}
Some(before) => {
let _ = fs::write(&dst, before);
}
}
discard(&pending);
return Err(e);
}
@@ -511,11 +596,12 @@ mod tests {
let (_t, shims, prefix) = setup("deps");
let sys = system32_dir(&prefix);
let staged = stage(&shims, &sys).unwrap();
assert_eq!(staged.len(), 2, "{staged:?}");
assert_eq!(staged.len(), 3, "{staged:?}");
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
assert!(
!sys.join("unrelated.dll").exists(),
"only imported shims are staged"
"only SYSTEM32_SHIMS and imported shims are staged"
);
}
@@ -808,6 +894,67 @@ mod tests {
);
}
#[test]
fn a_manifest_write_failure_leaves_no_unowned_file() {
let (_t, shims, prefix) = setup("manifest");
let sys = system32_dir(&prefix);
// A directory where the manifest's temporary file has to go makes
// `write_manifest` fail after the first shim has already been published.
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::create_dir(&obstacle).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("cannot write"), "{err}");
assert!(
!sys.join("bx_runtime_veh.dll").exists(),
"the published file was rolled back, so the retry is not refused as foreign"
);
assert!(!sys.join(MANIFEST_NAME).exists());
// Only the obstacle itself is left: no staged copy, no temporary file.
let entries: Vec<String> = fs::read_dir(&sys)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(
entries,
vec![obstacle.file_name().unwrap().to_string_lossy().into_owned()],
"system32 holds nothing but the obstacle that failed the manifest write"
);
fs::remove_dir(&obstacle).unwrap();
// The retry installs everything fresh; nothing is reported as foreign.
let retry = stage(&shims, &sys).unwrap();
assert!(
retry.iter().all(|s| matches!(s, Staged::Copied(_))),
"{retry:?}"
);
// And a shim rebuilt later refreshes bx-cli's own copy rather than failing.
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let update = stage(&shims, &sys).unwrap();
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
}
#[test]
fn a_manifest_write_failure_restores_the_previous_bytes() {
let (_t, shims, prefix) = setup("restore");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
// Rebuild the shim, then make the manifest write fail after the rename.
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::create_dir(&obstacle).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(
fs::read(sys.join("bx_runtime_veh.dll")).unwrap(),
b"veh v1",
"the replaced file must be restored to the bytes it had before the rename"
);
// The manifest still names the old copy, so the retry refreshes it rather than
// calling it foreign.
fs::remove_dir(&obstacle).unwrap();
let retry = stage(&shims, &sys).unwrap();
assert!(retry.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
}
#[test]
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
let (t, shims, prefix) = setup("visible");
@@ -867,10 +1014,15 @@ mod tests {
#[test]
fn missing_shim_is_reported_and_nothing_is_staged() {
let (t, shims, prefix) = setup("missing");
fs::remove_file(shims.join("xgameruntime.dll")).unwrap();
for name in SYSTEM32_SHIMS {
fs::remove_file(shims.join(name)).unwrap();
}
assert!(!has_system32_shims(&shims));
let sys = system32_dir(&prefix);
let expected = vec![Staged::Absent(shims.join("xgameruntime.dll"))];
let expected: Vec<Staged> = SYSTEM32_SHIMS
.iter()
.map(|name| Staged::Absent(shims.join(name)))
.collect();
assert_eq!(stage(&shims, &sys).unwrap(), expected);
assert_eq!(fs::read_dir(&sys).unwrap().count(), 0);
// With nothing to stage, a prefix without system32 is not an error either.
@@ -879,6 +1031,71 @@ mod tests {
assert!(!fresh.exists());
}
fn make_fake_wine_builtin_pe() -> Vec<u8> {
let mut pe = vec![0u8; 0x100];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3c..0x40].copy_from_slice(&(0x80u32).to_le_bytes());
pe[0x40..0x51].copy_from_slice(b"Wine builtin DLL\0");
pe[0x80..0x84].copy_from_slice(b"PE\0\0");
pe
}
#[test]
fn replaces_a_wine_builtin_stub_after_saving_a_backup() {
let (_t, shims, prefix) = setup("wine-stub");
let sys = system32_dir(&prefix);
let wine_stub = make_fake_wine_builtin_pe();
assert!(is_wine_builtin_dll(&wine_stub));
fs::write(sys.join("gameinput.dll"), &wine_stub).unwrap();
let first = stage(&shims, &sys).unwrap();
assert!(first.contains(&Staged::ReplacedWineStub(sys.join("gameinput.dll"))));
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
assert_eq!(
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
wine_stub
);
let owned = read_manifest(&sys).unwrap();
assert_eq!(owned.get("gameinput.dll"), Some(&sha256_hex(b"shim v1")));
// Subsequent rebuilds refresh our owned copy while keeping the original Wine backup intact.
fs::write(shims.join("GameInput.dll"), b"shim v2").unwrap();
let second = stage(&shims, &sys).unwrap();
assert!(second.contains(&Staged::Replaced(sys.join("gameinput.dll"))));
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v2");
assert_eq!(
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
wine_stub
);
}
#[test]
fn non_wine_pe_and_symlinks_to_wine_stubs_are_still_refused() {
let (t, shims, prefix) = setup("non-wine-pe");
let sys = system32_dir(&prefix);
// A regular native PE (standard DOS stub, no "Wine builtin DLL" marker) is foreign.
let mut native_pe = make_fake_wine_builtin_pe();
native_pe[0x40..0x51].copy_from_slice(b"This program can!");
assert!(!is_wine_builtin_dll(&native_pe));
fs::write(sys.join("gameinput.dll"), &native_pe).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), native_pe);
// A symlink pointing to a real Wine builtin stub is ALSO refused (never follow links).
fs::remove_file(sys.join("gameinput.dll")).unwrap();
let wine_target = t.0.join("wine_gameinput.dll");
fs::write(&wine_target, make_fake_wine_builtin_pe()).unwrap();
std::os::unix::fs::symlink(&wine_target, sys.join("gameinput.dll")).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("symbolic link"), "{err}");
assert!(
fs::symlink_metadata(sys.join("gameinput.dll"))
.unwrap()
.file_type()
.is_symlink()
);
}
#[test]
fn uninitialized_prefix_is_an_error_not_a_skip() {
let (t, shims, _prefix) = setup("uninit");
+262 -15
View File
@@ -8,7 +8,7 @@ use std::io::IsTerminal;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use std::time::{Duration, Instant};
const POLL: Duration = Duration::from_millis(50);
@@ -16,29 +16,81 @@ const POLL: Duration = Duration::from_millis(50);
const GRACE: Duration = Duration::from_secs(5);
const SERVER_WAIT: Duration = Duration::from_secs(15);
/// Signals that stop the run: the guest group is terminated and the environment cleaned up.
/// SIGQUIT (Ctrl-\) is included so it cannot kill `bx-cli` and leave the guest running (#461).
const STOP_SIGNALS: [libc::c_int; 4] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];
static SIGNAL: AtomicI32 = AtomicI32::new(0);
static SUSPEND: AtomicBool = AtomicBool::new(false);
/// Total time this process has spent suspended inside [`supervise`], in nanoseconds.
static SUSPENDED_NANOS: AtomicU64 = AtomicU64::new(0);
extern "C" fn note_signal(signal: libc::c_int) {
SIGNAL.store(signal, Ordering::SeqCst);
}
/// Records SIGINT, SIGTERM and SIGHUP instead of dying, so the run can be cleaned up.
pub fn install_signal_handlers() {
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
// SAFETY: the handler only stores to an atomic, which is async-signal-safe.
unsafe {
libc::signal(
signal,
note_signal as extern "C" fn(libc::c_int) as libc::sighandler_t,
);
extern "C" fn note_suspend(_signal: libc::c_int) {
SUSPEND.store(true, Ordering::SeqCst);
}
/// Installs `handler` for `signal` unless the disposition this process inherited is `SIG_IGN`.
/// Returns whether the handler was installed.
///
/// A signal the caller chose to ignore (`nohup`, or a `&` job of a non-interactive shell) stays
/// ignored, so it cannot stop the run or the bottle (#461).
fn install_unless_ignored(signal: libc::c_int, handler: extern "C" fn(libc::c_int)) -> bool {
// SAFETY: `current` is a valid, writable sigaction; a null new action only queries. The
// handlers passed here only store to an atomic, which is async-signal-safe.
unsafe {
let mut current: libc::sigaction = std::mem::zeroed();
if libc::sigaction(signal, std::ptr::null(), &mut current) == 0
&& current.sa_sigaction == libc::SIG_IGN
{
return false;
}
libc::signal(signal, handler as libc::sighandler_t) != libc::SIG_ERR
}
}
/// Records SIGINT, SIGTERM, SIGHUP and SIGQUIT instead of dying, so the run can be cleaned up,
/// and records SIGTSTP (Ctrl-Z) so the guest group can be suspended together with `bx-cli`.
/// Signals that were inherited as ignored are left ignored.
///
/// SIGTSTP is only acted on inside [`supervise`]. A Ctrl-Z typed while nothing is being
/// supervised (for example while shims are copied) has no visible effect until the next
/// supervised phase starts, which is then suspended at once.
pub fn install_signal_handlers() {
for signal in STOP_SIGNALS {
install_unless_ignored(signal, note_signal);
}
install_unless_ignored(libc::SIGTSTP, note_suspend);
}
pub fn received_signal() -> i32 {
SIGNAL.load(Ordering::SeqCst)
}
/// Total time spent suspended (Ctrl-Z until continued) across every [`supervise`] call so far.
///
/// A caller that budgets one `--timeout` over several supervised phases subtracts this from its
/// own wall-clock measurement, so a pause during an earlier phase is not charged to a later one.
pub fn suspended_time() -> Duration {
Duration::from_nanos(SUSPENDED_NANOS.load(Ordering::SeqCst))
}
/// True once per SIGTSTP received since the last call.
fn take_suspend_request() -> bool {
SUSPEND.swap(false, Ordering::SeqCst)
}
/// Stops this process the way the terminal's Ctrl-Z would; returns when it is continued.
fn suspend_self(_guest: libc::pid_t) {
// SAFETY: raise takes no pointers. SIGSTOP cannot be caught, so this stops the process.
unsafe {
libc::raise(libc::SIGSTOP);
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Stop {
TimedOut,
@@ -52,11 +104,14 @@ pub enum Outcome {
}
impl Outcome {
/// 0 or 1 for the guest's own result, 124 for a timeout (as `timeout(1)`), 128 + N for a
/// signal.
/// The guest's own numeric exit code (so a conformance fixture's documented exit-77 skip
/// stays distinguishable from a failure, #565), 124 for a timeout (as `timeout(1)`),
/// 128 + N for a signal.
pub fn exit_code(&self) -> u8 {
match self {
Outcome::Exited(status) => u8::from(!status.success()),
// Unix guest codes are already 0-255; a signalled guest has no code, which is a
// failure. `code.max(1)` at the call sites still turns a failed cleanup into 1.
Outcome::Exited(status) => status.code().map_or(1, |code| code.clamp(0, 255) as u8),
Outcome::Stopped(Stop::TimedOut) => 124,
Outcome::Stopped(Stop::Signalled(signal)) => 128u8.saturating_add(*signal as u8),
}
@@ -85,10 +140,27 @@ fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<Ex
/// Runs `command` in a new process group until it exits, `timeout` passes, or `signal`
/// returns non-zero. On a stop the whole group is terminated before this returns.
///
/// The guest is not in the terminal's foreground group, so Ctrl-Z reaches only `bx-cli`. It is
/// passed on: the guest group gets SIGTSTP, `bx-cli` stops itself, and when `bx-cli` is continued
/// the guest group gets SIGCONT. Time spent suspended does not count against `timeout`.
pub fn supervise(
command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
) -> std::io::Result<Outcome> {
supervise_with(command, timeout, signal, take_suspend_request, suspend_self)
}
/// [`supervise`] with the suspend request and the self-stop injected, so tests can exercise the
/// job-control path without stopping the test process. `suspend` is called with the guest
/// group's id after that group was sent SIGTSTP and returns when the launcher may continue.
fn supervise_with(
mut command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
suspend_requested: impl Fn() -> bool,
mut suspend: impl FnMut(libc::pid_t),
) -> std::io::Result<Outcome> {
// A background process group is stopped by SIGTTIN if it reads the terminal, so a terminal
// is replaced by end-of-file. Piped and redirected input is passed through.
@@ -97,6 +169,7 @@ pub fn supervise(
}
let mut child = command.process_group(0).spawn()?;
let started = Instant::now();
let mut suspended = Duration::ZERO;
let stop = loop {
if let Some(status) = child.try_wait()? {
return Ok(Outcome::Exited(status));
@@ -105,7 +178,20 @@ pub fn supervise(
if received != 0 {
break Stop::Signalled(received);
}
if timeout.is_some_and(|limit| started.elapsed() >= limit) {
if suspend_requested() {
let paused = Instant::now();
signal_group(&child, libc::SIGTSTP);
suspend(child.id() as libc::pid_t);
signal_group(&child, libc::SIGCONT);
let pause = paused.elapsed();
suspended += pause;
SUSPENDED_NANOS.fetch_add(
u64::try_from(pause.as_nanos()).unwrap_or(u64::MAX),
Ordering::SeqCst,
);
continue;
}
if timeout.is_some_and(|limit| started.elapsed().saturating_sub(suspended) >= limit) {
break Stop::TimedOut;
}
std::thread::sleep(POLL);
@@ -141,6 +227,10 @@ fn group_leader_running(child: &Child) -> bool {
///
/// `-k` exits 1 when no server is running (observed on CrossOver 26.3), so 1 is accepted
/// there; `-w` must still succeed, which a surviving server prevents.
///
/// Each `wineserver` runs in its own process group with no terminal input, so a second Ctrl-C
/// typed while cleanup is running reaches only `bx-cli` (which records it) and cannot kill the
/// cleanup itself (#461).
pub fn stop_server(
wineserver: &Path,
prefix: &Path,
@@ -152,8 +242,10 @@ pub fn stop_server(
.env_clear()
.envs(environment.iter().map(|(k, v)| (k, v)))
.env("WINEPREFIX", prefix)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0)
.spawn()
.map_err(|e| format!("cannot start wineserver {flag}: {e}"))?;
match wait_until(&mut child, Instant::now() + SERVER_WAIT) {
@@ -191,7 +283,11 @@ mod tests {
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
assert_eq!(ok.exit_code(), 0);
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
assert_eq!(failed.exit_code(), 1);
assert_eq!(failed.exit_code(), 7);
// A conformance fixture's documented skip must stay distinguishable from a failure
// through `bx-cli run` (#565); the old `!status.success()` collapsed it to 1.
let skipped = supervise(shell("exit 77"), Some(Duration::from_secs(10)), || 0).unwrap();
assert_eq!(skipped.exit_code(), 77);
let slow = supervise(shell("sleep 30"), Some(Duration::from_millis(200)), || 0).unwrap();
assert!(matches!(slow, Outcome::Stopped(Stop::TimedOut)));
assert_eq!(slow.exit_code(), 124);
@@ -222,6 +318,157 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// Signal dispositions and the recorded signal are process-wide: tests that touch them run
/// one at a time and use signals no other test raises.
static SIGNAL_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn set_disposition(signal: libc::c_int, action: libc::sighandler_t) {
// SAFETY: SIG_DFL and SIG_IGN are valid dispositions for these signals.
unsafe {
libc::signal(signal, action);
}
}
fn disposition(signal: libc::c_int) -> libc::sighandler_t {
// SAFETY: a null new action only queries; `current` is valid and writable.
unsafe {
let mut current: libc::sigaction = std::mem::zeroed();
assert_eq!(libc::sigaction(signal, std::ptr::null(), &mut current), 0);
current.sa_sigaction
}
}
fn raise(signal: libc::c_int) {
// SAFETY: raise takes no pointers.
unsafe {
libc::raise(signal);
}
}
#[test]
fn an_inherited_ignored_signal_stays_ignored() {
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
// As under nohup: the signal arrives already ignored.
set_disposition(libc::SIGUSR2, libc::SIG_IGN);
SIGNAL.store(0, Ordering::SeqCst);
assert!(!install_unless_ignored(libc::SIGUSR2, note_signal));
assert_eq!(disposition(libc::SIGUSR2), libc::SIG_IGN);
raise(libc::SIGUSR2);
assert_eq!(
received_signal(),
0,
"an ignored signal must not stop the run"
);
// Control: the same signal with the default disposition is recorded.
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
assert!(install_unless_ignored(libc::SIGUSR2, note_signal));
raise(libc::SIGUSR2);
assert_eq!(received_signal(), libc::SIGUSR2);
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
SIGNAL.store(0, Ordering::SeqCst);
}
#[test]
fn sigquit_is_recorded_and_stops_the_guest_group() {
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
assert!(STOP_SIGNALS.contains(&libc::SIGQUIT));
let before = disposition(libc::SIGQUIT);
set_disposition(libc::SIGQUIT, libc::SIG_DFL);
SIGNAL.store(0, Ordering::SeqCst);
assert!(install_unless_ignored(libc::SIGQUIT, note_signal));
// Without the handler this would kill the test process, as it killed bx-cli.
raise(libc::SIGQUIT);
assert_eq!(received_signal(), libc::SIGQUIT);
set_disposition(libc::SIGQUIT, before);
SIGNAL.store(0, Ordering::SeqCst);
let stopped = supervise(shell("sleep 30"), None, || libc::SIGQUIT).unwrap();
assert!(matches!(
stopped,
Outcome::Stopped(Stop::Signalled(libc::SIGQUIT))
));
assert_eq!(stopped.exit_code(), 128 + libc::SIGQUIT as u8);
}
/// True once `pid` is reported stopped; leaves the status in place.
fn is_stopped(pid: libc::pid_t) -> bool {
(0..100).any(|_| {
// SAFETY: `info` is valid and writable; WNOWAIT leaves the child's state in place.
let stopped = unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WSTOPPED | libc::WNOHANG | libc::WNOWAIT,
) == 0
&& info.si_pid() == pid
};
if !stopped {
std::thread::sleep(POLL);
}
stopped
})
}
#[test]
fn a_suspend_request_stops_and_resumes_the_guest_without_using_up_the_timeout() {
let requested = std::cell::Cell::new(false);
let guest_was_stopped = std::cell::Cell::new(false);
let suspended_before = suspended_time();
let outcome = supervise_with(
shell("sleep 0.4; exit 0"),
// Shorter than the suspension below: only running time may count.
Some(Duration::from_millis(1500)),
|| 0,
|| !requested.replace(true),
|guest| {
guest_was_stopped.set(is_stopped(guest));
std::thread::sleep(Duration::from_millis(2000));
},
)
.unwrap();
assert!(guest_was_stopped.get(), "the guest group was not stopped");
// The pause is also reported to callers that budget a timeout across several phases.
let reported = suspended_time() - suspended_before;
assert!(reported >= Duration::from_millis(2000), "{reported:?}");
match outcome {
Outcome::Exited(status) => assert!(status.success(), "{status}"),
other => panic!("the resumed guest should have finished on its own: {other:?}"),
}
}
#[test]
fn cleanup_runs_outside_the_callers_process_group() {
let dir = scratch("cleanup-group");
let server = dir.join("wineserver");
let seen = dir.join("pgid");
std::fs::write(
&server,
format!(
"#!/bin/sh\n/bin/ps -o pgid= -p $$ >> '{}'\n",
seen.display()
),
)
.unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_server(&server, &dir, &[]).unwrap();
// SAFETY: getpgrp takes no arguments and cannot fail.
let ours = unsafe { libc::getpgrp() };
let groups: Vec<libc::pid_t> = std::fs::read_to_string(&seen)
.unwrap()
.lines()
.map(|line| line.trim().parse().unwrap())
.collect();
assert_eq!(groups.len(), 2, "-k and -w should both have run");
for group in groups {
// A terminal signal goes to the foreground group, which these are not part of.
assert_ne!(group, ours, "cleanup shares the caller's process group");
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn an_idle_server_is_accepted_only_when_the_wait_succeeds() {
let dir = scratch("server");
+349 -11
View File
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
}
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeSummary {
pub image_base: u64,
pub size_of_image: u32,
@@ -128,12 +128,21 @@ struct Section {
}
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
}
/// Map an RVA to a file offset and report how many raw bytes remain in that
/// section from the mapped offset. The bound lets callers walk a table without
/// leaving the section that contains it.
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
for s in sections {
let span = s.vsize.max(s.raw_size);
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
let delta = rva - s.vaddr;
if delta < s.raw_size {
return Some((s.raw_ptr + delta) as usize);
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
return Some((off, remaining));
}
}
}
@@ -167,8 +176,36 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
let mut sections = Vec::with_capacity(section_count as usize);
// The import data directory is entry index 1, an 8-byte RVA/size pair at
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
// validated while the optional header is read: a short optional header must
// not let the read fall through into the section table.
const IMPORT_DIR_INDEX: u32 = 1;
const IMPORT_DIR_OFF: usize = 112 + 8;
let mut import_dir: Option<(u32, u32)> = None;
if num_rvas > IMPORT_DIR_INDEX {
let entry = bytes
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
if IMPORT_DIR_OFF + 8 > opt_size {
return Err(ProbeError::NotPe32Plus(
"import directory outside SizeOfOptionalHeader",
));
}
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
import_dir = Some((rva, size));
}
let sec_base = opt + opt_size;
let section_table_size = (section_count as usize)
.checked_mul(40)
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
bytes
.get(sec_base..sec_base + section_table_size)
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
let mut sections = Vec::with_capacity(section_count as usize);
for i in 0..section_count as usize {
let so = sec_base + i * 40;
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
@@ -184,16 +221,22 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
}
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
if num_rvas > 1 {
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
if let Some((imp_rva, imp_size)) = import_dir {
if imp_rva != 0
&& let Some(mut desc_off) = rva_to_off(&sections, imp_rva)
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(&sections, imp_rva)
{
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) {
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
// declared directory Size and the section's raw bytes, whichever
// ends first, so descriptors past the directory are not reported.
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
while desc_bytes_left >= 20 {
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) else {
break;
};
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
break;
}
@@ -225,6 +268,7 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
imports.entry(dll).or_default().extend(syms);
}
desc_off += 20;
desc_bytes_left -= 20;
}
}
}
@@ -242,6 +286,129 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
mod tests {
use super::*;
const PE_OFF: usize = 0x80;
const COFF: usize = PE_OFF + 4;
const OPT: usize = COFF + 20;
const OPT_SIZE: usize = 0xF0;
const SEC: usize = OPT + OPT_SIZE;
const SECTION_RVA: u32 = 0x1000;
const RAW_PTR: u32 = 0x200;
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
}
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
}
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
}
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
put_u32(bytes, base + 8, raw_size);
put_u32(bytes, base + 12, rva);
put_u32(bytes, base + 16, raw_size);
put_u32(bytes, base + 20, raw_ptr);
}
fn minimal_pe32_plus() -> Vec<u8> {
let mut bytes = vec![0u8; 0x400];
bytes[0..2].copy_from_slice(b"MZ");
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
put_u16(&mut bytes, COFF, 0x8664);
put_u16(&mut bytes, COFF + 2, 1);
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
put_u16(&mut bytes, OPT, 0x020B);
put_u32(&mut bytes, OPT + 16, 0x1234);
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
put_u32(&mut bytes, OPT + 56, 0x2000);
put_u32(&mut bytes, OPT + 108, 16);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
bytes
}
fn two_import_pe32_plus() -> Vec<u8> {
let mut bytes = minimal_pe32_plus();
let import_rva = SECTION_RVA;
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
// Two descriptors followed by the required all-zero terminator.
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
put_u64(
&mut bytes,
RAW_PTR as usize + 0x80,
u64::from(SECTION_RVA + 0x60),
);
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
bytes
}
/// Two sections: an import-descriptor section holding exactly two
/// descriptors and no terminator, and a data section for names and thunks.
/// Ellipsis bytes just past the descriptor section spell a third valid
/// descriptor, so an unbounded walk reports a DLL that is not imported.
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
const DATA_PTR: u32 = 0x300;
let mut bytes = minimal_pe32_plus();
put_u16(&mut bytes, COFF + 2, 2);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
// Declare the directory to cover the whole descriptor section, so the
// section bound (not the Size) is what this fixture exercises.
put_u32(&mut bytes, OPT + 112 + 12, 40);
for (base, dll_rva, thunk_rva) in [
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
] {
put_u32(&mut bytes, base, thunk_rva);
put_u32(&mut bytes, base + 12, dll_rva);
put_u32(&mut bytes, base + 16, thunk_rva);
}
// A third, entirely valid descriptor just past the section boundary.
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
for (delta, name) in [
(0x00, &b"ONE.DLL\0"[..]),
(0x20, &b"TWO.DLL\0"[..]),
(0x40, &b"THREE.DLL\0"[..]),
] {
let off = DATA_PTR as usize + delta;
bytes[off..off + name.len()].copy_from_slice(name);
}
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
let off = DATA_PTR as usize + delta;
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
put_u64(&mut bytes, off + 8, 0);
}
bytes
}
#[test]
fn classifies_tracks_accurately() {
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
@@ -263,4 +430,175 @@ mod tests {
);
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
}
#[test]
fn parses_minimal_pe32_plus_without_imports() {
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
assert_eq!(summary.entry_point_rva, 0x1234);
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
assert_eq!(summary.size_of_image, 0x2000);
assert_eq!(summary.section_count, 1);
assert!(summary.imports.is_empty());
}
#[test]
fn parses_named_and_ordinal_imports_from_two_dlls() {
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
#[test]
fn rejects_truncation_at_every_header_boundary() {
let image = minimal_pe32_plus();
for len in 0..=0x100 {
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
}
}
#[test]
fn rejects_section_rva_mapping_that_would_wrap_u32() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
put_u32(&mut image, SEC + 20, u32::MAX);
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
assert!(result.is_ok(), "raw pointer addition panicked");
assert!(result.unwrap().unwrap().imports.is_empty());
}
#[test]
fn rejects_section_count_larger_than_file() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, COFF + 2, u16::MAX);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated section table")
);
}
#[test]
fn rejects_pe32_magic() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, OPT, 0x010B);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
);
}
#[test]
fn import_directory_outside_all_sections_is_safe() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, 0x8000);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
#[test]
fn rejects_truncated_import_directory() {
let mut image = minimal_pe32_plus();
// An empty section table that fits, an optional header long enough to
// declare the import entry, and a file cut after two of the entry's
// RVA bytes.
put_u16(&mut image, COFF + 2, 0);
put_u16(&mut image, COFF + 16, 0xE0);
image.truncate(OPT + 112 + 8 + 2);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated import directory")
);
}
#[test]
fn bounds_unterminated_import_descriptor_walk() {
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
/// past the end of the optional header, so its 8 bytes would otherwise be
/// read from the section table. The entry index is still within
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
#[test]
fn rejects_import_directory_outside_short_optional_header() {
let mut image = two_import_pe32_plus();
// Import entry spans optional-header offsets 120..128; declare the
// optional header to end at 120, inside the entry.
put_u16(&mut image, COFF + 16, 120);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// One byte short of the full 8-byte entry is still out of range.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 127);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// Exactly 128 bytes covers the whole entry, so the import directory is
// read normally. The section table now starts at OPT + 128, so write it
// there for this size.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 128);
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.contains_key("ALPHA.DLL"));
assert!(summary.imports.contains_key("BETA.DLL"));
}
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
/// import entry (index 1) must not be probed even though its bytes are
/// present and inside SizeOfOptionalHeader.
#[test]
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
let mut image = two_import_pe32_plus();
put_u32(&mut image, OPT + 108, 1);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
/// (b) The declared import directory Size is shorter than the containing
/// section, so descriptors past the declared size must not be reported even
/// though they are valid and inside the section's raw bytes.
#[test]
fn bounds_import_descriptor_walk_by_declared_directory_size() {
// Size 40 covers exactly the two real descriptors; the third valid
// descriptor at +40 lies outside the directory but inside the section.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 40);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
assert!(!summary.imports.contains_key("THREE.DLL"));
// Size 20 reports only the first descriptor.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 20);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
// A size that is not a multiple of 20 stops before the next descriptor
// would exceed the directory.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 39);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
}
}
+678 -5
View File
@@ -13,10 +13,165 @@ pub struct TraceSummary {
pub clwb_events: usize,
/// Highest cumulative counter in the sampled CLWB records, if available.
pub clwb_trap_lower_bound: Option<u64>,
/// Sampled `<kind>_trapped` records for the other AMD-only instructions the
/// VEH emulates (`clzero`, `monitorx`, `mwaitx`, `rdpru`, `extrq`, `insertq`).
pub amd_traps: BTreeMap<String, TrapCount>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
pub shader_gate: ShaderGateSummary,
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
pub shader_gaps: Vec<ShaderGap>,
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
pub shader_gap_groups: Vec<ShaderGapGroup>,
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
/// they are grouped under `unknown`. Counted here so the group counts reconcile
/// with [`TraceSummary::shader_gaps`].
pub shader_gaps_missing_identity: usize,
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
/// value for one). Counted here rather than dropped or assumed.
pub shader_gaps_missing_constraints: usize,
/// `shader_bridge_missing` messages, in log order.
pub shader_bridge_missing: Vec<String>,
}
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapGroup {
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
/// `unknown`).
pub pso: Option<String>,
/// The emitted `stage=` value, or `None` when the record carried none.
pub stage: Option<String>,
/// How many gap records this `(pso, stage)` pair covers.
pub count: usize,
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
/// first-seen order. Two pipelines of the same kind and stage can need different
/// wave widths or atomic features, so a group keeps each constraint set rather than
/// reporting only the first and losing the rest.
pub variants: Vec<ShaderGapVariant>,
}
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapVariant {
pub wave_lanes_min: Option<String>,
pub atomic64_flags: Option<String>,
/// How many records in the group carried exactly these constraints.
pub count: usize,
}
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
/// their emitted string so unknown values are counted rather than dropped.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGateSummary {
pub total: usize,
/// Gate records whose `detail` could not be parsed as `key=value` pairs.
pub unparsed: usize,
/// Parsed gate records that carry no `decision` field, so they appear in no
/// `decisions` bucket. Counted here so the decision counts can be
/// reconciled against `total` (#497 review). `kind` is legitimately absent
/// on unclassified records and is not counted here.
pub missing_decision: usize,
pub decisions: BTreeMap<String, usize>,
pub kinds: BTreeMap<String, usize>,
pub stages: BTreeMap<String, usize>,
/// Individual gate records, in log order.
pub records: Vec<ShaderGateRecord>,
}
/// One `shader_gate` record. Fields absent from the emitted `detail` (for
/// example on unclassified records) are `None`; `atomic64` may be `Some("")`.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGateRecord {
pub pso: Option<String>,
pub stage: Option<String>,
pub decision: Option<String>,
pub hr: Option<String>,
pub kind: Option<String>,
pub shader_stage: Option<String>,
pub sm: Option<String>,
pub bytes: Option<String>,
pub dxil: Option<String>,
pub accc: Option<String>,
pub sfi0: Option<String>,
pub wave_ops: Option<String>,
pub int64_ops: Option<String>,
pub atomic64: Option<String>,
pub wave_lanes: Option<String>,
}
/// One `shader_d3dmetal_gap` record.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGap {
pub pso: Option<String>,
pub stage: Option<String>,
pub wave_lanes_min: Option<String>,
pub atomic64_flags: Option<String>,
}
/// Tokenize a `detail` string of space-separated `key=value` pairs.
///
/// Only the `shader_d3dmetal_gap` record appends free text after its pairs
/// (`... atomic64_flags=0x400000: D3DMetal ...`), so `stop_at_free_text`
/// selects how a token without `=` is treated:
///
/// - `true` (gap records): the token ends the key=value section.
/// - `false` (`shader_gate` records): a stray token is skipped and parsing
/// continues, so one unexpected word cannot silently drop every later
/// field (#497 review).
///
/// Values never contain spaces, so `atomic64=` followed by a space yields an
/// empty value.
/// Splits a log detail string into `key=value` pairs.
///
/// `stop_at_free_text` exists for records that end with prose after their
/// fields (`shader_d3dmetal_gap` ends in a sentence), where the first token
/// without `=` marks the end of the structured part.
///
/// For `shader_gate` the whole string is structured, so a token without `=`
/// is skipped rather than treated as the end. Stopping there would silently
/// drop every later field while the record still counted as parsed: with
/// `atomic64=typed, raw, wave_lanes=64-64`, a `break` loses `wave_lanes`,
/// whereas a `continue` keeps it. The emitter writes no spaces inside a value
/// today, so this is robustness against a future value containing one, not a
/// fix for current output.
fn parse_key_values(detail: &str, stop_at_free_text: bool) -> Vec<(&str, &str)> {
let mut pairs = Vec::new();
for token in detail.split_ascii_whitespace() {
match token.split_once('=') {
Some((key, value)) if !key.is_empty() => pairs.push((key, value)),
_ if stop_at_free_text => break,
_ => continue,
}
}
pairs
}
/// Sampled trap records of one instruction kind.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TrapCount {
pub events: usize,
/// Highest cumulative counter in the sampled records, if available.
pub lower_bound: Option<u64>,
}
const AMD_TRAP_EVENTS: [(&str, &str); 6] = [
("clzero_trapped", "clzero"),
("monitorx_trapped", "monitorx"),
("mwaitx_trapped", "mwaitx"),
("rdpru_trapped", "rdpru"),
("extrq_trapped", "extrq"),
("insertq_trapped", "insertq"),
];
fn sampled_counter(detail: &str) -> Option<u64> {
detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok())
}
#[derive(Debug, PartialEq, Eq)]
@@ -35,6 +190,124 @@ fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
Some(&rest[..end])
}
fn get_field<'a>(pairs: &[(&'a str, &'a str)], key: &str) -> Option<String> {
pairs
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| (*v).to_owned())
}
fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
let gate = &mut summary.shader_gate;
gate.total += 1;
let pairs = parse_key_values(detail, false);
if pairs.is_empty() {
gate.unparsed += 1;
return;
}
let record = ShaderGateRecord {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
decision: get_field(&pairs, "decision"),
hr: get_field(&pairs, "hr"),
kind: get_field(&pairs, "kind"),
shader_stage: get_field(&pairs, "shader_stage"),
sm: get_field(&pairs, "sm"),
bytes: get_field(&pairs, "bytes"),
dxil: get_field(&pairs, "dxil"),
accc: get_field(&pairs, "accc"),
sfi0: get_field(&pairs, "sfi0"),
wave_ops: get_field(&pairs, "wave_ops"),
int64_ops: get_field(&pairs, "int64_ops"),
atomic64: get_field(&pairs, "atomic64"),
wave_lanes: get_field(&pairs, "wave_lanes"),
};
match &record.decision {
Some(decision) => *gate.decisions.entry(decision.clone()).or_insert(0) += 1,
None => gate.missing_decision += 1,
}
if let Some(kind) = &record.kind {
*gate.kinds.entry(kind.clone()).or_insert(0) += 1;
}
if let Some(stage) = &record.stage {
*gate.stages.entry(stage.clone()).or_insert(0) += 1;
}
gate.records.push(record);
}
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
/// always writes a value, so an empty one means the record is malformed, not that the
/// pipeline is named "".
fn non_empty(value: Option<String>) -> Option<String> {
value.filter(|v| !v.is_empty())
}
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
///
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
let pso = non_empty(gap.pso.clone());
let stage = non_empty(gap.stage.clone());
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
if pso.is_none() || stage.is_none() {
groups.shader_gaps_missing_identity += 1;
}
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
groups.shader_gaps_missing_constraints += 1;
}
// The group list is small (one entry per affected pipeline stage), so a linear scan
// keeps first-seen order without a second index to keep in sync.
let group_index = match groups
.shader_gap_groups
.iter()
.position(|g| g.pso == pso && g.stage == stage)
{
Some(index) => index,
None => {
groups.shader_gap_groups.push(ShaderGapGroup {
pso,
stage,
count: 0,
variants: Vec::new(),
});
groups.shader_gap_groups.len() - 1
}
};
let group = &mut groups.shader_gap_groups[group_index];
group.count += 1;
match group
.variants
.iter()
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
{
Some(index) => group.variants[index].count += 1,
None => group.variants.push(ShaderGapVariant {
wave_lanes_min,
atomic64_flags,
count: 1,
}),
}
}
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
let pairs = parse_key_values(detail, true);
// The emitter appends `: D3DMetal creates such pipelines ...` directly
// after the flags value, so strip the trailing colon.
let atomic64_flags = get_field(&pairs, "atomic64_flags")
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
let gap = ShaderGap {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
atomic64_flags,
};
record_shader_gap_group(summary, &gap);
summary.shader_gaps.push(gap);
}
pub fn summarize_jsonl(input: &str) -> TraceSummary {
let mut summary = TraceSummary::default();
for line in input.lines() {
@@ -48,11 +321,19 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
match event {
"clwb_trapped" => {
summary.clwb_events += 1;
let sample = detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok());
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
summary.clwb_trap_lower_bound =
summary.clwb_trap_lower_bound.max(sampled_counter(detail));
}
_ if AMD_TRAP_EVENTS.iter().any(|(e, _)| *e == event) => {
let name = AMD_TRAP_EVENTS.iter().find(|(e, _)| *e == event).unwrap().1;
let entry = summary.amd_traps.entry(name.to_string()).or_default();
entry.events += 1;
entry.lower_bound = entry.lower_bound.max(sampled_counter(detail));
}
"shader_gate" => record_shader_gate(&mut summary, detail),
"shader_d3dmetal_gap" => record_shader_gap(&mut summary, detail),
"shader_bridge_missing" => {
summary.shader_bridge_missing.push(detail.to_owned());
}
"adx_illegal_instruction" => summary.adx_errors += 1,
"unhandled_exception" => {
@@ -165,4 +446,396 @@ mod tests {
]
);
}
#[test]
fn counts_amd_only_traps_per_kind() {
let summary = summarize_jsonl(
r#"{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=1"}
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=2"}
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=4"}
{"event":"extrq_trapped","detail":"rip=0x2000 len=5 total_traps=1"}
{"event":"rdpru_trapped","detail":"rip=0x3000 len=3"}"#,
);
assert_eq!(
summary.amd_traps["clzero"],
TrapCount {
events: 3,
lower_bound: Some(4)
}
);
assert_eq!(
summary.amd_traps["extrq"],
TrapCount {
events: 1,
lower_bound: Some(1)
}
);
assert_eq!(
summary.amd_traps["rdpru"],
TrapCount {
events: 1,
lower_bound: None
}
);
assert!(!summary.amd_traps.contains_key("mwaitx"));
assert_eq!(summary.clwb_events, 0);
}
#[test]
fn summarizes_full_pass_dxil_gate_record() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.unparsed, 0);
assert_eq!(summary.shader_gate.decisions["pass_dxil"], 1);
assert_eq!(summary.shader_gate.kinds["dxil"], 1);
assert_eq!(summary.shader_gate.stages["CS"], 1);
assert_eq!(summary.shader_gate.records.len(), 1);
let r = &summary.shader_gate.records[0];
assert_eq!(r.pso.as_deref(), Some("compute"));
assert_eq!(r.stage.as_deref(), Some("CS"));
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
assert_eq!(r.hr.as_deref(), Some("0x00000000"));
assert_eq!(r.kind.as_deref(), Some("dxil"));
assert_eq!(r.shader_stage.as_deref(), Some("5"));
assert_eq!(r.sm.as_deref(), Some("6.6"));
assert_eq!(r.bytes.as_deref(), Some("1234"));
assert_eq!(r.dxil.as_deref(), Some("800"));
assert_eq!(r.accc.as_deref(), Some("0"));
assert_eq!(r.sfi0.as_deref(), Some("0x4000"));
assert_eq!(r.wave_ops.as_deref(), Some("1"));
assert_eq!(r.int64_ops.as_deref(), Some("0"));
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
}
#[test]
fn summarizes_reject_accc_only_gate_record() {
let log = r#"{"ts_ms":12,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_gate","detail":"pso=graphics stage=VS decision=reject_accc_only hr=0x80004001 kind=accc_only shader_stage=0 sm=6.0 bytes=2048 dxil=0 accc=512 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=none"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.decisions["reject_accc_only"], 1);
assert_eq!(summary.shader_gate.kinds["accc_only"], 1);
assert_eq!(summary.shader_gate.stages["VS"], 1);
let r = &summary.shader_gate.records[0];
assert_eq!(r.hr.as_deref(), Some("0x80004001"));
assert_eq!(r.sm.as_deref(), Some("6.0"));
assert_eq!(r.accc.as_deref(), Some("512"));
assert_eq!(r.atomic64.as_deref(), Some(""));
assert_eq!(r.wave_lanes.as_deref(), Some("none"));
}
#[test]
fn summarizes_unclassified_gate_record_without_kind() {
let log = r#"{"ts_ms":14,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_unclassified hr=0x00000000 bytes=4096"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.decisions["pass_unclassified"], 1);
assert_eq!(summary.shader_gate.stages["CS"], 1);
assert!(summary.shader_gate.kinds.is_empty());
let r = &summary.shader_gate.records[0];
assert_eq!(r.bytes.as_deref(), Some("4096"));
assert_eq!(r.kind, None);
assert_eq!(r.sm, None);
assert_eq!(r.dxil, None);
assert_eq!(r.atomic64, None);
assert_eq!(r.wave_lanes, None);
}
#[test]
fn summarizes_d3dmetal_gap_with_free_text_suffix() {
let log = r#"{"ts_ms":16,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gaps.len(), 1);
let gap = &summary.shader_gaps[0];
assert_eq!(gap.pso.as_deref(), Some("compute"));
assert_eq!(gap.stage.as_deref(), Some("CS"));
assert_eq!(gap.wave_lanes_min.as_deref(), Some("64"));
assert_eq!(gap.atomic64_flags.as_deref(), Some("0x400000"));
}
#[test]
fn collects_shader_bridge_missing_messages() {
let log = r#"{"ts_ms":18,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_bridge_missing","detail":"bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, ACCC-only refused"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_bridge_missing.len(), 1);
assert!(summary.shader_bridge_missing[0].contains("not found beside d3d12_xs.dll"));
}
#[test]
fn malformed_shader_gate_detail_is_counted_not_dropped() {
for detail in ["", "garbage", "=value", " "] {
let log = format!(
"{{\"ts_ms\":20,\"tid\":1,\"level\":\"INFO\",\"sub\":\"d3d12_xs\",\"event\":\"shader_gate\",\"detail\":\"{detail}\"}}"
);
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gate.total, 1, "detail={detail:?}");
assert_eq!(summary.shader_gate.unparsed, 1, "detail={detail:?}");
assert!(summary.shader_gate.records.is_empty(), "detail={detail:?}");
}
}
#[test]
fn empty_atomic64_value_is_preserved() {
let log = r#"{"ts_ms":22,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=100 dxil=64 accc=0 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=0-4294967295"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.atomic64.as_deref(), Some(""));
assert_eq!(r.wave_lanes.as_deref(), Some("0-4294967295"));
}
#[test]
fn a_stray_token_does_not_drop_later_gate_fields() {
// #497 review point 1: one value containing a space must not turn every
// later field into None.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil atomic64=typed, raw wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
assert_eq!(summary.shader_gate.unparsed, 0);
}
#[test]
fn two_atomic64_flags_are_parsed() {
// #497 review point 1: the emitter concatenates flags with no separator,
// but two flags must round-trip if they ever are spaced.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil kind=dxil atomic64=typed, groupshared, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
}
#[test]
fn a_gate_record_without_a_decision_is_counted_as_missing() {
// #497 review point 2: decision counts must reconcile against total.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.missing_decision, 1);
assert_eq!(summary.shader_gate.unparsed, 0);
assert!(summary.shader_gate.decisions.is_empty());
assert_eq!(summary.shader_gate.stages["CS"], 1);
}
#[test]
fn decision_buckets_plus_missing_reconcile_with_total() {
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil bytes=1"}
{"event":"shader_gate","detail":"pso=compute stage=CS"}
{"event":"shader_gate","detail":"garbage"}"#;
let summary = summarize_jsonl(log);
let gate = &summary.shader_gate;
let bucketed: usize = gate.decisions.values().sum();
assert_eq!(gate.total, 3);
assert_eq!(gate.unparsed, 1);
assert_eq!(gate.missing_decision, 1);
assert_eq!(bucketed + gate.unparsed + gate.missing_decision, gate.total);
}
#[test]
fn unknown_decisions_and_kinds_are_counted() {
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=some_future_decision hr=0x00000000 kind=some_future_kind bytes=1"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.decisions["some_future_decision"], 1);
assert_eq!(summary.shader_gate.kinds["some_future_kind"], 1);
}
/// A stray token must not end the structured part of a `shader_gate`
/// record: if it did, every later field would silently become `None`
/// while the record still counted as parsed.
#[test]
fn a_record_without_a_decision_is_counted_as_missing() {
let mut summary = TraceSummary::default();
record_shader_gate(&mut summary, "pso=graphics stage=pixel");
let gate = &summary.shader_gate;
assert_eq!(gate.total, 1);
assert_eq!(gate.unparsed, 0);
assert_eq!(gate.missing_decision, 1);
assert!(gate.decisions.is_empty());
}
/// The free-text path is the opposite: `shader_d3dmetal_gap` ends in a
/// sentence, so the first token without `=` ends the structured part.
#[test]
fn free_text_ends_the_structured_part_of_a_gap_record() {
let pairs = parse_key_values("pso=graphics stage=pixel and then some prose", true);
assert_eq!(pairs.len(), 2);
assert_eq!(pairs[1], ("stage", "pixel"));
}
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
/// with its own wave width and 64-bit-atomic flags.
#[test]
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
// Same pso, different stages: grouping on pso alone would collapse these, so the
// test discriminates the (pso, stage) key rather than only the pso.
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
assert_eq!(summary.shader_gap_groups.len(), 3);
let first = &summary.shader_gap_groups[0];
assert_eq!(first.pso.as_deref(), Some("graphics"));
assert_eq!(first.stage.as_deref(), Some("VS"));
assert_eq!(first.count, 1);
assert_eq!(
first.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 1,
}]
);
let second = &summary.shader_gap_groups[1];
assert_eq!(second.pso.as_deref(), Some("compute"));
assert_eq!(second.stage.as_deref(), Some("CS"));
assert_eq!(second.count, 1);
// A second stage of the *same* pso stays its own group, which is what separates a
// (pso, stage) key from a pso-only key.
let third = &summary.shader_gap_groups[2];
assert_eq!(third.pso.as_deref(), Some("graphics"));
assert_eq!(third.stage.as_deref(), Some("PS"));
assert_eq!(third.count, 1);
}
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
/// identical records are not adjacent.
#[test]
fn groups_identical_gaps_together() {
let record = r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let log = format!("{record}\n{other}\n{record}\n");
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gap_groups.len(), 2);
let compute = &summary.shader_gap_groups[0];
assert_eq!(compute.stage.as_deref(), Some("CS"));
assert_eq!(compute.count, 2);
assert_eq!(
compute.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 2,
}]
);
assert_eq!(summary.shader_gap_groups[1].count, 1);
// Every record is in exactly one group.
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
assert_eq!(grouped, summary.shader_gaps.len());
}
/// #590: one pipeline kind and stage can need different wave widths or atomic
/// features, so a group keeps every distinct constraint set, not only the first.
#[test]
fn one_group_keeps_each_distinct_constraint_set() {
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gap_groups.len(), 1);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 3);
assert_eq!(
group.variants,
[
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 2,
},
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 1,
},
]
);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
/// #590: a gap record with a missing or empty field must not panic. It is grouped
/// under `unknown` and counted, never dropped or guessed.
#[test]
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
for (detail, missing_identity, missing_constraints) in [
("", 1, 1),
("garbage", 1, 1),
("pso=compute", 1, 1),
("stage=CS", 1, 1),
(
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
1,
0,
),
("pso=compute stage=CS", 0, 1),
(
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
0,
1,
),
] {
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
assert_eq!(
summary.shader_gap_groups.len(),
1,
"detail={detail:?} lost its record"
);
assert_eq!(
summary.shader_gaps_missing_identity, missing_identity,
"detail={detail:?}"
);
assert_eq!(
summary.shader_gaps_missing_constraints, missing_constraints,
"detail={detail:?}"
);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 1, "detail={detail:?}");
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
assert_eq!(recorded, 1, "detail={detail:?}");
}
}
/// #590: the fields a malformed record does carry are still reported.
#[test]
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
let log =
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
let summary = summarize_jsonl(log);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.pso.as_deref(), Some("compute"));
assert_eq!(group.stage.as_deref(), Some("CS"));
assert_eq!(
group.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: None,
count: 1,
}]
);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 1);
}
/// #590: a run with no gap records produces no groups and no missing-field counts, so
/// the trace renders as it did before the grouping existed.
#[test]
fn a_run_with_no_gaps_has_no_groups() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert!(summary.shader_gaps.is_empty());
assert!(summary.shader_gap_groups.is_empty());
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
}
+116 -20
View File
@@ -4,11 +4,15 @@
Checks only tracked files:
1. no merge-conflict markers in tracked text files;
2. every relative Markdown link points at a tracked file or directory;
3. every workflow file under .github/workflows parses as YAML.
3. every fragment (``#heading``) in a Markdown link resolves to a real
heading in the target Markdown file, including in-page ``](#foo)``
links validated against the same file's headings;
4. every workflow file under .github/workflows parses as YAML.
External URLs and in-page anchors are not fetched or validated, so the result
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
when PyYAML is missing.
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
fetched or validated, so the result does not depend on the network.
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
not skip, when PyYAML is missing.
"""
import re
import subprocess
@@ -20,6 +24,13 @@ ROOT = Path(__file__).resolve().parents[2]
MARKER = re.compile(r"^(<{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):
+231
View File
@@ -0,0 +1,231 @@
#!/usr/bin/env python3
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
Run with:
python3 -m unittest scripts/audit/test_docs_hygiene.py
"""
import importlib.util
import sys
import unittest
from pathlib import Path
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
docs_hygiene = importlib.util.module_from_spec(_spec)
sys.modules["docs_hygiene"] = docs_hygiene
_spec.loader.exec_module(docs_hygiene)
class SlugTests(unittest.TestCase):
def test_basic_slug(self):
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
self.assertIn("hello-world", slugs)
def test_strips_punctuation(self):
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
self.assertIn("whats-new-2024", slugs)
def test_keeps_underscore_and_hyphen(self):
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
self.assertIn("foo_bar-baz", slugs)
def test_duplicate_headings(self):
body = "# Setup\n\n# Setup\n\n# Setup\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("setup", slugs)
self.assertIn("setup-1", slugs)
self.assertIn("setup-2", slugs)
def test_suffix_skips_literal_heading_slug(self):
# Regression: counting identical bases alone lets a generated
# suffix collide with a literal heading slug, so the third `Foo`
# also became `foo-1` and a link to the wrong heading validated.
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_suffix_skips_multiple_literal_heading_slugs(self):
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
def test_three_identical_headings(self):
body = "# Foo\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_literal_slug_before_duplicates(self):
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
def test_heading_link_contributes_only_its_text(self):
# GitHub slugs the rendered heading, where the link's URL is gone.
# Slugging the raw source appended the URL and made the first real
# link to the anchor look broken.
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
self.assertEqual(slugs, {"setup-guide-notes"})
def test_heading_link_matches_github_for_the_readme_heading(self):
# The exact heading at README.md:53; GitHub renders
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
def test_heading_link_duplicate_still_gets_a_suffix(self):
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
def test_heading_link_inside_a_code_span_stays_literal(self):
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
# the slug. Substituting links first made this `code-x-span`.
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
self.assertEqual(slugs, {"code-xy-span"})
def test_heading_mixes_a_code_span_and_a_link(self):
# Only the real link loses its URL; the code span keeps its text.
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
self.assertEqual(slugs, {"see-a-and-b"})
def test_heading_double_backtick_code_span(self):
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
# the inner single-backtick run closes the outer span early, so the
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
# observed GitHub anchor keeps this honest rather than assuming the
# "obvious" answer.
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
def test_heading_image_is_not_treated_as_a_link(self):
# An image contributes its alt text through GitHub's rendering, but
# the `(?<!\!)` guard must keep this path unchanged for now.
slugs = docs_hygiene.markdown_slugs("## ![img](a.png) caption\n")
self.assertEqual(len(slugs), 1)
def test_fenced_code_block_ignored(self):
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("real-heading", slugs)
self.assertNotIn("not-a-heading", slugs)
def test_tilde_fence_ignored(self):
body = "~~~\n# Not A Heading\n~~~\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertNotIn("not-a-heading", slugs)
def test_atx_levels(self):
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
slugs = docs_hygiene.markdown_slugs(body)
for s in ("one", "two", "three", "four", "five", "six"):
self.assertIn(s, slugs)
class CheckLinksTests(unittest.TestCase):
"""Exercise check_links with a synthetic in-memory file set."""
def _run(self, files):
"""files: dict mapping repo-relative path -> Markdown body."""
problems = []
original_text = docs_hygiene.text
def fake_text(path):
return files.get(path)
docs_hygiene.text = fake_text
try:
docs_hygiene.check_links(list(files), problems)
finally:
docs_hygiene.text = original_text
return problems
def test_existing_heading_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(problems, [])
def test_in_page_anchor_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
})
self.assertEqual(problems, [])
def test_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "[link](b.md#no-such-heading)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#no-such-heading", problems[0])
self.assertIn("heading not found", problems[0])
def test_in_page_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#this-heading-does-not-exist", problems[0])
def test_duplicate_heading_addressable(self):
problems = self._run({
"docs/a.md": "[link](b.md#setup-1)\n",
"docs/b.md": "# Setup\n\n# Setup\n",
})
self.assertEqual(problems, [])
def test_fenced_heading_not_a_slug(self):
problems = self._run({
"docs/a.md": "[link](b.md#not-a-heading)\n",
"docs/b.md": "```\n# Not A Heading\n```\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#not-a-heading", problems[0])
def test_external_url_with_fragment_not_checked(self):
problems = self._run({
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
})
self.assertEqual(problems, [])
def test_mailto_not_checked(self):
problems = self._run({
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
})
self.assertEqual(problems, [])
def test_protocol_relative_not_checked(self):
problems = self._run({
"docs/a.md": "[link](//example.com/page#frag)\n",
})
self.assertEqual(problems, [])
def test_bare_hash_skipped(self):
problems = self._run({
"docs/a.md": "[link](#)\n",
})
self.assertEqual(problems, [])
def test_missing_file_still_reported(self):
problems = self._run({
"docs/a.md": "[link](nonexistent.md#foo)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("broken relative link", problems[0])
def test_fragment_on_non_markdown_not_checked(self):
problems = self._run({
"docs/a.md": "[link](image.png#foo)\n",
"docs/image.png": None,
})
# image.png is binary (text returns None) but it exists in the
# file list, so the link itself resolves; fragment is not checked.
self.assertEqual(problems, [])
if __name__ == "__main__":
unittest.main()
+31
View File
@@ -18,6 +18,37 @@ cmake -S "$ROOT_DIR/shims" -B "$BUILD_DIR" \
cmake --build "$BUILD_DIR" --parallel "$JOBS"
# bx_shader_bridge.dll (#445, #484): shader-transpiler/crates/dxbc-accc built for x86-64
# Windows guests, linked with abi/defs/bx_shader_bridge.def so its export list and internal
# name are the frozen ones. The verifier below then checks it like every other shim.
# Cargo and rustc are resolved through rustup when present (a cargo earlier on PATH may have
# no Windows std), and the build always goes to <repo>/target so no stale DLL is staged.
BRIDGE_TARGET=x86_64-pc-windows-gnu
if command -v rustup >/dev/null 2>&1; then
BRIDGE_CARGO="$(cd "$ROOT_DIR" && rustup which cargo)"
BRIDGE_RUSTC="$(cd "$ROOT_DIR" && rustup which rustc)"
else
BRIDGE_CARGO="$(command -v cargo || true)"
BRIDGE_RUSTC="$(command -v rustc || true)"
fi
if [ -z "$BRIDGE_CARGO" ] || [ -z "$BRIDGE_RUSTC" ]; then
echo "error: cargo/rustc not found; bx_shader_bridge.dll needs the Rust toolchain" >&2
exit 1
fi
BRIDGE_LIBDIR="$("$BRIDGE_RUSTC" --print target-libdir --target "$BRIDGE_TARGET" 2>/dev/null || true)"
if [ -z "$BRIDGE_LIBDIR" ] || ! ls "$BRIDGE_LIBDIR"/libstd-*.rlib >/dev/null 2>&1; then
echo "error: $("$BRIDGE_RUSTC" --version) has no std for $BRIDGE_TARGET, needed for bx_shader_bridge.dll" >&2
echo "error: install it with: rustup target add $BRIDGE_TARGET" >&2
exit 1
fi
echo "=== Building bx_shader_bridge.dll with $("$BRIDGE_RUSTC" --version) ==="
RUSTC="$BRIDGE_RUSTC" CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
"$BRIDGE_CARGO" rustc --locked --release -j "$JOBS" --manifest-path "$ROOT_DIR/Cargo.toml" \
-p dxbc-accc --lib --crate-type cdylib --target "$BRIDGE_TARGET" --target-dir "$ROOT_DIR/target" \
-- -C link-arg="$ROOT_DIR/abi/defs/bx_shader_bridge.def"
mkdir -p "$BUILD_DIR/bin"
cp "$ROOT_DIR/target/$BRIDGE_TARGET/release/dxbc_accc.dll" "$BUILD_DIR/bin/bx_shader_bridge.dll"
echo "=== Verifying built PE32+ DLL Export Directories against abi/defs/*.def ==="
python3 - "$ROOT_DIR/abi/defs" "$BUILD_DIR/bin" <<'PY'
import os
@@ -185,6 +185,9 @@ pub enum Verdict {
DeviceRemoved { reason: u32 },
/// The GPU did not signal completion in time.
TimedOut { detail: String },
/// The device reported a highest shader model below the 6.6 the harness kernel
/// requires. The field was parsed and printed before, but never judged (#567).
UnsupportedShaderModel { reported: u8 },
/// Every word still holds the sentinel: the kernel never wrote.
KernelDidNotRun,
/// The kernel wrote, but some words differ from the expected values.
@@ -224,6 +227,12 @@ impl fmt::Display for Verdict {
)
}
Self::TimedOut { detail } => write!(f, "FAIL: GPU timeout ({detail})"),
Self::UnsupportedShaderModel { reported } => write!(
f,
"FAIL: highest shader model {}.{} is below the 6.6 the harness kernel requires",
reported >> 4,
reported & 0xf
),
Self::KernelDidNotRun => write!(
f,
"FAIL: all {WORDS} words still hold the sentinel 0x{SENTINEL:08x}; the kernel did not write"
@@ -272,6 +281,14 @@ pub fn judge(report: &ProbeReport) -> Verdict {
let incomplete = |reason: &str| Verdict::Incomplete {
reason: reason.to_owned(),
};
// Every kernel the harness runs is SM 6.6. A device that reports less, or a
// report with no shader_model record, must not pass on a matching readback
// alone (#567). The live Rust test asserted this; the standalone verdict did not.
match report.shader_model {
Some(sm) if sm < 0x66 => return Verdict::UnsupportedShaderModel { reported: sm },
None => return incomplete("no shader_model record"),
Some(_) => {}
}
match report.dispatch {
None => return incomplete("no dispatch record"),
Some(d) if d != expected_dispatch => {
@@ -341,6 +358,29 @@ mod tests {
assert_eq!(judge(&report), Verdict::Pass);
}
#[test]
fn a_shader_model_below_6_6_fails_even_with_a_matching_readback() {
// The kernel is SM 6.6; the readback matching proves only that something wrote.
for reported in ["0x65", "0x60"] {
let lower = output(&good_words()).replace(
"BXD3DM shader_model 0x66",
&format!("BXD3DM shader_model {reported}"),
);
let report = parse_report(&lower).unwrap();
assert_eq!(
judge(&report),
Verdict::UnsupportedShaderModel {
reported: if reported == "0x65" { 0x65 } else { 0x60 }
}
);
}
// Without the record the harness cannot say the device can run the shader.
let absent = output(&good_words()).replace("BXD3DM shader_model 0x66\n", "");
let report = parse_report(&absent).unwrap();
assert_eq!(report.shader_model, None);
assert!(matches!(judge(&report), Verdict::Incomplete { .. }));
}
#[test]
fn untouched_sentinel_means_the_kernel_did_not_run() {
let report = parse_report(&output(&[SENTINEL; WORDS])).unwrap();
@@ -80,12 +80,14 @@ fn collect(rx: &Receiver<Event>, until: Instant) -> io::Result<(Vec<u8>, Vec<u8>
Ok((stdout, stderr, true))
}
fn wait_until(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
/// `deadline: None` means the requested timeout is not representable on this clock, so the
/// probe is allowed to run without one (#587).
fn wait_until(child: &mut Child, deadline: Option<Instant>) -> io::Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if Instant::now() >= deadline {
if deadline.is_some_and(|at| Instant::now() >= at) {
child.kill()?;
child.wait()?;
return Ok(None);
@@ -112,7 +114,13 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
command.env(key, value);
}
}
let deadline = Instant::now() + timeout;
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow, so a
// huge value would abort the harness with exit 101 instead of one of its verdict codes
// (#586). Saturate at the platform maximum instead: the probe then simply never times out.
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow. When the
// requested timeout is not representable the probe simply has no deadline; representing
// that as `None` avoids inventing a fallback duration that might also not fit (#587).
let deadline = Instant::now().checked_add(timeout);
let mut child = command.spawn()?;
let (tx, rx) = mpsc::channel();
pump(
@@ -126,8 +134,11 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
tx,
);
let status = wait_until(&mut child, deadline)?;
let (stdout, stderr, output_complete) =
collect(&rx, deadline.max(Instant::now() + DRAIN_GRACE))?;
// With no deadline the probe has already exited, so draining still needs a bound.
let drain_until = deadline
.unwrap_or_else(Instant::now)
.max(Instant::now() + DRAIN_GRACE);
let (stdout, stderr, output_complete) = collect(&rx, drain_until)?;
Ok(ProbeRun {
status,
stdout: String::from_utf8_lossy(&stdout).into_owned(),
@@ -161,6 +172,35 @@ mod tests {
}
}
#[test]
fn an_unrepresentable_deadline_leaves_the_probe_without_a_timeout() {
// `checked_add` returns None for a timeout the clock cannot represent; the runner
// must then wait for the probe normally instead of inventing a fallback duration
// that could itself overflow (#587).
let script = Script::new("nodeadline", "sleep 0.2; exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
)
.expect("an unrepresentable deadline must not abort the run");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
assert!(run.output_complete);
}
#[test]
fn an_overflowing_timeout_does_not_panic() {
// u64::MAX seconds overflows `Instant + Duration`; before #586 this panicked.
let script = Script::new("overflow", "exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
);
let run = run.expect("an overflowing timeout must still run the probe, not panic");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
}
#[test]
fn passes_the_framework_and_only_allowlisted_environment() {
let script = Script::new("env", "echo \"args=$*\"; env; echo oops >&2; exit 3");
@@ -186,22 +226,70 @@ mod tests {
assert!(run.output_complete);
}
/// Timeout for the tests below whose stand-in probe has to start and print before the
/// deadline. Starting a freshly written script costs tens of milliseconds here and
/// occasionally far more, so a few hundred milliseconds made these tests fail now and then
/// (#479). They check what happens at the deadline, not how fast a script starts.
const START_MARGIN: Duration = Duration::from_secs(2);
/// Removes the pid file, and kills the recorded process if a failing test left it running.
struct PidFile(PathBuf);
impl Drop for PidFile {
fn drop(&mut self) {
if std::thread::panicking()
&& let Ok(pid) = std::fs::read_to_string(&self.0)
{
let _ = Command::new("/bin/kill").arg(pid.trim()).status();
}
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn kills_a_probe_that_exceeds_the_timeout() {
let script = Script::new("hang", "echo started; exec sleep 30");
let pid_file = PidFile(
std::env::temp_dir().join(format!("bx-harness-probe's-{}.pid", std::process::id())),
);
let _ = std::fs::remove_file(&pid_file.0);
// Pass the path as the value of --framework. The apostrophe tests literal path handling.
// `exec` keeps the pid, so the recorded pid is the process that has to be killed.
let script = Script::new(
"hang",
"echo $$ > \"$2\" || exit 1; echo started; exec sleep 30",
);
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), Duration::from_millis(300)).unwrap();
let run = run_probe(&script.0, &pid_file.0, START_MARGIN).unwrap();
let elapsed = started.elapsed();
assert!(run.status.is_none());
// Output written before the kill is kept.
assert_eq!(run.stdout, "started\n");
assert!(started.elapsed() < Duration::from_secs(10));
// The probe ran until the deadline and no longer: it was killed, not waited for.
assert!(elapsed >= START_MARGIN, "returned early after {elapsed:?}");
assert!(
elapsed < START_MARGIN + DRAIN_GRACE + Duration::from_secs(5),
"returned after {elapsed:?}"
);
// The process is gone. `output_complete` is deliberately not asserted: tests run in
// parallel, and a child spawned by another test at the wrong moment can inherit this
// probe's pipe and hold it open (seen in 2 of 200 runs).
let pid = std::fs::read_to_string(&pid_file.0).unwrap();
let alive = Command::new("/bin/kill")
.args(["-0", pid.trim()])
.stderr(Stdio::null())
.status()
.unwrap()
.success();
assert!(!alive, "probe {} survived the timeout", pid.trim());
}
/// The probe exits at once, but a background descendant inherits stdout and
/// keeps it open well past the timeout.
#[test]
fn a_descendant_holding_the_pipes_cannot_outlast_the_deadline() {
let script = Script::new("orphan", "sleep 5 & echo started");
let timeout = Duration::from_millis(500);
// The descendant has to outlive the bound asserted below by a wide margin.
let script = Script::new("orphan", "sleep 6 & echo started");
let timeout = START_MARGIN;
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), timeout).unwrap();
let elapsed = started.elapsed();
+18 -4
View File
@@ -2,6 +2,15 @@
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
## `FSPX` errors
A malformed `FSPX` table fails inspection with a `ParseError`; it never panics. Two bounds errors are kept apart (#599):
- **`FspxLayoutMismatch`:** a descriptor's offset lands inside the 16-byte header or the descriptor table, the region the synthetic layout reserves. The table does not follow BetterXen's clean-room layout. The error carries the section id, the offset and the table length.
- **`FspxSectionOutOfBounds`:** a section starts after the table but runs past the end of the payload.
Both are still errors. Over the C ABI, both are `BX_SHADER_ERR_INVALID_BLOB`, so a caller of `bx_shader_inspect` cannot tell them apart yet; that would need an `[ABI]` change to `abi/include/bx_shader_bridge.h`.
## Guest access: `bx_shader_bridge.dll` (#445)
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
@@ -52,8 +61,13 @@ This is a synthetic, single-host result. It is not a measurement of any title's
Each of these faults compiled into the DLL fails the check: `dxil_chunk_size` clamped to 1, `accc_chunk_size` multiplied, the digest zeroed, `has_root_signature` set to 7, and the DXIL and ACCC kind numbers swapped. The last one also fails when it is rebuilt with `CARGO_TARGET_DIR` set elsewhere.
### Not done here (other owners)
### Related work, owned elsewhere
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`):** the frozen export list for the DLL. Linking with it would also set the export directory's internal name, which is `dxbc_accc.dll` today. Wine loads by file name, so this does not affect loading.
- **Staging in `scripts/build-shims.sh` (Track A):** building the DLL there and verifying it with the other shims, so `build-shims/bin` ships it. That would also make CI build it; today nothing does, and `rustup target add x86_64-pc-windows-gnu` is a manual step.
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (#466):** today `bx_shader_prepare_for_d3dmetal` reports an ACCC-only container on the guest's stderr (`bx-shader event=prepare status=unsupported …`), not through `bx_log_emit`.
Three of these pieces around this crate were recorded here as outstanding when this section was written and have since landed. The fourth is the trace summary of the records the shim emits.
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`, #445, #484):** present and in use. Its `LIBRARY` directive is `bx_shader_bridge.dll`, and `scripts/build-shims.sh` passes it to `cargo rustc` as `-C link-arg=…/abi/defs/bx_shader_bridge.def`, so the built DLL's export directory holds exactly the three header entry points and its internal name is `bx_shader_bridge.dll`, not `dxbc_accc.dll`. Cargo still names the built file `dxbc_accc.dll`; the script copies it to `build-shims/bin/bx_shader_bridge.dll`, and the verifier requires the export-directory name to match the `.def`.
- **Staging in `scripts/build-shims.sh` (Track A, #484):** done. The script builds this crate for `x86_64-pc-windows-gnu`, copies the result to `build-shims/bin/bx_shader_bridge.dll`, and verifies its export directory with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. CI's hybrid job installs that target with its pinned toolchain, so `rustup target add x86_64-pc-windows-gnu` is only a one-off step for a local build, and the script stops with that hint when the target's `std` is missing.
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (Track C, #466):** done. `CreateGraphicsPipelineState` and `CreateComputePipelineState` in `shims/d3d12_xs/proxy.cpp` run every stage through `BxShaderGate::admit` (`shims/d3d12_xs/shader_gate.cpp`), which calls `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` and emits `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` records through `bx_log_emit`. The bridge itself still writes its ACCC-only inspection line to the guest's stderr (`bx-shader event=prepare status=unsupported …`), because this crate does not link `bx_log_emit`; the JSONL records come from the shim.
- **Trace summary of those records (`bx-cli trace`, Track A, #496):** the work to parse `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` into `bx-telemetry` and render them in `bx-cli trace` is tracked in #496. This bullet describes the split of responsibility only — it does not depend on that issue's status, and the crate's own behaviour is unaffected either way.
This change does not touch the crate's code or tests; the tests above still describe its own behavior.
+32 -3
View File
@@ -10,6 +10,13 @@
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
//! count is rejected before any descriptor is compared with another, so
//! inspection stays allocation-free and the pairwise check stays bounded.
//!
//! A descriptor whose offset lands inside the 16-byte header or the
//! descriptor table itself is a layout mismatch, reported apart from a
//! section that runs past the end of the payload. Read through this layout,
//! such a table is not merely truncated or corrupt: its descriptors do not
//! mean `(id, offset, size)` relative to the payload as this module assumes.
//! It is still an error, and the container is still refused.
use super::{ShaderStage, read_u32_le};
@@ -82,9 +89,22 @@ impl FspxInfo {
pub(crate) enum FspxError {
Truncated,
BadVersion(u32),
SectionOutOfBounds { section_id: u32 },
DuplicateSection { section_id: u32 },
Overlap { section_id: u32 },
SectionOutOfBounds {
section_id: u32,
},
/// The descriptor's offset lies inside the header plus descriptor table,
/// the region this layout reserves, so the table does not follow it.
LayoutMismatch {
section_id: u32,
offset: u32,
table_end: u32,
},
DuplicateSection {
section_id: u32,
},
Overlap {
section_id: u32,
},
BadStageConfig,
TooManySections(u32),
}
@@ -217,6 +237,15 @@ fn walk_sections(
) -> Result<(), FspxError> {
for index in 0..header.count {
let (id, offset, size) = descriptor_at(payload, index)?;
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
return Err(FspxError::LayoutMismatch {
section_id: id,
offset,
table_end,
});
}
let end = section_end(offset, size, header.table_end, payload.len())
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
for prev in 0..index {
+541 -56
View File
@@ -9,7 +9,10 @@
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
//! [`ParseError::FspxTooManySections`] before any pairwise comparison.
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
//! descriptor whose offset lands inside the header plus descriptor table is
//! [`ParseError::FspxLayoutMismatch`], kept apart from
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
//! code byte range. The code bytes are not decoded. This layout is synthetic.
@@ -26,13 +29,16 @@
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
//! so preparation does not copy it.
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
//! size and stage metadata but does not classify as executable `DXIL`.
//!
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
//! including when an accompanying `FSPX` table is malformed, and logs only an
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
//! is not implemented.
mod c_abi;
mod fspx;
@@ -100,16 +106,49 @@ pub enum ParseError {
BadMagic,
UnsupportedVersion(u32),
TruncatedChunkTable,
ChunkOutOfBounds { index: usize },
ChunkOutOfBounds {
index: usize,
},
TruncatedContainer,
FspxTruncated { chunk: usize },
FspxBadVersion { chunk: usize, version: u32 },
FspxSectionOutOfBounds { chunk: usize, section_id: u32 },
FspxDuplicateSection { chunk: usize, section_id: u32 },
FspxSectionOverlap { chunk: usize, section_id: u32 },
FspxBadStageConfig { chunk: usize },
FspxTooManySections { chunk: usize, count: u32 },
BadDxilHeader { chunk: usize },
FspxTruncated {
chunk: usize,
},
FspxBadVersion {
chunk: usize,
version: u32,
},
FspxSectionOutOfBounds {
chunk: usize,
section_id: u32,
},
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
/// table (`table_end` bytes), which the synthetic layout reserves. The
/// table does not follow BetterXen's clean-room layout; it is not reported
/// as an out-of-bounds section. The container is still rejected.
FspxLayoutMismatch {
chunk: usize,
section_id: u32,
offset: u32,
table_end: u32,
},
FspxDuplicateSection {
chunk: usize,
section_id: u32,
},
FspxSectionOverlap {
chunk: usize,
section_id: u32,
},
FspxBadStageConfig {
chunk: usize,
},
FspxTooManySections {
chunk: usize,
count: u32,
},
BadDxilHeader {
chunk: usize,
},
}
impl fmt::Display for ParseError {
@@ -133,6 +172,15 @@ impl fmt::Display for ParseError {
"FSPX section {section_id} out of bounds in chunk {chunk}"
)
}
Self::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
} => write!(
f,
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
),
Self::FspxDuplicateSection { chunk, section_id } => {
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
}
@@ -185,6 +233,16 @@ fn fspx_error(chunk: usize, err: fspx::FspxError) -> ParseError {
fspx::FspxError::SectionOutOfBounds { section_id } => {
ParseError::FspxSectionOutOfBounds { chunk, section_id }
}
fspx::FspxError::LayoutMismatch {
section_id,
offset,
table_end,
} => ParseError::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
},
fspx::FspxError::DuplicateSection { section_id } => {
ParseError::FspxDuplicateSection { chunk, section_id }
}
@@ -209,14 +267,22 @@ fn record_fspx_stage(
}
}
enum DxilProgram {
Executable((ShaderStage, u8, u8)),
HeaderOnly((ShaderStage, u8, u8)),
}
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
///
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
/// and must be at least 16. `BitcodeSize` must be non-zero, and
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
/// bitcode bytes are not decoded.
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
///
/// A bitcode payload beginning with `NOBC` is a header-only container (for
/// example, reflection or signature metadata with bitcode stripped) and is
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
const PROGRAM_PREFIX: u64 = 8;
const BITCODE_HEADER: u64 = 16;
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
@@ -245,7 +311,16 @@ fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
if end > program_bytes {
return Err(());
}
Ok(program_stage(program_version))
let bitcode_start =
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
let stage = program_stage(program_version);
if bitcode.starts_with(b"NOBC") {
Ok(DxilProgram::HeaderOnly(stage))
} else {
Ok(DxilProgram::Executable(stage))
}
}
struct ContainerLimit {
@@ -352,6 +427,37 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
}
}
#[derive(Default)]
struct DxilChunkState {
has_executable: bool,
size: u32,
executable_stage: Option<(ShaderStage, u8, u8)>,
header_only_stage: Option<(ShaderStage, u8, u8)>,
}
impl DxilChunkState {
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
/// header-only placeholders regardless of chunk order.
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
DxilProgram::Executable(stage) => {
self.has_executable = true;
self.size = size;
self.executable_stage = Some(stage);
}
DxilProgram::HeaderOnly(stage) => {
if !self.has_executable {
self.size = size;
}
if self.header_only_stage.is_none() {
self.header_only_stage = Some(stage);
}
}
}
Ok(())
}
}
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
/// keep chunk or section lists.
pub(crate) struct DxbcSummary {
@@ -370,24 +476,16 @@ pub(crate) struct DxbcSummary {
///
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -408,36 +506,40 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
}
Ok(())
})?;
let (stage, shader_model_major, shader_model_minor) = dxil_stage
let (stage, shader_model_major, shader_model_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(DxbcSummary {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major,
shader_model_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
})
}
/// `Ok(Some(container_size))` when the container is structurally valid and
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no `DXIL` chunk.
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no executable `DXIL` chunk.
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
let mut has_dxil = false;
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
if &fourcc == b"DXIL" {
if read_dxil_program(payload).is_err() {
return Err(ParseError::BadDxilHeader { chunk: index });
match read_dxil_program(payload) {
Ok(DxilProgram::Executable(_)) => has_dxil = true,
Ok(DxilProgram::HeaderOnly(_)) => {}
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
}
has_dxil = true;
}
Ok(())
})?;
@@ -457,27 +559,19 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
/// container through.
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
let mut chunks = Vec::new();
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut accc_is_fspx = false;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let mut fspx = None;
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -515,21 +609,22 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
Ok(())
})?;
let (stage, sm_major, sm_minor) =
dxil_stage
.or(legacy_stage)
.or(fspx_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
let (stage, sm_major, sm_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(ShaderInspection {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major: sm_major,
shader_model_minor: sm_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
accc_is_fspx,
fspx,
@@ -868,9 +963,11 @@ mod tests {
),
(
fspx_header(1, 1, &[(1, 0, 4)], 28),
ParseError::FspxSectionOutOfBounds {
ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 1,
offset: 0,
table_end: 28,
},
),
(
@@ -924,18 +1021,167 @@ mod tests {
#[test]
fn truncated_prefixes_do_not_panic() {
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
nobc_dxil[24..28].copy_from_slice(b"NOBC");
let blobs = [
synthetic_dxil_blob(),
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
vec![0xFF; 64],
];
for blob in blobs {
for len in 0..=blob.len() {
let _ = inspect_dxbc(&blob[..len]);
let _ = summarize_dxbc(&blob[..len]);
let _ = dxil_container_len(&blob[..len]);
}
}
}
/// A two-section table (`table_end` = 16 + 2 * 12 = 40) whose second
/// descriptor's offset is `second_offset`. The first descriptor is a valid
/// 12-byte stage section at 40, and the payload is 64 bytes long.
fn fspx_two_sections(second_offset: u32) -> Vec<u8> {
let mut payload = fspx_header(1, 2, &[(1, 40, 12), (6, second_offset, 4)], 64);
payload[40..44].copy_from_slice(&6u32.to_le_bytes());
payload[44..48].copy_from_slice(&6u32.to_le_bytes());
payload
}
#[test]
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
// Inside the 16-byte header, inside the first descriptor, inside the
// descriptor itself, and the last reserved byte.
for offset in [0u32, 8, 16, 28, 39] {
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
let expected = ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset,
table_end: 40,
};
assert_eq!(
inspect_dxbc(&blob),
Err(expected.clone()),
"offset {offset}"
);
// The C ABI path walks the table through `scan_fspx`, not
// `parse_fspx`, and must classify it the same way.
assert_eq!(
summarize_dxbc(&blob).map(|_| ()),
Err(expected),
"offset {offset}"
);
}
// The first byte after the table is outside the reserved region.
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
assert_eq!(info.kind, ShaderKind::AcccOnly);
assert_eq!(info.stage, ShaderStage::Compute);
assert!(summarize_dxbc(&blob).is_ok());
}
#[test]
fn fspx_layout_mismatch_is_not_out_of_bounds() {
// Past the payload end is still out of bounds, not a layout mismatch.
let mut payload = fspx_two_sections(62);
payload.truncate(64);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let out_of_bounds = ParseError::FspxSectionOutOfBounds {
chunk: 0,
section_id: 6,
};
assert_eq!(inspect_dxbc(&blob), Err(out_of_bounds.clone()));
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(out_of_bounds));
// A reserved offset wins even when the size would also overrun.
let mut payload = fspx_header(1, 1, &[(6, 20, u32::MAX)], 32);
payload.truncate(32);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset: 20,
table_end: 28,
})
);
let message = ParseError::FspxLayoutMismatch {
chunk: 2,
section_id: 6,
offset: 20,
table_end: 28,
}
.to_string();
assert!(message.contains("section 6"), "{message}");
assert!(message.contains("offset 20"), "{message}");
assert!(message.contains("28-byte"), "{message}");
assert!(message.contains("chunk 2"), "{message}");
assert!(!message.contains("out of bounds"), "{message}");
}
#[test]
fn c_abi_still_refuses_fspx_layout_mismatch() {
clear_shader_log();
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]);
let mut c_info = BxShaderInspection {
kind: 99,
..BxShaderInspection::default()
};
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert_eq!(c_info.kind, 0);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn arbitrary_fspx_tables_do_not_panic() {
// Deterministic xorshift so a failure reproduces.
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let mut next = || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for round in 0..4096u32 {
let len = 16 + (next() % 240) as usize;
let mut payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
payload[..4].copy_from_slice(b"FSPX");
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
let count = round % (FSPX_MAX_SECTIONS as u32 + 2);
payload[8..12].copy_from_slice(&count.to_le_bytes());
// Keep some offsets small so the reserved-region branch is hit.
if round % 2 == 0 {
let mut at = 20;
while at + 4 <= len.min(16 + count as usize * 12) {
let small = (next() % 64) as u32;
payload[at..at + 4].copy_from_slice(&small.to_le_bytes());
at += 12;
}
}
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let _ = inspect_dxbc(&blob);
let _ = summarize_dxbc(&blob);
let mut c_info = BxShaderInspection::default();
let _ = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
}
}
#[test]
fn c_abi_inspect_and_passthrough_round_trip() {
clear_shader_log();
@@ -1268,6 +1514,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;
+2
View File
@@ -1,6 +1,8 @@
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
d3d12_xs.cpp
vmem.cpp
proxy.cpp
proxy_generated.cpp
shader_gate.cpp
)
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
+36 -19
View File
@@ -1,8 +1,8 @@
#include "proxy.h"
#include "vmem.h"
#include <cstdio>
#include "bx_xmem_internal.h"
#include <mutex>
/*
* Track C (M1-C1, #414): Xbox Series D3D12 entry points over the host's d3d12.dll
@@ -20,9 +20,12 @@ HMODULE get_host_d3d12() {
return mod;
}
void refresh_trace_flag() {
const bx_runtime_config_t* cfg = bx_get_runtime_config();
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
void initialize_trace_flag() {
static std::once_flag initialized;
std::call_once(initialized, [] {
const bx_runtime_config_t* cfg = bx_get_runtime_config();
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
});
}
} // namespace
@@ -40,7 +43,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
return E_POINTER;
}
*ppv = nullptr;
refresh_trace_flag();
initialize_trace_flag();
using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
HMODULE d3d12 = get_host_d3d12();
@@ -53,12 +56,24 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
}
ID3D12Device* host = nullptr;
HRESULT hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
if (FAILED(hr) || !host) {
char detail[96];
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
return FAILED(hr) ? hr : E_FAIL;
char reuse[8] = {};
/* Test hook. While the backing cache holds a host heap, that heap keeps the host
device alive, and a real runtime then returns the same ID3D12Device. Set the
variable so the next proxy wraps that device even if this host does not. */
const bool reuse_backing = GetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", reuse, sizeof(reuse)) > 0 &&
reuse[0] == '1' && reuse[1] == '\0';
if (reuse_backing) {
host = static_cast<ID3D12Device*>(bx_vmem_addref_backing_host());
}
HRESULT hr = S_OK;
if (!host) {
hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
if (FAILED(hr) || !host) {
char detail[96];
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
return FAILED(hr) ? hr : E_FAIL;
}
}
BxDeviceProxy* proxy = BxDeviceProxy::create(host);
@@ -66,6 +81,10 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
if (!proxy) {
return E_OUTOFMEMORY;
}
if (!bx_vmem_install_device_hooks(proxy)) {
proxy->Release();
return E_FAIL;
}
/* Record how far up the ID3D12DeviceN chain the host goes: QueryInterface on the proxy stops there. */
int highest = 0;
@@ -77,10 +96,10 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
for (int i = 0; i < 10; ++i) {
if (levels[i]) highest = i + 1;
}
char detail[192];
char detail[256];
std::snprintf(detail, sizeof(detail),
"host device wrapped; highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
highest, params ? "non-null" : "null", g_bx_trace_d3d);
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
static_cast<void*>(proxy->h_ID3D12Device), highest, params ? "non-null" : "null", g_bx_trace_d3d);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
hr = proxy->QueryInterface(riid, ppv);
@@ -88,10 +107,8 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
return hr;
}
/* Logged no-op: console startup sequences check SUCCEEDED(hr) before reserving virtual memory. */
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID /*config*/) {
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID config) {
return bx_d3d12_configure_virtual_memory(config);
}
HRESULT WINAPI D3D12SerializeVersionedRootSignature(
+242 -14
View File
@@ -1,8 +1,12 @@
#include "proxy.h"
#include "vmem.h"
#include <cstdio>
#include <cstring>
#include <new>
#include <vector>
#include "shader_gate.h"
/* {6B1D5C0E-2F4A-4E0B-9A57-3C0E5D7B1A42}: private to this DLL, never handed to a host object. */
const GUID IID_BxProxyHost = {0x6b1d5c0e, 0x2f4a, 0x4e0b, {0x9a, 0x57, 0x3c, 0x0e, 0x5d, 0x7b, 0x1a, 0x42}};
@@ -132,9 +136,11 @@ bool log_shader(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTE
well_formed = false;
break;
}
/* ACCC counts too: the shader format gate (#466) decides what happens to it. */
if (std::memcmp(bytes + off, "DXIL", 4) == 0 ||
std::memcmp(bytes + off, "SHEX", 4) == 0 ||
std::memcmp(bytes + off, "SHDR", 4) == 0) {
std::memcmp(bytes + off, "SHDR", 4) == 0 ||
std::memcmp(bytes + off, "ACCC", 4) == 0) {
has_shader_chunk = true;
}
if (i < 16) {
@@ -199,13 +205,43 @@ ULONG STDMETHODCALLTYPE BxDeviceProxy::AddRef() {
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
}
bool BxDeviceProxy::bx_try_acquire_if_nonzero() {
ULONG cur = refs_.load(std::memory_order_acquire);
while (cur != 0) {
if (refs_.compare_exchange_weak(cur, cur + 1, std::memory_order_acq_rel, std::memory_order_acquire)) {
return true;
}
}
return false;
}
bool BxDeviceProxy::bx_try_release_last() {
ULONG expected = 1;
return refs_.compare_exchange_strong(expected, 0, std::memory_order_acq_rel, std::memory_order_acquire);
}
ULONG STDMETHODCALLTYPE BxDeviceProxy::Release() {
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (left == 0) {
bx_release_hosts();
delete this;
/* The 1->0 transition and a weak GetDevice acquire share g_section.
GetDevice adds a reference only when the count is non-zero, so a proxy
at zero is never brought back. Exactly one Release performs final cleanup. */
ULONG cur = refs_.load(std::memory_order_acquire);
for (;;) {
if (cur == 0) {
return 0;
}
if (cur > 1) {
if (refs_.compare_exchange_weak(cur, cur - 1, std::memory_order_acq_rel, std::memory_order_acquire)) {
return cur - 1;
}
continue;
}
if (bx_vmem_final_release(this)) {
bx_release_hosts();
delete this;
return 0;
}
cur = refs_.load(std::memory_order_acquire);
}
return left;
}
HRESULT BxDeviceProxy::wrap_child(IUnknown* host_child, const char* what, REFIID riid, void** ppv) {
@@ -345,7 +381,25 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateGraphicsPipelineState(const D3D12
log_created("graphics pipeline state", E_INVALIDARG);
return E_INVALIDARG;
}
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(desc, riid, ppv);
if (!desc) {
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(desc, riid, ppv);
log_created("graphics pipeline state", hr);
return hr;
}
/* M2 shader format gate (#466): every stage is classified; an ACCC-only stage fails the PSO. */
BxShaderGate gate;
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
HRESULT gated = gate.admit("graphics", "VS", desc->VS, admitted.VS);
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "PS", desc->PS, admitted.PS);
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "DS", desc->DS, admitted.DS);
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "HS", desc->HS, admitted.HS);
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "GS", desc->GS, admitted.GS);
if (FAILED(gated)) {
if (ppv) *ppv = nullptr;
log_created("graphics pipeline state", gated);
return gated;
}
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(&admitted, riid, ppv);
log_created("graphics pipeline state", hr);
return hr;
}
@@ -357,11 +411,147 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateComputePipelineState(const D3D12_
log_created("compute pipeline state", E_INVALIDARG);
return E_INVALIDARG;
}
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(desc, riid, ppv);
if (!desc) {
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(desc, riid, ppv);
log_created("compute pipeline state", hr);
return hr;
}
/* M2 shader format gate (#466): DXIL is passed on, an ACCC-only container is refused. */
BxShaderGate gate;
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
const HRESULT gated = gate.admit("compute", "CS", desc->CS, admitted.CS);
if (FAILED(gated)) {
if (ppv) *ppv = nullptr;
log_created("compute pipeline state", gated);
return gated;
}
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(&admitted, riid, ppv);
log_created("compute pipeline state", hr);
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, &copy[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, &copy[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, &copy[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) {
@@ -369,12 +559,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;
}
+6
View File
@@ -53,6 +53,12 @@ public:
ULONG STDMETHODCALLTYPE AddRef() override;
ULONG STDMETHODCALLTYPE Release() override;
/* Compare-exchange increment. False when the count is already zero.
Weak GetDevice calls this under g_section so a proxy at zero is never resurrected. */
bool bx_try_acquire_if_nonzero();
/* Compare-exchange 1 to 0. Caller holds g_section. True only for the thread that wins. */
bool bx_try_release_last();
HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID riid, void** ppv) override;
HRESULT STDMETHODCALLTYPE CreateCommandQueue1(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID creator_id, REFIID riid, void** ppv) override;
HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** ppv) override;
+4 -4
View File
@@ -175,7 +175,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateHeap(const D3D12_HEAP_DESC * a
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
BX_D3D_TRACE("ID3D12Device", "CreatePlacedResource");
if (!h_ID3D12Device) { BX_VTABLE_STUB_LOG("ID3D12Device", 29u, "CreatePlacedResource"); return E_NOTIMPL; }
return h_ID3D12Device->CreatePlacedResource(a0, a1, a2, a3, a4, a5, a6);
return h_ID3D12Device->CreatePlacedResource(bx_unwrap(a0), a1, a2, a3, a4, a5, a6);
}
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateReservedResource(const D3D12_RESOURCE_DESC * a0, D3D12_RESOURCE_STATES a1, const D3D12_CLEAR_VALUE * a2, REFIID a3, void ** a4) {
@@ -385,7 +385,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource2(const D3D12
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource1(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
BX_D3D_TRACE("ID3D12Device8", "CreatePlacedResource1");
if (!h_ID3D12Device8) { BX_VTABLE_STUB_LOG("ID3D12Device8", 70u, "CreatePlacedResource1"); return E_NOTIMPL; }
return h_ID3D12Device8->CreatePlacedResource1(a0, a1, a2, a3, a4, a5, a6);
return h_ID3D12Device8->CreatePlacedResource1(bx_unwrap(a0), a1, a2, a3, a4, a5, a6);
}
void STDMETHODCALLTYPE BxDeviceProxyGen::CreateSamplerFeedbackUnorderedAccessView(ID3D12Resource * a0, ID3D12Resource * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
@@ -421,7 +421,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource3(const D3D12
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource2(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_BARRIER_LAYOUT a3, const D3D12_CLEAR_VALUE * a4, UINT32 a5, DXGI_FORMAT * a6, REFIID a7, void ** a8) {
BX_D3D_TRACE("ID3D12Device10", "CreatePlacedResource2");
if (!h_ID3D12Device10) { BX_VTABLE_STUB_LOG("ID3D12Device10", 77u, "CreatePlacedResource2"); return E_NOTIMPL; }
return h_ID3D12Device10->CreatePlacedResource2(a0, a1, a2, a3, a4, a5, a6, a7, a8);
return h_ID3D12Device10->CreatePlacedResource2(bx_unwrap(a0), a1, a2, a3, a4, a5, a6, a7, a8);
}
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateReservedResource2(const D3D12_RESOURCE_DESC * a0, D3D12_BARRIER_LAYOUT a1, const D3D12_CLEAR_VALUE * a2, ID3D12ProtectedResourceSession * a3, UINT32 a4, DXGI_FORMAT * a5, REFIID a6, void ** a7) {
@@ -634,7 +634,7 @@ HRESULT STDMETHODCALLTYPE BxCommandQueueProxyGen::SetName(const WCHAR * a0) {
void STDMETHODCALLTYPE BxCommandQueueProxyGen::UpdateTileMappings(ID3D12Resource * a0, UINT a1, const D3D12_TILED_RESOURCE_COORDINATE * a2, const D3D12_TILE_REGION_SIZE * a3, ID3D12Heap * a4, UINT a5, const D3D12_TILE_RANGE_FLAGS * a6, const UINT * a7, const UINT * a8, D3D12_TILE_MAPPING_FLAGS a9) {
BX_D3D_TRACE("ID3D12CommandQueue", "UpdateTileMappings");
if (!h_ID3D12CommandQueue) { BX_VTABLE_STUB_LOG("ID3D12CommandQueue", 8u, "UpdateTileMappings"); return; }
h_ID3D12CommandQueue->UpdateTileMappings(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
h_ID3D12CommandQueue->UpdateTileMappings(a0, a1, a2, a3, bx_unwrap(a4), a5, a6, a7, a8, a9);
}
void STDMETHODCALLTYPE BxCommandQueueProxyGen::CopyTileMappings(ID3D12Resource * a0, const D3D12_TILED_RESOURCE_COORDINATE * a1, ID3D12Resource * a2, const D3D12_TILED_RESOURCE_COORDINATE * a3, const D3D12_TILE_REGION_SIZE * a4, D3D12_TILE_MAPPING_FLAGS a5) {
+302
View File
@@ -0,0 +1,302 @@
#include "shader_gate.h"
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <iterator>
#include "bx_log.h"
#include "bx_shader_bridge.h"
/*
* The bridge is loaded on first use, only by full path from this DLL's own directory, where
* build-shims.sh stages it with the shims (#484). A bare-name load would search the guest EXE's
* directory and PATH first and could pick up a different copy. It is optional at load time, so a
* missing bridge is a logged condition rather than a failure to load d3d12_xs.dll. Without it,
* shaders are not classified, but a container that has an ACCC chunk and no DXIL chunk is still
* refused, from a bounds-checked chunk scan, so it never reaches the host device.
*
* Constraint flags come from two public DXIL container parts, read here with bounds checks:
* - SFI0 is one uint64 of feature flags (DXC DxilContainer.h, DxilShaderFeatureInfo). The bit
* values are D3D_SHADER_FEATURE_* from the public DirectX-Headers d3dcommon.h (MIT):
* WAVE_OPS 0x4000, INT64_OPS 0x8000, ATOMIC_INT64_ON_TYPED_RESOURCE 0x400000,
* ATOMIC_INT64_ON_GROUP_SHARED 0x800000, ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE 0x10000000.
* - PSV0 starts with a uint32 PSVRuntimeInfo size, then PSVRuntimeInfo0, whose 16-byte stage
* union is followed by MinimumExpectedWaveLaneCount and MaximumExpectedWaveLaneCount (DXC
* DxilPipelineStateValidation.h). DXC 1.9.2609 writes 64/64 there for [WaveSize(64)] and
* 0/0xFFFFFFFF without it (checked on the #453 blobs).
* 64-bit atomics on raw buffers set only INT64_OPS, so they cannot be told apart from other
* 64-bit integer use here; see ADR 0008.
*/
namespace {
using InspectFn = bx_shader_status_t (*)(const uint8_t*, size_t, bx_shader_inspection_t*);
using PrepareFn = bx_shader_status_t (*)(const uint8_t*, size_t, uint8_t**, size_t*);
using FreeFn = void (*)(uint8_t*, size_t);
struct Bridge {
InspectFn inspect = nullptr;
PrepareFn prepare = nullptr;
FreeFn release = nullptr;
};
Bridge g_bridge;
INIT_ONCE g_bridge_once = INIT_ONCE_STATIC_INIT;
template <typename Fn>
Fn proc(HMODULE module, const char* name) {
return reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(module, name)));
}
BOOL CALLBACK load_bridge(PINIT_ONCE, PVOID, PVOID*) {
HMODULE self = nullptr;
HMODULE module = nullptr;
wchar_t path[MAX_PATH];
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&load_bridge), &self)) {
const DWORD length = GetModuleFileNameW(self, path, MAX_PATH);
wchar_t* slash = length && length < MAX_PATH ? std::wcsrchr(path, L'\\') : nullptr;
constexpr wchar_t kName[] = L"bx_shader_bridge.dll";
if (slash && static_cast<size_t>(slash + 1 - path) + std::size(kName) <= MAX_PATH) {
std::memcpy(slash + 1, kName, sizeof(kName));
module = LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
}
}
if (module) {
g_bridge.inspect = proc<InspectFn>(module, "bx_shader_inspect");
g_bridge.prepare = proc<PrepareFn>(module, "bx_shader_prepare_for_d3dmetal");
g_bridge.release = proc<FreeFn>(module, "bx_shader_free_buffer");
}
if (!g_bridge.inspect || !g_bridge.prepare || !g_bridge.release) {
g_bridge = {};
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_bridge_missing",
module ? "bx_shader_bridge.dll lacks an entry point; shaders pass unclassified, ACCC-only refused"
: "bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, "
"ACCC-only refused");
}
return TRUE;
}
const Bridge* bridge() {
InitOnceExecuteOnce(&g_bridge_once, load_bridge, nullptr, nullptr);
return g_bridge.inspect ? &g_bridge : nullptr;
}
uint32_t read_u32(const uint8_t* at) {
uint32_t value;
std::memcpy(&value, at, sizeof(value));
return value;
}
/* The payload of the first chunk named `fourcc`, or null. Every read is bounds-checked, so this
* is safe on a container nobody has validated (the no-bridge path relies on that). */
const uint8_t* find_chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
if (len < 32) return nullptr;
const uint32_t count = read_u32(bytes + 28);
for (uint32_t i = 0; i < count && 32 + 4 * static_cast<size_t>(i) + 4 <= len; ++i) {
const uint32_t offset = read_u32(bytes + 32 + 4 * static_cast<size_t>(i));
if (offset > len || len - offset < 8) continue;
if (std::memcmp(bytes + offset, fourcc, 4) != 0) continue;
const uint32_t chunk = read_u32(bytes + offset + 4);
if (chunk > len - offset - 8) return nullptr;
*size = chunk;
return bytes + offset + 8;
}
return nullptr;
}
/* True when any chunk header in the table is tagged `fourcc`, whatever its declared size. */
bool has_chunk_tag(const uint8_t* bytes, size_t len, const char* fourcc) {
if (len < 32) return false;
const uint32_t count = read_u32(bytes + 28);
for (uint32_t i = 0; i < count && 32 + 4 * static_cast<size_t>(i) + 4 <= len; ++i) {
const uint32_t offset = read_u32(bytes + 32 + 4 * static_cast<size_t>(i));
if (offset <= len && len - offset >= 4 && std::memcmp(bytes + offset, fourcc, 4) == 0) return true;
}
return false;
}
struct Constraints {
bool has_flags = false;
uint64_t flags = 0;
bool has_lanes = false;
uint32_t lanes_min = 0;
uint32_t lanes_max = 0;
};
Constraints read_constraints(const uint8_t* bytes, size_t len) {
Constraints c;
uint32_t size = 0;
if (const uint8_t* sfi0 = find_chunk(bytes, len, "SFI0", &size); sfi0 && size >= 8) {
std::memcpy(&c.flags, sfi0, sizeof(c.flags));
c.has_flags = true;
}
if (const uint8_t* psv0 = find_chunk(bytes, len, "PSV0", &size); psv0 && size >= 4) {
const uint32_t info_size = read_u32(psv0);
if (info_size >= 24 && size >= 4u + 24u) {
c.lanes_min = read_u32(psv0 + 4 + 16);
c.lanes_max = read_u32(psv0 + 4 + 20);
c.has_lanes = true;
}
}
return c;
}
constexpr uint64_t kWaveOps = 0x4000;
constexpr uint64_t kInt64Ops = 0x8000;
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) {
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";
case BX_SHADER_DXBC_LEGACY: return "legacy_dxbc";
case BX_SHADER_DXBC_ACCC: return "accc_only";
case BX_SHADER_DXBC_DUAL: return "dual";
default: return "unknown";
}
}
void log_gate(const char* pso_kind, const char* stage, size_t len, const bx_shader_inspection_t* info,
const Constraints* c, const char* decision, HRESULT hr) {
char lanes[32] = "none";
if (c && c->has_lanes) {
std::snprintf(lanes, sizeof(lanes), "%lu-%lu", static_cast<unsigned long>(c->lanes_min),
static_cast<unsigned long>(c->lanes_max));
}
char detail[400];
if (info) {
std::snprintf(detail, sizeof(detail),
"pso=%s stage=%s decision=%s hr=0x%08lx kind=%s shader_stage=%d sm=%lu.%lu bytes=%llu "
"dxil=%lu accc=%lu sfi0=0x%llx wave_ops=%d int64_ops=%d atomic64=%s%s%s wave_lanes=%s",
pso_kind, stage, decision, static_cast<unsigned long>(hr), kind_name(info->kind),
static_cast<int>(info->stage), static_cast<unsigned long>(info->shader_model_major),
static_cast<unsigned long>(info->shader_model_minor), static_cast<unsigned long long>(len),
static_cast<unsigned long>(info->dxil_chunk_size),
static_cast<unsigned long>(info->accc_chunk_size),
static_cast<unsigned long long>(c ? c->flags : 0), c && (c->flags & kWaveOps) ? 1 : 0,
c && (c->flags & kInt64Ops) ? 1 : 0,
c && (c->flags & kAtomic64Typed) ? "typed," : "",
c && (c->flags & kAtomic64GroupShared) ? "groupshared," : "",
c && (c->flags & kAtomic64Heap) ? "heap," : "", lanes);
} else {
std::snprintf(detail, sizeof(detail), "pso=%s stage=%s decision=%s hr=0x%08lx bytes=%llu", pso_kind, stage,
decision, static_cast<unsigned long>(hr), static_cast<unsigned long long>(len));
}
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "shader_gate", detail);
}
} // namespace
BxShaderGate::~BxShaderGate() {
const Bridge* b = copy_count_ ? bridge() : nullptr;
for (size_t i = 0; i < copy_count_; ++i) {
if (b) b->release(copies_[i], copy_sizes_[i]);
}
}
HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
D3D12_SHADER_BYTECODE& out) {
out = in;
if (!in.pShaderBytecode || in.BytecodeLength == 0) return S_OK;
const auto* bytes = static_cast<const uint8_t*>(in.pShaderBytecode);
const size_t len = in.BytecodeLength;
const Bridge* b = bridge();
if (!b) {
/* No classifier: still keep ACCC-only containers away from the host (#478 review). */
/* Any ACCC tag counts; only a DXIL chunk that fits counts as DXIL, so doubt refuses. */
uint32_t size = 0;
const bool dxbc = len >= 4 && std::memcmp(bytes, "DXBC", 4) == 0;
if (dxbc && has_chunk_tag(bytes, len, "ACCC") && !find_chunk(bytes, len, "DXIL", &size)) {
log_gate(pso_kind, stage, len, nullptr, nullptr, "reject_accc_only_unclassified", E_NOTIMPL);
return E_NOTIMPL;
}
log_gate(pso_kind, stage, len, nullptr, nullptr, "pass_unclassified", S_OK);
return S_OK;
}
bx_shader_inspection_t info{};
if (b->inspect(bytes, len, &info) != BX_SHADER_OK) {
/* Not a container the bridge understands; the host keeps its own validation. */
log_gate(pso_kind, stage, len, nullptr, nullptr, "pass_uninspected", S_OK);
return S_OK;
}
const Constraints constraints = read_constraints(bytes, len);
switch (info.kind) {
case BX_SHADER_DXBC_ACCC:
log_gate(pso_kind, stage, len, &info, &constraints, "reject_accc_only", E_NOTIMPL);
return E_NOTIMPL;
case BX_SHADER_DXBC_DXIL:
case BX_SHADER_DXBC_DUAL: {
if (copy_count_ == kMaxCopies) {
log_gate(pso_kind, stage, len, &info, &constraints, "copy_limit", E_UNEXPECTED);
return E_UNEXPECTED;
}
uint8_t* copy = nullptr;
size_t copy_len = 0;
const bx_shader_status_t status = b->prepare(bytes, len, &copy, &copy_len);
if (status != BX_SHADER_OK) {
const HRESULT hr = status == BX_SHADER_ERR_OOM ? E_OUTOFMEMORY : E_INVALIDARG;
log_gate(pso_kind, stage, len, &info, &constraints, "prepare_failed", hr);
return hr;
}
copies_[copy_count_] = copy;
copy_sizes_[copy_count_] = copy_len;
++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];
std::snprintf(detail, sizeof(detail),
"pso=%s stage=%s wave_lanes_min=%lu atomic64_flags=0x%llx: D3DMetal creates such "
"pipelines but does not run them (#453)",
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 S_OK;
}
default:
log_gate(pso_kind, stage, len, &info, &constraints, "pass_original", S_OK);
return S_OK;
}
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
/*
* M2 Shader Format Gate (#466): classifies every shader handed to Create*PipelineState through
* bx_shader_bridge.dll (abi/include/bx_shader_bridge.h, the Windows build of dxbc-accc, #445)
* and decides what the host device receives. See docs/adr/0008-m2-shader-format-gate.md.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstddef>
#include <cstdint>
class BxShaderGate {
public:
BxShaderGate() = default;
~BxShaderGate();
BxShaderGate(const BxShaderGate&) = delete;
BxShaderGate& operator=(const BxShaderGate&) = delete;
/*
* Logs one stage's classification (`shader_gate` event) and sets `out` to the bytecode the
* host gets: the bridge's prepared DXIL copy for DXIL and dual containers, or `in` unchanged
* for legacy DXBC, unclassifiable input, or when the bridge is missing (logged once as
* `shader_bridge_missing`). Returns E_NOTIMPL for an ACCC-only container, which has no
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge. Copies live until this
* object is destroyed.
*/
HRESULT admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
D3D12_SHADER_BYTECODE& out);
private:
static constexpr size_t kMaxCopies = 5; /* VS, PS, DS, HS, GS */
uint8_t* copies_[kMaxCopies] = {};
size_t copy_sizes_[kMaxCopies] = {};
size_t copy_count_ = 0;
};
+4 -1
View File
@@ -44,8 +44,11 @@ PROXIES = {
# Interfaces that carry no host pointer of their own: their methods forward through the root level.
ABSTRACT = {"IUnknown", "ID3D12Object", "ID3D12DeviceChild", "ID3D12Pageable", "ID3D12CommandList"}
# A single-pointer parameter of one of these types may be one of our proxies and is unwrapped.
# ID3D12Heap covers CreatePlacedResource, CreatePlacedResource1 and CreatePlacedResource2.
# A wrapped heap passed straight through faults in the host (0xc0000005 on D3DMetal).
MAYBE_PROXY = {"ID3D12CommandQueue", "ID3D12CommandAllocator", "ID3D12CommandList",
"ID3D12GraphicsCommandList", "ID3D12Pageable", "ID3D12DeviceChild", "ID3D12Object"}
"ID3D12GraphicsCommandList", "ID3D12Pageable", "ID3D12DeviceChild", "ID3D12Object",
"ID3D12Heap", "ID3D12Heap1"}
IUNKNOWN = [
("HRESULT", "QueryInterface", [("REFIID", ""), ("void **", "")]),
+876
View File
@@ -0,0 +1,876 @@
#include "proxy.h"
#include "vmem.h"
#include "bx_xmem_internal.h"
#include <cstdio>
#include <cstring>
#include <new>
/*
* The configured region is backed by one CUSTOM WRITE_BACK / L0 heap and a buffer
* that stays mapped. That heap is created with D3D12_HEAP_FLAG_NONE, 64 KiB
* alignment, and node masks 0. CreateHeap returns it only for the explicit
* opt-in desc documented in vmem.h. In #473, CPU and GPU reads agreed after
* a fence on tested L0 heaps. Both OpenExistingHeap methods returned E_NOTIMPL.
* This file does not request L1 and does not treat an xmem address as a GPU pointer.
*
* Any other CreateHeap forwards the caller's D3D12_HEAP_DESC unmodified.
* The wrapper charges the heap on create and credits it on final Release.
* Resources created by CreatePlacedResource retain the wrapper.
* GetDevice on every wrapper returns the BxDeviceProxy. An ordinary heap AddRefs
* that proxy and Releases it after the wrapper is destroyed, matching
* BxChildProxy, so the caller may release the device and keep the heap.
* The cached backing heap does not AddRef: this record would keep the device
* and its budget charge alive. That pointer is weak. It is cleared when the
* proxy is destroyed and set to the proxy that next receives the cached heap.
* The cache is keyed by the host ID3D12Device and is released when that device
* changes.
* A null out pointer is forwarded unchanged to the host.
* vkd3d on CrossOver 26.2 faults on that pointer with or without this shim.
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createheap
*
* CreatePlacedResource forwards the caller's parameters to the host.
* On the backing heap the offset must be a multiple of the alignment
* GetResourceAllocationInfo reports, the resource
* must fit, and an upload or readback heap (not this CUSTOM heap) must use the
* initial state Microsoft Learn requires:
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getresourceallocationinfo
* Heap alignment values 0, 64 KiB and 4 MiB, and ID3D12Heap1:
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_desc
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12heap1
* Non-custom heap properties use UNKNOWN CPU page and memory pool:
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_properties
*/
namespace {
constexpr uint64_t k64K = 64ull * 1024ull;
constexpr uint32_t kConfigVersion = 1;
constexpr GUID kPlacedResourceHeap = {0x3a652cbb, 0xb5b3, 0x4e09, {0xb3, 0x6c, 0xc0, 0x2c, 0xa9, 0x83, 0xae, 0x1a}};
struct Record {
bool configured = false;
bool backing_opt_in = false;
bx_hardware_profile_t profile = BX_PROFILE_LOCKHART;
uint64_t title_limit = 0;
bool have_region = false;
uint64_t config_base = 0;
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. */
uint64_t charged_private_bytes = 0;
uint64_t cpu_pointer = 0;
class BxChargedHeap* backing = nullptr;
ID3D12Resource* backing_buffer = nullptr;
/* Host device that created `backing`. Not an owning reference. A later
CreateHeap whose host device pointer differs releases the cache. */
ID3D12Device* backing_host = nullptr;
};
struct Section {
CRITICAL_SECTION cs;
Section() { InitializeCriticalSection(&cs); }
~Section() { DeleteCriticalSection(&cs); }
};
Section g_section;
Record g_record;
struct Guard {
explicit Guard(Section& section) : section(section) { EnterCriticalSection(&section.cs); }
~Guard() { LeaveCriticalSection(&section.cs); }
Section& section;
};
uint64_t title_limit() {
const bx_runtime_config_t* cfg = bx_get_runtime_config();
if (cfg && cfg->title_memory_limit_bytes) {
return cfg->title_memory_limit_bytes;
}
/* Same 8 GiB Lockhart default bx_runtime_veh stores when no profile is set. */
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. */
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) {
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;
return true;
}
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;
return;
}
g_record.charged_private_bytes -= bytes;
}
/*
* Holds the budget charge for one private host heap and drops it on the last Release.
* QueryInterface for ID3D12Heap, and for ID3D12Heap1 when the host heap answers it,
* returns this object. bx_unwrap sees IID_BxProxyHost and receives the host heap.
* GetProtectedResourceSession forwards to the host ID3D12Heap1.
* GetDevice returns the BxDeviceProxy, matching BxChildProxy::GetDevice.
* Ordinary heaps (`owns_device_`) AddRef the proxy in the constructor and
* Release it after `delete this`, the same order as BxChildProxy::Release.
* The process-wide backing heap does not. g_record holds that heap for the
* life of the region, so a strong reference would pin the device and the
* budget charge after the caller dropped the proxy. `device_` on that heap is
* weak. It is cleared when the heap leaves the cache and when its proxy's
* reference count goes from 1 to 0. hand_out_backing_locked points it at the
* proxy that receives the cache. Those writes happen under g_section, together
* with the 1->0 transition, so GetDevice cannot resurrect a proxy at zero.
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12heap1
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12devicechild-getdevice
*/
class BxChargedHeap final : public ID3D12Heap1 {
public:
static BxChargedHeap* create(ID3D12Heap* host, ID3D12Heap1* host1, uint64_t bytes, BxDeviceProxy* device,
bool own_device) {
return new (std::nothrow) BxChargedHeap(host, host1, bytes, device, own_device);
}
/* Weak backing heap only. Called under g_section. */
void set_device(BxDeviceProxy* device) {
if (!owns_device_) {
device_ = device;
}
}
BxDeviceProxy* device() const { return device_; }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
if (!ppv) {
return E_POINTER;
}
*ppv = nullptr;
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12Heap)) {
*ppv = static_cast<ID3D12Heap*>(this);
AddRef();
return S_OK;
}
if (riid == __uuidof(ID3D12Heap1)) {
if (!host1_) {
return E_NOINTERFACE;
}
*ppv = static_cast<ID3D12Heap1*>(this);
AddRef();
return S_OK;
}
if (riid == IID_BxProxyHost) {
*ppv = host_;
return S_OK;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override { return InterlockedIncrement(&refs_); }
ULONG STDMETHODCALLTYPE Release() override {
const ULONG left = InterlockedDecrement(&refs_);
if (left == 0) {
/* Final Release of a live heap. D3DMetal may pool the pages after this,
so the budget credit is the live-heap count, not a physical-memory drop. */
if (host1_) {
host1_->Release();
}
if (host_) {
host_->Release();
}
release_charge(bytes_);
/* Same order as BxChildProxy::Release: destroy the wrapper, then Release the device. */
BxDeviceProxy* owned = owns_device_ ? device_ : nullptr;
device_ = nullptr;
delete this;
if (owned) {
owned->Release();
}
}
return left;
}
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override {
return host_->GetPrivateData(guid, size, data);
}
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override {
return host_->SetPrivateData(guid, size, data);
}
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* data) override {
return host_->SetPrivateDataInterface(guid, data);
}
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { return host_->SetName(name); }
HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override {
BX_D3D_TRACE("ID3D12DeviceChild", "GetDevice");
if (!ppv) {
return E_POINTER;
}
/* The proxy, never the host device.
An ordinary heap owns its proxy and nothing else writes device_, so that
path stays lock-free. The backing heap is weak. Its acquire and the
proxy's 1->0 Release share g_section. The acquire is a compare-exchange
that refuses zero, so it cannot resurrect a proxy that Release has
already claimed. QueryInterface below adds one more reference from a
non-zero count and does not enter g_section; the compare-exchange
reference is then dropped. Guard's critical section is recursive, and
this path does not re-enter it. */
if (owns_device_) {
if (!device_) {
*ppv = nullptr;
return E_FAIL;
}
return device_->QueryInterface(riid, ppv);
}
BxDeviceProxy* proxy = nullptr;
{
Guard guard(g_section);
proxy = device_;
if (!proxy || !proxy->bx_try_acquire_if_nonzero()) {
*ppv = nullptr;
return E_FAIL;
}
}
/* The compare-exchange reference keeps the proxy alive. QueryInterface
adds the caller's reference from a non-zero count, then the
compare-exchange reference is dropped. Release is outside g_section
so a 1->0 transition cannot try to take that lock on this thread. */
const HRESULT hr = proxy->QueryInterface(riid, ppv);
proxy->Release();
return hr;
}
D3D12_HEAP_DESC* STDMETHODCALLTYPE GetDesc(D3D12_HEAP_DESC* ret) override { return host_->GetDesc(ret); }
HRESULT STDMETHODCALLTYPE GetProtectedResourceSession(REFIID riid, void** session) override {
if (!session) {
return E_POINTER;
}
*session = nullptr;
if (!host1_) {
return E_NOINTERFACE;
}
return host1_->GetProtectedResourceSession(riid, session);
}
private:
BxChargedHeap(ID3D12Heap* host, ID3D12Heap1* host1, uint64_t bytes, BxDeviceProxy* device, bool own_device)
: host_(host), host1_(host1), bytes_(bytes), device_(device), owns_device_(own_device) {
if (host_) {
host_->AddRef();
}
if (host1_) {
host1_->AddRef();
}
if (owns_device_ && device_) {
device_->AddRef();
}
}
~BxChargedHeap() = default;
ID3D12Heap* host_;
ID3D12Heap1* host1_;
uint64_t bytes_;
BxDeviceProxy* device_;
bool owns_device_; /* ordinary heap: strong, like BxChildProxy. Backing cache: weak. */
LONG refs_ = 1;
};
struct RegionSnap {
bool eligible = false;
uint64_t base = 0;
uint64_t size = 0;
uint64_t generation = 0;
};
RegionSnap region_snap() {
Guard guard(g_section);
RegionSnap snap;
snap.eligible = g_record.configured && g_record.backing_opt_in && g_record.have_region && g_record.config_size != 0;
snap.base = g_record.region.base_va;
snap.size = g_record.config_size;
snap.generation = g_record.config_generation;
return snap;
}
bool region_still_mapped(const RegionSnap& snap) {
if (!snap.eligible || snap.size == 0) {
return false;
}
bx_xmem_region_info_t live{};
if (!bx_xmem_query_region(snap.base, &live) || live.base_va != snap.base || live.size_bytes == 0 ||
snap.size % live.size_bytes != 0) {
return false;
}
const uint64_t page = live.size_bytes;
for (uint64_t offset = 0; offset < snap.size; offset += page) {
bx_xmem_region_info_t part{};
if (!bx_xmem_query_region(snap.base + offset, &part) || part.base_va != snap.base + offset ||
part.size_bytes != page) {
return false;
}
}
return true;
}
/* True only for the explicit backing-heap request documented in vmem.h. */
bool backing_request(const D3D12_HEAP_DESC* desc, RegionSnap& snap) {
if (!desc) {
return false;
}
if (desc->Properties.Type != D3D12_HEAP_TYPE_CUSTOM ||
desc->Properties.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_WRITE_BACK ||
desc->Properties.MemoryPoolPreference != D3D12_MEMORY_POOL_L0) {
return false;
}
if (desc->Alignment != 0 && desc->Alignment != k64K) {
return false;
}
if (desc->Flags != D3D12_HEAP_FLAG_NONE) {
return false;
}
if (desc->Properties.CreationNodeMask > 1 || desc->Properties.VisibleNodeMask > 1) {
return false;
}
snap = region_snap();
if (!snap.eligible || desc->SizeInBytes != snap.size) {
return false;
}
return region_still_mapped(snap);
}
HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out, bool own_device);
/* Test hook. One CreateHeap treats the cached host as foreign even when the
runtime returns the same ID3D12Device, so the replacement path can be checked
on a machine that keeps a single host device alive. */
bool force_backing_replace() {
char buf[8] = {};
return GetEnvironmentVariableA("BX_D3D12_FORCE_BACKING_REPLACE", buf, sizeof(buf)) > 0 && buf[0] == '1' &&
buf[1] == '\0';
}
/* Caller holds g_section. */
bool cache_matches_locked(ID3D12Device* host, uint64_t bytes) {
if (force_backing_replace()) {
return false;
}
return g_record.backing && g_record.backing_host == host && g_record.configured && g_record.backing_opt_in &&
g_record.have_region && g_record.config_size == bytes;
}
/* Caller holds g_section. A heap that leaves the cache loses its weak proxy
pointer before the cache drops it, so a caller who still holds the heap
gets E_FAIL from GetDevice instead of a freed proxy. */
void take_cached_heap_locked(BxChargedHeap** heap, ID3D12Resource** buffer) {
*heap = g_record.backing;
*buffer = g_record.backing_buffer;
if (*heap) {
(*heap)->set_device(nullptr);
}
g_record.backing = nullptr;
g_record.backing_buffer = nullptr;
g_record.backing_host = nullptr;
g_record.cpu_pointer = 0;
}
/* Caller holds g_section. Host and size were just checked. Retarget and take
the caller's reference before the lock is released. */
HRESULT hand_out_backing_locked(BxDeviceProxy* self, REFIID riid, void** out) {
g_record.backing->set_device(self);
g_record.backing->AddRef();
const HRESULT hr = g_record.backing->QueryInterface(riid, out);
g_record.backing->Release();
return hr;
}
void release_backing_pair(BxChargedHeap* heap, ID3D12Resource* buffer) {
if (buffer) {
buffer->Unmap(0, nullptr);
buffer->Release();
}
if (heap) {
heap->Release();
}
}
HRESULT ensure_backing(BxDeviceProxy* self, const RegionSnap& snap, REFIID riid, void** out) {
const uint64_t bytes = snap.size;
BxChargedHeap* stale_heap = nullptr;
ID3D12Resource* stale_buffer = nullptr;
{
/* One section covers the host and config check, the heap choice, and the
reference handed to the caller. A second device cannot swap the cache
in the middle of that. */
Guard guard(g_section);
if (snap.generation != g_record.config_generation) {
return HRESULT_FROM_WIN32(ERROR_RETRY);
}
if (cache_matches_locked(self->h_ID3D12Device, bytes)) {
return hand_out_backing_locked(self, riid, out);
}
if (g_record.backing) {
take_cached_heap_locked(&stale_heap, &stale_buffer);
}
}
release_backing_pair(stale_heap, stale_buffer);
stale_heap = nullptr;
stale_buffer = nullptr;
D3D12_HEAP_DESC desc = {};
desc.SizeInBytes = bytes;
desc.Alignment = k64K;
desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
desc.Flags = D3D12_HEAP_FLAG_NONE;
void* created = nullptr;
HRESULT hr = host_private_heap(self, &desc, __uuidof(ID3D12Heap), &created, false);
if (FAILED(hr) || !created) {
return FAILED(hr) ? hr : E_FAIL;
}
auto* wrap = static_cast<BxChargedHeap*>(created);
ID3D12Heap* host_heap = bx_unwrap(wrap);
D3D12_RESOURCE_DESC buffer = {};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = bytes;
buffer.Height = 1;
buffer.DepthOrArraySize = 1;
buffer.MipLevels = 1;
buffer.Format = DXGI_FORMAT_UNKNOWN;
buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* resource = nullptr;
hr = self->h_ID3D12Device->CreatePlacedResource(host_heap, 0, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
if (FAILED(hr) || !resource) {
wrap->Release();
return FAILED(hr) ? hr : E_FAIL;
}
void* mapped = nullptr;
hr = resource->Map(0, nullptr, &mapped);
if (FAILED(hr) || !mapped) {
resource->Release();
wrap->Release();
return FAILED(hr) ? hr : E_FAIL;
}
HRESULT published = E_FAIL;
bool keep_new = false;
{
/* The host allocation may have raced with a config change or another
creator. Publish only for the configuration this request validated. */
Guard guard(g_section);
if (snap.generation != g_record.config_generation) {
published = HRESULT_FROM_WIN32(ERROR_RETRY);
} else if (cache_matches_locked(self->h_ID3D12Device, bytes)) {
published = hand_out_backing_locked(self, riid, out);
} else {
if (g_record.backing) {
take_cached_heap_locked(&stale_heap, &stale_buffer);
}
keep_new = true;
g_record.backing = wrap;
g_record.backing_buffer = resource;
g_record.backing_host = self->h_ID3D12Device;
/* Remember the map. The caller's config block is not stored and is not written here. */
g_record.cpu_pointer = reinterpret_cast<uint64_t>(mapped);
published = hand_out_backing_locked(self, riid, out);
}
}
if (!keep_new) {
release_backing_pair(wrap, resource);
}
release_backing_pair(stale_heap, stale_buffer);
return published;
}
HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out, bool own_device) {
/* desc is forwarded unmodified. The charge follows the wrapper, including ID3D12Heap1. */
if (!try_charge(desc->SizeInBytes)) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "heap_budget",
"CreateHeap exceeds the Lockhart/Anaconda xmem title budget");
return E_OUTOFMEMORY;
}
void* raw = nullptr;
HRESULT hr = self->h_ID3D12Device->CreateHeap(desc, riid, &raw);
if (FAILED(hr) || !raw) {
release_charge(desc->SizeInBytes);
return FAILED(hr) ? hr : E_FAIL;
}
auto* unknown = static_cast<IUnknown*>(raw);
ID3D12Heap* host = nullptr;
const HRESULT heap_hr = unknown->QueryInterface(__uuidof(ID3D12Heap), reinterpret_cast<void**>(&host));
if (FAILED(heap_hr) || !host) {
unknown->Release();
release_charge(desc->SizeInBytes);
return FAILED(heap_hr) ? heap_hr : E_NOINTERFACE;
}
ID3D12Heap1* host1 = nullptr;
void* probed = nullptr;
if (host->QueryInterface(__uuidof(ID3D12Heap1), &probed) == S_OK && probed) {
host1 = static_cast<ID3D12Heap1*>(probed);
}
BxChargedHeap* wrap = BxChargedHeap::create(host, host1, desc->SizeInBytes, self, own_device);
if (host1) {
host1->Release();
}
host->Release();
unknown->Release();
if (!wrap) {
release_charge(desc->SizeInBytes);
return E_OUTOFMEMORY;
}
hr = wrap->QueryInterface(riid, out);
wrap->Release();
if (FAILED(hr) && out) {
*out = nullptr;
}
return hr;
}
bool is_backing_heap(ID3D12Heap* heap) {
if (!heap) {
return false;
}
BxChargedHeap* backing = nullptr;
{
Guard guard(g_section);
backing = g_record.backing;
if (!backing) {
return false;
}
backing->AddRef();
}
IUnknown* want = nullptr;
IUnknown* got = nullptr;
const HRESULT want_hr = backing->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&want));
const HRESULT got_hr = heap->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&got));
const bool same = SUCCEEDED(want_hr) && SUCCEEDED(got_hr) && want == got;
if (want) {
want->Release();
}
if (got) {
got->Release();
}
backing->Release();
return same;
}
void log_placed(UINT64 offset, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "CreatePlacedResource offset=%llu hr=0x%08lx",
static_cast<unsigned long long>(offset), static_cast<unsigned long>(hr));
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail);
}
HRESULT STDMETHODCALLTYPE create_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out) {
BX_D3D_TRACE("ID3D12Device", "CreateHeap");
if (!self || !self->h_ID3D12Device) {
if (out) {
*out = nullptr;
}
BX_VTABLE_STUB_LOG("ID3D12Device", 28u, "CreateHeap");
return E_NOTIMPL;
}
if (!desc) {
if (out) {
*out = nullptr;
}
return E_INVALIDARG;
}
if (!out) {
/* A null out pointer is forwarded unchanged to the host.
* vkd3d on CrossOver 26.2 faults on that pointer with or without this shim.
*/
return self->h_ID3D12Device->CreateHeap(desc, riid, nullptr);
}
*out = nullptr;
RegionSnap snap;
if (backing_request(desc, snap)) {
return ensure_backing(self, snap, riid, out);
}
return host_private_heap(self, desc, riid, out, true);
}
HRESULT validate_backing_placement(ID3D12Device* device, ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) {
if (!heap || !desc) {
return E_INVALIDARG;
}
if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && clear) {
return E_INVALIDARG;
}
D3D12_HEAP_DESC heap_desc = heap->GetDesc();
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && state != D3D12_RESOURCE_STATE_GENERIC_READ) {
return E_INVALIDARG;
}
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_READBACK && state != D3D12_RESOURCE_STATE_COPY_DEST) {
return E_INVALIDARG;
}
D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, desc);
if (info.SizeInBytes == 0 || info.SizeInBytes == ~0ull) {
return E_INVALIDARG;
}
if (info.Alignment != 0 && (offset % info.Alignment) != 0) {
return E_INVALIDARG;
}
if (offset > heap_desc.SizeInBytes || info.SizeInBytes > heap_desc.SizeInBytes - offset) {
return E_INVALIDARG;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, UINT64 offset,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
BX_D3D_TRACE("ID3D12Device", "CreatePlacedResource");
if (!self || !self->h_ID3D12Device) {
if (out) {
*out = nullptr;
}
BX_VTABLE_STUB_LOG("ID3D12Device", 29u, "CreatePlacedResource");
return E_NOTIMPL;
}
if (out) {
*out = nullptr;
}
if (is_backing_heap(heap)) {
const HRESULT check_hr = validate_backing_placement(self->h_ID3D12Device, heap, offset, desc, state, clear);
if (FAILED(check_hr)) {
log_placed(offset, check_hr);
return check_hr;
}
}
ID3D12Heap* host_heap = bx_unwrap(heap);
HRESULT hr = self->h_ID3D12Device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out);
if (SUCCEEDED(hr) && out && *out && host_heap != heap) {
/* The resource owns a reference to the shim heap through its host
object's private data, including across QueryInterface calls. */
auto* created = static_cast<IUnknown*>(*out);
ID3D12Object* object = nullptr;
HRESULT retain_hr = created->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast<void**>(&object));
if (SUCCEEDED(retain_hr)) {
retain_hr = object->SetPrivateDataInterface(kPlacedResourceHeap, heap);
object->Release();
}
if (FAILED(retain_hr)) {
created->Release();
*out = nullptr;
hr = retain_hr;
}
}
log_placed(offset, hr);
return hr;
}
struct ConfigHeader {
uint32_t magic;
uint32_t struct_size;
};
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));
}
} // 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;
}
/*
* 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;
}
BxD3d12VirtualMemoryConfig in{};
std::memcpy(&in, config, sizeof(in));
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. */
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)) {
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) {
return E_INVALIDARG;
}
bx_xmem_region_info_t region{};
bool have_region = false;
if (in.base_va != 0) {
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) {
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) {
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) {
return E_INVALIDARG;
}
}
region = first;
region.size_bytes = span;
have_region = true;
}
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;
{
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);
}
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();
}
uint64_t charged = 0;
{
Guard guard(g_section);
charged = g_record.charged_private_bytes;
}
char detail[384];
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",
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),
static_cast<unsigned long long>(have_region ? region.size_bytes : 0),
static_cast<unsigned long long>(charged));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12ConfigureVirtualMemoryX", detail);
return S_OK;
}
bool bx_vmem_final_release(void* device_proxy) {
Guard guard(g_section);
auto* proxy = static_cast<BxDeviceProxy*>(device_proxy);
if (!proxy->bx_try_release_last()) {
return false;
}
/* The only weak pointer is the cached backing heap. Heaps that already left
the cache were cleared in take_cached_heap_locked. */
if (g_record.backing && g_record.backing->device() == proxy) {
g_record.backing->set_device(nullptr);
}
return true;
}
void* bx_vmem_addref_backing_host() {
Guard guard(g_section);
if (!g_record.backing_host) {
return nullptr;
}
g_record.backing_host->AddRef();
return g_record.backing_host;
}
bool bx_vmem_install_device_hooks(void* device) {
/*
* CreateHeap is slot 28 and CreatePlacedResource is slot 29 on ID3D12Device.
* BxDeviceProxy inherits both methods from the generated forwarders.
* The proxy vtable is shared static data: every BxDeviceProxy instance points at
* the same function table. Patching it once covers every device this DLL creates.
* That table is in a read-only section, so VirtualProtect opens the two slots for
* the store and then puts the previous protection back.
* No other hook in this DLL replaces those methods without editing the proxy sources.
*/
/* No caller may publish a proxy until both shared slots are ready. */
static bool installed = false;
Guard guard(g_section);
if (installed) {
return true;
}
auto* proxy = static_cast<BxDeviceProxy*>(device);
void** vtable = *reinterpret_cast<void***>(proxy);
DWORD old = 0;
if (!VirtualProtect(vtable + 28, sizeof(void*) * 2, PAGE_READWRITE, &old)) {
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "vmem_hook", "VirtualProtect on the device vtable failed");
BX_VTABLE_STUB_LOG("ID3D12Device", 28u, "CreateHeap");
return false;
}
vtable[28] = reinterpret_cast<void*>(&create_heap);
vtable[29] = reinterpret_cast<void*>(&create_placed);
DWORD ignored = 0;
VirtualProtect(vtable + 28, sizeof(void*) * 2, old, &ignored);
installed = true;
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "vmem_hook", "CreateHeap and CreatePlacedResource installed");
return true;
}
+106
View File
@@ -0,0 +1,106 @@
#ifndef BETTERXEN_D3D12_XS_VMEM_H
#define BETTERXEN_D3D12_XS_VMEM_H
#include <stddef.h>
#include <stdint.h>
#include <windows.h>
/*
* 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.
*
* 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.
*
* 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.
*
* The call copies what it needs. The caller's pointer is not kept. cpu_pointer
* is written only before this call returns: the persistent Map address of the
* WRITE_BACK buffer if that backing heap already exists, otherwise 0. CreateHeap
* does not write the block. A caller that needs the address after the backing
* heap has been created calls D3D12ConfigureVirtualMemoryX again with the same
* region (same base_va and size). That second call does not reset or recreate
* the backing heap. It writes the current map into the new block. A nonzero
* cpu_pointer is valid only while that backing buffer remains cached. Changing
* the region or replacing the cache for another host device unmaps it, even if
* the caller retains the heap. Callers must synchronize those operations with
* access through the pointer and obtain a fresh pointer after replacement.
*
* CreateHeap returns that backing heap only when all of the following hold:
* the block opted in with BX_D3D12_VMEM_FLAG_BACKING_HEAP, the region size is
* non-zero, and the desc is the heap this file creates for the region:
* Type CUSTOM, CPUPageProperty WRITE_BACK, MemoryPoolPreference L0,
* SizeInBytes equal to the configured region, Alignment 0 or 64 KiB,
* Flags exactly D3D12_HEAP_FLAG_NONE (the flag set used when the backing heap
* is created), and CreationNodeMask and VisibleNodeMask each 0 or 1.
* If the backing configuration changes during a backing request, CreateHeap
* returns HRESULT_FROM_WIN32(ERROR_RETRY) and discards any newly allocated heap.
* Any other CreateHeap is the host CreateHeap. The desc is not modified.
* The live-heap budget charge is taken on create and dropped on the wrapper's
* final Release. A resource created by CreatePlacedResource holds the wrapper
* for its lifetime.
* GetDevice on every wrapper returns the BxDeviceProxy. An ordinary heap AddRefs
* 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 AddRef. The cache would keep the device and its charge alive. That
* pointer is weak. It is cleared when the heap leaves the cache (a new region
* or a different host device) and when that proxy's last reference drops.
* CreatePlacedResource1 and CreatePlacedResource2 unwrap the wrapper to the
* host heap before the host call. The cache records the host ID3D12Device
* that built the heap. CreateHeap for a different host device releases the
* heap and its buffer, credits the charge, and builds a new one. CreateHeap
* for the same host device returns the cached heap. The check, the retarget,
* and the caller's reference happen in one critical section.
*
* The layout must match tests/conformance/test_d3d12_placed/main.cpp.
*/
constexpr uint32_t BX_D3D12_VMEM_MAGIC = 0x4D565842u;
constexpr uint32_t BX_D3D12_VMEM_FLAG_BACKING_HEAP = 0x1u;
struct BxD3d12VirtualMemoryConfig {
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;
};
static_assert(sizeof(BxD3d12VirtualMemoryConfig) == 48, "config block is 48 bytes");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, magic) == 0, "magic offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, struct_size) == 4, "struct_size offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, version) == 8, "version offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, flags) == 12, "flags offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, base_va) == 16, "base_va offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_bytes offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 32, "reserved offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_pointer offset");
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. */
bool bx_vmem_install_device_hooks(void* device);
/* 1->0 Release of a device proxy, under g_section. Compare-exchanges the count from
1 to 0 and clears every weak backing-heap pointer aimed at that proxy. Returns false
when the count was no longer 1, so the caller retries. A true return is the only
path into final cleanup. */
bool bx_vmem_final_release(void* device_proxy);
/* AddRefs the host ID3D12Device that created the cached backing heap, or returns null.
The test sets BX_D3D12_REUSE_BACKING_HOST=1 so a second proxy wraps this same host
while the cache still holds it. */
void* bx_vmem_addref_backing_host();
#endif /* BETTERXEN_D3D12_XS_VMEM_H */
+116 -4
View File
@@ -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;
}
+184 -9
View File
@@ -3,6 +3,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <intrin.h>
#include "bx_config.h"
#include "bx_log.h"
@@ -17,6 +18,14 @@ LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
std::atomic_flag g_crash_logged{};
std::atomic<bool> g_crash_in_flight{false};
std::atomic<uint64_t> g_clwb_traps{0};
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
// counts reach the JSONL trace only: the frozen .def has no export for them.
enum AmdKind { kClzero, kMonitorx, kMwaitx, kRdpru, kExtrq, kInsertq, kAmdKinds };
constexpr const char* kAmdEvents[kAmdKinds] = {
"clzero_trapped", "monitorx_trapped", "mwaitx_trapped",
"rdpru_trapped", "extrq_trapped", "insertq_trapped"};
std::atomic<uint64_t> g_amd_traps[kAmdKinds]{};
bx_runtime_config_t g_config = {
BX_ABI_VERSION,
BX_PROFILE_LOCKHART,
@@ -135,6 +144,167 @@ bool is_adx_opcode(const uint8_t* ip, size_t size) {
return size - idx >= 4 && ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
}
// Logs the first trap of a kind and then every power of two, as for clwb.
void log_sampled_trap(const char* event, uint64_t count, uint64_t rip, size_t len) {
if (count == 1 || (count & (count - 1)) == 0) {
char msg[160];
std::snprintf(msg, sizeof(msg),
"rip=0x%016llx len=%zu total_traps=%llu",
static_cast<unsigned long long>(rip), len,
static_cast<unsigned long long>(count));
bx_log_emit(BX_LOG_INFO, "runtime_veh", event, msg);
}
}
// The instruction encodings and architectural effects below are derived from
// AMD APM vol. 3 (24594, rev. 3.36), Instruction Prefixes and CLZERO, MONITORX,
// MWAITX, RDPRU, and vol. 4 (26568, rev. 3.25), EXTRQ and INSERTQ.
struct AmdInstruction {
AmdKind kind = kAmdKinds;
size_t length = 0;
bool address32 = false;
size_t destination = 0;
size_t source = 0;
bool immediate = false;
uint16_t field = 0;
};
AmdInstruction decode_amd_instruction(const uint8_t* bytes, size_t size) {
if (size < 3) {
return {};
}
const bool address32 = bytes[0] == 0x67;
const bool extract = bytes[0] == 0x66;
const bool insert = bytes[0] == 0xF2;
size_t offset = (address32 || extract || insert) ? 1 : 0;
uint8_t rex = 0;
if ((bytes[offset] & 0xF0) == 0x40) {
rex = bytes[offset++];
}
if (size - offset < 3 || bytes[offset] != 0x0F) {
return {};
}
const uint8_t opcode = bytes[offset + 1];
const uint8_t operand = bytes[offset + 2];
const size_t length = offset + 3;
if (!extract && !insert && opcode == 0x01) {
switch (operand) {
case 0xFC: return {kClzero, length, address32};
case 0xFA: return {kMonitorx, length, address32};
case 0xFB: return address32 ? AmdInstruction{} : AmdInstruction{kMwaitx, length};
case 0xFD: return address32 ? AmdInstruction{} : AmdInstruction{kRdpru, length};
default: return {};
}
}
if ((!extract && !insert) || (opcode != 0x78 && opcode != 0x79) ||
(operand & 0xC0) != 0xC0) {
return {};
}
const bool immediate = opcode == 0x78;
const unsigned reg = (operand & 0x38) >> 3;
if (immediate && (size - length < 2 || (extract && reg != 0))) {
return {};
}
const size_t rm = (operand & 7) + ((rex & 1) ? 8 : 0);
AmdInstruction result{extract ? kExtrq : kInsertq, length};
result.destination = extract && immediate ? rm : reg + ((rex & 4) ? 8 : 0);
result.source = rm;
result.immediate = immediate;
if (immediate) {
result.length += 2;
result.field = static_cast<uint16_t>(bytes[length + 1] * 256u + bytes[length]);
}
return result;
}
void apply_sse4a(const AmdInstruction& instruction, CONTEXT& context) {
M128A* registers = context.FltSave.XmmRegisters;
M128A& destination = registers[instruction.destination];
const M128A source = registers[instruction.source];
const bool extract = instruction.kind == kExtrq;
// EXTRQ takes register controls from bits 13:0 and INSERTQ from 77:64.
uint64_t field = instruction.field;
if (!instruction.immediate) {
field = extract ? source.Low : static_cast<uint64_t>(source.High);
}
const unsigned index = (field & 0x3F00) >> 8;
const unsigned width = field & 0x3F;
const uint64_t low_mask = width ? UINT64_MAX >> (64 - width) : UINT64_MAX;
if (extract) {
destination.Low = (destination.Low >> index) & low_mask;
} else {
const uint64_t positioned_mask = low_mask << index;
destination.Low = (destination.Low & ~positioned_mask) |
((source.Low << index) & positioned_mask);
}
// The APM leaves the upper quadword and out-of-range fields undefined.
}
bool zero_guest_cache_line(uint64_t address, EXCEPTION_RECORD& exception) {
// The supported guest has 64-byte cache lines. An aligned line fits
// in one Windows page, including when the address is at the end of it.
constexpr uintptr_t line_size = 64;
const uintptr_t start = address & ~(line_size - 1);
constexpr DWORD write_protections = PAGE_READWRITE | PAGE_WRITECOPY |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
MEMORY_BASIC_INFORMATION page{};
if (VirtualQuery(reinterpret_cast<const void*>(start), &page, sizeof(page)) &&
page.State == MEM_COMMIT && (page.Protect & write_protections) &&
!(page.Protect & PAGE_GUARD)) {
std::memset(reinterpret_cast<void*>(start), 0, line_size);
return true;
}
// Pass the write fault on at the original guest RIP. Guard pages use
// the same fallback, without Windows' one-shot guard-page semantics.
exception.ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
exception.NumberParameters = 2;
exception.ExceptionInformation[0] = 1; // Write access.
exception.ExceptionInformation[1] = start;
return false;
}
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
EXCEPTION_RECORD& exception) {
switch (instruction.kind) {
case kClzero:
return zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax)
: context.Rax, exception);
case kMonitorx:
// There is no host monitor state. MWAITX may complete immediately.
return true;
case kMwaitx:
// Approximate an early wakeup with one scheduler yield.
SwitchToThread();
return true;
case kRdpru: {
const uint32_t selector = static_cast<uint32_t>(context.Rcx);
const uint64_t counter = selector < 2 ? __rdtsc() : 0;
context.Rax = static_cast<uint32_t>(counter);
context.Rdx = static_cast<uint32_t>(counter >> 32);
// The APM specifies zero for these five flags and marks CF modified.
// BetterXen chooses a clear CF until its native behavior is verified.
constexpr DWORD arithmetic_flags = (1u << 11) | (1u << 7) | (1u << 6) |
(1u << 4) | (1u << 2) | (1u << 0);
context.EFlags &= ~arithmetic_flags;
return true;
}
case kExtrq:
case kInsertq:
apply_sse4a(instruction, context);
return true;
case kAmdKinds:
return false;
}
return false;
}
LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
// Wine can invoke the top-level filter again for the same terminal fault.
if (ep && ep->ExceptionRecord && ep->ContextRecord &&
@@ -198,20 +368,25 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
size_t len = decode_clwb_length(ip, size);
if (len > 0) {
uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1;
if (count == 1 || (count & (count - 1)) == 0) {
char msg[160];
std::snprintf(msg, sizeof(msg),
"rip=0x%016llx len=%zu total_traps=%llu",
static_cast<unsigned long long>(ep->ContextRecord->Rip),
len,
static_cast<unsigned long long>(count));
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clwb_trapped", msg);
}
log_sampled_trap("clwb_trapped", count, ep->ContextRecord->Rip, len);
ep->ContextRecord->Rip += len;
return EXCEPTION_CONTINUE_EXECUTION;
}
}
const AmdInstruction instruction = decode_amd_instruction(ip, size);
if (instruction.length != 0) {
if (!apply_amd_instruction(instruction, *ep->ContextRecord, *ep->ExceptionRecord)) {
return EXCEPTION_CONTINUE_SEARCH;
}
const uint64_t count =
g_amd_traps[instruction.kind].fetch_add(1, std::memory_order_relaxed) + 1;
log_sampled_trap(kAmdEvents[instruction.kind], count, ep->ContextRecord->Rip,
instruction.length);
ep->ContextRecord->Rip += instruction.length;
return EXCEPTION_CONTINUE_EXECUTION;
}
if (g_config.enable_adx_tripwire && is_adx_opcode(ip, size)) {
char msg[160];
std::snprintf(msg, sizeof(msg),
+2
View File
@@ -1,4 +1,6 @@
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
xcrdapi.cpp
)
target_include_directories(xcrdapi PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/dstorage")
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32 uuid)
target_compile_definitions(xcrdapi PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+15
View File
@@ -0,0 +1,15 @@
# Vendored DirectStorage headers (#483)
`dstorage.h` and `dstorageerr.h` are Microsoft's public PC DirectStorage headers, copied **unmodified** (CRLF line endings preserved) so that `XCRDAPI.dll` and `test_xcrdapi` can implement and call the public `IDStorageFactory`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` interfaces.
| Item | Value |
| --- | --- |
| Source | NuGet package [`Microsoft.Direct3D.DirectStorage` 1.4.0](https://www.nuget.org/packages/Microsoft.Direct3D.DirectStorage/1.4.0), downloaded from `api.nuget.org` on 2026-11-26 |
| Package SHA-256 | `0838e7f71b14acfbd1ac7ecc5e943f6c95e4f4e679e8a67f8ff6e7c102414321` |
| Files | `native/include/dstorage.h` (SHA-256 `3f966750423b59145bd05b2ccd889b819f0484813baafbc1345cb16e544b4f87`), `native/include/dstorageerr.h` (SHA-256 `07ea8182503c25dd1684d3f9105db7b6fa70fc96dcdab18bd9de75fcec427fa2`), `LICENSE-CODE.txt` (SHA-256 `903df5512f7d02609fed0c780a9b704f5a3eeb6e4d84ebe42a29845c81899a3c`) |
| Licence | MIT. Both headers start with `Copyright (c) Microsoft Corporation` / `Licensed under the MIT license`; the package's `LICENSE-CODE.txt` (copied here) holds the MIT text. |
| Modifications | None |
The package as a whole is under the proprietary *Microsoft DirectStorage SDK* licence terms (`LICENSE.txt`), whose distributable list (`distributable_files.txt`) names only `dstorage.dll` and `dstoragecore.dll`. BetterXen uses neither DLL and copies nothing else from the package.
The Xbox console interfaces (`IDStorageFactoryX` and others, `dstorage_xs.h`) are not included: their IIDs have no licence-compatible public source. See the discussion on #483.
File diff suppressed because it is too large. Load diff
+502
View File
@@ -0,0 +1,502 @@
/*-------------------------------------------------------------------------------------
*
* Copyright (c) Microsoft Corporation
* Licensed under the MIT license
*
*-------------------------------------------------------------------------------------*/
#pragma once
/*++
MessageId's 0x0000 - 0x00ff (inclusive) are reserved for DirectStorage.
--*/
//
// Values are 32 bit values laid out as follows:
//
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +---+-+-+-----------------------+-------------------------------+
// |Sev|C|R| Facility | Code |
// +---+-+-+-----------------------+-------------------------------+
//
// where
//
// Sev - is the severity code
//
// 00 - Success
// 01 - Informational
// 10 - Warning
// 11 - Error
//
// C - is the Customer code flag
//
// R - is a reserved bit
//
// Facility - is the facility code
//
// Code - is the facility's status code
//
//
// Define the facility codes
//
#define FACILITY_GAME 2340
//
// Define the severity codes
//
//
// MessageId: E_DSTORAGE_ALREADY_RUNNING
//
// MessageText:
//
// DStorage is already running exclusively.
//
#define E_DSTORAGE_ALREADY_RUNNING ((HRESULT)0x89240001L)
//
// MessageId: E_DSTORAGE_NOT_RUNNING
//
// MessageText:
//
// DStorage is not running.
//
#define E_DSTORAGE_NOT_RUNNING ((HRESULT)0x89240002L)
//
// MessageId: E_DSTORAGE_INVALID_QUEUE_CAPACITY
//
// MessageText:
//
// Invalid queue capacity parameter.
//
#define E_DSTORAGE_INVALID_QUEUE_CAPACITY ((HRESULT)0x89240003L)
//
// MessageId: E_DSTORAGE_XVD_DEVICE_NOT_SUPPORTED
//
// MessageText:
//
// The specified XVD is not on a supported NVMe device.
// This error only applies to Xbox.
//
#define E_DSTORAGE_XVD_DEVICE_NOT_SUPPORTED ((HRESULT)0x89240004L)
//
// MessageId: E_DSTORAGE_UNSUPPORTED_VOLUME
//
// MessageText:
//
// The specified XVD is not on a supported volume.
// This error only applies to Xbox.
//
#define E_DSTORAGE_UNSUPPORTED_VOLUME ((HRESULT)0x89240005L)
//
// MessageId: E_DSTORAGE_END_OF_FILE
//
// MessageText:
//
// The specified offset and length exceeds the size of the file.
//
#define E_DSTORAGE_END_OF_FILE ((HRESULT)0x89240007L)
//
// MessageId: E_DSTORAGE_REQUEST_TOO_LARGE
//
// MessageText:
//
// The IO request is too large.
//
#define E_DSTORAGE_REQUEST_TOO_LARGE ((HRESULT)0x89240008L)
//
// MessageId: E_DSTORAGE_ACCESS_VIOLATION
//
// MessageText:
//
// The destination buffer for the DStorage request is not accessible.
//
#define E_DSTORAGE_ACCESS_VIOLATION ((HRESULT)0x89240009L)
//
// MessageId: E_DSTORAGE_UNSUPPORTED_FILE
//
// MessageText:
//
// The file is not supported by DStorage. Possible reasons include the file is a
// sparse file, or is compressed in NTFS.
// This error only applies to Xbox.
//
#define E_DSTORAGE_UNSUPPORTED_FILE ((HRESULT)0x8924000AL)
//
// MessageId: E_DSTORAGE_FILE_NOT_OPEN
//
// MessageText:
//
// The file is not open.
//
#define E_DSTORAGE_FILE_NOT_OPEN ((HRESULT)0x8924000BL)
//
// MessageId: E_DSTORAGE_RESERVED_FIELDS
//
// MessageText:
//
// A reserved field is not set to 0.
//
#define E_DSTORAGE_RESERVED_FIELDS ((HRESULT)0x8924000CL)
//
// MessageId: E_DSTORAGE_INVALID_BCPACK_MODE
//
// MessageText:
//
// The request has invalid BCPack decompression mode.
// This error only applies to Xbox.
//
#define E_DSTORAGE_INVALID_BCPACK_MODE ((HRESULT)0x8924000DL)
//
// MessageId: E_DSTORAGE_INVALID_SWIZZLE_MODE
//
// MessageText:
//
// The request has invalid swizzle mode.
// This error only applies to Xbox.
//
#define E_DSTORAGE_INVALID_SWIZZLE_MODE ((HRESULT)0x8924000EL)
//
// MessageId: E_DSTORAGE_INVALID_DESTINATION_SIZE
//
// MessageText:
//
// The request's destination size is invalid. If no decompression is used, it must
// be equal to the request's length; If decompression is used, it must be larger
// than the request's length.
//
#define E_DSTORAGE_INVALID_DESTINATION_SIZE ((HRESULT)0x8924000FL)
//
// MessageId: E_DSTORAGE_QUEUE_CLOSED
//
// MessageText:
//
// The request targets a queue that is closed.
//
#define E_DSTORAGE_QUEUE_CLOSED ((HRESULT)0x89240010L)
//
// MessageId: E_DSTORAGE_INVALID_CLUSTER_SIZE
//
// MessageText:
//
// The volume is formatted with an unsupported cluster size.
// This error only applies to Xbox.
//
#define E_DSTORAGE_INVALID_CLUSTER_SIZE ((HRESULT)0x89240011L)
//
// MessageId: E_DSTORAGE_TOO_MANY_QUEUES
//
// MessageText:
//
// The number of queues has reached the maximum limit.
//
#define E_DSTORAGE_TOO_MANY_QUEUES ((HRESULT)0x89240012L)
//
// MessageId: E_DSTORAGE_INVALID_QUEUE_PRIORITY
//
// MessageText:
//
// Invalid priority is specified for the queue.
//
#define E_DSTORAGE_INVALID_QUEUE_PRIORITY ((HRESULT)0x89240013L)
//
// MessageId: E_DSTORAGE_TOO_MANY_FILES
//
// MessageText:
//
// The number of files has reached the maximum limit.
//
#define E_DSTORAGE_TOO_MANY_FILES ((HRESULT)0x89240014L)
//
// MessageId: E_DSTORAGE_INDEX_BOUND
//
// MessageText:
//
// The index parameter is out of bound.
//
#define E_DSTORAGE_INDEX_BOUND ((HRESULT)0x89240015L)
//
// MessageId: E_DSTORAGE_IO_TIMEOUT
//
// MessageText:
//
// The IO operation has timed out.
//
#define E_DSTORAGE_IO_TIMEOUT ((HRESULT)0x89240016L)
//
// MessageId: E_DSTORAGE_INVALID_FILE_HANDLE
//
// MessageText:
//
// The specified file has not been opened.
//
#define E_DSTORAGE_INVALID_FILE_HANDLE ((HRESULT)0x89240017L)
//
// MessageId: E_DSTORAGE_DEPRECATED_PREVIEW_GDK
//
// MessageText:
//
// This GDK preview is deprecated. Update to a supported GDK version.
// This error only applies to Xbox.
//
#define E_DSTORAGE_DEPRECATED_PREVIEW_GDK ((HRESULT)0x89240018L)
//
// MessageId: E_DSTORAGE_XVD_NOT_REGISTERED
//
// MessageText:
//
// The specified XVD is not registered or unmounted.
// This error only applies to Xbox.
//
#define E_DSTORAGE_XVD_NOT_REGISTERED ((HRESULT)0x89240019L)
//
// MessageId: E_DSTORAGE_INVALID_FILE_OFFSET
//
// MessageText:
//
// The request has invalid file offset for the specified decompression mode.
//
#define E_DSTORAGE_INVALID_FILE_OFFSET ((HRESULT)0x8924001AL)
//
// MessageId: E_DSTORAGE_INVALID_SOURCE_TYPE
//
// MessageText:
//
// A memory source request was enqueued into a file source queue, or a file source
// request was enqueued into a memory source queue.
//
#define E_DSTORAGE_INVALID_SOURCE_TYPE ((HRESULT)0x8924001BL)
//
// MessageId: E_DSTORAGE_INVALID_INTERMEDIATE_SIZE
//
// MessageText:
//
// The request has invalid intermediate size for the specified decompression modes.
// This error only applies to Xbox.
//
#define E_DSTORAGE_INVALID_INTERMEDIATE_SIZE ((HRESULT)0x8924001CL)
//
// MessageId: E_DSTORAGE_SYSTEM_NOT_SUPPORTED
//
// MessageText:
//
// This console generation doesn't support DirectStorage.
// This error only applies to Xbox.
//
#define E_DSTORAGE_SYSTEM_NOT_SUPPORTED ((HRESULT)0x8924001DL)
//
// MessageId: E_DSTORAGE_STAGING_BUFFER_LOCKED
//
// MessageText:
//
// Staging buffer size can only be changed when no queue is created and no file is
// open.
//
#define E_DSTORAGE_STAGING_BUFFER_LOCKED ((HRESULT)0x8924001FL)
//
// MessageId: E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE
//
// MessageText:
//
// The specified staging buffer size is not valid.
//
#define E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE ((HRESULT)0x89240020L)
//
// MessageId: E_DSTORAGE_STAGING_BUFFER_TOO_SMALL
//
// MessageText:
//
// The staging buffer isn't large enough to perform this operation.
//
#define E_DSTORAGE_STAGING_BUFFER_TOO_SMALL ((HRESULT)0x89240021L)
//
// MessageId: E_DSTORAGE_INVALID_FENCE
//
// MessageText:
//
// The fence is not valid or has been released.
//
#define E_DSTORAGE_INVALID_FENCE ((HRESULT)0x89240022L)
//
// MessageId: E_DSTORAGE_INVALID_STATUS_ARRAY
//
// MessageText:
//
// The status array is not valid or has been released.
//
#define E_DSTORAGE_INVALID_STATUS_ARRAY ((HRESULT)0x89240023L)
//
// MessageId: E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY
//
// MessageText:
//
// Invalid priority is specified for the queue. Only DSTORAGE_PRIORITY_REALTIME
// is a valid priority for a memory queue.
//
#define E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY ((HRESULT)0x89240024L)
//
// MessageId: E_DSTORAGE_DECOMPRESSION_ERROR
//
// MessageText:
//
// A generic error has happened during decompression.
//
#define E_DSTORAGE_DECOMPRESSION_ERROR ((HRESULT)0x89240030L)
//
// MessageId: E_DSTORAGE_ZLIB_BAD_HEADER
//
// MessageText:
//
// ZLIB header is corrupted.
// This error only applies to Xbox.
//
#define E_DSTORAGE_ZLIB_BAD_HEADER ((HRESULT)0x89240031L)
//
// MessageId: E_DSTORAGE_ZLIB_BAD_DATA
//
// MessageText:
//
// ZLIB compressed data is corrupted/invalid.
// This error only applies to Xbox.
//
#define E_DSTORAGE_ZLIB_BAD_DATA ((HRESULT)0x89240032L)
//
// MessageId: E_DSTORAGE_ZLIB_PARITY_FAIL
//
// MessageText:
//
// Block-level ADLER parity check failed during ZLIB decompression.
// This error only applies to Xbox.
//
#define E_DSTORAGE_ZLIB_PARITY_FAIL ((HRESULT)0x89240033L)
//
// MessageId: E_DSTORAGE_BCPACK_BAD_HEADER
//
// MessageText:
//
// BCPack header is corrupted.
// This error only applies to Xbox.
//
#define E_DSTORAGE_BCPACK_BAD_HEADER ((HRESULT)0x89240034L)
//
// MessageId: E_DSTORAGE_BCPACK_BAD_DATA
//
// MessageText:
//
// BCPack decoder has generated more data than expected, most likely due to
// corrupted bitstream.
// This error only applies to Xbox.
//
#define E_DSTORAGE_BCPACK_BAD_DATA ((HRESULT)0x89240035L)
//
// MessageId: E_DSTORAGE_DECRYPTION_ERROR
//
// MessageText:
//
// A generic error has happened during decryption.
// This error only applies to Xbox.
//
#define E_DSTORAGE_DECRYPTION_ERROR ((HRESULT)0x89240036L)
//
// MessageId: E_DSTORAGE_PASSTHROUGH_ERROR
//
// MessageText:
//
// A generic error has happened during copy operation.
// This error only applies to Xbox.
//
#define E_DSTORAGE_PASSTHROUGH_ERROR ((HRESULT)0x89240037L)
//
// MessageId: E_DSTORAGE_FILE_TOO_FRAGMENTED
//
// MessageText:
//
// The file is too fragmented to be accessed by DStorage. This error can only
// happen with files overly fragmented on a writable volume.
// This error only applies to Xbox.
//
#define E_DSTORAGE_FILE_TOO_FRAGMENTED ((HRESULT)0x89240038L)
//
// MessageId: E_DSTORAGE_COMPRESSED_DATA_TOO_LARGE
//
// MessageText:
//
// The size of the resulting compressed data is too large for
// DirectStorage to decompress successfully on the GPU.
//
#define E_DSTORAGE_COMPRESSED_DATA_TOO_LARGE ((HRESULT)0x89240039L)
//
// MessageId: E_DSTORAGE_INVALID_DESTINATION_TYPE
//
// MessageText:
//
// A gpu memory destination request was enqueued into a queue that
// was created without a D3D device or the destination type is
// unknown.
//
#define E_DSTORAGE_INVALID_DESTINATION_TYPE ((HRESULT)0x89240040L)
//
// MessageId: E_DSTORAGE_FILEBUFFERING_REQUIRES_DISABLED_BYPASSIO
//
// MessageText:
//
// ForceFileBuffering was enabled without disabling BypassIO.
//
#define E_DSTORAGE_FILEBUFFERING_REQUIRES_DISABLED_BYPASSIO ((HRESULT)0x89240041L)
//
// MessageId: E_DSTORAGE_SCRATCH_BUFFER_TOO_SMALL
//
// MessageText:
//
// The scratch buffer given to the driver is too small
// to decompress buffers successfully.
//
#define E_DSTORAGE_SCRATCH_BUFFER_TOO_SMALL ((HRESULT)0x89240042L)
+27
View File
@@ -0,0 +1,27 @@
#ifndef BETTERXEN_DSTORAGE_MINGW_H
#define BETTERXEN_DSTORAGE_MINGW_H
// dstorage.h attaches its IIDs with the MSVC-only __declspec(uuid(...)) through
// DECLARE_INTERFACE_IID_, which MinGW-w64 GCC ignores, so __uuidof() has no
// definition. These declarations restate the same IIDs for MinGW. They were
// generated from the DECLARE_INTERFACE_IID_ lines of the vendored, unmodified
// dstorage/dstorage.h (SDK 1.4.0, MIT); regenerate them if that header changes.
#include <dstorage.h>
#if defined(__MINGW32__) && !defined(_MSC_VER)
__CRT_UUID_DECL(IDStorageFile, 0x5de95e7b, 0x955a, 0x4868, 0xa7, 0x3c, 0x24, 0x3b, 0x29, 0xf4, 0xb8, 0xda)
__CRT_UUID_DECL(IDStorageCustomDecompressionQueue, 0x97179b2f, 0x2c21, 0x49ca, 0x82, 0x91, 0x4e, 0x1b, 0xf4, 0xa1, 0x60, 0xdf)
__CRT_UUID_DECL(IDStorageCustomDecompressionQueue1, 0x0D47C6C9, 0xE61A, 0x4706, 0x93, 0xB4, 0x68, 0xBF, 0xE3, 0xF4, 0xAA, 0x4A)
__CRT_UUID_DECL(IDStorageFactory, 0x6924ea0c, 0xc3cd, 0x4826, 0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1)
__CRT_UUID_DECL(IDStorageFactory1, 0x1e0da17e, 0xb6d9, 0x4c17, 0x91, 0xb0, 0xe5, 0x7a, 0xe9, 0xbd, 0xa1, 0x2e)
__CRT_UUID_DECL(IDStorageStatusArray, 0x82397587, 0x7cd5, 0x453b, 0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56)
__CRT_UUID_DECL(IDStorageQueue, 0xcfdbd83f, 0x9e06, 0x4fda, 0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b)
__CRT_UUID_DECL(IDStorageQueue1, 0xdd2f482c, 0x5eff, 0x41e8, 0x9c, 0x9e, 0xd2, 0x37, 0x4b, 0x27, 0x81, 0x28)
__CRT_UUID_DECL(IDStorageQueue2, 0xb1c9d643, 0x3a49, 0x44a2, 0xb4, 0x6f, 0x65, 0x36, 0x49, 0x47, 0x0d, 0x18)
__CRT_UUID_DECL(IDStorageQueue3, 0xdeb54c52, 0xeca8, 0x46b3, 0x82, 0xa7, 0x03, 0x1b, 0x72, 0x26, 0x26, 0x53)
__CRT_UUID_DECL(IDStorageQueue4, 0x639ff1a7, 0x739e, 0x4291, 0xb6, 0x72, 0xc7, 0x21, 0xc5, 0xf2, 0xa3, 0xda)
__CRT_UUID_DECL(IDStorageCompressionCodec, 0x84ef5121, 0x9b43, 0x4d03, 0xb5, 0xc1, 0xcc, 0x34, 0x60, 0x6b, 0x26, 0x2d)
#endif
#endif
+26 -2
View File
@@ -2,6 +2,12 @@
#define BETTERXEN_SYNTHETIC_STORAGE_H
#include <windows.h>
// Host d3d12.dll returns large structs such as D3D12_RESOURCE_DESC through a
// hidden pointer. WIDL_EXPLICIT_AGGREGATE_RETURNS has to be set before <d3d12.h>
// is parsed. A #define in this header is too late if the translation unit
// included <d3d12.h> already. The xcrdapi and test_xcrdapi targets pass it as
// a compile definition. GetHeapProperties is an HRESULT with out-parameters
// and does not use that aggregate-return ABI.
#include <d3d12.h>
#include <unknwn.h>
@@ -26,9 +32,20 @@ struct Status : IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetResult(UINT index) = 0;
};
// Requests keep source and destination buffers borrowed until completion.
// BetterXen-defined request. Borrowed CPU pointers stay valid until completion.
// File requests retain a duplicate of the file handle when enqueued.
// Exactly one of `file` or `source` may be non-null; setting both returns E_INVALIDARG.
// Exactly one of `file` or `source` may be non-null.
// A non-zero `size` needs exactly one of `destination` (CPU memory) or `resource`
// (an ID3D12Resource buffer written at `resource_offset`). CPU-visible heaps are
// mapped. A default heap is copied on the device GetDevice returns and must be
// in D3D12_RESOURCE_STATE_COMMON across that copy.
// BX_XCRDAPI_COPY_TIMEOUT_MS is the staged-copy wait in milliseconds. Unset,
// empty, or non-numeric values use 10000. Numeric values clamp to 0..60000.
// BX_XCRDAPI_DEFER_COPY=1 holds the copy queue on a private fence until that
// wait has been decided, so a 0 ms timeout observes an unconfirmed completion
// instead of racing a fast GPU, then lets the copy finish. An unconfirmed
// completion keeps the destination and the copy's GPU objects alive.
// `compression` values are BetterXen-defined selectors, not an Xbox enum.
struct Request {
File* file;
UINT64 file_offset;
@@ -36,8 +53,15 @@ struct Request {
void* destination;
DWORD size;
UINT compression;
ID3D12Resource* resource = nullptr;
UINT64 resource_offset = 0;
};
inline constexpr UINT compression_none = 0;
inline constexpr UINT compression_lz = 1;
inline constexpr UINT compression_bcpack = 2;
inline constexpr UINT compression_gdeflate = 3;
struct ErrorRecord {
HRESULT first_error;
UINT64 failure_count;
+1275 -28
View File
File diff suppressed because it is too large. Load diff
+296 -26
View File
@@ -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, &params)) {
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(&params, 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, &params)) {
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, &params)) {
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(&params, 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;
+227 -2
View File
@@ -6,9 +6,16 @@
* distributed PC GDK NuGet package (Microsoft.GDK.Windows 2610.0.9661, nuget.org) using an
* independently authored synthetic caller invoking public documented GDK APIs. No Microsoft
* source code or binary code is copied or bundled.
*
* XGameSave and XPackage class ids, interface ids, and vtable order are separate from that
* work. Those facts are from https://github.com/xodus-gaming/xgameruntime-docs commit
* 7090008692569aa6081e30dfdd9de58237741e24. Function signatures follow the public Microsoft
* Learn GDK reference (learn.microsoft.com/gaming/gdk). No text from either source is copied.
*/
#include "com_dispatch.h"
#include "runtime_internal.h"
#include <array>
#include <atomic>
#include <cstddef>
@@ -27,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);
@@ -177,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);
@@ -290,8 +301,25 @@ ComSingleton kSystemObj{kSystemVtbl.data(), &kSystemIid, "IXSystem"};
void WINAPI err_set_callback(void*, void*, void*) {}
void WINAPI err_set_options(void*, uint32_t, uint32_t) {}
/*
* IXError slot 3. xodus-gaming/xgameruntime-docs (commit 7090008) lists this slot as unknown.
* Its behaviour here comes from the #492 review's interop observation (atesahmet0,
* 2026-11-26): the GDK's static library calls it before some subsystem calls, for example
* XPackageMount, and continues only when it returns false. The default stub returned E_NOTIMPL,
* whose low byte reads as true and stopped those calls. The parameters are not known, so none
* are read. It is logged once so the call stays visible in `bx-cli trace`.
*/
bool WINAPI err_slot3(void*) {
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
bx_log_emit(BX_LOG_INFO, "xgameruntime", "IXError_slot3", "returning false (continue); arguments not read");
}
return false;
}
const std::array<const void*, 8> kErrorVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&err_slot3);
v[4] = reinterpret_cast<const void*>(&err_set_callback);
v[5] = reinterpret_cast<const void*>(&err_set_options);
return v;
@@ -573,6 +601,196 @@ const std::array<const void*, 8> kGameVtbl = [] {
}();
ComSingleton kGameObj{kGameVtbl.data(), &kGameIid, "IXGame"};
// --- XGameSave / XPackage (#468) ---
// Ids and inheritance from xodus-gaming/xgameruntime-docs commit
// 7090008692569aa6081e30dfdd9de58237741e24.
// IXGameSaveImpl uses the class id and lists 27 methods in slots 3-29.
// IXGameSaveImpl2 adds 3 XGameSaveFiles methods in slots 30-32.
// IXGameSaveImpl3 adds none.
// IXPackageImpl lists 32 methods in slots 3-34.
// IXPackageImpl2 adds 4 methods in slots 35-38.
// IXPackageImpl3 adds 2 methods in slots 39-40.
// IXPackageImpl4 adds XPackageGetPackageKind at slot 41.
constexpr GUID kGameSaveClsid = {0x704C3F58, 0xE629, 0x4CC2, {0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6F, 0xE2}};
constexpr GUID kGameSaveIid2 = {0x704C3F58, 0xE629, 0x4CC2, {0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6E, 0xE2}};
constexpr GUID kGameSaveIid3 = {0x1BFFF3AF, 0xF14A, 0x40A3, {0x8E, 0x35, 0x9A, 0xDA, 0x90, 0x65, 0x93, 0xF9}};
constexpr GUID kPackageClsid = {0xAF406016, 0xE850, 0x4AA8, {0xA8, 0x8D, 0x2F, 0x3D, 0xCB, 0x9D, 0xAC, 0x7E}};
constexpr GUID kPackageIid = {0x3720DE07, 0xE8E4, 0x44A3, {0xAD, 0x32, 0xB3, 0x59, 0xE8, 0xAD, 0xBE, 0x55}};
constexpr GUID kPackageIid2 = {0xF92D8712, 0x2B27, 0x4D8A, {0xBF, 0x01, 0x11, 0xA6, 0xF8, 0xE3, 0xEB, 0x42}};
constexpr GUID kPackageIid3 = {0xE2A4734B, 0x2F4A, 0x456D, {0xAA, 0x8F, 0xD0, 0x65, 0xE0, 0x4F, 0xB2, 0x09}};
constexpr GUID kPackageIid4 = {0x0B9D556E, 0xAB70, 0x43F4, {0xBA, 0xA0, 0x99, 0x99, 0xAC, 0x4C, 0xB0, 0x40}};
HRESULT WINAPI game_save_query_interface(void* self, const GUID* riid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!riid) return E_INVALIDARG;
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, kGameSaveClsid) || guid_eq(*riid, kGameSaveIid2) ||
guid_eq(*riid, kGameSaveIid3)) {
*out = self;
return S_OK;
}
return E_NOINTERFACE;
}
HRESULT WINAPI package_query_interface(void* self, const GUID* riid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!riid) return E_INVALIDARG;
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, kPackageIid) || guid_eq(*riid, kPackageIid2) ||
guid_eq(*riid, kPackageIid3) || guid_eq(*riid, kPackageIid4)) {
*out = self;
return S_OK;
}
return E_NOINTERFACE;
}
#define BX_HR(fn, iface, slot, method) \
HRESULT WINAPI fn(void*) { \
BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); \
return E_NOTIMPL; \
}
#define BX_VOID(fn, iface, slot, method) \
void WINAPI fn(void*) { BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); }
// Bool slots log and return false. The HRESULT bit pattern would look like true to a caller.
#define BX_BOOL(fn, iface, slot, method) \
bool WINAPI fn(void*) { \
BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); \
return false; \
}
BX_HR(gs_quota, "IXGameSaveImpl", 7, "XGameSaveGetRemainingQuota")
BX_HR(gs_quota_async, "IXGameSaveImpl", 8, "XGameSaveGetRemainingQuotaAsync")
BX_HR(gs_quota_result, "IXGameSaveImpl", 9, "XGameSaveGetRemainingQuotaResult")
BX_HR(gs_delete, "IXGameSaveImpl", 10, "XGameSaveDeleteContainer")
BX_HR(gs_delete_async, "IXGameSaveImpl", 11, "XGameSaveDeleteContainerAsync")
BX_HR(gs_delete_result, "IXGameSaveImpl", 12, "XGameSaveDeleteContainerResult")
BX_HR(gs_container_info, "IXGameSaveImpl", 13, "XGameSaveGetContainerInfo")
BX_HR(gs_enum_by_name, "IXGameSaveImpl", 15, "XGameSaveEnumerateContainerInfoByName")
BX_HR(gs_enum_blobs, "IXGameSaveImpl", 18, "XGameSaveEnumerateBlobInfo")
BX_HR(gs_enum_blobs_by_name, "IXGameSaveImpl", 19, "XGameSaveEnumerateBlobInfoByName")
BX_HR(gs_blob_delete, "IXGameSaveImpl", 26, "XGameSaveSubmitBlobDelete")
BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWithUiAsync")
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
BX_HR(pk_create_monitor, "IXPackageImpl", 5, "XPackageCreateInstallationMonitor")
BX_VOID(pk_close_monitor, "IXPackageImpl", 6, "XPackageCloseInstallationMonitorHandle")
BX_VOID(pk_get_progress, "IXPackageImpl", 7, "XPackageGetInstallationProgress")
BX_BOOL(pk_update_monitor, "IXPackageImpl", 8, "XPackageUpdateInstallationMonitor")
BX_HR(pk_reg_progress, "IXPackageImpl", 9, "XPackageRegisterInstallationProgressChanged")
BX_BOOL(pk_unreg_progress, "IXPackageImpl", 10, "XPackageUnregisterInstallationProgressChanged")
BX_HR(pk_locale, "IXPackageImpl", 11, "XPackageGetUserLocale")
BX_HR(pk_find_chunk, "IXPackageImpl", 12, "XPackageFindChunkAvailability")
BX_HR(pk_enum_chunk, "IXPackageImpl", 13, "XPackageEnumerateChunkAvailability")
BX_HR(pk_change_order, "IXPackageImpl", 14, "XPackageChangeChunkInstallOrder")
BX_HR(pk_install, "IXPackageImpl", 15, "XPackageInstallChunks")
BX_HR(pk_install_async, "IXPackageImpl", 16, "XPackageInstallChunksAsync")
BX_HR(pk_install_result, "IXPackageImpl", 17, "XPackageInstallChunksResult")
BX_HR(pk_estimate, "IXPackageImpl", 18, "XPackageEstimateDownloadSize")
BX_HR(pk_uninstall_chunks, "IXPackageImpl", 19, "XPackageUninstallChunks")
BX_HR(pk_unknown_20, "IXPackageImpl", 20, "unknown")
BX_HR(pk_unknown_21, "IXPackageImpl", 21, "unknown")
BX_BOOL(pk_unreg_installed, "IXPackageImpl", 22, "XPackageUnregisterPackageInstalled")
BX_HR(pk_unknown_27, "IXPackageImpl", 27, "unknown")
BX_HR(pk_enum_packages, "IXPackageImpl", 28, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed, "IXPackageImpl", 29, "XPackageRegisterPackageInstalled")
BX_HR(pk_write_stats, "IXPackageImpl", 30, "XPackageGetWriteStats")
BX_HR(pk_unknown_31, "IXPackageImpl", 31, "unknown")
BX_HR(pk_uninstall_uwp, "IXPackageImpl", 32, "XPackageUninstallUWPInstance")
BX_HR(pk_enum_features, "IXPackageImpl", 33, "XPackageEnumerateFeatures")
BX_HR(pk_uninstall, "IXPackageImpl", 34, "XPackageUninstallPackage")
BX_HR(pk_enum_packages_2, "IXPackageImpl2", 35, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
BX_HR(pk_enum_packages_3, "IXPackageImpl3", 39, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalled")
#undef BX_HR
#undef BX_VOID
#undef BX_BOOL
const std::array<const void*, 33> kGameSaveVtbl = [] {
auto v = make_default_vtbl<33>();
v[0] = reinterpret_cast<const void*>(&game_save_query_interface);
v[3] = reinterpret_cast<const void*>(&initialize_provider);
v[4] = reinterpret_cast<const void*>(&initialize_provider_async);
v[5] = reinterpret_cast<const void*>(&initialize_provider_result);
v[6] = reinterpret_cast<const void*>(&close_provider);
v[7] = reinterpret_cast<const void*>(&gs_quota);
v[8] = reinterpret_cast<const void*>(&gs_quota_async);
v[9] = reinterpret_cast<const void*>(&gs_quota_result);
v[10] = reinterpret_cast<const void*>(&gs_delete);
v[11] = reinterpret_cast<const void*>(&gs_delete_async);
v[12] = reinterpret_cast<const void*>(&gs_delete_result);
v[13] = reinterpret_cast<const void*>(&gs_container_info);
v[14] = reinterpret_cast<const void*>(&enumerate_container_info);
v[15] = reinterpret_cast<const void*>(&gs_enum_by_name);
v[16] = reinterpret_cast<const void*>(&create_container);
v[17] = reinterpret_cast<const void*>(&close_container);
v[18] = reinterpret_cast<const void*>(&gs_enum_blobs);
v[19] = reinterpret_cast<const void*>(&gs_enum_blobs_by_name);
v[20] = reinterpret_cast<const void*>(&read_blob_data);
v[21] = reinterpret_cast<const void*>(&read_blob_data_async);
v[22] = reinterpret_cast<const void*>(&read_blob_data_result);
v[23] = reinterpret_cast<const void*>(&create_update);
v[24] = reinterpret_cast<const void*>(&close_update);
v[25] = reinterpret_cast<const void*>(&submit_blob_write);
v[26] = reinterpret_cast<const void*>(&gs_blob_delete);
v[27] = reinterpret_cast<const void*>(&submit_update);
v[28] = reinterpret_cast<const void*>(&submit_update_async);
v[29] = reinterpret_cast<const void*>(&submit_update_result);
v[30] = reinterpret_cast<const void*>(&gs_files_folder_async);
v[31] = reinterpret_cast<const void*>(&gs_files_folder_result);
v[32] = reinterpret_cast<const void*>(&gs_files_quota);
return v;
}();
ComSingleton kGameSaveObj{kGameSaveVtbl.data(), &kGameSaveClsid, "IXGameSaveImpl"};
const std::array<const void*, 42> kPackageVtbl = [] {
auto v = make_default_vtbl<42>();
v[0] = reinterpret_cast<const void*>(&package_query_interface);
v[3] = reinterpret_cast<const void*>(&get_current_process_package_identifier);
v[4] = reinterpret_cast<const void*>(&is_packaged_process);
v[5] = reinterpret_cast<const void*>(&pk_create_monitor);
v[6] = reinterpret_cast<const void*>(&pk_close_monitor);
v[7] = reinterpret_cast<const void*>(&pk_get_progress);
v[8] = reinterpret_cast<const void*>(&pk_update_monitor);
v[9] = reinterpret_cast<const void*>(&pk_reg_progress);
v[10] = reinterpret_cast<const void*>(&pk_unreg_progress);
v[11] = reinterpret_cast<const void*>(&pk_locale);
v[12] = reinterpret_cast<const void*>(&pk_find_chunk);
v[13] = reinterpret_cast<const void*>(&pk_enum_chunk);
v[14] = reinterpret_cast<const void*>(&pk_change_order);
v[15] = reinterpret_cast<const void*>(&pk_install);
v[16] = reinterpret_cast<const void*>(&pk_install_async);
v[17] = reinterpret_cast<const void*>(&pk_install_result);
v[18] = reinterpret_cast<const void*>(&pk_estimate);
v[19] = reinterpret_cast<const void*>(&pk_uninstall_chunks);
v[20] = reinterpret_cast<const void*>(&pk_unknown_20);
v[21] = reinterpret_cast<const void*>(&pk_unknown_21);
v[22] = reinterpret_cast<const void*>(&pk_unreg_installed);
v[23] = reinterpret_cast<const void*>(&mount);
v[24] = reinterpret_cast<const void*>(&get_mount_path_size);
v[25] = reinterpret_cast<const void*>(&get_mount_path);
v[26] = reinterpret_cast<const void*>(&close_mount_handle);
v[27] = reinterpret_cast<const void*>(&pk_unknown_27);
v[28] = reinterpret_cast<const void*>(&pk_enum_packages);
v[29] = reinterpret_cast<const void*>(&pk_reg_installed);
v[30] = reinterpret_cast<const void*>(&pk_write_stats);
v[31] = reinterpret_cast<const void*>(&pk_unknown_31);
v[32] = reinterpret_cast<const void*>(&pk_uninstall_uwp);
v[33] = reinterpret_cast<const void*>(&pk_enum_features);
v[34] = reinterpret_cast<const void*>(&pk_uninstall);
v[35] = reinterpret_cast<const void*>(&pk_enum_packages_2);
v[36] = reinterpret_cast<const void*>(&pk_reg_installed_2);
v[37] = reinterpret_cast<const void*>(&mount_with_ui_async);
v[38] = reinterpret_cast<const void*>(&mount_with_ui_result);
v[39] = reinterpret_cast<const void*>(&pk_enum_packages_3);
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
v[41] = reinterpret_cast<const void*>(&get_package_kind);
return v;
}();
ComSingleton kPackageObj{kPackageVtbl.data(), &kPackageIid4, "IXPackageImpl"};
struct PublicEntry {
const GUID* clsid;
const GUID* iid;
@@ -592,6 +810,13 @@ const PublicEntry kPublicEntries[] = {
{&kGameUiClsid, &kGameUiIid, &kGameUiObj},
{&kNetworkingClsid, &kNetworkingIid, &kNetworkingObj},
{&kGameClsid, &kGameIid, &kGameObj},
{&kGameSaveClsid, &kGameSaveClsid, &kGameSaveObj},
{&kGameSaveClsid, &kGameSaveIid2, &kGameSaveObj},
{&kGameSaveClsid, &kGameSaveIid3, &kGameSaveObj},
{&kPackageClsid, &kPackageIid, &kPackageObj},
{&kPackageClsid, &kPackageIid2, &kPackageObj},
{&kPackageClsid, &kPackageIid3, &kPackageObj},
{&kPackageClsid, &kPackageIid4, &kPackageObj},
};
} // namespace
+60 -7
View File
@@ -1,8 +1,9 @@
/*
* Offline XGameSave over bottle-local storage (#468).
*
* Reached only through QueryApiImpl with the BetterXen synthetic xgamesave key; the key and
* the vtable slot order are in synthetic_keys.h. Nothing here is exported.
* Reached through QueryApiImpl. The BetterXen synthetic key and its vtable order are in
* synthetic_keys.h. Public class and interface ids use the const vtable in com_dispatch.cpp.
* Nothing here is exported.
*
* Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XGameSave members
* page and the function and structure pages it links. The signatures, the
@@ -65,6 +66,8 @@
#include "bx_log.h"
extern "C" HRESULT WINAPI XAsyncGetStatus(void* block, bool wait);
namespace bx::gdk {
namespace {
@@ -663,7 +666,10 @@ HRESULT stale_handle_error(uint32_t generation) {
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
}
// --- Slots ---
} // anonymous helpers
// Slot functions declared in runtime_internal.h. The const public vtable takes their addresses
// at static initialization.
HRESULT WINAPI initialize_provider_async(void*, void* user, const char* scid, bool /*sync_on_demand*/,
void* async) {
@@ -822,21 +828,22 @@ HRESULT WINAPI read_blob_data_async(void*, void* container, const char** names,
return begin_async_op(async, std::move(op));
}
HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, Blob* blobs, uint32_t* count) {
HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, void* blobs, uint32_t* count) {
if (!count) return E_POINTER;
*count = 0;
return consume_async_op(async, kReadBlobsOp, [&](AsyncOp& base) {
const auto& op = static_cast<const ReadBlobsOp&>(base);
if (size < op.bytes) return kProvidedBufferTooSmall;
if (op.bytes && !blobs) return E_POINTER;
op.copy_to(blobs);
op.copy_to(static_cast<Blob*>(blobs));
*count = static_cast<uint32_t>(op.found.size());
return S_OK;
});
}
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, ContainerInfoCallback callback) {
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, GameSaveContainerInfoCallback callback) {
if (!callback) return E_INVALIDARG;
const auto typed = reinterpret_cast<ContainerInfoCallback>(callback);
const auto generation = active_runtime_generation();
std::vector<ContainerData> list;
try {
@@ -860,11 +867,57 @@ HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, Co
const ContainerInfo info{data.name.c_str(), data.display_name.c_str(),
static_cast<uint32_t>(data.blobs.size()), data.total_size,
static_cast<time_t>(data.last_modified), false};
if (!callback(&info, context)) break;
if (!typed(&info, context)) break;
}
return S_OK;
}
// Synchronous public slots. Each one runs the async operation above on the process task
// queue (a null XAsyncBlock queue) and waits. syncOnDemand is passed through and has no
// effect, the same as InitializeProviderAsync. Signatures follow the public Microsoft Learn
// pages for these three functions.
struct LocalAsync {
void* queue;
void* context;
void (CALLBACK* callback)(LocalAsync*);
unsigned char internal[4 * sizeof(void*)];
};
static_assert(sizeof(LocalAsync) == 7 * sizeof(void*));
HRESULT WINAPI initialize_provider(void*, void* user, const char* scid, bool sync_on_demand, void** provider) {
if (!provider) return E_POINTER;
*provider = nullptr;
LocalAsync block{};
const auto hr = initialize_provider_async(nullptr, user, scid, sync_on_demand, &block);
if (FAILED(hr)) return hr;
const auto status = XAsyncGetStatus(&block, true);
if (FAILED(status)) return status;
return initialize_provider_result(nullptr, &block, provider);
}
HRESULT WINAPI read_blob_data(void*, void* container, const char** names, uint32_t* count, size_t size, void* blobs) {
if (!count) return E_POINTER;
const uint32_t requested = *count;
*count = 0;
LocalAsync block{};
const auto hr = read_blob_data_async(nullptr, container, names, requested, &block);
if (FAILED(hr)) return hr;
const auto status = XAsyncGetStatus(&block, true);
if (FAILED(status)) return status;
return read_blob_data_result(nullptr, &block, size, blobs, count);
}
HRESULT WINAPI submit_update(void*, void* update) {
LocalAsync block{};
const auto hr = submit_update_async(nullptr, update, &block);
if (FAILED(hr)) return hr;
const auto status = XAsyncGetStatus(&block, true);
if (FAILED(status)) return status;
return submit_update_result(nullptr, &block);
}
namespace {
// --- COM object ---
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
+93 -23
View File
@@ -1,8 +1,9 @@
/*
* Offline XPackage identity and mount queries (#468).
*
* Reached only through QueryApiImpl with the BetterXen synthetic xpackage key; the key and
* the vtable slot order are in synthetic_keys.h. Nothing here is exported.
* Reached through QueryApiImpl. The BetterXen synthetic key and its vtable order are in
* synthetic_keys.h. Public class and interface ids use the const vtable in com_dispatch.cpp.
* Nothing here is exported.
*
* Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XPackage members
* page, the pages for the functions below, and XPackageKind (enum class : uint32_t
@@ -15,9 +16,12 @@
* (lowercased), so it is stable for a directory and differs between directories.
* XPACKAGE_IDENTIFIER_MAX_LENGTH has no published value; this identifier needs 22 bytes.
* - GetPackageKind reports Game for that identifier and ERROR_NOT_FOUND for any other.
* - Mount (the documented, deprecated XPackageMount) accepts only that identifier, and the
* - Mount (the documented, deprecated XPackageMount) and its replacement
* XPackageMountWithUiAsync / XPackageMountWithUiResult accept only that identifier, and the
* mount path is the executable's directory. On Windows only content packages can be
* mounted; BetterXen allows the game's own package so titles can locate their files.
* mounted; BetterXen allows the game's own package so titles can locate their files. Offline
* there is no license or parental-consent prompt, so the asynchronous form shows no UI; an
* identifier mismatch is reported as the operation's status (ERROR_NOT_FOUND).
* - The last XGameRuntimeUninitialize closes every mount handle.
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
*/
@@ -28,6 +32,7 @@
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <memory>
#include <mutex>
#include <new>
#include <string>
@@ -97,7 +102,65 @@ HRESULT stale_handle_error(uint32_t generation) {
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
}
// --- Slots ---
// Checks that identifier names this process's package and returns its mount path in UTF-8.
HRESULT resolve_mount(const char* identifier, std::string& path) {
bool match = false;
auto hr = is_current_package(identifier, match);
if (FAILED(hr)) return hr;
if (!match) return kNotFound;
std::wstring dir;
hr = executable_directory(dir);
if (FAILED(hr)) return hr;
const int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (bytes <= 0) return HRESULT_FROM_WIN32(GetLastError());
try {
path.assign(static_cast<size_t>(bytes), '\0');
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, path.data(), bytes, nullptr, nullptr);
path.pop_back(); // The terminator is added back on copy-out.
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT insert_mount(uint32_t generation, std::string path, void** out) {
try {
std::lock_guard lock(mount_mutex);
++handle_counter;
void* handle = reinterpret_cast<void*>(kMountTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
mounts.emplace(handle, Mount{generation, std::move(path)});
*out = handle;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
return S_OK;
}
constexpr uint32_t kMountWithUiOp = 0x58504B01;
// XPackageMountWithUiAsync: the identity check runs on the work port; the Result call then
// creates the mount handle, as XPackageMount does synchronously.
class MountWithUiOp final : public AsyncOp {
public:
uint32_t generation = 0;
std::string identifier;
std::string path;
uint32_t kind() const override { return kMountWithUiOp; }
HRESULT execute() override { return resolve_mount(identifier.c_str(), path); }
size_t result_size() const override { return sizeof(void*); }
};
} // anonymous helpers
// Slot functions declared in runtime_internal.h. The const public vtable takes their addresses
// at static initialization.
bool WINAPI is_packaged_process(void*) {
if (!active_runtime_generation()) return false;
char id[kIdBytes];
return SUCCEEDED(current_identifier(id));
}
HRESULT WINAPI get_current_process_package_identifier(void*, size_t size, char* buffer) {
if (!buffer) return E_POINTER;
@@ -128,29 +191,34 @@ HRESULT WINAPI mount(void*, const char* identifier, void** out) {
if (!identifier) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!generation) return kRuntimeNotInitialized;
bool match = false;
auto hr = is_current_package(identifier, match);
if (FAILED(hr)) return hr;
if (!match) return kNotFound;
std::string path;
const auto hr = resolve_mount(identifier, path);
return FAILED(hr) ? hr : insert_mount(generation, std::move(path), out);
}
std::wstring dir;
hr = executable_directory(dir);
if (FAILED(hr)) return hr;
const int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (bytes <= 0) return HRESULT_FROM_WIN32(GetLastError());
HRESULT WINAPI mount_with_ui_async(void*, const char* identifier, void* async) {
if (!async) return E_POINTER;
if (!identifier) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!generation) return kRuntimeNotInitialized;
std::unique_ptr<MountWithUiOp> op(new (std::nothrow) MountWithUiOp);
if (!op) return E_OUTOFMEMORY;
try {
std::string path(static_cast<size_t>(bytes), '\0');
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, path.data(), bytes, nullptr, nullptr);
path.pop_back(); // The terminator is added back on copy-out.
std::lock_guard lock(mount_mutex);
++handle_counter;
void* handle = reinterpret_cast<void*>(kMountTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
mounts.emplace(handle, Mount{generation, std::move(path)});
*out = handle;
op->identifier = identifier;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
return S_OK;
op->generation = generation;
return begin_async_op(async, std::move(op));
}
HRESULT WINAPI mount_with_ui_result(void*, void* async, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
return consume_async_op(async, kMountWithUiOp, [&](AsyncOp& base) {
auto& op = static_cast<MountWithUiOp&>(base);
return insert_mount(op.generation, op.path, out);
});
}
HRESULT WINAPI get_mount_path_size(void*, void* handle, size_t* size) {
@@ -180,6 +248,8 @@ void WINAPI close_mount_handle(void*, void* handle) {
mounts.erase(handle);
}
namespace {
// --- COM object ---
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
+34
View File
@@ -72,4 +72,38 @@ extern const void* const package_object; // package.cpp
void release_game_save_state(); // game_save.cpp
void release_package_state(); // package.cpp
// XGameSave and XPackage slots shared by the synthetic objects and the const public vtables
// in com_dispatch.cpp. C++ linkage only. The DLL export list does not include them.
// The container-info callback receives the public XGameSaveContainerInfo layout.
using GameSaveContainerInfoCallback = bool(CALLBACK*)(const void* info, void* context);
HRESULT WINAPI initialize_provider(void* self, void* user, const char* scid, bool sync_on_demand, void** provider);
HRESULT WINAPI initialize_provider_async(void* self, void* user, const char* scid, bool sync_on_demand, void* async);
HRESULT WINAPI initialize_provider_result(void* self, void* async, void** provider);
void WINAPI close_provider(void* self, void* provider);
HRESULT WINAPI create_container(void* self, void* provider, const char* name, void** out);
void WINAPI close_container(void* self, void* container);
HRESULT WINAPI enumerate_container_info(void* self, void* provider, void* context,
GameSaveContainerInfoCallback callback);
HRESULT WINAPI read_blob_data(void* self, void* container, const char** names, uint32_t* count, size_t size,
void* blobs);
HRESULT WINAPI read_blob_data_async(void* self, void* container, const char** names, uint32_t count, void* async);
HRESULT WINAPI read_blob_data_result(void* self, void* async, size_t size, void* blobs, uint32_t* count);
HRESULT WINAPI create_update(void* self, void* container, const char* display_name, void** out);
void WINAPI close_update(void* self, void* update);
HRESULT WINAPI submit_blob_write(void* self, void* update, const char* blob_name, const uint8_t* data, size_t size);
HRESULT WINAPI submit_update(void* self, void* update);
HRESULT WINAPI submit_update_async(void* self, void* update, void* async);
HRESULT WINAPI submit_update_result(void* self, void* async);
bool WINAPI is_packaged_process(void* self);
HRESULT WINAPI get_current_process_package_identifier(void* self, size_t size, char* buffer);
HRESULT WINAPI get_package_kind(void* self, const char* identifier, uint32_t* kind);
HRESULT WINAPI mount(void* self, const char* identifier, void** out);
HRESULT WINAPI mount_with_ui_async(void* self, const char* identifier, void* async);
HRESULT WINAPI mount_with_ui_result(void* self, void* async, void** out);
HRESULT WINAPI get_mount_path_size(void* self, void* handle, size_t* size);
HRESULT WINAPI get_mount_path(void* self, void* handle, size_t size, char* path);
void WINAPI close_mount_handle(void* self, void* handle);
} // namespace bx::gdk
+4 -2
View File
@@ -6,8 +6,10 @@
* These class and interface ids are defined by BetterXen. They are NOT Microsoft
* identifiers and were not derived from any Microsoft binary. A title linked against
* Microsoft's xgameruntime.lib will not request them. They let BetterXen's own callers
* and conformance fixtures reach the offline families through QueryApiImpl until a
* properly sourced mapping exists. To replace a family's keys, change its entry here and
* and conformance fixtures reach the offline families through QueryApiImpl. The public
* class and interface ids for XGameSave and XPackage are registered separately in
* com_dispatch.cpp. These synthetic keys stay so the fixtures below keep working.
* To replace a family's keys, change its entry here and
* the expected values in the fixtures listed below. The fixtures keep their own copies on
* purpose, so a wrong key here fails a test instead of agreeing with itself:
* tests/conformance/test_xgameruntime/main.cpp (all families)
+67 -4
View File
@@ -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;
}
+16
View File
@@ -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);
}
}
+2
View File
@@ -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) {
+104 -1
View File
@@ -3,6 +3,8 @@
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <thread>
extern "C" {
@@ -31,7 +33,64 @@ namespace {
void WINAPI dummy_device_callback(uint64_t, void*, void*, uint64_t, uint32_t, uint32_t) {}
} // 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 count reached zero,
// not that the object was freed. Removing `delete this` would leave the
// count correct while leaking, so this assertion is what catches it.
// `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. This works whether the log path came from the runner or from
// the temp file the fixture creates below.
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() {
// `bx-cli run` sets BX_LOG_FILE for the guest. When the fixture is
// run directly there is no such variable, so create a temp log and
// point the shim at it; otherwise the assertions below would read an
// empty file and fail for the wrong reason.
char log_path[MAX_PATH]{};
DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
if (n == 0 || n >= sizeof(log_path)) {
char temp_dir[MAX_PATH]{};
CHECK(GetTempPathA(sizeof(temp_dir), temp_dir) > 0);
CHECK(GetTempFileNameA(temp_dir, "bxg", 0, log_path) != 0);
CHECK(SetEnvironmentVariableA("BX_LOG_FILE", log_path));
}
const uint64_t log_start = log_file_size(log_path);
void* object = nullptr;
CHECK(AcpHalCreate(&object) == S_OK && object);
auto* hal = static_cast<IUnknown*>(object);
@@ -186,8 +245,52 @@ 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);
// The live-dispatcher count is the only observable evidence that the
// dispatcher was destroyed: `Release` returning 0 proves the count, not
// the deallocation. `dispatch_mode` logs `mode=manual live_dispatchers=N`
// on every transition, so a `delete this` removal that leaks the object
// would leave `live_dispatchers=1` behind and fail here.
{
const std::string log = read_log_file_from(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");
}
@@ -0,0 +1,4 @@
# M2-C1 (#464): D3D12ConfigureVirtualMemoryX plus placed buffer and RGBA8 texture readback.
add_executable(test_d3d12_placed main.cpp)
target_include_directories(test_d3d12_placed PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_d3d12_placed PRIVATE d3d12_xs xmem bx_runtime_veh kernel32)
File diff suppressed because it is too large. Load diff
+77 -1
View File
@@ -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,10 @@
# M2 Shader Format Gate (#466): Create*PipelineState through d3d12_xs.dll with DXIL, ACCC-only and
# constraint-carrying shaders. Needs bx_shader_bridge.dll (shader-transpiler/crates/dxbc-accc/guest/build.sh,
# #445) next to the shims at run time. The DXIL blobs are existing DXC 1.9.2609 outputs in the tree.
add_executable(test_shader_gate main.cpp)
target_include_directories(test_shader_gate PRIVATE
"${BX_ABI_INCLUDE_DIR}"
"${BX_ROOT_DIR}/shader-transpiler/crates/d3dmetal-harness/probe/shaders"
"${BX_ROOT_DIR}/tests/conformance/test_d3dmetal_gpu_limits/shaders"
)
target_link_libraries(test_shader_gate PRIVATE d3d12_xs kernel32)
+612
View File
@@ -0,0 +1,612 @@
/*
* M2 Shader Format Gate (#466): synthetic conformance test for the PSO hook in d3d12_xs.dll.
*
* Through D3D12XboxCreateDevice it:
* 1. creates a compute PSO from a real DXC 1.9.2609 SM 6.6 DXIL blob (fill_cs66, from
* d3dmetal-harness), dispatches it and checks all 256 output words on the CPU;
* 2. submits a synthetic ACCC-only container (BetterXen FSPX v1, compute) to
* CreateComputePipelineState and to CreateGraphicsPipelineState and requires E_NOTIMPL
* 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.
*
* 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.
*
* Expected values come from the D3D12 contract, the DXBC layout and the documented kernel, not
* from the shim. Needs bx_shader_bridge.dll next to the shims and BX_LOG_FILE (bx-cli --log).
* It also checks that the bridge was loaded from d3d12_xs.dll's directory; run it with the EXE
* in a different directory from the shims to exercise that lookup.
*/
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
#endif
#include <windows.h>
#include <unknwn.h>
#include <d3d12.h>
#include <climits>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <string>
#include <vector>
#include "atomic64_image.h" // g_atomic64_image_cs, #453
#include "fill_cs66.h" // g_fill_cs66, d3dmetal-harness
#include "wave64_lanes.h" // g_wave64_lanes_cs, #453
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12SerializeVersionedRootSignature(
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error);
namespace {
int g_checks = 0;
int g_failures = 0;
__attribute__((format(gnu_printf, 2, 3)))
bool check(bool ok, const char* fmt, ...) {
++g_checks;
if (!ok) {
++g_failures;
char msg[320];
va_list ap;
va_start(ap, fmt);
std::vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
std::fprintf(stderr, "FAIL: %s\n", msg);
std::fflush(stderr);
}
return ok;
}
unsigned long ul(HRESULT hr) { return static_cast<unsigned long>(hr); }
int finish() {
if (g_failures) {
std::fprintf(stderr, "FAIL: test_shader_gate (%d of %d checks failed)\n", g_failures, g_checks);
return 1;
}
std::printf("PASS: test_shader_gate (%d checks)\n", g_checks);
return 0;
}
/* The kernel in fill_cs66.hlsl: Out[i] = hash(i) for 4 groups of 64 threads. */
constexpr uint32_t kWords = 256;
uint32_t expected_word(uint32_t i) {
uint32_t v = i * 0x9E3779B1u;
v ^= v >> 15;
return v + 0x01234567u;
}
void put32(std::vector<uint8_t>& out, size_t at, uint32_t value) { std::memcpy(out.data() + at, &value, 4); }
/* A DXBC container (version 1) holding one ACCC chunk with a BetterXen FSPX v1 table whose only
* section is the stage configuration: compute, shader model 6.0. No DXIL. */
std::vector<uint8_t> accc_only_container() {
std::vector<uint8_t> fspx(40, 0);
std::memcpy(fspx.data(), "FSPX", 4);
put32(fspx, 4, 1); // version
put32(fspx, 8, 1); // section count
put32(fspx, 16, 1); // section id 1: stage configuration
put32(fspx, 20, 28); // offset
put32(fspx, 24, 12); // size
put32(fspx, 28, 6); // stage: compute
put32(fspx, 32, 6); // shader model 6.0
put32(fspx, 36, 0);
const uint32_t total = 32 + 4 + 8 + static_cast<uint32_t>(fspx.size());
std::vector<uint8_t> out(total, 0);
std::memcpy(out.data(), "DXBC", 4);
put32(out, 20, 1);
put32(out, 24, total);
put32(out, 28, 1);
put32(out, 32, 36);
std::memcpy(out.data() + 36, "ACCC", 4);
put32(out, 40, static_cast<uint32_t>(fspx.size()));
std::memcpy(out.data() + 44, fspx.data(), fspx.size());
return out;
}
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* file = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
std::fclose(file);
}
return text;
}
/* True when one JSONL line holds every needle. */
bool log_has(const std::string& log, std::initializer_list<const char*> needles) {
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);
bool all = true;
for (const char* needle : needles) all = all && line.find(needle) != std::string::npos;
if (all) return true;
start = end + 1;
}
return false;
}
ID3D12RootSignature* make_root(ID3D12Device* device, const D3D12_ROOT_PARAMETER& param) {
D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = {};
desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
desc.Desc_1_0.NumParameters = 1;
desc.Desc_1_0.pParameters = &param;
ID3DBlob* blob = nullptr;
ID3DBlob* error = nullptr;
HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &blob, &error);
if (error) error->Release();
if (!check(SUCCEEDED(hr) && blob, "D3D12SerializeVersionedRootSignature hr=0x%08lx", ul(hr))) return nullptr;
ID3D12RootSignature* root = nullptr;
hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), __uuidof(ID3D12RootSignature),
reinterpret_cast<void**>(&root));
blob->Release();
check(SUCCEEDED(hr) && root, "CreateRootSignature hr=0x%08lx", ul(hr));
return root;
}
ID3D12Resource* make_buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_FLAGS flags,
D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES props = {};
props.Type = heap;
D3D12_RESOURCE_DESC desc = {};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = kWords * 4;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
desc.Flags = flags;
ID3D12Resource* buffer = nullptr;
const HRESULT hr = device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&buffer));
check(SUCCEEDED(hr) && buffer, "CreateCommittedResource heap=%d hr=0x%08lx", static_cast<int>(heap), ul(hr));
return buffer;
}
HRESULT create_compute(ID3D12Device* device, ID3D12RootSignature* root, const void* code, size_t size,
ID3D12PipelineState** pso) {
D3D12_COMPUTE_PIPELINE_STATE_DESC desc = {};
desc.pRootSignature = root;
desc.CS.pShaderBytecode = code;
desc.CS.BytecodeLength = size;
*pso = nullptr;
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 = {};
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
ID3D12CommandQueue* queue = nullptr;
ID3D12CommandAllocator* allocator = nullptr;
ID3D12GraphicsCommandList* list = nullptr;
ID3D12Fence* fence = nullptr;
HRESULT hr = device->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&queue));
if (!check(SUCCEEDED(hr), "CreateCommandQueue hr=0x%08lx", ul(hr))) return;
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
reinterpret_cast<void**>(&allocator));
if (check(SUCCEEDED(hr), "CreateCommandAllocator hr=0x%08lx", ul(hr))) {
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, pso,
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
check(SUCCEEDED(hr), "CreateCommandList hr=0x%08lx", ul(hr));
}
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
check(SUCCEEDED(hr), "CreateFence hr=0x%08lx", ul(hr));
ID3D12Resource* out = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
ID3D12Resource* readback =
make_buffer(device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST);
if (list && fence && out && readback) {
list->SetComputeRootSignature(root);
list->SetComputeRootUnorderedAccessView(0, out->GetGPUVirtualAddress());
list->Dispatch(kWords / 64, 1, 1);
D3D12_RESOURCE_BARRIER barrier = {};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition.pResource = out;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
list->ResourceBarrier(1, &barrier);
list->CopyResource(readback, out);
hr = list->Close();
check(SUCCEEDED(hr), "Close hr=0x%08lx", ul(hr));
ID3D12CommandList* lists[] = {list};
queue->ExecuteCommandLists(1, lists);
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
check(SUCCEEDED(queue->Signal(fence, 1)), "Signal");
if (fence->GetCompletedValue() < 1) {
check(SUCCEEDED(fence->SetEventOnCompletion(1, done)), "SetEventOnCompletion");
check(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "fence did not complete within 10 s");
}
CloseHandle(done);
check(fence->GetCompletedValue() != UINT64_MAX, "device removed (fence value UINT64_MAX)");
void* mapped = nullptr;
D3D12_RANGE range = {0, kWords * 4};
hr = readback->Map(0, &range, &mapped);
if (check(SUCCEEDED(hr) && mapped, "Map hr=0x%08lx", ul(hr))) {
const auto* words = static_cast<const uint32_t*>(mapped);
uint32_t mismatched = 0, first = kWords;
for (uint32_t i = 0; i < kWords; ++i) {
if (words[i] != expected_word(i)) {
if (!mismatched) first = i;
++mismatched;
}
}
check(mismatched == 0, "DXIL readback: %u of %u words wrong (first %u: got 0x%08x want 0x%08x)",
mismatched, kWords, first, first < kWords ? words[first] : 0u,
first < kWords ? expected_word(first) : 0u);
D3D12_RANGE none = {0, 0};
readback->Unmap(0, &none);
if (!mismatched) std::printf("dxil: %u/%u words verified\n", kWords, kWords);
}
}
if (readback) readback->Release();
if (out) out->Release();
if (fence) fence->Release();
if (list) list->Release();
if (allocator) allocator->Release();
if (queue) queue->Release();
}
std::wstring directory_of(const wchar_t* path) {
const std::wstring text(path);
return text.substr(0, text.find_last_of(L'\\'));
}
/* --no-bridge: run from a directory that holds d3d12_xs.dll and its BetterXen imports but no
* bx_shader_bridge.dll. DXIL must still run and ACCC-only must still be refused. */
int no_bridge_main() {
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "no-bridge: D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
D3D12_ROOT_PARAMETER uav = {};
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
uav.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
ID3D12RootSignature* root = make_root(device, uav);
if (!root) return finish();
ID3D12PipelineState* pso = nullptr;
hr = create_compute(device, root, g_fill_cs66, sizeof(g_fill_cs66), &pso);
check(SUCCEEDED(hr) && pso, "no-bridge: DXIL CreateComputePipelineState hr=0x%08lx", ul(hr));
if (pso) {
run_dxil(device, root, pso);
pso->Release();
}
check(GetModuleHandleW(L"bx_shader_bridge.dll") == nullptr, "no-bridge: a bx_shader_bridge.dll was loaded anyway");
const std::vector<uint8_t> accc = accc_only_container();
hr = create_compute(device, root, accc.data(), accc.size(), &pso);
check(hr == E_NOTIMPL && !pso, "no-bridge: ACCC-only compute hr=0x%08lx (want E_NOTIMPL)", ul(hr));
if (pso) pso->Release();
D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics = {};
graphics.pRootSignature = root;
graphics.VS.pShaderBytecode = accc.data();
graphics.VS.BytecodeLength = accc.size();
graphics.SampleMask = UINT_MAX;
graphics.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
graphics.SampleDesc.Count = 1;
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();
}
/* Copies this EXE and d3d12_xs.dll's directory minus the bridge into a scratch directory, runs
* the copy with --no-bridge, and requires it to pass. */
void run_no_bridge_child() {
wchar_t exe[MAX_PATH] = {}, shim[MAX_PATH] = {}, temp[MAX_PATH] = {};
GetModuleFileNameW(nullptr, exe, MAX_PATH);
GetModuleFileNameW(GetModuleHandleW(L"d3d12_xs.dll"), shim, MAX_PATH);
GetTempPathW(MAX_PATH, temp);
wchar_t dir[MAX_PATH];
std::swprintf(dir, MAX_PATH, L"%lsbx_shader_gate_nobridge_%lu", temp, GetCurrentProcessId());
if (!check(CreateDirectoryW(dir, nullptr) || GetLastError() == ERROR_ALREADY_EXISTS,
"no-bridge: cannot create %ls", dir)) {
return;
}
const std::wstring from = directory_of(shim);
const std::wstring to(dir);
const wchar_t* files[] = {L"d3d12_xs.dll", L"xmem.dll", L"bx_runtime_veh.dll"};
bool copied = CopyFileW(exe, (to + L"\\test_shader_gate.exe").c_str(), FALSE) != 0;
for (const wchar_t* name : files) {
copied = copied && CopyFileW((from + L"\\" + name).c_str(), (to + L"\\" + name).c_str(), FALSE) != 0;
}
if (check(copied, "no-bridge: copying the shims to %ls failed (error %lu)", dir, GetLastError())) {
std::wstring command = L"\"" + to + L"\\test_shader_gate.exe\" --no-bridge";
STARTUPINFOW startup = {};
startup.cb = sizeof(startup);
PROCESS_INFORMATION child = {};
if (check(CreateProcessW(nullptr, command.data(), nullptr, nullptr, FALSE, 0, nullptr, dir, &startup, &child),
"no-bridge: CreateProcessW error %lu", GetLastError())) {
DWORD code = 99;
check(WaitForSingleObject(child.hProcess, 60000) == WAIT_OBJECT_0, "no-bridge: child did not finish in 60 s");
GetExitCodeProcess(child.hProcess, &code);
check(code == 0, "no-bridge: child exited %lu (a crash shows as an exception code)", code);
CloseHandle(child.hThread);
CloseHandle(child.hProcess);
}
}
DeleteFileW((to + L"\\test_shader_gate.exe").c_str());
for (const wchar_t* name : files) DeleteFileW((to + L"\\" + name).c_str());
RemoveDirectoryW(dir);
}
} // namespace
int main() {
if (std::wcsstr(GetCommandLineW(), L" --no-bridge")) return no_bridge_main();
// Self-check of the reference against values computed independently for d3dmetal-harness.
check(expected_word(0) == 0x01234567u && expected_word(1) == 0x9f598b46u && expected_word(255) == 0x9a664b32u,
"expected_word reference values");
if (!check(GetEnvironmentVariableA("BX_LOG_FILE", nullptr, 0) > 0,
"BX_LOG_FILE is not set; run through bx-cli run --log")) {
return finish();
}
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
D3D12_ROOT_PARAMETER uav = {};
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
uav.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
ID3D12RootSignature* root_uav = make_root(device, uav);
D3D12_DESCRIPTOR_RANGE range = {};
range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
range.NumDescriptors = 1;
D3D12_ROOT_PARAMETER table = {};
table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
table.DescriptorTable.NumDescriptorRanges = 1;
table.DescriptorTable.pDescriptorRanges = &range;
table.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
ID3D12RootSignature* root_table = make_root(device, table);
if (!root_uav || !root_table) return finish();
// 1. DXIL passes the gate and runs.
ID3D12PipelineState* pso = nullptr;
hr = create_compute(device, root_uav, g_fill_cs66, sizeof(g_fill_cs66), &pso);
check(SUCCEEDED(hr) && pso, "DXIL SM 6.6 CreateComputePipelineState hr=0x%08lx", ul(hr));
const HMODULE bridge = GetModuleHandleW(L"bx_shader_bridge.dll");
if (!check(bridge != nullptr,
"bx_shader_bridge.dll was not loaded beside d3d12_xs.dll: scripts/build-shims.sh stages it in "
"build-shims/bin (#484)")) {
if (pso) pso->Release();
return finish();
}
// The shim must find the bridge beside itself, not through the EXE's directory (crate README).
wchar_t bridge_path[MAX_PATH] = {}, shim_path[MAX_PATH] = {};
GetModuleFileNameW(bridge, bridge_path, MAX_PATH);
GetModuleFileNameW(GetModuleHandleW(L"d3d12_xs.dll"), shim_path, MAX_PATH);
const auto dir_of = [](std::wstring path) { return path.substr(0, path.find_last_of(L'\\')); };
check(_wcsicmp(dir_of(bridge_path).c_str(), dir_of(shim_path).c_str()) == 0,
"bx_shader_bridge.dll was loaded from %ls, not beside d3d12_xs.dll (%ls)", bridge_path, shim_path);
if (pso) {
run_dxil(device, root_uav, pso);
pso->Release();
}
// 2. An ACCC-only container is refused, for compute and graphics, without a host object.
const std::vector<uint8_t> accc = accc_only_container();
hr = create_compute(device, root_uav, accc.data(), accc.size(), &pso);
check(hr == E_NOTIMPL && !pso, "ACCC-only compute PSO: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr),
static_cast<void*>(pso));
if (pso) pso->Release();
D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics = {};
graphics.pRootSignature = root_uav;
graphics.VS.pShaderBytecode = accc.data();
graphics.VS.BytecodeLength = accc.size();
graphics.SampleMask = UINT_MAX;
graphics.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
graphics.SampleDesc.Count = 1;
hr = device->CreateGraphicsPipelineState(&graphics, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
check(hr == E_NOTIMPL && !pso, "ACCC-only graphics VS: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr),
static_cast<void*>(pso));
if (pso) pso->Release();
// The device is still usable after a refusal.
hr = create_compute(device, root_uav, g_fill_cs66, sizeof(g_fill_cs66), &pso);
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);
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));
if (pso) pso->Release();
// 4. Without the bridge (a separate process from a directory without it).
run_no_bridge_child();
// 5. The JSONL records.
const std::string log = read_log();
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",
fill_bytes, "atomic64= ", "wave_lanes=0-4294967295"}),
"shader_gate record for the DXIL SM 6.6 compute shader");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=reject_accc_only", "hr=0x80004001",
"kind=accc_only", "sm=6.0"}),
"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\"", "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,"}),
"shader_gate record with 64-bit typed atomics");
check(log_has(log, {"\"event\":\"shader_d3dmetal_gap\"", "atomic64_flags=0x400000"}),
"shader_d3dmetal_gap record for 64-bit typed atomics");
check(log_has(log, {"\"event\":\"shader_bridge_missing\"", "not found beside d3d12_xs.dll"}),
"shader_bridge_missing record from the no-bridge child");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=reject_accc_only_unclassified",
"hr=0x80004001"}),
"no-bridge child refused the ACCC-only compute shader");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=graphics", "decision=reject_accc_only_unclassified"}),
"no-bridge child refused the ACCC-only vertex shader");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=pass_unclassified"}),
"no-bridge child passed DXIL unclassified");
root_table->Release();
root_uav->Release();
device->Release();
return finish();
}
+26 -1
View File
@@ -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;
}
@@ -1,17 +1,23 @@
/*
* #457: clean-room synthetic test for system32 shim staging by `bx-cli run`.
* #457 / #482: clean-room synthetic test for system32 shim staging by `bx-cli run`.
*
* GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll", NULL,
* GDK titles load `xgameruntime.dll` and `GameInput.dll` with LoadLibraryExW(...,
* LOAD_LIBRARY_SEARCH_SYSTEM32), which does not search WINEPATH or the executable's folder.
* This test makes that load and requires that BetterXen's shim answers it:
* - the module loads, from a path under system32;
* - it exports QueryApiImpl (a BetterXen xgameruntime export, absent from Wine builtins);
* - LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR gives the same module.
* In addition, Wine pre-populates `system32\gameinput.dll` with a builtin stub whose
* `GameInputCreate` returns E_NOTIMPL.
*
* `--expect-missing` is the negative control for an unstaged prefix: the load must fail.
* This test makes both loads and requires that BetterXen's shims answer them:
* - xgameruntime.dll loads from system32, exports QueryApiImpl, and matches
* LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR;
* - GameInput.dll loads from system32, exports GameInputCreate (@1 and by name), and
* GameInputCreate(&input) returns S_OK with a valid IUnknown pointer.
*
* `--expect-missing` is the negative control for an unstaged prefix: xgameruntime.dll must
* fail to load, and GameInput.dll must either fail to load or fail GameInputCreate (Wine stub).
* Exit 0 on pass, 1 on failure.
*/
#include <windows.h>
#include <unknwn.h>
#include <cstdio>
#include <cstring>
@@ -33,13 +39,13 @@ bool check(bool ok, const char* what) {
return ok;
}
bool path_in_system32(HMODULE m) {
bool path_in_system32(HMODULE m, const wchar_t* needle) {
wchar_t path[MAX_PATH * 2] = {};
const DWORD n = GetModuleFileNameW(m, path, MAX_PATH * 2);
if (n == 0 || n >= MAX_PATH * 2) return false;
for (DWORD i = 0; i < n; ++i) path[i] = static_cast<wchar_t>(towlower(path[i]));
std::printf("INFO: loaded from %ls\n", path);
return std::wcsstr(path, L"\\windows\\system32\\xgameruntime.dll") != nullptr;
return std::wcsstr(path, needle) != nullptr;
}
} // namespace
@@ -49,16 +55,57 @@ int main(int argc, char** argv) {
HMODULE sys = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (expect_missing) {
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 load fails");
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 xgameruntime.dll load fails");
if (sys) FreeLibrary(sys);
} else if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) {
check(path_in_system32(sys), "module path is under system32");
check(GetProcAddress(sys, "QueryApiImpl") != nullptr, "module exports QueryApiImpl (BetterXen shim)");
HMODULE both = LoadLibraryExW(L"xgameruntime.dll", nullptr,
LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR);
check(both == sys, "SYSTEM32 | APPLICATION_DIR search returns the same module");
if (both) FreeLibrary(both);
FreeLibrary(sys);
HMODULE gi = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
bool gi_unusable = (gi == nullptr);
if (gi) {
using CreateFn = HRESULT (WINAPI*)(void**);
auto fn = reinterpret_cast<CreateFn>(
reinterpret_cast<void*>(GetProcAddress(gi, "GameInputCreate")));
void* obj = nullptr;
HRESULT hr = fn ? fn(&obj) : E_FAIL;
if (SUCCEEDED(hr) && obj) {
static_cast<IUnknown*>(obj)->Release();
} else {
gi_unusable = true;
}
FreeLibrary(gi);
}
check(gi_unusable, "unstaged: GameInput.dll is absent or Wine stub returns failure");
} else {
if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) {
check(path_in_system32(sys, L"\\windows\\system32\\xgameruntime.dll"),
"xgameruntime.dll module path is under system32");
check(GetProcAddress(sys, "QueryApiImpl") != nullptr,
"module exports QueryApiImpl (BetterXen shim)");
HMODULE both = LoadLibraryExW(
L"xgameruntime.dll", nullptr,
LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR);
check(both == sys, "SYSTEM32 | APPLICATION_DIR search returns the same module");
if (both) FreeLibrary(both);
FreeLibrary(sys);
}
HMODULE gi = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (check(gi != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads GameInput.dll")) {
check(path_in_system32(gi, L"\\windows\\system32\\gameinput.dll"),
"GameInput.dll module path is under system32");
FARPROC ord1 = GetProcAddress(gi, MAKEINTRESOURCEA(1));
FARPROC named = GetProcAddress(gi, "GameInputCreate");
check(ord1 != nullptr && ord1 == named,
"GameInput.dll exports GameInputCreate at ordinal 1");
using CreateFn = HRESULT (WINAPI*)(void**);
auto create = reinterpret_cast<CreateFn>(reinterpret_cast<void*>(named));
void* input = nullptr;
HRESULT hr = create ? create(&input) : E_FAIL;
if (check(hr == S_OK && input != nullptr,
"GameInputCreate returns S_OK (BetterXen shim, not Wine builtin stub)")) {
static_cast<IUnknown*>(input)->Release();
}
FreeLibrary(gi);
}
}
std::printf("SUMMARY: %d checks, %d failed\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 1;
@@ -0,0 +1,3 @@
add_executable(test_veh_amd_only main.cpp)
target_include_directories(test_veh_amd_only PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_veh_amd_only PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,251 @@
// Synthetic Windows x64 fixture for the Rosetta exception path. Expectations
// come from the AMD APM vol. 3 (24594, rev. 3.36), CLZERO, MONITORX, MWAITX,
// and RDPRU, and vol. 4 (26568, rev. 3.25), EXTRQ and INSERTQ.
#include <windows.h>
#include <cpuid.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
namespace {
unsigned failures = 0;
unsigned checks = 0;
void expect(bool passed, const char* name) {
++checks;
if (passed) {
std::printf("ok: %s\n", name);
} else {
std::fprintf(stderr, "FAIL: %s\n", name);
++failures;
}
}
bool equals(const uint8_t* bytes, size_t count, uint8_t value) {
for (size_t index = 0; index < count; ++index) {
if (bytes[index] != value) {
return false;
}
}
return true;
}
void clzero(uintptr_t address) {
__asm__ volatile(".byte 0x0f, 0x01, 0xfc" :: "a"(address) : "memory");
}
void check_cache_lines() {
alignas(64) uint8_t lines[192];
std::memset(lines, 0xA5, sizeof(lines));
clzero(reinterpret_cast<uintptr_t>(lines + 127));
expect(equals(lines + 64, 64, 0), "CLZERO clears the selected 64 bytes");
expect(equals(lines, 64, 0xA5) && equals(lines + 128, 64, 0xA5),
"CLZERO preserves both adjacent cache lines");
std::memset(lines, 0xA5, sizeof(lines));
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfc" :: "a"(lines + 79) : "memory");
expect(equals(lines + 64, 64, 0) && equals(lines, 64, 0xA5) &&
equals(lines + 128, 64, 0xA5), "CLZERO accepts a redundant REX.W");
}
void check_address_override() {
uint8_t* page = nullptr;
for (uintptr_t address = 0x10000000; address < 0x70000000; address += 0x10000000) {
page = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(address), 4096,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (page) {
break;
}
}
expect(page != nullptr, "allocate a page below 4 GiB for address-size coverage");
if (!page) {
return;
}
std::memset(page, 0x6C, 192);
const uint64_t address = 0x1234567800000000ULL | reinterpret_cast<uintptr_t>(page + 75);
__asm__ volatile(".byte 0x67, 0x0f, 0x01, 0xfc" :: "a"(address) : "memory");
expect(equals(page + 64, 64, 0) && equals(page, 64, 0x6C) && equals(page + 128, 64, 0x6C),
"CLZERO address-size override selects EAX and resumes after four bytes");
__asm__ volatile(".byte 0x67, 0x0f, 0x01, 0xfa"
:: "a"(address), "c"(0), "d"(0) : "memory");
expect(page[75] == 0, "MONITORX with an address-size override resumes after four bytes");
VirtualFree(page, 0, MEM_RELEASE);
}
struct WriteFault {
uint8_t* page = nullptr;
unsigned hits = 0;
DWORD code = 0;
ULONG_PTR operation = 0;
ULONG_PTR address = 0;
};
WriteFault fault;
LONG CALLBACK retry_cache_line_store(EXCEPTION_POINTERS* pointers) {
const EXCEPTION_RECORD& record = *pointers->ExceptionRecord;
if (record.ExceptionCode != EXCEPTION_ACCESS_VIOLATION &&
record.ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
return EXCEPTION_CONTINUE_SEARCH;
}
++fault.hits;
fault.code = record.ExceptionCode;
if (record.NumberParameters >= 2) {
fault.operation = record.ExceptionInformation[0];
fault.address = record.ExceptionInformation[1];
}
// Repair the page and retry at the original guest instruction.
DWORD previous = 0;
if (fault.hits == 1 && VirtualProtect(fault.page, 4096, PAGE_READWRITE, &previous)) {
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
void check_write_fault() {
fault.page = static_cast<uint8_t*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE));
expect(fault.page != nullptr, "allocate the CLZERO write-fault page");
if (!fault.page) {
return;
}
std::memset(fault.page, 0xA5, 192);
DWORD previous = 0;
if (!VirtualProtect(fault.page, 4096, PAGE_READONLY, &previous)) {
expect(false, "protect the CLZERO write-fault page");
VirtualFree(fault.page, 0, MEM_RELEASE);
return;
}
PVOID handler = AddVectoredExceptionHandler(0, retry_cache_line_store);
expect(handler != nullptr, "install the guest write-fault handler");
if (handler) {
clzero(reinterpret_cast<uintptr_t>(fault.page + 99));
RemoveVectoredExceptionHandler(handler);
expect(fault.hits == 1 && fault.code == EXCEPTION_ACCESS_VIOLATION &&
fault.operation == 1 && fault.address == reinterpret_cast<uintptr_t>(fault.page + 64),
"CLZERO dispatches a write access violation at the cache-line address");
expect(equals(fault.page + 64, 64, 0) && equals(fault.page, 64, 0xA5) &&
equals(fault.page + 128, 64, 0xA5), "CLZERO retries after the guest repairs the page");
}
VirtualFree(fault.page, 0, MEM_RELEASE);
}
void check_wait_instructions() {
alignas(64) uint64_t word = 0;
__asm__ volatile(".byte 0x0f, 0x01, 0xfa" :: "a"(&word), "c"(0), "d"(0) : "memory");
__asm__ volatile(".byte 0x0f, 0x01, 0xfb" :: "a"(0xF0), "b"(1024), "c"(2) : "memory");
expect(word == 0, "MONITORX and MWAITX return and preserve the watched value");
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfa"
:: "a"(&word), "c"(0), "d"(0) : "memory");
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfb"
:: "a"(0xF0), "b"(1024), "c"(2) : "memory");
expect(word == 0, "MONITORX and MWAITX also return with redundant REX.W");
}
uint64_t read_processor_register(uint32_t selector) {
uint64_t low;
uint64_t high;
__asm__ volatile(".byte 0x0f, 0x01, 0xfd" : "=a"(low), "=d"(high) : "c"(selector) : "cc");
return (high << 32) | low;
}
void check_processor_registers() {
const uint64_t mperf = read_processor_register(0);
const uint64_t aperf = read_processor_register(1);
expect(mperf != 0 && read_processor_register(0) >= mperf, "RDPRU reports a plausible MPERF");
expect(aperf != 0 && read_processor_register(1) >= aperf, "RDPRU reports a plausible APERF");
expect(read_processor_register(UINT32_MAX) == 0, "RDPRU returns zero for an unknown selector");
uint32_t low;
uint32_t high;
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfd"
: "=a"(low), "=d"(high) : "c"(1) : "cc");
expect((low | high) != 0, "RDPRU accepts a redundant REX.W");
uint64_t flags;
__asm__ volatile("pushfq\n\t"
"orq $0x8d5, (%%rsp)\n\t"
"popfq\n\t"
".byte 0x0f, 0x01, 0xfd\n\t"
"pushfq\n\t"
"popq %0"
: "=r"(flags) : "c"(0) : "rax", "rdx", "cc", "memory");
expect((flags & 0x8D4) == 0, "RDPRU clears the five flags specified by the APM");
// CF has no specified value on hardware. Check the shim's choice when
// CPUID Fn8000_0008 EBX[4] does not advertise native RDPRU.
unsigned eax, ebx, ecx, edx;
if (!__get_cpuid(0x80000008, &eax, &ebx, &ecx, &edx) || !(ebx & (1u << 4))) {
expect((flags & 1) == 0, "emulated RDPRU clears CF");
}
}
struct Quadwords {
uint64_t low;
uint64_t high;
};
// The upper result quadword is undefined and is outside the assertion.
#define CHECK_SSE4A(dst, src, encoding, initial, field, expected, name) \
do { \
uint64_t result; \
__asm__ volatile("movdqu %1, %%" dst "\n\t" \
"movdqu %2, %%" src "\n\t" \
".byte " encoding "\n\t" \
"movq %%" dst ", %0" \
: "=r"(result) : "m"(initial), "m"(field) : dst, src); \
expect(result == (expected), name); \
} while (false)
void check_bit_fields() {
const Quadwords initial{0xA1B2C3D4E5F60718ULL, 0};
// Extract [63:60] from the destination.
const Quadwords extract_field{0x3C04, 0};
// Insert source nibble 5 into [63:60], or low byte 0xB5 into [15:8].
const Quadwords insert_field{0x9876543210FEDCB5ULL, 0x3C04};
CHECK_SSE4A("xmm3", "xmm4", "0x66, 0x0f, 0x78, 0xc3, 12, 12", initial, extract_field, 0xF60,
"EXTRQ immediate without REX uses the destination low quadword");
CHECK_SSE4A("xmm3", "xmm4", "0x66, 0x0f, 0x79, 0xdc", initial, extract_field, 0xA,
"EXTRQ register without REX reads the source low quadword");
CHECK_SSE4A("xmm3", "xmm4", "0xf2, 0x0f, 0x78, 0xdc, 8, 8", initial, insert_field,
0xA1B2C3D4E5F6B518ULL, "INSERTQ immediate without REX preserves surrounding bits");
CHECK_SSE4A("xmm3", "xmm4", "0xf2, 0x0f, 0x79, 0xdc", initial, insert_field,
0x51B2C3D4E5F60718ULL, "INSERTQ register without REX reads the source high quadword");
CHECK_SSE4A("xmm11", "xmm12", "0x66, 0x49, 0x0f, 0x78, 0xc3, 12, 12",
initial, extract_field, 0xF60,
"EXTRQ immediate uses REX.B and ignores REX.W");
CHECK_SSE4A("xmm11", "xmm12", "0x66, 0x45, 0x0f, 0x79, 0xdc", initial, extract_field, 0xA,
"EXTRQ register reads the source low quadword");
CHECK_SSE4A("xmm11", "xmm12", "0xf2, 0x45, 0x0f, 0x78, 0xdc, 8, 8", initial, insert_field,
0xA1B2C3D4E5F6B518ULL, "INSERTQ immediate preserves bits outside the field");
CHECK_SSE4A("xmm11", "xmm12", "0xf2, 0x4d, 0x0f, 0x79, 0xdc", initial, insert_field,
0x51B2C3D4E5F60718ULL, "INSERTQ register reads the source high quadword");
CHECK_SSE4A("xmm11", "xmm12", "0x66, 0x41, 0x0f, 0x78, 0xc3, 0, 0", initial, extract_field,
0xA1B2C3D4E5F60718ULL, "EXTRQ length zero selects all 64 bits");
CHECK_SSE4A("xmm11", "xmm12", "0xf2, 0x45, 0x0f, 0x78, 0xdc, 0, 0", initial, insert_field,
0x9876543210FEDCB5ULL, "INSERTQ length zero replaces all 64 bits");
}
#undef CHECK_SSE4A
} // namespace
int main() {
// Keep the DLL import so that its VEH is installed before this fixture.
(void)bx_veh_get_clwb_trap_count();
check_cache_lines();
check_address_override();
check_write_fault();
check_wait_instructions();
check_processor_registers();
check_bit_fields();
std::printf("%s: test_veh_amd_only (%u/%u checks)\n",
failures ? "FAIL" : "PASS", checks - failures, checks);
return failures ? 1 : 0;
}
@@ -1,3 +1,4 @@
add_executable(test_xcrdapi main.cpp)
target_include_directories(test_xcrdapi PRIVATE "${BX_ROOT_DIR}/shims/xcrdapi")
target_link_libraries(test_xcrdapi PRIVATE xcrdapi kernel32 uuid)
target_compile_definitions(test_xcrdapi PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_include_directories(test_xcrdapi PRIVATE "${BX_ROOT_DIR}/shims/xcrdapi" "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
target_link_libraries(test_xcrdapi PRIVATE xcrdapi d3d12_xs kernel32 uuid)
+826 -1
View File
@@ -1,10 +1,15 @@
#include "synthetic_storage.h"
// Public PC DirectStorage contract (SDK 1.4.0, MIT per file), vendored under shims/xcrdapi/dstorage.
#include "dstorage_mingw.h"
#include <array>
#include <cstdio>
#include <cstring>
#include <limits>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
using namespace bx::storage;
#define CHECK(condition) \
@@ -62,6 +67,820 @@ struct MockFence final : ID3D12Fence {
}
};
unsigned char pattern_byte(unsigned index) {
return static_cast<unsigned char>(index * 17u + 3u);
}
bool bytes_match(const unsigned char* got, const unsigned char* expected, unsigned count, const char* label) {
for (unsigned i = 0; i < count; ++i) {
if (got[i] == expected[i]) continue;
std::fprintf(stderr, "xcrdapi: %s[%u]=0x%02x expected 0x%02x\n", label, i, got[i], expected[i]);
return false;
}
return true;
}
int map_fill(ID3D12Resource* resource, unsigned char value, unsigned count) {
D3D12_RANGE no_read{0, 0};
void* mapped = nullptr;
const HRESULT hr = resource->Map(0, &no_read, &mapped);
if (hr != S_OK || !mapped) {
std::fprintf(stderr, "xcrdapi: Map(fill) hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
std::memset(mapped, value, count);
resource->Unmap(0, nullptr);
return 0;
}
int map_copy(ID3D12Resource* resource, unsigned char* dest, unsigned count) {
D3D12_RANGE read{0, count};
void* mapped = nullptr;
const HRESULT hr = resource->Map(0, &read, &mapped);
if (hr != S_OK || !mapped) {
std::fprintf(stderr, "xcrdapi: Map(read) hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
std::memcpy(dest, mapped, count);
D3D12_RANGE none{0, 0};
resource->Unmap(0, &none);
return 0;
}
HRESULT create_buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_STATES state,
UINT64 width, ID3D12Resource** out) {
if (!out) return E_POINTER;
*out = nullptr;
D3D12_HEAP_PROPERTIES props{};
props.Type = heap;
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = width;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
return device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(out));
}
void test_transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource,
D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
if (before == after) return;
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition.pResource = resource;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = before;
barrier.Transition.StateAfter = after;
list->ResourceBarrier(1, &barrier);
}
int copy_region(ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, UINT64 src_offset, UINT64 size,
D3D12_RESOURCE_STATES dst_state, D3D12_RESOURCE_STATES dst_for_copy,
D3D12_RESOURCE_STATES src_state, D3D12_RESOURCE_STATES src_for_copy) {
Com<ID3D12Device> device;
HRESULT hr = dst->GetDevice(__uuidof(ID3D12Device), device.out());
if (hr != S_OK || !device.value) {
std::fprintf(stderr, "xcrdapi: GetDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
D3D12_COMMAND_QUEUE_DESC queue_desc{};
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
Com<ID3D12CommandQueue> queue;
hr = device->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), queue.out());
if (hr != S_OK || !queue.value) {
std::fprintf(stderr, "xcrdapi: CreateCommandQueue hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
Com<ID3D12CommandAllocator> allocator;
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), allocator.out());
if (hr != S_OK || !allocator.value) {
std::fprintf(stderr, "xcrdapi: CreateCommandAllocator hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
Com<ID3D12GraphicsCommandList> list;
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.value, nullptr,
__uuidof(ID3D12GraphicsCommandList), list.out());
if (hr != S_OK || !list.value) {
std::fprintf(stderr, "xcrdapi: CreateCommandList hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
test_transition(list.value, dst, dst_state, dst_for_copy);
test_transition(list.value, src, src_state, src_for_copy);
list->CopyBufferRegion(dst, dst_offset, src, src_offset, size);
test_transition(list.value, dst, dst_for_copy, dst_state);
test_transition(list.value, src, src_for_copy, src_state);
hr = list->Close();
if (hr != S_OK) {
std::fprintf(stderr, "xcrdapi: command list Close hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
ID3D12CommandList* lists[] = {list.value};
queue->ExecuteCommandLists(1, lists);
Com<ID3D12Fence> fence;
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), fence.out());
if (hr != S_OK || !fence.value) {
std::fprintf(stderr, "xcrdapi: CreateFence hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
hr = queue->Signal(fence.value, 1);
if (hr != S_OK) {
std::fprintf(stderr, "xcrdapi: Signal hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
Event done;
if (!done.handle) return 1;
hr = fence->SetEventOnCompletion(1, done.handle);
if (hr != S_OK) {
std::fprintf(stderr, "xcrdapi: SetEventOnCompletion hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
const DWORD waited = WaitForSingleObject(done.handle, 10000);
if (waited != WAIT_OBJECT_0) {
std::fprintf(stderr, "xcrdapi: copy wait=%lu\n", static_cast<unsigned long>(waited));
return 1;
}
return 0;
}
int check_compressed_rejection(Factory* factory) {
unsigned char source[4];
std::memset(source, 0x11, sizeof(source));
unsigned char unchanged[4];
std::memset(unchanged, 0x3C, sizeof(unchanged));
unsigned char dests[3][4];
for (auto& dest : dests) std::memset(dest, 0x3C, 4);
const UINT formats[] = {compression_lz, compression_bcpack, compression_gdeflate};
Com<Status> status;
CHECK(factory->CreateStatusArray(3, status_iid, status.out()) == S_OK);
Com<Queue> queue;
CHECK(factory->CreateQueue(8, queue_iid, queue.out()) == S_OK);
Event event;
CHECK(event.handle);
for (UINT i = 0; i < 3; ++i) {
Request request{nullptr, 0, source, dests[i], 4, formats[i]};
CHECK(queue->EnqueueRequest(&request) == S_OK);
CHECK(queue->EnqueueStatus(status.value, i) == S_OK);
}
CHECK(queue->EnqueueSetEvent(event.handle) == S_OK);
CHECK(status->GetResult(0) == E_PENDING);
CHECK(queue->Submit() == S_OK);
CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0);
for (UINT i = 0; i < 3; ++i) {
const HRESULT hr = status->GetResult(i);
if (hr != E_NOTIMPL) {
std::fprintf(stderr, "xcrdapi: compression %u hr=0x%08lx\n", i, static_cast<unsigned long>(hr));
return 1;
}
CHECK(bytes_match(dests[i], unchanged, 4, "compressed"));
}
ErrorRecord error{};
CHECK(queue->RetrieveErrorRecord(&error) == S_OK);
CHECK(error.failure_count == 3 && error.first_error == E_NOTIMPL);
CHECK(queue->Close() == S_OK);
return 0;
}
int check_batched_buffer_transfers(Factory* factory) {
// Expected bytes come from pattern_byte, the same function that fills the file.
// Two slices overlap on purpose: index 8 matches the later slice only when Submit
// runs the requests in enqueue order.
constexpr unsigned kBytes = 32;
constexpr unsigned kFileBytes = 40;
CHECK(pattern_byte(8) != pattern_byte(24));
unsigned char expect_mem[kBytes] = {};
unsigned char expect_gpu[kBytes];
std::memset(expect_gpu, 0xA5, kBytes);
for (unsigned i = 0; i < 16; ++i) {
expect_mem[i] = pattern_byte(i);
expect_gpu[i] = pattern_byte(i);
}
for (unsigned i = 0; i < 16; ++i) {
expect_mem[8 + i] = pattern_byte(24 + i);
expect_gpu[8 + i] = pattern_byte(24 + i);
}
CHECK(expect_mem[8] == pattern_byte(24) && expect_mem[24] == 0);
CHECK(expect_gpu[8] == pattern_byte(24) && expect_gpu[24] == 0xA5);
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
Com<ID3D12Device> device;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
if (hr != S_OK || !device.value) {
std::fprintf(stderr, "xcrdapi: D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
Com<ID3D12Resource> upload;
Com<ID3D12Resource> gpu;
Com<ID3D12Resource> readback;
hr = create_buffer(device.value, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, kBytes, &upload.value);
if (hr != S_OK || !upload.value) {
std::fprintf(stderr, "xcrdapi: upload buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
hr = create_buffer(device.value, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, kBytes, &gpu.value);
if (hr != S_OK || !gpu.value) {
std::fprintf(stderr, "xcrdapi: default buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
hr = create_buffer(device.value, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, kBytes, &readback.value);
if (hr != S_OK || !readback.value) {
std::fprintf(stderr, "xcrdapi: readback buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
D3D12_HEAP_PROPERTIES heap{};
hr = upload->GetHeapProperties(&heap, nullptr);
if (hr != S_OK || heap.Type != D3D12_HEAP_TYPE_UPLOAD) {
std::fprintf(stderr, "xcrdapi: upload heap hr=0x%08lx type=%d\n", static_cast<unsigned long>(hr), static_cast<int>(heap.Type));
return 1;
}
hr = gpu->GetHeapProperties(&heap, nullptr);
if (hr != S_OK || heap.Type != D3D12_HEAP_TYPE_DEFAULT) {
std::fprintf(stderr, "xcrdapi: default heap hr=0x%08lx type=%d\n", static_cast<unsigned long>(hr), static_cast<int>(heap.Type));
return 1;
}
if (map_fill(upload.value, 0xA5, kBytes) != 0) return 1;
if (copy_region(gpu.value, 0, upload.value, 0, kBytes,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_GENERIC_READ) != 0) {
return 1;
}
unsigned char file_bytes[kFileBytes];
for (unsigned i = 0; i < kFileBytes; ++i) file_bytes[i] = pattern_byte(i);
TemporaryFile temporary;
WCHAR directory[MAX_PATH];
const DWORD directory_len = GetTempPathW(MAX_PATH, directory);
CHECK(directory_len && directory_len < MAX_PATH);
CHECK(GetTempFileNameW(directory, L"bxg", 0, temporary.name));
const HANDLE writer = CreateFileW(temporary.name, GENERIC_WRITE, 0, nullptr, TRUNCATE_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(writer != INVALID_HANDLE_VALUE);
DWORD written = 0;
const BOOL wrote = WriteFile(writer, file_bytes, kFileBytes, &written, nullptr);
CloseHandle(writer);
CHECK(wrote && written == kFileBytes);
Com<File> file;
CHECK(factory->OpenFile(temporary.name, file_iid, file.out()) == S_OK);
unsigned char memory[kBytes] = {};
Com<Status> status;
CHECK(factory->CreateStatusArray(6, status_iid, status.out()) == S_OK);
Com<Queue> queue;
CHECK(factory->CreateQueue(16, queue_iid, queue.out()) == S_OK);
Event event;
CHECK(event.handle);
Request requests[6] = {
{file.value, 0, nullptr, memory, 16, compression_none},
{file.value, 24, nullptr, memory + 8, 16, compression_none},
{file.value, 0, nullptr, nullptr, 16, compression_none, upload.value, 0},
{file.value, 24, nullptr, nullptr, 16, compression_none, upload.value, 8},
{file.value, 0, nullptr, nullptr, 16, compression_none, gpu.value, 0},
{file.value, 24, nullptr, nullptr, 16, compression_none, gpu.value, 8},
};
for (UINT i = 0; i < 6; ++i) {
CHECK(queue->EnqueueRequest(&requests[i]) == S_OK);
CHECK(queue->EnqueueStatus(status.value, i) == S_OK);
}
CHECK(queue->EnqueueSetEvent(event.handle) == S_OK);
CHECK(status->GetResult(0) == E_PENDING);
CHECK(WaitForSingleObject(event.handle, 0) == WAIT_TIMEOUT);
unsigned char zeros[kBytes] = {};
CHECK(bytes_match(memory, zeros, kBytes, "memory-before"));
unsigned char upload_before[kBytes];
if (map_copy(upload.value, upload_before, kBytes) != 0) return 1;
for (unsigned i = 0; i < kBytes; ++i) CHECK(upload_before[i] == 0xA5);
CHECK(queue->Submit() == S_OK);
CHECK(WaitForSingleObject(event.handle, 15000) == WAIT_OBJECT_0);
for (UINT i = 0; i < 6; ++i) {
const HRESULT slot = status->GetResult(i);
if (slot != S_OK) {
std::fprintf(stderr, "xcrdapi: batch status %u hr=0x%08lx\n", i, static_cast<unsigned long>(slot));
return 1;
}
}
CHECK(bytes_match(memory, expect_mem, kBytes, "memory"));
unsigned char upload_got[kBytes];
if (map_copy(upload.value, upload_got, kBytes) != 0) return 1;
CHECK(bytes_match(upload_got, expect_gpu, kBytes, "upload"));
if (copy_region(readback.value, 0, gpu.value, 0, kBytes,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE) != 0) {
return 1;
}
unsigned char gpu_got[kBytes];
if (map_copy(readback.value, gpu_got, kBytes) != 0) return 1;
CHECK(bytes_match(gpu_got, expect_gpu, kBytes, "default"));
ErrorRecord error{};
CHECK(queue->RetrieveErrorRecord(&error) == S_OK && error.failure_count == 0);
CHECK(queue->Close() == S_OK);
Com<Queue> rejected;
CHECK(factory->CreateQueue(4, queue_iid, rejected.out()) == S_OK);
Request both{nullptr, 0, memory, memory, 4, compression_none, upload.value, 0};
CHECK(rejected->EnqueueRequest(&both) == E_INVALIDARG);
Com<Status> rejected_status;
CHECK(factory->CreateStatusArray(1, status_iid, rejected_status.out()) == S_OK);
Request past{file.value, 0, nullptr, nullptr, 1, compression_none, upload.value, kBytes};
CHECK(rejected->EnqueueRequest(&past) == S_OK);
CHECK(rejected->EnqueueStatus(rejected_status.value, 0) == S_OK);
CHECK(rejected->Submit() == S_OK);
CHECK(rejected->Close() == S_OK);
const HRESULT past_hr = rejected_status->GetResult(0);
if (past_hr != E_INVALIDARG) {
std::fprintf(stderr, "xcrdapi: past-end buffer hr=0x%08lx\n", static_cast<unsigned long>(past_hr));
return 1;
}
unsigned char upload_after[kBytes];
if (map_copy(upload.value, upload_after, kBytes) != 0) return 1;
CHECK(bytes_match(upload_after, expect_gpu, kBytes, "upload-after-reject"));
return 0;
}
ULONG live_refs(IUnknown* object) {
const ULONG held = object->AddRef();
object->Release();
return held - 1;
}
// Proves the post-ExecuteCommandLists timeout path: with a 0 ms wait and the
// copy queue held until that wait is decided, at least one request returns
// HRESULT_FROM_WIN32(WAIT_TIMEOUT), the device is not removed, the shim still
// holds the destination, and the destination bytes match after the GPU drains.
int check_unconfirmed_staged_copy(Factory* factory) {
constexpr unsigned kBytes = 16;
constexpr int kAttempts = 4;
const HRESULT kTimeout = HRESULT_FROM_WIN32(WAIT_TIMEOUT);
struct RestoreEnv {
~RestoreEnv() {
SetEnvironmentVariableW(L"BX_XCRDAPI_COPY_TIMEOUT_MS", nullptr);
SetEnvironmentVariableW(L"BX_XCRDAPI_DEFER_COPY", nullptr);
}
} restore_env;
CHECK(SetEnvironmentVariableW(L"BX_XCRDAPI_COPY_TIMEOUT_MS", L"0"));
CHECK(SetEnvironmentVariableW(L"BX_XCRDAPI_DEFER_COPY", L"1"));
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
Com<ID3D12Device> device;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
if (hr != S_OK || !device.value) {
std::fprintf(stderr, "xcrdapi: unconfirmed D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
Com<ID3D12Resource> upload;
Com<ID3D12Resource> readback;
hr = create_buffer(device.value, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, kBytes, &upload.value);
if (hr != S_OK || !upload.value) {
std::fprintf(stderr, "xcrdapi: unconfirmed upload hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
hr = create_buffer(device.value, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, kBytes, &readback.value);
if (hr != S_OK || !readback.value) {
std::fprintf(stderr, "xcrdapi: unconfirmed readback hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
if (map_fill(upload.value, 0x5A, kBytes) != 0) return 1;
unsigned char file_bytes[kBytes];
unsigned char expect[kBytes];
for (unsigned i = 0; i < kBytes; ++i) {
file_bytes[i] = pattern_byte(i);
expect[i] = pattern_byte(i);
}
CHECK(expect[0] != 0x5A);
TemporaryFile temporary;
WCHAR directory[MAX_PATH];
const DWORD directory_len = GetTempPathW(MAX_PATH, directory);
CHECK(directory_len && directory_len < MAX_PATH);
CHECK(GetTempFileNameW(directory, L"bxu", 0, temporary.name));
const HANDLE writer = CreateFileW(temporary.name, GENERIC_WRITE, 0, nullptr, TRUNCATE_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(writer != INVALID_HANDLE_VALUE);
DWORD written = 0;
const BOOL wrote = WriteFile(writer, file_bytes, kBytes, &written, nullptr);
CloseHandle(writer);
CHECK(wrote && written == kBytes);
Com<File> file;
CHECK(factory->OpenFile(temporary.name, file_iid, file.out()) == S_OK);
HRESULT last_hr = E_FAIL;
ULONG last_before = 0;
ULONG last_after = 0;
for (int attempt = 0; attempt < kAttempts; ++attempt) {
Com<ID3D12Resource> dest;
hr = create_buffer(device.value, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, kBytes, &dest.value);
if (hr != S_OK || !dest.value) {
std::fprintf(stderr, "xcrdapi: unconfirmed dest hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
D3D12_HEAP_PROPERTIES heap{};
hr = dest->GetHeapProperties(&heap, nullptr);
if (hr != S_OK || heap.Type != D3D12_HEAP_TYPE_DEFAULT) {
std::fprintf(stderr, "xcrdapi: unconfirmed heap hr=0x%08lx type=%d\n",
static_cast<unsigned long>(hr), static_cast<int>(heap.Type));
return 1;
}
if (copy_region(dest.value, 0, upload.value, 0, kBytes,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_GENERIC_READ) != 0) {
return 1;
}
const ULONG before = live_refs(dest.value);
const HRESULT removed_before = device->GetDeviceRemovedReason();
if (removed_before != S_OK) {
std::fprintf(stderr, "xcrdapi: device removed before unconfirmed copy hr=0x%08lx\n",
static_cast<unsigned long>(removed_before));
return 1;
}
Com<Status> status;
CHECK(factory->CreateStatusArray(1, status_iid, status.out()) == S_OK);
Com<Queue> queue;
CHECK(factory->CreateQueue(4, queue_iid, queue.out()) == S_OK);
Event event;
CHECK(event.handle);
Request request{file.value, 0, nullptr, nullptr, kBytes, compression_none, dest.value, 0};
CHECK(queue->EnqueueRequest(&request) == S_OK);
CHECK(queue->EnqueueStatus(status.value, 0) == S_OK);
CHECK(queue->EnqueueSetEvent(event.handle) == S_OK);
CHECK(queue->Submit() == S_OK);
CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0);
CHECK(queue->Close() == S_OK);
last_hr = status->GetResult(0);
last_before = before;
last_after = live_refs(dest.value);
const HRESULT removed = device->GetDeviceRemovedReason();
if (removed != S_OK) {
std::fprintf(stderr, "xcrdapi: device removed during unconfirmed copy hr=0x%08lx\n",
static_cast<unsigned long>(removed));
return 1;
}
// In-flight driver references can sit on top of the shim's hold. The
// count after the GPU drains is the one that has to be exactly one
// above the pre-request count.
if (last_hr != kTimeout || last_after < before + 1) continue;
ErrorRecord error{};
CHECK(queue->RetrieveErrorRecord(&error) == S_OK);
if (error.failure_count != 1 || error.first_error != kTimeout) {
std::fprintf(stderr, "xcrdapi: unconfirmed error record count=%llu hr=0x%08lx\n",
static_cast<unsigned long long>(error.failure_count),
static_cast<unsigned long>(error.first_error));
return 1;
}
bool bytes_ok = false;
unsigned char got[kBytes];
for (int spin = 0; spin < 8 && !bytes_ok; ++spin) {
Sleep(spin == 0 ? 200 : 100);
if (device->GetDeviceRemovedReason() != S_OK) break;
if (copy_region(readback.value, 0, dest.value, 0, kBytes,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE) != 0) {
return 1;
}
if (map_copy(readback.value, got, kBytes) != 0) return 1;
bytes_ok = true;
for (unsigned i = 0; i < kBytes; ++i) {
if (got[i] != expect[i]) bytes_ok = false;
}
if (!bytes_ok && spin == 7) bytes_match(got, expect, kBytes, "unconfirmed");
}
if (!bytes_ok) return 1;
const HRESULT removed_after = device->GetDeviceRemovedReason();
const ULONG still_held = live_refs(dest.value);
if (removed_after != S_OK || still_held != before + 1) {
std::fprintf(stderr, "xcrdapi: after drain removed=0x%08lx refs=%lu expected=%lu (at timeout %lu)\n",
static_cast<unsigned long>(removed_after),
static_cast<unsigned long>(still_held),
static_cast<unsigned long>(before + 1),
static_cast<unsigned long>(last_after));
return 1;
}
std::printf("test_xcrdapi: unconfirmed copy attempt=%d hr=0x%08lx refs %lu -> %lu device_removed=0x%08lx bytes=%u\n",
attempt,
static_cast<unsigned long>(last_hr),
static_cast<unsigned long>(before),
static_cast<unsigned long>(still_held),
static_cast<unsigned long>(removed_after),
kBytes);
return 0;
}
std::fprintf(stderr, "xcrdapi: unconfirmed path not observed in %d attempts (last hr=0x%08lx refs %lu -> %lu)\n",
kAttempts, static_cast<unsigned long>(last_hr),
static_cast<unsigned long>(last_before), static_cast<unsigned long>(last_after));
return 1;
}
// Public PC DirectStorage interfaces. Expected values come from the documentation
// comments in dstorage.h 1.4.0, not from the shim: capacity limits, "capacity - 1"
// empty slots, automatic submission at half capacity, IsComplete == (GetHResult !=
// E_PENDING), status entries scoped to the requests since the previous one, and the
// E_DSTORAGE_* codes in dstorageerr.h. Where the header is silent (unsupported
// destinations and compression), the expected E_NOTIMPL is BetterXen's documented choice.
struct ForeignStatusArray final : IDStorageStatusArray {
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; }
ULONG STDMETHODCALLTYPE AddRef() override { return 1; }
ULONG STDMETHODCALLTYPE Release() override { return 1; }
bool STDMETHODCALLTYPE IsComplete(UINT32) override { return true; }
HRESULT STDMETHODCALLTYPE GetHResult(UINT32) override { return S_OK; }
};
DSTORAGE_REQUEST file_to_memory(IDStorageFile* file, UINT64 offset, void* dest, UINT32 size) {
DSTORAGE_REQUEST request{};
request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;
request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;
request.Source.File.Source = file;
request.Source.File.Offset = offset;
request.Source.File.Size = size;
request.Destination.Memory.Buffer = dest;
request.Destination.Memory.Size = size;
return request;
}
DSTORAGE_REQUEST memory_to_memory(const void* source, void* dest, 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 = dest;
request.Destination.Memory.Size = size;
return request;
}
int check_public_interfaces(const WCHAR* path, const char* contents) {
// The generated MinGW IID declarations must match values typed independently from
// Silk.NET's IDStorageFactory binding and the #483 issue text, not from dstorage_mingw.h.
const IID typed_factory{0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}};
CHECK(IsEqualIID(__uuidof(IDStorageFactory), typed_factory));
// Factory: public IIDs are served, an unknown IID is refused with ppv cleared.
const IID unknown_iid{0x0badf00d, 0x1234, 0x4abc, {0x80, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}};
void* refused = reinterpret_cast<void*>(1);
CHECK(DStorageGetFactory(unknown_iid, &refused) == E_NOINTERFACE && !refused);
Com<IDStorageFactory> factory;
CHECK(DStorageGetFactory(__uuidof(IDStorageFactory), factory.out()) == S_OK && factory.value);
Com<IDStorageFactory1> factory1;
CHECK(factory->QueryInterface(__uuidof(IDStorageFactory1), factory1.out()) == S_OK);
Com<IUnknown> identity;
CHECK(factory->QueryInterface(IID_IUnknown, identity.out()) == S_OK);
Com<IUnknown> identity1;
CHECK(factory1->QueryInterface(IID_IUnknown, identity1.out()) == S_OK && identity.value == identity1.value);
Com<IDStorageFactory1> direct1;
CHECK(DStorageGetFactory(__uuidof(IDStorageFactory1), direct1.out()) == S_OK && direct1.value);
CHECK(factory->SetStagingBufferSize(DSTORAGE_STAGING_BUFFER_SIZE_32MB) == S_OK);
// Queue creation limits: DSTORAGE_MIN/MAX_QUEUE_CAPACITY and DSTORAGE_PRIORITY range.
DSTORAGE_QUEUE_DESC desc{};
desc.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;
desc.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
desc.Priority = DSTORAGE_PRIORITY_NORMAL;
desc.Name = "bx file queue";
void* bad_queue = reinterpret_cast<void*>(1);
DSTORAGE_QUEUE_DESC bad = desc;
bad.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY - 1;
CHECK(factory->CreateQueue(&bad, __uuidof(IDStorageQueue), &bad_queue) == E_DSTORAGE_INVALID_QUEUE_CAPACITY
&& !bad_queue);
bad.Capacity = DSTORAGE_MAX_QUEUE_CAPACITY + 1;
CHECK(factory->CreateQueue(&bad, __uuidof(IDStorageQueue), &bad_queue) == E_DSTORAGE_INVALID_QUEUE_CAPACITY);
bad = desc;
bad.Priority = static_cast<DSTORAGE_PRIORITY>(DSTORAGE_PRIORITY_LAST + 1);
CHECK(factory->CreateQueue(&bad, __uuidof(IDStorageQueue), &bad_queue) == E_DSTORAGE_INVALID_QUEUE_PRIORITY);
Com<IDStorageFile> file;
CHECK(factory->OpenFile(path, __uuidof(IDStorageFile), file.out()) == S_OK);
BY_HANDLE_FILE_INFORMATION file_info{};
CHECK(file->GetFileInformation(&file_info) == S_OK && file_info.nFileSizeLow == std::strlen(contents) + 1);
Com<IDStorageStatusArray> status;
CHECK(factory->CreateStatusArray(4, "bx status", __uuidof(IDStorageStatusArray), status.out()) == S_OK);
Com<IDStorageQueue> queue;
CHECK(factory->CreateQueue(&desc, __uuidof(IDStorageQueue), queue.out()) == S_OK);
Com<IDStorageQueue4> queue4;
CHECK(queue->QueryInterface(__uuidof(IDStorageQueue4), queue4.out()) == S_OK);
DSTORAGE_QUEUE_INFO info{};
queue->Query(&info);
CHECK(info.Desc.Capacity == DSTORAGE_MIN_QUEUE_CAPACITY && info.Desc.SourceType == DSTORAGE_REQUEST_SOURCE_FILE);
CHECK(info.Desc.Name && std::strcmp(info.Desc.Name, "bx file queue") == 0);
CHECK(info.EmptySlotCount == DSTORAGE_MIN_QUEUE_CAPACITY - 1);
CHECK(info.RequestCountUntilAutoSubmit == DSTORAGE_MIN_QUEUE_CAPACITY / 2);
CHECK(queue4->GetCompressionSupport(DSTORAGE_COMPRESSION_FORMAT_GDEFLATE) == DSTORAGE_COMPRESSION_SUPPORT_NONE);
// Two file reads, a status entry and an event; nothing runs before Submit.
std::array<char, 5> first{}, second{};
Event done;
CHECK(done.handle);
DSTORAGE_REQUEST read1 = file_to_memory(file.value, 2, first.data(), 4);
DSTORAGE_REQUEST read2 = file_to_memory(file.value, 10, second.data(), 4);
queue->EnqueueRequest(&read1);
queue->EnqueueRequest(&read2);
queue->EnqueueStatus(status.value, 0);
queue4->EnqueueSetEvent(done.handle);
DSTORAGE_QUEUE_INFO1 info1{};
queue4->Query1(&info1);
CHECK(info1.EmptySlotCount == DSTORAGE_MIN_QUEUE_CAPACITY - 1 - 4);
CHECK(info1.RequestCountUntilAutoSubmit == DSTORAGE_MIN_QUEUE_CAPACITY / 2 - 4);
CHECK(!status->IsComplete(0) && status->GetHResult(0) == E_PENDING);
queue->Submit();
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
CHECK(status->IsComplete(0) && status->GetHResult(0) == S_OK);
CHECK(std::memcmp(first.data(), contents + 2, 4) == 0 && std::memcmp(second.data(), contents + 10, 4) == 0);
// Rejected requests are reported in queue order, scoped by status entries.
const HANDLE error_event = queue->GetErrorEvent();
CHECK(error_event && WaitForSingleObject(error_event, 0) == WAIT_TIMEOUT);
std::array<char, 5> scratch{}, third{};
DSTORAGE_REQUEST reserved = file_to_memory(file.value, 0, scratch.data(), 4);
reserved.Options.Reserved1[0] = 1;
const char memory_source[4] = {'w', 'x', 'y', 'z'};
DSTORAGE_REQUEST wrong_source = memory_to_memory(memory_source, scratch.data(), 4);
DSTORAGE_REQUEST read3 = file_to_memory(file.value, 4, third.data(), 4);
queue->EnqueueRequest(&reserved);
queue->EnqueueRequest(&wrong_source);
queue->EnqueueStatus(status.value, 1);
queue->EnqueueRequest(&read3);
queue->EnqueueStatus(status.value, 2);
queue4->EnqueueSetEvent(done.handle);
queue->Submit();
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
CHECK(status->GetHResult(1) == E_DSTORAGE_RESERVED_FIELDS);
CHECK(status->GetHResult(2) == S_OK && std::memcmp(third.data(), contents + 4, 4) == 0);
CHECK(scratch[0] == 0);
CHECK(WaitForSingleObject(error_event, 0) == WAIT_OBJECT_0);
DSTORAGE_ERROR_RECORD record{};
queue->RetrieveErrorRecord(&record);
CHECK(record.FailureCount == 2 && record.FirstFailure.HResult == E_DSTORAGE_RESERVED_FIELDS);
CHECK(record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_REQUEST);
queue->RetrieveErrorRecord(&record);
CHECK(record.FailureCount == 0 && record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_NONE);
// A foreign status array and a null fence are rejected without poisoning the next status.
ForeignStatusArray foreign;
queue->EnqueueStatus(&foreign, 0);
queue->EnqueueSignal(nullptr, 1);
queue->EnqueueStatus(status.value, 3);
queue4->EnqueueSetEvent(done.handle);
queue->Submit();
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
CHECK(status->GetHResult(3) == S_OK);
queue->RetrieveErrorRecord(&record);
CHECK(record.FailureCount == 2 && record.FirstFailure.HResult == E_DSTORAGE_INVALID_STATUS_ARRAY);
CHECK(record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_STATUS);
// Unsupported shapes on a memory queue without a device: each is its own status scope.
DSTORAGE_QUEUE_DESC memory_desc = desc;
memory_desc.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
memory_desc.Name = nullptr;
Com<IDStorageQueue1> memory_queue;
CHECK(factory->CreateQueue(&memory_desc, __uuidof(IDStorageQueue1), memory_queue.out()) == S_OK);
Com<IDStorageStatusArray> shapes;
CHECK(factory->CreateStatusArray(4, nullptr, __uuidof(IDStorageStatusArray), shapes.out()) == S_OK);
unsigned char untouched[4] = {0x5A, 0x5A, 0x5A, 0x5A};
DSTORAGE_REQUEST buffer_without_device = memory_to_memory(memory_source, untouched, 4);
buffer_without_device.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_BUFFER;
buffer_without_device.Destination.Buffer.Resource = nullptr;
buffer_without_device.Destination.Buffer.Offset = 0;
buffer_without_device.Destination.Buffer.Size = 4;
DSTORAGE_REQUEST texture = memory_to_memory(memory_source, untouched, 4);
texture.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_TEXTURE_REGION;
DSTORAGE_REQUEST zstd = memory_to_memory(memory_source, untouched, 4);
zstd.Options.CompressionFormat = DSTORAGE_COMPRESSION_FORMAT_ZSTD;
DSTORAGE_REQUEST short_destination = memory_to_memory(memory_source, untouched, 4);
short_destination.Destination.Memory.Size = 3;
const DSTORAGE_REQUEST* shaped[] = {&buffer_without_device, &texture, &zstd, &short_destination};
const HRESULT expected[] = {E_DSTORAGE_INVALID_DESTINATION_TYPE, E_NOTIMPL, E_NOTIMPL,
E_DSTORAGE_INVALID_DESTINATION_SIZE};
for (UINT i = 0; i < 4; ++i) {
memory_queue->EnqueueRequest(shaped[i]);
memory_queue->EnqueueStatus(shapes.value, i);
}
memory_queue->EnqueueSetEvent(done.handle);
memory_queue->Submit();
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
for (UINT i = 0; i < 4; ++i) {
const HRESULT hr = shapes->GetHResult(i);
if (hr != expected[i]) {
std::fprintf(stderr, "xcrdapi: public shape %u hr=0x%08lx expected 0x%08lx\n", i,
static_cast<unsigned long>(hr), static_cast<unsigned long>(expected[i]));
return 1;
}
}
CHECK(untouched[0] == 0x5A && untouched[3] == 0x5A);
// Half capacity triggers submission: the event is the 64th entry, and Submit is never called.
constexpr UINT kAuto = DSTORAGE_MIN_QUEUE_CAPACITY / 2;
static unsigned char auto_dest[kAuto - 1][4];
std::memset(auto_dest, 0, sizeof(auto_dest));
for (UINT i = 0; i + 1 < kAuto; ++i) {
DSTORAGE_REQUEST copy = memory_to_memory(memory_source, auto_dest[i], 4);
memory_queue->EnqueueRequest(&copy);
}
memory_queue->EnqueueSetEvent(done.handle);
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
for (UINT i = 0; i + 1 < kAuto; ++i) CHECK(std::memcmp(auto_dest[i], memory_source, 4) == 0);
// More requests than the queue holds: all are accepted, the caller waiting for free slots.
constexpr UINT kBlocking = 3 * DSTORAGE_MIN_QUEUE_CAPACITY;
static unsigned char blocking_dest[kBlocking][4];
std::memset(blocking_dest, 0, sizeof(blocking_dest));
for (UINT i = 0; i < kBlocking; ++i) {
DSTORAGE_REQUEST copy = memory_to_memory(memory_source, blocking_dest[i], 4);
memory_queue->EnqueueRequest(&copy);
}
memory_queue->EnqueueStatus(shapes.value, 0);
memory_queue->EnqueueSetEvent(done.handle);
memory_queue->Submit();
CHECK(WaitForSingleObject(done.handle, 10000) == WAIT_OBJECT_0);
CHECK(shapes->GetHResult(0) == S_OK);
for (UINT i = 0; i < kBlocking; ++i) CHECK(std::memcmp(blocking_dest[i], memory_source, 4) == 0);
memory_queue->RetrieveErrorRecord(&record);
CHECK(record.FailureCount == 4 && record.FirstFailure.HResult == E_DSTORAGE_INVALID_DESTINATION_TYPE);
// After Close, enqueued commands are dropped and Close is repeatable.
file->Close();
CHECK(file->GetFileInformation(&file_info) == HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE));
queue->Close();
queue->EnqueueRequest(&read1);
queue->Submit();
queue->Close();
memory_queue->Close();
return 0;
}
// Public buffer destination: a memory source written into an upload-heap buffer on
// the queue's device. Expected bytes are the source bytes.
int check_public_buffer_destination() {
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
Com<ID3D12Device> device;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
if (hr != S_OK || !device.value) {
std::fprintf(stderr, "xcrdapi: public D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
constexpr unsigned kBytes = 16;
Com<ID3D12Resource> upload;
hr = create_buffer(device.value, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, kBytes, &upload.value);
if (hr != S_OK || !upload.value) {
std::fprintf(stderr, "xcrdapi: public upload buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
if (const int filled = map_fill(upload.value, 0xEE, kBytes)) return filled;
Com<IDStorageFactory> factory;
CHECK(DStorageGetFactory(__uuidof(IDStorageFactory), factory.out()) == S_OK);
DSTORAGE_QUEUE_DESC desc{};
desc.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
desc.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
desc.Priority = DSTORAGE_PRIORITY_NORMAL;
desc.Device = device.value;
Com<IDStorageQueue1> queue;
CHECK(factory->CreateQueue(&desc, __uuidof(IDStorageQueue1), queue.out()) == S_OK);
Com<IDStorageStatusArray> status;
CHECK(factory->CreateStatusArray(1, nullptr, __uuidof(IDStorageStatusArray), status.out()) == S_OK);
unsigned char source[8];
for (unsigned i = 0; i < 8; ++i) source[i] = pattern_byte(i);
DSTORAGE_REQUEST request{};
request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_BUFFER;
request.Source.Memory.Source = source;
request.Source.Memory.Size = 8;
request.Destination.Buffer.Resource = upload.value;
request.Destination.Buffer.Offset = 4;
request.Destination.Buffer.Size = 8;
Event done;
CHECK(done.handle);
queue->EnqueueRequest(&request);
queue->EnqueueStatus(status.value, 0);
queue->EnqueueSetEvent(done.handle);
queue->Submit();
CHECK(WaitForSingleObject(done.handle, 10000) == WAIT_OBJECT_0);
CHECK(status->GetHResult(0) == S_OK);
unsigned char got[kBytes];
if (const int copied = map_copy(upload.value, got, kBytes)) return copied;
unsigned char expect[kBytes];
std::memset(expect, 0xEE, kBytes);
std::memcpy(expect + 4, source, 8);
CHECK(bytes_match(got, expect, kBytes, "public_buffer"));
queue->Close();
return 0;
}
int main() {
void* unsupported = nullptr;
CHECK(DStorageGetFactory(file_iid, &unsupported) == E_NOINTERFACE && !unsupported);
@@ -125,7 +944,7 @@ int main() {
ErrorRecord error{};
CHECK(queue->RetrieveErrorRecord(&error) == S_OK && error.failure_count == 0);
Request past_end{file.value, sizeof(contents), nullptr, first.data(), 1, 0};
Request compressed{nullptr, 0, first.data(), copied.data(), 4, 1};
Request compressed{nullptr, 0, first.data(), copied.data(), 4, compression_lz};
CHECK(queue->EnqueueRequest(&past_end) == S_OK);
CHECK(queue->EnqueueRequest(&compressed) == S_OK);
CHECK(queue->EnqueueStatus(status.value, 0) == S_OK);
@@ -174,5 +993,11 @@ int main() {
CHECK(status->GetResult(0) == S_OK);
CHECK(WaitForSingleObject(close_event.handle, 0) == WAIT_OBJECT_0);
if (const int public_api = check_public_interfaces(temporary.name, contents)) return public_api;
if (const int public_buffer = check_public_buffer_destination()) return public_buffer;
if (const int compressed = check_compressed_rejection(factory.value)) return compressed;
if (const int batched = check_batched_buffer_transfers(factory.value)) return batched;
if (const int unconfirmed = check_unconfirmed_staged_copy(factory.value)) return unconfirmed;
std::puts("test_xcrdapi: passed");
}
@@ -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)
+722
View File
@@ -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;
}
+371 -1
View File
@@ -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();
@@ -444,6 +444,212 @@ int writer_main(int id, int count, const wchar_t* event_name) {
return 0;
}
// Public COM ids and slot numbers counted from xodus-gaming/xgameruntime-docs
// commit 7090008692569aa6081e30dfdd9de58237741e24. IUnknown is slots 0-2.
// The test keeps its own copies. IXGameSaveImpl lists 27 methods in slots 3-29.
// IXGameSaveImpl2 adds 3 methods in slots 30-32 and IXGameSaveImpl3 adds none.
// IXPackageImpl lists 32 methods in slots 3-34. IXPackageImpl2 adds 4, IXPackageImpl3
// adds 2, and IXPackageImpl4 adds 1.
enum : int {
kGsInit = 3, kGsInitAsync, kGsInitResult, kGsCloseProvider, kGsQuota, kGsQuotaAsync, kGsQuotaResult,
kGsDelete, kGsDeleteAsync, kGsDeleteResult, kGsGetContainerInfo, kGsEnumerate, kGsEnumerateByName,
kGsCreateContainer, kGsCloseContainer, kGsEnumerateBlobs, kGsEnumerateBlobsByName, kGsRead, kGsReadAsync,
kGsReadResult, kGsCreateUpdate, kGsCloseUpdate, kGsBlobWrite, kGsBlobDelete, kGsSubmit, kGsSubmitAsync,
kGsSubmitResult, kGsFilesFolderAsync, kGsFilesFolderResult, kGsFilesQuota,
};
static_assert(kGsQuota == 7 && kGsEnumerate == 14 && kGsCreateContainer == 16 && kGsRead == 20);
static_assert(kGsCreateUpdate == 23 && kGsBlobWrite == 25 && kGsSubmit == 27 && kGsFilesQuota == 32);
enum : int {
kPkId = 3, kPkIsPackaged, kPkCreateMonitor, kPkCloseMonitor, kPkGetProgress, kPkUpdateMonitor,
kPkRegisterProgress, kPkUnregisterProgress, kPkLocale, kPkFindChunk, kPkEnumChunk, kPkChangeOrder,
kPkInstall, kPkInstallAsync, kPkInstallResult, kPkEstimate, kPkUninstallChunks, kPkUnknown20,
kPkUnknown21, kPkUnregisterInstalled, kPkMount, kPkPathSize, kPkPath, kPkCloseMount, kPkUnknown27,
kPkEnumPackages, kPkRegisterInstalled, kPkWriteStats, kPkUnknown31, kPkUninstallUwp, kPkEnumFeatures,
kPkUninstall, kPkEnumPackages2, kPkRegisterInstalled2, kPkMountUiAsync, kPkMountUiResult,
kPkEnumPackages3, kPkRegisterInstalled3, kPkKind,
};
static_assert(kPkUnknown20 == 20 && kPkMount == 23 && kPkCloseMount == 26 && kPkKind == 41);
GUID guid_bytes(uint32_t a, uint16_t b, uint16_t c, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4,
uint8_t d5, uint8_t d6, uint8_t d7) {
return {a, b, c, {d0, d1, d2, d3, d4, d5, d6, d7}};
}
void expect_same_object(void* object, const GUID& iid) {
void* out = nullptr;
CHECK(slot<QiFn>(object, kQueryInterface)(object, &iid, &out) == S_OK && out == object);
}
// QueryApiImpl with the public class and interface ids, then one save and one package round trip
// through those vtable slots. Expected bytes and the mount path come from this function's inputs.
void check_public_dispatch(void* user, void* synthetic_save, void* synthetic_package, time_t started) {
const GUID save_class = guid_bytes(0x704C3F58, 0xE629, 0x4CC2, 0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6F, 0xE2);
const GUID save_iid2 = guid_bytes(0x704C3F58, 0xE629, 0x4CC2, 0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6E, 0xE2);
const GUID save_iid3 = guid_bytes(0x1BFFF3AF, 0xF14A, 0x40A3, 0x8E, 0x35, 0x9A, 0xDA, 0x90, 0x65, 0x93, 0xF9);
const GUID package_class = guid_bytes(0xAF406016, 0xE850, 0x4AA8, 0xA8, 0x8D, 0x2F, 0x3D, 0xCB, 0x9D, 0xAC, 0x7E);
const GUID package_iid = guid_bytes(0x3720DE07, 0xE8E4, 0x44A3, 0xAD, 0x32, 0xB3, 0x59, 0xE8, 0xAD, 0xBE, 0x55);
const GUID package_iid2 = guid_bytes(0xF92D8712, 0x2B27, 0x4D8A, 0xBF, 0x01, 0x11, 0xA6, 0xF8, 0xE3, 0xEB, 0x42);
const GUID package_iid3 = guid_bytes(0xE2A4734B, 0x2F4A, 0x456D, 0xAA, 0x8F, 0xD0, 0x65, 0xE0, 0x4F, 0xB2, 0x09);
const GUID package_iid4 = guid_bytes(0x0B9D556E, 0xAB70, 0x43F4, 0xBA, 0xA0, 0x99, 0x99, 0xAC, 0x4C, 0xB0, 0x40);
const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
const GUID unknown = {0xDEADBEEF, 0x0000, 0x0000, {0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
void* save = nullptr;
CHECK(QueryApiImpl(&save_class, &save_class, &save) == S_OK && save && save != synthetic_save);
void* again = nullptr;
CHECK(QueryApiImpl(&save_class, &save_iid2, &again) == S_OK && again == save);
CHECK(QueryApiImpl(&save_class, &save_iid3, &again) == S_OK && again == save);
CHECK(QueryApiImpl(&save_class, &iunknown, &again) == S_OK && again == save);
expect_same_object(save, iunknown);
expect_same_object(save, save_class);
expect_same_object(save, save_iid2);
expect_same_object(save, save_iid3);
void* refused = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(slot<QiFn>(save, kQueryInterface)(save, &unknown, &refused) == E_NOINTERFACE && !refused);
refused = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(QueryApiImpl(&save_class, &unknown, &refused) == E_NOINTERFACE && !refused);
CHECK(slot<RefFn>(save, kAddRef)(save) >= 1 && slot<RefFn>(save, kRelease)(save) >= 1);
using Hr0 = HRESULT(WINAPI*)(void*);
CHECK(slot<Hr0>(save, kGsQuota)(save) == E_NOTIMPL);
CHECK(slot<Hr0>(save, kGsFilesQuota)(save) == E_NOTIMPL);
constexpr const char* kPublicScid = "11111111-1111-1111-1111-111111111111";
constexpr const char* kContainer = "pub_slot";
constexpr const char* kDisplay = "Round";
constexpr const char* kBlob = "note";
const uint8_t payload[] = {0x10, 0x20, 0x30, 0xFF};
using InitFn = HRESULT(WINAPI*)(void*, void*, const char*, bool, void**);
void* provider = nullptr;
CHECK(slot<InitFn>(save, kGsInit)(save, user, kPublicScid, false, &provider) == S_OK && provider);
void* container = nullptr;
CHECK(slot<CreateContainerFn>(save, kGsCreateContainer)(save, provider, kContainer, &container) == S_OK &&
container);
void* update = nullptr;
CHECK(slot<CreateUpdateFn>(save, kGsCreateUpdate)(save, container, kDisplay, &update) == S_OK && update);
CHECK(slot<BlobWriteFn>(save, kGsBlobWrite)(save, update, kBlob, payload, sizeof(payload)) == S_OK);
using SubmitFn = HRESULT(WINAPI*)(void*, void*);
CHECK(slot<SubmitFn>(save, kGsSubmit)(save, update) == S_OK);
const char* names[] = {kBlob};
uint32_t count = 1;
using ReadFn = HRESULT(WINAPI*)(void*, void*, const char**, uint32_t*, size_t, Blob*);
CHECK(slot<ReadFn>(save, kGsRead)(save, container, names, &count, 0, nullptr) == kBufferTooSmall && count == 0);
count = 1;
const size_t need = sizeof(Blob) + std::strlen(kBlob) + 1 + sizeof(payload);
std::vector<unsigned char> buffer(need + 8, 0xCD);
auto* blobs = reinterpret_cast<Blob*>(buffer.data());
CHECK(slot<ReadFn>(save, kGsRead)(save, container, names, &count, need, blobs) == S_OK && count == 1);
CHECK(std::strcmp(blobs[0].name, kBlob) == 0 && blobs[0].size == sizeof(payload));
CHECK(std::memcmp(blobs[0].data, payload, sizeof(payload)) == 0);
const auto* base = buffer.data();
CHECK(reinterpret_cast<const unsigned char*>(blobs[0].name) >= base &&
reinterpret_cast<const unsigned char*>(blobs[0].name) + std::strlen(kBlob) + 1 <= base + need);
CHECK(blobs[0].data >= base && blobs[0].data + blobs[0].size <= base + need);
for (size_t i = need; i < buffer.size(); ++i) CHECK(buffer[i] == 0xCD);
Listing listing;
CHECK(slot<EnumerateFn>(save, kGsEnumerate)(save, provider, &listing, collect) == S_OK);
CHECK(listing.seen.size() == 1);
CHECK(listing.seen[0].name == kContainer && listing.seen[0].display_name == kDisplay);
CHECK(listing.seen[0].blob_count == 1 && listing.seen[0].total_size == sizeof(payload));
CHECK(!listing.seen[0].needs_sync && listing.seen[0].modified >= started);
slot<CloseFn>(save, kGsCloseUpdate)(save, update);
slot<CloseFn>(save, kGsCloseContainer)(save, container);
slot<CloseFn>(save, kGsCloseProvider)(save, provider);
void* package = nullptr;
CHECK(QueryApiImpl(&package_class, &package_iid4, &package) == S_OK && package && package != synthetic_package);
CHECK(QueryApiImpl(&package_class, &package_iid, &again) == S_OK && again == package);
CHECK(QueryApiImpl(&package_class, &package_iid2, &again) == S_OK && again == package);
CHECK(QueryApiImpl(&package_class, &package_iid3, &again) == S_OK && again == package);
CHECK(QueryApiImpl(&package_class, &iunknown, &again) == S_OK && again == package);
expect_same_object(package, iunknown);
expect_same_object(package, package_iid);
expect_same_object(package, package_iid2);
expect_same_object(package, package_iid3);
expect_same_object(package, package_iid4);
refused = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(slot<QiFn>(package, kQueryInterface)(package, &unknown, &refused) == E_NOINTERFACE && !refused);
refused = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(QueryApiImpl(&package_class, &save_class, &refused) == E_NOINTERFACE && !refused);
refused = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(QueryApiImpl(&package_class, &package_class, &refused) == E_NOINTERFACE && !refused);
using Bool1 = bool(WINAPI*)(void*);
CHECK(slot<Bool1>(package, kPkIsPackaged)(package) == true);
using Bool2 = bool(WINAPI*)(void*, void*);
CHECK(slot<Bool2>(package, kPkUpdateMonitor)(package, nullptr) == false);
using Void2 = void(WINAPI*)(void*, void*);
slot<Void2>(package, kPkCloseMonitor)(package, nullptr);
CHECK(slot<Hr0>(package, kPkUnknown20)(package) == E_NOTIMPL);
char id[64]{};
CHECK(slot<GetIdFn>(package, kPkId)(package, sizeof(id), id) == S_OK);
CHECK(std::strncmp(id, "BXPKG", 5) == 0 && std::strlen(id) == 21);
uint32_t kind = 99;
CHECK(slot<GetKindFn>(package, kPkKind)(package, id, &kind) == S_OK && kind == 0);
wchar_t exe_w[MAX_PATH]{};
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
*std::wcsrchr(exe_w, L'\\') = L'\0';
const std::string exe_dir = utf8(exe_w);
void* mount = nullptr;
CHECK(slot<MountFn>(package, kPkMount)(package, id, &mount) == S_OK && mount);
size_t path_size = 0;
CHECK(slot<PathSizeFn>(package, kPkPathSize)(package, mount, &path_size) == S_OK);
CHECK(path_size == exe_dir.size() + 1);
std::vector<char> path(path_size);
CHECK(slot<PathFn>(package, kPkPath)(package, mount, path_size, path.data()) == S_OK);
CHECK(exe_dir == path.data());
slot<CloseFn>(package, kPkCloseMount)(package, mount);
CHECK(slot<PathSizeFn>(package, kPkPathSize)(package, mount, &path_size) == kInvalidHandle);
// XPackageMountWithUiAsync / Result (IXPackageImpl2 slots 37-38): the same mount, as an XAsync
// operation on the process task queue. A foreign identifier is the operation's status.
using MountAsyncFn = HRESULT(WINAPI*)(void*, const char*, Async*);
using MountResultFn = HRESULT(WINAPI*)(void*, Async*, void**);
const auto mount_async = slot<MountAsyncFn>(package, kPkMountUiAsync);
const auto mount_result = slot<MountResultFn>(package, kPkMountUiResult);
CHECK(mount_async(package, id, nullptr) == E_POINTER);
Async probe{nullptr, nullptr, nullptr, {}};
CHECK(mount_async(package, nullptr, &probe) == E_INVALIDARG);
CHECK(mount_result(package, &probe, nullptr) == E_POINTER);
{
Async async{nullptr, nullptr, nullptr, {}};
CHECK(mount_async(package, id, &async) == S_OK);
CHECK(XAsyncGetStatus(&async, true) == S_OK);
size_t size = 0;
CHECK(XAsyncGetResultSize(&async, &size) == S_OK && size == sizeof(void*));
void* ui_mount = nullptr;
CHECK(mount_result(package, &async, &ui_mount) == S_OK && ui_mount);
void* twice = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(mount_result(package, &async, &twice) == kIllegalCall && !twice);
CHECK(slot<PathSizeFn>(package, kPkPathSize)(package, ui_mount, &path_size) == S_OK &&
path_size == exe_dir.size() + 1);
std::vector<char> ui_path(path_size);
CHECK(slot<PathFn>(package, kPkPath)(package, ui_mount, path_size, ui_path.data()) == S_OK);
CHECK(exe_dir == ui_path.data());
slot<CloseFn>(package, kPkCloseMount)(package, ui_mount);
CHECK(slot<PathSizeFn>(package, kPkPathSize)(package, ui_mount, &path_size) == kInvalidHandle);
}
{
Async async{nullptr, nullptr, nullptr, {}};
CHECK(mount_async(package, "BXPKG0000000000000000", &async) == S_OK);
CHECK(XAsyncGetStatus(&async, true) == kNotFound);
void* none = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(mount_result(package, &async, &none) == kNotFound && !none);
}
// IXError slot 3 answers false ("continue"); a true answer stops GDK calls such as XPackageMount.
const GUID error_class = guid_bytes(0x8CA467F7, 0x22E8, 0x4096, 0x84, 0x56, 0xBB, 0x8A, 0xA1, 0x3F, 0x79, 0xD8);
void* error = nullptr;
CHECK(QueryApiImpl(&error_class, &error_class, &error) == S_OK && error);
CHECK(slot<Bool1>(error, 3)(error) == false);
}
void check_blobs(const Blobs& blobs, char prefix, int writers, int count) {
for (int id = 0; id < writers; ++id) {
for (int k = 0; k < count; ++k) {
@@ -486,6 +692,7 @@ int main() {
CHECK(XTaskQueueCreate(kManual, kManual, &queue) == S_OK && queue);
const Saves saves{api, queue};
void* user = add_user(queue);
check_public_dispatch(user, api, package, started);
const std::string dir = saves_directory(kScid);
const std::string other_dir = saves_directory("scid-b");
@@ -875,6 +1082,6 @@ int main() {
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(id), id) == kNotInitialized);
std::printf("PASS: test_xgameruntime_saves (round trip, SCID isolation, damaged files, failed replace, "
"64 threaded + 160 cross-process submits, uninitialize; package %s)\n", id);
"64 threaded + 160 cross-process submits, uninitialize, public COM ids; package %s)\n", id);
return 0;
}