Compare commits

...
Author SHA1 Message Date
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
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
59 changed files with 10429 additions and 273 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: |
+59 -23
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`.
---
@@ -83,7 +95,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
- 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.
- **Provenance first:** Exclude anything (code, data, documentation, or observations) 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 patches, asset-specific workarounds, and decryption-related code are never adopted; general Xbox Game OS, Direct3D, DirectStorage, and runtime ABI contracts established from project-authorized builds that meet every Section 6 condition are in-scope compatibility work.
---
@@ -97,26 +109,32 @@ 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.
- **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.
- **Conditions for target builds:** A build is project-authorized only when a maintainer has approved it for compatibility research **and all** of the following hold. Approval is an additional condition, never a substitute: it cannot grant access or license rights that the project does not hold.
- The person inspecting it obtained it lawfully.
- Its license terms and applicable law permit the inspection performed.
- It is not leaked, stolen, confidential, or otherwise distributed without authorization, and neither are the tools used on it.
- Inspecting it requires no decryption and no circumvention of security, DRM, licensing, or activation controls.
If any condition is unknown, do not use the build. State in the PR which contracts come from target-build observation, without naming the title or build.
- **Never obtain or use** leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or unauthorized game builds and shader collections. Maintainer approval does not change this.
- **Repository & clean-tree boundary:** Never commit or paste proprietary executables, SDKs, confidential vendor documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, proprietary shaders, raw caller memory dumps, executable contents/addresses, private traces, proprietary file names or hashes, personal paths, or secrets into the repository, its Git history, commit messages, issues, or PR descriptions.
- **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.
---
## 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.
---
@@ -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 meets every required approval and check, 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.
+37
View File
@@ -10,6 +10,27 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
- **Not included:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source. Provenance is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
- **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 +47,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 +60,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.
@@ -81,6 +109,10 @@ remains unsupported.
- 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
- 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 +142,8 @@ 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
- 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 +157,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).
+2 -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).
+7 -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,9 @@ 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 the 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine. It does **not** load `bx_shader_bridge.dll`; the Rust bridge is exercised by `test_shader_gate.exe` instead.
- **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
+75
View File
@@ -0,0 +1,75 @@
# 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 |
No measurement of a title's shader corpus exists or is planned. BetterXen runs only original synthetic programs, so the DXIL vs. ACCC mix of real titles is unknown. 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 from a lawful workload shows ACCC-only containers in practice;
- 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.
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
- **Not covered by the gate yet:**
- **Stream PSOs:** `ID3D12Device2::CreatePipelineState` stream descriptions are still forwarded unparsed.
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
- **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 and public-source review.
+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.
+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.
+3 -2
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):
@@ -36,7 +37,7 @@ 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)** |
| **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 |
+630 -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, 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,131 @@ 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 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));
}
}
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 +306,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 +335,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 +621,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 +659,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 +830,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 +842,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 +856,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 +871,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 +913,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 +929,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 +950,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 +984,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 +999,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 +1071,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 +1549,117 @@ 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}");
}
}
+143 -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,
@@ -415,6 +446,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)
@@ -511,11 +577,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"
);
}
@@ -867,10 +934,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 +951,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");
+409 -5
View File
@@ -13,10 +13,130 @@ 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>,
/// `shader_bridge_missing` messages, in log order.
pub shader_bridge_missing: Vec<String>,
}
/// 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 +155,65 @@ 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);
}
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
let pairs = parse_key_values(detail, true);
// The emitter appends `: D3DMetal creates such pipelines ...` directly
// after the flags value, so strip the trailing colon.
let atomic64_flags = get_field(&pairs, "atomic64_flags")
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
summary.shader_gaps.push(ShaderGap {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
atomic64_flags,
});
}
pub fn summarize_jsonl(input: &str) -> TraceSummary {
let mut summary = TraceSummary::default();
for line in input.lines() {
@@ -48,11 +227,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 +352,221 @@ 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"));
}
}
+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();
@@ -186,22 +186,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();
+9 -4
View File
@@ -52,8 +52,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.
+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(
+75 -8
View File
@@ -1,9 +1,12 @@
#include "proxy.h"
#include "vmem.h"
#include <cstdio>
#include <cstring>
#include <new>
#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 +135,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 +204,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 +380,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,7 +410,21 @@ 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;
}
+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) {
+274
View File
@@ -0,0 +1,274 @@
#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;
/* Measured on D3DMetal (docs/research/d3dmetal-gpu-limits.md): pipelines that require a wave
* wider than 32 lanes, or 64-bit atomics, are created but never run. */
bool known_d3dmetal_gap(const Constraints& c) {
const bool wide_wave = c.has_lanes && c.lanes_min > 32;
return wide_wave || (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
}
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;
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 */
+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;
+878 -28
View File
File diff suppressed because it is too large. Load diff
+221
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>
@@ -290,8 +297,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 +597,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 +806,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)
@@ -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
@@ -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)
+473
View File
@@ -0,0 +1,473 @@
/*
* 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));
}
/* 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();
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();
// 3. Constraint-carrying DXIL still passes; its constraints are logged (results not dispatched).
hr = create_compute(device, root_uav, g_wave64_lanes_cs, sizeof(g_wave64_lanes_cs), &pso);
std::printf("wave64 PSO hr=0x%08lx\n", ul(hr));
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\"", "decision=pass_dxil", "wave_ops=1", "wave_lanes=64-64"}),
"shader_gate record with WaveSize(64)");
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();
}
@@ -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");
}
@@ -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;
}