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
ates cd72ef8ec3 [M2-E3] gameinput: implement device-callback lifecycle and SetFocusPolicy (#481)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 23:47:28 +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
Ateş 52e786664d Merge pull request #476 from jelly013/track-d/445-guest-shader-bridge
[M2-D] dxbc-accc: reach Windows guests as bx_shader_bridge.dll (#445)
2026-11-26 23:40:30 +03:00
Ateş b22ec27c79 Merge pull request #477 from sahib453/track-a/474-staging-ownership
[Track A] Keep system32 shim staging from overwriting files it did not create (#474)
2026-11-26 23:39:16 +03:00
sahib453 0749dcf236 Address review: stub visibility, link entries, partial staging
A bottle that launched from a different prefix fails the run only when
the staged shims cannot be found with the same contents there; a
private stub linking back to the managed prefix is accepted. The
destination entry is inspected without following links, so a dangling
symbolic link is a foreign entry and is left alone. New files are
installed without replacing anything. Temporary copies are all written
first and each installed file is recorded in the manifest before the
next, so a later failure leaves earlier files owned.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:06:27 +05:30
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 238daa6b25 dxbc-accc: tighten the guest build and check from review
guest/build.sh:
- Always build into, and copy from, <repo>/target, whatever
  CARGO_TARGET_DIR says, so a stale DLL can no longer be packaged.
- Resolve cargo and rustc through rustup, check that this rustc has std
  for x86_64-pc-windows-gnu, and print which rustc was used.
- Check the whole Export Address Table the way build-shims.sh does:
  every populated entry must be a direct RVA owned by one of the three
  names, so an ordinal-only extra or a forwarder fails. Imports must be
  Wine-provided system DLLs from an allowlist.

guest/check_bridge.c:
- Load the DLL by full path from the EXE's own directory.
- Check the exact DXIL and ACCC chunk sizes and the root signature
  flag, derived from the program's own chunk-table walk, and the
  digest against header bytes 4..20 for every container.
- Add a container with trailing bytes, checking that only the declared
  container is reported and copied.

The README documents how a calling shim must locate the bridge: by
full path from its own directory, not by bare name. It also records
that CI does not build the bridge yet.

Refs #445

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 21:27:51 +01:00
jelly013 7815a947e5 Merge remote-tracking branch 'upstream/main' into track-d/445-guest-shader-bridge
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:27:01 +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
Jelly 99bfbc26ef [M2-E2] Offline XGameSave and XPackage through QueryApiImpl (#472)
QueryApiImpl now serves offline XGameSave and XPackage as COM IUnknown
objects under BetterXen synthetic keys (shims/xgameruntime/synthetic_keys.h),
backed by bottle-local storage. Public Microsoft.GDK.Windows com_dispatch.cpp
wiring remains tracked in #468.

- XGameSave: provider init, containers, updates, blob writes, async submit
  and read, enumeration, and parent-child handle cascade close. Saves are
  isolated per SCID under C:\bx_pls\<exe_hash>\saves\<scid_hash>\ with
  atomic temp-file + MoveFileExW replacement, cross-process named mutex
  serialization, FILE_SHARE_DELETE readers, strict BXGS format validation,
  256-byte blob-name limits counted toward the 16 MiB update cap, and
  E_GS_OUT_OF_LOCAL_STORAGE mapping.
- XPackage: treats the running executable's directory as the installed
  package (BXPKG<16 hex> identifier, XPackageKind::Game, and mount queries).
- Lifetimes & XAsync: generic AsyncOp support with runtime generation guard
  before execute(), disjoint handle tag ranges, and full handle/result
  cleanup on final XGameRuntimeUninitialize.
- Tests: tests/conformance/test_xgameruntime_saves covering round-trip,
  SCID isolation, crafted corrupt files, atomic replace, 64 threaded +
  160 cross-process submits, uninitialize memory release, and UTF-8 paths.

Refs #468

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 23:21:19 +03: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 1ec92916b9 Keep system32 shim staging from overwriting files it did not create
Fixes the three points of #474 in bx-cli run. Staging records what it
wrote in a .bx-staged manifest (one SHA-256 per file) and replaces only
files listed there and unchanged since; any other same-named file stops
the run before anything is written. For a named bottle the prefix is
re-resolved after the run and a launch in a different prefix is
reported and fails the run. When initialization uses the whole
--timeout the guest is not started. Adds 9 unit tests.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 01:19:53 +05:30
jelly013 9d504d12d7 dxbc-accc: reach Windows guests as bx_shader_bridge.dll
Shims that see shader bytecode run as x86-64 PE32+ DLLs inside
CrossOver and cannot load the arm64 host library. Build this same crate
for x86_64-pc-windows-gnu instead: its cdylib becomes
bx_shader_bridge.dll, exporting exactly the three bx_shader_bridge.h
entry points, with no MinGW runtime DLL dependency. There is no second
implementation to keep in sync.

guest/build.sh builds the DLL, checks its exports and imports, and
builds check_bridge.exe, a C guest program compiled against the frozen
header. It sends a real DXC SM 6.6 blob and seven synthetic containers
through the DLL, checks classification, prepare and free, and prints a
DXIL vs. ACCC count. It passes under CrossOver 26.3 in a prefix and a
D3DMetal bottle.

The abi/defs export list, staging in build-shims and the d3d12_xs PSO
hook (#466) are separate changes.

Closes #445

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 20:43:56 +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
Ateş f7fb52bc56 Merge pull request #455 from Scarlet-Noble/track-f/453-d3dmetal-gpu-limits
[M2-F] D3DMetal GPU limits research and test_d3dmetal_gpu_limits fixture (#453)
2026-11-26 22:22:22 +03:00
atharvranjan ec2170d480 Merge main into track-f/453-d3dmetal-gpu-limits
Bring in main at cc5ce59 and resolve three documentation conflicts:

- CHANGELOG.md: keep the #453 entry above the entries added on main.
- docs/README.md: keep both new research links (swapchain references
  and D3DMetal GPU limits).
- docs/roadmap.md: take main's milestone table, including the verified
  M0/M1 status and the expanded M2 row, and append only the two
  measured-constraint links from this branch to the M2 and M3 rows.

No source, shader, header or research-note content changes relative to
either parent.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 13:16:44 -06:00
Ateş cc5ce59d21 Merge pull request #463 from MacosPorters/track-f/m2-docs-sync
[M2-F] Update README and roadmap for M1 completion and M2 kickoff
2026-11-26 21:35:40 +03:00
ates 61fc3590b2 Merge remote-tracking branch 'origin/main' into track-f/m2-docs-sync
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:34:31 +03:00
Ateş 58fc63c7ec Merge pull request #462 from MacosPorters/track-e/456-query-api-impl-dispatch
[M2-E] Public GDK COM QueryApiImpl dispatch in xgameruntime.dll (#456)
2026-11-26 21:33:40 +03:00
ates 600a0ab08f Merge remote-tracking branch 'origin/main' into track-f/m2-docs-sync
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:31:51 +03:00
ates cda66a57f2 Merge remote-tracking branch 'origin/main' into track-e/456-query-api-impl-dispatch
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:31:48 +03:00
ates a5c1995f21 Link Wave 2 M2 issues (#464-#469) in README progress board
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:25:25 +03:00
atharvranjan 868444ed30 Merge pull request #458 from Scarlet-Noble/track-a/457-system32-staging
[M1-A] Stage xgameruntime.dll and its shim imports into system32 (#457)
2026-11-26 12:22:56 -06:00
atharvranjan 510b6d1d66 Supervise wineboot and tolerate partial shim folders in system32 staging (#457)
A --shims folder without xgameruntime.dll made every bx-cli run fail; it is now reported and skipped.

wineboot --init ran before the signal handlers and outside --timeout, so Ctrl-C during a first run left wineserver and its services running. It now runs under the supervisor and shares the --timeout budget.

The temporary staging file name is now per process, so concurrent runs cannot publish each other's partial write.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 12:22:42 -06:00
ates 92c2ff7add Update README and roadmap for M1 completion and M2 kickoff
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:19:26 +03:00
ates 39baf092a3 Wire offline IXUser change-event and query slots in com_dispatch
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:17:41 +03:00
ates 0a30562cde Implement public GDK COM QueryApiImpl dispatch in xgameruntime.dll (#456)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:15:21 +03:00
Vicente Abarca fb56805459 Stage xgameruntime.dll and its shim imports into system32 (#457)
GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll",
NULL, LOAD_LIBRARY_SEARCH_SYSTEM32), which never searches WINEPATH, so
the bootstrap failed with E_GAMERUNTIME_DLL_NOT_FOUND before the #441
loader exports were reached.

bx-cli run now copies xgameruntime.dll into the environment's
drive_c/windows/system32 before launch. It also copies every BetterXen
shim that DLL imports, found with bx-probe (today bx_runtime_veh.dll),
because the restricted search also applies to a DLL's own imports.
Copies are idempotent and replaced through a rename, and bx-cli prints
what it staged. A bare --prefix with no system32 is initialized with
wineboot --init under the same isolated environment. A bottle with no
system32 fails with a hint.

Adds 8 unit tests for staging and the dependency walk, and
tests/conformance/test_system32_staging with a --expect-missing
negative control.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 15:00:38 -03:00
Vicente Abarca 1eb963d883 Address review of test_d3dmetal_gpu_limits and its note (#453)
Fixture:
- check_lock64 keeps its upload buffer alive until the list that copies
  from it has run.
- The spin lock takes an acquire DeviceMemoryBarrier after winning the
  lock, before reading the data, as well as the release barrier.
- A check that fails partway through recording closes and resets the
  list (abandon) instead of leaving stale commands for the next check.
- wave.control checks what D3D12 guarantees: one wave width for every
  thread, and lane indices forming a permutation within each wave, with
  waves identified by WaveReadLaneFirst(id.x). It no longer assumes
  lane == i % width.
- Skips with exit 77 when shader model 6.6 is unavailable or the query
  fails.
- submit checks Signal, SetEventOnCompletion and the Reset calls.
  Resources the GPU may still use are leaked rather than released after
  a hung or removed queue.

Note: the measured constraints are separated from the reports taken
from a commercial title. The reports move to an "Unverified reports
(not evidence)" section, each with the synthetic workload that would
verify it. The M2-gate inference is dropped, and the roadmap rows link
only the measured section. The results are re-measured after the fixes:
with the acquire fence, the 64-try cap drops 96-108 of 512 updates. The
1024-try cap is still exact.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 14:53:44 -03:00
Ateş ac0fd2e502 Merge pull request #454 from MacosPorters/track-a/408-bx-cli-supervision
[M1-A1] Supervised timeout, cleanup and trace summary for bx-cli run
2026-11-26 20:45:44 +03:00
ates 73c190d725 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 20:43:46 +03:00
ates f3c2b7fe34 Re-resolve bottle prefix on timeout/signal cleanup for managed first-launch stubs
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:43:20 +03:00
Ateş 4333a7cc5e Merge pull request #452 from skakwy/track-a/437-api-set-shims
Add API-set resolution fixture and ADR 0007 (#437)
2026-11-26 20:42:35 +03:00
ates 66e9351410 Require valid module lookups in test_apiset_resolution and accept ADR 0007
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:42:05 +03:00
Ateş 060083cc56 Merge pull request #441 from devil8blade/track-e/439-xgameruntime-dynamic-api-impl
[M1-E3][ABI] Dynamic GDK loader exports in xgameruntime.dll
2026-11-26 20:36:09 +03:00
Vicente Abarca 120a5ec5f6 Document D3DMetal GPU limits and add test_d3dmetal_gpu_limits (#453)
Adds docs/research/d3dmetal-gpu-limits.md: the D3DMetal and Apple GPU
constraints a shader translator has to handle (wave64 splitting, 64-bit
atomics and lock emulation, the 32 KiB mesh output limit, an Apple
shader compiler crash on early-merged output stores, and
OpenExistingHeapFromAddress). Each item is marked as either measured by
the new fixture or reported from local builds of a commercial title. It
is linked from the M2 and M3 roadmap rows and from the docs index.

Adds tests/conformance/test_d3dmetal_gpu_limits: an original D3D12
compute fixture that talks to the host d3d12.dll directly. It has four
original HLSL kernels with committed DXC 1.9.2609 output, and
shaders/compile.sh regenerates them. Expected values are computed on
the CPU.

On an Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from
source, D3DMetal 4.0b3) the WaveSize(64) pipeline and the kernels using
SM 6.6 64-bit atomics are created but never run. The bounded lock
emulation is exact at a 1024-try cap and drops updates at 64 tries.

Signed-off-by: Vicente Abarca <135478656+Scarlet-Noble@users.noreply.github.com>
2026-11-26 14:32:09 -03:00
atharvranjan 7d7249ee8b Clean up the bottle CrossOver actually launches; limit --backend to bottles
- Locate --bottle through CrossOver's CXBottle module with the launch's
  environment, so CX_BOTTLE_PATH, configured paths and managed bottles are
  stopped correctly. Refuse to launch if it cannot be located.
- Require --bottle for --backend: a bare prefix loads Wine's own D3D12.

Both reproduced by atesahmet0 on #454.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:19:36 -06:00
atharvranjan d0395a61da Add supervised timeout and cleanup to bx-cli run (#408)
- --timeout, and cleanup on timeout, SIGINT, SIGTERM or SIGHUP: stop the
  launcher process group, then wineserver for the selected bottle or prefix.
  wineserver -k exit 1 (nothing running) is accepted only if -w succeeds.
- Pass shim overrides with bin/wine --dll and --backend with --env in bottle
  mode, because bin/wine discards WINEDLLOVERRIDES and applies bottle
  settings over the environment. First found by jelly013.
- Print the trace summary after a run with --log.
- Record the libc dependency and a one-host D3D12 swapchain observation.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:01:28 -06:00
skakwyandClaude Sonnet 5.5 2eb59e033b Add API-set resolution fixture and ADR 0007 (#437)
test_apiset_resolution imports one export from each of the six win32_bridge
API-set DLLs through the PE import directory and reports, per name, whether a
BetterXen shim file or a host module serves it, and which module the import
address table slot is bound to. --expect host (default) or --expect shim
selects the outcome that passes.

On CrossOver 26.0 all six names are served by the host (twinapi.appcore.dll
for PSM, user32.dll for ntuser) and +loaddll shows no Loaded record for any
shim file. ADR 0007 proposes relying on Wine's built-ins and records that
evidence; a CrossOver 26.3 re-run is still needed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: skakwy <nils_0805@icloud.com>
2026-11-26 17:53:14 +01:00
Ateş eec56dd028 Merge pull request #448 from MacosPorters/track-f/446-boot-texture-computer
[M1-F2] Exercise the texture computer in test_integration_boot
2026-11-26 19:27:14 +03:00
devil8blade e7899574ab Keep XErrorReport logs valid UTF-8 and record loader provenance
Invalid bytes are written as \u00XX and a multi-byte character is not
split when the detail buffer fills. The six loader prototypes are
recorded as BetterXen-defined. The two changelog notes are one entry.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:25:51 +00:00
atharvranjan 486f7b197f Check full footprints and keep one Fixed changelog section
Also verify footprint format, width, height and depth, call Release through
the computer's own vtable, and state the release check precisely.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 10:11:04 -06:00
atharvranjan 390e85fc8d Exercise the texture computer in test_integration_boot
The fixture passed a null descriptor to XGCreateTextureComputer and reported
the stage as pending, although #415 implemented it. Create a 100x50 two-mip
RGBA8 computer, check its layout against hand-computed values, require the
suggested layout to be linear and require release to free the object.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 10:09:10 -06:00
devil8blade 18178da12c Address review: surface unsupported QueryApiImpl in trace, null out on failure
Unsupported and mismatched QueryApiImpl queries keep their structured log
and also call BX_STUB_LOG so bx-cli trace lists them. Failure paths clear
the output pointer. XErrorReport uses the public void signature.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:05:11 +00:00
Ateş bfa80dee8b Merge pull request #440 from MacosPorters/track-a/438-trace-summary
Report sampled CLWB bounds and guest crashes in bx-cli trace
2026-11-26 18:47:38 +03:00
ates 829a94fa2f bx-cli: print clwb VEH traps : 0 when no CLWB records exist
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:47:28 +03:00
devil8blade 2e895e0f9b Export GDK dynamic loader entry points from xgameruntime.dll
The static loader resolves InitializeApiImpl, InitializeApiImplEx,
InitializeApiImplEx2, UninitializeApiImpl, QueryApiImpl, and XErrorReport
with GetProcAddress. Those initialize entry points share the existing
runtime refcount with XGameRuntimeInitialize and
XGameRuntimeInitializeWithOptions. UninitializeApiImpl releases that same
state. QueryApiImpl dispatches the offline families this DLL already
implements and logs any other class or interface. XErrorReport records
the code and message and does not terminate the process.

Closes #439

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 15:38:34 +00:00
Ateş 02b8924de7 Merge pull request #427 from MacosPorters/track-b/412-xmem-physical
[M1-B2] Map xmem physical pages into shared aliases
2026-11-26 18:31:10 +03:00
ates 925311e852 Merge main and address PR #427 review findings
- Wire physical-page accounting into xmem.cpp via shims/xmem/xmem_accounting.h so XMemGetWorkingSetStatistics and bx_xmem_get_internal_stats report allocated_physical_bytes and enforce one shared title memory budget across heap, virtual, and physical allocations.
- Require exact full-span coverage in unmap_span; empty or partially mapped spans now fail with ERROR_INVALID_PARAMETER without disturbing existing views.
- Document Win32 AWE-modeled synthetic signatures (AllocateUserPhysicalPages / FreeUserPhysicalPages in memoryapi.h) and intra-span duplicate-tag aliasing vs duplicate-tag free rejection.
- Expand test_xmem_physical to cover working-set stats, shared cap enforcement, invalid flags, intra-span duplicate-tag aliasing, duplicate and stale free non-mutation, and partial/empty unmap rejection.
- Resolve CHANGELOG.md conflict with origin/main.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:30:37 +03:00
Ateş f7194d0255 Merge pull request #431 from MacosPorters/track-a/410-win32-bridge
[M1-A3] Cover Win32 bridges and track offline PSM registrations
2026-11-26 18:20:03 +03:00
ates 7ea4f1f6ca Merge main and address PR #431 review findings
- Replace std::mutex/std::unordered_set + -fexceptions in psm_appnotify.cpp with a Win32 SRWLOCK and HeapAlloc open-addressed token set, keeping -fno-exceptions and reducing both PSM DLLs from ~2.4 MB back to 118 KB.
- Tag state (PSM1) and constrained (PSM2) tokens so cross-family unregisters log foreign_token while duplicate, null, or arbitrary invalid tokens log unknown_token.
- Fix load_bridge to call FreeLibrary on path mismatch or path-query failure without leaking the module handle or reporting a stale GetLastError().
- Verify exact per-(event, detail) JSONL counts inside test_win32_bridge (both with caller-provided BX_LOG_FILE and a self-managed temp log).
- Resolve CHANGELOG.md conflict with origin/main.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:19:30 +03:00
Ateş bd8edd8f70 Merge pull request #429 from MacosPorters/track-e/419-audio-input
Implement bounded audio queues and GameInput ordinal 1 COM stub
2026-11-26 18:09:00 +03:00
ates 058bc981dc Merge main and address PR #429 review findings
- Reject ApuAlloc before ApuCreateHeap is called and reset used=0 explicitly on heap creation
- Validate max_streams > 0 and record it on DSP connections in XDspConnectWithMaximumStreamLimit
- Expand test_audio_input to cover pre-heap ApuAlloc failure, single-output ApuAlloc, zero max_streams rejection, and GameInput v0 QueryInterface/method dispatch
- Resolve CHANGELOG.md merge conflict with main

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:08:53 +03:00
ates a8c4dbb77e Report sampled CLWB bounds and guest crashes in bx-cli trace
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:08:33 +03:00
Ateş d8b83818c1 Merge pull request #430 from MacosPorters/track-a/409-veh-clwb-crash-log
[M1-A2] Cover CLWB addressing and log unhandled guest exceptions
2026-11-26 18:01:49 +03:00
ates 0a2544cd51 Merge main and address review feedback on REX decoding, crash write isolation, and marker constant
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:01:41 +03:00
Ateş 0082d16b1e Merge pull request #424 from MacosPorters/track-b/411-xmem-core
[M1-B1] Enforce xmem title memory budgets
2026-11-26 17:19:59 +03:00
ates 4c7f1c5aff Merge main, sanitize console memory attributes in XMemVirtualAlloc, and zero larger stats tail
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:19:52 +03:00
Ateş d72350c854 Merge pull request #426 from MacosPorters/track-b/413-xcrdapi-dstorage
[M1-B3] Exercise asynchronous storage through XCRDAPI
2026-11-26 17:17:27 +03:00
ates cee636193a Cover Win32 bridges and track offline PSM registrations
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:13:12 +03:00
ates 134eee3a28 Cover CLWB addressing and log unhandled guest exceptions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:13:12 +03:00
ates 43f32acb82 Implement bounded audio queues and GameInput COM stub
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:06:36 +03:00
ates ab696f1f07 Map xmem physical pages into shared aliases
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:52:04 +03:00
ates 19c240edd5 Enforce xmem title memory budgets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:38:59 +03:00
109 changed files with 22626 additions and 476 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.
+85
View File
@@ -10,6 +10,78 @@ 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.
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
- name rules, the write and read round trip, and the size limits;
- SCID isolation and enumeration;
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
- 64 threaded and 160 cross-process concurrent submits;
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
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.
Everything else is printed as `OBSERVED:` lines. On one Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from source, D3DMetal 4.0b3), three runs gave the same outcomes, with 4/4 required checks passing each time:
- the `[WaveSize(64)]` pipeline is created but never runs;
- kernels using SM 6.6 64-bit atomics, on a typed UAV or a raw buffer, are created but never run, although the device reports support for them; a plain-store marker beside the atomics shows the skip;
- a 64-try lock cap drops 96–108 of 512 updates.
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.
- **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently.
- **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed.
- **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running.
- **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix.
- **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host.
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
- Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437).
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
- `xgameruntime.dll` exports BetterXen-defined `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, `UninitializeApiImpl`, `QueryApiImpl`, and `XErrorReport` so a static loader can resolve them. No public prototype for those six names was found. The documented `XGameRuntimeInitialize`, `XGameRuntimeUninitialize`, `XGameRuntimeInitializeWithOptions`, and `XGameRuntimeOptions` behavior is what the shared refcount follows. `QueryApiImpl` rejects a missing output or id, clears the output pointer on failure, dispatches the offline families this DLL already implements, and logs any other class through `BX_STUB_LOG` before `E_NOINTERFACE`. `XErrorReport` is `void` and writes only valid UTF-8, replacing an invalid byte with `\u00XX` and truncating on a character boundary. The DLL has 49 exports. This is not an Xbox hardware result (#439).
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
- Added a BetterXen-only DirectStorage conformance interface for asynchronous uncompressed file and memory transfers, status arrays, and completion events in `XCRDAPI.dll` (#413).
- Implemented offline `xgameruntime.dll` task queues and async completion, local user handles, synthetic game-license queries, console identity, and bottle-local storage (#418). Added a synthetic conformance executable for Lockhart and Anaconda launches. Only the marked conformance title receives an active synthetic SKU. The build also produces an unmarked control with the same executable name. Queue shutdown delivers accepted callbacks, and bottle-local storage is keyed by executable path.
- `xg_xs.dll` computes linear 2D layouts for `R8G8B8A8` and BC1 through BC7 (`XGCreateTextureComputer`, `XGSuggestSwizzleMode`, and COM `IXGTextureAddressComputer`). Row pitch uses the public D3D12 256-byte alignment and each subresource is placed on the public 512-byte alignment. `GetResourceLayout` reports that aligned allocation span in `total_bytes` (512 for a 1x1 RGBA8 texture) and a separate D3D12-style `copy_end` on each footprint (4 for that same texture). Sizes are overflow-checked, null pointers return `E_POINTER`, and copies stay inside the caller buffers. `SW_64KB_S`, `SW_64KB_D`, and `SW_64KB_R` return `E_NOTIMPL` and write no address. Synthetic `test_xg_xs.exe` checks hand-computed mip offsets, alignment, refcounts, and a byte-identical copy round trip. This is not an Xbox hardware result (#415).
@@ -37,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.
@@ -66,6 +142,12 @@ 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).
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
@@ -75,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).
Generated
+7
View File
@@ -9,6 +9,7 @@ dependencies = [
"bx-probe",
"bx-telemetry",
"dxbc-accc",
"libc",
]
[[package]]
@@ -29,3 +30,9 @@ dependencies = [
[[package]]
name = "dxbc-accc"
version = "0.2.0"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+22 -21
View File
@@ -9,13 +9,13 @@
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: D3DMetal 3.0](https://img.shields.io/badge/graphics-D3DMetal%203.0%20%2F%20Metal-8957e5)
![Stack: Rust + C++20 PE32+](https://img.shields.io/badge/stack-Rust%20%2B%20C%2B%2B20%20PE32%2B-dea584)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M0)-d29922)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M2)-0969da)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
</div>
> [!IMPORTANT]
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
@@ -33,9 +33,9 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
```mermaid
flowchart LR
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
M2["M2: First Frame &\nShader Gate"]:::planned
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
M3["M3: Shaders &\nTexture Tiling"]:::planned
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
M5["M5: Audio, Saves\n& Stability"]:::planned
@@ -50,16 +50,16 @@ flowchart LR
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
| Track | Focus | Visual Status | Live Issues |
| --- | --- | --- | --- |
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
@@ -67,9 +67,9 @@ 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`) | 🟢 **Merged (`#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`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
| **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 |
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
@@ -129,10 +129,10 @@ 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 |
| `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)) |
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
@@ -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.
+65 -1
View File
@@ -1,6 +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. 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)
@@ -11,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
+6
View File
@@ -43,3 +43,9 @@ EXPORTS
XGameUiShowTextEntryAsync
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
XNetworkingQuerySecurityInformationForUrlAsync
InitializeApiImpl
InitializeApiImplEx
InitializeApiImplEx2
UninitializeApiImpl
QueryApiImpl
XErrorReport
+4
View File
@@ -14,6 +14,8 @@
- [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
@@ -21,6 +23,8 @@
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
## Governance, Security & Legal
+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
@@ -0,0 +1,45 @@
# ADR 0007: API-set win32_bridge shims are not reached under CrossOver
Status: **Accepted** (2026-11-26, issue #437). Independently verified on CrossOver 26.0 and CrossOver 26.3 on Apple Silicon.
## Context
`shims/win32_bridge/` builds six DLLs named after Windows API sets:
`api-ms-win-core-psm-appnotify-l1-1-0`, `api-ms-win-core-psm-appnotify-l1-1-1` and four `ext-ms-win-rtcore-ntuser-*` forwarders to `user32.dll`. A guest that imports those names statically is expected to load the BetterXen files placed next to the EXE. #437 reports that under CrossOver 26.3 it does not: Wine answers the names itself, even with `WINEDLLOVERRIDES=<name>=n,b` and the shim files in the EXE's directory.
## Evidence
`tests/conformance/test_apiset_resolution` imports one export from each of the six DLLs through the PE import directory, then reports for every name the module that owns the name and the module the loader bound the import address table slot to.
Run on an Apple M-series Mac, macOS 27.2.1, Rosetta 2, **CrossOver 26.0 (`26.0.0.39794`)**, bare prefix, with the override list from `bx-cli` (`SHIM_DLL_OVERRIDES`) and `build-shims/bin` as the EXE directory:
| Import name | Served by | Module that owns the name | Module the import is bound to |
| --- | --- | --- | --- |
| `api-ms-win-core-psm-appnotify-l1-1-0` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `api-ms-win-core-psm-appnotify-l1-1-1` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
`WINEDEBUG=+loaddll` shows `Loaded` records for `user32.dll` and `twinapi.appcore.dll` (both builtin) and none for any of the six shim files. `--expect shim` fails 0/6, so the fixture does distinguish the two outcomes.
This behaviour was independently reproduced on **CrossOver 26.3** on Apple Silicon (`bx-cli run` with the shim directory and direct loader runs with `WINEDEBUG=+loaddll`), yielding the exact same 6/6 host resolution (`twinapi.appcore.dll` and `user32.dll`, both builtin, with no `Loaded` records for the six shim files) and `--expect shim` exiting 1. The internal Wine mechanism is not claimed here; this records observed loader behaviour.
## Decision
Rely on Wine's built-ins. Under CrossOver the six API-set shims are not part of the supported path: the host answers window and message calls through `user32.dll` and PSM registration through `twinapi.appcore.dll`.
- The six DLLs stay in the tree, built and export-checked, and are still exercised by explicit full-path loads (#431).
- No attempt is made to make them win name resolution. That would depend on undocumented Wine API-set behaviour (#350) and, within this issue's scope, on patching or redistributing CrossOver or Wine components, which is out of scope.
- Offline PSM behaviour that a title needs must live somewhere a static import actually reaches. This ADR does not choose that place.
## Consequences
- `test_apiset_resolution` records the current behaviour (`--expect host`) and fails when it changes. If a CrossOver build starts loading the shims, run it with `--expect shim` and revisit this ADR.
- `test_integration_boot` continues to report `shim_backing` as pending for these six names under CrossOver.
- Documentation describes the bridges as Windows-only stubs that CrossOver does not load for static imports.
## Not claimed
Nothing here shows Xbox title compatibility, behaviour on Xbox hardware, or behaviour on CrossOver builds outside 26.0 and 26.3. Evidence class: local Apple Silicon runs.
+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.
+2 -2
View File
@@ -9,7 +9,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
@@ -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
+4
View File
@@ -20,5 +20,9 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
| 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.
+169
View File
@@ -0,0 +1,169 @@
# D3DMetal and Apple GPU limits for a shader translator
Constraints that a translator emitting shaders for D3DMetal on Apple Silicon has to
handle (#453). Writing the translator is out of scope.
The note has two parts:
- [Measured constraints](#measured-constraints) come from
`tests/conformance/test_d3dmetal_gpu_limits`, an original synthetic D3D12 compute
fixture checked against values computed on the CPU. These are the only items the
roadmap links to. They are a local Apple Silicon run by the implementer, class A for
the stated host only, not independently reproduced.
- [Unverified reports](#unverified-reports-not-evidence) are observations a contributor
posted on #453 from local builds of another project running a commercial title. They are
**not evidence** under [AGENTS.md](../../AGENTS.md) §5–6 and must not steer the plan
until a synthetic workload reproduces them. They are kept only as leads for writing such
workloads.
Nothing here is an Xbox hardware result, and nothing generalizes beyond the D3DMetal
version named.
## Measured constraints
### `WaveSize(64)` is created but not run
`wave.control` (no `WaveSize`) and `wave.wavesize64` (`[WaveSize(64)]`, SM 6.6) record,
for each thread, the wave width, its lane index and the dispatch index of its wave's first
lane.
The control passes the check D3D12 actually guarantees: every thread reports the same
width, and within each wave the lane indices are a permutation of `0..W-1`. No particular
thread-to-lane order is assumed. On D3DMetal 4.0b3:
- the device reports `WaveLaneCountMin = WaveLaneCountMax = 32`;
- the control runs at width 32;
- the wave64 pipeline is **created without error but never runs**: its output buffer keeps
the sentinel.
So a translator cannot rely on pipeline creation failing. A program written for a 64-lane
wave has to be emitted as 32-lane code, with its two halves made to agree wherever the
original wave acted as one.
### Kernels using SM 6.6 64-bit atomics are created but not run
`atomic64.image` runs a 64-bit `InterlockedAdd` (low halves carrying into the high half)
and an `InterlockedMax` (decided by the high half) on a `RWTexture2D<uint64_t>` over
`DXGI_FORMAT_R32G32_UINT`. `atomic64.buffer` runs the same operations on a raw buffer. Each
kernel also writes a plain 64-bit marker next to its atomics, which shows whether the kernel
ran at all. On D3DMetal 4.0b3:
- The device reports `AtomicInt64OnTypedResourceSupported` and
`AtomicInt64OnDescriptorHeapResourceSupported` as supported, and both pipelines are
created without error.
- Neither kernel runs. The atomic results and the markers all read back as their initial
zeros, on the texture and on the raw buffer alike.
- A throwaway variant with the atomics removed but the markers kept wrote 8/8 markers.
That shows the readback path is sound and the skip comes from the atomics.
So these kernels are silently skipped, on raw buffers as well as images. This is
consistent with d3dmetal-native's `d3d12-atomic64-test` reading back zeros in the
[d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) evaluation
on D3DMetal 3.0. A translator has to lower 64-bit atomics to 32-bit operations.
### Lock-based emulation needs a sufficient retry cap and both fences
`lock64.cap64` and `lock64.cap1024` emulate both operations with a per-texel lock word,
with 32 contending threads per texel and a bounded number of tries:
1. take the lock with `InterlockedCompareExchange` 0→1;
2. `DeviceMemoryBarrier()` (**acquire**: the data reads are ordered after taking the lock;
`globallycoherent` gives visibility, not ordering);
3. update the two 32-bit halves;
4. `DeviceMemoryBarrier()` (**release**);
5. free the lock with `InterlockedExchange`.
A thread that runs out of tries counts a drop instead of spinning on. The 1024-try run is
required to drop nothing and to match the CPU reference exactly. The 64-try run is
reported. On D3DMetal 4.0b3, in three runs each:
- **1024 tries:** nothing dropped, 16/16 values exact, about 15,000–18,000 tries in all.
- **64 tries:** 96–108 of 512 updates dropped.
So a low cap trades a hang for silently lost updates. With 32 contending threads, 64 tries
is already too low.
The loop shape matters. The critical section sits **inside** the retry loop, so a lane
that wins finishes it in the same iteration, and no lane waits for another lane to leave a
loop. The fixture does not run the classic shape (`while (!acquire()) {}` followed by the
critical section). There, the winning lane can be parked at the loop's reconvergence point
behind the lanes still spinning, and on a GPU without independent forward progress for
each thread that could hang the queue. Apple's shader converter prints `Warning:
Undefined: Shader might rely on forward progress/persistent thread` even for the safe
shape.
## Fixture results
A local run by the implementer on 2026-11-26. Class A for this host only; not
independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
| | |
| --- | --- |
| Host | Apple M3 Pro, macOS 27.2.1 (26B131), Rosetta 2 |
| Wine | CodeWeavers Wine 11.0 built from CodeWeavers' published source; CrossOver itself was not installed |
| D3DMetal | 4.0b3 from Apple's Game Porting Toolkit (x86_64; SHA-256 of the binary starts with `b16aab78127d`), user-supplied |
| Shaders | DXC 1.9.2609 via `shaders/compile.sh`; the same DXC reproduces the d3dmetal-harness `fill_cs66` container byte for byte (SHA-256 `7df11b63…`) |
| Command | `ROSETTA_ADVERTISE_AVX=1 WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" wine build-shims/bin/test_d3dmetal_gpu_limits.exe` in a fresh prefix |
| Runs | 3, identical outcomes apart from the 64-try drop counts; exit 0, `SUMMARY: 4 required checks, 0 failed` each time |
| Check | Outcome |
| --- | --- |
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
| `wave.wavesize64` | created but not run (output still sentinel) |
| `atomic64.reported` | typed and descriptor-heap 64-bit atomics reported as supported |
| `atomic64.buffer` | not run: marker 0/8, atomic values 16/16 still zero |
| `atomic64.image` | not run: marker 0/8, atomic values 16/16 still zero |
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
(D3DMetal 3.0) by another contributor.
## Unverified reports (not evidence)
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
host. None of this is a BetterXen measurement, no code or shader from that project is
used, and none of it may be cited by the roadmap or a milestone gate. Each item names the
synthetic workload that would turn it into evidence.
- **Splitting wave64 programs.** Operations that need care when the two halves must agree:
- wave reductions;
- first-lane and indexed lane reads;
- the 64-bit lane mask read as data;
- cross-half permutes;
- scalar values spilled into vector lanes;
- group barriers, which are only safe where both halves provably reach them.
The reporter found a uniformity analysis of the program's values, with barriers placed
only after uniform branches, made most such programs translate exactly. Where agreement
cannot be proven and each half runs as its own wave, a group sync that not every lane
reaches must become a memory fence without the group wait. *Workload needed:* SM 6.6
wave64-style kernels with each of these patterns, checked half by half.
- **Helper lanes in a spin lock.** In a pixel shader, helper lanes must not take part in
such a lock: their atomics have no effect, so they never win and spin to the cap. This
was reported as a hard queue hang with no macOS GPU timeout logged. A cap of 2^16 was
reported to hang while 2^10 did not; whether the cap or the helper lanes caused it was not
separated. *Workload needed:* a pixel shader with a lock-protected 64-bit update across
triangle edges.
- **Mesh output size.** Metal refuses mesh pipelines whose per-vertex outputs exceed 32,768
bytes, counting the aligned layout (distances, position, then outputs in register order,
each aligned to its own size). A refused pipeline submitted anyway was reported to hang
the queue under Wine. *Workload needed:* mesh shaders whose output size crosses 32 KiB
only once alignment is counted.
- **Apple shader compiler crash.** `MTLCompilerService` was reported to crash in register
allocation on mesh pipelines whose pixel shader writes several render targets. The
reported cause was output stores merged before all their values are defined, and the
reported fix was emitting each output row's stores after its values. *Workload needed:* a
mesh and pixel pair with several render targets and late-computed outputs.
- **No zero-copy heaps.** D3DMetal 4.0b3 was reported to answer
`ID3D12Device3::OpenExistingHeapFromAddress` with "Not implemented". *Workload needed:*
a fixture that calls it on a page-aligned allocation.
## Regenerating the shaders
`tests/conformance/test_d3dmetal_gpu_limits/shaders/compile.sh` regenerates the committed
headers with Microsoft's DXC release v1.9.2609 (`dxc_2026_09_29.zip`, SHA-256
`ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1`, the same package the
d3dmetal-harness records), running `bin/x64/dxc.exe` under a Wine loader.
@@ -0,0 +1,88 @@
# 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. See the independent Apple M2 Pro run below.
| | D3DMetal | Wine `vkd3d` path |
| --- | --- | --- |
| References on the swapchain right after creation | 2 | 1 |
| Count returned by the application's final `Release` | 1 | 0 |
| Swapchains still referenced after 12 create/release cycles | 12 | 0 |
The same program was used for both, and it submitted no GPU work of its own. Under D3DMetal
each retained swapchain also kept a device reference. The cause inside D3DMetal is unknown. A
program that recreates swapchains (for example on resize) should be expected to grow until this
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.
+17
View File
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
## Built and run for M1-D2 (#417)
@@ -25,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.
+6 -5
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,10 +37,10 @@ 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 | **In validation (PR #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`, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, and combined synthetic integration boot fixture | All 13 Wave 1 conformance binaries pass under CrossOver + Rosetta 2; combined `integration_boot.exe` initializes every subsystem cleanly | **Next (Wave 1 ready)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, and `dxbc-accc` shader inspection to establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)** | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | Planned |
| **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 | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), 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 |
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
+2
View File
@@ -13,6 +13,8 @@ path = "src/main.rs"
bx-probe = { path = "../bx-probe" }
bx-telemetry = { path = "../bx-telemetry" }
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
# POSIX signals and process groups for `run` supervision.
libc = "=0.2.191"
[lints]
workspace = true
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+492
View File
@@ -0,0 +1,492 @@
//! Supervision for `bx-cli run` (#408): the launcher gets its own process group, and a timeout
//! or signal stops that group and then the environment's `wineserver`.
//!
//! The `wineserver` is stopped only after a timeout or signal, never after a normal exit,
//! because it ends every program in that bottle or prefix, not only this run's.
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::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use std::time::{Duration, Instant};
const POLL: Duration = Duration::from_millis(50);
/// How long the launcher group has to exit after SIGTERM before SIGKILL.
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);
}
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,
Signalled(i32),
}
#[derive(Debug)]
pub enum Outcome {
Exited(ExitStatus),
Stopped(Stop),
}
impl Outcome {
/// 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 {
// 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),
}
}
}
fn signal_group(child: &Child, signal: libc::c_int) {
// SAFETY: kill takes no pointers. The child leads its own group and has not been reaped,
// so the group id cannot have been reused.
unsafe {
libc::kill(-(child.id() as libc::pid_t), signal);
}
}
fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if Instant::now() >= deadline {
return Ok(None);
}
std::thread::sleep(POLL);
}
}
/// 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.
if std::io::stdin().is_terminal() {
command.stdin(Stdio::null());
}
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));
}
let received = signal();
if received != 0 {
break Stop::Signalled(received);
}
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);
};
signal_group(&child, libc::SIGTERM);
// Wait without reaping first, so SIGKILL still reaches members that outlive the leader.
std::thread::sleep(POLL);
let deadline = Instant::now() + GRACE;
while Instant::now() < deadline && group_leader_running(&child) {
std::thread::sleep(POLL);
}
signal_group(&child, libc::SIGKILL);
wait_until(&mut child, Instant::now() + GRACE)?;
Ok(Outcome::Stopped(stop))
}
/// True while the leader has not exited; does not reap it.
fn group_leader_running(child: &Child) -> bool {
// SAFETY: `info` is a valid, writable siginfo_t and WNOWAIT leaves the child unreaped.
unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
libc::waitid(
libc::P_PID,
child.id() as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
) == 0
&& info.si_pid() == 0
}
}
/// `wineserver -k` then `-w` for the environment at `prefix`.
///
/// `-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,
environment: &[(String, String)],
) -> Result<(), String> {
for (flag, idle_code) in [("-k", Some(1)), ("-w", None)] {
let mut child = Command::new(wineserver)
.arg(flag)
.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) {
Ok(Some(status)) if status.success() => {}
Ok(Some(status)) if idle_code.is_some() && status.code() == idle_code => {}
other => {
let _ = child.kill();
let _ = child.wait();
return Err(format!("wineserver {flag} did not succeed: {other:?}"));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
fn shell(script: &str) -> Command {
let mut command = Command::new("/bin/sh");
command.args(["-c", script]);
command
}
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("bx-cli-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn classifies_exit_timeout_and_signal() {
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(), 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);
let interrupted = supervise(shell("sleep 30"), None, || libc::SIGTERM).unwrap();
assert_eq!(interrupted.exit_code(), 128 + libc::SIGTERM as u8);
}
#[test]
fn a_timeout_stops_children_that_ignore_sigterm() {
let dir = scratch("group");
let pid_file = dir.join("child.pid");
let script = format!(
"(trap '' TERM; exec sleep 30) & echo $! > '{}'; wait",
pid_file.display()
);
supervise(shell(&script), Some(Duration::from_millis(500)), || 0).unwrap();
let pid: libc::pid_t = std::fs::read_to_string(&pid_file)
.unwrap()
.trim()
.parse()
.unwrap();
let gone = (0..100).any(|_| {
std::thread::sleep(POLL);
// SAFETY: signal 0 only checks whether the process exists.
unsafe { libc::kill(pid, 0) != 0 }
});
assert!(gone, "grandchild {pid} survived the timeout");
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");
for (name, kill, wait, ok) in [
("running", 0, 0, true),
("idle", 1, 0, true),
("stuck", 1, 1, false),
("broken", 2, 0, false),
] {
let server = dir.join(name);
std::fs::write(
&server,
format!("#!/bin/sh\n[ \"$1\" = -k ] && exit {kill}\nexit {wait}\n"),
)
.unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(stop_server(&server, &dir, &[]).is_ok(), ok, "{name}");
}
std::fs::remove_dir_all(dir).unwrap();
}
}
+497 -3
View File
@@ -1,18 +1,150 @@
//! Track A / F: Structured JSONL shim trace aggregator.
//!
//! Summarizes `bx_runtime_veh.dll` logs (stub API calls, unimplemented COM vtable
//! slots, `clwb` traps, and ADX illegal-instruction tripwires) so tracks can prioritize
//! the exact next blocking API.
//! slots, `clwb` traps, ADX illegal-instruction tripwires, and unhandled exceptions)
//! so tracks can identify guest failures and missing APIs.
use std::collections::BTreeMap;
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TraceSummary {
pub total_lines: usize,
/// Number of `clwb_trapped` records in the log.
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)]
pub struct UnhandledException {
pub exception_code: Option<String>,
pub module_base: Option<String>,
pub rva: Option<String>,
pub rip: Option<String>,
}
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
@@ -23,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() {
@@ -34,8 +225,31 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
let event = extract_json_str(trimmed, "event").unwrap_or("");
let detail = extract_json_str(trimmed, "detail").unwrap_or("");
match event {
"clwb_trapped" => summary.clwb_events += 1,
"clwb_trapped" => {
summary.clwb_events += 1;
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" => {
summary.unhandled_exceptions.push(UnhandledException {
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
});
}
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
"unimpl_vtable" => {
*summary
@@ -64,7 +278,9 @@ mod tests {
let s = summarize_jsonl(sample);
assert_eq!(s.total_lines, 4);
assert_eq!(s.clwb_events, 1);
assert_eq!(s.clwb_trap_lower_bound, Some(1));
assert_eq!(s.adx_errors, 0);
assert!(s.unhandled_exceptions.is_empty());
assert_eq!(
s.unimpl_apis.get("d3d12_xs.dll!D3D12XboxCreateDevice"),
Some(&2)
@@ -75,4 +291,282 @@ mod tests {
Some(&1)
);
}
#[test]
fn uses_highest_counter_from_sampled_clwb_records() {
for (actual_traps, records, expected_bound) in [
(1, &[1][..], 1),
(6, &[1, 4, 2], 4),
(100, &[1, 2, 4, 8, 16, 32, 64], 64),
] {
let mut log = String::new();
for counter in records {
log.push_str(&format!(
"{{\"event\":\"clwb_trapped\",\"detail\":\"rip=0x1000 len=4 total_traps={counter}\"}}\n"
));
}
let summary = summarize_jsonl(&log);
assert_eq!(summary.clwb_events, records.len(), "{actual_traps} traps");
assert_eq!(
summary.clwb_trap_lower_bound,
Some(expected_bound),
"{actual_traps} traps"
);
}
}
#[test]
fn preserves_clwb_record_count_without_valid_counters() {
let summary = summarize_jsonl(
r#"{"event":"clwb_trapped","detail":"rip=0x1000 len=4"}
{"event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=invalid"}
{"event":"unimpl_api","detail":"total_traps=100"}"#,
);
assert_eq!(summary.clwb_events, 2);
assert_eq!(summary.clwb_trap_lower_bound, None);
}
#[test]
fn collects_unhandled_exceptions_in_log_order() {
let log = r#"
{"ts_ms":16,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc0000005","module_base":"0x0000000140000000","rva":"0x0000000000001234","rip":"0x0000000140001234","rsp":"0x000000000021fd80","registers":{"rax":"0x0123456789abcdef","rbx":"0x0000000000000000","rcx":"0x0000000000000000","rdx":"0x0000000000000000","rsi":"0x0000000000000000","rdi":"0x0000000000000000","rbp":"0x0000000000000000","r8":"0x0000000000000000","r9":"0x0000000000000000","r10":"0x0000000000000000","r11":"0x0000000000000000","r12":"0x0000000000000000","r13":"0x0000000000000000","r14":"0x0000000000000000","r15":"0x0000000000000000"}}
{"ts_ms":20,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc000001d","module_base":"0x0000000000000000","rva":"0x0000000000000000","rip":"0x0000000000410000","rsp":"0x000000000021fd80","registers":{}}
"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.total_lines, 2);
assert_eq!(
summary.unhandled_exceptions,
[
UnhandledException {
exception_code: Some("0xc0000005".into()),
module_base: Some("0x0000000140000000".into()),
rva: Some("0x0000000000001234".into()),
rip: Some("0x0000000140001234".into()),
},
UnhandledException {
exception_code: Some("0xc000001d".into()),
module_base: Some("0x0000000000000000".into()),
rva: Some("0x0000000000000000".into()),
rip: Some("0x0000000000410000".into()),
},
]
);
}
#[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();
@@ -0,0 +1,64 @@
# dxbc-accc
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
## Guest access: `bx_shader_bridge.dll` (#445)
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
- **Build:** `cargo build --target x86_64-pc-windows-gnu` turns the crate's `cdylib` into a PE32+ DLL, published as `bx_shader_bridge.dll`. Its Export Address Table holds exactly the three header functions as direct RVAs. It imports only Windows system DLLs that Wine provides, so no MinGW runtime DLL. `guest/build.sh` enforces both. The allowlist is `KERNEL32`, `ntdll`, `bcryptprimitives`, `USERENV`, `WS2_32` and the `api-ms-win-crt-*` / `api-ms-win-core-*` sets.
- **Callers:** a shim loads the bridge at run time with `GetProcAddress`, so a missing bridge is a logged condition, not a load failure of the shim.
- **Full path:** it must load the bridge by **full path from its own directory**. That is `GetModuleFileNameW` of the shim's own module (for example via `GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, ...)`), plus `bx_shader_bridge.dll`, loaded with `LoadLibraryExW(..., LOAD_WITH_ALTERED_SEARCH_PATH)`.
- **Why not the bare name:** a bare `LoadLibraryW(L"bx_shader_bridge.dll")` searches the guest EXE's directory first under the [standard search order](https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order). It can therefore miss a bridge staged next to the shims, or pick up a different copy.
- **Staging:** the bridge is meant to be staged in the same directory as the shims that call it.
- **Why not a host tool over captured logs:** the M2 gate needs the decision at `Create*PipelineState` time inside the guest. That means passing DXIL through and rejecting ACCC-only containers. An offline host tool could count shaders but could not act on them.
### Build and check
```sh
rustup target add x86_64-pc-windows-gnu # once
shader-transpiler/crates/dxbc-accc/guest/build.sh
target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
--exe target/bx-shader-bridge/check_bridge.exe
```
`guest/build.sh` writes `bx_shader_bridge.dll` and `check_bridge.exe` to `target/bx-shader-bridge/`. It always builds into, and copies from, `<repo>/target`, whatever `CARGO_TARGET_DIR` says, so it cannot package a stale DLL. It resolves `cargo` and `rustc` through rustup, checks that this `rustc` has `std` for the Windows target, and prints which `rustc` it used. It fails if the Export Address Table holds anything other than the three entry points as direct RVAs (an ordinal-only entry or a forwarder fails it), or if any import is outside the allowlist above.
[`guest/check_bridge.c`](guest/check_bridge.c) is a C guest program built against the frozen header. It checks the struct layout with `_Static_assert`, loads the DLL by full path from its own directory, and sends nine containers through the DLL:
- a real DXC SM 6.6 compute blob (from [`d3dmetal-harness`](../d3dmetal-harness/README.md));
- synthetic DXIL pixel SM 6.0 with `RTS0`, once as is and once followed by 16 bytes past its declared size;
- `ACCC` with an `FSPX` v1 stage section, and `ACCC` with an `FSPX` v0 stub;
- `DXIL` + `ACCC`;
- legacy `SHEX`;
- two malformed blobs.
The program prints one `BXSHADER` line per container and a count line, and checks:
- **Classification:**
- kind, stage and shader model;
- the declared container size;
- the exact `DXIL` and `ACCC` chunk sizes and the root signature flag, each derived from the program's own chunk-table walk;
- the digest, compared with header bytes 4..20 for every container, the real one included.
- **Prepare:** exactly the declared container is copied, never the trailing bytes. ACCC-only and legacy are `BX_SHADER_ERR_UNSUPPORTED`. Malformed input is `BX_SHADER_ERR_INVALID_BLOB`, with output cleared.
- **Free and argument errors:** freeing returned buffers, and null arguments at the DLL boundary.
Recorded run (one Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 `26.3.0.39832`, both a fresh prefix and a D3DMetal bottle):
```text
BXSHADER counts dxil=3 accc_only=2 dual=1 legacy=1 unknown=0 invalid=2
PASS: check_bridge (9 containers through bx_shader_bridge.dll)
```
This is a synthetic, single-host result. It is not a measurement of any title's shader corpus, and not Xbox hardware.
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.
### Related work, owned elsewhere
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.
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Builds bx_shader_bridge.dll (this crate for x86_64-pc-windows-gnu) and the guest check
# check_bridge.exe into one directory (default: <repo>/target/bx-shader-bridge), then checks
# the DLL: its Export Address Table holds exactly the three bx_shader_bridge.h entry points as
# direct RVAs (no extra named or ordinal-only entries, no forwarders), and every imported DLL
# is a system DLL Wine provides. Run the check under CrossOver afterwards, for example:
# target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
# --exe target/bx-shader-bridge/check_bridge.exe
#
# Needs: rustup with the x86_64-pc-windows-gnu target, x86_64-w64-mingw32-gcc / -objdump
# (mingw-w64), and python3.
set -eu
crate=$(cd "$(dirname "$0")/.." && pwd)
root=$(cd "$crate/../../.." && pwd)
out=${1:-$root/target/bx-shader-bridge}
target=x86_64-pc-windows-gnu
cc=${BX_MINGW_CC:-x86_64-w64-mingw32-gcc}
objdump=${BX_MINGW_OBJDUMP:-x86_64-w64-mingw32-objdump}
# Always build here and copy from here, whatever CARGO_TARGET_DIR or build.target-dir say,
# so a stale DLL left elsewhere can never be packaged.
target_dir=$root/target
for tool in "$cc" "$objdump" python3; do
command -v "$tool" >/dev/null 2>&1 || { echo "build.sh: $tool not found" >&2; exit 1; }
done
# Use one toolchain for both the target check and the build. With rustup, resolve cargo and
# rustc through it (a cargo earlier on PATH, e.g. Homebrew's, has no Windows std).
if command -v rustup >/dev/null 2>&1; then
cargo=$(cd "$root" && rustup which cargo)
rustc=$(cd "$root" && rustup which rustc)
else
cargo=$(command -v cargo) || { echo "build.sh: cargo not found" >&2; exit 1; }
rustc=$(command -v rustc) || { echo "build.sh: rustc not found" >&2; exit 1; }
fi
libdir=$("$rustc" --print target-libdir --target "$target" 2>/dev/null || true)
if [ -z "$libdir" ] || ! ls "$libdir"/libstd-*.rlib >/dev/null 2>&1; then
echo "build.sh: $rustc ($("$rustc" --version)) has no std for $target" >&2
echo "build.sh: install it with: rustup target add $target" >&2
exit 1
fi
echo "build.sh: using $("$rustc" --version) at $rustc"
RUSTC=$rustc CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=$cc \
"$cargo" build --locked --release -p dxbc-accc --target "$target" \
--target-dir "$target_dir" --manifest-path "$root/Cargo.toml"
mkdir -p "$out"
cp "$target_dir/$target/release/dxbc_accc.dll" "$out/bx_shader_bridge.dll"
dll=$out/bx_shader_bridge.dll
# Same reading of `objdump -p` as scripts/build-shims.sh: every populated Export Address Table
# slot must be a direct RVA owned by one of the expected names.
"$objdump" -p "$dll" | python3 -I -c '
import re, sys
expected = {"bx_shader_inspect", "bx_shader_prepare_for_d3dmetal", "bx_shader_free_buffer"}
# The Windows-provided system DLLs a Rust std cdylib imports; anything else is an error.
allowed = {"kernel32.dll", "ntdll.dll", "bcryptprimitives.dll", "userenv.dll", "ws2_32.dll"}
allowed_prefixes = ("api-ms-win-crt-", "api-ms-win-core-")
eat, names, imports, mode = {}, {}, [], None
for line in sys.stdin:
line = line.rstrip("\n")
m = re.match(r"^\s*DLL Name:\s*(\S+)", line)
if m:
imports.append(m.group(1))
if line.startswith("Export Address Table --"):
mode = "eat"; continue
if line.startswith("[Ordinal/Name Pointer] Table --"):
mode = "names"; continue
if not line.strip():
mode = None; continue
if mode == "eat":
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(Export|Forwarder) RVA", line)
if m:
eat[int(m.group(1))] = m.group(2)
elif mode == "names":
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(\S+)", line)
if m:
names[m.group(2)] = int(m.group(1))
errors = []
if set(names) != expected:
errors.append("named exports %s, want %s" % (sorted(names), sorted(expected)))
owned = set(names.values())
for ordinal, kind in sorted(eat.items()):
if ordinal not in owned:
errors.append("export @%d has no name (ordinal-only or stray entry)" % ordinal)
if kind != "Export":
errors.append("export @%d is a forwarder" % ordinal)
for name, ordinal in names.items():
if ordinal not in eat:
errors.append("%s @%d missing from the Export Address Table" % (name, ordinal))
for dll in imports:
low = dll.lower()
if low not in allowed and not low.startswith(allowed_prefixes):
errors.append("unexpected import %s (only Wine-provided system DLLs are allowed)" % dll)
if errors:
sys.exit("build.sh: bx_shader_bridge.dll: " + "; ".join(errors))
print("build.sh: exports %s; imports %s" % (" ".join(sorted(names)), " ".join(imports)))
'
"$cc" -std=c11 -O2 -Wall -Wextra -Werror -static \
-I"$root/abi/include" -I"$crate/../d3dmetal-harness/probe/shaders" \
-o "$out/check_bridge.exe" "$crate/guest/check_bridge.c"
echo "built $dll"
echo "built $out/check_bridge.exe"
@@ -0,0 +1,296 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
*
* Guest-side check for bx_shader_bridge.dll, the x86-64 Windows build of this crate (#445).
*
* Runs as a PE32+ guest under CrossOver/Wine, loads the DLL by full path from its own directory,
* and drives the three entry points from abi/include/bx_shader_bridge.h with synthetic
* containers plus one real DXC SM 6.6 compute blob. It counts the classifications and checks
* them, and the prepare/free behaviour, against expectations written here from the DXBC
* layout and the frozen header, not from the Rust implementation.
*
* Output: "BXSHADER" lines with each blob's classification, one "BXSHADER counts" line, then
* PASS or FAIL. Exit code 0 on success, 1 on a failed check, 2 if the DLL cannot be loaded.
*/
#include <windows.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include "bx_shader_bridge.h"
#include "fill_cs66.h" /* g_fill_cs66: DXC 1.9.2609 output, see d3dmetal-harness */
/* The Rust side asserts the same layout; agreeing here proves both sides read one struct. */
_Static_assert(sizeof(bx_shader_kind_t) == 4, "C enum must be 4 bytes");
_Static_assert(sizeof(bx_shader_inspection_t) == 48, "bx_shader_inspection_t size");
_Static_assert(offsetof(bx_shader_inspection_t, container_size) == 16, "container_size offset");
_Static_assert(offsetof(bx_shader_inspection_t, digest_hash) == 32, "digest_hash offset");
typedef bx_shader_status_t (*inspect_fn)(const uint8_t*, size_t, bx_shader_inspection_t*);
typedef bx_shader_status_t (*prepare_fn)(const uint8_t*, size_t, uint8_t**, size_t*);
typedef void (*free_fn)(uint8_t*, size_t);
static int failures;
#define CHECK(expr) \
do { \
if (!(expr)) { \
fprintf(stderr, "FAIL: check_bridge line %d: %s\n", __LINE__, #expr); \
++failures; \
} \
} while (0)
/* --- Synthetic DXBC containers --- */
static void put32(uint8_t* at, uint32_t value) {
at[0] = (uint8_t)value;
at[1] = (uint8_t)(value >> 8);
at[2] = (uint8_t)(value >> 16);
at[3] = (uint8_t)(value >> 24);
}
typedef struct {
const char* fourcc;
const uint8_t* data;
uint32_t size;
} chunk_t;
/* DXBC layout: "DXBC", 16-byte digest, u32 version 1, u32 total size, u32 chunk count, then
* one u32 offset per chunk; each chunk is fourcc, u32 size, payload. */
static uint32_t build_dxbc(uint8_t* out, size_t cap, const chunk_t* chunks, uint32_t count) {
uint32_t at = 32 + 4 * count;
for (uint32_t i = 0; i < count; ++i) at += 8 + chunks[i].size;
if (at > cap) abort();
memcpy(out, "DXBC", 4);
memset(out + 4, 0x5A, 16);
put32(out + 20, 1);
put32(out + 24, at);
put32(out + 28, count);
uint32_t offset = 32 + 4 * count;
for (uint32_t i = 0; i < count; ++i) {
put32(out + 32 + 4 * i, offset);
memcpy(out + offset, chunks[i].fourcc, 4);
put32(out + offset + 4, chunks[i].size);
memcpy(out + offset + 8, chunks[i].data, chunks[i].size);
offset += 8 + chunks[i].size;
}
return at;
}
/* A 28-byte DxilProgramHeader: program version word (kind << 16 | major << 4 | minor), size
* in dwords (7), "DXIL", DXIL version 1.0, bitcode offset 16, bitcode size 4, 4 bitcode bytes. */
static void dxil_program(uint8_t out[28], uint32_t kind, uint32_t major, uint32_t minor) {
memset(out, 0, 28);
put32(out, kind << 16 | major << 4 | minor);
put32(out + 4, 7);
memcpy(out + 8, "DXIL", 4);
put32(out + 12, 0x0100);
put32(out + 16, 16);
put32(out + 20, 4);
put32(out + 24, 0xDEC011D1u);
}
/* Size of the first chunk named fourcc in a well-formed container, 0 if absent. Written from
* the DXBC layout, independently of the Rust parser. */
static uint32_t get32(const uint8_t* at) {
return (uint32_t)at[0] | (uint32_t)at[1] << 8 | (uint32_t)at[2] << 16 | (uint32_t)at[3] << 24;
}
static int chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
if (len < 32 || memcmp(bytes, "DXBC", 4) != 0) return 0;
const uint32_t count = get32(bytes + 28);
for (uint32_t i = 0; i < count && 36 + 4 * (size_t)i <= len; ++i) {
const uint32_t offset = get32(bytes + 32 + 4 * i);
if (offset + 8 <= len && memcmp(bytes + offset, fourcc, 4) == 0) {
*size = get32(bytes + offset + 4);
return 1;
}
}
return 0;
}
/* --- Cases --- */
typedef struct {
const char* name;
const uint8_t* bytes;
size_t len;
bx_shader_status_t inspect_status;
bx_shader_kind_t kind;
bx_shader_stage_t stage;
uint32_t sm_major, sm_minor;
uint32_t container_size; /* the container's declared size, which may be less than len */
bx_shader_status_t prepare_status;
} case_t;
static 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";
case BX_SHADER_DXBC_ACCC: return "accc_only";
case BX_SHADER_DXBC_DUAL: return "dual";
default: return "unknown";
}
}
int main(void) {
/* By full path beside this EXE, as a caller should (see the crate README). */
wchar_t path[MAX_PATH];
const DWORD path_len = GetModuleFileNameW(NULL, path, MAX_PATH);
wchar_t* slash = path_len && path_len < MAX_PATH ? wcsrchr(path, L'\\') : NULL;
if (!slash || (size_t)(slash + 1 - path) + 21 > MAX_PATH) {
fprintf(stderr, "FAIL: check_bridge: executable path too long\n");
return 2;
}
wcscpy(slash + 1, L"bx_shader_bridge.dll");
HMODULE dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!dll) {
fprintf(stderr, "FAIL: check_bridge: bx_shader_bridge.dll not loaded (error %lu)\n", GetLastError());
return 2;
}
inspect_fn inspect = (inspect_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_inspect");
prepare_fn prepare = (prepare_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_prepare_for_d3dmetal");
free_fn release = (free_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_free_buffer");
if (!inspect || !prepare || !release) {
fprintf(stderr, "FAIL: check_bridge: missing export\n");
return 2;
}
uint8_t dxil_cs66[28], dxil_ps60[28];
dxil_program(dxil_cs66, 5, 6, 6); /* DXIL program kind 5 = compute */
dxil_program(dxil_ps60, 0, 6, 0); /* kind 0 = pixel */
const uint8_t rts0[4] = {1, 2, 3, 4};
/* FSPX v1 (BetterXen's synthetic layout): header "FSPX", version 1, 1 section, flags 0;
* descriptor {id 1 (stage config), offset 28, size 12}; body {stage 6 compute, SM 6.0}. */
uint8_t fspx_v1[40] = {0};
memcpy(fspx_v1, "FSPX", 4);
put32(fspx_v1 + 4, 1);
put32(fspx_v1 + 8, 1);
put32(fspx_v1 + 16, 1);
put32(fspx_v1 + 20, 28);
put32(fspx_v1 + 24, 12);
put32(fspx_v1 + 28, BX_STAGE_COMPUTE);
put32(fspx_v1 + 32, 6);
put32(fspx_v1 + 36, 0);
/* FSPX version 0: magic-only stub, no sections. */
uint8_t fspx_v0[16] = {'F', 'S', 'P', 'X'};
/* SM 5.0 compute SHEX token (program type 5 << 16 | 5 << 4 | 0) and a length dword. */
uint8_t shex[8];
put32(shex, 5u << 16 | 5u << 4);
put32(shex + 4, 2);
static uint8_t ps60[256], accc_v1[256], accc_v0[256], dual[256], legacy[256];
const chunk_t ps60_chunks[] = {{"RTS0", rts0, 4}, {"DXIL", dxil_ps60, 28}};
const chunk_t accc_v1_chunks[] = {{"ACCC", fspx_v1, sizeof(fspx_v1)}};
const chunk_t accc_v0_chunks[] = {{"ACCC", fspx_v0, sizeof(fspx_v0)}};
const chunk_t dual_chunks[] = {{"DXIL", dxil_cs66, 28}, {"ACCC", fspx_v0, sizeof(fspx_v0)}};
const chunk_t legacy_chunks[] = {{"SHEX", shex, sizeof(shex)}};
const uint32_t ps60_len = build_dxbc(ps60, sizeof(ps60), ps60_chunks, 2);
const uint32_t accc_v1_len = build_dxbc(accc_v1, sizeof(accc_v1), accc_v1_chunks, 1);
const uint32_t accc_v0_len = build_dxbc(accc_v0, sizeof(accc_v0), accc_v0_chunks, 1);
const uint32_t dual_len = build_dxbc(dual, sizeof(dual), dual_chunks, 2);
const uint32_t legacy_len = build_dxbc(legacy, sizeof(legacy), legacy_chunks, 1);
/* The pixel shader again, followed by 16 bytes that are not part of the container. */
static uint8_t padded[256 + 16];
memcpy(padded, ps60, ps60_len);
memset(padded + ps60_len, 0xEE, 16);
static const uint8_t truncated[20] = {'D', 'X', 'B', 'C'};
static const uint8_t not_dxbc[64] = {'X', 'X', 'X', 'X'};
const case_t cases[] = {
{"dxc_cs_6_6", g_fill_cs66, sizeof(g_fill_cs66), BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_COMPUTE, 6, 6,
sizeof(g_fill_cs66), BX_SHADER_OK},
{"synthetic_ps_6_0", ps60, ps60_len, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
BX_SHADER_OK},
{"trailing_bytes", padded, ps60_len + 16, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
BX_SHADER_OK},
{"accc_fspx_v1", accc_v1, accc_v1_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_COMPUTE, 6, 0, accc_v1_len,
BX_SHADER_ERR_UNSUPPORTED},
{"accc_fspx_v0", accc_v0, accc_v0_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_UNKNOWN, 0, 0, accc_v0_len,
BX_SHADER_ERR_UNSUPPORTED},
{"dual_dxil_accc", dual, dual_len, BX_SHADER_OK, BX_SHADER_DXBC_DUAL, BX_STAGE_COMPUTE, 6, 6, dual_len,
BX_SHADER_OK},
{"legacy_shex_5_0", legacy, legacy_len, BX_SHADER_OK, BX_SHADER_DXBC_LEGACY, BX_STAGE_COMPUTE, 5, 0,
legacy_len, BX_SHADER_ERR_UNSUPPORTED},
{"truncated", truncated, sizeof(truncated), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN,
0, 0, 0, BX_SHADER_ERR_INVALID_BLOB},
{"not_dxbc", not_dxbc, sizeof(not_dxbc), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN, 0,
0, 0, BX_SHADER_ERR_INVALID_BLOB},
};
const size_t count = sizeof(cases) / sizeof(cases[0]);
unsigned tally[5] = {0};
unsigned invalid = 0;
for (size_t i = 0; i < count; ++i) {
const case_t* c = &cases[i];
bx_shader_inspection_t info;
memset(&info, 0xEE, sizeof(info));
const bx_shader_status_t status = inspect(c->bytes, c->len, &info);
printf("BXSHADER %s status=%d kind=%s stage=%d sm=%u.%u container_size=%u dxil=%u accc=%u rts0=%u\n",
c->name, (int)status, kind_name(info.kind), (int)info.stage, info.shader_model_major,
info.shader_model_minor, info.container_size, info.dxil_chunk_size, info.accc_chunk_size,
info.has_root_signature);
CHECK(status == c->inspect_status);
if (status == BX_SHADER_OK) {
if ((unsigned)info.kind < 5) ++tally[info.kind];
CHECK(info.kind == c->kind);
CHECK(info.stage == c->stage);
CHECK(info.shader_model_major == c->sm_major && info.shader_model_minor == c->sm_minor);
CHECK(info.container_size == c->container_size);
/* Exact chunk sizes and the root signature flag, from this file's own chunk walk. */
uint32_t want_dxil = 0, want_accc = 0, rts0_size = 0;
chunk(c->bytes, c->len, "DXIL", &want_dxil);
chunk(c->bytes, c->len, "ACCC", &want_accc);
const uint32_t want_rts0 = (uint32_t)chunk(c->bytes, c->len, "RTS0", &rts0_size);
CHECK(info.dxil_chunk_size == want_dxil);
CHECK(info.accc_chunk_size == want_accc);
CHECK(info.has_root_signature == want_rts0);
CHECK((want_dxil != 0) == (c->kind == BX_SHADER_DXBC_DXIL || c->kind == BX_SHADER_DXBC_DUAL));
CHECK((want_accc != 0) == (c->kind == BX_SHADER_DXBC_ACCC || c->kind == BX_SHADER_DXBC_DUAL));
/* The digest is the container header's bytes 4..20, for every case. */
CHECK(memcmp(info.digest_hash, c->bytes + 4, 16) == 0);
} else {
++invalid;
const bx_shader_inspection_t zero = {0};
CHECK(memcmp(&info, &zero, sizeof(info)) == 0); /* cleared on failure */
}
uint8_t* copy = (uint8_t*)(uintptr_t)1;
size_t copy_len = 1;
const bx_shader_status_t prepared = prepare(c->bytes, c->len, &copy, &copy_len);
CHECK(prepared == c->prepare_status);
if (prepared == BX_SHADER_OK) {
/* Only the declared container is copied, never bytes past it. */
CHECK(copy && copy_len == c->container_size && memcmp(copy, c->bytes, c->container_size) == 0);
release(copy, copy_len);
} else {
CHECK(copy == NULL && copy_len == 0);
}
}
/* Argument checks at the DLL boundary. */
bx_shader_inspection_t info;
CHECK(inspect(g_fill_cs66, sizeof(g_fill_cs66), NULL) == BX_SHADER_ERR_INVALID_BLOB);
CHECK(inspect(NULL, 16, &info) == BX_SHADER_ERR_INVALID_BLOB);
uint8_t* copy = NULL;
CHECK(prepare(g_fill_cs66, sizeof(g_fill_cs66), NULL, NULL) == BX_SHADER_ERR_INVALID_BLOB);
CHECK(prepare(NULL, 16, &copy, &(size_t){0}) == BX_SHADER_ERR_INVALID_BLOB && copy == NULL);
release(NULL, 0);
printf("BXSHADER counts dxil=%u accc_only=%u dual=%u legacy=%u unknown=%u invalid=%u\n",
tally[BX_SHADER_DXBC_DXIL], tally[BX_SHADER_DXBC_ACCC], tally[BX_SHADER_DXBC_DUAL],
tally[BX_SHADER_DXBC_LEGACY], tally[BX_SHADER_UNKNOWN], invalid);
CHECK(tally[BX_SHADER_DXBC_DXIL] == 3 && tally[BX_SHADER_DXBC_ACCC] == 2 && tally[BX_SHADER_DXBC_DUAL] == 1);
CHECK(tally[BX_SHADER_DXBC_LEGACY] == 1 && tally[BX_SHADER_UNKNOWN] == 0 && invalid == 2);
if (failures) {
fprintf(stderr, "FAIL: check_bridge (%d failed checks)\n", failures);
return 1;
}
printf("PASS: check_bridge (%u containers through bx_shader_bridge.dll)\n", (unsigned)count);
return 0;
}
+108 -24
View File
@@ -1,20 +1,53 @@
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
#include <cstdlib>
#include <mutex>
#include <new>
#include "bx_log.h"
/* Track E (M1-E2 / M5): AcpHal.dll SHAPE Audio Coprocessor HAL shim. */
namespace {
class AcpHal final : public IUnknown {
LONG refs = 1;
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
ULONG left = InterlockedDecrement(&refs);
if (!left) delete this;
return left;
}
};
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
struct Allocation {
uintptr_t va;
uint32_t base, size;
Allocation* next;
};
Allocation* allocations;
std::mutex heap_lock;
uint64_t capacity = 0;
uint64_t used = 0;
bool heap_created = false;
}
extern "C" {
HRESULT WINAPI AcpHalCreate(void** out_hal) {
BX_STUB_LOG("AcpHal.dll", "AcpHalCreate");
if (out_hal) *out_hal = nullptr;
return E_NOTIMPL;
HRESULT WINAPI AcpHalCreate(void** out) {
if (!out) return E_POINTER;
*out = new (std::nothrow) AcpHal;
return *out ? S_OK : E_OUTOFMEMORY;
}
HRESULT WINAPI AcpHalAllocateShapeContexts(void* /*desc*/) {
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
return S_OK;
}
@@ -24,35 +57,86 @@ HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
return S_OK;
}
HRESULT WINAPI ApuCreateHeap(uint32_t /*cached_size*/, uint32_t /*non_cached_size*/) {
BX_STUB_LOG("AcpHal.dll", "ApuCreateHeap");
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
std::lock_guard guard(heap_lock);
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
used = 0;
capacity = uint64_t(cached) + non_cached;
heap_created = true;
return S_OK;
}
HRESULT WINAPI ApuAlloc(void** out_va, uint32_t* out_apu_addr, uint32_t size, uint32_t alignment) {
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment) {
if (va) *va = nullptr;
if (apu) *apu = 0;
if (!va && !apu) return E_POINTER;
if (alignment && (alignment & (alignment - 1))) return E_INVALIDARG;
if (alignment < 64) alignment = 64;
void* p = _aligned_malloc(size ? size : 64, alignment);
if (out_va) *out_va = p;
if (out_apu_addr) *out_apu_addr = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(p) & 0xFFFFFFFFu);
return p ? S_OK : E_OUTOFMEMORY;
if (!size) size = 64;
std::lock_guard guard(heap_lock);
if (!heap_created || size > capacity - used) return E_OUTOFMEMORY;
uint64_t base = alignment;
Allocation** link = &allocations;
while (*link && base + size > (*link)->base) {
const uint64_t end = uint64_t((*link)->base) + (*link)->size;
base = (end + alignment - 1) & ~(uint64_t(alignment) - 1);
link = &(*link)->next;
}
if (base + size > (uint64_t{1} << 32)) return E_OUTOFMEMORY;
void* ptr = _aligned_malloc(size, alignment);
if (!ptr) return E_OUTOFMEMORY;
auto* entry = new (std::nothrow) Allocation{reinterpret_cast<uintptr_t>(ptr),
static_cast<uint32_t>(base), size, *link};
if (!entry) {
_aligned_free(ptr);
return E_OUTOFMEMORY;
}
*link = entry;
used += size;
if (va) *va = ptr;
if (apu) *apu = entry->base;
return S_OK;
}
HRESULT WINAPI ApuFree(void* va) {
if (va) _aligned_free(va);
return S_OK;
if (!va) return S_OK;
std::lock_guard guard(heap_lock);
for (auto** link = &allocations; *link; link = &(*link)->next) {
auto* entry = *link;
if (entry->va != reinterpret_cast<uintptr_t>(va)) continue;
*link = entry->next;
used -= entry->size;
_aligned_free(va);
delete entry;
return S_OK;
}
return E_INVALIDARG;
}
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t /*size*/) {
return va != nullptr;
static uint32_t lookup_va(const void* va, uint32_t size) {
const auto address = reinterpret_cast<uintptr_t>(va);
std::lock_guard guard(heap_lock);
for (auto* entry = allocations; entry; entry = entry->next) {
const auto offset = address - entry->va;
if (offset < entry->size && size <= entry->size - offset)
return entry->base + static_cast<uint32_t>(offset);
}
return 0;
}
void* WINAPI ApuMapApuAddress(uint32_t /*apu_addr*/) {
BX_STUB_LOG("AcpHal.dll", "ApuMapApuAddress");
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t size) {
return lookup_va(va, size) != 0;
}
void* WINAPI ApuMapApuAddress(uint32_t address) {
std::lock_guard guard(heap_lock);
for (auto* entry = allocations; entry && entry->base <= address; entry = entry->next) {
const auto offset = address - entry->base;
if (offset < entry->size) return reinterpret_cast<void*>(entry->va + offset);
}
return nullptr;
}
uint32_t WINAPI ApuMapVirtualAddress(const void* va) {
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(va) & 0xFFFFFFFFu);
uint32_t WINAPI ApuMapVirtualAddress(const void* va) { return lookup_va(va, 1); }
}
} // extern "C"
+34 -14
View File
@@ -1,21 +1,41 @@
#include <windows.h>
#include <cstdint>
#include "bx_log.h"
/* Track E (M1-E2 / M5): chad.dll Xbox DSP command shim. */
#define BX_DSP_CONNECTIONS
#include "command_ring.h"
extern "C" {
// Validate and record the caller's stream limit; the synthetic command ring
// holds a fixed 32-packet backlog independent of stream count.
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t max_streams, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!max_streams) return E_INVALIDARG;
return connect(out, max_streams);
}
HRESULT WINAPI XDspDisconnect(void* handle) { return disconnect(handle); }
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t /*max_streams*/, void** out_handle) {
BX_STUB_LOG("chad.dll", "XDspConnectWithMaximumStreamLimit");
if (out_handle) *out_handle = reinterpret_cast<void*>(0x5001);
HRESULT WINAPI XDspActivate(void* handle) {
std::lock_guard guard(connections_lock);
auto* c = lookup(handle);
if (!c) return E_HANDLE;
c->active = true;
// chad has no result export. Active DSP commands complete synchronously.
while (c->queue.count) c->queue.pop();
return S_OK;
}
HRESULT WINAPI XDspDisconnect(void* /*handle*/) { return S_OK; }
HRESULT WINAPI XDspActivate(void* /*handle*/) { return S_OK; }
HRESULT WINAPI XDspDeactivate(void* /*handle*/) { return S_OK; }
HRESULT WINAPI XDspSubmitCommand(void* /*handle*/, const void* /*cmd*/, uint32_t /*size*/) { return S_OK; }
HRESULT WINAPI XDspDeactivate(void* handle) {
std::lock_guard guard(connections_lock);
auto* c = lookup(handle);
if (!c) return E_HANDLE;
c->active = false;
return S_OK;
}
} // extern "C"
HRESULT WINAPI XDspSubmitCommand(void* handle, const void* cmd, uint32_t size) {
std::lock_guard guard(connections_lock);
auto* c = lookup(handle);
if (!c) return E_HANDLE;
const HRESULT hr = c->queue.push(cmd, size);
if (SUCCEEDED(hr) && c->active) c->queue.pop();
return hr;
}
}
+96
View File
@@ -0,0 +1,96 @@
#pragma once
#include <windows.h>
#include <array>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <new>
namespace {
// A synthetic command completes by returning its opaque bytes unchanged.
struct CommandRing {
struct Packet {
uint32_t size;
unsigned char bytes[1024];
};
std::array<Packet, 32> packets;
unsigned head = 0, count = 0;
HRESULT push(const void* data, uint32_t size) {
if (!data || !size || size > sizeof(Packet::bytes)) return E_INVALIDARG;
if (count == packets.size()) return HRESULT_FROM_WIN32(ERROR_BUSY);
auto& packet = packets[(head + count) % packets.size()];
packet.size = size;
std::memcpy(packet.bytes, data, size);
++count;
return S_OK;
}
void pop() {
head = (head + 1) % packets.size();
--count;
}
HRESULT read(void* data, uint32_t size) {
if (!data) return E_POINTER;
if (!count) return S_FALSE;
const auto& packet = packets[head];
if (size < packet.size) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
std::memcpy(data, packet.bytes, packet.size);
pop();
return S_OK;
}
};
struct Connection {
uintptr_t id;
Connection* next;
CommandRing queue;
uint32_t max_streams = 0;
bool active = false;
};
// Each DLL owns its registry. An ID stays invalid after disconnect, including
// when the allocator subsequently reuses the same Connection address.
std::mutex connections_lock;
Connection* connections;
#ifdef BX_DSP_CONNECTIONS
uintptr_t next_id = 2;
#else
uintptr_t next_id = 1;
#endif
HRESULT connect(void** out, uint32_t max_streams = 0) {
if (!out) return E_POINTER;
*out = nullptr;
std::lock_guard guard(connections_lock);
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
auto* c = new (std::nothrow) Connection;
if (!c) return E_OUTOFMEMORY;
c->id = next_id;
c->max_streams = max_streams;
next_id += 2;
c->next = connections;
connections = c;
*out = reinterpret_cast<void*>(c->id);
return S_OK;
}
// Caller holds connections_lock through the operation.
Connection* lookup(void* handle) {
for (auto* c = connections; c; c = c->next)
if (c->id == reinterpret_cast<uintptr_t>(handle)) return c;
return nullptr;
}
HRESULT disconnect(void* handle) {
std::lock_guard guard(connections_lock);
for (auto** link = &connections; *link; link = &(*link)->next) {
auto* c = *link;
if (c->id != reinterpret_cast<uintptr_t>(handle)) continue;
*link = c->next;
delete c;
return S_OK;
}
return E_HANDLE;
}
}
+15 -23
View File
@@ -1,32 +1,24 @@
#include <windows.h>
#include <cstdint>
#include "bx_log.h"
/* Track E (M1-E2 / M5): xapu.dll APU command queue shim. */
#include "command_ring.h"
extern "C" {
HRESULT WINAPI XApuConnect(void** out) { return connect(out); }
HRESULT WINAPI XApuDisconnect(void* conn) { return disconnect(conn); }
HRESULT WINAPI XApuConnect(void** out_conn) {
BX_STUB_LOG("xapu.dll", "XApuConnect");
if (out_conn) *out_conn = reinterpret_cast<void*>(0x4001);
return S_OK;
HRESULT WINAPI XApuEnqueueCommand(void* conn, const void* cmd, uint32_t size) {
std::lock_guard guard(connections_lock);
auto* c = lookup(conn);
return c ? c->queue.push(cmd, size) : E_HANDLE;
}
HRESULT WINAPI XApuDisconnect(void* /*conn*/) {
return S_OK;
HRESULT WINAPI XApuDequeueResult(void* conn, void* result, uint32_t size) {
std::lock_guard guard(connections_lock);
auto* c = lookup(conn);
return c ? c->queue.read(result, size) : E_HANDLE;
}
HRESULT WINAPI XApuEnqueueCommand(void* /*conn*/, const void* /*cmd*/, uint32_t /*size*/) {
return S_OK;
uint32_t WINAPI XApuGetResultCount(void* conn) {
std::lock_guard guard(connections_lock);
auto* c = lookup(conn);
return c ? c->queue.count : 0;
}
HRESULT WINAPI XApuDequeueResult(void* /*conn*/, void* /*out_res*/, uint32_t /*size*/) {
return S_FALSE;
}
uint32_t WINAPI XApuGetResultCount(void* /*conn*/) {
return 0u;
}
} // extern "C"
+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 */
+170 -6
View File
@@ -1,13 +1,177 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstdint>
#include <unordered_map>
#include "bx_log.h"
/* Track E (M1-E2): GameInput.dll ordinal 1 (GameInputCreate) shim. */
namespace {
// GameInputCreate @1 exposes the legacy v0 COM layout.
constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
using Callback = void (WINAPI*)();
extern "C" HRESULT WINAPI GameInputCreate(void** out_game_input) {
BX_STUB_LOG("GameInput.dll", "GameInputCreate@1");
if (out_game_input) {
*out_game_input = nullptr;
}
// GameInputEnumerationKind values from Microsoft's public GDK GameInput (v0) reference:
// 0 = GameInputNoEnumeration, 1 = GameInputAsyncEnumeration, 2 = GameInputBlockingEnumeration.
constexpr uint32_t kMaxEnumerationKind = 2;
struct SrwExclusiveLock {
explicit SrwExclusiveLock(SRWLOCK& lock) : lock_(lock) { AcquireSRWLockExclusive(&lock_); }
~SrwExclusiveLock() { ReleaseSRWLockExclusive(&lock_); }
SrwExclusiveLock(const SrwExclusiveLock&) = delete;
SrwExclusiveLock& operator=(const SrwExclusiveLock&) = delete;
private:
SRWLOCK& lock_;
};
struct RegisteredDeviceCallback {
void* device = nullptr;
uint32_t input_kind = 0;
uint32_t status_filter = 0;
uint32_t enumeration_kind = 0;
void* context = nullptr;
Callback callback = nullptr;
bool stopped = false;
};
template<class T>
HRESULT unavailable(T* out) {
if (!out) return E_POINTER;
*out = {};
return E_NOTIMPL;
}
class GameInput final : public IUnknown {
LONG refs = 0;
SRWLOCK callback_lock_ = SRWLOCK_INIT;
uint64_t next_token_ = 1;
std::unordered_map<uint64_t, RegisteredDeviceCallback> callbacks_;
std::atomic<uint32_t> focus_policy_{0};
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown && iid != game_input_v0) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override { return InterlockedDecrement(&refs); }
virtual uint64_t WINAPI GetCurrentTimestamp() {
return GetTickCount64() * 1000;
}
virtual HRESULT WINAPI GetCurrentReading(uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading");
return unavailable(out);
}
virtual HRESULT WINAPI GetNextReading(void*, uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 5, "GetNextReading");
return unavailable(out);
}
virtual HRESULT WINAPI GetPreviousReading(void*, uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 6, "GetPreviousReading");
return unavailable(out);
}
virtual HRESULT WINAPI GetTemporalReading(uint64_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 7, "GetTemporalReading");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterReadingCallback(void*, uint32_t, float, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterDeviceCallback(
void* device,
uint32_t input_kind,
uint32_t status_filter,
uint32_t enumeration_kind,
void* context,
Callback callback,
uint64_t* out_token
) {
if (out_token) *out_token = 0;
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kMaxEnumerationKind) {
return E_INVALIDARG;
}
SrwExclusiveLock guard(callback_lock_);
const uint64_t token = next_token_++;
callbacks_.emplace(token, RegisteredDeviceCallback{
device,
input_kind,
status_filter,
enumeration_kind,
context,
callback,
false,
});
if (out_token) *out_token = token;
return S_OK;
}
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 10, "RegisterSystemButtonCallback");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterKeyboardLayoutCallback(void*, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
return unavailable(out);
}
virtual void WINAPI StopCallback(uint64_t token) {
if (token == 0) return;
SrwExclusiveLock guard(callback_lock_);
auto it = callbacks_.find(token);
if (it != callbacks_.end()) {
it->second.stopped = true;
}
}
virtual bool WINAPI UnregisterCallback(uint64_t token, uint64_t /*timeout_us*/) {
if (token == 0) return false;
SrwExclusiveLock guard(callback_lock_);
return callbacks_.erase(token) > 0;
}
virtual HRESULT WINAPI CreateDispatcher(void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
return unavailable(out);
}
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromId(const void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 16, "FindDeviceFromId");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromObject(IUnknown*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 17, "FindDeviceFromObject");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromPlatformHandle(HANDLE, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 18, "FindDeviceFromPlatformHandle");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromPlatformString(const wchar_t*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 19, "FindDeviceFromPlatformString");
return unavailable(out);
}
virtual HRESULT WINAPI EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) {
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
return E_NOTIMPL;
}
virtual void WINAPI SetFocusPolicy(uint32_t policy) {
focus_policy_.store(policy, std::memory_order_relaxed);
}
};
GameInput singleton;
}
extern "C" HRESULT WINAPI GameInputCreate(void** out) {
if (!out) return E_POINTER;
singleton.AddRef();
*out = &singleton;
return S_OK;
}
+306 -68
View File
@@ -3,6 +3,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <intrin.h>
#include "bx_config.h"
#include "bx_log.h"
@@ -13,7 +14,18 @@ CRITICAL_SECTION g_log_lock;
bool g_log_lock_ready = false;
HANDLE g_log_handle = INVALID_HANDLE_VALUE;
PVOID g_veh_handle = nullptr;
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,
@@ -26,6 +38,11 @@ bx_runtime_config_t g_config = {
};
void write_log_line(const char* line, size_t len) {
// Pause regular logging while a terminal crash record is being emitted so
// background threads cannot interleave with the unlocked crash WriteFile.
if (g_crash_in_flight.load(std::memory_order_acquire)) {
return;
}
if (g_log_lock_ready) {
EnterCriticalSection(&g_log_lock);
}
@@ -45,90 +62,296 @@ void write_log_line(const char* line, size_t len) {
}
}
/*
* Decode an x86-64 `clwb m8` instruction at `ip`.
* Encoding: [legacy prefixes] 0x66 [REX 0x40..0x4F] 0x0F 0xAE /6 (mod != 3).
* Returns total instruction length in bytes, or 0 if `ip` is not `clwb`.
*/
size_t decode_clwb_length(const uint8_t* ip) {
constexpr size_t kMaxInstructionLength = 15;
size_t read_instruction(uint64_t rip, uint8_t (&bytes)[kMaxInstructionLength]) {
HANDLE process = GetCurrentProcess();
if (ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip),
bytes, sizeof(bytes), nullptr)) {
return sizeof(bytes);
}
// A short instruction can end immediately before an inaccessible page.
size_t size = 0;
while (size < sizeof(bytes) &&
ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip + size),
&bytes[size], 1, nullptr)) {
++size;
}
return size;
}
// CLWB is 66 0F AE /6 with a memory operand. The address-size override
// selects 32-bit addressing but leaves the ModRM/SIB displacement lengths intact.
size_t decode_clwb_length(const uint8_t* ip, size_t size) {
size_t idx = 0;
bool has_66 = false;
bool has_addr_override = false;
while (idx < 6) {
uint8_t b = ip[idx];
if (b == 0x66) {
while (idx < size) {
const uint8_t byte = ip[idx];
if (byte == 0x66) {
has_66 = true;
idx++;
} else if (b == 0x67) {
has_addr_override = true;
idx++;
} else if (b == 0x26 || b == 0x2E || b == 0x36 || b == 0x3E || b == 0x64 || b == 0x65) {
idx++;
} else {
} else if (byte != 0x67 && byte != 0x26 && byte != 0x2E &&
byte != 0x36 && byte != 0x3E && byte != 0x64 && byte != 0x65) {
break;
}
}
(void)has_addr_override;
if (!has_66) {
return 0;
++idx;
}
if ((ip[idx] & 0xF0) == 0x40) {
idx++; /* Optional REX prefix */
// x86-64 allows at most one REX prefix immediately before the opcode.
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
++idx;
}
if (ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
if (!has_66 || size - idx < 3 || ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
return 0;
}
idx += 2;
uint8_t modrm = ip[idx++];
uint8_t mod = (modrm >> 6) & 0x3;
uint8_t reg = (modrm >> 3) & 0x7;
uint8_t rm = modrm & 0x7;
/* `clwb` requires memory operand (mod != 3) and opcode extension /6. */
const uint8_t modrm = ip[idx++];
const uint8_t mod = modrm >> 6;
const uint8_t reg = (modrm >> 3) & 7;
const uint8_t rm = modrm & 7;
if (mod == 3 || reg != 6) {
return 0;
}
uint8_t base = rm;
if (rm == 4) {
uint8_t sib = ip[idx++];
if (mod == 0 && (sib & 0x7) == 5) {
idx += 4; /* disp32 with no base */
if (idx == size) {
return 0;
}
} else if (mod == 0 && rm == 5) {
idx += 4; /* RIP-relative disp32 */
base = ip[idx++] & 7;
}
if (mod == 1) {
idx += 1; /* disp8 */
} else if (mod == 2) {
idx += 4; /* disp32 */
idx += 1;
} else if (mod == 2 || (mod == 0 && base == 5)) {
idx += 4;
}
return idx;
return idx <= size ? idx : 0;
}
bool is_adx_opcode(const uint8_t* ip) {
bool is_adx_opcode(const uint8_t* ip, size_t size) {
size_t idx = 0;
bool has_66_or_f3 = false;
while (idx < 4) {
if (ip[idx] == 0x66 || ip[idx] == 0xF3) {
has_66_or_f3 = true;
idx++;
} else {
break;
}
while (idx < size && (ip[idx] == 0x66 || ip[idx] == 0xF3)) {
++idx;
}
if (!has_66_or_f3) {
if (idx == 0) {
return false;
}
if ((ip[idx] & 0xF0) == 0x40) {
idx++;
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
++idx;
}
return ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
// Require the 3-byte ADCX/ADOX opcode (0F 38 F6) plus at least 1 ModRM byte.
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 &&
!g_crash_logged.test_and_set(std::memory_order_relaxed)) {
g_crash_in_flight.store(true, std::memory_order_release);
const CONTEXT& ctx = *ep->ContextRecord;
MEMORY_BASIC_INFORMATION region{};
unsigned long long module_base = 0;
if (VirtualQuery(reinterpret_cast<LPCVOID>(ctx.Rip), &region, sizeof(region)) &&
region.Type == MEM_IMAGE) {
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char line[1024];
int length = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"ERROR\",\"sub\":\"runtime_veh\","
"\"event\":\"unhandled_exception\",\"exception_code\":\"0x%08lx\","
"\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
"\"rip\":\"0x%016llx\",\"rsp\":\"0x%016llx\","
"\"registers\":{\"rax\":\"0x%016llx\",\"rbx\":\"0x%016llx\","
"\"rcx\":\"0x%016llx\",\"rdx\":\"0x%016llx\",\"rsi\":\"0x%016llx\","
"\"rdi\":\"0x%016llx\",\"rbp\":\"0x%016llx\",\"r8\":\"0x%016llx\","
"\"r9\":\"0x%016llx\",\"r10\":\"0x%016llx\",\"r11\":\"0x%016llx\","
"\"r12\":\"0x%016llx\",\"r13\":\"0x%016llx\",\"r14\":\"0x%016llx\","
"\"r15\":\"0x%016llx\"}}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
ep->ExceptionRecord->ExceptionCode, module_base,
module_base ? ctx.Rip - module_base : 0ULL, ctx.Rip, ctx.Rsp,
ctx.Rax, ctx.Rbx, ctx.Rcx, ctx.Rdx, ctx.Rsi, ctx.Rdi, ctx.Rbp,
ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15);
// A crashed thread may already own the regular logger's lock.
HANDLE output = g_log_handle != INVALID_HANDLE_VALUE
? g_log_handle : GetStdHandle(STD_ERROR_HANDLE);
if (length > 0 && length < static_cast<int>(sizeof(line)) &&
output && output != INVALID_HANDLE_VALUE) {
DWORD written = 0;
WriteFile(output, line, static_cast<DWORD>(length), &written, nullptr);
}
}
const LONG disposition = g_previous_filter ? g_previous_filter(ep) : EXCEPTION_CONTINUE_SEARCH;
if (disposition == EXCEPTION_CONTINUE_EXECUTION) {
g_crash_in_flight.store(false, std::memory_order_release);
g_crash_logged.clear(std::memory_order_relaxed);
}
return disposition;
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
@@ -139,26 +362,32 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
return EXCEPTION_CONTINUE_SEARCH;
}
auto* ip = reinterpret_cast<const uint8_t*>(ep->ContextRecord->Rip);
uint8_t ip[kMaxInstructionLength]{};
const size_t size = read_instruction(ep->ContextRecord->Rip, ip);
if (g_config.enable_clwb_veh) {
size_t len = decode_clwb_length(ip);
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;
}
}
if (g_config.enable_adx_tripwire && is_adx_opcode(ip)) {
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),
"rip=0x%016llx bytes=%02x %02x %02x %02x %02x",
@@ -262,9 +491,18 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
init_config_and_logging();
bx_veh_install();
g_previous_filter = SetUnhandledExceptionFilter(log_unhandled_exception);
bx_log_emit(BX_LOG_INFO, "runtime_veh", "attached",
g_config.profile == BX_PROFILE_ANACONDA ? "profile=anaconda" : "profile=lockhart");
} else if (reason == DLL_PROCESS_DETACH) {
// Restore g_previous_filter only when our filter is still the active
// top-level filter; if the guest installed its own filter after attach,
// put the guest filter back unchanged. (The frozen .def has no separate
// uninstall export, so detach performs this bounded pointer swap.)
const auto current_filter = SetUnhandledExceptionFilter(g_previous_filter);
if (current_filter != log_unhandled_exception) {
SetUnhandledExceptionFilter(current_filter);
}
if (g_veh_handle) {
RemoveVectoredExceptionHandler(g_veh_handle);
g_veh_handle = nullptr;
+229 -17
View File
@@ -1,37 +1,249 @@
#include <windows.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include "bx_log.h"
namespace {
std::atomic<uintptr_t> g_next_token{1};
static_assert(sizeof(uintptr_t) == 8, "BetterXen Win32 shims target x86-64");
constexpr uintptr_t kPrefixMask = 0xFFFFFFFF00000000ULL;
constexpr uintptr_t kSequenceMask = 0x00000000FFFFFFFFULL;
constexpr uintptr_t kStatePrefix = 0x50534D3100000000ULL; // "PSM1"
constexpr uintptr_t kConstrainedPrefix = 0x50534D3200000000ULL; // "PSM2"
constexpr uintptr_t kEmptySlot = 0;
constexpr uintptr_t kTombstoneSlot = ~uintptr_t{0};
struct SrwLockGuard {
SRWLOCK& lock;
explicit SrwLockGuard(SRWLOCK& l) : lock(l) { AcquireSRWLockExclusive(&lock); }
~SrwLockGuard() { ReleaseSRWLockExclusive(&lock); }
SrwLockGuard(const SrwLockGuard&) = delete;
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
};
// Exception-free open-addressed hash set backed by the Win32 process heap so
// both PSM DLLs stay on -fno-exceptions and map OOM to ERROR_NOT_ENOUGH_MEMORY.
struct TokenSet {
uintptr_t* slots = nullptr;
size_t capacity = 0;
size_t count = 0;
size_t used = 0; // active entries + tombstones
static size_t hash(uintptr_t value) {
uint64_t x = static_cast<uint64_t>(value);
x ^= x >> 30;
x *= 0xbf58476d1ce4e5b9ULL;
x ^= x >> 27;
x *= 0x94d049bb133111ebULL;
x ^= x >> 31;
return static_cast<size_t>(x);
}
bool rehash(size_t new_capacity) {
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(uintptr_t)) {
return false;
}
HANDLE heap = GetProcessHeap();
if (!heap) {
return false;
}
auto* fresh = static_cast<uintptr_t*>(
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(uintptr_t)));
if (!fresh) {
return false;
}
const size_t mask = new_capacity - 1;
for (size_t i = 0; i < capacity; ++i) {
const uintptr_t entry = slots[i];
if (entry != kEmptySlot && entry != kTombstoneSlot) {
size_t idx = hash(entry) & mask;
while (fresh[idx] != kEmptySlot) {
idx = (idx + 1) & mask;
}
fresh[idx] = entry;
}
}
if (slots) {
HeapFree(heap, 0, slots);
}
slots = fresh;
capacity = new_capacity;
used = count;
return true;
}
bool insert(uintptr_t token) {
if (capacity == 0 || (used + 1) * 4 >= capacity * 3) {
size_t next_capacity = 64;
if (capacity != 0) {
if (count * 2 >= capacity) {
if (capacity > (SIZE_MAX / sizeof(uintptr_t)) / 2) {
return false;
}
next_capacity = capacity * 2;
} else {
// Compact tombstones in place without growing the table.
next_capacity = capacity;
}
}
if (!rehash(next_capacity)) {
return false;
}
}
const size_t mask = capacity - 1;
size_t idx = hash(token) & mask;
size_t first_tombstone = capacity;
while (true) {
const uintptr_t entry = slots[idx];
if (entry == token) {
return true;
}
if (entry == kEmptySlot) {
if (first_tombstone != capacity) {
slots[first_tombstone] = token;
} else {
slots[idx] = token;
++used;
}
++count;
return true;
}
if (entry == kTombstoneSlot && first_tombstone == capacity) {
first_tombstone = idx;
}
idx = (idx + 1) & mask;
}
}
bool erase(uintptr_t token) {
if (capacity == 0 || count == 0 || token == kEmptySlot || token == kTombstoneSlot) {
return false;
}
const size_t mask = capacity - 1;
size_t idx = hash(token) & mask;
for (size_t probed = 0; probed < capacity; ++probed) {
const uintptr_t entry = slots[idx];
if (entry == kEmptySlot) {
return false;
}
if (entry == token) {
slots[idx] = kTombstoneSlot;
--count;
return true;
}
idx = (idx + 1) & mask;
}
return false;
}
void reset() {
if (slots) {
HANDLE heap = GetProcessHeap();
if (heap) {
HeapFree(heap, 0, slots);
}
slots = nullptr;
}
capacity = 0;
count = 0;
used = 0;
}
};
struct Registrations {
SRWLOCK lock;
TokenSet active;
uintptr_t own_prefix;
uintptr_t foreign_prefix;
uint64_t next_seq;
};
// Each DLL exposes one family. Disjoint tagged token spaces prevent an
// unregister call on the wrong DLL from removing another registration and let
// logs distinguish foreign-family tokens from retired or invalid ones.
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
ULONG register_notification(Registrations& registrations, PVOID callback,
PVOID* out_reg, const char* event) {
if (!out_reg) {
return ERROR_INVALID_PARAMETER;
}
*out_reg = nullptr;
if (!callback) {
return ERROR_INVALID_PARAMETER;
}
uintptr_t token = 0;
{
const SrwLockGuard guard(registrations.lock);
// Never recycle a token that a caller may still retain.
if (registrations.next_seq > kSequenceMask) {
return ERROR_NOT_ENOUGH_MEMORY;
}
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
if (!registrations.active.insert(token)) {
return ERROR_NOT_ENOUGH_MEMORY;
}
++registrations.next_seq;
}
*out_reg = reinterpret_cast<PVOID>(token);
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, "registered_offline");
return ERROR_SUCCESS;
}
void unregister_notification(Registrations& registrations, PVOID reg, const char* event) {
const uintptr_t token = reinterpret_cast<uintptr_t>(reg);
bool removed = false;
{
const SrwLockGuard guard(registrations.lock);
removed = registrations.active.erase(token);
}
const char* detail = "unknown_token";
if (removed) {
detail = "unregistered";
} else if ((token & kPrefixMask) == registrations.foreign_prefix &&
(token & kSequenceMask) != 0) {
detail = "foreign_token";
}
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
}
} // namespace
extern "C" {
ULONG WINAPI RegisterAppStateChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppStateChangeNotification", "noop_ok");
if (out_reg) {
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
if (reason == DLL_PROCESS_DETACH && reserved == nullptr) {
{
const SrwLockGuard guard(g_state.lock);
g_state.active.reset();
}
{
const SrwLockGuard guard(g_constrained.lock);
g_constrained.active.reset();
}
}
return ERROR_SUCCESS;
return TRUE;
}
VOID WINAPI UnregisterAppStateChangeNotification(PVOID /*reg*/) {
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppStateChangeNotification", "noop_ok");
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
return register_notification(g_state, callback, out_reg, "RegisterAppStateChangeNotification");
}
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppConstrainedChangeNotification", "noop_ok");
if (out_reg) {
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
}
return ERROR_SUCCESS;
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
}
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID /*reg*/) {
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppConstrainedChangeNotification", "noop_ok");
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
return register_notification(g_constrained, callback, out_reg, "RegisterAppConstrainedChangeNotification");
}
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID reg) {
unregister_notification(g_constrained, reg, "UnregisterAppConstrainedChangeNotification");
}
} // extern "C"
+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
+3
View File
@@ -1,6 +1,9 @@
bx_add_shim_dll(xgameruntime xgameruntime xgameruntime.def
xgameruntime.cpp
task_queue.cpp
com_dispatch.cpp
game_save.cpp
package.cpp
)
target_link_libraries(xgameruntime PRIVATE bx_runtime_veh kernel32)
target_compile_options(xgameruntime PRIVATE -fexceptions)
+837
View File
@@ -0,0 +1,837 @@
/*
* Clean-room COM IUnknown vtable dispatch for xgameruntime.dll!QueryApiImpl (#456).
*
* Provenance: Interface identifiers, IUnknown inheritance, and vtable slot indices were
* established via clean-room black-box interoperability testing against Microsoft's publicly
* 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>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <unordered_set>
#include <utility>
#include "bx_log.h"
#include "task_queue.h"
extern "C" {
HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, void**);
void WINAPI XTaskQueueCloseHandle(void*);
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
HRESULT WINAPI XAsyncGetStatus(void*, bool);
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
void WINAPI XAsyncCancel(void*);
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
HRESULT WINAPI XUserAddResult(void*, void**);
void WINAPI XUserCloseHandle(void*);
HRESULT WINAPI XUserGetId(void*, uint64_t*);
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
const uint8_t*, void*);
HRESULT WINAPI XUserGetTokenAndSignatureResultSize(void*, size_t*);
HRESULT WINAPI XUserGetTokenAndSignatureResult(void*, size_t, void*, void**, size_t*);
HRESULT WINAPI XUserResolvePrivilegeWithUiAsync(void*, uint32_t, uint32_t, void*);
HRESULT WINAPI XUserResolvePrivilegeWithUiResult(void*);
HRESULT WINAPI XStoreCreateContext(void*, void**);
void WINAPI XStoreCloseContextHandle(void*);
HRESULT WINAPI XStoreQueryGameLicenseAsync(void*, void*);
HRESULT WINAPI XStoreQueryGameLicenseResult(void*, void*);
HRESULT WINAPI XStoreAcquireLicenseForPackageAsync(void*, const char*, void*);
HRESULT WINAPI XStoreAcquireLicenseForPackageResult(void*, void**);
HRESULT WINAPI XStoreAcquireLicenseForDurablesAsync(void*, const char*, void*);
HRESULT WINAPI XStoreAcquireLicenseForDurablesResult(void*, void**);
HRESULT WINAPI XStoreQueryEntitledProductsAsync(void*, uint32_t, uint32_t, void*);
HRESULT WINAPI XStoreQueryEntitledProductsResult(void*, void**);
HRESULT WINAPI XStoreQueryAssociatedProductsAsync(void*, uint32_t, uint32_t, void*);
HRESULT WINAPI XStoreQueryAssociatedProductsResult(void*, void**);
HRESULT WINAPI XSystemGetConsoleId(size_t, char*, size_t*);
uint32_t WINAPI XSystemGetDeviceType();
HRESULT WINAPI XSystemGetXboxLiveSandboxId(size_t, char*, size_t*);
HRESULT WINAPI XPersistentLocalStorageGetPathSize(size_t*);
HRESULT WINAPI XPersistentLocalStorageGetPath(size_t, char*, size_t*);
HRESULT WINAPI XPersistentLocalStorageGetSpaceInfo(void*);
HRESULT WINAPI XGameUiShowPlayerProfileCardAsync(void*, uint64_t, void*);
HRESULT WINAPI XGameUiShowTextEntryAsync(const char*, const char*, const char*, uint32_t, uint32_t, void*);
HRESULT WINAPI XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(void*);
HRESULT WINAPI XNetworkingQuerySecurityInformationForUrlAsync(const char*, void*);
} // extern "C"
namespace bx::gdk {
namespace {
constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
// Public Microsoft.GDK.Windows 2610.0.9661 QueryApiImpl class & interface identifiers.
constexpr GUID kCoreGuid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
constexpr GUID kFeatureGuid = {0x8836FE87, 0xEDB9, 0x4FE3, {0x8D, 0xAD, 0x05, 0xF0, 0xD2, 0xCD, 0x5B, 0x40}};
constexpr GUID kSystemClsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
constexpr GUID kSystemIid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
constexpr GUID kErrorGuid = {0x8CA467F7, 0x22E8, 0x4096, {0x84, 0x56, 0xBB, 0x8A, 0xA1, 0x3F, 0x79, 0xD8}};
constexpr GUID kPlsClsid = {0xF4FAF4D4, 0x2D04, 0x4FCE, {0xB3, 0xE0, 0x47, 0x4A, 0x71, 0x3A, 0x3E, 0x84}};
constexpr GUID kPlsIid = {0x41A4E10C, 0x5A7E, 0x41D9, {0x8C, 0x37, 0x37, 0xBD, 0xE6, 0x2A, 0x07, 0xD6}};
constexpr GUID kUserClsid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
constexpr GUID kUserGamertagIid = {0xCEF4FAC0, 0x7676, 0x4A94, {0xA1, 0x19, 0x4C, 0x43, 0xF9, 0xEB, 0x5B, 0x74}};
constexpr GUID kStoreClsid = {0x0DD112AC, 0x7C24, 0x448C, {0xB9, 0x2B, 0x39, 0x60, 0xFB, 0x5B, 0xD3, 0x0C}};
constexpr GUID kStoreIid = {0xB09D803C, 0x2414, 0x4A05, {0x82, 0xC6, 0x66, 0xDF, 0xDC, 0x9E, 0x9A, 0x44}};
constexpr GUID kStoreDurablesIid = {0x2D42FEA5, 0xE71D, 0x4B76, {0x97, 0xCD, 0xC5, 0x0A, 0xFB, 0xB3, 0xAE, 0x5D}};
constexpr GUID kGameUiClsid = {0xDFCD4649, 0x4FF8, 0x4043, {0xBA, 0x07, 0x35, 0xD6, 0x07, 0xDF, 0x98, 0xB0}};
constexpr GUID kGameUiIid = {0xEAF669DF, 0x5542, 0x4590, {0x99, 0xA3, 0x8D, 0xC0, 0x61, 0xF8, 0x37, 0xCC}};
constexpr GUID kNetworkingClsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36, 0xED, 0xB1, 0x85, 0x33, 0x1A}};
constexpr GUID kNetworkingIid = {0xBF2346B2, 0x39AF, 0x4658, {0xB5, 0xEA, 0x44, 0x71, 0x3C, 0x7E, 0x83, 0xB3}};
constexpr GUID kGameClsid = {0x973A344E, 0x24BF, 0x4D0F, {0x84, 0x57, 0x56, 0xC5, 0x34, 0x89, 0x2B, 0x29}};
constexpr GUID kGameIid = {0x2549F142, 0x6419, 0x4A06, {0x97, 0xB5, 0x93, 0x1A, 0xAB, 0x7C, 0x2F, 0x34}};
bool guid_eq(const GUID& a, const GUID& b) {
return std::memcmp(&a, &b, sizeof(GUID)) == 0;
}
struct ComSingleton {
const void* const* vtbl;
const GUID* iid;
const char* name;
};
HRESULT WINAPI com_query_interface(void* self, const GUID* riid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!riid) return E_INVALIDARG;
auto* obj = static_cast<ComSingleton*>(self);
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, *obj->iid)) {
*out = obj;
return S_OK;
}
return E_NOINTERFACE;
}
ULONG WINAPI com_add_ref(void*) {
return 1;
}
ULONG WINAPI com_release(void*) {
return 1;
}
template <size_t Slot>
HRESULT WINAPI com_unimpl_slot(void* self) {
auto* obj = static_cast<const ComSingleton*>(self);
char method[32];
std::snprintf(method, sizeof(method), "slot_%zu", Slot);
BX_VTABLE_STUB_LOG(obj ? obj->name : "IXGameRuntime", static_cast<uint32_t>(Slot), method);
return E_NOTIMPL;
}
template <size_t N, size_t... Is>
constexpr std::array<const void*, N> make_default_vtbl_impl(std::index_sequence<Is...>) {
return {((Is == 0) ? reinterpret_cast<const void*>(&com_query_interface)
: (Is == 1) ? reinterpret_cast<const void*>(&com_add_ref)
: (Is == 2) ? reinterpret_cast<const void*>(&com_release)
: reinterpret_cast<const void*>(&com_unimpl_slot<Is>))...};
}
template <size_t N>
std::array<const void*, N> make_default_vtbl() {
return make_default_vtbl_impl<N>(std::make_index_sequence<N>{});
}
// --- Core (XAsync + XTaskQueue + XThread) ---
thread_local bool tls_time_sensitive = false;
HRESULT WINAPI core_async_get_status(void*, void* async, bool wait) {
return XAsyncGetStatus(async, wait);
}
HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
return XAsyncGetResultSize(async, size);
}
void WINAPI core_async_cancel(void*, void* async) {
XAsyncCancel(async);
}
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
return XTaskQueueCreate(work, comp, out);
}
bool WINAPI core_tq_dispatch(void*, void* queue, Port port, uint32_t timeout) {
return XTaskQueueDispatch(queue, port, timeout);
}
void WINAPI core_tq_close(void*, void* queue) {
XTaskQueueCloseHandle(queue);
}
HRESULT WINAPI core_tq_submit(void*, void* queue, Port port, void* ctx, void (CALLBACK* cb)(void*, bool)) {
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
}
HRESULT WINAPI core_tq_submit_delayed(void*, void* queue, Port port, uint32_t delay_ms, void* ctx,
void (CALLBACK* cb)(void*, bool)) {
if (delay_ms > 0) {
BX_VTABLE_STUB_LOG("IXGameRuntimeCore", 19, "XTaskQueueSubmitDelayedCallback(nonzero_delay)");
}
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
}
bool WINAPI core_tq_get_process(void*, void** out) {
return XTaskQueueGetCurrentProcessTaskQueue(out);
}
HRESULT WINAPI core_thread_set_time_sensitive(void*, bool is_ts) {
tls_time_sensitive = is_ts;
return S_OK;
}
HRESULT WINAPI core_thread_verify_not_time_sensitive(void*) {
return tls_time_sensitive ? E_FAIL : S_OK;
}
HRESULT WINAPI core_runtime_guard_hook(void*, uint32_t, void*) {
// Invoked by public GDK static thunks before subsystem dispatch.
return S_OK;
}
bool WINAPI core_thread_is_time_sensitive(void*) {
return tls_time_sensitive;
}
const std::array<const void*, 36> kCoreVtbl = [] {
auto v = make_default_vtbl<36>();
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
v[12] = reinterpret_cast<const void*>(&core_tq_create);
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
v[17] = reinterpret_cast<const void*>(&core_tq_close);
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
v[19] = reinterpret_cast<const void*>(&core_tq_submit_delayed);
v[25] = reinterpret_cast<const void*>(&core_tq_get_process);
v[27] = reinterpret_cast<const void*>(&core_thread_set_time_sensitive);
v[28] = reinterpret_cast<const void*>(&core_thread_verify_not_time_sensitive);
v[29] = reinterpret_cast<const void*>(&core_runtime_guard_hook);
v[30] = reinterpret_cast<const void*>(&core_thread_is_time_sensitive);
return v;
}();
ComSingleton kCoreObj{kCoreVtbl.data(), &kCoreGuid, "IXGameRuntimeCore"};
// --- XGameRuntimeIsFeatureAvailable ---
bool WINAPI feature_is_available(void*, uint32_t feature) {
// XGameRuntimeFeature enum values from public XGameRuntimeFeature.h.
switch (feature) {
case 2: // XAsync
case 5: // XGame
case 8: // XGameUI
case 10: // XNetworking
case 12: // XPersistentLocalStorage
case 14: // XStore
case 15: // XSystem
case 16: // XTaskQueue
case 17: // XThread
case 18: // XUser
case 19: // XError
return true;
default:
return false;
}
}
const std::array<const void*, 8> kFeatureVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&feature_is_available);
return v;
}();
ComSingleton kFeatureObj{kFeatureVtbl.data(), &kFeatureGuid, "IXGameRuntimeFeature"};
// --- XSystem ---
HRESULT WINAPI sys_get_console_id(void*, size_t sz, char* out, size_t* used) {
return XSystemGetConsoleId(sz, out, used);
}
HRESULT WINAPI sys_get_sandbox_id(void*, size_t sz, char* out, size_t* used) {
return XSystemGetXboxLiveSandboxId(sz, out, used);
}
HRESULT WINAPI sys_get_app_device_id(void*, size_t sz, char* out, size_t* used) {
constexpr char kDeviceId[] = "BX-OFFLINE-APP-DEVICE-000000000001";
if (used) *used = 0;
if (!out) return E_POINTER;
const size_t req = sizeof(kDeviceId);
if (sz < req) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
std::memcpy(out, kDeviceId, req);
if (used) *used = req;
return S_OK;
}
HRESULT WINAPI sys_handle_track(void*, void*, void*) {
return S_OK;
}
bool WINAPI sys_is_handle_valid(void*, void* handle) {
return handle != nullptr;
}
void WINAPI sys_allow_full_bandwidth(void*, bool) {}
const std::array<const void*, 12> kSystemVtbl = [] {
auto v = make_default_vtbl<12>();
v[3] = reinterpret_cast<const void*>(&sys_get_console_id);
v[4] = reinterpret_cast<const void*>(&sys_get_sandbox_id);
v[5] = reinterpret_cast<const void*>(&sys_get_app_device_id);
v[6] = reinterpret_cast<const void*>(&sys_handle_track);
v[7] = reinterpret_cast<const void*>(&sys_is_handle_valid);
v[8] = reinterpret_cast<const void*>(&sys_allow_full_bandwidth);
return v;
}();
ComSingleton kSystemObj{kSystemVtbl.data(), &kSystemIid, "IXSystem"};
// --- XError ---
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;
}();
ComSingleton kErrorObj{kErrorVtbl.data(), &kErrorGuid, "IXError"};
// --- XPersistentLocalStorage ---
HRESULT WINAPI pls_get_path_size(void*, size_t* sz) {
return XPersistentLocalStorageGetPathSize(sz);
}
HRESULT WINAPI pls_get_path(void*, size_t sz, char* out, size_t* used) {
return XPersistentLocalStorageGetPath(sz, out, used);
}
HRESULT WINAPI pls_get_space_info(void*, void* info) {
return XPersistentLocalStorageGetSpaceInfo(info);
}
const std::array<const void*, 12> kPlsVtbl = [] {
auto v = make_default_vtbl<12>();
v[3] = reinterpret_cast<const void*>(&pls_get_path_size);
v[4] = reinterpret_cast<const void*>(&pls_get_path);
v[5] = reinterpret_cast<const void*>(&pls_get_space_info);
return v;
}();
ComSingleton kPlsObj{kPlsVtbl.data(), &kPlsIid, "IXPersistentLocalStorage"};
// --- XUser ---
std::mutex user_event_mutex;
uint64_t next_user_event_token = 1;
std::unordered_set<uint64_t> user_event_tokens;
void WINAPI user_close_handle(void*, void* h) {
XUserCloseHandle(h);
}
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
if (u1 == u2) return 0;
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
}
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
if (!max_users) return E_POINTER;
*max_users = 1;
return S_OK;
}
HRESULT WINAPI user_add_async(void*, uint32_t opts, void* async) {
return XUserAddAsync(opts, async);
}
HRESULT WINAPI user_add_result(void*, void* async, void** out) {
return XUserAddResult(async, out);
}
HRESULT WINAPI user_get_local_id(void*, void* user, uint64_t* local_id) {
if (!local_id) return E_POINTER;
if (!user) return E_INVALIDARG;
*local_id = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(user));
return S_OK;
}
HRESULT WINAPI user_get_id(void*, void* user, uint64_t* id) {
return XUserGetId(user, id);
}
HRESULT WINAPI user_get_is_guest(void*, void* user, bool* is_guest) {
if (!is_guest) return E_POINTER;
if (!user) return E_INVALIDARG;
*is_guest = false;
return S_OK;
}
HRESULT WINAPI user_get_state(void*, void* user, uint32_t* state) {
if (!state) return E_POINTER;
if (!user) return E_INVALIDARG;
*state = 0; // XUserState::SignedIn
return S_OK;
}
HRESULT WINAPI user_get_age_group(void*, void* user, uint32_t* age_group) {
if (!age_group) return E_POINTER;
if (!user) return E_INVALIDARG;
*age_group = 3; // XUserAgeGroup::Adult
return S_OK;
}
HRESULT WINAPI user_check_privilege(void*, void* user, uint32_t, uint32_t, bool* has_priv, uint32_t* deny_reason) {
if (!has_priv) return E_POINTER;
if (!user) return E_INVALIDARG;
*has_priv = true;
if (deny_reason) *deny_reason = 0; // XUserPrivilegeDenyReason::None
return S_OK;
}
HRESULT WINAPI user_resolve_priv_async(void*, void* user, uint32_t opts, uint32_t priv, void* async) {
return XUserResolvePrivilegeWithUiAsync(user, opts, priv, async);
}
HRESULT WINAPI user_resolve_priv_result(void*, void* async) {
return XUserResolvePrivilegeWithUiResult(async);
}
HRESULT WINAPI user_token_async(void*, void* user, uint32_t opts, const char* method, const char* url,
size_t hdr_cnt, const void* hdrs, size_t body_sz, const uint8_t* body, void* async) {
return XUserGetTokenAndSignatureAsync(user, opts, method, url, hdr_cnt, hdrs, body_sz, body, async);
}
HRESULT WINAPI user_token_result_size(void*, void* async, size_t* sz) {
return XUserGetTokenAndSignatureResultSize(async, sz);
}
HRESULT WINAPI user_token_result(void*, void* async, size_t sz, void* buf, void** res, size_t* used) {
return XUserGetTokenAndSignatureResult(async, sz, buf, res, used);
}
HRESULT WINAPI user_register_change_event(void*, void*, void*, void* callback, uint64_t* token) {
if (!token) return E_POINTER;
if (!callback) return E_INVALIDARG;
std::lock_guard lock(user_event_mutex);
const uint64_t id = next_user_event_token++;
user_event_tokens.insert(id);
*token = id;
return S_OK;
}
bool WINAPI user_unregister_change_event(void*, uint64_t token, bool) {
std::lock_guard lock(user_event_mutex);
return user_event_tokens.erase(token) > 0;
}
HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, char* out, size_t* used) {
return XUserGetGamertag(user, comp, sz, out, used);
}
const std::array<const void*, 64> kUserVtbl = [] {
auto v = make_default_vtbl<64>();
v[4] = reinterpret_cast<const void*>(&user_close_handle);
v[5] = reinterpret_cast<const void*>(&user_compare);
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
v[7] = reinterpret_cast<const void*>(&user_add_async);
v[8] = reinterpret_cast<const void*>(&user_add_result);
v[9] = reinterpret_cast<const void*>(&user_get_local_id);
v[11] = reinterpret_cast<const void*>(&user_get_id);
v[13] = reinterpret_cast<const void*>(&user_get_is_guest);
v[14] = reinterpret_cast<const void*>(&user_get_state);
v[19] = reinterpret_cast<const void*>(&user_get_age_group);
v[20] = reinterpret_cast<const void*>(&user_check_privilege);
v[21] = reinterpret_cast<const void*>(&user_resolve_priv_async);
v[22] = reinterpret_cast<const void*>(&user_resolve_priv_result);
v[23] = reinterpret_cast<const void*>(&user_token_async);
v[24] = reinterpret_cast<const void*>(&user_token_result_size);
v[25] = reinterpret_cast<const void*>(&user_token_result);
v[33] = reinterpret_cast<const void*>(&user_register_change_event);
v[34] = reinterpret_cast<const void*>(&user_unregister_change_event);
return v;
}();
ComSingleton kUserObj{kUserVtbl.data(), &kUserClsid, "IXUser"};
const std::array<const void*, 8> kUserGamertagVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&user_get_gamertag);
return v;
}();
ComSingleton kUserGamertagObj{kUserGamertagVtbl.data(), &kUserGamertagIid, "IXUserGamertag"};
// --- XStore ---
HRESULT WINAPI store_create_ctx(void*, void* user, void** out) {
return XStoreCreateContext(user, out);
}
void WINAPI store_close_ctx(void*, void* ctx) {
XStoreCloseContextHandle(ctx);
}
HRESULT WINAPI store_assoc_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
return XStoreQueryAssociatedProductsAsync(ctx, pf, max_items, async);
}
HRESULT WINAPI store_assoc_result(void*, void* async, void** out) {
return XStoreQueryAssociatedProductsResult(async, out);
}
HRESULT WINAPI store_entitled_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
return XStoreQueryEntitledProductsAsync(ctx, pf, max_items, async);
}
HRESULT WINAPI store_entitled_result(void*, void* async, void** out) {
return XStoreQueryEntitledProductsResult(async, out);
}
HRESULT WINAPI store_pkg_lic_async(void*, void* ctx, const char* id, void* async) {
return XStoreAcquireLicenseForPackageAsync(ctx, id, async);
}
HRESULT WINAPI store_pkg_lic_result(void*, void* async, void** out) {
return XStoreAcquireLicenseForPackageResult(async, out);
}
HRESULT WINAPI store_game_lic_async(void*, void* ctx, void* async) {
return XStoreQueryGameLicenseAsync(ctx, async);
}
HRESULT WINAPI store_game_lic_result(void*, void* async, void* out) {
return XStoreQueryGameLicenseResult(async, out);
}
HRESULT WINAPI store_dur_lic_async(void*, void* ctx, const char* id, void* async) {
return XStoreAcquireLicenseForDurablesAsync(ctx, id, async);
}
HRESULT WINAPI store_dur_lic_result(void*, void* async, void** out) {
return XStoreAcquireLicenseForDurablesResult(async, out);
}
const std::array<const void*, 40> kStoreVtbl = [] {
auto v = make_default_vtbl<40>();
v[3] = reinterpret_cast<const void*>(&store_create_ctx);
v[4] = reinterpret_cast<const void*>(&store_close_ctx);
v[5] = reinterpret_cast<const void*>(&store_assoc_async);
v[6] = reinterpret_cast<const void*>(&store_assoc_result);
v[9] = reinterpret_cast<const void*>(&store_entitled_async);
v[10] = reinterpret_cast<const void*>(&store_entitled_result);
v[20] = reinterpret_cast<const void*>(&store_pkg_lic_async);
v[21] = reinterpret_cast<const void*>(&store_pkg_lic_result);
v[28] = reinterpret_cast<const void*>(&store_game_lic_async);
v[29] = reinterpret_cast<const void*>(&store_game_lic_result);
return v;
}();
ComSingleton kStoreObj{kStoreVtbl.data(), &kStoreIid, "IXStore"};
const std::array<const void*, 80> kStoreDurablesVtbl = [] {
auto v = make_default_vtbl<80>();
v[71] = reinterpret_cast<const void*>(&store_dur_lic_async);
v[72] = reinterpret_cast<const void*>(&store_dur_lic_result);
return v;
}();
ComSingleton kStoreDurablesObj{kStoreDurablesVtbl.data(), &kStoreDurablesIid, "IXStoreDurables"};
// --- XGameUi ---
HRESULT WINAPI gameui_profile_async(void*, void* user, uint64_t xuid, void* async) {
return XGameUiShowPlayerProfileCardAsync(user, xuid, async);
}
HRESULT WINAPI gameui_text_async(void*, const char* title, const char* desc, const char* def, uint32_t scope,
uint32_t max_chars, void* async) {
return XGameUiShowTextEntryAsync(title, desc, def, scope, max_chars, async);
}
const std::array<const void*, 32> kGameUiVtbl = [] {
auto v = make_default_vtbl<32>();
v[7] = reinterpret_cast<const void*>(&gameui_profile_async);
v[17] = reinterpret_cast<const void*>(&gameui_text_async);
return v;
}();
ComSingleton kGameUiObj{kGameUiVtbl.data(), &kGameUiIid, "IXGameUi"};
// --- XNetworking ---
struct ConnectivityHint {
uint32_t connectivity_level;
uint32_t connectivity_cost;
uint32_t iana_interface_type;
bool network_initialized;
bool approaching_data_limit;
bool over_data_limit;
bool roaming;
};
static_assert(sizeof(ConnectivityHint) == 16);
HRESULT WINAPI net_udp_port_async(void*, void* async) {
return XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(async);
}
HRESULT WINAPI net_sec_info_async(void*, const char* url, void* async) {
return XNetworkingQuerySecurityInformationForUrlAsync(url, async);
}
HRESULT WINAPI net_get_connectivity_hint(void*, ConnectivityHint* hint) {
if (!hint) return E_POINTER;
// Offline profile: ConnectivityLevelHint::None (1), CostHint::Unrestricted (1).
*hint = {1u, 1u, 6u, true, false, false, false};
return S_OK;
}
const std::array<const void*, 24> kNetworkingVtbl = [] {
auto v = make_default_vtbl<24>();
v[4] = reinterpret_cast<const void*>(&net_udp_port_async);
v[8] = reinterpret_cast<const void*>(&net_sec_info_async);
v[15] = reinterpret_cast<const void*>(&net_get_connectivity_hint);
return v;
}();
ComSingleton kNetworkingObj{kNetworkingVtbl.data(), &kNetworkingIid, "IXNetworking"};
// --- XGame ---
HRESULT WINAPI game_get_xbox_title_id(void*, uint32_t* title_id) {
if (!title_id) return E_POINTER;
// Synthetic offline title ID for BetterXen runtime.
*title_id = 0x42580001u;
return S_OK;
}
const std::array<const void*, 8> kGameVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&game_get_xbox_title_id);
return v;
}();
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;
ComSingleton* obj;
};
const PublicEntry kPublicEntries[] = {
{&kCoreGuid, &kCoreGuid, &kCoreObj},
{&kFeatureGuid, &kFeatureGuid, &kFeatureObj},
{&kSystemClsid, &kSystemIid, &kSystemObj},
{&kErrorGuid, &kErrorGuid, &kErrorObj},
{&kPlsClsid, &kPlsIid, &kPlsObj},
{&kUserClsid, &kUserClsid, &kUserObj},
{&kUserClsid, &kUserGamertagIid, &kUserGamertagObj},
{&kStoreClsid, &kStoreIid, &kStoreObj},
{&kStoreClsid, &kStoreDurablesIid, &kStoreDurablesObj},
{&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
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known) {
*clsid_known = false;
for (const auto& entry : kPublicEntries) {
if (guid_eq(*clsid, *entry.clsid)) {
*clsid_known = true;
if (guid_eq(*iid, *entry.iid) || guid_eq(*iid, kIUnknown)) {
*out = entry.obj;
char detail[96];
std::snprintf(detail, sizeof(detail), "dispatch public_com=%s", entry.obj->name);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "QueryApiImpl", detail);
return true;
}
}
}
return false;
}
} // namespace bx::gdk
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <windows.h>
namespace bx::gdk {
// Dispatches public Microsoft PC GDK (Microsoft.GDK.Windows 2610.0.9661) COM IUnknown
// interfaces queried through QueryApiImpl. Returns true when (clsid, iid) matched and
// *out was populated, or sets *clsid_known=true when clsid matched but iid did not.
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known);
} // namespace bx::gdk
+983
View File
@@ -0,0 +1,983 @@
/*
* Offline XGameSave over bottle-local storage (#468).
*
* 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
* XGameSaveContainerInfo / XGameSaveBlobInfo / XGameSaveBlob layouts, the E_GS_* values,
* the container-name rules and the 16 MB update limit come from there:
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgamesave/xgamesave_members
* No Microsoft header, source or binary was used.
*
* Storage: each SCID has its own directory, <XPersistentLocalStorage path>\saves\<scid id>,
* and each container is one file in it, <container id>.bxgs. Both ids are the 64-bit FNV-1a
* hash of the string's bytes (each byte taken as one UTF-16 code unit 0-255) as 16 lowercase
* hex digits; neither string is ever used as a path. A submitted update
* rewrites the file through a temporary file and MoveFileExW, so an update lands entirely or
* not at all. Every read and read-modify-write of a SCID directory holds a named mutex derived
* from that directory, so threads and processes sharing a title directory do not lose updates.
* The format is BetterXen-defined, little-endian:
* u32 magic "BXGS", u32 version 1, str name, str display name, i64 last-modified time_t,
* u32 blob count, then per blob: str name, u32 size, size bytes. (str = u32 length + bytes)
* A file is valid only if it is consumed exactly, its container name is valid and matches its
* file name, no string holds a NUL, and blob names are unique and within the limit below.
*
* Offline behaviour, where the public pages leave it open:
* - There is no service. syncOnDemand has no effect and needsSync is always false.
* - The provider needs a live XUser handle and a non-null SCID. Saves are separated by SCID.
* - A second write of the same blob in one update fails with E_INVALIDARG (the page allows
* one modification per blob per update but names no error).
* - "16 MB" for GS_MAX_BLOB_SIZE is read as 16 MiB, enforced on the staged total of blob
* names and data.
* - GS_MAX_BLOB_NAME_SIZE has no published value. BetterXen limits blob names to 256 bytes.
* - A null display name in CreateUpdate keeps the container's current display name.
* - While an update's submit is pending, writing to or submitting that update fails with
* E_ILLEGAL_METHOD_CALL. Once it completes, succeeded, failed or canceled, the update can
* be submitted again, so a failed submit can be retried without staging the data again.
* - Reading named blobs of a container that was never submitted fails with
* E_GS_BLOB_NOT_FOUND; reading all of them returns zero blobs.
* - A full disk on submit is E_GS_OUT_OF_LOCAL_STORAGE.
* - Closing a provider closes its containers and their updates; closing a container closes
* its updates. The last XGameRuntimeUninitialize closes every handle.
* - Paths of MAX_PATH or more (executable or storage) fail with ERROR_FILENAME_EXCED_RANGE.
*/
#include "runtime_internal.h"
#include "synthetic_keys.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <new>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "bx_log.h"
extern "C" HRESULT WINAPI XAsyncGetStatus(void* block, bool wait);
namespace bx::gdk {
namespace {
using synthetic::GameSaveSlot;
// E_GS_* values listed on the XGameSave members page.
constexpr HRESULT kInvalidContainerName = static_cast<HRESULT>(0x80830001u);
constexpr HRESULT kOutOfLocalStorage = static_cast<HRESULT>(0x80830003u);
constexpr HRESULT kUpdateTooBig = static_cast<HRESULT>(0x80830005u);
constexpr HRESULT kProvidedBufferTooSmall = static_cast<HRESULT>(0x80830007u);
constexpr HRESULT kBlobNotFound = static_cast<HRESULT>(0x80830008u);
constexpr HRESULT kFileCorrupt = HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT);
constexpr size_t kMaxUpdateBytes = 16u * 1024u * 1024u;
constexpr size_t kMaxContainerName = 256;
constexpr size_t kMaxBlobName = 256;
struct ContainerInfo { // XGameSaveContainerInfo
const char* name;
const char* display_name;
uint32_t blob_count;
uint64_t total_size;
time_t last_modified_time;
bool needs_sync;
};
static_assert(sizeof(time_t) == 8);
static_assert(offsetof(ContainerInfo, blob_count) == 16 && offsetof(ContainerInfo, total_size) == 24);
static_assert(offsetof(ContainerInfo, last_modified_time) == 32 && offsetof(ContainerInfo, needs_sync) == 40);
struct BlobInfo { // XGameSaveBlobInfo
const char* name;
uint32_t size;
};
struct Blob { // XGameSaveBlob
BlobInfo info;
uint8_t* data;
};
static_assert(sizeof(BlobInfo) == 16 && offsetof(Blob, data) == 16 && sizeof(Blob) == 24);
using ContainerInfoCallback = bool(CALLBACK*)(const ContainerInfo*, void*);
// FNV-1a over the string's bytes, each taken as one UTF-16 code unit 0-255, as 16 hex digits.
std::wstring hex_id(const std::string& text) {
std::wstring wide;
wide.reserve(text.size());
for (const char c : text) wide.push_back(static_cast<wchar_t>(static_cast<unsigned char>(c)));
wchar_t id[17];
std::swprintf(id, 17, L"%016llx", static_cast<unsigned long long>(fnv1a(wide.c_str())));
return id;
}
// --- Names ---
bool name_char(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
}
// Rules from the XGameSaveCreateContainer page: an optional path part up to the last '/'
// (A-Z, a-z, 0-9, _, /) and a non-empty file part (A-Z, a-z, 0-9, _, ., -) that does not
// end in a period or contain "..". At most 256 characters.
bool valid_container_name(const char* name, size_t length) {
if (!name || length == 0 || length > kMaxContainerName) return false;
const char* end = name + length;
const char* file = name;
for (const char* c = name; c < end; ++c) {
if (*c == '/') file = c + 1;
}
for (const char* c = name; c < file; ++c) {
if (!name_char(*c) && *c != '/') return false;
}
if (file == end || end[-1] == '.') return false;
for (const char* c = file; c < end; ++c) {
if (!name_char(*c) && *c != '.' && *c != '-') return false;
if (c[0] == '.' && c + 1 < end && c[1] == '.') return false;
}
return true;
}
bool valid_container_name(const char* name) {
return name && valid_container_name(name, strnlen(name, kMaxContainerName + 1));
}
bool valid_blob_name(const std::string& name) {
return !name.empty() && name.size() <= kMaxBlobName && name.find('\0') == std::string::npos;
}
// --- Container files ---
struct ContainerData {
std::string name;
std::string display_name;
int64_t last_modified = 0;
uint64_t total_size = 0;
std::map<std::string, std::vector<uint8_t>> blobs; // Data left empty when parsed without data.
};
constexpr uint32_t kMagic = 0x53475842; // "BXGS"
constexpr uint32_t kFormatVersion = 1;
constexpr wchar_t kExtension[] = L".bxgs";
void put_u32(std::vector<uint8_t>& out, uint32_t value) {
for (int shift = 0; shift < 32; shift += 8) out.push_back(static_cast<uint8_t>(value >> shift));
}
void put_u64(std::vector<uint8_t>& out, uint64_t value) {
put_u32(out, static_cast<uint32_t>(value));
put_u32(out, static_cast<uint32_t>(value >> 32));
}
void put_string(std::vector<uint8_t>& out, const std::string& text) {
put_u32(out, static_cast<uint32_t>(text.size()));
out.insert(out.end(), text.begin(), text.end());
}
std::vector<uint8_t> serialize(const ContainerData& data) {
std::vector<uint8_t> out;
put_u32(out, kMagic);
put_u32(out, kFormatVersion);
put_string(out, data.name);
put_string(out, data.display_name);
put_u64(out, static_cast<uint64_t>(data.last_modified));
put_u32(out, static_cast<uint32_t>(data.blobs.size()));
for (const auto& [name, bytes] : data.blobs) {
put_string(out, name);
put_u32(out, static_cast<uint32_t>(bytes.size()));
out.insert(out.end(), bytes.begin(), bytes.end());
}
return out;
}
class Reader {
public:
explicit Reader(const std::vector<uint8_t>& bytes) : next_(bytes.data()), left_(bytes.size()) {}
bool u32(uint32_t& value) {
if (left_ < 4) return false;
value = 0;
for (int i = 0; i < 4; ++i) value |= static_cast<uint32_t>(next_[i]) << (8 * i);
next_ += 4;
left_ -= 4;
return true;
}
bool u64(uint64_t& value) {
uint32_t low, high;
if (!u32(low) || !u32(high)) return false;
value = (static_cast<uint64_t>(high) << 32) | low;
return true;
}
bool bytes(size_t size, const uint8_t*& data) {
if (left_ < size) return false;
data = next_;
next_ += size;
left_ -= size;
return true;
}
// A NUL cannot pass through the C string APIs, so a stored one is corruption.
bool string(std::string& text) {
uint32_t size;
const uint8_t* data;
if (!u32(size) || !bytes(size, data) || std::memchr(data, 0, size)) return false;
text.assign(reinterpret_cast<const char*>(data), size);
return true;
}
bool done() const { return left_ == 0; }
private:
const uint8_t* next_;
size_t left_;
};
// with_data false validates the whole file but keeps only names and sizes.
bool parse(const std::vector<uint8_t>& bytes, ContainerData& data, bool with_data) {
Reader in(bytes);
uint32_t magic, version, count;
uint64_t modified;
if (!in.u32(magic) || magic != kMagic || !in.u32(version) || version != kFormatVersion ||
!in.string(data.name) || !valid_container_name(data.name.c_str(), data.name.size()) ||
!in.string(data.display_name) || !in.u64(modified) || !in.u32(count)) {
return false;
}
data.last_modified = static_cast<int64_t>(modified);
for (uint32_t i = 0; i < count; ++i) {
std::string name;
uint32_t size;
const uint8_t* blob;
if (!in.string(name) || !valid_blob_name(name) || !in.u32(size) || !in.bytes(size, blob)) return false;
auto content = with_data ? std::vector<uint8_t>(blob, blob + size) : std::vector<uint8_t>();
if (!data.blobs.emplace(std::move(name), std::move(content)).second) return false;
data.total_size += size;
}
return in.done();
}
std::wstring container_file(const std::wstring& dir, const std::string& name) {
return dir + L"\\" + hex_id(name) + kExtension;
}
HRESULT read_file(const std::wstring& path, std::vector<uint8_t>& out, bool& exists) {
exists = false;
// Share everything, so a reader never blocks another process's replace.
const HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
const auto error = GetLastError();
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error);
}
exists = true;
HRESULT hr = S_OK;
LARGE_INTEGER size{};
if (!GetFileSizeEx(file, &size)) {
hr = HRESULT_FROM_WIN32(GetLastError());
} else {
try {
out.resize(static_cast<size_t>(size.QuadPart));
} catch (const std::bad_alloc&) {
hr = E_OUTOFMEMORY;
}
size_t done = 0;
while (SUCCEEDED(hr) && done < out.size()) {
const DWORD chunk = static_cast<DWORD>(std::min<size_t>(out.size() - done, 1u << 30));
DWORD got = 0;
if (!ReadFile(file, out.data() + done, chunk, &got, nullptr)) hr = HRESULT_FROM_WIN32(GetLastError());
else if (got == 0) hr = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
done += got;
}
}
CloseHandle(file);
return hr;
}
HRESULT write_error(DWORD error) {
return error == ERROR_DISK_FULL || error == ERROR_HANDLE_DISK_FULL ? kOutOfLocalStorage
: HRESULT_FROM_WIN32(error);
}
HRESULT write_file_atomic(const std::wstring& path, const std::vector<uint8_t>& bytes) {
const std::wstring temp = path + L"." + std::to_wstring(GetCurrentProcessId()) + L".tmp";
const HANDLE file =
CreateFileW(temp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return write_error(GetLastError());
HRESULT hr = S_OK;
size_t done = 0;
while (SUCCEEDED(hr) && done < bytes.size()) {
const DWORD chunk = static_cast<DWORD>(std::min<size_t>(bytes.size() - done, 1u << 30));
DWORD wrote = 0;
if (!WriteFile(file, bytes.data() + done, chunk, &wrote, nullptr)) hr = write_error(GetLastError());
done += wrote;
}
if (SUCCEEDED(hr) && !FlushFileBuffers(file)) hr = write_error(GetLastError());
CloseHandle(file);
if (SUCCEEDED(hr) && !MoveFileExW(temp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
hr = write_error(GetLastError());
}
if (FAILED(hr)) DeleteFileW(temp.c_str());
return hr;
}
// Logs the file name only: bx_log_emit does not escape, and a Windows file name cannot hold
// a backslash, quote or control character, so it is always valid JSON string content. The
// directory is the title's saves directory for one SCID.
void log_bad_file(const char* event, const std::wstring& path) {
const auto slash = path.find_last_of(L'\\');
const std::wstring name = slash == std::wstring::npos ? path : path.substr(slash + 1);
char detail[MAX_PATH * 3 + 8];
const int bytes = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), -1, detail, sizeof(detail), nullptr, nullptr);
if (bytes <= 0) std::snprintf(detail, sizeof(detail), "(unprintable file name)");
bx_log_emit(BX_LOG_WARN, "xgamesave", event, detail);
}
// Holds the named mutex for one SCID directory. Abandonment by a crashed owner is not an
// error: every file is replaced atomically, so a half-done update never reaches disk.
class DirectoryLock {
public:
explicit DirectoryLock(const std::wstring& dir) {
wchar_t lower[MAX_PATH];
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr,
nullptr, 0)) {
status_ = HRESULT_FROM_WIN32(GetLastError());
return;
}
wchar_t name[64];
std::swprintf(name, 64, L"Local\\BetterXen.XGameSave.%016llx", static_cast<unsigned long long>(fnv1a(lower)));
mutex_ = CreateMutexW(nullptr, FALSE, name);
if (!mutex_) {
status_ = HRESULT_FROM_WIN32(GetLastError());
return;
}
const DWORD wait = WaitForSingleObject(mutex_, INFINITE);
status_ = wait == WAIT_OBJECT_0 || wait == WAIT_ABANDONED ? S_OK : HRESULT_FROM_WIN32(GetLastError());
}
~DirectoryLock() {
if (!mutex_) return;
if (SUCCEEDED(status_)) ReleaseMutex(mutex_);
CloseHandle(mutex_);
}
DirectoryLock(const DirectoryLock&) = delete;
DirectoryLock& operator=(const DirectoryLock&) = delete;
HRESULT status() const { return status_; }
private:
HANDLE mutex_ = nullptr;
HRESULT status_ = E_FAIL;
};
// Caller holds the DirectoryLock for dir.
HRESULT load_container(const std::wstring& dir, const std::string& name, ContainerData& data, bool& exists) {
const auto path = container_file(dir, name);
std::vector<uint8_t> bytes;
auto hr = read_file(path, bytes, exists);
if (FAILED(hr) || !exists) return hr;
if (!parse(bytes, data, true)) {
log_bad_file("corrupt_container", path);
return kFileCorrupt;
}
if (data.name != name) {
log_bad_file("container_id_collision", path);
return HRESULT_FROM_WIN32(ERROR_FILE_EXISTS);
}
return S_OK;
}
// Caller holds the DirectoryLock for dir. Files that cannot be read or parsed are logged and
// skipped, so one bad file does not hide the others.
HRESULT list_containers(const std::wstring& dir, std::vector<ContainerData>& out) {
WIN32_FIND_DATAW found;
const HANDLE search = FindFirstFileW((dir + L"\\*" + kExtension).c_str(), &found);
if (search == INVALID_HANDLE_VALUE) {
const auto error = GetLastError();
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error);
}
HRESULT hr = S_OK;
do {
const std::wstring file = found.cFileName;
constexpr size_t ext = std::size(kExtension) - 1;
if ((found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || file.size() <= ext ||
file.compare(file.size() - ext, ext, kExtension) != 0) {
continue;
}
const std::wstring path = dir + L"\\" + file;
std::vector<uint8_t> bytes;
bool exists;
ContainerData data;
const auto read = read_file(path, bytes, exists);
if (read == E_OUTOFMEMORY) {
hr = read;
break;
}
if (FAILED(read)) {
log_bad_file("unreadable_container", path);
continue;
}
if (!exists) continue; // Replaced or removed since the search returned it.
if (!parse(bytes, data, false) || container_file(dir, data.name) != path) {
log_bad_file("corrupt_container", path);
continue;
}
try {
out.push_back(std::move(data));
} catch (const std::bad_alloc&) {
hr = E_OUTOFMEMORY;
}
} while (SUCCEEDED(hr) && FindNextFileW(search, &found));
FindClose(search);
return hr;
}
HRESULT saves_directory(const std::string& scid, std::wstring& dir) {
wchar_t root[MAX_PATH];
auto hr = title_storage_directory(root);
if (FAILED(hr)) return hr;
const std::wstring saves = std::wstring(root) + L"\\saves";
hr = ensure_directory(saves.c_str());
if (FAILED(hr)) return hr;
dir = saves + L"\\" + hex_id(scid);
if (dir.size() >= MAX_PATH) return HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
return ensure_directory(dir.c_str());
}
// --- Handles ---
// Lock order: the runtime lock (taken by active_runtime_generation, is_valid_user, around
// consume callbacks and around release_game_save_state) before handle_mutex. Nothing here
// calls into the runtime while holding handle_mutex.
struct Provider {
uint32_t generation;
std::wstring dir;
};
struct Container {
void* provider;
std::string name;
};
struct Update {
void* container;
bool keep_display_name;
std::string display_name;
std::map<std::string, std::vector<uint8_t>> writes;
size_t staged_bytes = 0;
// Set while a submit of this update is queued or running; cleared by that operation.
std::shared_ptr<std::atomic<bool>> pending;
};
std::mutex handle_mutex;
std::unordered_map<void*, Provider> providers;
std::unordered_map<void*, Container> containers;
std::unordered_map<void*, Update> updates;
// Each handle type has its own range (tag in bits 40-43), so a handle of one type is never
// a valid handle of another. package.cpp uses tag 4.
enum : uintptr_t { kProviderTag = 1, kContainerTag = 2, kUpdateTag = 3 };
uintptr_t handle_counter = 0;
void* next_handle(uintptr_t tag) {
++handle_counter;
return reinterpret_cast<void*>(tag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
}
// The finders below require handle_mutex. A handle from before the last uninitialize, or
// one whose provider was closed, is not found.
const Provider* find_provider(void* handle, uint32_t generation) {
const auto found = providers.find(handle);
if (found == providers.end() || generation == 0 || found->second.generation != generation) return nullptr;
return &found->second;
}
const Container* find_container(void* handle, uint32_t generation, const Provider** provider) {
const auto found = containers.find(handle);
if (found == containers.end()) return nullptr;
*provider = find_provider(found->second.provider, generation);
return *provider ? &found->second : nullptr;
}
Update* find_update(void* handle, uint32_t generation, const Container** container, const Provider** provider) {
const auto found = updates.find(handle);
if (found == updates.end()) return nullptr;
*container = find_container(found->second.container, generation, provider);
return *container ? &found->second : nullptr;
}
template <typename Map, typename Value>
HRESULT insert_handle(Map& map, uintptr_t tag, Value&& value, void** out) {
void* handle = next_handle(tag);
try {
map.emplace(handle, std::forward<Value>(value));
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
*out = handle;
return S_OK;
}
// Caller holds handle_mutex.
void erase_updates_of(void* container) {
std::erase_if(updates, [&](const auto& entry) { return entry.second.container == container; });
}
// Caller holds handle_mutex.
void erase_containers_of(void* provider) {
for (auto it = containers.begin(); it != containers.end();) {
if (it->second.provider == provider) {
erase_updates_of(it->first);
it = containers.erase(it);
} else {
++it;
}
}
}
// --- Async operations ---
enum : uint32_t { kInitProviderOp = 0x58475301, kSubmitUpdateOp = 0x58475302, kReadBlobsOp = 0x58475303 };
class InitProviderOp final : public AsyncOp {
public:
uint32_t generation = 0;
std::string scid;
std::wstring dir;
uint32_t kind() const override { return kInitProviderOp; }
HRESULT execute() override try {
return saves_directory(scid, dir);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
size_t result_size() const override { return sizeof(void*); }
};
class SubmitUpdateOp final : public AsyncOp {
public:
std::wstring dir;
std::string name;
bool keep_display_name = false;
std::string display_name;
std::map<std::string, std::vector<uint8_t>> writes;
std::shared_ptr<std::atomic<bool>> pending;
// Covers cancellation and a submission that never ran.
~SubmitUpdateOp() override { finish(); }
uint32_t kind() const override { return kSubmitUpdateOp; }
size_t result_size() const override { return 0; }
HRESULT execute() override {
const auto hr = write();
finish();
return hr;
}
private:
// Once per op: a resubmit shares the flag, so an old op must not clear it again later.
void finish() {
if (pending) pending->store(false);
pending.reset();
}
HRESULT write() try {
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
ContainerData data;
bool exists = false;
auto hr = load_container(dir, name, data, exists);
if (FAILED(hr)) return hr;
if (!exists) data.name = name;
if (!keep_display_name) data.display_name = display_name;
for (auto& [blob, bytes] : writes) data.blobs[blob] = std::move(bytes);
data.last_modified = static_cast<int64_t>(std::time(nullptr));
return write_file_atomic(container_file(dir, name), serialize(data));
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
};
class ReadBlobsOp final : public AsyncOp {
public:
std::wstring dir;
std::string name;
std::vector<std::string> wanted; // Empty: every blob.
std::vector<std::pair<std::string, std::vector<uint8_t>>> found;
size_t bytes = 0;
uint32_t kind() const override { return kReadBlobsOp; }
size_t result_size() const override { return bytes; }
HRESULT execute() override try {
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
ContainerData data;
bool exists = false;
const auto hr = load_container(dir, name, data, exists);
if (FAILED(hr)) return hr;
if (wanted.empty()) {
for (auto& [blob, content] : data.blobs) found.emplace_back(blob, std::move(content));
} else {
for (const auto& blob : wanted) {
const auto match = data.blobs.find(blob);
if (match == data.blobs.end()) return kBlobNotFound;
found.emplace_back(blob, std::move(match->second));
}
}
bytes = found.size() * sizeof(Blob);
for (const auto& [blob, content] : found) bytes += blob.size() + 1 + content.size();
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
// Layout in the caller's buffer: the Blob array, then all data, then the names.
void copy_to(Blob* out) const {
auto* cursor = reinterpret_cast<uint8_t*>(out) + found.size() * sizeof(Blob);
for (size_t i = 0; i < found.size(); ++i) {
const auto& content = found[i].second;
out[i].info.size = static_cast<uint32_t>(content.size());
out[i].data = cursor;
if (!content.empty()) std::memcpy(cursor, content.data(), content.size());
cursor += content.size();
}
for (size_t i = 0; i < found.size(); ++i) {
const auto& blob = found[i].first;
std::memcpy(cursor, blob.c_str(), blob.size() + 1);
out[i].info.name = reinterpret_cast<const char*>(cursor);
cursor += blob.size() + 1;
}
}
};
HRESULT stale_handle_error(uint32_t generation) {
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
}
} // 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) {
if (!async) return E_POINTER;
if (!scid) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!is_valid_user(user)) return stale_handle_error(generation);
std::unique_ptr<InitProviderOp> op(new (std::nothrow) InitProviderOp);
if (!op) return E_OUTOFMEMORY;
try {
op->scid = scid;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
op->generation = generation;
return begin_async_op(async, std::move(op));
}
HRESULT WINAPI initialize_provider_result(void*, void* async, void** provider) {
if (!provider) return E_POINTER;
*provider = nullptr;
return consume_async_op(async, kInitProviderOp, [&](AsyncOp& base) {
auto& op = static_cast<InitProviderOp&>(base);
std::lock_guard lock(handle_mutex);
return insert_handle(providers, kProviderTag, Provider{op.generation, op.dir}, provider);
});
}
void WINAPI close_provider(void*, void* provider) {
std::lock_guard lock(handle_mutex);
if (providers.erase(provider)) erase_containers_of(provider);
}
HRESULT WINAPI create_container(void*, void* provider, const char* name, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
if (!find_provider(provider, generation)) return stale_handle_error(generation);
if (!valid_container_name(name)) return kInvalidContainerName;
try {
return insert_handle(containers, kContainerTag, Container{provider, name}, out);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
void WINAPI close_container(void*, void* container) {
std::lock_guard lock(handle_mutex);
if (containers.erase(container)) erase_updates_of(container);
}
HRESULT WINAPI create_update(void*, void* container, const char* display_name, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
const Provider* provider = nullptr;
if (!find_container(container, generation, &provider)) return stale_handle_error(generation);
try {
Update staged;
staged.container = container;
staged.keep_display_name = display_name == nullptr;
staged.display_name = display_name ? display_name : "";
staged.pending = std::make_shared<std::atomic<bool>>(false);
return insert_handle(updates, kUpdateTag, std::move(staged), out);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
void WINAPI close_update(void*, void* update) {
std::lock_guard lock(handle_mutex);
updates.erase(update);
}
HRESULT WINAPI submit_blob_write(void*, void* update, const char* blob_name, const uint8_t* data, size_t size) {
if (!blob_name) return E_INVALIDARG;
const size_t name_length = strnlen(blob_name, kMaxBlobName + 1);
if (name_length == 0 || name_length > kMaxBlobName) return E_INVALIDARG;
if (!data && size) return E_POINTER;
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
const Container* container = nullptr;
const Provider* provider = nullptr;
auto* staged = find_update(update, generation, &container, &provider);
if (!staged) return stale_handle_error(generation);
if (staged->pending->load()) return kIllegalMethodCall;
if (staged->writes.contains(blob_name)) return E_INVALIDARG;
if (size > kMaxUpdateBytes - staged->staged_bytes ||
name_length > kMaxUpdateBytes - staged->staged_bytes - size) {
return kUpdateTooBig;
}
try {
staged->writes.emplace(blob_name, std::vector<uint8_t>(data, data + size));
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
staged->staged_bytes += name_length + size;
return S_OK;
}
HRESULT WINAPI submit_update_async(void*, void* update, void* async) {
if (!async) return E_POINTER;
std::unique_ptr<SubmitUpdateOp> op(new (std::nothrow) SubmitUpdateOp);
if (!op) return E_OUTOFMEMORY;
const auto generation = active_runtime_generation();
{
std::lock_guard lock(handle_mutex);
const Container* container = nullptr;
const Provider* provider = nullptr;
auto* staged = find_update(update, generation, &container, &provider);
if (!staged) return stale_handle_error(generation);
if (staged->pending->load()) return kIllegalMethodCall;
try {
op->dir = provider->dir;
op->name = container->name;
op->keep_display_name = staged->keep_display_name;
op->display_name = staged->display_name;
op->writes = staged->writes;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
staged->pending->store(true);
op->pending = staged->pending;
}
// On failure begin_async_op destroys op, whose destructor clears the pending flag.
return begin_async_op(async, std::move(op));
}
HRESULT WINAPI submit_update_result(void*, void* async) {
return consume_async_op(async, kSubmitUpdateOp, [](AsyncOp&) { return S_OK; });
}
HRESULT WINAPI read_blob_data_async(void*, void* container, const char** names, uint32_t count, void* async) {
if (!async) return E_POINTER;
if (count && !names) return E_INVALIDARG;
std::unique_ptr<ReadBlobsOp> op(new (std::nothrow) ReadBlobsOp);
if (!op) return E_OUTOFMEMORY;
try {
for (uint32_t i = 0; i < count; ++i) {
if (!names[i] || !*names[i]) return E_INVALIDARG;
if (std::find(op->wanted.begin(), op->wanted.end(), names[i]) != op->wanted.end()) return E_INVALIDARG;
op->wanted.emplace_back(names[i]);
}
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
const Provider* provider = nullptr;
const auto* open = find_container(container, generation, &provider);
if (!open) return stale_handle_error(generation);
op->dir = provider->dir;
op->name = open->name;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
return begin_async_op(async, std::move(op));
}
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(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, 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 {
std::wstring dir;
{
std::lock_guard lock(handle_mutex);
const auto* open = find_provider(provider, generation);
if (!open) return stale_handle_error(generation);
dir = open->dir;
}
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
const auto hr = list_containers(dir, list);
if (FAILED(hr)) return hr;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.name < b.name; });
// No lock is held here, so the callback may call back into XGameSave.
for (const auto& data : list) {
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 (!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) {
if (!out) return E_POINTER;
*out = nullptr;
if (!iid) return E_INVALIDARG;
constexpr GUID own = synthetic::key(synthetic::kGameSave.iid);
if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) {
*out = self;
return S_OK;
}
return E_NOINTERFACE;
}
// A process-lifetime singleton: reference counting has nothing to free.
ULONG WINAPI add_ref(void*) { return 1; }
ULONG WINAPI release(void*) { return 1; }
template <typename Fn>
const void* slot_fn(Fn fn) {
return reinterpret_cast<const void*>(fn);
}
constexpr size_t at(GameSaveSlot slot) { return static_cast<size_t>(slot); }
const std::array<const void*, at(GameSaveSlot::Count)> kVtbl = [] {
std::array<const void*, at(GameSaveSlot::Count)> v{};
v[at(GameSaveSlot::QueryInterface)] = slot_fn(&query_interface);
v[at(GameSaveSlot::AddRef)] = slot_fn(&add_ref);
v[at(GameSaveSlot::Release)] = slot_fn(&release);
v[at(GameSaveSlot::InitializeProviderAsync)] = slot_fn(&initialize_provider_async);
v[at(GameSaveSlot::InitializeProviderResult)] = slot_fn(&initialize_provider_result);
v[at(GameSaveSlot::CloseProvider)] = slot_fn(&close_provider);
v[at(GameSaveSlot::CreateContainer)] = slot_fn(&create_container);
v[at(GameSaveSlot::CloseContainer)] = slot_fn(&close_container);
v[at(GameSaveSlot::CreateUpdate)] = slot_fn(&create_update);
v[at(GameSaveSlot::CloseUpdate)] = slot_fn(&close_update);
v[at(GameSaveSlot::SubmitBlobWrite)] = slot_fn(&submit_blob_write);
v[at(GameSaveSlot::SubmitUpdateAsync)] = slot_fn(&submit_update_async);
v[at(GameSaveSlot::SubmitUpdateResult)] = slot_fn(&submit_update_result);
v[at(GameSaveSlot::ReadBlobDataAsync)] = slot_fn(&read_blob_data_async);
v[at(GameSaveSlot::ReadBlobDataResult)] = slot_fn(&read_blob_data_result);
v[at(GameSaveSlot::EnumerateContainerInfo)] = slot_fn(&enumerate_container_info);
return v;
}();
struct ComObject {
const void* const* vtbl;
};
const ComObject kObject{kVtbl.data()};
} // namespace
const void* const game_save_object = &kObject;
void release_game_save_state() {
std::lock_guard lock(handle_mutex);
updates.clear();
containers.clear();
providers.clear();
}
} // namespace bx::gdk
+306
View File
@@ -0,0 +1,306 @@
/*
* Offline XPackage identity and mount queries (#468).
*
* 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
* { Game, Content, PublisherContent }, so Game is 0):
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xpackage/xpackage_members
* No Microsoft header, source or binary was used.
*
* Offline behaviour: the running executable's directory stands in for the installed package.
* - The identifier is "BXPKG" + 16 hex digits of the FNV-1a hash of that directory
* (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) 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. 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.
*/
#include "runtime_internal.h"
#include "synthetic_keys.h"
#include <array>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <memory>
#include <mutex>
#include <new>
#include <string>
#include <unordered_map>
namespace bx::gdk {
namespace {
using synthetic::PackageSlot;
constexpr uint32_t kPackageKindGame = 0;
constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
constexpr char kIdPrefix[] = "BXPKG";
constexpr size_t kIdBytes = sizeof(kIdPrefix) - 1 + 16 + 1;
HRESULT executable_directory(std::wstring& dir) {
wchar_t path[MAX_PATH];
const auto hr = executable_path(path);
if (FAILED(hr)) return hr;
wchar_t* slash = std::wcsrchr(path, L'\\');
if (!slash) return HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME);
// Keep the separator of a drive root ("C:\").
slash[slash == path + 2 && path[1] == L':' ? 1 : 0] = L'\0';
dir = path;
return S_OK;
}
HRESULT current_identifier(char (&id)[kIdBytes]) {
std::wstring dir;
auto hr = executable_directory(dir);
if (FAILED(hr)) return hr;
wchar_t lower[MAX_PATH];
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr, nullptr, 0)) {
return HRESULT_FROM_WIN32(GetLastError());
}
std::snprintf(id, kIdBytes, "%s%016llx", kIdPrefix, static_cast<unsigned long long>(fnv1a(lower)));
return S_OK;
}
HRESULT is_current_package(const char* identifier, bool& match) {
char id[kIdBytes];
const auto hr = current_identifier(id);
match = SUCCEEDED(hr) && std::strcmp(identifier, id) == 0;
return hr;
}
struct Mount {
uint32_t generation;
std::string path; // UTF-8
};
std::mutex mount_mutex;
uintptr_t handle_counter = 0;
std::unordered_map<void*, Mount> mounts;
// Mount handles use tag 4 in bits 40-43, a range no XGameSave handle uses (game_save.cpp).
constexpr uintptr_t kMountTag = 4;
// Caller holds mount_mutex.
const Mount* find_mount(void* handle, uint32_t generation) {
const auto found = mounts.find(handle);
if (found == mounts.end() || generation == 0 || found->second.generation != generation) return nullptr;
return &found->second;
}
HRESULT stale_handle_error(uint32_t generation) {
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
}
// 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;
if (!active_runtime_generation()) return kRuntimeNotInitialized;
char id[kIdBytes];
const auto hr = current_identifier(id);
if (FAILED(hr)) return hr;
if (size < kIdBytes) return kInsufficientBuffer;
std::memcpy(buffer, id, kIdBytes);
return S_OK;
}
HRESULT WINAPI get_package_kind(void*, const char* identifier, uint32_t* kind) {
if (!kind) return E_POINTER;
if (!identifier) return E_INVALIDARG;
if (!active_runtime_generation()) return kRuntimeNotInitialized;
bool match = false;
const auto hr = is_current_package(identifier, match);
if (FAILED(hr)) return hr;
if (!match) return kNotFound;
*kind = kPackageKindGame;
return S_OK;
}
HRESULT WINAPI mount(void*, const char* identifier, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!identifier) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!generation) return kRuntimeNotInitialized;
std::string path;
const auto hr = resolve_mount(identifier, path);
return FAILED(hr) ? hr : insert_mount(generation, std::move(path), out);
}
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 {
op->identifier = identifier;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
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) {
if (!size) return E_POINTER;
*size = 0;
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
const auto* open = find_mount(handle, generation);
if (!open) return stale_handle_error(generation);
*size = open->path.size() + 1;
return S_OK;
}
HRESULT WINAPI get_mount_path(void*, void* handle, size_t size, char* path) {
if (!path) return E_POINTER;
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
const auto* open = find_mount(handle, generation);
if (!open) return stale_handle_error(generation);
if (size < open->path.size() + 1) return kInsufficientBuffer;
std::memcpy(path, open->path.c_str(), open->path.size() + 1);
return S_OK;
}
void WINAPI close_mount_handle(void*, void* handle) {
std::lock_guard lock(mount_mutex);
mounts.erase(handle);
}
namespace {
// --- COM object ---
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!iid) return E_INVALIDARG;
constexpr GUID own = synthetic::key(synthetic::kPackage.iid);
if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) {
*out = self;
return S_OK;
}
return E_NOINTERFACE;
}
// A process-lifetime singleton: reference counting has nothing to free.
ULONG WINAPI add_ref(void*) { return 1; }
ULONG WINAPI release(void*) { return 1; }
template <typename Fn>
const void* slot_fn(Fn fn) {
return reinterpret_cast<const void*>(fn);
}
constexpr size_t at(PackageSlot slot) { return static_cast<size_t>(slot); }
const std::array<const void*, at(PackageSlot::Count)> kVtbl = [] {
std::array<const void*, at(PackageSlot::Count)> v{};
v[at(PackageSlot::QueryInterface)] = slot_fn(&query_interface);
v[at(PackageSlot::AddRef)] = slot_fn(&add_ref);
v[at(PackageSlot::Release)] = slot_fn(&release);
v[at(PackageSlot::GetCurrentProcessPackageIdentifier)] = slot_fn(&get_current_process_package_identifier);
v[at(PackageSlot::GetPackageKind)] = slot_fn(&get_package_kind);
v[at(PackageSlot::Mount)] = slot_fn(&mount);
v[at(PackageSlot::GetMountPathSize)] = slot_fn(&get_mount_path_size);
v[at(PackageSlot::GetMountPath)] = slot_fn(&get_mount_path);
v[at(PackageSlot::CloseMountHandle)] = slot_fn(&close_mount_handle);
return v;
}();
struct ComObject {
const void* const* vtbl;
};
const ComObject kObject{kVtbl.data()};
} // namespace
const void* const package_object = &kObject;
void release_package_state() {
std::lock_guard lock(mount_mutex);
mounts.clear();
}
} // namespace bx::gdk
+109
View File
@@ -0,0 +1,109 @@
#pragma once
// Internal interfaces shared by the xgameruntime.dll translation units. Nothing here is exported.
#include <windows.h>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
namespace bx::gdk {
// ABI values checked against Microsoft's public PC GDK 2510.5.6322 (see xgameruntime.cpp).
constexpr HRESULT kRuntimeNotInitialized = static_cast<HRESULT>(0x89240100u);
constexpr HRESULT kRuntimeInvalidHandle = static_cast<HRESULT>(0x8924010cu);
constexpr HRESULT kIllegalMethodCall = static_cast<HRESULT>(0x8000000eu);
constexpr HRESULT kInsufficientBuffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
// Work for an XAsyncBlock, run on the block's work port. execute() is skipped, and the block
// completes with E_GAMERUNTIME_NOT_INITIALIZED (0x89240100), if the runtime was uninitialized
// after the operation started; an execute() that is already running finishes. A finished
// object, including its result data, is kept until its Result call consumes it, the same
// block starts another operation, or the last uninitialize. A caller that frees a block
// without calling Result leaves that result in memory until then; the retention is not
// bounded.
class AsyncOp {
public:
virtual ~AsyncOp() = default;
// Identifies the family/function, so a Result call can reject a foreign block.
virtual uint32_t kind() const = 0;
// Runs without the runtime lock held. Not called if the operation was canceled.
virtual HRESULT execute() = 0;
// Value reported by XAsyncGetResultSize after execute() succeeded.
virtual size_t result_size() const = 0;
};
// Starts op on block (an XAsyncBlock*). Returns the submission status, as XUserAddAsync does.
HRESULT begin_async_op(void* block, std::unique_ptr<AsyncOp> op);
// Checks that block holds a finished op of this kind, then calls consume while the runtime
// lock is held. The result is marked consumed only when consume succeeds, so a caller can
// retry with a larger buffer. consume must not call back into the runtime.
HRESULT consume_async_op(void* block, uint32_t kind, const std::function<HRESULT(AsyncOp&)>& consume);
// Zero while the runtime is not initialized; otherwise changes on every first initialize,
// so handles created before an uninitialize can be recognized as stale.
uint32_t active_runtime_generation();
bool is_valid_user(void* user);
// Full Windows path of the running executable.
HRESULT executable_path(wchar_t (&path)[MAX_PATH]);
// The executable's C:\bx_pls\<hash> directory (XPersistentLocalStorageGetPath), created if needed.
HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]);
// Creates path if missing. Fails if it exists and is not a plain directory.
HRESULT ensure_directory(const wchar_t* path);
// FNV-1a over UTF-16 code units, as used for the storage directory name.
uint64_t fnv1a(const wchar_t* text);
constexpr GUID kIUnknownIid = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
// COM IUnknown objects QueryApiImpl returns for the synthetic xgamesave and xpackage keys.
extern const void* const game_save_object; // game_save.cpp
extern const void* const package_object; // package.cpp
// Close every XGameSave / XPackage handle. Called by the last uninitialize, with the runtime
// lock held (the runtime lock is always taken before these files' own locks).
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
+92
View File
@@ -0,0 +1,92 @@
#pragma once
/*
* BetterXen synthetic QueryApiImpl keys: the single place to find or change them.
*
* 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. 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)
* tests/conformance/test_xgameruntime_saves/main.cpp (xgamesave, xpackage)
*
* Encoding: Data1 is the key below. Data2 = 0x5853 ("XS"), Data3 = 0x4000,
* Data4 = 80 00 00 00 00 00 00 01. For example, 0xB7581601 is
* {B7581601-5853-4000-8000-000000000001}.
*/
#include <windows.h>
#include <cstdint>
namespace bx::gdk::synthetic {
constexpr uint16_t kData2 = 0x5853;
constexpr uint16_t kData3 = 0x4000;
constexpr uint8_t kData4[8] = {0x80, 0, 0, 0, 0, 0, 0, 0x01};
constexpr GUID key(uint32_t data1) {
return {data1, kData2, kData3, {kData4[0], kData4[1], kData4[2], kData4[3],
kData4[4], kData4[5], kData4[6], kData4[7]}};
}
struct FamilyKey {
uint32_t clsid;
uint32_t iid;
};
// Plain function tables (#439). QueryApiImpl returns a pointer to a C struct of
// function pointers; the layouts are the *Dispatch structs in xgameruntime.cpp.
constexpr FamilyKey kTaskQueue{0xB7581001, 0xB7581002};
constexpr FamilyKey kAsync{0xB7581101, 0xB7581102};
constexpr FamilyKey kUser{0xB7581201, 0xB7581202};
constexpr FamilyKey kStore{0xB7581301, 0xB7581302};
constexpr FamilyKey kSystem{0xB7581401, 0xB7581402};
constexpr FamilyKey kPersistentLocalStorage{0xB7581501, 0xB7581502};
// COM IUnknown objects (#468). QueryApiImpl returns an object whose first member is a
// vtable pointer. Slots 0-2 are IUnknown; the remaining slots follow the enums below.
// Every slot takes the object pointer first, then the parameters of the Microsoft Learn
// function it names, in the documented order.
constexpr FamilyKey kGameSave{0xB7581601, 0xB7581602};
constexpr FamilyKey kPackage{0xB7581701, 0xB7581702};
enum class GameSaveSlot : uint32_t {
QueryInterface,
AddRef,
Release,
InitializeProviderAsync, // (XUserHandle, const char* scid, bool syncOnDemand, XAsyncBlock*)
InitializeProviderResult, // (XAsyncBlock*, XGameSaveProviderHandle*)
CloseProvider, // (XGameSaveProviderHandle)
CreateContainer, // (XGameSaveProviderHandle, const char* name, XGameSaveContainerHandle*)
CloseContainer, // (XGameSaveContainerHandle)
CreateUpdate, // (XGameSaveContainerHandle, const char* displayName, XGameSaveUpdateHandle*)
CloseUpdate, // (XGameSaveUpdateHandle)
SubmitBlobWrite, // (XGameSaveUpdateHandle, const char* blobName, const uint8_t*, size_t)
SubmitUpdateAsync, // (XGameSaveUpdateHandle, XAsyncBlock*)
SubmitUpdateResult, // (XAsyncBlock*)
ReadBlobDataAsync, // (XGameSaveContainerHandle, const char** names, uint32_t count, XAsyncBlock*)
ReadBlobDataResult, // (XAsyncBlock*, size_t, XGameSaveBlob*, uint32_t* count)
EnumerateContainerInfo, // (XGameSaveProviderHandle, void* context, XGameSaveContainerInfoCallback*)
Count,
};
enum class PackageSlot : uint32_t {
QueryInterface,
AddRef,
Release,
GetCurrentProcessPackageIdentifier, // (size_t bufferSize, char* buffer)
GetPackageKind, // (const char* packageIdentifier, XPackageKind*)
Mount, // (const char* packageIdentifier, XPackageMountHandle*)
GetMountPathSize, // (XPackageMountHandle, size_t*)
GetMountPath, // (XPackageMountHandle, size_t, char*)
CloseMountHandle, // (XPackageMountHandle)
Count,
};
} // namespace bx::gdk::synthetic
+444 -37
View File
@@ -1,9 +1,14 @@
#include "com_dispatch.h"
#include "runtime_internal.h"
#include "synthetic_keys.h"
#include "task_queue.h"
#include <condition_variable>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <map>
#include <mutex>
#include <new>
#include <unordered_set>
@@ -16,10 +21,10 @@ namespace {
using namespace bx::gdk;
// ABI values and layouts checked against Microsoft's public PC GDK 2510.5.6322.
constexpr HRESULT runtime_not_initialized = static_cast<HRESULT>(0x89240100u);
constexpr HRESULT runtime_invalid_handle = static_cast<HRESULT>(0x8924010cu);
constexpr HRESULT illegal_method_call = static_cast<HRESULT>(0x8000000eu);
constexpr HRESULT insufficient_buffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
constexpr HRESULT runtime_not_initialized = kRuntimeNotInitialized;
constexpr HRESULT runtime_invalid_handle = kRuntimeInvalidHandle;
constexpr HRESULT illegal_method_call = kIllegalMethodCall;
constexpr HRESULT insufficient_buffer = kInsufficientBuffer;
struct AsyncBlock {
void* queue;
@@ -54,7 +59,8 @@ struct SpaceInfo {
uint64_t total_bytes;
};
enum class Operation : uint32_t { add_user, game_license };
// custom: an AsyncOp from another translation unit (XGameSave), see runtime_internal.h.
enum class Operation : uint32_t { add_user, game_license, custom };
struct AsyncState {
const AsyncBlock* owner;
@@ -77,6 +83,8 @@ uint64_t next_operation = 1;
uintptr_t next_handle = 2;
std::unordered_set<void*> users;
std::unordered_set<void*> stores;
// Finished custom operations awaiting their Result call, keyed by AsyncState::sequence.
std::map<uint64_t, std::unique_ptr<AsyncOp>> finished_ops;
HRESULT create_handle(std::unordered_set<void*>& handles, void** out) {
auto handle = reinterpret_cast<void*>(next_handle);
@@ -157,10 +165,12 @@ class AsyncTask final : public Task {
public:
AsyncBlock* block;
Operation operation;
std::unique_ptr<AsyncOp> op;
std::unique_ptr<CompletionTask> completion;
bool queued = false;
AsyncTask(AsyncBlock* block, Operation operation) : block(block), operation(operation) {}
AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr<AsyncOp> op)
: block(block), operation(operation), op(std::move(op)) {}
~AsyncTask() override {
if (!queued) return;
@@ -183,11 +193,34 @@ public:
private:
void finish(const QueueRef& queue, bool canceled) {
const bool entitled = !canceled && operation == Operation::game_license && fixture_entitlement();
bool cancel_requested;
bool stale;
{
std::lock_guard lock(state_mutex);
const auto state = read_state(block);
cancel_requested = state.cancel_requested;
stale = !runtime_refs || state.runtime_generation != runtime_generation;
}
// The block stays E_PENDING meanwhile, so the caller cannot reuse it. Once an op has
// run, a later XAsyncCancel or uninitialize cannot undo it, so its own status is
// reported. An op whose runtime was uninitialized before it ran is not run.
const bool executed = op && !canceled && !cancel_requested && !stale;
const HRESULT op_status = executed ? op->execute() : S_OK;
{
std::lock_guard lock(state_mutex);
auto state = read_state(block);
state.status = (canceled || state.cancel_requested) ? E_ABORT : S_OK;
state.status = executed ? op_status
: canceled || state.cancel_requested ? E_ABORT
: op && stale ? runtime_not_initialized
: S_OK;
state.entitled = entitled;
if (op && SUCCEEDED(state.status) && state.runtime_generation == runtime_generation && runtime_refs) {
try {
finished_ops[state.sequence] = std::move(op);
} catch (const std::bad_alloc&) {
state.status = E_OUTOFMEMORY;
}
}
if (completion) completion->sequence = state.sequence;
queued = false;
write_state(block, state);
@@ -196,12 +229,12 @@ private:
}
};
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) {
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std::unique_ptr<AsyncOp> op = nullptr) {
if (!block) return E_POINTER;
const auto queue = acquire_queue(block->queue);
if (!queue) return block->queue ? E_HANDLE : E_OUTOFMEMORY;
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation));
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation, std::move(op)));
if (!work) return E_OUTOFMEMORY;
if (block->callback) {
work->completion.reset(new (std::nothrow) CompletionTask(block));
@@ -220,6 +253,8 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) {
callback_running(previous.sequence, GetCurrentThreadId()))) {
return illegal_method_call;
}
// An unconsumed result of an earlier operation on this block is abandoned.
if (previous.owner == block) finished_ops.erase(previous.sequence);
write_state(block, {block, next_operation++, E_PENDING, operation, runtime_generation,
false, block->callback != nullptr, false, false});
work->queued = true;
@@ -275,6 +310,173 @@ bool fixture_entitlement() {
GetProcAddress(GetModuleHandleW(nullptr), "BetterXenSyntheticStoreFixture") != nullptr;
}
HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
wchar_t module[MAX_PATH];
const wchar_t* name = nullptr;
const auto hr = executable_name(module, name);
if (FAILED(hr)) return hr;
// Hash the full Windows path so identically named workloads in separate
// directories get distinct storage within the same bottle.
wchar_t normalized[MAX_PATH];
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, module, -1,
normalized, MAX_PATH, nullptr, nullptr, 0)) {
return HRESULT_FROM_WIN32(GetLastError());
}
const uint64_t path_id = bx::gdk::fnv1a(normalized);
const auto length = std::swprintf(path, MAX_PATH, L"%ls\\%016llx", storage_root,
static_cast<unsigned long long>(path_id));
return length < 0 ? HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE) : S_OK;
}
HRESULT create_storage(const wchar_t* path) {
const auto hr = ensure_directory(storage_root);
return FAILED(hr) ? hr : ensure_directory(path);
}
// Caller holds state_mutex. Same transition XGameRuntimeUninitialize uses.
bool release_runtime_ref() {
if (!runtime_refs) return false;
if (!--runtime_refs) {
users.clear();
stores.clear();
finished_ops.clear();
bx::gdk::release_game_save_state();
bx::gdk::release_package_state();
}
return true;
}
bool runtime_active() {
std::lock_guard lock(state_mutex);
return runtime_refs != 0;
}
/*
* Loader export provenance, checked 2026-11-26.
*
* Public Microsoft Learn pages that were opened:
* XGameRuntimeInitialize, XGameRuntimeUninitialize, and
* XGameRuntimeInitializeWithOptions (header named there: XGameRuntimeInit.h),
* XGameRuntimeOptions { XGameRuntimeGameConfigSource gameConfigSource; const char* gameConfig },
* and XGameRuntimeGameConfigSource : uint32_t { Default, Inline, File }.
* Those pages also say the DLL init is ref-counted and that an XErrorReport is
* emitted when uninit fails with live objects. They do not give a prototype
* for XErrorReport. The XError member list names only XErrorCallback,
* XErrorSetCallback, and XErrorSetOptions. XErrorCallback is
* bool(HRESULT, const char*, void*).
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/functions/xgameruntimeinitialize
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/functions/xgameruntimeuninitialize
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/functions/xgameruntimeinitializewithoptions
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/structures/xgameruntimeoptions
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/enumerations/xgameruntimegameconfigsource
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xerror/xerror_members
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xerror/functions/xerrorcallback
*
* InitializeApiImpl, InitializeApiImplEx, InitializeApiImplEx2, QueryApiImpl,
* UninitializeApiImpl, and a callable XErrorReport prototype were not found
* on those pages, and https://github.com/microsoft/GDK/main/include/XGameRuntimeInit.h
* returned 404. Their names and parameter lists below are BetterXen-defined
* so a static loader can resolve the exports. ApiInitOptions is not the
* public XGameRuntimeOptions struct. RuntimeOptions above matches that
* public two-field layout. No Microsoft source was copied.
*/
struct ApiInitOptions {
uint32_t unknown;
uint8_t is_inline;
uint8_t pad[3];
const char* game_config;
};
static_assert(offsetof(ApiInitOptions, game_config) == 8);
// The synthetic key encoding is defined in synthetic_keys.h.
bool synthetic_guid(const GUID* guid) {
return guid->Data2 == synthetic::kData2 && guid->Data3 == synthetic::kData3 &&
std::memcmp(guid->Data4, synthetic::kData4, sizeof(synthetic::kData4)) == 0;
}
void format_guid(char* dst, size_t cap, const GUID* guid) {
std::snprintf(dst, cap, "%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
static_cast<unsigned long>(guid->Data1), static_cast<unsigned>(guid->Data2),
static_cast<unsigned>(guid->Data3), guid->Data4[0], guid->Data4[1], guid->Data4[2],
guid->Data4[3], guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
}
bool utf8_continuation(unsigned char c) { return (c & 0xC0) == 0x80; }
/* Byte length of one well-formed UTF-8 character at s, or 0 if s is not one. */
size_t utf8_len(const unsigned char* s) {
const unsigned char c = s[0];
size_t len = 0;
if (c < 0x80) return 1;
if (c >= 0xC2 && c <= 0xDF) len = 2;
else if (c == 0xE0 || (c >= 0xE1 && c <= 0xEC) || c == 0xED || (c >= 0xEE && c <= 0xEF)) len = 3;
else if (c == 0xF0 || (c >= 0xF1 && c <= 0xF3) || c == 0xF4) len = 4;
else return 0;
for (size_t i = 1; i < len; ++i) {
if (s[i] == 0 || !utf8_continuation(s[i])) return 0;
}
if (c == 0xE0 && s[1] < 0xA0) return 0;
if (c == 0xED && s[1] > 0x9F) return 0;
if (c == 0xF0 && s[1] < 0x90) return 0;
if (c == 0xF4 && s[1] > 0x8F) return 0;
return len;
}
/*
* Append src as JSON string content and valid UTF-8.
* A quote or backslash is escaped. Bytes below 0x20 and an invalid UTF-8
* byte are written as \u00XX, which stays ASCII. A character that does not
* fit is left out, so a multi-byte sequence is never split.
*/
void append_escaped(char* dst, size_t cap, size_t* used, const char* src) {
size_t u = *used;
if (!src) src = "(null)";
const auto* p = reinterpret_cast<const unsigned char*>(src);
while (*p) {
auto fits = [&](size_t n) { return u + n < cap; };
const unsigned char c = *p;
if (c < 0x20 || c == 0x7F) {
if (!fits(6)) break;
u += static_cast<size_t>(std::snprintf(dst + u, cap - u, "\\u%04X", c));
++p;
continue;
}
if (c == '"' || c == '\\') {
if (!fits(2)) break;
dst[u++] = '\\';
dst[u++] = static_cast<char>(c);
++p;
continue;
}
const size_t len = c < 0x80 ? 1 : utf8_len(p);
if (len == 0) {
if (!fits(6)) break;
u += static_cast<size_t>(std::snprintf(dst + u, cap - u, "\\u%04X", c));
++p;
continue;
}
if (!fits(len)) break;
std::memcpy(dst + u, p, len);
u += len;
p += len;
}
if (u < cap) dst[u] = '\0';
else if (cap) dst[cap - 1] = '\0';
*used = u < cap ? u : cap - 1;
}
HRESULT check_loader_versions(uint32_t gdk_ver, uint32_t gs_ver, const char* event) {
if (gdk_ver == 0 || gs_ver == 0) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", event, "invalid_args");
return E_INVALIDARG;
}
return S_OK;
}
} // namespace
namespace bx::gdk {
HRESULT ensure_directory(const wchar_t* path) {
if (CreateDirectoryW(path, nullptr)) return S_OK;
const auto error = GetLastError();
@@ -288,34 +490,59 @@ HRESULT ensure_directory(const wchar_t* path) {
return S_OK;
}
HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
wchar_t module[MAX_PATH];
uint64_t fnv1a(const wchar_t* text) {
uint64_t hash = 14695981039346656037ULL;
for (auto* ch = text; *ch; ++ch) {
hash ^= static_cast<uint16_t>(*ch);
hash *= 1099511628211ULL;
}
return hash;
}
HRESULT executable_path(wchar_t (&path)[MAX_PATH]) {
const wchar_t* name = nullptr;
const auto hr = executable_name(module, name);
return executable_name(path, name);
}
HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]) {
const auto hr = storage_path(path);
return FAILED(hr) ? hr : create_storage(path);
}
uint32_t active_runtime_generation() {
std::lock_guard lock(state_mutex);
return runtime_refs ? runtime_generation : 0;
}
bool is_valid_user(void* user) {
std::lock_guard lock(state_mutex);
return runtime_refs && users.contains(user);
}
HRESULT begin_async_op(void* block, std::unique_ptr<AsyncOp> op) {
if (!op) return E_OUTOFMEMORY;
return begin(static_cast<AsyncBlock*>(block), Operation::custom, nullptr, std::move(op));
}
HRESULT consume_async_op(void* block, uint32_t kind, const std::function<HRESULT(AsyncOp&)>& consume) {
auto* async = static_cast<AsyncBlock*>(block);
std::lock_guard lock(state_mutex);
AsyncState state{};
const auto hr = check_result(async, Operation::custom, state);
if (FAILED(hr)) return hr;
// Hash the full Windows path so identically named workloads in separate
// directories get distinct storage within the same bottle.
wchar_t normalized[MAX_PATH];
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, module, -1,
normalized, MAX_PATH, nullptr, nullptr, 0)) {
return HRESULT_FROM_WIN32(GetLastError());
const auto found = finished_ops.find(state.sequence);
if (found == finished_ops.end() || found->second->kind() != kind) return illegal_method_call;
const auto result = consume(*found->second);
if (SUCCEEDED(result)) {
finished_ops.erase(found);
state.result_consumed = true;
write_state(async, state);
}
uint64_t path_id = 14695981039346656037ULL;
for (auto* ch = normalized; *ch; ++ch) {
path_id ^= static_cast<uint16_t>(*ch);
path_id *= 1099511628211ULL;
}
const auto length = std::swprintf(path, MAX_PATH, L"%ls\\%016llx", storage_root,
static_cast<unsigned long long>(path_id));
return length < 0 ? HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE) : S_OK;
return result;
}
HRESULT create_storage(const wchar_t* path) {
const auto hr = ensure_directory(storage_root);
return FAILED(hr) ? hr : ensure_directory(path);
}
} // namespace
} // namespace bx::gdk
extern "C" {
@@ -339,10 +566,7 @@ HRESULT WINAPI XGameRuntimeInitializeWithOptions(const RuntimeOptions* options)
void WINAPI XGameRuntimeUninitialize() {
std::lock_guard lock(state_mutex);
if (runtime_refs && !--runtime_refs) {
users.clear();
stores.clear();
}
release_runtime_ref();
}
HRESULT WINAPI XAsyncGetStatus(AsyncBlock* block, bool wait) {
@@ -374,7 +598,16 @@ HRESULT WINAPI XAsyncGetResultSize(AsyncBlock* block, size_t* size) {
const auto state = read_state(block);
if (state.owner != block || state.result_consumed) return illegal_method_call;
if (SUCCEEDED(state.status)) {
*size = state.operation == Operation::add_user ? sizeof(void*) : sizeof(GameLicense);
switch (state.operation) {
case Operation::add_user: *size = sizeof(void*); break;
case Operation::game_license: *size = sizeof(GameLicense); break;
case Operation::custom: {
const auto found = finished_ops.find(state.sequence);
if (found == finished_ops.end()) return illegal_method_call;
*size = found->second->result_size();
break;
}
}
}
return state.status;
}
@@ -561,4 +794,178 @@ OFFLINE_STUB(XNetworkingQuerySecurityInformationForUrlAsync, (const char*, Async
#undef OFFLINE_STUB
HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, void**);
void WINAPI XTaskQueueCloseHandle(void*);
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
HRESULT WINAPI InitializeApiImpl(uint32_t gdk_ver, uint32_t gs_ver) {
const auto hr = check_loader_versions(gdk_ver, gs_ver, "InitializeApiImpl");
return FAILED(hr) ? hr : XGameRuntimeInitialize();
}
HRESULT WINAPI InitializeApiImplEx(uint32_t gdk_ver, uint32_t gs_ver, char /*mode*/) {
const auto hr = check_loader_versions(gdk_ver, gs_ver, "InitializeApiImplEx");
return FAILED(hr) ? hr : XGameRuntimeInitialize();
}
HRESULT WINAPI InitializeApiImplEx2(uint32_t gdk_ver, uint32_t gs_ver, char /*mode*/, const ApiInitOptions* options) {
const auto hr = check_loader_versions(gdk_ver, gs_ver, "InitializeApiImplEx2");
if (FAILED(hr)) return hr;
if (options && options->is_inline && !options->game_config) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "InitializeApiImplEx2", "invalid_args");
return E_INVALIDARG;
}
// Custom game config is the same unimplemented path as XGameRuntimeInitializeWithOptions.
if (options && (options->is_inline || options->game_config)) {
BX_STUB_LOG("xgameruntime.dll", "InitializeApiImplEx2");
return E_NOTIMPL;
}
return XGameRuntimeInitialize();
}
HRESULT WINAPI UninitializeApiImpl() {
bool released;
{
std::lock_guard lock(state_mutex);
released = release_runtime_ref();
}
if (!released) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "UninitializeApiImpl", "not_initialized");
return runtime_not_initialized;
}
return S_OK;
}
void WINAPI XErrorReport(HRESULT hr, const char* message) {
char detail[480];
const auto prefix = std::snprintf(detail, sizeof(detail), "hr=0x%08lX msg=",
static_cast<unsigned long>(static_cast<uint32_t>(hr)));
size_t used = prefix > 0 ? static_cast<size_t>(prefix) : 0;
if (used >= sizeof(detail)) used = sizeof(detail) - 1;
append_escaped(detail, sizeof(detail), &used, message);
bx_log_emit(BX_LOG_ERROR, "xgameruntime", "XErrorReport", detail);
}
struct TaskQueueDispatch {
decltype(&XTaskQueueCreate) create;
decltype(&XTaskQueueCloseHandle) close_handle;
decltype(&XTaskQueueDispatch) dispatch;
decltype(&XTaskQueueSubmitCallback) submit;
decltype(&XTaskQueueGetCurrentProcessTaskQueue) current;
};
struct AsyncDispatch {
decltype(&XAsyncGetStatus) get_status;
decltype(&XAsyncGetResultSize) get_result_size;
decltype(&XAsyncCancel) cancel;
};
struct UserDispatch {
decltype(&XUserAddAsync) add_async;
decltype(&XUserAddResult) add_result;
decltype(&XUserGetId) get_id;
decltype(&XUserGetGamertag) get_gamertag;
};
struct StoreDispatch {
decltype(&XStoreCreateContext) create_context;
decltype(&XStoreQueryGameLicenseAsync) query_license_async;
decltype(&XStoreQueryGameLicenseResult) query_license_result;
};
struct SystemDispatch {
decltype(&XSystemGetDeviceType) get_device_type;
decltype(&XSystemGetConsoleId) get_console_id;
decltype(&XSystemGetXboxLiveSandboxId) get_sandbox_id;
};
struct StorageDispatch {
decltype(&XPersistentLocalStorageGetPathSize) get_path_size;
decltype(&XPersistentLocalStorageGetPath) get_path;
decltype(&XPersistentLocalStorageGetSpaceInfo) get_space_info;
};
const TaskQueueDispatch task_queue_api{&XTaskQueueCreate, &XTaskQueueCloseHandle, &XTaskQueueDispatch,
&XTaskQueueSubmitCallback, &XTaskQueueGetCurrentProcessTaskQueue};
const AsyncDispatch async_api{&XAsyncGetStatus, &XAsyncGetResultSize, &XAsyncCancel};
const UserDispatch user_api{&XUserAddAsync, &XUserAddResult, &XUserGetId, &XUserGetGamertag};
const StoreDispatch store_api{&XStoreCreateContext, &XStoreQueryGameLicenseAsync, &XStoreQueryGameLicenseResult};
const SystemDispatch system_api{&XSystemGetDeviceType, &XSystemGetConsoleId, &XSystemGetXboxLiveSandboxId};
const StorageDispatch storage_api{&XPersistentLocalStorageGetPathSize, &XPersistentLocalStorageGetPath,
&XPersistentLocalStorageGetSpaceInfo};
struct Family {
uint32_t clsid;
uint32_t iid;
const char* name;
const void* table;
bool com; // table is a COM object, so IID_IUnknown also reaches it
};
// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs. All keys and the COM slot
// orders live in synthetic_keys.h.
const Family families[] = {
{synthetic::kTaskQueue.clsid, synthetic::kTaskQueue.iid, "xtaskqueue", &task_queue_api, false},
{synthetic::kAsync.clsid, synthetic::kAsync.iid, "xasync", &async_api, false},
{synthetic::kUser.clsid, synthetic::kUser.iid, "xuser", &user_api, false},
{synthetic::kStore.clsid, synthetic::kStore.iid, "xstore", &store_api, false},
{synthetic::kSystem.clsid, synthetic::kSystem.iid, "xsystem", &system_api, false},
{synthetic::kPersistentLocalStorage.clsid, synthetic::kPersistentLocalStorage.iid, "xpersistentlocalstorage",
&storage_api, false},
{synthetic::kGameSave.clsid, synthetic::kGameSave.iid, "xgamesave", bx::gdk::game_save_object, true},
{synthetic::kPackage.clsid, synthetic::kPackage.iid, "xpackage", bx::gdk::package_object, true},
};
const Family* find_family(const GUID* clsid) {
if (!synthetic_guid(clsid)) return nullptr;
for (const auto& family : families) {
if (clsid->Data1 == family.clsid) return &family;
}
return nullptr;
}
HRESULT WINAPI QueryApiImpl(const GUID* clsid, const GUID* iid, void** out) {
if (!out) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", "invalid_args");
return E_POINTER;
}
*out = nullptr;
if (!clsid || !iid) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", "invalid_args");
return E_INVALIDARG;
}
if (!runtime_active()) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", "not_initialized");
return runtime_not_initialized;
}
bool public_clsid_known = false;
if (bx::gdk::query_public_gdk_interface(clsid, iid, out, &public_clsid_known)) {
return S_OK;
}
const auto* family = find_family(clsid);
if (family && ((synthetic_guid(iid) && iid->Data1 == family->iid) ||
(family->com && IsEqualGUID(*iid, bx::gdk::kIUnknownIid)))) {
*out = const_cast<void*>(family->table);
char detail[64];
std::snprintf(detail, sizeof(detail), "dispatch family=%s", family->name);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "QueryApiImpl", detail);
return S_OK;
}
char clsid_text[48], iid_text[48], detail[192], symbol[160];
format_guid(clsid_text, sizeof(clsid_text), clsid);
format_guid(iid_text, sizeof(iid_text), iid);
std::snprintf(symbol, sizeof(symbol), "QueryApiImpl(%s/%s)", clsid_text, iid_text);
if (family) {
std::snprintf(detail, sizeof(detail), "iid_mismatch family=%s clsid=%s iid=%s", family->name, clsid_text,
iid_text);
} else if (public_clsid_known) {
std::snprintf(detail, sizeof(detail), "public_iid_mismatch clsid=%s iid=%s", clsid_text, iid_text);
} else {
std::snprintf(detail, sizeof(detail), "unsupported clsid=%s iid=%s", clsid_text, iid_text);
}
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", detail);
BX_STUB_LOG("xgameruntime.dll", symbol);
return E_NOINTERFACE;
}
} // extern "C"
+1
View File
@@ -1,4 +1,5 @@
bx_add_shim_dll(xmem xmem xmem.def
xmem.cpp
physical_pages.cpp
)
target_link_libraries(xmem PRIVATE bx_runtime_veh kernel32)
+385
View File
@@ -0,0 +1,385 @@
#include <windows.h>
#include <cstdint>
#include <limits>
#include <new>
#include "bx_log.h"
#include "bx_xmem_internal.h"
#include "xmem_accounting.h"
namespace {
constexpr SIZE_T small_page = 64 * 1024;
constexpr SIZE_T large_page = 2 * 1024 * 1024;
struct PageBlock;
struct Page {
PageBlock* block;
HANDLE section;
bool releasing;
};
struct PageBlock {
ULONG_PTR first_tag;
SIZE_T count;
SIZE_T size;
SIZE_T live;
Page* entries;
PageBlock* next;
};
struct View {
Page* page;
BYTE* address;
View* next;
};
SRWLOCK memory_lock = SRWLOCK_INIT;
PageBlock* blocks = nullptr;
View* views = nullptr;
ULONG_PTR next_tag = 1;
struct Lock {
Lock() { AcquireSRWLockExclusive(&memory_lock); }
~Lock() { ReleaseSRWLockExclusive(&memory_lock); }
};
using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
MEM_EXTENDED_PARAMETER*, ULONG);
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
struct PlaceholderApi {
HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
ReservePlaceholder reserve = resolve<ReservePlaceholder>("VirtualAlloc2");
ReplacePlaceholder replace = resolve<ReplacePlaceholder>("MapViewOfFile3");
template<class Function>
Function resolve(const char* name) const {
return reinterpret_cast<Function>(reinterpret_cast<void*>(GetProcAddress(kernel, name)));
}
};
// The public backlog defines the supported sizes. The flags accepted here
// belong to BetterXen's synthetic fixtures, pending a public console flags ABI.
SIZE_T page_size(uint64_t flags) {
switch (flags) {
case 0:
case small_page: return small_page;
case large_page: return large_page;
default: return 0;
}
}
Page* find_page(ULONG_PTR tag) {
for (PageBlock* block = blocks; block; block = block->next) {
if (tag >= block->first_tag && tag - block->first_tag < block->count) {
Page* page = &block->entries[tag - block->first_tag];
return page->section ? page : nullptr;
}
}
return nullptr;
}
ULONG_PTR page_tag(const Page* page) {
return page->block->first_tag + (page - page->block->entries);
}
void delete_block(PageBlock* block) {
for (SIZE_T i = 0; i < block->count; ++i) {
if (block->entries[i].section) CloseHandle(block->entries[i].section);
}
delete[] block->entries;
delete block;
}
void destroy_views(View* first) {
while (first) {
View* next = first->next;
delete first;
first = next;
}
}
bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
const auto address = reinterpret_cast<uintptr_t>(base);
return size && count && address % size == 0
&& count <= (std::numeric_limits<uintptr_t>::max() - address) / size;
}
bool remove_view(View** link) {
View* view = *link;
if (!UnmapViewOfFile(view->address)) return false;
*link = view->next;
delete view;
return true;
}
// Require every page slot in [base, base + count * size) to be actively mapped
// with matching page size before unmapping; empty or partial spans fail without
// modifying any existing views.
PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
if (!base) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
const auto begin = reinterpret_cast<uintptr_t>(base);
const auto end = begin + count * size;
SIZE_T matched = 0;
for (const View* view = views; view; view = view->next) {
const auto address = reinterpret_cast<uintptr_t>(view->address);
if (address >= begin && address < end && view->page->block->size == size) {
++matched;
}
}
if (matched != count) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
for (View** link = &views; *link;) {
View* view = *link;
const auto address = reinterpret_cast<uintptr_t>(view->address);
if (address >= begin && address < end && view->page->block->size == size) {
if (!remove_view(link)) return nullptr;
} else {
link = &view->next;
}
}
return base;
}
// Duplicate tags in `tags` are intentionally permitted so a single virtual span
// can alias one physical page at multiple offsets (e.g. ring buffers / tiles).
PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* tags) {
const SIZE_T size = page_size(flags);
if (!valid_span(address, count, size)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
Lock lock;
if (!tags) return unmap_span(static_cast<BYTE*>(address), count, size);
static const PlaceholderApi api;
if (!api.reserve || !api.replace) {
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return nullptr;
}
View* pending = nullptr;
for (SIZE_T i = count; i > 0; --i) {
Page* page = find_page(tags[i - 1]);
if (!page || page->block->size != size) {
destroy_views(pending);
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
auto* view = new (std::nothrow) View{page, nullptr, pending};
if (!view) {
destroy_views(pending);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
pending = view;
}
MEM_ADDRESS_REQUIREMENTS requirements{};
requirements.Alignment = size;
MEM_EXTENDED_PARAMETER alignment{};
alignment.Type = MemExtendedParameterAddressRequirements;
alignment.Pointer = &requirements;
auto* base = static_cast<BYTE*>(api.reserve(nullptr, address, count * size,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
address ? nullptr : &alignment, address ? 0 : 1));
if (!base) {
const DWORD error = GetLastError();
destroy_views(pending);
SetLastError(error);
return nullptr;
}
BYTE* cursor = base;
SIZE_T remaining = count;
View* view = pending;
for (; view; view = view->next, cursor += size, --remaining) {
const bool split = remaining > 1;
if (split && !VirtualFree(cursor, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
if (!api.replace(view->page->section, nullptr, cursor, 0, size,
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
const DWORD error = GetLastError();
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
SetLastError(error);
break;
}
view->address = cursor;
}
if (view) {
const DWORD error = GetLastError();
VirtualFree(cursor, 0, MEM_RELEASE);
for (View* completed = pending; completed != view; completed = completed->next) {
UnmapViewOfFile(completed->address);
}
destroy_views(pending);
SetLastError(error);
return nullptr;
}
while (pending) {
View* next = pending->next;
pending->next = views;
views = pending;
pending = next;
}
return base;
}
} // namespace
// Clean-room synthetic signatures modeled after public Win32 AWE
// AllocateUserPhysicalPages / FreeUserPhysicalPages (memoryapi.h, [in, out]
// page count pointer), pending a public console flags/signature ABI.
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
uint64_t flags) {
const SIZE_T size = page_size(flags);
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
Lock lock;
const SIZE_T count = *num_pages;
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|| count > std::numeric_limits<uint64_t>::max() / size) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
const uint64_t total_bytes = static_cast<uint64_t>(count) * size;
if (!bx_xmem::try_reserve_physical(total_bytes)) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
auto* entries = new (std::nothrow) Page[count]{};
if (!entries) {
bx_xmem::release_physical(total_bytes);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, entries, blocks};
if (!block) {
delete[] entries;
bx_xmem::release_physical(total_bytes);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
for (SIZE_T i = 0; i < count; ++i) {
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
0, static_cast<DWORD>(size), nullptr);
if (!section) {
const DWORD error = GetLastError();
delete_block(block);
bx_xmem::release_physical(total_bytes);
SetLastError(error);
return FALSE;
}
entries[i] = {block, section, false};
}
blocks = block;
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
next_tag += count;
return TRUE;
}
// Rejects unknown, wrong-size, or duplicate tags in `page_array` with
// ERROR_INVALID_PARAMETER without mutating `page_array` or live views.
extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
uint64_t flags) {
const SIZE_T size = page_size(flags);
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
Lock lock;
const SIZE_T count = *num_pages;
SIZE_T validated = 0;
for (; validated < count; ++validated) {
Page* page = find_page(page_array[validated]);
if (!page || page->block->size != size || page->releasing) break;
page->releasing = true;
}
if (validated != count) {
for (SIZE_T i = 0; i < validated; ++i) find_page(page_array[i])->releasing = false;
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
for (View** link = &views; *link;) {
if ((*link)->page->releasing) {
if (!remove_view(link)) {
const DWORD error = GetLastError();
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
SetLastError(error);
return FALSE;
}
} else {
link = &(*link)->next;
}
}
for (SIZE_T i = 0; i < count; ++i) {
Page* page = find_page(page_array[i]);
CloseHandle(page->section);
page->section = nullptr;
--page->block->live;
page_array[i] = 0;
}
for (PageBlock** link = &blocks; *link;) {
PageBlock* block = *link;
if (block->live) {
link = &block->next;
} else {
*link = block->next;
delete_block(block);
}
}
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
return TRUE;
}
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags,
PULONG_PTR page_array) {
return map_pages(base, count, flags, page_array);
}
extern "C" PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID base, SIZE_T count, uint64_t flags,
PULONG_PTR page_array) {
return map_pages(base, count, flags, page_array);
}
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
if (!out_info) return 0;
Lock lock;
for (const View* view = views; view; view = view->next) {
const auto base = reinterpret_cast<uintptr_t>(view->address);
const SIZE_T size = view->page->block->size;
if (va >= base && va - base < size) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(view->address, &region, sizeof(region))
|| region.AllocationBase != view->address || region.Type != MEM_MAPPED) {
return 0;
}
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page)};
return 1;
}
}
return 0;
}
+273 -62
View File
@@ -1,30 +1,132 @@
#include <windows.h>
#include <atomic>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <mutex>
#include <utility>
#include "bx_config.h"
#include "bx_log.h"
#include "bx_xmem_internal.h"
/*
* Track B (M1-B1 / M1-B2): Starter implementation of xmem.dll.
* Provides working default heap & virtual allocations so dependent DLLs can link
* and load immediately; Track B issues expand physical/scatter page mapping,
* __XMemAllocationHooks__ dispatch, and Lockhart working-set enforcement.
*/
#include "xmem_accounting.h"
namespace {
std::atomic<uint64_t> g_committed_virtual{0};
std::atomic<uint64_t> g_allocated_physical{0};
std::atomic<uint64_t> g_peak_committed{0};
constexpr SIZE_T heap_alignment = 64;
void record_alloc(uint64_t bytes) {
uint64_t cur = g_committed_virtual.fetch_add(bytes) + bytes;
uint64_t peak = g_peak_committed.load();
while (cur > peak && !g_peak_committed.compare_exchange_weak(peak, cur)) {}
struct VirtualCommit {
uintptr_t begin;
uintptr_t end;
PVOID allocation_base;
};
// The shim build disables exceptions. Grow the table before committing pages
// so a bookkeeping allocation failure leaves the Win32 allocation untouched.
struct CommitTable {
VirtualCommit* entries = nullptr;
size_t count = 0;
size_t capacity = 0;
CommitTable() = default;
CommitTable(const CommitTable&) = delete;
CommitTable& operator=(const CommitTable&) = delete;
~CommitTable() { std::free(entries); }
VirtualCommit* begin() const { return entries; }
VirtualCommit* end() const { return count ? entries + count : entries; }
bool append(VirtualCommit commit) {
if (count == capacity) {
const size_t max_entries = std::numeric_limits<size_t>::max() / sizeof(commit);
if (capacity > max_entries / 2) return false;
const size_t next_capacity = capacity ? capacity * 2 : 8;
auto* next = static_cast<VirtualCommit*>(
std::realloc(entries, next_capacity * sizeof(commit)));
if (!next) return false;
entries = next;
capacity = next_capacity;
}
entries[count++] = commit;
return true;
}
void swap(CommitTable& other) {
std::swap(entries, other.entries);
std::swap(count, other.count);
std::swap(capacity, other.capacity);
}
};
std::mutex usage_lock;
CommitTable virtual_commits;
uint64_t heap_bytes = 0;
uint64_t virtual_bytes = 0;
uint64_t physical_bytes = 0;
uint64_t peak_bytes = 0;
uint64_t title_limit() {
const auto* config = bx_get_runtime_config();
return config ? config->title_memory_limit_bytes : (8ULL << 30);
}
bool can_commit(uint64_t bytes) {
const uint64_t limit = title_limit();
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;
return used <= limit && bytes <= limit - used;
}
void update_peak() {
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
}
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
return reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
// The export table has no XMemVirtualFree. Reconcile tracked ranges with
// Win32 when the guest releases or decommits pages using VirtualFree.
bool refresh_virtual_commits() {
CommitTable live;
uint64_t bytes = 0;
for (const auto& commit : virtual_commits) {
uintptr_t cursor = commit.begin;
while (cursor < commit.end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<PVOID>(cursor), &region, sizeof(region))) {
break;
}
const uintptr_t end = std::min(commit.end, region_end(region));
if (end <= cursor) break;
if (region.State == MEM_COMMIT && region.AllocationBase == commit.allocation_base) {
if (!live.append({cursor, end, commit.allocation_base})) return false;
bytes += end - cursor;
}
cursor = end;
}
}
virtual_commits.swap(live);
virtual_bytes = bytes;
return true;
}
void report_unsupported_host_hooks() {
static const bool reported = [] {
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
}
return true;
}();
(void)reported;
}
SIZE_T page_size() {
static const SIZE_T size = [] {
SYSTEM_INFO info{};
GetSystemInfo(&info);
return info.dwPageSize;
}();
return size;
}
} // namespace
@@ -32,20 +134,46 @@ extern "C" {
PVOID WINAPI XMemAllocDefault(SIZE_T size, uint64_t /*attributes*/) {
if (size == 0) size = 16;
void* p = _aligned_malloc(size, 64);
if (p) record_alloc(size);
return p;
if (size > std::numeric_limits<SIZE_T>::max() - heap_alignment) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
std::lock_guard guard(usage_lock);
if (!can_commit(size) && (!refresh_virtual_commits() || !can_commit(size))) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
auto* allocation = static_cast<unsigned char*>(_aligned_malloc(size + heap_alignment, heap_alignment));
if (!allocation) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
std::memcpy(allocation, &size, sizeof(size));
heap_bytes += size;
update_peak();
return allocation + heap_alignment;
}
VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
if (address) _aligned_free(address);
if (!address) return;
auto* allocation = static_cast<unsigned char*>(address) - heap_alignment;
SIZE_T size;
std::memcpy(&size, allocation, sizeof(size));
std::lock_guard guard(usage_lock);
_aligned_free(allocation);
heap_bytes -= size;
}
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
report_unsupported_host_hooks();
return XMemAllocDefault(size, attributes);
}
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
report_unsupported_host_hooks();
XMemFreeDefault(address, attributes);
}
@@ -53,51 +181,118 @@ PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWOR
/* Strip console-only high bits before forwarding to standard Win32 VirtualAlloc. */
DWORD win_alloc = alloc_type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN);
if (win_alloc == 0) win_alloc = MEM_COMMIT | MEM_RESERVE;
DWORD win_prot = protect & 0xFFu;
if (win_prot == 0) win_prot = PAGE_READWRITE;
void* p = VirtualAlloc(address, size, win_alloc, win_prot);
if (p && (win_alloc & MEM_COMMIT)) record_alloc(size);
return p;
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
DWORD low_prot = protect & 0xFFu;
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
: PAGE_READWRITE;
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
* early here cannot commit pages outside the working-set budget. */
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
return VirtualAlloc(address, size, win_alloc, win_prot);
}
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
const SIZE_T page = page_size();
// Explicit reservations round down to allocation granularity.
SIZE_T alignment = page;
if (win_alloc & MEM_RESERVE) {
SYSTEM_INFO info{};
GetSystemInfo(&info);
alignment = info.dwAllocationGranularity;
}
const uintptr_t begin = requested - requested % alignment;
constexpr uintptr_t max_address = std::numeric_limits<uintptr_t>::max();
if (!size || requested > max_address - (page - 1)
|| size > max_address - requested - (page - 1)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
const uintptr_t end = (requested + size + page - 1) & ~(page - 1);
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
CommitTable next;
for (const auto& commit : virtual_commits) {
if (!next.append(commit)) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
}
uint64_t charge = end - begin;
uintptr_t cursor = begin;
if (address && !(win_alloc & MEM_RESERVE)) {
for (const auto& commit : virtual_commits) {
if (commit.end <= cursor) continue;
if (commit.begin >= end) break;
if (cursor < commit.begin && !next.append({cursor, commit.begin, nullptr})) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
const uintptr_t overlap_end = std::min(end, commit.end);
charge -= overlap_end - std::max(cursor, commit.begin);
cursor = overlap_end;
}
}
if ((cursor < end && !next.append({cursor, end, nullptr})) || !can_commit(charge)) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
PVOID allocation = VirtualAlloc(address, size, win_alloc, win_prot);
if (!allocation || next.count == virtual_commits.count) return allocation;
MEMORY_BASIC_INFORMATION region{};
// A successful commit establishes a region containing the returned address.
VirtualQuery(allocation, &region, sizeof(region));
const uintptr_t relocation = address ? 0 : reinterpret_cast<uintptr_t>(allocation);
for (size_t i = virtual_commits.count; i < next.count; ++i) {
next.entries[i].begin += relocation;
next.entries[i].end += relocation;
next.entries[i].allocation_base = region.AllocationBase;
}
std::sort(next.begin(), next.end(), [](const auto& lhs, const auto& rhs) {
return lhs.begin < rhs.begin;
});
virtual_commits.swap(next);
virtual_bytes += charge;
update_peak();
return allocation;
}
SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len) {
return VirtualQuery(address, buf, len);
}
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
BX_STUB_LOG("xmem.dll", "XMemAllocatePhysicalPages");
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return FALSE;
}
BOOL WINAPI XMemFreePhysicalPages(SIZE_T /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
BX_STUB_LOG("xmem.dll", "XMemFreePhysicalPages");
return TRUE;
}
PVOID WINAPI XMemMapPhysicalPages(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPages");
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return nullptr;
}
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPagesScatter");
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return nullptr;
}
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*flags*/) {
if (!dst || !src) return FALSE;
std::memcpy(dst, src, bytes);
if (bytes == 0) return TRUE;
if (!dst || !src) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::memmove(dst, src, bytes);
return TRUE;
}
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
BX_STUB_LOG("xmem.dll", "XMemGetWorkingSetStatistics");
if (out_stats && stats_size > 0) {
std::memset(out_stats, 0, stats_size);
if (!out_stats || stats_size < sizeof(bx_xmem_stats_t)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
std::memset(out_stats, 0, stats_size);
std::memcpy(out_stats, &stats, sizeof(stats));
return TRUE;
}
@@ -105,17 +300,33 @@ BOOL WINAPI XMemIsToolsMemAvailable(void) {
return FALSE;
}
int bx_xmem_query_region(uint64_t /*va*/, bx_xmem_region_info_t* /*out_info*/) {
return 0;
}
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
if (!out_stats) return;
const bx_runtime_config_t* cfg = bx_get_runtime_config();
out_stats->title_limit_bytes = cfg ? cfg->title_memory_limit_bytes : (8ULL << 30);
out_stats->committed_virtual_bytes = g_committed_virtual.load();
out_stats->allocated_physical_bytes = g_allocated_physical.load();
out_stats->peak_committed_bytes = g_peak_committed.load();
if (!XMemGetWorkingSetStatistics(out_stats, sizeof(*out_stats))) {
// The internal ABI has no error return. Preserve the most recent
// accounting snapshot if refreshing it runs out of bookkeeping memory.
std::lock_guard guard(usage_lock);
*out_stats = {title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
}
}
} // extern "C"
namespace bx_xmem {
bool try_reserve_physical(uint64_t bytes) {
std::lock_guard guard(usage_lock);
if (!can_commit(bytes) && (!refresh_virtual_commits() || !can_commit(bytes))) {
return false;
}
physical_bytes += bytes;
update_peak();
return true;
}
void release_physical(uint64_t bytes) {
std::lock_guard guard(usage_lock);
physical_bytes = physical_bytes >= bytes ? physical_bytes - bytes : 0;
}
} // namespace bx_xmem
+15
View File
@@ -0,0 +1,15 @@
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
#include <cstdint>
namespace bx_xmem {
// Reserve or release physical-page bytes against the shared xmem title memory
// cap and working-set statistics (heap + virtual + physical <= title limit).
bool try_reserve_physical(uint64_t bytes);
void release_physical(uint64_t bytes);
} // namespace bx_xmem
#endif // BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
@@ -0,0 +1,16 @@
# #437: which module serves the six API-set import names under CrossOver?
#
# Links statically (PE import directory, not LoadLibrary) against the import
# library of each win32_bridge shim. The ntuser forwarder libraries come first so
# the ntuser exports bind to the shim import libraries instead of user32's.
add_executable(test_apiset_resolution main.cpp)
target_link_libraries(test_apiset_resolution PRIVATE
ntuser_win_ansi_1_0
ntuser_win_1_0
ntuser_msg_ansi_1_0
ntuser_msg_1_0
psm_appnotify_1_0
psm_appnotify_1_1
user32
kernel32
)
@@ -0,0 +1,240 @@
/*
* #437: API-set import resolution fixture.
*
* Statically imports one export from each of the six win32_bridge shim DLLs
* (api-ms-win-core-psm-appnotify-l1-1-{0,1}, ext-ms-win-rtcore-ntuser-*) and
* reports, per name, which module actually served it:
*
* shim - the BetterXen file of that name next to this EXE is the loaded module.
* host - a module that is not that file answers the name (for example Wine's
* own API-set handling).
* absent - no module is loaded under that name.
*
* `bound_to` is the module that owns the address the loader wrote into the first
* import address table slot for that name, which is the module that serves a call
* made through the static import. The check is made through the PE import directory, not LoadLibrary,
* which is how real titles reach these names (see #437).
*
* Usage: test_apiset_resolution [--expect host|shim]
* --expect host (default): pass when all six names are served by the host.
* --expect shim: pass when all six names are served by BetterXen shim files.
* Exit 0 when every name matches the expectation, 1 otherwise, 2 on bad arguments.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#define BX_IMPORT extern "C" __declspec(dllimport)
BX_IMPORT ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID context, PVOID* out_reg);
BX_IMPORT ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID context, PVOID* out_reg);
namespace {
struct ApiSetName {
const char* dll;
const char* export_name;
};
/* One export per shim DLL. The calls in keep_imports() make the linker emit each import. */
const ApiSetName kNames[] = {
{"api-ms-win-core-psm-appnotify-l1-1-0.dll", "RegisterAppStateChangeNotification"},
{"api-ms-win-core-psm-appnotify-l1-1-1.dll", "RegisterAppConstrainedChangeNotification"},
{"ext-ms-win-rtcore-ntuser-message-l1-1-0.dll", "TranslateMessage"},
{"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll", "PeekMessageA"},
{"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow"},
{"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA"},
};
constexpr size_t kNameCount = sizeof(kNames) / sizeof(kNames[0]);
enum class Served { Shim, Host, Absent };
const char* served_name(Served s) {
switch (s) {
case Served::Shim: return "shim";
case Served::Host: return "host";
default: return "absent";
}
}
const IMAGE_IMPORT_DESCRIPTOR* find_import(const char* dll) {
auto* base = reinterpret_cast<const uint8_t*>(GetModuleHandleA(nullptr));
auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew);
const IMAGE_DATA_DIRECTORY& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
if (dir.VirtualAddress == 0) {
return nullptr;
}
auto* desc = reinterpret_cast<const IMAGE_IMPORT_DESCRIPTOR*>(base + dir.VirtualAddress);
for (; desc->Name != 0; ++desc) {
if (_stricmp(reinterpret_cast<const char*>(base + desc->Name), dll) == 0) {
return desc;
}
}
return nullptr;
}
/* The address the loader wrote into the first import address table slot for `dll`. */
const void* first_bound_address(const IMAGE_IMPORT_DESCRIPTOR* desc) {
auto* base = reinterpret_cast<const uint8_t*>(GetModuleHandleA(nullptr));
auto* iat = reinterpret_cast<const uintptr_t*>(base + desc->FirstThunk);
return reinterpret_cast<const void*>(iat[0]);
}
/* Referencing each export makes the linker keep the import. main() calls this only for an impossible argc. */
__attribute__((noinline)) void keep_imports() {
const void* const sink[] = {
reinterpret_cast<const void*>(&RegisterAppStateChangeNotification),
reinterpret_cast<const void*>(&RegisterAppConstrainedChangeNotification),
reinterpret_cast<const void*>(&TranslateMessage),
reinterpret_cast<const void*>(&PeekMessageA),
reinterpret_cast<const void*>(&ShowWindow),
reinterpret_cast<const void*>(&CreateWindowExA),
};
for (const void* p : sink) {
std::printf("%p\n", p);
}
}
/* Lower-cased full path of a module; empty when it cannot be read. */
bool path_of(HMODULE mod, char* out, DWORD out_len) {
out[0] = '\0';
if (!mod) {
return false;
}
DWORD n = GetModuleFileNameA(mod, out, out_len);
if (n == 0 || n >= out_len) {
out[0] = '\0';
return false;
}
CharLowerBuffA(out, n);
return true;
}
/* Directory part of `path` (up to the last backslash), or false when there is none. */
bool dir_len_of(const char* path, size_t* len) {
const char* slash = std::strrchr(path, '\\');
if (!slash) {
return false;
}
*len = static_cast<size_t>(slash - path);
return true;
}
/* Paths contain backslashes; escape them (and quotes) so each line stays valid JSON. */
void json_escape(const char* in, char* out, size_t out_len) {
size_t o = 0;
for (; *in && o + 2 < out_len; ++in) {
if (*in == '\\' || *in == '"') {
out[o++] = '\\';
}
out[o++] = *in;
}
out[o] = '\0';
}
int g_fail = 0;
int g_seq = 0;
void checkpoint(const char* stage, bool ok, const char* served, bool imported, const char* name_path,
const char* bound_path, const char* detail) {
char np[1024];
char bp[1024];
json_escape(name_path, np, sizeof(np));
json_escape(bound_path, bp, sizeof(bp));
g_seq++;
if (!ok) {
g_fail++;
}
std::printf("{\"bx_checkpoint\":\"test_apiset_resolution\",\"seq\":%d,\"stage\":\"%s\",\"status\":\"%s\","
"\"served_by\":\"%s\",\"statically_imported\":%s,\"name_module\":\"%s\",\"bound_to\":\"%s\",\"detail\":\"%s\"}\n",
g_seq, stage, ok ? "pass" : "fail", served, imported ? "true" : "false", np, bp, detail);
std::fflush(stdout);
}
} // namespace
int main(int argc, char** argv) {
if (argc > 1000) {
keep_imports();
}
Served expect = Served::Host;
if (argc == 3 && std::strcmp(argv[1], "--expect") == 0) {
if (std::strcmp(argv[2], "shim") == 0) {
expect = Served::Shim;
} else if (std::strcmp(argv[2], "host") != 0) {
std::fprintf(stderr, "usage: %s [--expect host|shim]\n", argv[0]);
return 2;
}
} else if (argc != 1) {
std::fprintf(stderr, "usage: %s [--expect host|shim]\n", argv[0]);
return 2;
}
char exe[MAX_PATH] = "";
const bool exe_ok = path_of(GetModuleHandleA(nullptr), exe, sizeof(exe));
size_t exe_dir = 0;
const bool have_exe_dir = exe_ok && dir_len_of(exe, &exe_dir);
int matched = 0;
for (const ApiSetName& n : kNames) {
const IMAGE_IMPORT_DESCRIPTOR* import = find_import(n.dll);
const bool imported = import != nullptr;
HMODULE name_mod = GetModuleHandleA(n.dll);
char name_path[MAX_PATH] = "";
const bool name_ok = path_of(name_mod, name_path, sizeof(name_path));
HMODULE bound_mod = nullptr;
char bound_path[MAX_PATH] = "";
bool bound_ok = false;
if (import
&& GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
static_cast<LPCSTR>(first_bound_address(import)), &bound_mod)) {
bound_ok = path_of(bound_mod, bound_path, sizeof(bound_path));
}
/* The shim serves the name only when the loaded module is that file next to this EXE. */
Served served = Served::Absent;
if (name_mod && name_ok && have_exe_dir) {
size_t dir = 0;
const char* slash = std::strrchr(name_path, '\\');
const bool same_dir = dir_len_of(name_path, &dir) && dir == exe_dir
&& std::memcmp(name_path, exe, exe_dir) == 0;
served = same_dir && slash && _stricmp(slash + 1, n.dll) == 0 ? Served::Shim : Served::Host;
}
const bool lookup_ok = have_exe_dir && name_mod && name_ok && bound_ok;
const bool ok = imported && lookup_ok && served == expect;
if (ok) {
matched++;
}
char detail[160];
if (!imported) {
std::snprintf(detail, sizeof(detail), "name is not in the static import directory");
} else if (!have_exe_dir) {
std::snprintf(detail, sizeof(detail), "%s: failed to resolve executable directory", n.export_name);
} else if (!name_mod) {
std::snprintf(detail, sizeof(detail), "%s: GetModuleHandleA returned null (expected %s)", n.export_name,
served_name(expect));
} else if (!name_ok) {
std::snprintf(detail, sizeof(detail), "%s: failed to resolve path for name module", n.export_name);
} else if (!bound_ok) {
std::snprintf(detail, sizeof(detail), "%s: failed to resolve owning module for bound IAT entry",
n.export_name);
} else {
std::snprintf(detail, sizeof(detail), "%s: served by %s, expected %s", n.export_name, served_name(served),
served_name(expect));
}
checkpoint(n.dll, ok, served_name(served), imported, name_ok ? name_path : "", bound_ok ? bound_path : "",
detail);
}
const bool ok = g_fail == 0;
std::printf("{\"bx_summary\":\"test_apiset_resolution\",\"names\":%zu,\"matched\":%d,\"expected\":\"%s\",\"result\":\"%s\"}\n",
kNameCount, matched, served_name(expect), ok ? "pass" : "fail");
std::printf("%s: test_apiset_resolution (%d/%zu names served by %s)\n", ok ? "PASS" : "FAIL", matched, kNameCount,
served_name(expect));
std::fflush(stdout);
return ok ? 0 : 1;
}
@@ -0,0 +1,3 @@
add_executable(test_audio_input main.cpp)
target_link_libraries(test_audio_input PRIVATE acphal xapu chad kernel32)
add_dependencies(test_audio_input gameinput)
+193
View File
@@ -0,0 +1,193 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <thread>
extern "C" {
HRESULT WINAPI AcpHalCreate(void**);
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
HRESULT WINAPI ApuFree(void*);
BOOL WINAPI ApuIsVirtualAddressValid(const void*, uint32_t);
void* WINAPI ApuMapApuAddress(uint32_t);
uint32_t WINAPI ApuMapVirtualAddress(const void*);
HRESULT WINAPI XApuConnect(void**);
HRESULT WINAPI XApuDisconnect(void*);
HRESULT WINAPI XApuEnqueueCommand(void*, const void*, uint32_t);
HRESULT WINAPI XApuDequeueResult(void*, void*, uint32_t);
uint32_t WINAPI XApuGetResultCount(void*);
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t, void**);
HRESULT WINAPI XDspActivate(void*);
HRESULT WINAPI XDspDeactivate(void*);
HRESULT WINAPI XDspSubmitCommand(void*, const void*, uint32_t);
HRESULT WINAPI XDspDisconnect(void*);
}
#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
namespace {
void WINAPI dummy_device_callback(uint64_t, void*, void*, uint64_t, uint32_t, uint32_t) {}
} // namespace
int main() {
void* object = nullptr;
CHECK(AcpHalCreate(&object) == S_OK && object);
auto* hal = static_cast<IUnknown*>(object);
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
CHECK(hal->Release() == 1);
void *va = nullptr, *second = nullptr;
uint32_t base = 0, other = 0;
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
CHECK(ApuCreateHeap(64, 64) == S_OK);
CHECK(ApuAlloc(&va, nullptr, 64, 64) == S_OK && va);
CHECK(ApuFree(va) == S_OK);
va = nullptr;
CHECK(ApuAlloc(nullptr, &base, 64, 64) == S_OK && base);
va = ApuMapApuAddress(base);
CHECK(va && ApuFree(va) == S_OK);
va = nullptr;
base = 0;
CHECK(ApuAlloc(&va, &base, 64, 256) == S_OK && va && base);
CHECK(reinterpret_cast<uintptr_t>(va) % 256 == 0 && base % 256 == 0);
CHECK(ApuAlloc(&second, &other, 64, 64) == S_OK && other != base);
CHECK(ApuCreateHeap(0, 0) == HRESULT_FROM_WIN32(ERROR_BUSY));
void* excess = nullptr;
CHECK(ApuAlloc(&excess, nullptr, 1, 64) == E_OUTOFMEMORY);
auto* tail = static_cast<unsigned char*>(va) + 63;
CHECK(ApuMapApuAddress(base + 63) == tail && ApuMapVirtualAddress(tail) == base + 63);
CHECK(ApuIsVirtualAddressValid(tail, 1) && !ApuIsVirtualAddressValid(tail, 2));
CHECK(ApuFree(tail) == E_INVALIDARG);
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
unsigned result = 0;
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_FALSE);
for (unsigned cycle = 0; cycle < 3; ++cycle) {
HRESULT status = S_OK;
unsigned accepted = 0;
std::thread producer([&] {
for (; accepted < 1024; ++accepted) {
unsigned command = cycle * 1024 + accepted;
status = XApuEnqueueCommand(apu, &command, sizeof(command));
if (status != S_OK) break;
}
});
producer.join();
CHECK(accepted && status == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(XApuGetResultCount(apu) == accepted && XApuGetResultCount(peer) == 0);
CHECK(XApuDequeueResult(apu, &result, 1) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
for (unsigned i = 0; i < accepted; ++i) {
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_OK);
CHECK(result == cycle * 1024 + i);
}
CHECK(XApuGetResultCount(apu) == 0);
}
// A stalled peer must fail this test rather than wait forever.
constexpr unsigned messages = 4096;
const auto deadline = GetTickCount64() + 10000;
std::atomic<bool> failed{false};
std::thread worker([&] {
for (unsigned i = 0; i < messages && !failed;) {
const auto hr = XApuEnqueueCommand(apu, &i, sizeof(i));
if (hr == S_OK) ++i;
else if (hr != HRESULT_FROM_WIN32(ERROR_BUSY) || GetTickCount64() >= deadline)
failed = true;
else std::this_thread::yield();
}
});
for (unsigned i = 0; i < messages && !failed;) {
const auto hr = XApuDequeueResult(apu, &result, sizeof(result));
if (hr == S_OK && result == i) ++i;
else if (hr != S_FALSE || GetTickCount64() >= deadline) failed = true;
else std::this_thread::yield();
}
worker.join();
CHECK(!failed && XApuGetResultCount(apu) == 0);
CHECK(XApuDisconnect(apu) == S_OK && XApuDisconnect(peer) == S_OK);
CHECK(XApuEnqueueCommand(apu, &result, sizeof(result)) == E_HANDLE);
CHECK(XDspConnectWithMaximumStreamLimit(0, &dsp) == E_INVALIDARG && !dsp);
CHECK(XDspConnectWithMaximumStreamLimit(2, &dsp) == S_OK && dsp);
for (unsigned cycle = 0; cycle < 2; ++cycle) {
unsigned queued = 0;
HRESULT hr = S_OK;
while (queued < 1024 && (hr = XDspSubmitCommand(dsp, &result, sizeof(result))) == S_OK)
++queued;
CHECK(queued && hr == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(XDspActivate(dsp) == S_OK);
for (unsigned i = 0; i <= queued; ++i)
CHECK(XDspSubmitCommand(dsp, &result, sizeof(result)) == S_OK);
CHECK(XDspDeactivate(dsp) == S_OK);
}
CHECK(XDspDisconnect(dsp) == S_OK && XDspActivate(dsp) == E_HANDLE);
HMODULE dll = LoadLibraryW(L"GameInput.dll");
CHECK(dll);
auto proc = GetProcAddress(dll, MAKEINTRESOURCEA(1));
CHECK(proc && proc == GetProcAddress(dll, "GameInputCreate"));
using Factory = HRESULT (WINAPI*)(void**);
auto create = reinterpret_cast<Factory>(reinterpret_cast<void*>(proc));
CHECK(create(&object) == S_OK && object);
auto* input = static_cast<IUnknown*>(object);
CHECK(create(&object) == S_OK && object == input && input->Release() == 1);
CHECK(input->QueryInterface(IID_IUnknown, &object) == S_OK && object == input);
CHECK(input->Release() == 1);
constexpr GUID kGameInputV0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
constexpr GUID kUnknownIid = {0x00000001, 0x0002, 0x0003,
{0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b}};
void* unknown = reinterpret_cast<void*>(uintptr_t{1});
CHECK(input->QueryInterface(kUnknownIid, &unknown) == E_NOINTERFACE && !unknown);
void* v0_obj = nullptr;
CHECK(input->QueryInterface(kGameInputV0, &v0_obj) == S_OK && v0_obj == input);
auto* v0 = static_cast<IUnknown*>(v0_obj);
auto** table = *reinterpret_cast<void***>(v0);
using Timestamp = uint64_t (WINAPI*)(IUnknown*);
CHECK(reinterpret_cast<Timestamp>(table[3])(v0) > 0);
using Reading = HRESULT (WINAPI*)(IUnknown*, uint32_t, void*, void**);
void* reading = reinterpret_cast<void*>(uintptr_t{1});
CHECK(reinterpret_cast<Reading>(table[4])(v0, 0, nullptr, &reading) == E_NOTIMPL && !reading);
using RegisterDeviceCb = HRESULT (WINAPI*)(
IUnknown*, void*, uint32_t, uint32_t, uint32_t, void*, void*, uint64_t*);
using StopCb = void (WINAPI*)(IUnknown*, uint64_t);
using UnregisterCb = bool (WINAPI*)(IUnknown*, uint64_t, uint64_t);
using SetFocusPolicyFn = void (WINAPI*)(IUnknown*, uint32_t);
auto reg_dev = reinterpret_cast<RegisterDeviceCb>(table[9]);
auto stop_cb = reinterpret_cast<StopCb>(table[12]);
auto unreg_cb = reinterpret_cast<UnregisterCb>(table[13]);
auto set_focus = reinterpret_cast<SetFocusPolicyFn>(table[21]);
void* cb_fn = reinterpret_cast<void*>(&dummy_device_callback);
uint64_t tok1 = 99, tok2 = 0;
CHECK(reg_dev(v0, nullptr, 1, 1, 0, nullptr, nullptr, &tok1) == E_INVALIDARG && tok1 == 0);
tok1 = 99;
CHECK(reg_dev(v0, nullptr, 0, 1, 0, nullptr, cb_fn, &tok1) == E_INVALIDARG && tok1 == 0);
tok1 = 99;
CHECK(reg_dev(v0, nullptr, 1, 0, 0, nullptr, cb_fn, &tok1) == E_INVALIDARG && tok1 == 0);
tok1 = 99;
CHECK(reg_dev(v0, nullptr, 1, 1, 3, nullptr, cb_fn, &tok1) == E_INVALIDARG && tok1 == 0);
CHECK(reg_dev(v0, nullptr, 0x10000, 0x1, 2, &tok1, cb_fn, &tok1) == S_OK && tok1 != 0);
CHECK(reg_dev(v0, nullptr, 0x10000, 0x1, 1, nullptr, cb_fn, &tok2) == S_OK && tok2 > tok1);
CHECK(reg_dev(v0, nullptr, 0x10000, 0x1, 0, nullptr, cb_fn, nullptr) == S_OK);
CHECK(!unreg_cb(v0, 0, 5000));
CHECK(!unreg_cb(v0, 0xdeadbeefULL, 5000));
stop_cb(v0, tok1);
CHECK(unreg_cb(v0, tok1, 5000));
CHECK(!unreg_cb(v0, tok1, 5000));
CHECK(unreg_cb(v0, tok2, 0));
CHECK(!unreg_cb(v0, tok2, 0));
set_focus(v0, 0x2);
CHECK(v0->Release() == 1);
CHECK(input->Release() == 0);
FreeLibrary(dll);
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1 and device callbacks");
}
@@ -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,6 @@
# #453: D3DMetal GPU limits (WaveSize(64), 64-bit typed UAV atomics, bounded lock emulation).
# Loads the host d3d12.dll at run time; links no BetterXen shim. Shader headers are
# generated by shaders/compile.sh (DXC v1.9.2609) and committed.
add_executable(test_d3dmetal_gpu_limits main.cpp)
target_include_directories(test_d3dmetal_gpu_limits PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(test_d3dmetal_gpu_limits PRIVATE kernel32)
@@ -0,0 +1,798 @@
/*
* #453: synthetic D3D12 compute fixtures for three GPU limits seen under D3DMetal.
*
* 1. wave64 A [WaveSize(64)] compute shader (SM 6.6). Observed: is it rejected
* at pipeline creation, created but not run, or run, and at which
* wave width? A shader without WaveSize is the control and must run.
* 2. atomic64 SM 6.6 64-bit atomics (add with carry, max) on a typed UAV
* (RWTexture2D<uint64_t> over R32G32_UINT). Observed: correct or
* wrong values. The same operations on a raw buffer are run as a
* control and observed the same way. A plain store beside the
* atomics shows whether each kernel ran at all.
* 3. lock64 The same two operations emulated with a per-texel spin lock over
* 32-bit words and a bounded retry cap (64 and 1024 tries). Required:
* with the 1024 cap no update is dropped and every value is exact.
*
* Talks to the host d3d12.dll directly (no BetterXen shim in the path), so under
* CrossOver/Wine with D3DMetal it measures D3DMetal. Expected values come from the
* public HLSL/D3D12 semantics and are computed here on the CPU, never by the GPU.
*
* Output: one "OBSERVED: <check> <outcome>" line per observation, "FAIL:" lines for
* required checks, and a final summary. Exit 0 when every required check passed,
* 1 otherwise, 77 when no D3D12 device can be created or it lacks shader model 6.6.
*/
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
#define WIDL_EXPLICIT_AGGREGATE_RETURNS /* call struct-returning COM methods with the real x64 ABI */
#endif
#include <windows.h>
#include <d3d12.h>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
#include "shaders/atomic64_buffer.h"
#include "shaders/atomic64_image.h"
#include "shaders/lock64_image.h"
#include "shaders/wave64_lanes.h"
#include "shaders/wave_lanes.h"
namespace {
constexpr uint32_t kSentinel = 0xA5A5A5A5u;
constexpr DWORD kGpuTimeoutMs = 10000;
constexpr UINT kThreads = 256; /* 4 groups of 64 for the atomic kernels */
constexpr UINT kTexels = 8;
int g_required = 0;
int g_failures = 0;
__attribute__((format(gnu_printf, 2, 3)))
bool require(bool ok, const char* fmt, ...) {
g_required++;
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;
}
__attribute__((format(gnu_printf, 1, 2)))
void observed(const char* fmt, ...) {
char msg[320];
va_list ap;
va_start(ap, fmt);
std::vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
std::printf("OBSERVED: %s\n", msg);
std::fflush(stdout);
}
unsigned long ul(HRESULT hr) { return static_cast<unsigned long>(hr); }
template <typename T>
void release(T*& p) {
if (p) {
p->Release();
p = nullptr;
}
}
/* ---- CPU reference values (independent of every shader) ---- */
uint64_t add_operand(uint32_t i) { return (uint64_t{0x10000000u} << 32) | uint64_t{0xF0000000u + i}; }
uint64_t max_operand(uint32_t i) { return (uint64_t{i} << 40) | uint64_t{0xFFFFFFFFu - i}; }
void expected_texels(uint64_t add[kTexels], uint64_t mx[kTexels]) {
for (UINT p = 0; p < kTexels; ++p) {
add[p] = 0;
mx[p] = 0;
}
for (uint32_t i = 0; i < kThreads; ++i) {
add[i & 7u] += add_operand(i); /* uint64_t wraps, as the HLSL add does */
if (max_operand(i) > mx[i & 7u]) mx[i & 7u] = max_operand(i);
}
}
/* ---- D3D12 plumbing ---- */
using PFN_CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
using PFN_Serialize = HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*, D3D_ROOT_SIGNATURE_VERSION, ID3DBlob**,
ID3DBlob**);
struct Gpu {
ID3D12Device* dev = nullptr;
ID3D12CommandQueue* queue = nullptr;
ID3D12CommandAllocator* alloc = nullptr;
ID3D12GraphicsCommandList* list = nullptr;
ID3D12Fence* fence = nullptr;
UINT64 fence_value = 0;
HANDLE event = nullptr;
PFN_Serialize serialize = nullptr;
bool lost = false; /* a submission timed out or the device was removed */
};
/* Close, submit, wait (bounded) and reopen the list. False on timeout or device removal. */
bool submit(Gpu& g, const char* what) {
if (g.lost) return false;
HRESULT hr = g.list->Close();
if (FAILED(hr)) {
observed("%s command list Close failed hr=0x%08lx", what, ul(hr));
return false;
}
ID3D12CommandList* lists[] = {g.list};
g.queue->ExecuteCommandLists(1, lists);
hr = g.queue->Signal(g.fence, ++g.fence_value);
if (FAILED(hr)) {
observed("%s queue Signal failed hr=0x%08lx", what, ul(hr));
g.lost = true;
return false;
}
if (g.fence->GetCompletedValue() < g.fence_value) {
hr = g.fence->SetEventOnCompletion(g.fence_value, g.event);
if (FAILED(hr) || WaitForSingleObject(g.event, kGpuTimeoutMs) != WAIT_OBJECT_0) {
observed("%s GPU work did not finish within %lu ms (queue considered hung; later checks skipped)", what,
static_cast<unsigned long>(kGpuTimeoutMs));
g.lost = true;
return false;
}
}
if (g.fence->GetCompletedValue() == UINT64_MAX) {
observed("%s device removed, reason hr=0x%08lx", what, ul(g.dev->GetDeviceRemovedReason()));
g.lost = true;
return false;
}
hr = g.alloc->Reset();
if (SUCCEEDED(hr)) hr = g.list->Reset(g.alloc, nullptr);
if (FAILED(hr)) {
observed("%s allocator or command list Reset failed hr=0x%08lx", what, ul(hr));
g.lost = true;
return false;
}
return true;
}
/* Discards whatever is recorded in the open list without executing it (used when a
* check fails partway through recording), so the next check starts from an empty list. */
void abandon(Gpu& g) {
if (g.lost) return;
g.list->Close();
if (FAILED(g.alloc->Reset()) || FAILED(g.list->Reset(g.alloc, nullptr))) g.lost = true;
}
/* Releases a resource the GPU may have used. After a hung or removed queue the GPU may
* still reference it, so it is deliberately leaked instead. */
template <typename T>
void drop(const Gpu& g, T*& p) {
if (g.lost) {
p = nullptr;
return;
}
release(p);
}
ID3D12Resource* make_buffer(Gpu& g, D3D12_HEAP_TYPE heap, UINT64 size, D3D12_RESOURCE_STATES state,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
D3D12_HEAP_PROPERTIES hp = {};
hp.Type = heap;
D3D12_RESOURCE_DESC rd = {};
rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
rd.Width = size;
rd.Height = 1;
rd.DepthOrArraySize = 1;
rd.MipLevels = 1;
rd.SampleDesc.Count = 1;
rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
rd.Flags = flags;
ID3D12Resource* r = nullptr;
HRESULT hr = g.dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, state, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return SUCCEEDED(hr) ? r : nullptr;
}
ID3D12Resource* make_texture(Gpu& g, UINT width, UINT height, DXGI_FORMAT format) {
D3D12_HEAP_PROPERTIES hp = {};
hp.Type = D3D12_HEAP_TYPE_DEFAULT;
D3D12_RESOURCE_DESC rd = {};
rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
rd.Width = width;
rd.Height = height;
rd.DepthOrArraySize = 1;
rd.MipLevels = 1;
rd.Format = format;
rd.SampleDesc.Count = 1;
rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
ID3D12Resource* r = nullptr;
HRESULT hr = g.dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return SUCCEEDED(hr) ? r : nullptr;
}
void transition(Gpu& g, ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
D3D12_RESOURCE_BARRIER b = {};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
b.Transition.pResource = r;
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
b.Transition.StateBefore = before;
b.Transition.StateAfter = after;
g.list->ResourceBarrier(1, &b);
}
void uav_barrier(Gpu& g) {
D3D12_RESOURCE_BARRIER b = {};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
g.list->ResourceBarrier(1, &b);
}
bool map_write(ID3D12Resource* r, const void* src, size_t n) {
void* p = nullptr;
if (FAILED(r->Map(0, nullptr, &p)) || !p) return false;
std::memcpy(p, src, n);
r->Unmap(0, nullptr);
return true;
}
bool map_read(ID3D12Resource* r, void* dst, size_t n) {
void* p = nullptr;
D3D12_RANGE range = {0, n};
if (FAILED(r->Map(0, &range, &p)) || !p) return false;
std::memcpy(dst, p, n);
D3D12_RANGE none = {0, 0};
r->Unmap(0, &none);
return true;
}
/* Root signature from parameters; logs and returns null on failure. */
ID3D12RootSignature* make_root(Gpu& g, const char* what, const D3D12_ROOT_PARAMETER* params, UINT count) {
D3D12_ROOT_SIGNATURE_DESC desc = {};
desc.NumParameters = count;
desc.pParameters = params;
ID3DBlob* blob = nullptr;
ID3DBlob* err = nullptr;
HRESULT hr = g.serialize(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err);
release(err);
if (FAILED(hr)) {
observed("%s root signature serialization failed hr=0x%08lx", what, ul(hr));
return nullptr;
}
ID3D12RootSignature* rs = nullptr;
hr = g.dev->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), __uuidof(ID3D12RootSignature),
reinterpret_cast<void**>(&rs));
release(blob);
if (FAILED(hr)) {
observed("%s CreateRootSignature failed hr=0x%08lx", what, ul(hr));
return nullptr;
}
return rs;
}
ID3D12PipelineState* make_pipeline(Gpu& g, ID3D12RootSignature* rs, const unsigned char* code, size_t size,
HRESULT* out_hr) {
D3D12_COMPUTE_PIPELINE_STATE_DESC pd = {};
pd.pRootSignature = rs;
pd.CS.pShaderBytecode = code;
pd.CS.BytecodeLength = size;
ID3D12PipelineState* pso = nullptr;
*out_hr = g.dev->CreateComputePipelineState(&pd, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
return SUCCEEDED(*out_hr) ? pso : nullptr;
}
D3D12_ROOT_PARAMETER root_uav(UINT reg) {
D3D12_ROOT_PARAMETER p = {};
p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
p.Descriptor.ShaderRegister = reg;
p.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
return p;
}
/* ---- buffer kernels: run one dispatch over a root-UAV buffer, return its words ---- */
bool run_buffer_kernel(Gpu& g, const char* what, ID3D12PipelineState* pso, ID3D12RootSignature* rs,
const std::vector<uint32_t>& init, UINT groups, std::vector<uint32_t>& out) {
const UINT64 bytes = init.size() * sizeof(uint32_t);
ID3D12Resource* up = make_buffer(g, D3D12_HEAP_TYPE_UPLOAD, bytes, D3D12_RESOURCE_STATE_GENERIC_READ);
ID3D12Resource* buf = make_buffer(g, D3D12_HEAP_TYPE_DEFAULT, bytes, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
ID3D12Resource* rb = make_buffer(g, D3D12_HEAP_TYPE_READBACK, bytes, D3D12_RESOURCE_STATE_COPY_DEST);
bool ok = up && buf && rb && map_write(up, init.data(), bytes);
if (ok) {
g.list->CopyBufferRegion(buf, 0, up, 0, bytes);
transition(g, buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
g.list->SetComputeRootSignature(rs);
g.list->SetPipelineState(pso);
g.list->SetComputeRootUnorderedAccessView(0, buf->GetGPUVirtualAddress());
g.list->Dispatch(groups, 1, 1);
transition(g, buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
g.list->CopyBufferRegion(rb, 0, buf, 0, bytes);
ok = submit(g, what);
out.assign(init.size(), 0);
ok = ok && map_read(rb, out.data(), bytes);
} else {
observed("%s buffer creation or upload failed", what);
}
drop(g, up);
drop(g, buf);
drop(g, rb);
return ok;
}
/* ---- 1. wave64 ---- */
void check_wave64(Gpu& g) {
D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1 = {};
if (SUCCEEDED(g.dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof(o1)))) {
observed("wave.reported WaveOps=%d WaveLaneCountMin=%u WaveLaneCountMax=%u", o1.WaveOps ? 1 : 0,
o1.WaveLaneCountMin, o1.WaveLaneCountMax);
}
D3D12_ROOT_PARAMETER params[] = {root_uav(0)};
ID3D12RootSignature* rs = make_root(g, "wave", params, 1);
if (!require(rs != nullptr, "wave root signature")) return;
/* Two words per thread: (wave width << 16) | lane index, then the dispatch index of the
* wave's first active lane, which names the wave the thread ran in. */
const std::vector<uint32_t> init(128, kSentinel);
struct Case {
const char* name;
const unsigned char* code;
size_t size;
bool control;
} cases[] = {
{"wave.control", g_wave_lanes_cs, sizeof(g_wave_lanes_cs), true},
{"wave.wavesize64", g_wave64_lanes_cs, sizeof(g_wave64_lanes_cs), false},
};
for (const Case& c : cases) {
HRESULT hr = S_OK;
ID3D12PipelineState* pso = make_pipeline(g, rs, c.code, c.size, &hr);
if (!pso) {
observed("%s rejected at CreateComputePipelineState hr=0x%08lx", c.name, ul(hr));
if (c.control) require(false, "%s: control pipeline must be created", c.name);
continue;
}
std::vector<uint32_t> out;
bool ran = run_buffer_kernel(g, c.name, pso, rs, init, 1, out);
release(pso);
if (!ran) {
if (c.control) require(false, "%s: control dispatch must complete", c.name);
continue;
}
bool all_sentinel = true;
for (uint32_t w : out) all_sentinel = all_sentinel && w == kSentinel;
if (all_sentinel) {
observed("%s created but not run (output still sentinel)", c.name);
if (c.control) require(false, "%s: control kernel must write its output", c.name);
continue;
}
/* What D3D12 guarantees: every thread reports the same width, and within each wave the
* lane indices are a permutation of 0..W-1. Threads are grouped into waves by the
* dispatch index of the wave's first lane; no particular thread-to-lane order is assumed. */
const uint32_t width = out[0] >> 16;
bool layout_ok = width >= 1 && width <= 64 && 64 % width == 0;
std::vector<std::vector<uint32_t>> waves(64);
for (uint32_t i = 0; layout_ok && i < 64; ++i) {
const uint32_t lanes = out[2 * i], leader = out[2 * i + 1];
layout_ok = (lanes >> 16) == width && leader < 64;
if (layout_ok) waves[leader].push_back(lanes & 0xFFFFu);
}
uint32_t wave_count = 0;
for (auto& w : waves) {
if (!layout_ok || w.empty()) continue;
wave_count++;
std::vector<bool> seen(width, false);
layout_ok = w.size() == width;
for (uint32_t lane : w) {
layout_ok = layout_ok && lane < width && !seen[lane];
if (layout_ok) seen[lane] = true;
}
}
layout_ok = layout_ok && wave_count * width == 64;
observed("%s ran with wave width %u, lane layout %s", c.name, width, layout_ok ? "consistent" : "INCONSISTENT");
if (c.control) require(layout_ok, "%s: each wave's lane indices must be a permutation of 0..W-1", c.name);
if (!c.control && layout_ok && width != 64) {
observed("%s WaveSize(64) not honoured: ran at width %u instead of being rejected", c.name, width);
}
}
release(rs);
}
/* ---- 2. 64-bit atomics on a typed UAV, with a raw-buffer control ---- */
/* Plain-store marker the atomic kernels write next to their atomics: proves the kernel ran. */
uint64_t marker(UINT p) { return (uint64_t{0xC0DEu} << 32) | p; }
void report_marker(const char* name, const uint64_t got[kTexels]) {
int bad = 0;
for (UINT p = 0; p < kTexels; ++p) bad += got[p] != marker(p);
observed("%s plain-store marker %s (%d/8 match)", name, bad == 0 ? "written: kernel ran" : "WRONG or missing",
8 - bad);
}
void report_texels(const char* name, const uint64_t got_add[kTexels], const uint64_t got_max[kTexels]) {
uint64_t want_add[kTexels], want_max[kTexels];
expected_texels(want_add, want_max);
int bad = 0;
for (UINT p = 0; p < kTexels; ++p) {
bad += got_add[p] != want_add[p];
bad += got_max[p] != want_max[p];
}
if (bad == 0) {
observed("%s correct (16/16 values)", name);
} else {
observed("%s WRONG values: %d/16 differ; texel 0 add got 0x%016llx want 0x%016llx, max got 0x%016llx want "
"0x%016llx",
name, bad, static_cast<unsigned long long>(got_add[0]), static_cast<unsigned long long>(want_add[0]),
static_cast<unsigned long long>(got_max[0]), static_cast<unsigned long long>(want_max[0]));
}
}
void check_atomic64_buffer(Gpu& g) {
D3D12_ROOT_PARAMETER params[] = {root_uav(0)};
ID3D12RootSignature* rs = make_root(g, "atomic64.buffer", params, 1);
if (!rs) return;
HRESULT hr = S_OK;
ID3D12PipelineState* pso = make_pipeline(g, rs, g_atomic64_buffer_cs, sizeof(g_atomic64_buffer_cs), &hr);
if (!pso) {
observed("atomic64.buffer rejected at CreateComputePipelineState hr=0x%08lx", ul(hr));
release(rs);
return;
}
std::vector<uint32_t> out;
if (run_buffer_kernel(g, "atomic64.buffer", pso, rs, std::vector<uint32_t>(48, 0), kThreads / 64, out)) {
uint64_t add[kTexels], mx[kTexels], mark[kTexels];
for (UINT p = 0; p < kTexels; ++p) {
add[p] = (uint64_t{out[2 * p + 1]} << 32) | out[2 * p];
mx[p] = (uint64_t{out[16 + 2 * p + 1]} << 32) | out[16 + 2 * p];
mark[p] = (uint64_t{out[32 + 2 * p + 1]} << 32) | out[32 + 2 * p];
}
report_marker("atomic64.buffer", mark);
report_texels("atomic64.buffer", add, mx);
}
release(pso);
release(rs);
}
/* Texture helpers: upload zeros into / read back a tightly described 2D texture. */
struct TexCopy {
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp = {};
UINT64 total = 0;
};
TexCopy footprint(Gpu& g, ID3D12Resource* tex) {
TexCopy t;
D3D12_RESOURCE_DESC rd;
tex->GetDesc(&rd);
UINT rows = 0;
UINT64 row_bytes = 0;
g.dev->GetCopyableFootprints(&rd, 0, 1, 0, &t.fp, &rows, &row_bytes, &t.total);
return t;
}
void copy_to_texture(Gpu& g, ID3D12Resource* tex, ID3D12Resource* up, const TexCopy& t) {
D3D12_TEXTURE_COPY_LOCATION dst = {};
dst.pResource = tex;
dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
D3D12_TEXTURE_COPY_LOCATION src = {};
src.pResource = up;
src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
src.PlacedFootprint = t.fp;
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
}
void copy_from_texture(Gpu& g, ID3D12Resource* tex, ID3D12Resource* rb, const TexCopy& t) {
D3D12_TEXTURE_COPY_LOCATION dst = {};
dst.pResource = rb;
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
dst.PlacedFootprint = t.fp;
D3D12_TEXTURE_COPY_LOCATION src = {};
src.pResource = tex;
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
}
/* Reads texel (x, y), `words` 32-bit words per texel, out of a readback copy. */
uint32_t texel_word(const std::vector<uint8_t>& data, const TexCopy& t, UINT x, UINT y, UINT words, UINT w) {
uint32_t v = 0;
std::memcpy(&v, data.data() + t.fp.Offset + y * t.fp.Footprint.RowPitch + (x * words + w) * 4, 4);
return v;
}
struct ImageSet {
explicit ImageSet(const Gpu& gpu) : g(gpu) {}
const Gpu& g;
ID3D12DescriptorHeap* heap = nullptr;
std::vector<ID3D12Resource*> tex;
std::vector<TexCopy> copy;
std::vector<ID3D12Resource*> rb;
~ImageSet() {
drop(g, heap);
for (auto*& r : tex) drop(g, r);
for (auto*& r : rb) drop(g, r);
}
};
/* Creates zero-filled UAV textures with descriptors in one shader-visible heap, ready in UAV state. */
bool make_images(Gpu& g, const char* what, ImageSet& s, const UINT (*dims)[2], const DXGI_FORMAT* formats, UINT count) {
D3D12_DESCRIPTOR_HEAP_DESC hd = {};
hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
hd.NumDescriptors = count;
hd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
if (FAILED(g.dev->CreateDescriptorHeap(&hd, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&s.heap)))) {
observed("%s descriptor heap creation failed", what);
return false;
}
D3D12_CPU_DESCRIPTOR_HANDLE cpu;
s.heap->GetCPUDescriptorHandleForHeapStart(&cpu);
const UINT inc = g.dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
std::vector<ID3D12Resource*> uploads;
bool ok = true;
for (UINT i = 0; i < count && ok; ++i) {
ID3D12Resource* t = make_texture(g, dims[i][0], dims[i][1], formats[i]);
if (!t) {
observed("%s texture %u creation failed", what, i);
ok = false;
break;
}
s.tex.push_back(t);
s.copy.push_back(footprint(g, t));
const TexCopy& c = s.copy.back();
ID3D12Resource* up = make_buffer(g, D3D12_HEAP_TYPE_UPLOAD, c.total, D3D12_RESOURCE_STATE_GENERIC_READ);
ID3D12Resource* rb = make_buffer(g, D3D12_HEAP_TYPE_READBACK, c.total, D3D12_RESOURCE_STATE_COPY_DEST);
s.rb.push_back(rb);
uploads.push_back(up);
std::vector<uint8_t> zeros(static_cast<size_t>(c.total), 0);
ok = up && rb && map_write(up, zeros.data(), zeros.size());
if (!ok) break;
copy_to_texture(g, t, up, c);
transition(g, t, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
D3D12_UNORDERED_ACCESS_VIEW_DESC ud = {};
ud.Format = formats[i];
ud.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
D3D12_CPU_DESCRIPTOR_HANDLE h = {cpu.ptr + static_cast<SIZE_T>(i) * inc};
g.dev->CreateUnorderedAccessView(t, nullptr, &ud, h);
}
if (ok) {
ok = submit(g, what);
} else {
abandon(g);
}
for (auto*& u : uploads) drop(g, u);
return ok;
}
bool read_images(Gpu& g, const char* what, ImageSet& s, std::vector<std::vector<uint8_t>>& data) {
for (size_t i = 0; i < s.tex.size(); ++i) {
transition(g, s.tex[i], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
copy_from_texture(g, s.tex[i], s.rb[i], s.copy[i]);
}
if (!submit(g, what)) return false;
data.resize(s.tex.size());
for (size_t i = 0; i < s.tex.size(); ++i) {
data[i].resize(static_cast<size_t>(s.copy[i].total));
if (!map_read(s.rb[i], data[i].data(), data[i].size())) return false;
}
return true;
}
void bind_table(Gpu& g, ImageSet& s) {
ID3D12DescriptorHeap* heaps[] = {s.heap};
g.list->SetDescriptorHeaps(1, heaps);
D3D12_GPU_DESCRIPTOR_HANDLE gpu;
s.heap->GetGPUDescriptorHandleForHeapStart(&gpu);
g.list->SetComputeRootDescriptorTable(0, gpu);
}
void check_atomic64_image(Gpu& g) {
D3D12_FEATURE_DATA_D3D12_OPTIONS9 o9 = {};
D3D12_FEATURE_DATA_D3D12_OPTIONS11 o11 = {};
const bool have9 = SUCCEEDED(g.dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS9, &o9, sizeof(o9)));
const bool have11 = SUCCEEDED(g.dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS11, &o11, sizeof(o11)));
observed("atomic64.reported AtomicInt64OnTypedResourceSupported=%s AtomicInt64OnDescriptorHeapResourceSupported=%s",
have9 ? (o9.AtomicInt64OnTypedResourceSupported ? "1" : "0") : "query-failed",
have11 ? (o11.AtomicInt64OnDescriptorHeapResourceSupported ? "1" : "0") : "query-failed");
D3D12_DESCRIPTOR_RANGE range = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0};
D3D12_ROOT_PARAMETER table = {};
table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
table.DescriptorTable.NumDescriptorRanges = 1;
table.DescriptorTable.pDescriptorRanges = &range;
ID3D12RootSignature* rs = make_root(g, "atomic64.image", &table, 1);
if (!rs) return;
HRESULT hr = S_OK;
ID3D12PipelineState* pso = make_pipeline(g, rs, g_atomic64_image_cs, sizeof(g_atomic64_image_cs), &hr);
if (!pso) {
observed("atomic64.image rejected at CreateComputePipelineState hr=0x%08lx", ul(hr));
release(rs);
return;
}
{
ImageSet s(g);
const UINT dims[][2] = {{kTexels, 3}};
const DXGI_FORMAT fmt[] = {DXGI_FORMAT_R32G32_UINT};
std::vector<std::vector<uint8_t>> data;
if (make_images(g, "atomic64.image", s, dims, fmt, 1)) {
g.list->SetComputeRootSignature(rs);
g.list->SetPipelineState(pso);
bind_table(g, s);
g.list->Dispatch(kThreads / 64, 1, 1);
if (read_images(g, "atomic64.image", s, data)) {
uint64_t add[kTexels], mx[kTexels], mark[kTexels];
for (UINT p = 0; p < kTexels; ++p) {
mark[p] = (uint64_t{texel_word(data[0], s.copy[0], p, 2, 2, 1)} << 32) |
texel_word(data[0], s.copy[0], p, 2, 2, 0);
add[p] = (uint64_t{texel_word(data[0], s.copy[0], p, 0, 2, 1)} << 32) |
texel_word(data[0], s.copy[0], p, 0, 2, 0);
mx[p] = (uint64_t{texel_word(data[0], s.copy[0], p, 1, 2, 1)} << 32) |
texel_word(data[0], s.copy[0], p, 1, 2, 0);
}
report_marker("atomic64.image", mark);
report_texels("atomic64.image", add, mx);
}
}
}
release(pso);
release(rs);
}
/* ---- 3. lock-based emulation with a bounded retry cap ---- */
void check_lock64(Gpu& g, UINT cap, bool required) {
char name[48];
std::snprintf(name, sizeof(name), "lock64.cap%u", cap);
D3D12_DESCRIPTOR_RANGE range = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0, 0, 0};
D3D12_ROOT_PARAMETER params[3] = {};
params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
params[0].DescriptorTable.NumDescriptorRanges = 1;
params[0].DescriptorTable.pDescriptorRanges = &range;
params[1] = root_uav(2);
params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
params[2].Constants.ShaderRegister = 0;
params[2].Constants.Num32BitValues = 1;
ID3D12RootSignature* rs = make_root(g, name, params, 3);
if (!rs) {
if (required) require(false, "%s: root signature", name);
return;
}
HRESULT hr = S_OK;
ID3D12PipelineState* pso = make_pipeline(g, rs, g_lock64_image_cs, sizeof(g_lock64_image_cs), &hr);
if (!pso) {
observed("%s rejected at CreateComputePipelineState hr=0x%08lx", name, ul(hr));
if (required) require(false, "%s: lock emulation pipeline must be created", name);
release(rs);
return;
}
{
ImageSet s(g);
const UINT dims[][2] = {{2 * kTexels, 2}, {kTexels, 2}};
const DXGI_FORMAT fmt[] = {DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_UINT};
ID3D12Resource* stats = nullptr;
ID3D12Resource* stats_rb = nullptr;
ID3D12Resource* up = nullptr; /* kept alive until the list that copies from it has run */
bool ok = make_images(g, name, s, dims, fmt, 2);
if (ok) {
const uint32_t zeros[2] = {0, 0};
up = make_buffer(g, D3D12_HEAP_TYPE_UPLOAD, 8, D3D12_RESOURCE_STATE_GENERIC_READ);
stats = make_buffer(g, D3D12_HEAP_TYPE_DEFAULT, 256, D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
stats_rb = make_buffer(g, D3D12_HEAP_TYPE_READBACK, 8, D3D12_RESOURCE_STATE_COPY_DEST);
ok = up && stats && stats_rb && map_write(up, zeros, sizeof(zeros));
if (ok) {
g.list->CopyBufferRegion(stats, 0, up, 0, 8);
transition(g, stats, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
g.list->SetComputeRootSignature(rs);
g.list->SetPipelineState(pso);
bind_table(g, s);
g.list->SetComputeRootUnorderedAccessView(1, stats->GetGPUVirtualAddress());
g.list->SetComputeRoot32BitConstant(2, cap, 0);
g.list->Dispatch(kThreads / 64, 1, 1);
uav_barrier(g);
transition(g, stats, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
g.list->CopyBufferRegion(stats_rb, 0, stats, 0, 8);
} else {
abandon(g);
}
}
std::vector<std::vector<uint8_t>> data;
ok = ok && read_images(g, name, s, data);
drop(g, up);
uint32_t st[2] = {0, 0};
ok = ok && map_read(stats_rb, st, sizeof(st));
if (ok) {
uint64_t add[kTexels], mx[kTexels];
for (UINT p = 0; p < kTexels; ++p) {
add[p] = (uint64_t{texel_word(data[0], s.copy[0], 2 * p + 1, 0, 1, 0)} << 32) |
texel_word(data[0], s.copy[0], 2 * p, 0, 1, 0);
mx[p] = (uint64_t{texel_word(data[0], s.copy[0], 2 * p + 1, 1, 1, 0)} << 32) |
texel_word(data[0], s.copy[0], 2 * p, 1, 1, 0);
}
observed("%s dropped %u of %u updates, %u tries in all", name, st[0], 2 * kThreads, st[1]);
if (st[0] == 0) {
report_texels(name, add, mx);
} else {
observed("%s values not compared (updates were dropped)", name);
}
if (required) {
uint64_t want_add[kTexels], want_max[kTexels];
expected_texels(want_add, want_max);
bool exact = st[0] == 0;
for (UINT p = 0; exact && p < kTexels; ++p) exact = add[p] == want_add[p] && mx[p] == want_max[p];
require(exact, "%s: no update dropped and every value exact (dropped %u)", name, st[0]);
}
} else if (required) {
require(false, "%s: dispatch and readback must complete", name);
}
drop(g, stats);
drop(g, stats_rb);
}
release(pso);
release(rs);
}
} // namespace
int main() {
std::setvbuf(stdout, nullptr, _IONBF, 0);
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = d3d12 ? reinterpret_cast<PFN_CreateDevice>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice"))) : nullptr;
Gpu g;
g.serialize = d3d12 ? reinterpret_cast<PFN_Serialize>(
reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeRootSignature"))) : nullptr;
if (!create || !g.serialize) {
std::printf("SKIP: d3d12.dll or its exports are unavailable\n");
return 77;
}
HRESULT hr = create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g.dev));
if (FAILED(hr) || !g.dev) {
std::printf("SKIP: D3D12CreateDevice failed hr=0x%08lx\n", ul(hr));
return 77;
}
/* Every kernel is cs_6_6: below that (or when the query fails) the fixture cannot say
* anything about these limits, so it skips instead of reporting a failure. */
D3D12_FEATURE_DATA_SHADER_MODEL sm = {D3D_SHADER_MODEL_6_6};
if (FAILED(g.dev->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm))) ||
sm.HighestShaderModel < D3D_SHADER_MODEL_6_6) {
std::printf("SKIP: shader model 6.6 is not available\n");
release(g.dev);
return 77;
}
observed("device.shader_model 0x%x", static_cast<unsigned>(sm.HighestShaderModel));
D3D12_COMMAND_QUEUE_DESC qd = {};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
bool setup = SUCCEEDED(g.dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue),
reinterpret_cast<void**>(&g.queue))) &&
SUCCEEDED(g.dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
__uuidof(ID3D12CommandAllocator),
reinterpret_cast<void**>(&g.alloc))) &&
SUCCEEDED(g.dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.alloc, nullptr,
__uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(&g.list))) &&
SUCCEEDED(g.dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence),
reinterpret_cast<void**>(&g.fence)));
g.event = CreateEventA(nullptr, FALSE, FALSE, nullptr);
if (!require(setup && g.event, "queue, allocator, command list and fence creation")) return 1;
check_wave64(g);
check_atomic64_buffer(g);
check_atomic64_image(g);
check_lock64(g, 64, false);
check_lock64(g, 1024, true);
if (g.lost) require(false, "GPU work must finish and the device must stay alive");
std::printf("SUMMARY: %d required checks, %d failed\n", g_required, g_failures);
if (g.lost) return 1; /* leave the device and queue alone: the GPU may still be using them */
release(g.fence);
release(g.list);
release(g.alloc);
release(g.queue);
release(g.dev);
if (g.event) CloseHandle(g.event);
return g_failures == 0 ? 0 : 1;
}
@@ -0,0 +1,387 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// GENERATED by DXC 1.9.2609 from atomic64_buffer.hlsl by compile.sh; do not edit.
#if 0
;
; Note: shader requires additional functionality:
; 64-Bit integer
;
;
; Input signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
;
; Output signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
; shader hash: 190fd681a6fdc81561132f9a2e60b00c
;
; Pipeline Runtime Information:
;
;PSVRuntimeInfo:
; Compute Shader
; NumThreads=(64,1,1)
; MinimumExpectedWaveLaneCount: 0
; MaximumExpectedWaveLaneCount: 4294967295
; UsesViewID: false
; SigInputElements: 0
; SigOutputElements: 0
; SigPatchConstOrPrimElements: 0
; SigInputVectors: 0
; SigOutputVectors[0]: 0
; SigOutputVectors[1]: 0
; SigOutputVectors[2]: 0
; SigOutputVectors[3]: 0
; EntryFunctionName: main
;
;
; Buffer Definitions:
;
;
; Resource Bindings:
;
; Name Type Format Dim ID HLSL Bind Count
; ------------------------------ ---------- ------- ----------- ------- -------------- ------
; Buf UAV byte r/w U0 u0 1
;
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
%dx.types.Handle = type { i8* }
%dx.types.ResBind = type { i32, i32, i32, i8 }
%dx.types.ResourceProperties = type { i32, i32 }
%struct.RWByteAddressBuffer = type { i32 }
define void @main() {
%1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 0, i32 0, i32 0, i8 1 }, i32 0, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%2 = call i32 @dx.op.threadId.i32(i32 93, i32 0) ; ThreadId(component)
%3 = and i32 %2, 7
%4 = add i32 %2, -268435456
%5 = zext i32 %4 to i64
%6 = or i64 %5, 1152921504606846976
%7 = shl nuw nsw i32 %3, 3
%8 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) ; AnnotateHandle(res,props) resource: RWByteAddressBuffer
%9 = call i64 @dx.op.atomicBinOp.i64(i32 78, %dx.types.Handle %8, i32 0, i32 %7, i32 undef, i32 undef, i64 %6) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
%10 = zext i32 %2 to i64
%11 = shl i64 %10, 40
%12 = xor i32 %2, -1
%13 = zext i32 %12 to i64
%14 = or i64 %11, %13
%15 = or i32 %7, 64
%16 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) ; AnnotateHandle(res,props) resource: RWByteAddressBuffer
%17 = call i64 @dx.op.atomicBinOp.i64(i32 78, %dx.types.Handle %16, i32 7, i32 %15, i32 undef, i32 undef, i64 %14) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
%18 = or i32 %7, 128
%19 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) ; AnnotateHandle(res,props) resource: RWByteAddressBuffer
call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %19, i32 %18, i32 undef, i32 %3, i32 49374, i32 undef, i32 undef, i8 3, i32 4) ; RawBufferStore(uav,index,elementOffset,value0,value1,value2,value3,mask,alignment)
ret void
}
; Function Attrs: nounwind readnone
declare i32 @dx.op.threadId.i32(i32, i32) #0
; Function Attrs: nounwind
declare i64 @dx.op.atomicBinOp.i64(i32, %dx.types.Handle, i32, i32, i32, i32, i64) #1
; Function Attrs: nounwind
declare void @dx.op.rawBufferStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i8, i32) #1
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0
attributes #0 = { nounwind readnone }
attributes #1 = { nounwind }
!llvm.ident = !{!0}
!dx.version = !{!1}
!dx.valver = !{!2}
!dx.shaderModel = !{!3}
!dx.resources = !{!4}
!dx.entryPoints = !{!8}
!0 = !{!"dxcoob 1.9.2609.5 (01b62ad47)"}
!1 = !{i32 1, i32 6}
!2 = !{i32 1, i32 9}
!3 = !{!"cs", i32 6, i32 6}
!4 = !{null, !5, null, null}
!5 = !{!6}
!6 = !{i32 0, %struct.RWByteAddressBuffer* undef, !"", i32 0, i32 0, i32 1, i32 11, i1 false, i1 false, i1 false, !7}
!7 = !{i32 3, i32 1}
!8 = !{void ()* @main, !"main", null, !4, !9}
!9 = !{i32 0, i64 1048592, i32 4, !10}
!10 = !{i32 64, i32 1, i32 1}
#endif
const unsigned char g_atomic64_buffer_cs[] = {
0x44, 0x58, 0x42, 0x43, 0x5b, 0x87, 0x05, 0x91, 0x7d, 0xd4, 0x0f, 0xf5,
0x40, 0xd1, 0x11, 0xa2, 0x1d, 0x9a, 0x7f, 0xbb, 0x01, 0x00, 0x00, 0x00,
0x50, 0x0c, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00,
0xdc, 0x00, 0x00, 0x00, 0x4c, 0x06, 0x00, 0x00, 0x68, 0x06, 0x00, 0x00,
0x53, 0x46, 0x49, 0x30, 0x08, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x31, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x4f, 0x53, 0x47, 0x31,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x50, 0x53, 0x56, 0x30, 0x68, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x53, 0x54, 0x41, 0x54, 0x68, 0x05, 0x00, 0x00,
0x66, 0x00, 0x05, 0x00, 0x5a, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x50, 0x05, 0x00, 0x00,
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x51, 0x01, 0x00, 0x00,
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xa4, 0x10, 0x32, 0x14,
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88, 0x48, 0x90, 0x14, 0x20,
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
0x84, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x01, 0x00, 0x00, 0x00,
0x49, 0x18, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42,
0x20, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00,
0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04, 0x93, 0x22, 0xa4, 0x84,
0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8a, 0x8c,
0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00, 0x25, 0x00, 0x14, 0xe6,
0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x73, 0x04, 0xa0, 0x30, 0x47,
0x80, 0xd0, 0xb9, 0x67, 0xb8, 0xfc, 0x09, 0x7b, 0x08, 0xc9, 0x0f, 0x81,
0x66, 0x58, 0x08, 0x14, 0xa0, 0x82, 0x98, 0x91, 0xc6, 0x18, 0xc3, 0x90,
0x2a, 0x0b, 0x18, 0x69, 0x8c, 0x31, 0xc6, 0x38, 0x83, 0xd8, 0x6d, 0xc3,
0xe5, 0x4f, 0xd8, 0x43, 0x48, 0xfe, 0x4a, 0x48, 0x0e, 0x15, 0x09, 0x44,
0x1a, 0x39, 0x0f, 0x11, 0x4d, 0x08, 0x21, 0x21, 0x61, 0x8c, 0x42, 0xa4,
0x91, 0x1c, 0xbd, 0x83, 0x86, 0xcb, 0x9f, 0xb0, 0x87, 0x90, 0xfc, 0x95,
0x90, 0x36, 0xa4, 0x19, 0x10, 0x31, 0xc6, 0x38, 0x73, 0x04, 0x41, 0x29,
0xd2, 0x88, 0x43, 0xd2, 0x1c, 0x08, 0x38, 0x4d, 0x9a, 0x22, 0x4a, 0x98,
0xfc, 0x15, 0xde, 0xb0, 0x89, 0xd0, 0x86, 0x21, 0x22, 0x24, 0x69, 0xa3,
0x8a, 0x82, 0x88, 0x50, 0x30, 0xc8, 0x02, 0x00, 0x13, 0x14, 0x72, 0xc0,
0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79, 0x68, 0x03, 0x72, 0xc0,
0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d,
0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73,
0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07, 0x7a, 0x60, 0x07, 0x74,
0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6,
0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78,
0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x76,
0x40, 0x07, 0x43, 0x9e, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x14, 0x20, 0x00, 0x04, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x30, 0x40, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4, 0x79, 0x80, 0x00, 0x08,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc8, 0x33, 0x01, 0x01,
0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x16, 0x08, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14, 0x19, 0x11, 0x4c, 0x90,
0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a, 0x25, 0x50, 0x0c, 0x23,
0x00, 0x65, 0x51, 0x06, 0x85, 0x50, 0x80, 0x01, 0x45, 0x50, 0x2a, 0x64,
0x0a, 0x14, 0x10, 0x30, 0x80, 0xe4, 0x08, 0x00, 0xdd, 0x19, 0x00, 0x00,
0x79, 0x18, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90,
0x46, 0x02, 0x13, 0xc4, 0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24,
0xc6, 0x25, 0xc7, 0x45, 0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05,
0x26, 0x46, 0xcc, 0x46, 0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10,
0x4c, 0x10, 0x06, 0x63, 0x82, 0x30, 0x1c, 0x1b, 0x84, 0x81, 0x98, 0x20,
0x0c, 0xc8, 0x06, 0xc1, 0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82,
0x98, 0x20, 0x5c, 0x11, 0x07, 0xa1, 0x3a, 0xb3, 0x09, 0xc2, 0x90, 0x4c,
0x10, 0x24, 0x68, 0x82, 0x30, 0x28, 0x1b, 0x04, 0x67, 0xd8, 0xb0, 0x18,
0xca, 0x62, 0x18, 0x03, 0xd3, 0x34, 0xcd, 0xb3, 0x21, 0x80, 0x36, 0x10,
0x40, 0x04, 0x00, 0x13, 0x04, 0x01, 0xd8, 0x00, 0x6c, 0x18, 0x0c, 0x8a,
0xda, 0x10, 0x54, 0x1b, 0x86, 0x61, 0xb2, 0x48, 0xb4, 0x85, 0xa5, 0xb9,
0x4d, 0x10, 0x8c, 0x67, 0x82, 0x30, 0x2c, 0x13, 0x84, 0x81, 0xd9, 0x30,
0x6c, 0xc3, 0xb0, 0x81, 0x30, 0x32, 0x8d, 0xdb, 0x50, 0x4c, 0x18, 0x20,
0x75, 0x34, 0xc2, 0xe8, 0xde, 0xda, 0xd2, 0xc6, 0x26, 0x08, 0x43, 0xc3,
0x22, 0xcd, 0x6d, 0x8e, 0x6e, 0x6e, 0x82, 0x30, 0x38, 0x24, 0xd2, 0xdc,
0xe8, 0xe6, 0x98, 0xd0, 0x95, 0xe1, 0x7d, 0xcd, 0xd1, 0xbd, 0xc9, 0x95,
0xb1, 0xa8, 0x4b, 0x73, 0xa3, 0x9b, 0xdb, 0xa0, 0x7c, 0x60, 0x10, 0x06,
0x62, 0x30, 0x06, 0x03, 0x19, 0x0c, 0x65, 0xc0, 0x54, 0x61, 0x63, 0xb3,
0x6b, 0x73, 0x49, 0x23, 0x2b, 0x73, 0xa3, 0x9b, 0x12, 0x04, 0x55, 0xc8,
0xf0, 0x5c, 0xec, 0xca, 0xe4, 0xe6, 0xd2, 0xde, 0xdc, 0xa6, 0x04, 0x44,
0x13, 0x32, 0x3c, 0x17, 0xbb, 0x30, 0x36, 0xbb, 0x32, 0xb9, 0x29, 0x81,
0x51, 0x87, 0x0c, 0xcf, 0x65, 0x0e, 0x2d, 0x8c, 0xac, 0x4c, 0xae, 0xe9,
0x8d, 0xac, 0x8c, 0x6d, 0x4a, 0x80, 0x94, 0x21, 0xc3, 0x73, 0x91, 0x2b,
0x9b, 0x7b, 0xab, 0x93, 0x1b, 0x2b, 0x9b, 0x9b, 0x12, 0x44, 0x95, 0xc8,
0xf0, 0x5c, 0xe8, 0xf2, 0xe0, 0xca, 0x82, 0xdc, 0xdc, 0xde, 0xe8, 0xc2,
0xe8, 0xd2, 0xde, 0xdc, 0xe6, 0xa6, 0x04, 0x56, 0x1d, 0x32, 0x3c, 0x97,
0x32, 0x37, 0x3a, 0xb9, 0x3c, 0xa8, 0xb7, 0x34, 0x37, 0xba, 0xb9, 0x29,
0x41, 0xd7, 0x85, 0x0c, 0xcf, 0x65, 0xec, 0xad, 0xce, 0x8d, 0xae, 0x4c,
0x6e, 0x6e, 0x4a, 0x50, 0x06, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66,
0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07,
0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10,
0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce,
0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b,
0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c,
0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07,
0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11,
0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0,
0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8,
0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b,
0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b,
0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87,
0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07,
0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87,
0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81,
0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30,
0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4,
0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca,
0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39,
0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b,
0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b,
0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87,
0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20,
0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90,
0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00, 0x00, 0x00, 0x71, 0x20, 0x00, 0x00,
0x1a, 0x00, 0x00, 0x00, 0x46, 0x40, 0x0d, 0x97, 0xef, 0x3c, 0x3e, 0xd0,
0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3, 0x42, 0x98, 0x40, 0x35,
0x5c, 0xbe, 0xf3, 0xf8, 0xc0, 0xe4, 0x30, 0x88, 0xb0, 0x21, 0x0d, 0xfa,
0xf8, 0x88, 0x8e, 0x5b, 0x41, 0x37, 0x5c, 0xbe, 0xf3, 0xf8, 0x42, 0x44,
0x00, 0x13, 0x11, 0x02, 0xcd, 0xb0, 0x10, 0x5f, 0xe4, 0x30, 0x1b, 0xd2,
0x0c, 0x48, 0x63, 0xd8, 0x00, 0x36, 0x5c, 0xbe, 0xf3, 0xf8, 0x11, 0x60,
0x6d, 0x54, 0x51, 0x10, 0x11, 0x3b, 0x39, 0x11, 0xe1, 0x23, 0xb7, 0x6d,
0x01, 0xd2, 0x70, 0xf9, 0xce, 0xe3, 0x4f, 0x47, 0x44, 0x00, 0x83, 0x38,
0xf8, 0xc8, 0x6d, 0x1b, 0x00, 0xc1, 0x00, 0x48, 0x03, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x41, 0x53, 0x48, 0x14, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x19, 0x0f, 0xd6, 0x81, 0xa6, 0xfd, 0xc8, 0x15,
0x61, 0x13, 0x2f, 0x9a, 0x2e, 0x60, 0xb0, 0x0c, 0x44, 0x58, 0x49, 0x4c,
0xe0, 0x05, 0x00, 0x00, 0x66, 0x00, 0x05, 0x00, 0x78, 0x01, 0x00, 0x00,
0x44, 0x58, 0x49, 0x4c, 0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0xc8, 0x05, 0x00, 0x00, 0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00,
0x6f, 0x01, 0x00, 0x00, 0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49,
0x06, 0x10, 0x32, 0x39, 0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19,
0x1e, 0x04, 0x8b, 0x62, 0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42,
0xa4, 0x10, 0x32, 0x14, 0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88,
0x48, 0x90, 0x14, 0x20, 0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42,
0xe4, 0x48, 0x0e, 0x90, 0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c,
0xe1, 0x83, 0xe5, 0x8a, 0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07,
0x40, 0x02, 0xa8, 0x0d, 0x84, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20,
0x01, 0x00, 0x00, 0x00, 0x49, 0x18, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x13, 0x82, 0x60, 0x42, 0x20, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00,
0x29, 0x00, 0x00, 0x00, 0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04,
0x93, 0x22, 0xa4, 0x84, 0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14,
0x12, 0x4c, 0x8a, 0x8c, 0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00,
0x25, 0x00, 0x14, 0xe6, 0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x73,
0x04, 0xa0, 0x30, 0x47, 0x80, 0xd0, 0xb9, 0x67, 0xb8, 0xfc, 0x09, 0x7b,
0x08, 0xc9, 0x0f, 0x81, 0x66, 0x58, 0x08, 0x14, 0xa0, 0x82, 0x98, 0x91,
0xc6, 0x18, 0xc3, 0x90, 0x2a, 0x0b, 0x18, 0x69, 0x8c, 0x31, 0xc6, 0x38,
0x83, 0xd8, 0x6d, 0xc3, 0xe5, 0x4f, 0xd8, 0x43, 0x48, 0xfe, 0x4a, 0x48,
0x0e, 0x15, 0x09, 0x44, 0x1a, 0x39, 0x0f, 0x11, 0x4d, 0x08, 0x21, 0x21,
0x61, 0x8c, 0x42, 0xa4, 0x91, 0x1c, 0xbd, 0x83, 0x86, 0xcb, 0x9f, 0xb0,
0x87, 0x90, 0xfc, 0x95, 0x90, 0x36, 0xa4, 0x19, 0x10, 0x31, 0xc6, 0x38,
0x73, 0x04, 0x41, 0x29, 0xd2, 0x88, 0x43, 0xd2, 0x1c, 0x08, 0x38, 0x4d,
0x9a, 0x22, 0x4a, 0x98, 0xfc, 0x15, 0xde, 0xb0, 0x89, 0xd0, 0x86, 0x21,
0x22, 0x24, 0x69, 0xa3, 0x8a, 0x82, 0x88, 0x50, 0x30, 0xc8, 0x02, 0x00,
0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79,
0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e,
0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07,
0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e,
0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07,
0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07,
0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x14, 0x20,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x30,
0x40, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4,
0x79, 0x80, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60,
0xc8, 0x33, 0x01, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x16, 0x08, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14,
0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a,
0x25, 0x50, 0x0c, 0x25, 0x31, 0x02, 0x50, 0x16, 0x65, 0x50, 0x08, 0x05,
0x18, 0x40, 0xa6, 0x40, 0x01, 0x01, 0x03, 0x48, 0x8e, 0x00, 0xd0, 0x9d,
0x01, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x00,
0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4, 0x8e, 0x0c, 0x6f, 0xec,
0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45, 0xc6, 0x06, 0x26, 0xc7,
0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46, 0x26, 0x8c, 0x8c, 0xe6,
0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x06, 0x63, 0x82, 0x30, 0x1c, 0x1b,
0x84, 0x81, 0x98, 0x20, 0x0c, 0xc8, 0x06, 0x61, 0x30, 0x28, 0x8c, 0xcd,
0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x0c, 0xc9, 0x04, 0xe1, 0x82, 0x08,
0x4c, 0x10, 0x06, 0x65, 0x82, 0x20, 0x3d, 0x13, 0x84, 0x61, 0xd9, 0x20,
0x3c, 0xc3, 0x86, 0x45, 0x59, 0x18, 0x45, 0x19, 0x1a, 0xc7, 0x71, 0xa0,
0x0d, 0x41, 0xb4, 0x81, 0x00, 0x24, 0x00, 0x98, 0x20, 0x08, 0x00, 0x89,
0xb6, 0xb0, 0x34, 0xb7, 0x09, 0x82, 0xe1, 0x4c, 0x10, 0x06, 0x66, 0x82,
0x30, 0x34, 0x1b, 0x06, 0x6c, 0x18, 0x36, 0x10, 0x8a, 0x75, 0x65, 0x1b,
0x0a, 0xaa, 0x02, 0x26, 0xad, 0x0a, 0x1b, 0x9b, 0x5d, 0x9b, 0x4b, 0x1a,
0x59, 0x99, 0x1b, 0xdd, 0x94, 0x20, 0xa8, 0x42, 0x86, 0xe7, 0x62, 0x57,
0x26, 0x37, 0x97, 0xf6, 0xe6, 0x36, 0x25, 0x20, 0x9a, 0x90, 0xe1, 0xb9,
0xd8, 0x85, 0xb1, 0xd9, 0x95, 0xc9, 0x4d, 0x09, 0x8c, 0x3a, 0x64, 0x78,
0x2e, 0x73, 0x68, 0x61, 0x64, 0x65, 0x72, 0x4d, 0x6f, 0x64, 0x65, 0x6c,
0x53, 0x02, 0xa4, 0x0c, 0x19, 0x9e, 0x8b, 0x5c, 0xd9, 0xdc, 0x5b, 0x9d,
0xdc, 0x58, 0xd9, 0xdc, 0x94, 0x40, 0xaa, 0x43, 0x86, 0xe7, 0x52, 0xe6,
0x46, 0x27, 0x97, 0x07, 0xf5, 0x96, 0xe6, 0x46, 0x37, 0x37, 0x25, 0xd0,
0x00, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00,
0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88,
0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73,
0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e,
0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30,
0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8,
0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b,
0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76,
0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e,
0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e,
0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61,
0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4,
0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76,
0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37,
0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76,
0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71,
0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e,
0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1,
0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61,
0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90,
0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8,
0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc,
0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4,
0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19,
0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06,
0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f,
0xf4, 0x00, 0x00, 0x00, 0x71, 0x20, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00,
0x46, 0x40, 0x0d, 0x97, 0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c,
0x44, 0x08, 0x34, 0xc3, 0x42, 0x98, 0x40, 0x35, 0x5c, 0xbe, 0xf3, 0xf8,
0xc0, 0xe4, 0x30, 0x88, 0xb0, 0x21, 0x0d, 0xfa, 0xf8, 0x88, 0x8e, 0x5b,
0x41, 0x37, 0x5c, 0xbe, 0xf3, 0xf8, 0x42, 0x44, 0x00, 0x13, 0x11, 0x02,
0xcd, 0xb0, 0x10, 0x5f, 0xe4, 0x30, 0x1b, 0xd2, 0x0c, 0x48, 0x63, 0xd8,
0x00, 0x36, 0x5c, 0xbe, 0xf3, 0xf8, 0x11, 0x60, 0x6d, 0x54, 0x51, 0x10,
0x11, 0x3b, 0x39, 0x11, 0xe1, 0x23, 0xb7, 0x6d, 0x01, 0xd2, 0x70, 0xf9,
0xce, 0xe3, 0x4f, 0x47, 0x44, 0x00, 0x83, 0x38, 0xf8, 0xc8, 0x6d, 0x1b,
0x00, 0xc1, 0x00, 0x48, 0x03, 0x00, 0x00, 0x00, 0x61, 0x20, 0x00, 0x00,
0x36, 0x00, 0x00, 0x00, 0x13, 0x04, 0x41, 0x2c, 0x10, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x34, 0x66, 0x00, 0x0a, 0x76, 0xa0, 0x1c, 0x8a,
0x33, 0xa0, 0x64, 0x07, 0x4a, 0x37, 0xa0, 0x02, 0x01, 0x01, 0x01, 0x05,
0xca, 0x12, 0xa8, 0x06, 0x0a, 0x50, 0xa0, 0x30, 0x05, 0x8a, 0x77, 0xd0,
0x80, 0x4c, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x82, 0x14,
0x14, 0x9d, 0x12, 0x28, 0x03, 0x72, 0x73, 0x08, 0x58, 0x42, 0x71, 0x0e,
0x22, 0x49, 0x92, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x23, 0x06, 0x08, 0x00,
0x82, 0x60, 0x30, 0x79, 0x4e, 0xa0, 0x51, 0x23, 0x06, 0x06, 0x00, 0x82,
0x60, 0x40, 0x8c, 0x81, 0xb3, 0x55, 0x20, 0x69, 0x09, 0x0f, 0x5c, 0x60,
0xa2, 0x82, 0x65, 0x8d, 0xf0, 0x6e, 0x30, 0x62, 0x70, 0x00, 0x20, 0x08,
0x06, 0x8f, 0x19, 0x60, 0x47, 0x32, 0x62, 0xb0, 0x00, 0x20, 0x08, 0x06,
0x4a, 0x1a, 0x5c, 0x81, 0x18, 0x08, 0x9a, 0x36, 0x1c, 0x62, 0xa2, 0x82,
0xe7, 0x4a, 0xa9, 0xf8, 0x02, 0x13, 0x35, 0x04, 0x5b, 0x08, 0x19, 0xec,
0x88, 0xc1, 0x01, 0x80, 0x20, 0x18, 0x3c, 0x6e, 0x00, 0x06, 0x4f, 0x34,
0x62, 0xb0, 0x00, 0x20, 0x08, 0x06, 0x4a, 0x1c, 0x7c, 0x01, 0x18, 0x08,
0x62, 0x20, 0x06, 0x43, 0x2d, 0xda, 0x8e, 0x18, 0x1c, 0x00, 0x08, 0x82,
0xc1, 0x13, 0x07, 0x63, 0x20, 0x51, 0x23, 0x06, 0x0e, 0x00, 0x82, 0x60,
0xc0, 0xcc, 0xc1, 0x16, 0x08, 0x65, 0x10, 0x69, 0x65, 0x50, 0x06, 0x96,
0x1a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// #453: control for atomic64_image.hlsl. The same operations on a raw buffer
// (RWByteAddressBuffer::InterlockedAdd64 / InterlockedMax64), so a failure of
// the typed form can be told apart from 64-bit atomics failing everywhere.
// Layout: 8 add slots, 8 max slots, then 8 plain-store marker slots, 8 bytes each.
RWByteAddressBuffer Buf : register(u0);
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
uint px = id.x & 7u;
uint64_t add = (uint64_t(0x10000000u) << 32) | uint64_t(0xF0000000u + id.x);
Buf.InterlockedAdd64(px * 8u, add);
uint64_t m = (uint64_t(id.x) << 40) | uint64_t(0xFFFFFFFFu - id.x);
Buf.InterlockedMax64(64u + px * 8u, m);
Buf.Store2(128u + px * 8u, uint2(px, 0xC0DEu));
}
@@ -0,0 +1,391 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// GENERATED by DXC 1.9.2609 from atomic64_image.hlsl by compile.sh; do not edit.
#if 0
;
; Note: shader requires additional functionality:
; 64-Bit integer
; 64-bit Atomics on Typed Resources
;
;
; Input signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
;
; Output signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
; shader hash: 659a63357ea7f50fffd00a1792de5b68
;
; Pipeline Runtime Information:
;
;PSVRuntimeInfo:
; Compute Shader
; NumThreads=(64,1,1)
; MinimumExpectedWaveLaneCount: 0
; MaximumExpectedWaveLaneCount: 4294967295
; UsesViewID: false
; SigInputElements: 0
; SigOutputElements: 0
; SigPatchConstOrPrimElements: 0
; SigInputVectors: 0
; SigOutputVectors[0]: 0
; SigOutputVectors[1]: 0
; SigOutputVectors[2]: 0
; SigOutputVectors[3]: 0
; EntryFunctionName: main
;
;
; Buffer Definitions:
;
;
; Resource Bindings:
;
; Name Type Format Dim ID HLSL Bind Count
; ------------------------------ ---------- ------- ----------- ------- -------------- ------
; Img UAV u32 2d U0 u0 1
;
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
%dx.types.Handle = type { i8* }
%dx.types.ResBind = type { i32, i32, i32, i8 }
%dx.types.ResourceProperties = type { i32, i32 }
%"class.RWTexture2D<unsigned long long>" = type { i64 }
define void @main() {
%1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 0, i32 0, i32 0, i8 1 }, i32 0, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%2 = call i32 @dx.op.threadId.i32(i32 93, i32 0) ; ThreadId(component)
%3 = and i32 %2, 7
%4 = add i32 %2, -268435456
%5 = zext i32 %4 to i64
%6 = or i64 %5, 1152921504606846976
%7 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4098, i32 261 }) ; AnnotateHandle(res,props) resource: RWTexture2D<U32>
%8 = call i64 @dx.op.atomicBinOp.i64(i32 78, %dx.types.Handle %7, i32 0, i32 %3, i32 0, i32 undef, i64 %6) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
%9 = zext i32 %2 to i64
%10 = shl i64 %9, 40
%11 = xor i32 %2, -1
%12 = zext i32 %11 to i64
%13 = or i64 %10, %12
%14 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4098, i32 261 }) ; AnnotateHandle(res,props) resource: RWTexture2D<U32>
%15 = call i64 @dx.op.atomicBinOp.i64(i32 78, %dx.types.Handle %14, i32 7, i32 %3, i32 1, i32 undef, i64 %13) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
%16 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4098, i32 261 }) ; AnnotateHandle(res,props) resource: RWTexture2D<U32>
call void @dx.op.textureStore.i32(i32 67, %dx.types.Handle %16, i32 %3, i32 2, i32 undef, i32 %3, i32 49374, i32 %3, i32 49374, i8 15) ; TextureStore(srv,coord0,coord1,coord2,value0,value1,value2,value3,mask)
ret void
}
; Function Attrs: nounwind readnone
declare i32 @dx.op.threadId.i32(i32, i32) #0
; Function Attrs: nounwind
declare i64 @dx.op.atomicBinOp.i64(i32, %dx.types.Handle, i32, i32, i32, i32, i64) #1
; Function Attrs: nounwind
declare void @dx.op.textureStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i32, i8) #1
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0
attributes #0 = { nounwind readnone }
attributes #1 = { nounwind }
!llvm.ident = !{!0}
!dx.version = !{!1}
!dx.valver = !{!2}
!dx.shaderModel = !{!3}
!dx.resources = !{!4}
!dx.entryPoints = !{!8}
!0 = !{!"dxcoob 1.9.2609.5 (01b62ad47)"}
!1 = !{i32 1, i32 6}
!2 = !{i32 1, i32 9}
!3 = !{!"cs", i32 6, i32 6}
!4 = !{null, !5, null, null}
!5 = !{!6}
!6 = !{i32 0, %"class.RWTexture2D<unsigned long long>"* undef, !"", i32 0, i32 0, i32 1, i32 2, i1 false, i1 false, i1 false, !7}
!7 = !{i32 0, i32 5, i32 3, i32 1}
!8 = !{void ()* @main, !"main", null, !4, !9}
!9 = !{i32 0, i64 135266304, i32 4, !10}
!10 = !{i32 64, i32 1, i32 1}
#endif
const unsigned char g_atomic64_image_cs[] = {
0x44, 0x58, 0x42, 0x43, 0xfe, 0x59, 0x2d, 0xd5, 0xc7, 0xff, 0x0b, 0xbd,
0xc9, 0xaa, 0xb8, 0x78, 0x82, 0xae, 0x4f, 0x26, 0x01, 0x00, 0x00, 0x00,
0x9c, 0x0c, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00,
0xdc, 0x00, 0x00, 0x00, 0x78, 0x06, 0x00, 0x00, 0x94, 0x06, 0x00, 0x00,
0x53, 0x46, 0x49, 0x30, 0x08, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x00,
0x00, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x31, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x4f, 0x53, 0x47, 0x31,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x50, 0x53, 0x56, 0x30, 0x68, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x53, 0x54, 0x41, 0x54, 0x94, 0x05, 0x00, 0x00,
0x66, 0x00, 0x05, 0x00, 0x65, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x7c, 0x05, 0x00, 0x00,
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x5c, 0x01, 0x00, 0x00,
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xa4, 0x10, 0x32, 0x14,
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88, 0x48, 0x90, 0x14, 0x20,
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
0x84, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x01, 0x00, 0x00, 0x00,
0x49, 0x18, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42,
0x20, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00,
0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04, 0x93, 0x22, 0xa4, 0x84,
0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8a, 0x8c,
0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00, 0x25, 0x00, 0x14, 0xe6,
0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x73, 0x04, 0xa0, 0x30, 0x47,
0x80, 0xd0, 0xb9, 0x67, 0xb8, 0xfc, 0x09, 0x7b, 0x08, 0xc9, 0x0f, 0x81,
0x66, 0x58, 0x08, 0x14, 0xa0, 0x82, 0x98, 0x91, 0xc6, 0x18, 0xc3, 0x90,
0x2a, 0x0b, 0x18, 0x69, 0x8c, 0x31, 0xc6, 0x18, 0x87, 0xd8, 0x6d, 0xc3,
0xe5, 0x4f, 0xd8, 0x43, 0x48, 0xfe, 0x4a, 0x48, 0x0e, 0x15, 0x09, 0x44,
0x1a, 0x39, 0x0f, 0x11, 0x4d, 0x08, 0x21, 0x21, 0x61, 0x8c, 0x42, 0xa4,
0x91, 0x1c, 0xbd, 0x83, 0x86, 0xcb, 0x9f, 0xb0, 0x87, 0x90, 0xfc, 0x95,
0x90, 0x36, 0xa4, 0x19, 0x10, 0x31, 0xc6, 0x38, 0x73, 0x04, 0x41, 0x29,
0xd2, 0x88, 0x43, 0xd2, 0x1c, 0x08, 0x98, 0xa9, 0x0c, 0xc6, 0x81, 0x1d,
0xc2, 0x61, 0x1e, 0xe6, 0xc1, 0x0d, 0x64, 0xe1, 0x16, 0x68, 0xa1, 0x1c,
0xf0, 0x81, 0x1e, 0xea, 0x41, 0x1e, 0xca, 0x41, 0x0e, 0x48, 0x81, 0x0f,
0xea, 0xc1, 0x1d, 0xe6, 0x21, 0x1d, 0xce, 0xc1, 0x1d, 0xca, 0x81, 0x1c,
0xc0, 0x80, 0x1d, 0xde, 0xc1, 0x1d, 0xce, 0x01, 0x0c, 0xd8, 0xe1, 0x1d,
0xdc, 0xe1, 0x1c, 0xfc, 0x00, 0x05, 0x86, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79,
0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e,
0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07,
0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e,
0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07,
0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07,
0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x14, 0x20,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x30,
0x40, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4,
0x79, 0x80, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60,
0xc8, 0x33, 0x01, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x16, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14,
0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a,
0x25, 0x50, 0x0c, 0x23, 0x00, 0x45, 0x50, 0x0a, 0x65, 0x50, 0x08, 0x05,
0x18, 0x50, 0x24, 0x05, 0x41, 0xa6, 0x00, 0x01, 0x01, 0x03, 0x03, 0x48,
0x8e, 0x00, 0xd0, 0x9d, 0x01, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
0x55, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4,
0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45,
0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46,
0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x06, 0x63,
0x82, 0x30, 0x1c, 0x1b, 0x84, 0x81, 0x98, 0x20, 0x0c, 0xc8, 0x06, 0xc1,
0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x5c, 0x12,
0x87, 0xa4, 0xb6, 0xb3, 0x09, 0xc2, 0x90, 0x4c, 0x10, 0xa4, 0x68, 0x82,
0x30, 0x28, 0x13, 0x84, 0x61, 0xd9, 0x40, 0x18, 0xce, 0x33, 0x6c, 0x58,
0x0c, 0x65, 0x31, 0x8c, 0x81, 0x69, 0x9a, 0x06, 0xda, 0x10, 0x44, 0x1b,
0x08, 0x40, 0x02, 0x80, 0x09, 0x82, 0x00, 0x6c, 0x00, 0x36, 0x0c, 0x46,
0x55, 0x6d, 0x08, 0xac, 0x0d, 0xc3, 0x40, 0x5d, 0x24, 0xda, 0xc2, 0xd2,
0xdc, 0x26, 0x08, 0x06, 0x34, 0x41, 0x18, 0x98, 0x09, 0xc2, 0xd0, 0x6c,
0x18, 0xb8, 0x61, 0xd8, 0x40, 0x18, 0xda, 0xd6, 0x6d, 0x28, 0xa8, 0x0c,
0x98, 0x3c, 0x1a, 0x61, 0x74, 0x6f, 0x6d, 0x69, 0x63, 0x2c, 0xd2, 0xdc,
0xe6, 0xe8, 0xe6, 0x26, 0x08, 0x83, 0x43, 0x22, 0xcd, 0x8d, 0x6e, 0x8e,
0x09, 0x5d, 0x19, 0xde, 0xd7, 0x1c, 0xdd, 0x9b, 0x5c, 0x19, 0x8b, 0xba,
0x34, 0x37, 0xba, 0xb9, 0x09, 0xc2, 0xf0, 0x6c, 0x50, 0xc0, 0x80, 0x09,
0x03, 0x31, 0x18, 0x83, 0x81, 0x0c, 0x86, 0x32, 0x30, 0x83, 0x2a, 0x6c,
0x6c, 0x76, 0x6d, 0x2e, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x53, 0x82, 0xa0,
0x0a, 0x19, 0x9e, 0x8b, 0x5d, 0x99, 0xdc, 0x5c, 0xda, 0x9b, 0xdb, 0x94,
0x80, 0x68, 0x42, 0x86, 0xe7, 0x62, 0x17, 0xc6, 0x66, 0x57, 0x26, 0x37,
0x25, 0x30, 0xea, 0x90, 0xe1, 0xb9, 0xcc, 0xa1, 0x85, 0x91, 0x95, 0xc9,
0x35, 0xbd, 0x91, 0x95, 0xb1, 0x4d, 0x09, 0x90, 0x32, 0x64, 0x78, 0x2e,
0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x53, 0x02, 0xa9,
0x12, 0x19, 0x9e, 0x0b, 0x5d, 0x1e, 0x5c, 0x59, 0x90, 0x9b, 0xdb, 0x1b,
0x5d, 0x18, 0x5d, 0xda, 0x9b, 0xdb, 0xdc, 0x94, 0xe0, 0xaa, 0x43, 0x86,
0xe7, 0x52, 0xe6, 0x46, 0x27, 0x97, 0x07, 0xf5, 0x96, 0xe6, 0x46, 0x37,
0x37, 0x25, 0xf0, 0xba, 0x90, 0xe1, 0xb9, 0x8c, 0xbd, 0xd5, 0xb9, 0xd1,
0x95, 0xc9, 0xcd, 0x4d, 0x09, 0xcc, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66,
0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07,
0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10,
0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce,
0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b,
0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c,
0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07,
0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11,
0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0,
0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8,
0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b,
0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b,
0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87,
0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07,
0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87,
0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81,
0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30,
0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4,
0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca,
0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39,
0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b,
0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b,
0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87,
0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20,
0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90,
0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00, 0x00, 0x00, 0x71, 0x20, 0x00, 0x00,
0x19, 0x00, 0x00, 0x00, 0x46, 0x40, 0x0d, 0x97, 0xef, 0x3c, 0x3e, 0xd0,
0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3, 0x42, 0x98, 0x40, 0x35,
0x5c, 0xbe, 0xf3, 0xf8, 0xc0, 0xe4, 0x30, 0x88, 0xb0, 0x21, 0x0d, 0xfa,
0xf8, 0x88, 0x8e, 0x5b, 0x41, 0x37, 0x5c, 0xbe, 0xf3, 0xf8, 0x42, 0x44,
0x00, 0x13, 0x11, 0x02, 0xcd, 0xb0, 0x10, 0x5f, 0xe4, 0x30, 0x1b, 0xd2,
0x0c, 0x48, 0x63, 0xd8, 0x80, 0x35, 0x5c, 0xbe, 0xf3, 0xf8, 0x13, 0x71,
0x4d, 0x54, 0x44, 0xb0, 0x93, 0x13, 0x11, 0x3e, 0x72, 0xdb, 0x16, 0x20,
0x0d, 0x97, 0xef, 0x3c, 0xfe, 0x74, 0x44, 0x04, 0x30, 0x88, 0x83, 0x8f,
0xdc, 0xb6, 0x01, 0x10, 0x0c, 0x80, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x41, 0x53, 0x48, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x65, 0x9a, 0x63, 0x35, 0x7e, 0xa7, 0xf5, 0x0f, 0xff, 0xd0, 0x0a, 0x17,
0x92, 0xde, 0x5b, 0x68, 0x44, 0x58, 0x49, 0x4c, 0x00, 0x06, 0x00, 0x00,
0x66, 0x00, 0x05, 0x00, 0x80, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xe8, 0x05, 0x00, 0x00,
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x77, 0x01, 0x00, 0x00,
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xa4, 0x10, 0x32, 0x14,
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88, 0x48, 0x90, 0x14, 0x20,
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
0x84, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x01, 0x00, 0x00, 0x00,
0x49, 0x18, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42,
0x20, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00,
0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04, 0x93, 0x22, 0xa4, 0x84,
0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8a, 0x8c,
0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00, 0x25, 0x00, 0x14, 0xe6,
0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x73, 0x04, 0xa0, 0x30, 0x47,
0x80, 0xd0, 0xb9, 0x67, 0xb8, 0xfc, 0x09, 0x7b, 0x08, 0xc9, 0x0f, 0x81,
0x66, 0x58, 0x08, 0x14, 0xa0, 0x82, 0x98, 0x91, 0xc6, 0x18, 0xc3, 0x90,
0x2a, 0x0b, 0x18, 0x69, 0x8c, 0x31, 0xc6, 0x18, 0x87, 0xd8, 0x6d, 0xc3,
0xe5, 0x4f, 0xd8, 0x43, 0x48, 0xfe, 0x4a, 0x48, 0x0e, 0x15, 0x09, 0x44,
0x1a, 0x39, 0x0f, 0x11, 0x4d, 0x08, 0x21, 0x21, 0x61, 0x8c, 0x42, 0xa4,
0x91, 0x1c, 0xbd, 0x83, 0x86, 0xcb, 0x9f, 0xb0, 0x87, 0x90, 0xfc, 0x95,
0x90, 0x36, 0xa4, 0x19, 0x10, 0x31, 0xc6, 0x38, 0x73, 0x04, 0x41, 0x29,
0xd2, 0x88, 0x43, 0xd2, 0x1c, 0x08, 0x98, 0xa9, 0x0c, 0xc6, 0x81, 0x1d,
0xc2, 0x61, 0x1e, 0xe6, 0xc1, 0x0d, 0x64, 0xe1, 0x16, 0x68, 0xa1, 0x1c,
0xf0, 0x81, 0x1e, 0xea, 0x41, 0x1e, 0xca, 0x41, 0x0e, 0x48, 0x81, 0x0f,
0xea, 0xc1, 0x1d, 0xe6, 0x21, 0x1d, 0xce, 0xc1, 0x1d, 0xca, 0x81, 0x1c,
0xc0, 0x80, 0x1d, 0xde, 0xc1, 0x1d, 0xce, 0x01, 0x0c, 0xd8, 0xe1, 0x1d,
0xdc, 0xe1, 0x1c, 0xfc, 0x00, 0x05, 0x86, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79,
0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e,
0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07,
0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e,
0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07,
0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07,
0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x14, 0x20,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x30,
0x40, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4,
0x79, 0x80, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60,
0xc8, 0x33, 0x01, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x16, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14,
0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a,
0x25, 0x50, 0x0c, 0x25, 0x31, 0x02, 0x50, 0x04, 0xa5, 0x50, 0x06, 0x85,
0x50, 0x80, 0x01, 0x64, 0x0a, 0x10, 0x10, 0x30, 0x30, 0x80, 0xe4, 0x08,
0x00, 0xdd, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
0x3b, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4,
0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45,
0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46,
0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x06, 0x63,
0x82, 0x30, 0x1c, 0x1b, 0x84, 0x81, 0x98, 0x20, 0x0c, 0xc8, 0x06, 0x61,
0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x0c, 0xc9,
0x04, 0xe1, 0x8a, 0x08, 0x4c, 0x10, 0x06, 0x65, 0x82, 0x20, 0x41, 0x13,
0x84, 0x61, 0x99, 0x20, 0x0c, 0xcc, 0x06, 0x42, 0x79, 0xa0, 0x61, 0xc3,
0xa2, 0x2c, 0x8c, 0xa2, 0x0c, 0x8d, 0xe3, 0x38, 0xd1, 0x86, 0x40, 0xda,
0x40, 0x00, 0x13, 0x00, 0x4c, 0x10, 0x04, 0x80, 0x44, 0x5b, 0x58, 0x9a,
0xdb, 0x04, 0xc1, 0x78, 0x26, 0x08, 0x43, 0x33, 0x41, 0x18, 0x9c, 0x0d,
0x43, 0x36, 0x0c, 0x1b, 0x08, 0xe5, 0xc2, 0xb4, 0x0d, 0x45, 0x65, 0x01,
0xd4, 0x56, 0x85, 0x8d, 0xcd, 0xae, 0xcd, 0x25, 0x8d, 0xac, 0xcc, 0x8d,
0x6e, 0x4a, 0x10, 0x54, 0x21, 0xc3, 0x73, 0xb1, 0x2b, 0x93, 0x9b, 0x4b,
0x7b, 0x73, 0x9b, 0x12, 0x10, 0x4d, 0xc8, 0xf0, 0x5c, 0xec, 0xc2, 0xd8,
0xec, 0xca, 0xe4, 0xa6, 0x04, 0x46, 0x1d, 0x32, 0x3c, 0x97, 0x39, 0xb4,
0x30, 0xb2, 0x32, 0xb9, 0xa6, 0x37, 0xb2, 0x32, 0xb6, 0x29, 0x01, 0x52,
0x86, 0x0c, 0xcf, 0x45, 0xae, 0x6c, 0xee, 0xad, 0x4e, 0x6e, 0xac, 0x6c,
0x6e, 0x4a, 0x30, 0xd5, 0x21, 0xc3, 0x73, 0x29, 0x73, 0xa3, 0x93, 0xcb,
0x83, 0x7a, 0x4b, 0x73, 0xa3, 0x9b, 0x9b, 0x12, 0x6c, 0x00, 0x00, 0x00,
0x79, 0x18, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c,
0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3,
0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6,
0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e,
0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43,
0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03,
0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48,
0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20,
0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e,
0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d,
0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89,
0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83,
0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68,
0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90,
0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78,
0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98,
0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5,
0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c,
0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c,
0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43,
0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43,
0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82,
0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70,
0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8,
0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2,
0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00, 0x00, 0x00,
0x71, 0x20, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x46, 0x40, 0x0d, 0x97,
0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3,
0x42, 0x98, 0x40, 0x35, 0x5c, 0xbe, 0xf3, 0xf8, 0xc0, 0xe4, 0x30, 0x88,
0xb0, 0x21, 0x0d, 0xfa, 0xf8, 0x88, 0x8e, 0x5b, 0x41, 0x37, 0x5c, 0xbe,
0xf3, 0xf8, 0x42, 0x44, 0x00, 0x13, 0x11, 0x02, 0xcd, 0xb0, 0x10, 0x5f,
0xe4, 0x30, 0x1b, 0xd2, 0x0c, 0x48, 0x63, 0xd8, 0x80, 0x35, 0x5c, 0xbe,
0xf3, 0xf8, 0x13, 0x71, 0x4d, 0x54, 0x44, 0xb0, 0x93, 0x13, 0x11, 0x3e,
0x72, 0xdb, 0x16, 0x20, 0x0d, 0x97, 0xef, 0x3c, 0xfe, 0x74, 0x44, 0x04,
0x30, 0x88, 0x83, 0x8f, 0xdc, 0xb6, 0x01, 0x10, 0x0c, 0x80, 0x34, 0x00,
0x61, 0x20, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x13, 0x04, 0x41, 0x2c,
0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x34, 0x0a, 0x76, 0x60,
0x06, 0xa0, 0x1c, 0x8a, 0x33, 0xa0, 0x78, 0x07, 0x0d, 0x4a, 0x76, 0xa0,
0x74, 0x03, 0x2a, 0x10, 0x10, 0x10, 0x50, 0xa0, 0x08, 0x81, 0x4a, 0x91,
0xa0, 0x06, 0xca, 0x30, 0x80, 0x4c, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x82, 0x14, 0x14, 0x9d, 0x12, 0x28, 0x0f, 0x72, 0x73, 0x08,
0xda, 0x46, 0x71, 0x0e, 0x22, 0x49, 0x12, 0x30, 0x00, 0x00, 0x00, 0x00,
0x23, 0x06, 0x08, 0x00, 0x82, 0x60, 0x30, 0x7d, 0x4d, 0xb0, 0x51, 0x23,
0x06, 0x06, 0x00, 0x82, 0x60, 0x40, 0x90, 0x41, 0xc3, 0x55, 0x20, 0x69,
0x09, 0x0e, 0x5c, 0x60, 0xa2, 0x82, 0x65, 0x47, 0x0c, 0x0e, 0x00, 0x04,
0xc1, 0xe0, 0x31, 0x03, 0xcc, 0x40, 0x46, 0x0c, 0x16, 0x00, 0x04, 0xc1,
0x40, 0x49, 0x03, 0x2b, 0x10, 0x83, 0x42, 0x0c, 0x30, 0xe1, 0x0e, 0x13,
0x15, 0x38, 0x57, 0x89, 0xc4, 0x17, 0x98, 0xa8, 0x21, 0xd8, 0x11, 0x83,
0x03, 0x00, 0x41, 0x30, 0x78, 0xda, 0xe0, 0x6b, 0x9e, 0x11, 0x83, 0x05,
0x00, 0x41, 0x30, 0x50, 0xe0, 0xa0, 0x0b, 0x3c, 0x86, 0x0d, 0x3e, 0x61,
0xc4, 0xe0, 0x00, 0x40, 0x10, 0x0c, 0x9e, 0x37, 0x08, 0x83, 0x27, 0x1a,
0x31, 0x70, 0x00, 0x10, 0x04, 0x03, 0x26, 0x0e, 0xae, 0xc0, 0x51, 0x83,
0x30, 0x70, 0x3c, 0xc7, 0x9b, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// #453: original synthetic kernel for SM 6.6 64-bit atomics on a typed UAV
// (RWTexture2D<uint64_t> over a DXGI_FORMAT_R32G32_UINT texture, 8 x 3 texels).
// 256 threads, 32 per texel: row 0 takes a 64-bit add whose low halves carry
// into the high half, row 1 a 64-bit max decided by the high half. Row 2 gets a
// plain store (no atomic), so "atomics had no effect" is told apart from "the
// kernel never ran".
// Expected values are computed independently on the CPU by the fixture.
RWTexture2D<uint64_t> Img : register(u0);
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
uint px = id.x & 7u;
uint64_t add = (uint64_t(0x10000000u) << 32) | uint64_t(0xF0000000u + id.x);
InterlockedAdd(Img[uint2(px, 0)], add);
uint64_t m = (uint64_t(id.x) << 40) | uint64_t(0xFFFFFFFFu - id.x);
InterlockedMax(Img[uint2(px, 1)], m);
Img[uint2(px, 2)] = (uint64_t(0xC0DEu) << 32) | uint64_t(px);
}
@@ -0,0 +1,29 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Regenerates the committed *.h shader headers for test_d3dmetal_gpu_limits (#453).
# Needs Microsoft's official DXC release v1.9.2609 (dxc_2026_09_29.zip, SHA-256
# ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1); it has no
# macOS build, so bin/x64/dxc.exe runs under a Wine/CrossOver loader.
#
# WINE=/path/to/wine DXC=/path/to/dxc/bin/x64/dxc.exe ./compile.sh
set -eu
: "${WINE:?set WINE to a Wine or CrossOver wine loader}"
: "${DXC:?set DXC to dxc.exe from the DXC v1.9.2609 release}"
cd "$(dirname "$0")"
dxc() { "$WINE" "$DXC" -nologo "$@"; }
dxc -T cs_6_6 -E main -Vn g_wave_lanes_cs -Fh wave_lanes.h wave_lanes.hlsl
dxc -T cs_6_6 -E main -D BX_WAVE64=1 -Vn g_wave64_lanes_cs -Fh wave64_lanes.h wave_lanes.hlsl
dxc -T cs_6_6 -E main -Vn g_atomic64_image_cs -Fh atomic64_image.h atomic64_image.hlsl
dxc -T cs_6_6 -E main -Vn g_atomic64_buffer_cs -Fh atomic64_buffer.h atomic64_buffer.hlsl
dxc -T cs_6_6 -E main -Vn g_lock64_image_cs -Fh lock64_image.h lock64_image.hlsl
# Strip CRs and prepend the licence and provenance header.
for pair in wave_lanes:wave_lanes wave64_lanes:wave_lanes atomic64_image:atomic64_image \
atomic64_buffer:atomic64_buffer lock64_image:lock64_image; do
h=${pair%%:*} src=${pair#*:}
{
printf '// SPDX-License-Identifier: GPL-3.0-or-later\n//\n'
printf '// GENERATED by DXC 1.9.2609 from %s.hlsl by compile.sh; do not edit.\n\n' "$src"
tr -d '\r' < "$h.h"
} > "$h.h.tmp" && mv "$h.h.tmp" "$h.h"
done
@@ -0,0 +1,695 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// GENERATED by DXC 1.9.2609 from lock64_image.hlsl by compile.sh; do not edit.
#if 0
;
; Note: shader requires additional functionality:
; 64-Bit integer
;
;
; Input signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
;
; Output signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
; shader hash: 28e4ac966c16abf15f4beab80829e1ea
;
; Pipeline Runtime Information:
;
;PSVRuntimeInfo:
; Compute Shader
; NumThreads=(64,1,1)
; MinimumExpectedWaveLaneCount: 0
; MaximumExpectedWaveLaneCount: 4294967295
; UsesViewID: false
; SigInputElements: 0
; SigOutputElements: 0
; SigPatchConstOrPrimElements: 0
; SigInputVectors: 0
; SigOutputVectors[0]: 0
; SigOutputVectors[1]: 0
; SigOutputVectors[2]: 0
; SigOutputVectors[3]: 0
; EntryFunctionName: main
;
;
; Buffer Definitions:
;
; cbuffer Params
; {
;
; struct Params
; {
;
; uint cap; ; Offset: 0
;
; } Params; ; Offset: 0 Size: 4
;
; }
;
;
; Resource Bindings:
;
; Name Type Format Dim ID HLSL Bind Count
; ------------------------------ ---------- ------- ----------- ------- -------------- ------
; Params cbuffer NA NA CB0 cb0 1
; Data UAV u32 2d U0 u0 1
; Lock UAV u32 2d U1 u1 1
; Stats UAV byte r/w U2 u2 1
;
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
%dx.types.Handle = type { i8* }
%dx.types.ResBind = type { i32, i32, i32, i8 }
%dx.types.ResourceProperties = type { i32, i32 }
%dx.types.CBufRet.i32 = type { i32, i32, i32, i32 }
%dx.types.ResRet.i32 = type { i32, i32, i32, i32, i32 }
%"class.RWTexture2D<unsigned int>" = type { i32 }
%struct.RWByteAddressBuffer = type { i32 }
%Params = type { i32 }
define void @main() {
%1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 2, i32 2, i32 0, i8 1 }, i32 2, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%2 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 1, i32 1, i32 0, i8 1 }, i32 1, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%3 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %2, %dx.types.ResourceProperties { i32 20482, i32 261 }) ; AnnotateHandle(res,props) resource: globallycoherent RWTexture2D<U32>
%4 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 0, i32 0, i32 0, i8 1 }, i32 0, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%5 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %4, %dx.types.ResourceProperties { i32 20482, i32 261 }) ; AnnotateHandle(res,props) resource: globallycoherent RWTexture2D<U32>
%6 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 0, i32 0, i32 0, i8 2 }, i32 0, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%7 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %6, %dx.types.ResourceProperties { i32 13, i32 4 }) ; AnnotateHandle(res,props) resource: CBuffer
%8 = call i32 @dx.op.threadId.i32(i32 93, i32 0) ; ThreadId(component)
%9 = and i32 %8, 7
%10 = add i32 %8, -268435456
%11 = zext i32 %10 to i64
%12 = or i64 %11, 1152921504606846976
%13 = call %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32 59, %dx.types.Handle %7, i32 0) ; CBufferLoadLegacy(handle,regIndex)
%14 = extractvalue %dx.types.CBufRet.i32 %13, 0
%15 = icmp eq i32 %14, 0
br i1 %15, label %18, label %16
; <label>:16 ; preds = %0
br label %22
; <label>:17 ; preds = %43
br label %18
; <label>:18 ; preds = %17, %0
%19 = phi i32 [ 0, %0 ], [ %24, %17 ]
%20 = phi i32 [ 0, %0 ], [ %44, %17 ]
%21 = icmp eq i32 %20, 0
br i1 %21, label %50, label %53
; <label>:22 ; preds = %43, %16
%23 = phi i32 [ %24, %43 ], [ 0, %16 ]
%24 = add i32 %23, 1
%25 = call i32 @dx.op.atomicCompareExchange.i32(i32 79, %dx.types.Handle %3, i32 %9, i32 0, i32 undef, i32 0, i32 1) ; AtomicCompareExchange(handle,offset0,offset1,offset2,compareValue,newValue)
%26 = icmp eq i32 %25, 0
br i1 %26, label %27, label %43
; <label>:27 ; preds = %22
call void @dx.op.barrier(i32 80, i32 2) ; Barrier(barrierMode)
%28 = shl nuw nsw i32 %9, 1
%29 = or i32 %28, 1
%30 = call %dx.types.ResRet.i32 @dx.op.textureLoad.i32(i32 66, %dx.types.Handle %5, i32 undef, i32 %29, i32 0, i32 undef, i32 undef, i32 undef, i32 undef) ; TextureLoad(srv,mipLevelOrSampleCount,coord0,coord1,coord2,offset0,offset1,offset2)
%31 = extractvalue %dx.types.ResRet.i32 %30, 0
%32 = zext i32 %31 to i64
%33 = shl nuw i64 %32, 32
%34 = call %dx.types.ResRet.i32 @dx.op.textureLoad.i32(i32 66, %dx.types.Handle %5, i32 undef, i32 %28, i32 0, i32 undef, i32 undef, i32 undef, i32 undef) ; TextureLoad(srv,mipLevelOrSampleCount,coord0,coord1,coord2,offset0,offset1,offset2)
%35 = extractvalue %dx.types.ResRet.i32 %34, 0
%36 = zext i32 %35 to i64
%37 = or i64 %36, %33
%38 = add i64 %37, %12
%39 = trunc i64 %38 to i32
call void @dx.op.textureStore.i32(i32 67, %dx.types.Handle %5, i32 %28, i32 0, i32 undef, i32 %39, i32 %39, i32 %39, i32 %39, i8 15) ; TextureStore(srv,coord0,coord1,coord2,value0,value1,value2,value3,mask)
%40 = lshr i64 %38, 32
%41 = trunc i64 %40 to i32
call void @dx.op.textureStore.i32(i32 67, %dx.types.Handle %5, i32 %29, i32 0, i32 undef, i32 %41, i32 %41, i32 %41, i32 %41, i8 15) ; TextureStore(srv,coord0,coord1,coord2,value0,value1,value2,value3,mask)
call void @dx.op.barrier(i32 80, i32 2) ; Barrier(barrierMode)
%42 = call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle %3, i32 8, i32 %9, i32 0, i32 undef, i32 0) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
br label %43
; <label>:43 ; preds = %27, %22
%44 = phi i32 [ 1, %27 ], [ 0, %22 ]
%45 = call %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32 59, %dx.types.Handle %7, i32 0) ; CBufferLoadLegacy(handle,regIndex)
%46 = extractvalue %dx.types.CBufRet.i32 %45, 0
%47 = icmp ult i32 %24, %46
%48 = icmp eq i32 %44, 0
%49 = and i1 %48, %47
br i1 %49, label %22, label %17
; <label>:50 ; preds = %18
%51 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) ; AnnotateHandle(res,props) resource: RWByteAddressBuffer
%52 = call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle %51, i32 0, i32 0, i32 undef, i32 undef, i32 1) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
br label %53
; <label>:53 ; preds = %50, %18
%54 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) ; AnnotateHandle(res,props) resource: RWByteAddressBuffer
%55 = call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle %54, i32 0, i32 4, i32 undef, i32 undef, i32 %19) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
%56 = zext i32 %8 to i64
%57 = shl i64 %56, 40
%58 = xor i32 %8, -1
%59 = zext i32 %58 to i64
%60 = or i64 %57, %59
%61 = call %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32 59, %dx.types.Handle %7, i32 0) ; CBufferLoadLegacy(handle,regIndex)
%62 = extractvalue %dx.types.CBufRet.i32 %61, 0
%63 = icmp eq i32 %62, 0
br i1 %63, label %66, label %64
; <label>:64 ; preds = %53
br label %70
; <label>:65 ; preds = %91
br label %66
; <label>:66 ; preds = %65, %53
%67 = phi i32 [ 0, %53 ], [ %72, %65 ]
%68 = phi i32 [ 0, %53 ], [ %92, %65 ]
%69 = icmp eq i32 %68, 0
br i1 %69, label %98, label %101
; <label>:70 ; preds = %91, %64
%71 = phi i32 [ %72, %91 ], [ 0, %64 ]
%72 = add i32 %71, 1
%73 = call i32 @dx.op.atomicCompareExchange.i32(i32 79, %dx.types.Handle %3, i32 %9, i32 1, i32 undef, i32 0, i32 1) ; AtomicCompareExchange(handle,offset0,offset1,offset2,compareValue,newValue)
%74 = icmp eq i32 %73, 0
br i1 %74, label %75, label %91
; <label>:75 ; preds = %70
call void @dx.op.barrier(i32 80, i32 2) ; Barrier(barrierMode)
%76 = shl nuw nsw i32 %9, 1
%77 = or i32 %76, 1
%78 = call %dx.types.ResRet.i32 @dx.op.textureLoad.i32(i32 66, %dx.types.Handle %5, i32 undef, i32 %77, i32 1, i32 undef, i32 undef, i32 undef, i32 undef) ; TextureLoad(srv,mipLevelOrSampleCount,coord0,coord1,coord2,offset0,offset1,offset2)
%79 = extractvalue %dx.types.ResRet.i32 %78, 0
%80 = zext i32 %79 to i64
%81 = shl nuw i64 %80, 32
%82 = call %dx.types.ResRet.i32 @dx.op.textureLoad.i32(i32 66, %dx.types.Handle %5, i32 undef, i32 %76, i32 1, i32 undef, i32 undef, i32 undef, i32 undef) ; TextureLoad(srv,mipLevelOrSampleCount,coord0,coord1,coord2,offset0,offset1,offset2)
%83 = extractvalue %dx.types.ResRet.i32 %82, 0
%84 = zext i32 %83 to i64
%85 = or i64 %84, %81
%86 = call i64 @dx.op.binary.i64(i32 39, i64 %85, i64 %60) ; UMax(a,b)
%87 = trunc i64 %86 to i32
call void @dx.op.textureStore.i32(i32 67, %dx.types.Handle %5, i32 %76, i32 1, i32 undef, i32 %87, i32 %87, i32 %87, i32 %87, i8 15) ; TextureStore(srv,coord0,coord1,coord2,value0,value1,value2,value3,mask)
%88 = lshr i64 %86, 32
%89 = trunc i64 %88 to i32
call void @dx.op.textureStore.i32(i32 67, %dx.types.Handle %5, i32 %77, i32 1, i32 undef, i32 %89, i32 %89, i32 %89, i32 %89, i8 15) ; TextureStore(srv,coord0,coord1,coord2,value0,value1,value2,value3,mask)
call void @dx.op.barrier(i32 80, i32 2) ; Barrier(barrierMode)
%90 = call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle %3, i32 8, i32 %9, i32 1, i32 undef, i32 0) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
br label %91
; <label>:91 ; preds = %75, %70
%92 = phi i32 [ 1, %75 ], [ 0, %70 ]
%93 = call %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32 59, %dx.types.Handle %7, i32 0) ; CBufferLoadLegacy(handle,regIndex)
%94 = extractvalue %dx.types.CBufRet.i32 %93, 0
%95 = icmp ult i32 %72, %94
%96 = icmp eq i32 %92, 0
%97 = and i1 %96, %95
br i1 %97, label %70, label %65
; <label>:98 ; preds = %66
%99 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) ; AnnotateHandle(res,props) resource: RWByteAddressBuffer
%100 = call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle %99, i32 0, i32 0, i32 undef, i32 undef, i32 1) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
br label %101
; <label>:101 ; preds = %98, %66
%102 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) ; AnnotateHandle(res,props) resource: RWByteAddressBuffer
%103 = call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle %102, i32 0, i32 4, i32 undef, i32 undef, i32 %67) ; AtomicBinOp(handle,atomicOp,offset0,offset1,offset2,newValue)
ret void
}
; Function Attrs: nounwind readnone
declare i32 @dx.op.threadId.i32(i32, i32) #0
; Function Attrs: nounwind
declare i32 @dx.op.atomicBinOp.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32) #1
; Function Attrs: nounwind
declare void @dx.op.textureStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i32, i8) #1
; Function Attrs: nounwind readonly
declare %dx.types.ResRet.i32 @dx.op.textureLoad.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i32) #2
; Function Attrs: nounwind
declare i32 @dx.op.atomicCompareExchange.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32) #1
; Function Attrs: noduplicate nounwind
declare void @dx.op.barrier(i32, i32) #3
; Function Attrs: nounwind readnone
declare i64 @dx.op.binary.i64(i32, i64, i64) #0
; Function Attrs: nounwind readonly
declare %dx.types.CBufRet.i32 @dx.op.cbufferLoadLegacy.i32(i32, %dx.types.Handle, i32) #2
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0
attributes #0 = { nounwind readnone }
attributes #1 = { nounwind }
attributes #2 = { nounwind readonly }
attributes #3 = { noduplicate nounwind }
!llvm.ident = !{!0}
!dx.version = !{!1}
!dx.valver = !{!2}
!dx.shaderModel = !{!3}
!dx.resources = !{!4}
!dx.entryPoints = !{!12}
!0 = !{!"dxcoob 1.9.2609.5 (01b62ad47)"}
!1 = !{i32 1, i32 6}
!2 = !{i32 1, i32 9}
!3 = !{!"cs", i32 6, i32 6}
!4 = !{null, !5, !10, null}
!5 = !{!6, !8, !9}
!6 = !{i32 0, %"class.RWTexture2D<unsigned int>"* undef, !"", i32 0, i32 0, i32 1, i32 2, i1 true, i1 false, i1 false, !7}
!7 = !{i32 0, i32 5}
!8 = !{i32 1, %"class.RWTexture2D<unsigned int>"* undef, !"", i32 0, i32 1, i32 1, i32 2, i1 true, i1 false, i1 false, !7}
!9 = !{i32 2, %struct.RWByteAddressBuffer* undef, !"", i32 0, i32 2, i32 1, i32 11, i1 false, i1 false, i1 false, null}
!10 = !{!11}
!11 = !{i32 0, %Params* undef, !"", i32 0, i32 0, i32 1, i32 4, null}
!12 = !{void ()* @main, !"main", null, !4, !13}
!13 = !{i32 0, i64 1048592, i32 4, !14}
!14 = !{i32 64, i32 1, i32 1}
#endif
const unsigned char g_lock64_image_cs[] = {
0x44, 0x58, 0x42, 0x43, 0x6c, 0x63, 0x83, 0x34, 0x84, 0x6e, 0x2b, 0x4e,
0xb1, 0x53, 0xaa, 0x68, 0x3f, 0x1c, 0x2e, 0x06, 0x01, 0x00, 0x00, 0x00,
0x20, 0x13, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00,
0x24, 0x01, 0x00, 0x00, 0x90, 0x08, 0x00, 0x00, 0xac, 0x08, 0x00, 0x00,
0x53, 0x46, 0x49, 0x30, 0x08, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x31, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x4f, 0x53, 0x47, 0x31,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x50, 0x53, 0x56, 0x30, 0xb0, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x53, 0x54, 0x41, 0x54, 0x64, 0x07, 0x00, 0x00,
0x66, 0x00, 0x05, 0x00, 0xd9, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x4c, 0x07, 0x00, 0x00,
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0xd0, 0x01, 0x00, 0x00,
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
0x80, 0x18, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xc4, 0x10, 0x32, 0x14,
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x62, 0x88, 0x48, 0x90, 0x14, 0x20,
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
0x11, 0x23, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
0x04, 0x31, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
0x84, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x6d, 0x30, 0x86, 0xff,
0xff, 0xff, 0xff, 0x1f, 0x00, 0x09, 0xa8, 0x36, 0x18, 0xc4, 0xff, 0xff,
0xff, 0xff, 0x0f, 0x00, 0x03, 0x48, 0x00, 0x00, 0x49, 0x18, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42, 0x20, 0x4c, 0x08, 0x86,
0x09, 0x01, 0x01, 0x00, 0x89, 0x20, 0x00, 0x00, 0x4b, 0x00, 0x00, 0x00,
0x32, 0x22, 0x88, 0x09, 0x20, 0x64, 0x85, 0x04, 0x13, 0x23, 0xa4, 0x84,
0x04, 0x13, 0x23, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8c, 0x8c,
0x0b, 0x84, 0xc4, 0x4c, 0x10, 0x98, 0xc1, 0x08, 0x40, 0x09, 0x00, 0x0a,
0xe6, 0x08, 0xc0, 0xa0, 0x0c, 0xc3, 0x30, 0x10, 0x31, 0x47, 0x80, 0x90,
0x71, 0xcf, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92, 0x1f, 0x02, 0xcd, 0xb0,
0x10, 0x28, 0x38, 0x0a, 0x32, 0x0c, 0xc8, 0x30, 0x0c, 0xc3, 0x40, 0x49,
0x59, 0x80, 0x01, 0x19, 0x86, 0x61, 0x18, 0x86, 0xc1, 0xa0, 0xe5, 0xa6,
0xe1, 0xf2, 0x27, 0xec, 0x21, 0x24, 0x7f, 0x25, 0xa4, 0x95, 0x98, 0x7c,
0xe4, 0xb6, 0x51, 0x31, 0x0c, 0xc3, 0x30, 0x14, 0xa5, 0x19, 0x90, 0x61,
0x18, 0x86, 0x61, 0x18, 0xc8, 0x29, 0x03, 0x30, 0x0c, 0x04, 0xcd, 0x11,
0x80, 0x42, 0x21, 0xa4, 0x41, 0x92, 0x68, 0x3a, 0x6a, 0xb8, 0xfc, 0x09,
0x7b, 0x08, 0xc9, 0xe7, 0x36, 0xaa, 0x58, 0x89, 0xc9, 0x47, 0x6e, 0x1b,
0x11, 0xc3, 0x30, 0x0c, 0x85, 0xa8, 0x06, 0x64, 0x20, 0xeb, 0xb6, 0xe1,
0xf2, 0x27, 0xec, 0x21, 0x24, 0x7f, 0x25, 0x24, 0x87, 0x8a, 0x04, 0x22,
0x8d, 0x9c, 0x87, 0x88, 0x26, 0x84, 0x90, 0x90, 0x30, 0x0c, 0x85, 0x40,
0x06, 0x04, 0xa3, 0xec, 0xa0, 0xe1, 0xf2, 0x27, 0xec, 0x21, 0x24, 0x7f,
0x25, 0xa4, 0x0d, 0x69, 0x06, 0x44, 0x0c, 0xc3, 0x60, 0xcc, 0x11, 0x04,
0xa5, 0x40, 0x86, 0x6d, 0xe0, 0xa8, 0x1b, 0x08, 0x98, 0xe9, 0x1b, 0x07,
0x76, 0x08, 0x87, 0x79, 0x98, 0x07, 0x37, 0x90, 0x85, 0x5b, 0xa0, 0x85,
0x72, 0xc0, 0x07, 0x7a, 0xa8, 0x07, 0x79, 0x28, 0x07, 0x39, 0x20, 0x05,
0x3e, 0xa8, 0x07, 0x77, 0x98, 0x87, 0x74, 0x38, 0x07, 0x77, 0x28, 0x07,
0x72, 0x00, 0x83, 0x74, 0x70, 0x07, 0x7a, 0xf0, 0x03, 0x14, 0x0c, 0x04,
0x9e, 0x26, 0x4d, 0x11, 0x25, 0x4c, 0xfe, 0x0a, 0x6f, 0xd8, 0x44, 0x68,
0xc3, 0x10, 0x11, 0x92, 0xb4, 0x51, 0x45, 0x41, 0x44, 0x28, 0x18, 0x48,
0x3c, 0x23, 0x05, 0x22, 0x80, 0x91, 0x50, 0x30, 0x10, 0x09, 0x00, 0x00,
0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79,
0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e,
0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07,
0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e,
0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07,
0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07,
0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x12, 0x20,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x2c,
0x40, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4,
0x71, 0x80, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60,
0xc8, 0x93, 0x00, 0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xc0, 0x90, 0x07, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x21, 0xcf, 0x04, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x43, 0x1e, 0x0b, 0x08, 0x80, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x19, 0x10, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x3a, 0x20, 0x00, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x02, 0x01, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x18, 0x19, 0x11, 0x4c, 0x90,
0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a, 0x4a, 0xa0, 0x18, 0x46,
0x00, 0x8a, 0xa0, 0x14, 0xca, 0xa2, 0x10, 0xca, 0xa0, 0x1c, 0x0a, 0x30,
0xa0, 0x20, 0x0a, 0x3c, 0xa0, 0x48, 0x4a, 0x86, 0xa4, 0x02, 0x05, 0x04,
0x0c, 0x20, 0xae, 0x06, 0x46, 0x00, 0x28, 0x9c, 0x01, 0xa0, 0x71, 0x06,
0x80, 0xc8, 0x19, 0x00, 0x2a, 0x67, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
0x7a, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4,
0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45,
0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46,
0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x86, 0x65,
0x82, 0x30, 0x30, 0x1b, 0x84, 0x81, 0x98, 0x20, 0x0c, 0xcd, 0x06, 0xc1,
0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x84, 0x01,
0x47, 0x82, 0x28, 0x8c, 0x2e, 0x6c, 0x82, 0x30, 0x38, 0x13, 0x04, 0x4e,
0x9b, 0x20, 0x70, 0xdb, 0x04, 0x61, 0x78, 0x36, 0x08, 0xc6, 0xb3, 0x61,
0x31, 0x94, 0xc5, 0x30, 0x06, 0xa6, 0x71, 0x1c, 0x88, 0x04, 0xd3, 0xdb,
0xd8, 0xda, 0x86, 0x65, 0x50, 0x24, 0x63, 0x18, 0x98, 0xc6, 0x71, 0xa0,
0x09, 0xc2, 0x18, 0x74, 0x2c, 0xa6, 0xe8, 0xc2, 0xe8, 0xe6, 0x26, 0x08,
0x03, 0xb4, 0x61, 0x61, 0xa8, 0xca, 0x60, 0x06, 0xcb, 0x71, 0x1c, 0x60,
0xc3, 0x10, 0x4d, 0xd7, 0x04, 0xa1, 0x0c, 0x3e, 0x1a, 0x50, 0x61, 0x72,
0x61, 0x6d, 0x73, 0x13, 0x84, 0x21, 0xda, 0x80, 0x18, 0x99, 0x66, 0x18,
0xc3, 0x06, 0x6c, 0x08, 0xb8, 0x0d, 0x04, 0x80, 0x75, 0xc0, 0x04, 0x81,
0x0c, 0x3c, 0x0e, 0x63, 0x61, 0x70, 0x13, 0x84, 0x41, 0x9a, 0x20, 0x0c,
0xd3, 0x06, 0x83, 0x00, 0x83, 0x30, 0x30, 0xc4, 0xe0, 0xd9, 0x20, 0x6c,
0x63, 0xb0, 0x61, 0x30, 0x3e, 0x32, 0x98, 0x20, 0x08, 0xc0, 0x06, 0x60,
0xc3, 0x60, 0x9c, 0xc1, 0x19, 0x6c, 0x08, 0xd0, 0x60, 0xc3, 0x30, 0x98,
0x41, 0x1a, 0x90, 0x68, 0x0b, 0x4b, 0x73, 0x9b, 0x20, 0x48, 0xd9, 0x04,
0x61, 0xa0, 0x36, 0x0c, 0x6d, 0x30, 0x0c, 0x1b, 0x08, 0x83, 0x0d, 0x36,
0x37, 0xd8, 0x50, 0x98, 0xc1, 0x1a, 0x00, 0xde, 0x1b, 0xd0, 0x08, 0xa3,
0x7b, 0x6b, 0x4b, 0x1b, 0x9b, 0x20, 0x0c, 0x15, 0x0f, 0xb1, 0x30, 0x39,
0xb9, 0xb4, 0x32, 0x39, 0x22, 0x62, 0x72, 0x61, 0x6e, 0x63, 0x68, 0x65,
0x73, 0x2c, 0xd2, 0xdc, 0xe6, 0xe8, 0xe6, 0x26, 0x08, 0x83, 0x45, 0x22,
0xcd, 0x8d, 0x6e, 0x6e, 0x82, 0x30, 0x5c, 0x44, 0xe8, 0xca, 0xf0, 0xbe,
0xd8, 0xde, 0xc2, 0xc8, 0x98, 0xd0, 0x95, 0xe1, 0x7d, 0xcd, 0xd1, 0xbd,
0xc9, 0x95, 0xb1, 0xa8, 0x4b, 0x73, 0xa3, 0x9b, 0x9b, 0x20, 0x0c, 0xd8,
0x06, 0x28, 0x0e, 0xe4, 0x60, 0x0e, 0x36, 0x3a, 0x90, 0x83, 0x3a, 0xb0,
0x83, 0x3b, 0xc0, 0x83, 0x3c, 0xd8, 0xf4, 0x60, 0xdb, 0x03, 0x3e, 0xa8,
0xc2, 0xc6, 0x66, 0xd7, 0xe6, 0x92, 0x46, 0x56, 0xe6, 0x46, 0x37, 0x25,
0x08, 0xaa, 0x90, 0xe1, 0xb9, 0xd8, 0x95, 0xc9, 0xcd, 0xa5, 0xbd, 0xb9,
0x4d, 0x09, 0x88, 0x26, 0x64, 0x78, 0x2e, 0x76, 0x61, 0x6c, 0x76, 0x65,
0x72, 0x53, 0x02, 0xa3, 0x0e, 0x19, 0x9e, 0xcb, 0x1c, 0x5a, 0x18, 0x59,
0x99, 0x5c, 0xd3, 0x1b, 0x59, 0x19, 0xdb, 0x94, 0x00, 0x29, 0x43, 0x86,
0xe7, 0x22, 0x57, 0x36, 0xf7, 0x56, 0x27, 0x37, 0x56, 0x36, 0x37, 0x25,
0xe8, 0x2a, 0x91, 0xe1, 0xb9, 0xd0, 0xe5, 0xc1, 0x95, 0x05, 0xb9, 0xb9,
0xbd, 0xd1, 0x85, 0xd1, 0xa5, 0xbd, 0xb9, 0xcd, 0x4d, 0x11, 0xc8, 0x20,
0x0d, 0xea, 0x90, 0xe1, 0xb9, 0x94, 0xb9, 0xd1, 0xc9, 0xe5, 0x41, 0xbd,
0xa5, 0xb9, 0xd1, 0xcd, 0x4d, 0x09, 0xde, 0xa0, 0x0b, 0x19, 0x9e, 0xcb,
0xd8, 0x5b, 0x9d, 0x1b, 0x5d, 0x99, 0xdc, 0xdc, 0x94, 0x80, 0x0f, 0x00,
0x79, 0x18, 0x00, 0x00, 0x51, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c,
0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3,
0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6,
0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e,
0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43,
0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03,
0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48,
0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20,
0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e,
0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d,
0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89,
0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83,
0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68,
0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90,
0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78,
0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98,
0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5,
0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c,
0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c,
0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43,
0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43,
0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82,
0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70,
0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8,
0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2,
0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x30, 0x83, 0x81,
0xc8, 0x01, 0x1f, 0xdc, 0x40, 0x1c, 0xe4, 0xa1, 0x1c, 0xc2, 0x61, 0x1d,
0xdc, 0x40, 0x1c, 0xe4, 0x01, 0x00, 0x00, 0x00, 0x71, 0x20, 0x00, 0x00,
0x30, 0x00, 0x00, 0x00, 0x96, 0x40, 0x0d, 0x97, 0xef, 0x3c, 0x3e, 0xd0,
0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3, 0x42, 0x98, 0x40, 0x35,
0x5c, 0xbe, 0xf3, 0xf8, 0xc0, 0xe4, 0x30, 0x88, 0xb0, 0x21, 0x0d, 0xfa,
0xf8, 0xc8, 0x6d, 0x5b, 0xc1, 0x37, 0x5c, 0xbe, 0xf3, 0xf8, 0xc0, 0xe4,
0x30, 0x88, 0xc0, 0x39, 0xcc, 0x03, 0x44, 0x84, 0x77, 0x09, 0x07, 0xd0,
0x18, 0x84, 0x8f, 0xdc, 0xb6, 0x19, 0x34, 0xc3, 0xe5, 0x3b, 0x8f, 0x1f,
0x00, 0x51, 0x84, 0x10, 0x91, 0x1d, 0x40, 0xc3, 0xe5, 0x3b, 0x8f, 0x1f,
0x20, 0x0d, 0x10, 0x61, 0x3e, 0xa2, 0xe3, 0x86, 0xb0, 0x0d, 0x97, 0xef,
0x3c, 0xbe, 0x10, 0x50, 0x45, 0x41, 0x44, 0xa5, 0x03, 0x0c, 0x25, 0x61,
0x00, 0x02, 0xe6, 0x23, 0xb7, 0x6d, 0x0a, 0xdd, 0x70, 0xf9, 0xce, 0xe3,
0x0b, 0x11, 0x01, 0x4c, 0x44, 0x08, 0x34, 0xc3, 0x42, 0x7c, 0x91, 0xc3,
0x6c, 0x48, 0x33, 0x20, 0x8d, 0x61, 0x04, 0xd5, 0x70, 0xf9, 0xce, 0xe3,
0x4f, 0xc4, 0x35, 0x51, 0x11, 0x51, 0x3a, 0xc0, 0xe0, 0x23, 0xb7, 0x6d,
0x03, 0xd6, 0x70, 0xf9, 0xce, 0xe3, 0x4f, 0xc4, 0x35, 0x51, 0x11, 0xc1,
0x4e, 0x4e, 0x44, 0xf8, 0xc8, 0x6d, 0x5b, 0x80, 0x34, 0x5c, 0xbe, 0xf3,
0xf8, 0xd3, 0x11, 0x11, 0xc0, 0x20, 0x0e, 0x3e, 0x72, 0xdb, 0x06, 0x40,
0x30, 0x00, 0xd2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x41, 0x53, 0x48,
0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0xe4, 0xac, 0x96,
0x6c, 0x16, 0xab, 0xf1, 0x5f, 0x4b, 0xea, 0xb8, 0x08, 0x29, 0xe1, 0xea,
0x44, 0x58, 0x49, 0x4c, 0x6c, 0x0a, 0x00, 0x00, 0x66, 0x00, 0x05, 0x00,
0x9b, 0x02, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c, 0x06, 0x01, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x54, 0x0a, 0x00, 0x00, 0x42, 0x43, 0xc0, 0xde,
0x21, 0x0c, 0x00, 0x00, 0x92, 0x02, 0x00, 0x00, 0x0b, 0x82, 0x20, 0x00,
0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x07, 0x81, 0x23, 0x91,
0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39, 0x92, 0x01, 0x84, 0x0c,
0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62, 0x80, 0x18, 0x45, 0x02,
0x42, 0x92, 0x0b, 0x42, 0xc4, 0x10, 0x32, 0x14, 0x38, 0x08, 0x18, 0x4b,
0x0a, 0x32, 0x62, 0x88, 0x48, 0x90, 0x14, 0x20, 0x43, 0x46, 0x88, 0xa5,
0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90, 0x11, 0x23, 0xc4, 0x50,
0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a, 0x04, 0x31, 0x46, 0x06,
0x51, 0x18, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1b, 0x8c, 0xe0, 0xff,
0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d, 0x84, 0xf0, 0xff, 0xff,
0xff, 0xff, 0x03, 0x20, 0x6d, 0x30, 0x86, 0xff, 0xff, 0xff, 0xff, 0x1f,
0x00, 0x09, 0xa8, 0x36, 0x18, 0xc4, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00,
0x03, 0x48, 0x00, 0x00, 0x49, 0x18, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x13, 0x82, 0x60, 0x42, 0x20, 0x4c, 0x08, 0x86, 0x09, 0x01, 0x01, 0x00,
0x89, 0x20, 0x00, 0x00, 0x4b, 0x00, 0x00, 0x00, 0x32, 0x22, 0x88, 0x09,
0x20, 0x64, 0x85, 0x04, 0x13, 0x23, 0xa4, 0x84, 0x04, 0x13, 0x23, 0xe3,
0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8c, 0x8c, 0x0b, 0x84, 0xc4, 0x4c,
0x10, 0x9c, 0xc1, 0x08, 0x40, 0x09, 0x00, 0x0a, 0xe6, 0x08, 0xc0, 0xa0,
0x0c, 0xc3, 0x30, 0x10, 0x31, 0x47, 0x80, 0x90, 0x71, 0xcf, 0x70, 0xf9,
0x13, 0xf6, 0x10, 0x92, 0x1f, 0x02, 0xcd, 0xb0, 0x10, 0x28, 0x38, 0x0a,
0x32, 0x0c, 0xc8, 0x30, 0x0c, 0xc3, 0x40, 0x49, 0x59, 0x80, 0x01, 0x19,
0x86, 0x61, 0x18, 0x86, 0xc1, 0xa0, 0xe5, 0xa6, 0xe1, 0xf2, 0x27, 0xec,
0x21, 0x24, 0x7f, 0x25, 0xa4, 0x95, 0x98, 0x7c, 0xe4, 0xb6, 0x51, 0x31,
0x0c, 0xc3, 0x30, 0x14, 0xa5, 0x19, 0x90, 0x61, 0x18, 0x86, 0x61, 0x18,
0xc8, 0x29, 0x03, 0x30, 0x0c, 0x04, 0xcd, 0x11, 0x80, 0x42, 0x21, 0xa4,
0x41, 0x92, 0x68, 0x3a, 0x6a, 0xb8, 0xfc, 0x09, 0x7b, 0x08, 0xc9, 0xe7,
0x36, 0xaa, 0x58, 0x89, 0xc9, 0x47, 0x6e, 0x1b, 0x11, 0xc3, 0x30, 0x0c,
0x85, 0xa8, 0x06, 0x64, 0x20, 0xeb, 0xb6, 0xe1, 0xf2, 0x27, 0xec, 0x21,
0x24, 0x7f, 0x25, 0x24, 0x87, 0x8a, 0x04, 0x22, 0x8d, 0x9c, 0x87, 0x88,
0x26, 0x84, 0x90, 0x90, 0x30, 0x0c, 0x85, 0x40, 0x06, 0x04, 0xa3, 0xec,
0xa0, 0xe1, 0xf2, 0x27, 0xec, 0x21, 0x24, 0x7f, 0x25, 0xa4, 0x0d, 0x69,
0x06, 0x44, 0x0c, 0xc3, 0x60, 0xcc, 0x11, 0x04, 0xa5, 0x40, 0x86, 0x6d,
0xe0, 0xa8, 0x1b, 0x08, 0x98, 0xe9, 0x1b, 0x07, 0x76, 0x08, 0x87, 0x79,
0x98, 0x07, 0x37, 0x90, 0x85, 0x5b, 0xa0, 0x85, 0x72, 0xc0, 0x07, 0x7a,
0xa8, 0x07, 0x79, 0x28, 0x07, 0x39, 0x20, 0x05, 0x3e, 0xa8, 0x07, 0x77,
0x98, 0x87, 0x74, 0x38, 0x07, 0x77, 0x28, 0x07, 0x72, 0x00, 0x83, 0x74,
0x70, 0x07, 0x7a, 0xf0, 0x03, 0x14, 0x0c, 0x04, 0x9e, 0x26, 0x4d, 0x11,
0x25, 0x4c, 0xfe, 0x0a, 0x6f, 0xd8, 0x44, 0x68, 0xc3, 0x10, 0x11, 0x92,
0xb4, 0x51, 0x45, 0x41, 0x44, 0x28, 0x18, 0x48, 0x3c, 0x23, 0x05, 0x22,
0x80, 0x91, 0x50, 0x30, 0x10, 0x39, 0x05, 0x00, 0x13, 0x14, 0x72, 0xc0,
0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79, 0x68, 0x03, 0x72, 0xc0,
0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d,
0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73,
0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07, 0x7a, 0x60, 0x07, 0x74,
0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6,
0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78,
0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x76,
0x40, 0x07, 0x43, 0x9e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x12, 0x20, 0x00, 0x04, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x2c, 0x40, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4, 0x71, 0x80, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc8, 0x93, 0x00, 0x01,
0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x90, 0x07, 0x02,
0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x21, 0xcf,
0x04, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43,
0x1e, 0x0b, 0x08, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x86, 0x3c, 0x19, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0c, 0x79, 0x3a, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xc8, 0x02, 0x01, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00,
0x32, 0x1e, 0x98, 0x14, 0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47,
0xc6, 0x04, 0x43, 0x1a, 0x4a, 0xa0, 0x18, 0x4a, 0x62, 0x04, 0xa0, 0x08,
0x4a, 0xa1, 0x2c, 0x0a, 0xa1, 0x00, 0x03, 0x48, 0x2a, 0x50, 0x40, 0xc0,
0x00, 0xe2, 0x6a, 0x60, 0x04, 0x80, 0xc2, 0x19, 0x00, 0x1a, 0x67, 0x00,
0xa8, 0x9c, 0x01, 0x00, 0x79, 0x18, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00,
0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4, 0x8e, 0x0c, 0x6f, 0xec,
0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45, 0xc6, 0x06, 0x26, 0xc7,
0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46, 0x26, 0x8c, 0x8c, 0xe6,
0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x86, 0x65, 0x82, 0x30, 0x30, 0x1b,
0x84, 0x81, 0x98, 0x20, 0x0c, 0xcd, 0x06, 0x61, 0x30, 0x28, 0x8c, 0xcd,
0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x0c, 0xce, 0x04, 0x21, 0x0c, 0x2e,
0x02, 0x13, 0x84, 0xe1, 0x99, 0x20, 0x70, 0xd5, 0x04, 0x81, 0xb3, 0x26,
0x08, 0x03, 0xb4, 0x41, 0x50, 0xa0, 0x0d, 0x8b, 0xb2, 0x30, 0x8a, 0x32,
0x34, 0xce, 0xf3, 0x44, 0x1b, 0x96, 0x61, 0x61, 0x94, 0x61, 0x68, 0x9c,
0xe7, 0x89, 0x26, 0x08, 0x63, 0x80, 0x4d, 0x10, 0x86, 0x68, 0xc3, 0xd2,
0x50, 0x8c, 0xd2, 0x0c, 0xd5, 0xf3, 0x3c, 0xc0, 0x86, 0x41, 0x9a, 0xac,
0x09, 0x42, 0x19, 0x64, 0x13, 0x84, 0x41, 0xda, 0x80, 0x28, 0x18, 0xa3,
0x28, 0x43, 0x06, 0x6c, 0x08, 0xb4, 0x0d, 0x04, 0x70, 0x6d, 0xc0, 0x04,
0x41, 0x00, 0x48, 0xb4, 0x85, 0xa5, 0xb9, 0x4d, 0x10, 0x24, 0x6a, 0x82,
0x30, 0x4c, 0x1b, 0x06, 0x30, 0x18, 0x86, 0x0d, 0x84, 0xf2, 0x65, 0x61,
0xb0, 0xa1, 0xe8, 0x3c, 0x80, 0x13, 0x83, 0x2a, 0x6c, 0x6c, 0x76, 0x6d,
0x2e, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x53, 0x82, 0xa0, 0x0a, 0x19, 0x9e,
0x8b, 0x5d, 0x99, 0xdc, 0x5c, 0xda, 0x9b, 0xdb, 0x94, 0x80, 0x68, 0x42,
0x86, 0xe7, 0x62, 0x17, 0xc6, 0x66, 0x57, 0x26, 0x37, 0x25, 0x30, 0xea,
0x90, 0xe1, 0xb9, 0xcc, 0xa1, 0x85, 0x91, 0x95, 0xc9, 0x35, 0xbd, 0x91,
0x95, 0xb1, 0x4d, 0x09, 0x90, 0x32, 0x64, 0x78, 0x2e, 0x72, 0x65, 0x73,
0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x53, 0x82, 0xad, 0x0e, 0x19, 0x9e,
0x4b, 0x99, 0x1b, 0x9d, 0x5c, 0x1e, 0xd4, 0x5b, 0x9a, 0x1b, 0xdd, 0xdc,
0x94, 0x40, 0x0c, 0x00, 0x79, 0x18, 0x00, 0x00, 0x51, 0x00, 0x00, 0x00,
0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88,
0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73,
0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e,
0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30,
0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8,
0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b,
0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76,
0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e,
0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e,
0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61,
0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4,
0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76,
0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37,
0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76,
0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71,
0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e,
0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1,
0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61,
0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90,
0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8,
0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc,
0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4,
0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19,
0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06,
0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f,
0xf4, 0x30, 0x83, 0x81, 0xc8, 0x01, 0x1f, 0xdc, 0x40, 0x1c, 0xe4, 0xa1,
0x1c, 0xc2, 0x61, 0x1d, 0xdc, 0x40, 0x1c, 0xe4, 0x01, 0x00, 0x00, 0x00,
0x71, 0x20, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x96, 0x40, 0x0d, 0x97,
0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3,
0x42, 0x98, 0x40, 0x35, 0x5c, 0xbe, 0xf3, 0xf8, 0xc0, 0xe4, 0x30, 0x88,
0xb0, 0x21, 0x0d, 0xfa, 0xf8, 0xc8, 0x6d, 0x5b, 0xc1, 0x37, 0x5c, 0xbe,
0xf3, 0xf8, 0xc0, 0xe4, 0x30, 0x88, 0xc0, 0x39, 0xcc, 0x03, 0x44, 0x84,
0x77, 0x09, 0x07, 0xd0, 0x18, 0x84, 0x8f, 0xdc, 0xb6, 0x19, 0x34, 0xc3,
0xe5, 0x3b, 0x8f, 0x1f, 0x00, 0x51, 0x84, 0x10, 0x91, 0x1d, 0x40, 0xc3,
0xe5, 0x3b, 0x8f, 0x1f, 0x20, 0x0d, 0x10, 0x61, 0x3e, 0xa2, 0xe3, 0x86,
0xb0, 0x0d, 0x97, 0xef, 0x3c, 0xbe, 0x10, 0x50, 0x45, 0x41, 0x44, 0xa5,
0x03, 0x0c, 0x25, 0x61, 0x00, 0x02, 0xe6, 0x23, 0xb7, 0x6d, 0x0a, 0xdd,
0x70, 0xf9, 0xce, 0xe3, 0x0b, 0x11, 0x01, 0x4c, 0x44, 0x08, 0x34, 0xc3,
0x42, 0x7c, 0x91, 0xc3, 0x6c, 0x48, 0x33, 0x20, 0x8d, 0x61, 0x04, 0xd5,
0x70, 0xf9, 0xce, 0xe3, 0x4f, 0xc4, 0x35, 0x51, 0x11, 0x51, 0x3a, 0xc0,
0xe0, 0x23, 0xb7, 0x6d, 0x03, 0xd6, 0x70, 0xf9, 0xce, 0xe3, 0x4f, 0xc4,
0x35, 0x51, 0x11, 0xc1, 0x4e, 0x4e, 0x44, 0xf8, 0xc8, 0x6d, 0x5b, 0x80,
0x34, 0x5c, 0xbe, 0xf3, 0xf8, 0xd3, 0x11, 0x11, 0xc0, 0x20, 0x0e, 0x3e,
0x72, 0xdb, 0x06, 0x40, 0x30, 0x00, 0xd2, 0x00, 0x61, 0x20, 0x00, 0x00,
0xf7, 0x00, 0x00, 0x00, 0x13, 0x04, 0x51, 0x2c, 0x10, 0x00, 0x00, 0x00,
0x1b, 0x00, 0x00, 0x00, 0x34, 0xcc, 0x00, 0x14, 0xec, 0x40, 0x71, 0x06,
0x94, 0xec, 0x40, 0xd9, 0x15, 0x68, 0x40, 0x11, 0x06, 0x94, 0x61, 0x40,
0x79, 0x06, 0x14, 0x44, 0x11, 0x02, 0x0b, 0x94, 0x22, 0x41, 0x69, 0x94,
0x6e, 0x40, 0x39, 0x54, 0x20, 0x20, 0x20, 0xa0, 0x40, 0x59, 0x02, 0xd5,
0x40, 0x39, 0x91, 0x51, 0x1e, 0x25, 0x50, 0x04, 0x24, 0x15, 0x50, 0x01,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x82, 0x14, 0x14, 0x61, 0x73,
0x08, 0x6a, 0xe0, 0xcc, 0x21, 0x90, 0x41, 0x19, 0xcc, 0x21, 0x98, 0x81,
0x44, 0xdb, 0x1c, 0xc4, 0xf3, 0x38, 0x6e, 0x30, 0x07, 0xb1, 0x2c, 0x8e,
0x1b, 0xcc, 0x41, 0x38, 0x8e, 0xe3, 0x06, 0x73, 0x10, 0x8e, 0xe3, 0xbc,
0x01, 0x00, 0x00, 0x00, 0x23, 0x06, 0x08, 0x00, 0x82, 0x60, 0xd0, 0xc1,
0x41, 0x47, 0xac, 0x01, 0x19, 0x8c, 0x18, 0x20, 0x00, 0x08, 0x82, 0x41,
0x17, 0x07, 0x1e, 0x01, 0x07, 0x65, 0x30, 0x62, 0x70, 0x00, 0x20, 0x08,
0x06, 0xd9, 0x1c, 0x84, 0x41, 0x80, 0x8c, 0x18, 0x20, 0x00, 0x08, 0x82,
0x41, 0x37, 0x07, 0x60, 0x50, 0xbc, 0xc1, 0x19, 0x8c, 0x18, 0x1c, 0x00,
0x08, 0x82, 0x41, 0x56, 0x07, 0x63, 0x10, 0x28, 0x23, 0x06, 0x08, 0x00,
0x82, 0x60, 0xd0, 0xd5, 0x81, 0x18, 0x18, 0x71, 0x90, 0x06, 0x23, 0x06,
0x07, 0x00, 0x82, 0x60, 0x90, 0xdd, 0x41, 0x19, 0x04, 0xcb, 0x88, 0x81,
0x01, 0x80, 0x20, 0x18, 0x10, 0xa0, 0xa0, 0xcd, 0x41, 0x05, 0x9a, 0x96,
0xa0, 0xc1, 0x05, 0x52, 0x54, 0x40, 0xed, 0x88, 0xc1, 0x01, 0x80, 0x20,
0x18, 0x58, 0x7e, 0x80, 0x06, 0x06, 0x1e, 0x8c, 0x26, 0x04, 0xc0, 0x70,
0x43, 0xa0, 0x07, 0x60, 0x30, 0xcb, 0x30, 0x04, 0xc1, 0x2c, 0x01, 0x31,
0x4b, 0x30, 0x0c, 0x54, 0x0c, 0xf6, 0x00, 0x24, 0xc2, 0x40, 0xc5, 0x80,
0x0f, 0xc0, 0x1a, 0x08, 0xc3, 0x0d, 0x41, 0x1f, 0x80, 0xc1, 0x2c, 0xc3,
0x81, 0x04, 0x03, 0x15, 0xc3, 0x60, 0xf0, 0x43, 0x50, 0x81, 0x28, 0xc0,
0x88, 0xc1, 0x02, 0x80, 0x20, 0x18, 0x24, 0xa9, 0xc0, 0x06, 0x12, 0x03,
0x0a, 0x74, 0x00, 0x0a, 0xa3, 0x30, 0xdc, 0x10, 0x84, 0x02, 0x18, 0xcc,
0x32, 0x14, 0x46, 0x30, 0x62, 0x60, 0x00, 0x20, 0x08, 0x06, 0x90, 0x2a,
0xc4, 0x41, 0x28, 0x98, 0x53, 0x0a, 0x37, 0xa8, 0xc0, 0x14, 0x76, 0xc4,
0xa0, 0x01, 0x40, 0x10, 0x0c, 0x1c, 0x57, 0x90, 0x03, 0x0a, 0x0f, 0x02,
0x52, 0xc0, 0x03, 0x3c, 0xc0, 0x03, 0x3c, 0x18, 0x4d, 0x08, 0x80, 0x0b,
0xa4, 0xb0, 0xa0, 0x0c, 0x2e, 0x30, 0x62, 0xd0, 0x00, 0x20, 0x08, 0x06,
0x8e, 0x2c, 0xd8, 0x01, 0xc6, 0x07, 0x06, 0x2a, 0xf0, 0x01, 0x1f, 0xf0,
0x01, 0x1f, 0x8c, 0x26, 0x04, 0xc0, 0x05, 0x52, 0x54, 0x40, 0x6c, 0x05,
0x15, 0x5c, 0x30, 0xc0, 0x88, 0x81, 0x03, 0x80, 0x20, 0x18, 0x2c, 0xb9,
0xb0, 0x07, 0x1e, 0xe3, 0x0a, 0xa2, 0x10, 0x04, 0x41, 0xf0, 0x06, 0x25,
0xb0, 0x01, 0x5e, 0x30, 0xc0, 0x88, 0x81, 0x03, 0x80, 0x20, 0x18, 0x2c,
0xbb, 0xd0, 0x07, 0x60, 0xd0, 0xc0, 0x02, 0x29, 0x04, 0x41, 0x10, 0xc4,
0xc1, 0x88, 0x81, 0x01, 0x80, 0x20, 0x18, 0x40, 0xb8, 0xf0, 0x07, 0xaf,
0x30, 0x62, 0xb0, 0x00, 0x20, 0x08, 0x06, 0x09, 0x2f, 0x88, 0x82, 0x18,
0xec, 0x01, 0x07, 0x0b, 0xa4, 0x00, 0x0b, 0xb3, 0x04, 0xc6, 0x40, 0xc5,
0x80, 0x16, 0x85, 0x58, 0x10, 0x23, 0x06, 0x07, 0x00, 0x82, 0x60, 0x60,
0xe1, 0x82, 0x28, 0x80, 0x81, 0x2c, 0x8c, 0x26, 0x04, 0xc0, 0x70, 0x43,
0x15, 0x90, 0xc1, 0x70, 0x03, 0x51, 0x0b, 0x60, 0x50, 0x81, 0xa0, 0xb3,
0x0c, 0x84, 0x10, 0x8c, 0x18, 0x1c, 0x00, 0x08, 0x82, 0x41, 0xc6, 0x0b,
0xaa, 0xb0, 0x06, 0x72, 0x30, 0x62, 0xb0, 0x00, 0x20, 0x08, 0x06, 0x09,
0x39, 0xa8, 0x42, 0x80, 0x0b, 0xb8, 0xc0, 0x0a, 0xac, 0xb0, 0x0b, 0xb3,
0x04, 0xc8, 0x88, 0xc1, 0x01, 0x80, 0x20, 0x18, 0x64, 0xbe, 0xc0, 0x0a,
0x6d, 0x40, 0x07, 0x23, 0x06, 0x0b, 0x00, 0x82, 0x60, 0x90, 0x98, 0x03,
0x2b, 0x04, 0xba, 0x60, 0x0b, 0xae, 0xe0, 0x0a, 0xdf, 0xa1, 0x81, 0x14,
0x15, 0xe0, 0xc1, 0x95, 0x1a, 0x80, 0x02, 0x5f, 0x20, 0x45, 0x0d, 0xc1,
0x8e, 0x18, 0x1c, 0x00, 0x08, 0x82, 0x81, 0x65, 0x0e, 0xb0, 0xe0, 0x06,
0xe0, 0x30, 0x9a, 0x10, 0x00, 0xc3, 0x0d, 0x81, 0x38, 0x80, 0xc1, 0x2c,
0xc3, 0x92, 0x04, 0xb3, 0x04, 0xcc, 0x2c, 0xc1, 0x32, 0x50, 0x31, 0x98,
0x06, 0x92, 0x28, 0x03, 0x15, 0x03, 0x6a, 0x20, 0x6b, 0xa0, 0x0c, 0x37,
0x04, 0xe5, 0x00, 0x06, 0xb3, 0x0c, 0x0f, 0x14, 0x0c, 0x54, 0x0c, 0x83,
0xc3, 0x1a, 0x49, 0x05, 0xea, 0x00, 0x23, 0x06, 0x0b, 0x00, 0x82, 0x60,
0x90, 0xc4, 0x03, 0x2d, 0xe8, 0x01, 0x1d, 0xac, 0x03, 0x2f, 0xa0, 0xc3,
0x3a, 0x0c, 0x37, 0x04, 0xe9, 0x00, 0x06, 0xb3, 0x0c, 0x8d, 0x13, 0x8c,
0x18, 0x18, 0x00, 0x08, 0x82, 0x01, 0x24, 0x0f, 0xb9, 0x90, 0x0e, 0x66,
0x07, 0xed, 0x70, 0x83, 0x0a, 0xdc, 0x61, 0x47, 0x0c, 0x1a, 0x00, 0x04,
0xc1, 0xc0, 0xb1, 0x07, 0x5d, 0xe0, 0x03, 0x70, 0x08, 0xde, 0x01, 0x1c,
0xc0, 0x01, 0x1c, 0xc0, 0x61, 0x34, 0x21, 0x00, 0x2e, 0x90, 0xc2, 0x82,
0x56, 0xb8, 0xc0, 0x88, 0x41, 0x03, 0x80, 0x20, 0x18, 0x38, 0xfa, 0xe0,
0x0b, 0xa0, 0x40, 0x0e, 0xc6, 0x3c, 0x90, 0x03, 0x39, 0x90, 0x03, 0x39,
0x8c, 0x26, 0x04, 0xc0, 0x05, 0x52, 0x54, 0x40, 0xec, 0x88, 0xc1, 0x01,
0x80, 0x20, 0x18, 0x4c, 0xfb, 0x60, 0x0b, 0x41, 0x75, 0xc1, 0x00, 0x23,
0x06, 0x0e, 0x00, 0x82, 0x60, 0xb0, 0x84, 0xc4, 0x38, 0x98, 0x02, 0x93,
0x0f, 0xea, 0x10, 0x04, 0x41, 0x70, 0x0b, 0x25, 0xd0, 0x02, 0x5e, 0x30,
0xc0, 0x88, 0x81, 0x03, 0x80, 0x20, 0x18, 0x2c, 0x23, 0x51, 0x0e, 0xa8,
0xd0, 0xec, 0x03, 0x3b, 0x04, 0x41, 0x10, 0xe4, 0xc2, 0x88, 0x81, 0x01,
0x80, 0x20, 0x18, 0x40, 0x20, 0x71, 0x0e, 0xf7, 0x30, 0x62, 0xb0, 0x00,
0x20, 0x08, 0x06, 0x09, 0x49, 0xa8, 0x83, 0x2a, 0x8c, 0x03, 0x29, 0xec,
0x03, 0x3b, 0xe0, 0xc3, 0x2c, 0x81, 0x33, 0x50, 0x31, 0xe0, 0x47, 0x23,
0x1f, 0xcc, 0x88, 0xc1, 0x01, 0x80, 0x20, 0x18, 0x58, 0x20, 0xa1, 0x0e,
0xa8, 0xa0, 0x0f, 0xa3, 0x09, 0x01, 0x30, 0xdc, 0x50, 0x05, 0x64, 0x30,
0xdc, 0x40, 0xf4, 0x03, 0x18, 0x54, 0x20, 0xe8, 0x2c, 0x03, 0xa3, 0x04,
0x23, 0x06, 0x07, 0x00, 0x82, 0x60, 0x90, 0x91, 0x84, 0x3c, 0xcc, 0x82,
0x2e, 0x8c, 0x18, 0x2c, 0x00, 0x08, 0x82, 0x41, 0xc2, 0x12, 0xf2, 0x10,
0x80, 0x04, 0x48, 0xd0, 0x03, 0x3d, 0x8c, 0xc4, 0x2c, 0x01, 0x34, 0x62,
0x70, 0x00, 0x20, 0x08, 0x06, 0x99, 0x49, 0xd0, 0x43, 0x2d, 0xf0, 0xc2,
0x88, 0xc1, 0x02, 0x80, 0x20, 0x18, 0x24, 0x2e, 0x41, 0x0f, 0x81, 0x48,
0xf8, 0x83, 0x3d, 0xd8, 0xc3, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// #453: original synthetic kernel. Emulates the two 64-bit atomics of
// atomic64_image.hlsl with a per-texel spin lock over 32-bit words, with a
// bounded number of tries (root constant `cap`).
//
// Data (R32_UINT, 16 x 2): texel (2p, row) = low word, (2p + 1, row) = high word
// Lock (R32_UINT, 8 x 2): 0 = free, 1 = held
// Stats (raw buffer): [0] updates dropped after `cap` tries, [4] total tries
//
// The critical section sits inside the retry loop, so a lane that wins the lock
// finishes it in the same iteration. Lanes that lose keep looping with it and
// none waits for another lane to leave a loop. A lane that runs out of tries
// counts a drop instead of spinning on. The fixture checks values only when no
// update was dropped.
globallycoherent RWTexture2D<uint> Data : register(u0);
globallycoherent RWTexture2D<uint> Lock : register(u1);
RWByteAddressBuffer Stats : register(u2);
cbuffer Params : register(b0)
{
uint cap;
};
uint64_t load64(uint p, uint row)
{
return (uint64_t(Data[uint2(2u * p + 1u, row)]) << 32) | uint64_t(Data[uint2(2u * p, row)]);
}
void store64(uint p, uint row, uint64_t v)
{
Data[uint2(2u * p, row)] = uint(v);
Data[uint2(2u * p + 1u, row)] = uint(v >> 32);
}
void locked_update(uint p, uint row, uint64_t operand)
{
bool done = false;
uint tries = 0;
[allow_uav_condition]
for (uint t = 0; t < cap && !done; ++t) {
tries++;
uint prev;
InterlockedCompareExchange(Lock[uint2(p, row)], 0u, 1u, prev);
if (prev == 0u) {
// Acquire: order the data reads after taking the lock, so they see the previous
// holder's writes (globallycoherent gives visibility, not ordering).
DeviceMemoryBarrier();
uint64_t old = load64(p, row);
uint64_t now = row == 0u ? old + operand : max(old, operand);
store64(p, row, now);
// Release: the data writes become visible before the lock is freed.
DeviceMemoryBarrier();
uint ignored;
InterlockedExchange(Lock[uint2(p, row)], 0u, ignored);
done = true;
}
}
uint ignored2;
if (!done) {
Stats.InterlockedAdd(0, 1u, ignored2);
}
Stats.InterlockedAdd(4, tries, ignored2);
}
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
uint px = id.x & 7u;
locked_update(px, 0u, (uint64_t(0x10000000u) << 32) | uint64_t(0xF0000000u + id.x));
locked_update(px, 1u, (uint64_t(id.x) << 40) | uint64_t(0xFFFFFFFFu - id.x));
}
@@ -0,0 +1,414 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// GENERATED by DXC 1.9.2609 from wave_lanes.hlsl by compile.sh; do not edit.
#if 0
;
; Note: shader requires additional functionality:
; Wave level operations
;
;
; Input signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
;
; Output signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
; shader hash: 348f77383c3753e9ba617fa6c9d30a8c
;
; Pipeline Runtime Information:
;
;PSVRuntimeInfo:
; Compute Shader
; NumThreads=(64,1,1)
; WaveSize=64
; UsesViewID: false
; SigInputElements: 0
; SigOutputElements: 0
; SigPatchConstOrPrimElements: 0
; SigInputVectors: 0
; SigOutputVectors[0]: 0
; SigOutputVectors[1]: 0
; SigOutputVectors[2]: 0
; SigOutputVectors[3]: 0
; EntryFunctionName: main
;
;
; Buffer Definitions:
;
; Resource bind info for Out
; {
;
; uint $Element; ; Offset: 0 Size: 4
;
; }
;
;
; Resource Bindings:
;
; Name Type Format Dim ID HLSL Bind Count
; ------------------------------ ---------- ------- ----------- ------- -------------- ------
; Out UAV struct r/w U0 u0 1
;
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
%dx.types.Handle = type { i8* }
%dx.types.ResBind = type { i32, i32, i32, i8 }
%dx.types.ResourceProperties = type { i32, i32 }
%"class.RWStructuredBuffer<unsigned int>" = type { i32 }
define void @main() {
%1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 0, i32 0, i32 0, i8 1 }, i32 0, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%2 = call i32 @dx.op.threadId.i32(i32 93, i32 0) ; ThreadId(component)
%3 = call i32 @dx.op.waveGetLaneCount(i32 112) ; WaveGetLaneCount()
%4 = shl i32 %3, 16
%5 = call i32 @dx.op.waveGetLaneIndex(i32 111) ; WaveGetLaneIndex()
%6 = or i32 %4, %5
%7 = shl i32 %2, 1
%8 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4108, i32 4 }) ; AnnotateHandle(res,props) resource: RWStructuredBuffer<stride=4>
call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %8, i32 %7, i32 0, i32 %6, i32 undef, i32 undef, i32 undef, i8 1, i32 4) ; RawBufferStore(uav,index,elementOffset,value0,value1,value2,value3,mask,alignment)
%9 = call i32 @dx.op.waveReadLaneFirst.i32(i32 118, i32 %2) ; WaveReadLaneFirst(value)
%10 = or i32 %7, 1
%11 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4108, i32 4 }) ; AnnotateHandle(res,props) resource: RWStructuredBuffer<stride=4>
call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %11, i32 %10, i32 0, i32 %9, i32 undef, i32 undef, i32 undef, i8 1, i32 4) ; RawBufferStore(uav,index,elementOffset,value0,value1,value2,value3,mask,alignment)
ret void
}
; Function Attrs: nounwind readnone
declare i32 @dx.op.threadId.i32(i32, i32) #0
; Function Attrs: nounwind readnone
declare i32 @dx.op.waveGetLaneCount(i32) #0
; Function Attrs: nounwind readonly
declare i32 @dx.op.waveGetLaneIndex(i32) #1
; Function Attrs: nounwind
declare void @dx.op.rawBufferStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i8, i32) #2
; Function Attrs: nounwind
declare i32 @dx.op.waveReadLaneFirst.i32(i32, i32) #2
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0
attributes #0 = { nounwind readnone }
attributes #1 = { nounwind readonly }
attributes #2 = { nounwind }
!llvm.ident = !{!0}
!dx.version = !{!1}
!dx.valver = !{!2}
!dx.shaderModel = !{!3}
!dx.resources = !{!4}
!dx.entryPoints = !{!8}
!0 = !{!"dxcoob 1.9.2609.5 (01b62ad47)"}
!1 = !{i32 1, i32 6}
!2 = !{i32 1, i32 9}
!3 = !{!"cs", i32 6, i32 6}
!4 = !{null, !5, null, null}
!5 = !{!6}
!6 = !{i32 0, %"class.RWStructuredBuffer<unsigned int>"* undef, !"", i32 0, i32 0, i32 1, i32 12, i1 false, i1 false, i1 false, !7}
!7 = !{i32 1, i32 4}
!8 = !{void ()* @main, !"main", null, !4, !9}
!9 = !{i32 0, i64 524304, i32 4, !10, i32 11, !11}
!10 = !{i32 64, i32 1, i32 1}
!11 = !{i32 64}
#endif
const unsigned char g_wave64_lanes_cs[] = {
0x44, 0x58, 0x42, 0x43, 0x5b, 0x12, 0x31, 0xdd, 0xd1, 0xd6, 0x57, 0x55,
0xfa, 0x23, 0x85, 0xd6, 0x4c, 0x62, 0x8a, 0x53, 0x01, 0x00, 0x00, 0x00,
0x40, 0x0d, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00,
0xdc, 0x00, 0x00, 0x00, 0xf0, 0x06, 0x00, 0x00, 0x0c, 0x07, 0x00, 0x00,
0x53, 0x46, 0x49, 0x30, 0x08, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x31, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x4f, 0x53, 0x47, 0x31,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x50, 0x53, 0x56, 0x30, 0x68, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x53, 0x54, 0x41, 0x54, 0x0c, 0x06, 0x00, 0x00,
0x66, 0x00, 0x05, 0x00, 0x83, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xf4, 0x05, 0x00, 0x00,
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x7a, 0x01, 0x00, 0x00,
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xa4, 0x10, 0x32, 0x14,
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88, 0x48, 0x90, 0x14, 0x20,
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
0x86, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x01, 0xd5, 0x06, 0x62,
0xf8, 0xff, 0xff, 0xff, 0xff, 0x01, 0x90, 0x00, 0x49, 0x18, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42, 0x20, 0x4c, 0x08, 0x06,
0x00, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04, 0x93, 0x22, 0xa4, 0x84,
0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8a, 0x8c,
0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00, 0x25, 0x00, 0x14, 0xe6,
0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x45, 0x18, 0x83, 0xcc, 0x1c,
0x01, 0x42, 0xe8, 0x9e, 0xe1, 0xf2, 0x27, 0xec, 0x21, 0x24, 0x3f, 0x04,
0x9a, 0x61, 0x21, 0x50, 0x90, 0xca, 0x02, 0x86, 0x1a, 0x63, 0x8c, 0x31,
0xd0, 0xa0, 0x75, 0xdb, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92, 0xbf, 0x12,
0x92, 0x43, 0x45, 0x02, 0x91, 0x46, 0xce, 0x43, 0x44, 0x13, 0x42, 0x48,
0x48, 0x18, 0xa3, 0x10, 0x6a, 0xa8, 0x46, 0xee, 0xa0, 0xe1, 0xf2, 0x27,
0xec, 0x21, 0x24, 0x7f, 0x25, 0xa4, 0x0d, 0x69, 0x06, 0x44, 0x8c, 0x31,
0xd0, 0x1c, 0x41, 0x50, 0x0a, 0x35, 0xe0, 0x88, 0x24, 0x07, 0x02, 0x66,
0x32, 0x83, 0x71, 0x60, 0x87, 0x70, 0x98, 0x87, 0x79, 0x70, 0x03, 0x59,
0xb8, 0x85, 0x59, 0xa0, 0x07, 0x79, 0xa8, 0x87, 0x71, 0xa0, 0x87, 0x7a,
0x90, 0x87, 0x72, 0x20, 0x07, 0x51, 0xa8, 0x07, 0x73, 0x30, 0x87, 0x72,
0x90, 0x07, 0x3e, 0xa8, 0x07, 0x77, 0x98, 0x87, 0x74, 0x38, 0x07, 0x77,
0x28, 0x07, 0x72, 0x00, 0x83, 0x74, 0x70, 0x07, 0x7a, 0xf0, 0x03, 0x14,
0x0c, 0xaa, 0x73, 0x04, 0xa0, 0x00, 0x00, 0x00, 0x13, 0x14, 0x72, 0xc0,
0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79, 0x68, 0x03, 0x72, 0xc0,
0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d,
0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73,
0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07, 0x7a, 0x60, 0x07, 0x74,
0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6,
0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78,
0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x76,
0x40, 0x07, 0x43, 0x9e, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x0c, 0x20, 0x00, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x18, 0x40, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4, 0x59, 0x80, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc8, 0x43, 0x00, 0x01,
0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x90, 0xc7, 0x01,
0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x21, 0x8f,
0x04, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59,
0x20, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14,
0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a,
0x25, 0x50, 0x0c, 0x23, 0x00, 0x85, 0x51, 0x08, 0x65, 0x50, 0x0e, 0xa5,
0x30, 0x03, 0x50, 0x80, 0x01, 0x65, 0x51, 0x1c, 0x45, 0x40, 0x71, 0x04,
0x80, 0x6e, 0x81, 0x02, 0x02, 0x91, 0x9d, 0x01, 0xa0, 0x3a, 0x03, 0x00,
0x79, 0x18, 0x00, 0x00, 0x5e, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90,
0x46, 0x02, 0x13, 0xc4, 0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24,
0xc6, 0x25, 0xc7, 0x45, 0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05,
0x26, 0x46, 0xcc, 0x46, 0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10,
0x4c, 0x10, 0x06, 0x64, 0x82, 0x30, 0x24, 0x1b, 0x84, 0x81, 0x98, 0x20,
0x0c, 0xca, 0x06, 0xc1, 0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82,
0x98, 0x20, 0x58, 0x17, 0x87, 0xa7, 0x3a, 0xba, 0x09, 0xc2, 0xb0, 0x4c,
0x10, 0xa2, 0x6a, 0x82, 0x30, 0x30, 0x1b, 0x84, 0xc1, 0xd9, 0xb0, 0x18,
0xca, 0x62, 0x18, 0x03, 0xd3, 0x34, 0xcd, 0xb3, 0x21, 0x80, 0x36, 0x10,
0x40, 0x04, 0x00, 0x13, 0x84, 0x0a, 0x63, 0x80, 0x36, 0x41, 0x18, 0x9a,
0x09, 0xc2, 0xe0, 0x4c, 0x10, 0x86, 0x67, 0x83, 0x41, 0x50, 0x95, 0x61,
0x5d, 0x13, 0x84, 0x01, 0xda, 0x20, 0x18, 0xd9, 0x86, 0x40, 0xdb, 0x20,
0x18, 0xdb, 0x86, 0xc1, 0xc1, 0xb8, 0x0d, 0x83, 0x31, 0x75, 0x13, 0x04,
0x01, 0xd8, 0x00, 0x6c, 0x18, 0x0c, 0x30, 0x00, 0x83, 0x0d, 0x41, 0x18,
0x6c, 0x18, 0x86, 0x4f, 0x0c, 0x48, 0xb4, 0x85, 0xa5, 0xb9, 0x4d, 0x10,
0x2e, 0x6b, 0x82, 0x30, 0x44, 0x1b, 0x06, 0x33, 0x18, 0x86, 0x09, 0xc2,
0x20, 0x6d, 0x08, 0xcc, 0x60, 0x83, 0x61, 0x94, 0x81, 0x73, 0x06, 0x68,
0x90, 0x06, 0x1b, 0x8a, 0x8f, 0x0c, 0x00, 0x49, 0x0d, 0x58, 0xa4, 0xb9,
0xcd, 0xd1, 0xcd, 0x4d, 0x10, 0x86, 0x89, 0x09, 0x5d, 0x19, 0xde, 0xd7,
0x1c, 0xdd, 0x9b, 0x5c, 0xd9, 0x04, 0x61, 0xa0, 0x58, 0xd4, 0xa5, 0xb9,
0xd1, 0xcd, 0x6d, 0x30, 0xd8, 0xa0, 0x0d, 0xdc, 0xe0, 0x0d, 0xe0, 0xc0,
0xa9, 0xc2, 0xc6, 0x66, 0xd7, 0xe6, 0x92, 0x46, 0x56, 0xe6, 0x46, 0x37,
0x25, 0x08, 0xaa, 0x90, 0xe1, 0xb9, 0xd8, 0x95, 0xc9, 0xcd, 0xa5, 0xbd,
0xb9, 0x4d, 0x09, 0x88, 0x26, 0x64, 0x78, 0x2e, 0x76, 0x61, 0x6c, 0x76,
0x65, 0x72, 0x53, 0x02, 0xa3, 0x0e, 0x19, 0x9e, 0xcb, 0x1c, 0x5a, 0x18,
0x59, 0x99, 0x5c, 0xd3, 0x1b, 0x59, 0x19, 0xdb, 0x94, 0x00, 0x29, 0x43,
0x86, 0xe7, 0x22, 0x57, 0x36, 0xf7, 0x56, 0x27, 0x37, 0x56, 0x36, 0x37,
0x25, 0x88, 0x2a, 0x91, 0xe1, 0xb9, 0xd0, 0xe5, 0xc1, 0x95, 0x05, 0xb9,
0xb9, 0xbd, 0xd1, 0x85, 0xd1, 0xa5, 0xbd, 0xb9, 0xcd, 0x4d, 0x11, 0x3a,
0x31, 0xa8, 0x43, 0x86, 0xe7, 0x52, 0xe6, 0x46, 0x27, 0x97, 0x07, 0xf5,
0x96, 0xe6, 0x46, 0x37, 0x37, 0x25, 0x50, 0x83, 0x2e, 0x64, 0x78, 0x2e,
0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x53, 0x02, 0x38, 0x00,
0x79, 0x18, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c,
0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3,
0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6,
0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e,
0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43,
0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03,
0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48,
0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20,
0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e,
0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d,
0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89,
0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83,
0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68,
0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90,
0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78,
0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98,
0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5,
0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c,
0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c,
0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43,
0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43,
0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82,
0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70,
0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8,
0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2,
0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00, 0x00, 0x00,
0x71, 0x20, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x66, 0x40, 0x0d, 0x97,
0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3,
0x42, 0xd8, 0x41, 0x37, 0x5c, 0xbe, 0xf3, 0xf8, 0x42, 0x44, 0x00, 0x13,
0x11, 0x02, 0xcd, 0xb0, 0x10, 0x5f, 0xe4, 0x30, 0x1b, 0xd2, 0x0c, 0x48,
0x63, 0x18, 0x01, 0x36, 0x5c, 0xbe, 0xf3, 0xf8, 0x11, 0x60, 0x6d, 0x54,
0x51, 0x10, 0x11, 0x3b, 0x39, 0x11, 0xe1, 0x23, 0xb7, 0x6d, 0x01, 0xd2,
0x70, 0xf9, 0xce, 0xe3, 0x4f, 0x47, 0x44, 0x00, 0x83, 0x38, 0xf8, 0xc8,
0x6d, 0x9b, 0x80, 0x35, 0x5c, 0xbe, 0xf3, 0xf8, 0x16, 0x50, 0x11, 0x20,
0x31, 0x95, 0x40, 0x43, 0x70, 0x0e, 0xd5, 0x4c, 0x36, 0x60, 0x0d, 0x97,
0xef, 0x3c, 0xbe, 0x05, 0x54, 0x04, 0x48, 0x4c, 0x25, 0xd0, 0x10, 0x62,
0x33, 0x10, 0x97, 0x15, 0x6c, 0xc3, 0xe5, 0x3b, 0x8f, 0x6f, 0x01, 0x15,
0xb1, 0x12, 0xc0, 0x50, 0x02, 0x0d, 0xf1, 0x21, 0x91, 0x34, 0xf9, 0xc8,
0x6d, 0x1b, 0x00, 0xc1, 0x00, 0x48, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x41, 0x53, 0x48, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x34, 0x8f, 0x77, 0x38, 0x3c, 0x37, 0x53, 0xe9, 0xba, 0x61, 0x7f, 0xa6,
0xc9, 0xd3, 0x0a, 0x8c, 0x44, 0x58, 0x49, 0x4c, 0x2c, 0x06, 0x00, 0x00,
0x66, 0x00, 0x05, 0x00, 0x8b, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x14, 0x06, 0x00, 0x00,
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00,
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xa4, 0x10, 0x32, 0x14,
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88, 0x48, 0x90, 0x14, 0x20,
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
0x86, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x01, 0xd5, 0x06, 0x62,
0xf8, 0xff, 0xff, 0xff, 0xff, 0x01, 0x90, 0x00, 0x49, 0x18, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42, 0x20, 0x4c, 0x08, 0x06,
0x00, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04, 0x93, 0x22, 0xa4, 0x84,
0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8a, 0x8c,
0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00, 0x25, 0x00, 0x14, 0xe6,
0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x45, 0x18, 0x83, 0xcc, 0x1c,
0x01, 0x42, 0xe8, 0x9e, 0xe1, 0xf2, 0x27, 0xec, 0x21, 0x24, 0x3f, 0x04,
0x9a, 0x61, 0x21, 0x50, 0x90, 0xca, 0x02, 0x86, 0x1a, 0x63, 0x8c, 0x31,
0xd0, 0xa0, 0x75, 0xdb, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92, 0xbf, 0x12,
0x92, 0x43, 0x45, 0x02, 0x91, 0x46, 0xce, 0x43, 0x44, 0x13, 0x42, 0x48,
0x48, 0x18, 0xa3, 0x10, 0x6a, 0xa8, 0x46, 0xee, 0xa0, 0xe1, 0xf2, 0x27,
0xec, 0x21, 0x24, 0x7f, 0x25, 0xa4, 0x0d, 0x69, 0x06, 0x44, 0x8c, 0x31,
0xd0, 0x1c, 0x41, 0x50, 0x0a, 0x35, 0xe0, 0x88, 0x24, 0x07, 0x02, 0x66,
0x32, 0x83, 0x71, 0x60, 0x87, 0x70, 0x98, 0x87, 0x79, 0x70, 0x03, 0x59,
0xb8, 0x85, 0x59, 0xa0, 0x07, 0x79, 0xa8, 0x87, 0x71, 0xa0, 0x87, 0x7a,
0x90, 0x87, 0x72, 0x20, 0x07, 0x51, 0xa8, 0x07, 0x73, 0x30, 0x87, 0x72,
0x90, 0x07, 0x3e, 0xa8, 0x07, 0x77, 0x98, 0x87, 0x74, 0x38, 0x07, 0x77,
0x28, 0x07, 0x72, 0x00, 0x83, 0x74, 0x70, 0x07, 0x7a, 0xf0, 0x03, 0x14,
0x0c, 0xaa, 0x73, 0x04, 0xa0, 0x00, 0x00, 0x00, 0x13, 0x14, 0x72, 0xc0,
0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79, 0x68, 0x03, 0x72, 0xc0,
0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d,
0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73,
0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07, 0x7a, 0x60, 0x07, 0x74,
0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6,
0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78,
0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x76,
0x40, 0x07, 0x43, 0x9e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x0c, 0x20, 0x00, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x18, 0x40, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4, 0x59, 0x80, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc8, 0x43, 0x00, 0x01,
0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x90, 0xc7, 0x01,
0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x21, 0x8f,
0x04, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59,
0x20, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14,
0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a,
0x25, 0x50, 0x0c, 0x25, 0x31, 0x02, 0x50, 0x18, 0x85, 0x50, 0x80, 0x01,
0x65, 0x41, 0x71, 0x04, 0x80, 0x6e, 0x81, 0x02, 0x02, 0x91, 0x9d, 0x01,
0x00, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00,
0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4, 0x8e, 0x0c, 0x6f, 0xec,
0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45, 0xc6, 0x06, 0x26, 0xc7,
0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46, 0x26, 0x8c, 0x8c, 0xe6,
0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x06, 0x64, 0x82, 0x30, 0x24, 0x1b,
0x84, 0x81, 0x98, 0x20, 0x0c, 0xca, 0x06, 0x61, 0x30, 0x28, 0x8c, 0xcd,
0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x0c, 0xcb, 0x04, 0xc1, 0x92, 0x08,
0x4c, 0x10, 0x06, 0x66, 0x82, 0x10, 0x41, 0x13, 0x84, 0xa1, 0xd9, 0x20,
0x0c, 0xcf, 0x86, 0x45, 0x59, 0x18, 0x45, 0x19, 0x1a, 0xc7, 0x71, 0xa0,
0x0d, 0x41, 0xb4, 0x81, 0x00, 0x24, 0x00, 0x98, 0x20, 0x08, 0x00, 0x89,
0xb6, 0xb0, 0x34, 0xb7, 0x09, 0xc2, 0x15, 0x4d, 0x10, 0x06, 0x67, 0xc3,
0x70, 0x0d, 0xc3, 0x04, 0x61, 0x78, 0x36, 0x04, 0xd7, 0x06, 0x43, 0xb1,
0x1e, 0x2c, 0xd3, 0x36, 0x14, 0x54, 0x05, 0x4c, 0x5b, 0x15, 0x36, 0x36,
0xbb, 0x36, 0x97, 0x34, 0xb2, 0x32, 0x37, 0xba, 0x29, 0x41, 0x50, 0x85,
0x0c, 0xcf, 0xc5, 0xae, 0x4c, 0x6e, 0x2e, 0xed, 0xcd, 0x6d, 0x4a, 0x40,
0x34, 0x21, 0xc3, 0x73, 0xb1, 0x0b, 0x63, 0xb3, 0x2b, 0x93, 0x9b, 0x12,
0x18, 0x75, 0xc8, 0xf0, 0x5c, 0xe6, 0xd0, 0xc2, 0xc8, 0xca, 0xe4, 0x9a,
0xde, 0xc8, 0xca, 0xd8, 0xa6, 0x04, 0x48, 0x19, 0x32, 0x3c, 0x17, 0xb9,
0xb2, 0xb9, 0xb7, 0x3a, 0xb9, 0xb1, 0xb2, 0xb9, 0x29, 0x81, 0x54, 0x87,
0x0c, 0xcf, 0xa5, 0xcc, 0x8d, 0x4e, 0x2e, 0x0f, 0xea, 0x2d, 0xcd, 0x8d,
0x6e, 0x6e, 0x4a, 0xb0, 0x01, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66,
0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07,
0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10,
0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce,
0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b,
0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c,
0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07,
0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11,
0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0,
0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8,
0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b,
0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b,
0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87,
0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07,
0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87,
0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81,
0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30,
0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4,
0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca,
0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39,
0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b,
0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b,
0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87,
0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20,
0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90,
0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00, 0x00, 0x00, 0x71, 0x20, 0x00, 0x00,
0x24, 0x00, 0x00, 0x00, 0x66, 0x40, 0x0d, 0x97, 0xef, 0x3c, 0x3e, 0xd0,
0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3, 0x42, 0xd8, 0x41, 0x37,
0x5c, 0xbe, 0xf3, 0xf8, 0x42, 0x44, 0x00, 0x13, 0x11, 0x02, 0xcd, 0xb0,
0x10, 0x5f, 0xe4, 0x30, 0x1b, 0xd2, 0x0c, 0x48, 0x63, 0x18, 0x01, 0x36,
0x5c, 0xbe, 0xf3, 0xf8, 0x11, 0x60, 0x6d, 0x54, 0x51, 0x10, 0x11, 0x3b,
0x39, 0x11, 0xe1, 0x23, 0xb7, 0x6d, 0x01, 0xd2, 0x70, 0xf9, 0xce, 0xe3,
0x4f, 0x47, 0x44, 0x00, 0x83, 0x38, 0xf8, 0xc8, 0x6d, 0x9b, 0x80, 0x35,
0x5c, 0xbe, 0xf3, 0xf8, 0x16, 0x50, 0x11, 0x20, 0x31, 0x95, 0x40, 0x43,
0x70, 0x0e, 0xd5, 0x4c, 0x36, 0x60, 0x0d, 0x97, 0xef, 0x3c, 0xbe, 0x05,
0x54, 0x04, 0x48, 0x4c, 0x25, 0xd0, 0x10, 0x62, 0x33, 0x10, 0x97, 0x15,
0x6c, 0xc3, 0xe5, 0x3b, 0x8f, 0x6f, 0x01, 0x15, 0xb1, 0x12, 0xc0, 0x50,
0x02, 0x0d, 0xf1, 0x21, 0x91, 0x34, 0xf9, 0xc8, 0x6d, 0x1b, 0x00, 0xc1,
0x00, 0x48, 0x03, 0x00, 0x61, 0x20, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00,
0x13, 0x04, 0x41, 0x2c, 0x10, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x34, 0x66, 0x00, 0x0a, 0x76, 0xa0, 0x30, 0x05, 0x4a, 0x76, 0xa0, 0x74,
0x03, 0x0a, 0x3c, 0xa0, 0x40, 0xca, 0x3b, 0xa0, 0x30, 0x81, 0x8a, 0x3d,
0x80, 0x50, 0x09, 0x50, 0x9b, 0x43, 0xd8, 0x1a, 0x82, 0x73, 0x10, 0xcb,
0xb2, 0x74, 0x00, 0x00, 0x23, 0x06, 0x08, 0x00, 0x82, 0x60, 0x20, 0x65,
0x4a, 0x50, 0x41, 0x23, 0x06, 0x06, 0x00, 0x82, 0x60, 0x40, 0x80, 0x81,
0x62, 0x8d, 0x18, 0x14, 0x00, 0x08, 0x82, 0x81, 0x01, 0x06, 0x4a, 0x05,
0xca, 0x8d, 0x18, 0x14, 0x00, 0x08, 0x82, 0x81, 0x11, 0x06, 0x4a, 0x09,
0xc1, 0x56, 0xe1, 0xdd, 0x88, 0xc1, 0x01, 0x80, 0x20, 0x18, 0x38, 0x61,
0x30, 0x1d, 0xc9, 0x88, 0x81, 0x03, 0x80, 0x20, 0x18, 0x2c, 0x64, 0x30,
0x05, 0x42, 0x37, 0x54, 0x55, 0xb5, 0x6c, 0x23, 0x06, 0x06, 0x00, 0x82,
0x60, 0x40, 0x8c, 0x01, 0x73, 0xd4, 0x10, 0x06, 0x3b, 0x62, 0x70, 0x00,
0x20, 0x08, 0x06, 0x0e, 0x19, 0x58, 0x0a, 0x33, 0x62, 0xe0, 0x00, 0x20,
0x08, 0x06, 0xcb, 0x19, 0x58, 0x81, 0x00, 0x06, 0x03, 0x86, 0x61, 0x8e,
0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
@@ -0,0 +1,412 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// GENERATED by DXC 1.9.2609 from wave_lanes.hlsl by compile.sh; do not edit.
#if 0
;
; Note: shader requires additional functionality:
; Wave level operations
;
;
; Input signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
;
; Output signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
; shader hash: f1232f4e8018b62b4ed048d1f2cb902f
;
; Pipeline Runtime Information:
;
;PSVRuntimeInfo:
; Compute Shader
; NumThreads=(64,1,1)
; MinimumExpectedWaveLaneCount: 0
; MaximumExpectedWaveLaneCount: 4294967295
; UsesViewID: false
; SigInputElements: 0
; SigOutputElements: 0
; SigPatchConstOrPrimElements: 0
; SigInputVectors: 0
; SigOutputVectors[0]: 0
; SigOutputVectors[1]: 0
; SigOutputVectors[2]: 0
; SigOutputVectors[3]: 0
; EntryFunctionName: main
;
;
; Buffer Definitions:
;
; Resource bind info for Out
; {
;
; uint $Element; ; Offset: 0 Size: 4
;
; }
;
;
; Resource Bindings:
;
; Name Type Format Dim ID HLSL Bind Count
; ------------------------------ ---------- ------- ----------- ------- -------------- ------
; Out UAV struct r/w U0 u0 1
;
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
%dx.types.Handle = type { i8* }
%dx.types.ResBind = type { i32, i32, i32, i8 }
%dx.types.ResourceProperties = type { i32, i32 }
%"class.RWStructuredBuffer<unsigned int>" = type { i32 }
define void @main() {
%1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 0, i32 0, i32 0, i8 1 }, i32 0, i1 false) ; CreateHandleFromBinding(bind,index,nonUniformIndex)
%2 = call i32 @dx.op.threadId.i32(i32 93, i32 0) ; ThreadId(component)
%3 = call i32 @dx.op.waveGetLaneCount(i32 112) ; WaveGetLaneCount()
%4 = shl i32 %3, 16
%5 = call i32 @dx.op.waveGetLaneIndex(i32 111) ; WaveGetLaneIndex()
%6 = or i32 %4, %5
%7 = shl i32 %2, 1
%8 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4108, i32 4 }) ; AnnotateHandle(res,props) resource: RWStructuredBuffer<stride=4>
call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %8, i32 %7, i32 0, i32 %6, i32 undef, i32 undef, i32 undef, i8 1, i32 4) ; RawBufferStore(uav,index,elementOffset,value0,value1,value2,value3,mask,alignment)
%9 = call i32 @dx.op.waveReadLaneFirst.i32(i32 118, i32 %2) ; WaveReadLaneFirst(value)
%10 = or i32 %7, 1
%11 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4108, i32 4 }) ; AnnotateHandle(res,props) resource: RWStructuredBuffer<stride=4>
call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %11, i32 %10, i32 0, i32 %9, i32 undef, i32 undef, i32 undef, i8 1, i32 4) ; RawBufferStore(uav,index,elementOffset,value0,value1,value2,value3,mask,alignment)
ret void
}
; Function Attrs: nounwind readnone
declare i32 @dx.op.threadId.i32(i32, i32) #0
; Function Attrs: nounwind readnone
declare i32 @dx.op.waveGetLaneCount(i32) #0
; Function Attrs: nounwind readonly
declare i32 @dx.op.waveGetLaneIndex(i32) #1
; Function Attrs: nounwind
declare void @dx.op.rawBufferStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i8, i32) #2
; Function Attrs: nounwind
declare i32 @dx.op.waveReadLaneFirst.i32(i32, i32) #2
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0
; Function Attrs: nounwind readnone
declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0
attributes #0 = { nounwind readnone }
attributes #1 = { nounwind readonly }
attributes #2 = { nounwind }
!llvm.ident = !{!0}
!dx.version = !{!1}
!dx.valver = !{!2}
!dx.shaderModel = !{!3}
!dx.resources = !{!4}
!dx.entryPoints = !{!8}
!0 = !{!"dxcoob 1.9.2609.5 (01b62ad47)"}
!1 = !{i32 1, i32 6}
!2 = !{i32 1, i32 9}
!3 = !{!"cs", i32 6, i32 6}
!4 = !{null, !5, null, null}
!5 = !{!6}
!6 = !{i32 0, %"class.RWStructuredBuffer<unsigned int>"* undef, !"", i32 0, i32 0, i32 1, i32 12, i1 false, i1 false, i1 false, !7}
!7 = !{i32 1, i32 4}
!8 = !{void ()* @main, !"main", null, !4, !9}
!9 = !{i32 0, i64 524304, i32 4, !10}
!10 = !{i32 64, i32 1, i32 1}
#endif
const unsigned char g_wave_lanes_cs[] = {
0x44, 0x58, 0x42, 0x43, 0x45, 0x9b, 0xdb, 0x06, 0x88, 0x56, 0xe3, 0x06,
0xc2, 0xd4, 0x29, 0x71, 0xa4, 0xce, 0x5a, 0xc8, 0x01, 0x00, 0x00, 0x00,
0x28, 0x0d, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00,
0xdc, 0x00, 0x00, 0x00, 0xe8, 0x06, 0x00, 0x00, 0x04, 0x07, 0x00, 0x00,
0x53, 0x46, 0x49, 0x30, 0x08, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x31, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x4f, 0x53, 0x47, 0x31,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x50, 0x53, 0x56, 0x30, 0x68, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x53, 0x54, 0x41, 0x54, 0x04, 0x06, 0x00, 0x00,
0x66, 0x00, 0x05, 0x00, 0x81, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c,
0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xec, 0x05, 0x00, 0x00,
0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x78, 0x01, 0x00, 0x00,
0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39,
0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62,
0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0xa4, 0x10, 0x32, 0x14,
0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88, 0x48, 0x90, 0x14, 0x20,
0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90,
0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a,
0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0xa8, 0x0d,
0x86, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20, 0x01, 0xd5, 0x06, 0x62,
0xf8, 0xff, 0xff, 0xff, 0xff, 0x01, 0x90, 0x00, 0x49, 0x18, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42, 0x20, 0x4c, 0x08, 0x06,
0x00, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04, 0x93, 0x22, 0xa4, 0x84,
0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14, 0x12, 0x4c, 0x8a, 0x8c,
0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00, 0x25, 0x00, 0x14, 0xe6,
0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x45, 0x18, 0x83, 0xcc, 0x1c,
0x01, 0x42, 0xe8, 0x9e, 0xe1, 0xf2, 0x27, 0xec, 0x21, 0x24, 0x3f, 0x04,
0x9a, 0x61, 0x21, 0x50, 0x90, 0xca, 0x02, 0x86, 0x1a, 0x63, 0x8c, 0x31,
0xd0, 0xa0, 0x75, 0xdb, 0x70, 0xf9, 0x13, 0xf6, 0x10, 0x92, 0xbf, 0x12,
0x92, 0x43, 0x45, 0x02, 0x91, 0x46, 0xce, 0x43, 0x44, 0x13, 0x42, 0x48,
0x48, 0x18, 0xa3, 0x10, 0x6a, 0xa8, 0x46, 0xee, 0xa0, 0xe1, 0xf2, 0x27,
0xec, 0x21, 0x24, 0x7f, 0x25, 0xa4, 0x0d, 0x69, 0x06, 0x44, 0x8c, 0x31,
0xd0, 0x1c, 0x41, 0x50, 0x0a, 0x35, 0xe0, 0x88, 0x24, 0x07, 0x02, 0x66,
0x32, 0x83, 0x71, 0x60, 0x87, 0x70, 0x98, 0x87, 0x79, 0x70, 0x03, 0x59,
0xb8, 0x85, 0x59, 0xa0, 0x07, 0x79, 0xa8, 0x87, 0x71, 0xa0, 0x87, 0x7a,
0x90, 0x87, 0x72, 0x20, 0x07, 0x51, 0xa8, 0x07, 0x73, 0x30, 0x87, 0x72,
0x90, 0x07, 0x3e, 0xa8, 0x07, 0x77, 0x98, 0x87, 0x74, 0x38, 0x07, 0x77,
0x28, 0x07, 0x72, 0x00, 0x83, 0x74, 0x70, 0x07, 0x7a, 0xf0, 0x03, 0x14,
0x0c, 0xaa, 0x73, 0x04, 0xa0, 0x00, 0x00, 0x00, 0x13, 0x14, 0x72, 0xc0,
0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79, 0x68, 0x03, 0x72, 0xc0,
0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d,
0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x73,
0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07, 0x7a, 0x60, 0x07, 0x74,
0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6,
0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78,
0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07, 0x76,
0x40, 0x07, 0x43, 0x9e, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x0c, 0x20, 0x00, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x18, 0x40, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4, 0x59, 0x80, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xc8, 0x43, 0x00, 0x01,
0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x90, 0xc7, 0x01,
0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x21, 0x8f,
0x04, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59,
0x20, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x14,
0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x1a,
0x25, 0x50, 0x0c, 0x23, 0x00, 0x85, 0x51, 0x08, 0x65, 0x50, 0x0e, 0xa5,
0x30, 0x03, 0x50, 0x80, 0x01, 0xc5, 0x51, 0x04, 0x14, 0x47, 0x00, 0xe8,
0x16, 0x28, 0x20, 0x10, 0xd9, 0x19, 0x00, 0xaa, 0x33, 0x00, 0x00, 0x00,
0x79, 0x18, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90,
0x46, 0x02, 0x13, 0xc4, 0x8e, 0x0c, 0x6f, 0xec, 0xed, 0x4d, 0x0c, 0x24,
0xc6, 0x25, 0xc7, 0x45, 0xc6, 0x06, 0x26, 0xc7, 0xa5, 0x06, 0x04, 0x05,
0x26, 0x46, 0xcc, 0x46, 0x26, 0x8c, 0x8c, 0xe6, 0x26, 0x65, 0x43, 0x10,
0x4c, 0x10, 0x06, 0x64, 0x82, 0x30, 0x24, 0x1b, 0x84, 0x81, 0x98, 0x20,
0x0c, 0xca, 0x06, 0xc1, 0x30, 0x28, 0x8c, 0xcd, 0x6d, 0x18, 0x10, 0x82,
0x98, 0x20, 0x58, 0x16, 0x87, 0xa7, 0x3a, 0xba, 0x09, 0xc2, 0xb0, 0x4c,
0x10, 0x22, 0x6a, 0x82, 0x30, 0x30, 0x1b, 0x84, 0xc1, 0xd9, 0xb0, 0x18,
0xca, 0x62, 0x18, 0x03, 0xd3, 0x34, 0xcd, 0xb3, 0x21, 0x80, 0x36, 0x10,
0x40, 0x04, 0x00, 0x13, 0x84, 0xea, 0x62, 0x80, 0x36, 0x41, 0x18, 0x9a,
0x09, 0xc2, 0xe0, 0x4c, 0x10, 0x86, 0x67, 0x83, 0x41, 0x50, 0x95, 0x61,
0x5d, 0x13, 0x84, 0x01, 0xda, 0x20, 0x18, 0xd9, 0x86, 0x40, 0xdb, 0x20,
0x18, 0xdb, 0x86, 0xc1, 0xc1, 0xb8, 0x0d, 0x83, 0x31, 0x75, 0x13, 0x04,
0x01, 0xd8, 0x00, 0x6c, 0x18, 0x0c, 0x30, 0x00, 0x83, 0x0d, 0x41, 0x18,
0x6c, 0x18, 0x86, 0x4f, 0x0c, 0x48, 0xb4, 0x85, 0xa5, 0xb9, 0x4d, 0x10,
0xae, 0x6a, 0x82, 0x30, 0x44, 0x1b, 0x06, 0x33, 0x18, 0x86, 0x0d, 0x84,
0x51, 0x06, 0xce, 0x19, 0x6c, 0x28, 0x3e, 0x32, 0x00, 0x24, 0x34, 0x60,
0x91, 0xe6, 0x36, 0x47, 0x37, 0x37, 0x41, 0x18, 0x24, 0x26, 0x74, 0x65,
0x78, 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x13, 0x84, 0x61, 0x62, 0x51,
0x97, 0xe6, 0x46, 0x37, 0xb7, 0xc1, 0x50, 0x83, 0x35, 0x60, 0x83, 0x36,
0x70, 0x03, 0xa7, 0x0a, 0x1b, 0x9b, 0x5d, 0x9b, 0x4b, 0x1a, 0x59, 0x99,
0x1b, 0xdd, 0x94, 0x20, 0xa8, 0x42, 0x86, 0xe7, 0x62, 0x57, 0x26, 0x37,
0x97, 0xf6, 0xe6, 0x36, 0x25, 0x20, 0x9a, 0x90, 0xe1, 0xb9, 0xd8, 0x85,
0xb1, 0xd9, 0x95, 0xc9, 0x4d, 0x09, 0x8c, 0x3a, 0x64, 0x78, 0x2e, 0x73,
0x68, 0x61, 0x64, 0x65, 0x72, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x53, 0x02,
0xa4, 0x0c, 0x19, 0x9e, 0x8b, 0x5c, 0xd9, 0xdc, 0x5b, 0x9d, 0xdc, 0x58,
0xd9, 0xdc, 0x94, 0x20, 0xaa, 0x44, 0x86, 0xe7, 0x42, 0x97, 0x07, 0x57,
0x16, 0xe4, 0xe6, 0xf6, 0x46, 0x17, 0x46, 0x97, 0xf6, 0xe6, 0x36, 0x37,
0x45, 0xe8, 0xc4, 0xa0, 0x0e, 0x19, 0x9e, 0x4b, 0x99, 0x1b, 0x9d, 0x5c,
0x1e, 0xd4, 0x5b, 0x9a, 0x1b, 0xdd, 0xdc, 0x94, 0x00, 0x0d, 0xba, 0x90,
0xe1, 0xb9, 0x8c, 0xbd, 0xd5, 0xb9, 0xd1, 0x95, 0xc9, 0xcd, 0x4d, 0x09,
0xdc, 0x00, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00,
0x33, 0x08, 0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88,
0x43, 0x38, 0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73,
0x98, 0x71, 0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e,
0x33, 0x0c, 0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30,
0x05, 0x3d, 0x88, 0x43, 0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8,
0x43, 0x3d, 0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b,
0x08, 0x07, 0x79, 0x48, 0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76,
0x78, 0x87, 0x70, 0x20, 0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e,
0xe1, 0x30, 0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e,
0x33, 0x10, 0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61,
0x1e, 0x66, 0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4,
0x03, 0x3c, 0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76,
0x60, 0x07, 0x7b, 0x68, 0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37,
0x80, 0x87, 0x70, 0x90, 0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76,
0xf8, 0x05, 0x76, 0x78, 0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71,
0x18, 0x87, 0x72, 0x98, 0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e,
0xee, 0xe0, 0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1,
0x1c, 0xe4, 0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61,
0x1c, 0xca, 0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90,
0x43, 0x39, 0xc8, 0x43, 0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8,
0xc3, 0x38, 0x94, 0x43, 0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc,
0x83, 0x3c, 0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4,
0x21, 0x07, 0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19,
0xd1, 0x43, 0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06,
0xf6, 0x10, 0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f,
0xf4, 0x00, 0x00, 0x00, 0x71, 0x20, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00,
0x66, 0x40, 0x0d, 0x97, 0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c,
0x44, 0x08, 0x34, 0xc3, 0x42, 0xd8, 0x41, 0x37, 0x5c, 0xbe, 0xf3, 0xf8,
0x42, 0x44, 0x00, 0x13, 0x11, 0x02, 0xcd, 0xb0, 0x10, 0x5f, 0xe4, 0x30,
0x1b, 0xd2, 0x0c, 0x48, 0x63, 0x18, 0x01, 0x36, 0x5c, 0xbe, 0xf3, 0xf8,
0x11, 0x60, 0x6d, 0x54, 0x51, 0x10, 0x11, 0x3b, 0x39, 0x11, 0xe1, 0x23,
0xb7, 0x6d, 0x01, 0xd2, 0x70, 0xf9, 0xce, 0xe3, 0x4f, 0x47, 0x44, 0x00,
0x83, 0x38, 0xf8, 0xc8, 0x6d, 0x9b, 0x80, 0x35, 0x5c, 0xbe, 0xf3, 0xf8,
0x16, 0x50, 0x11, 0x20, 0x31, 0x95, 0x40, 0x43, 0x70, 0x0e, 0xd5, 0x4c,
0x36, 0x60, 0x0d, 0x97, 0xef, 0x3c, 0xbe, 0x05, 0x54, 0x04, 0x48, 0x4c,
0x25, 0xd0, 0x10, 0x62, 0x33, 0x10, 0x97, 0x15, 0x6c, 0xc3, 0xe5, 0x3b,
0x8f, 0x6f, 0x01, 0x15, 0xb1, 0x12, 0xc0, 0x50, 0x02, 0x0d, 0xf1, 0x21,
0x91, 0x34, 0xf9, 0xc8, 0x6d, 0x1b, 0x00, 0xc1, 0x00, 0x48, 0x03, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x41, 0x53, 0x48, 0x14, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xf1, 0x23, 0x2f, 0x4e, 0x80, 0x18, 0xb6, 0x2b,
0x4e, 0xd0, 0x48, 0xd1, 0xf2, 0xcb, 0x90, 0x2f, 0x44, 0x58, 0x49, 0x4c,
0x1c, 0x06, 0x00, 0x00, 0x66, 0x00, 0x05, 0x00, 0x87, 0x01, 0x00, 0x00,
0x44, 0x58, 0x49, 0x4c, 0x06, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x04, 0x06, 0x00, 0x00, 0x42, 0x43, 0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00,
0x7e, 0x01, 0x00, 0x00, 0x0b, 0x82, 0x20, 0x00, 0x02, 0x00, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x07, 0x81, 0x23, 0x91, 0x41, 0xc8, 0x04, 0x49,
0x06, 0x10, 0x32, 0x39, 0x92, 0x01, 0x84, 0x0c, 0x25, 0x05, 0x08, 0x19,
0x1e, 0x04, 0x8b, 0x62, 0x80, 0x14, 0x45, 0x02, 0x42, 0x92, 0x0b, 0x42,
0xa4, 0x10, 0x32, 0x14, 0x38, 0x08, 0x18, 0x4b, 0x0a, 0x32, 0x52, 0x88,
0x48, 0x90, 0x14, 0x20, 0x43, 0x46, 0x88, 0xa5, 0x00, 0x19, 0x32, 0x42,
0xe4, 0x48, 0x0e, 0x90, 0x91, 0x22, 0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c,
0xe1, 0x83, 0xe5, 0x8a, 0x04, 0x29, 0x46, 0x06, 0x51, 0x18, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x1b, 0x8c, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x07,
0x40, 0x02, 0xa8, 0x0d, 0x86, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x03, 0x20,
0x01, 0xd5, 0x06, 0x62, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x01, 0x90, 0x00,
0x49, 0x18, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x13, 0x82, 0x60, 0x42,
0x20, 0x4c, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, 0x89, 0x20, 0x00, 0x00,
0x32, 0x00, 0x00, 0x00, 0x32, 0x22, 0x48, 0x09, 0x20, 0x64, 0x85, 0x04,
0x93, 0x22, 0xa4, 0x84, 0x04, 0x93, 0x22, 0xe3, 0x84, 0xa1, 0x90, 0x14,
0x12, 0x4c, 0x8a, 0x8c, 0x0b, 0x84, 0xa4, 0x4c, 0x10, 0x60, 0x23, 0x00,
0x25, 0x00, 0x14, 0xe6, 0x08, 0xc0, 0xa0, 0x0c, 0x63, 0x0c, 0x22, 0x45,
0x18, 0x83, 0xcc, 0x1c, 0x01, 0x42, 0xe8, 0x9e, 0xe1, 0xf2, 0x27, 0xec,
0x21, 0x24, 0x3f, 0x04, 0x9a, 0x61, 0x21, 0x50, 0x90, 0xca, 0x02, 0x86,
0x1a, 0x63, 0x8c, 0x31, 0xd0, 0xa0, 0x75, 0xdb, 0x70, 0xf9, 0x13, 0xf6,
0x10, 0x92, 0xbf, 0x12, 0x92, 0x43, 0x45, 0x02, 0x91, 0x46, 0xce, 0x43,
0x44, 0x13, 0x42, 0x48, 0x48, 0x18, 0xa3, 0x10, 0x6a, 0xa8, 0x46, 0xee,
0xa0, 0xe1, 0xf2, 0x27, 0xec, 0x21, 0x24, 0x7f, 0x25, 0xa4, 0x0d, 0x69,
0x06, 0x44, 0x8c, 0x31, 0xd0, 0x1c, 0x41, 0x50, 0x0a, 0x35, 0xe0, 0x88,
0x24, 0x07, 0x02, 0x66, 0x32, 0x83, 0x71, 0x60, 0x87, 0x70, 0x98, 0x87,
0x79, 0x70, 0x03, 0x59, 0xb8, 0x85, 0x59, 0xa0, 0x07, 0x79, 0xa8, 0x87,
0x71, 0xa0, 0x87, 0x7a, 0x90, 0x87, 0x72, 0x20, 0x07, 0x51, 0xa8, 0x07,
0x73, 0x30, 0x87, 0x72, 0x90, 0x07, 0x3e, 0xa8, 0x07, 0x77, 0x98, 0x87,
0x74, 0x38, 0x07, 0x77, 0x28, 0x07, 0x72, 0x00, 0x83, 0x74, 0x70, 0x07,
0x7a, 0xf0, 0x03, 0x14, 0x0c, 0xaa, 0x73, 0x04, 0xa0, 0x00, 0x00, 0x00,
0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68, 0x87, 0x79,
0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d, 0xd0, 0x0e,
0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73, 0x20, 0x07,
0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e,
0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76, 0x40, 0x07,
0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76, 0xa0, 0x07,
0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76, 0x40, 0x07,
0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07,
0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x04, 0x10, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x79, 0x0c, 0x20,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xf2, 0x18,
0x40, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xe4,
0x59, 0x80, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60,
0xc8, 0x43, 0x00, 0x01, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xc0, 0x90, 0xc7, 0x01, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x21, 0x8f, 0x04, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x59, 0x20, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x32, 0x1e, 0x98, 0x14, 0x19, 0x11, 0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47,
0xc6, 0x04, 0x43, 0x1a, 0x25, 0x50, 0x0c, 0x25, 0x31, 0x02, 0x50, 0x18,
0x85, 0x50, 0x80, 0x01, 0x14, 0x47, 0x00, 0xe8, 0x16, 0x28, 0x20, 0x10,
0xd9, 0x19, 0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00,
0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02, 0x13, 0xc4, 0x8e, 0x0c, 0x6f, 0xec,
0xed, 0x4d, 0x0c, 0x24, 0xc6, 0x25, 0xc7, 0x45, 0xc6, 0x06, 0x26, 0xc7,
0xa5, 0x06, 0x04, 0x05, 0x26, 0x46, 0xcc, 0x46, 0x26, 0x8c, 0x8c, 0xe6,
0x26, 0x65, 0x43, 0x10, 0x4c, 0x10, 0x06, 0x64, 0x82, 0x30, 0x24, 0x1b,
0x84, 0x81, 0x98, 0x20, 0x0c, 0xca, 0x06, 0x61, 0x30, 0x28, 0x8c, 0xcd,
0x6d, 0x18, 0x10, 0x82, 0x98, 0x20, 0x0c, 0xcb, 0x04, 0xc1, 0x8a, 0x08,
0x4c, 0x10, 0x06, 0x66, 0x82, 0x10, 0x3d, 0x13, 0x84, 0xa1, 0xd9, 0x20,
0x0c, 0xcf, 0x86, 0x45, 0x59, 0x18, 0x45, 0x19, 0x1a, 0xc7, 0x71, 0xa0,
0x0d, 0x41, 0xb4, 0x81, 0x00, 0x24, 0x00, 0x98, 0x20, 0x08, 0x00, 0x89,
0xb6, 0xb0, 0x34, 0xb7, 0x09, 0xc2, 0x05, 0x4d, 0x10, 0x06, 0x67, 0xc3,
0x70, 0x0d, 0xc3, 0x06, 0x42, 0xb1, 0x1e, 0x6c, 0x43, 0x41, 0x55, 0xc0,
0x94, 0x55, 0x61, 0x63, 0xb3, 0x6b, 0x73, 0x49, 0x23, 0x2b, 0x73, 0xa3,
0x9b, 0x12, 0x04, 0x55, 0xc8, 0xf0, 0x5c, 0xec, 0xca, 0xe4, 0xe6, 0xd2,
0xde, 0xdc, 0xa6, 0x04, 0x44, 0x13, 0x32, 0x3c, 0x17, 0xbb, 0x30, 0x36,
0xbb, 0x32, 0xb9, 0x29, 0x81, 0x51, 0x87, 0x0c, 0xcf, 0x65, 0x0e, 0x2d,
0x8c, 0xac, 0x4c, 0xae, 0xe9, 0x8d, 0xac, 0x8c, 0x6d, 0x4a, 0x80, 0x94,
0x21, 0xc3, 0x73, 0x91, 0x2b, 0x9b, 0x7b, 0xab, 0x93, 0x1b, 0x2b, 0x9b,
0x9b, 0x12, 0x48, 0x75, 0xc8, 0xf0, 0x5c, 0xca, 0xdc, 0xe8, 0xe4, 0xf2,
0xa0, 0xde, 0xd2, 0xdc, 0xe8, 0xe6, 0xa6, 0x04, 0x19, 0x00, 0x00, 0x00,
0x79, 0x18, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x33, 0x08, 0x80, 0x1c,
0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88, 0x43, 0x38, 0x84, 0xc3,
0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73, 0x98, 0x71, 0x0c, 0xe6,
0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c, 0x42, 0x1e,
0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d, 0x88, 0x43,
0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d, 0x8c, 0x03,
0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b, 0x08, 0x07, 0x79, 0x48,
0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76, 0x78, 0x87, 0x70, 0x20,
0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30, 0x0f, 0x6e,
0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10, 0xc4, 0x1d,
0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66, 0x30, 0x89,
0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c, 0xbc, 0x83,
0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07, 0x7b, 0x68,
0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37, 0x80, 0x87, 0x70, 0x90,
0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76, 0xf8, 0x05, 0x76, 0x78,
0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71, 0x18, 0x87, 0x72, 0x98,
0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0, 0x0e, 0xf5,
0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c,
0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca, 0x21, 0x1c,
0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90, 0x43, 0x39, 0xc8, 0x43,
0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38, 0x94, 0x43,
0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c, 0xfc, 0x82,
0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07, 0x7c, 0x70,
0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19, 0xd1, 0x43, 0x0e, 0xf8,
0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10, 0x0e, 0xf2,
0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00, 0x00, 0x00,
0x71, 0x20, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x66, 0x40, 0x0d, 0x97,
0xef, 0x3c, 0x3e, 0xd0, 0x34, 0xce, 0x04, 0x4c, 0x44, 0x08, 0x34, 0xc3,
0x42, 0xd8, 0x41, 0x37, 0x5c, 0xbe, 0xf3, 0xf8, 0x42, 0x44, 0x00, 0x13,
0x11, 0x02, 0xcd, 0xb0, 0x10, 0x5f, 0xe4, 0x30, 0x1b, 0xd2, 0x0c, 0x48,
0x63, 0x18, 0x01, 0x36, 0x5c, 0xbe, 0xf3, 0xf8, 0x11, 0x60, 0x6d, 0x54,
0x51, 0x10, 0x11, 0x3b, 0x39, 0x11, 0xe1, 0x23, 0xb7, 0x6d, 0x01, 0xd2,
0x70, 0xf9, 0xce, 0xe3, 0x4f, 0x47, 0x44, 0x00, 0x83, 0x38, 0xf8, 0xc8,
0x6d, 0x9b, 0x80, 0x35, 0x5c, 0xbe, 0xf3, 0xf8, 0x16, 0x50, 0x11, 0x20,
0x31, 0x95, 0x40, 0x43, 0x70, 0x0e, 0xd5, 0x4c, 0x36, 0x60, 0x0d, 0x97,
0xef, 0x3c, 0xbe, 0x05, 0x54, 0x04, 0x48, 0x4c, 0x25, 0xd0, 0x10, 0x62,
0x33, 0x10, 0x97, 0x15, 0x6c, 0xc3, 0xe5, 0x3b, 0x8f, 0x6f, 0x01, 0x15,
0xb1, 0x12, 0xc0, 0x50, 0x02, 0x0d, 0xf1, 0x21, 0x91, 0x34, 0xf9, 0xc8,
0x6d, 0x1b, 0x00, 0xc1, 0x00, 0x48, 0x03, 0x00, 0x61, 0x20, 0x00, 0x00,
0x2a, 0x00, 0x00, 0x00, 0x13, 0x04, 0x41, 0x2c, 0x10, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x34, 0x66, 0x00, 0x0a, 0x76, 0xa0, 0x30, 0x05,
0x4a, 0x76, 0xa0, 0x74, 0x03, 0x0a, 0x3c, 0xa0, 0x40, 0xca, 0x3b, 0xa0,
0x30, 0x81, 0x8a, 0x3d, 0x80, 0x50, 0x09, 0x50, 0x9b, 0x43, 0xd0, 0x1a,
0x82, 0x73, 0x10, 0xcb, 0xb2, 0x70, 0x00, 0x00, 0x23, 0x06, 0x08, 0x00,
0x82, 0x60, 0x20, 0x61, 0x4a, 0x40, 0x41, 0x23, 0x06, 0x06, 0x00, 0x82,
0x60, 0x40, 0x7c, 0x4a, 0x35, 0x62, 0x50, 0x00, 0x20, 0x08, 0x06, 0xc6,
0xa7, 0x54, 0xa0, 0xdc, 0x88, 0x41, 0x01, 0x80, 0x20, 0x18, 0x18, 0x60,
0xa0, 0x94, 0x10, 0x6c, 0x15, 0xdd, 0x8d, 0x18, 0x1c, 0x00, 0x08, 0x82,
0x81, 0x03, 0x06, 0xd3, 0x91, 0x8c, 0x18, 0x38, 0x00, 0x08, 0x82, 0xc1,
0x32, 0x06, 0x53, 0x20, 0x70, 0x43, 0x55, 0x55, 0x8b, 0x36, 0x62, 0x60,
0x00, 0x20, 0x08, 0x06, 0x84, 0x18, 0x30, 0x47, 0x0d, 0x60, 0xb0, 0x23,
0x06, 0x07, 0x00, 0x82, 0x60, 0xe0, 0x8c, 0x81, 0xa5, 0x30, 0x23, 0x06,
0x0e, 0x00, 0x82, 0x60, 0xb0, 0x98, 0x81, 0x15, 0x08, 0xdf, 0x80, 0x61,
0x98, 0xd3, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00
};
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// #453: original synthetic kernel. Each thread of one 64-thread group records the
// wave width it ran with, its lane index, and the dispatch index of its wave's first
// active lane (which identifies the wave). Built twice (see compile.sh):
// g_wave_lanes_cs no WaveSize attribute (control: must run)
// g_wave64_lanes_cs BX_WAVE64 defined, [WaveSize(64)] (the case under test)
// The fixture computes the expected layout itself from the reported wave width.
RWStructuredBuffer<uint> Out : register(u0);
#ifdef BX_WAVE64
[WaveSize(64)]
#endif
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID)
{
Out[2 * id.x] = (WaveGetLaneCount() << 16) | WaveGetLaneIndex();
Out[2 * id.x + 1] = WaveReadLaneFirst(id.x);
}
@@ -6,7 +6,9 @@
# CreateWindowExA & co. bind to the ext-ms-win-rtcore-ntuser-* shims instead of
# the toolchain's default user32 import library.
add_executable(test_integration_boot main.cpp)
target_include_directories(test_integration_boot PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_include_directories(test_integration_boot PRIVATE
"${BX_ABI_INCLUDE_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/../../../shims/xg_xs")
target_link_libraries(test_integration_boot PRIVATE
ntuser_win_ansi_1_0
ntuser_win_1_0
@@ -24,7 +24,8 @@
* or an error-severity exception.
*
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
* fixture deliberately invents no console structure layouts.
* fixture deliberately invents no console structure layouts. The xg_xs
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
*/
#include <windows.h>
#include <unknwn.h>
@@ -40,6 +41,7 @@
#include "bx_config.h"
#include "bx_log.h"
#include "bx_xmem_internal.h"
#include "xg_texture.h"
#define BX_IMPORT __declspec(dllimport)
@@ -94,11 +96,7 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
/* GameInput.dll (ordinal 1) */
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
/* xg_xs.dll */
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const void* desc, void** out_computer);
BX_IMPORT uint32_t WINAPI XGSuggestSwizzleMode(uint32_t resource_type, uint32_t format, uint32_t width,
uint32_t height, uint32_t depth, uint32_t mip_levels,
uint32_t sample_count, uint32_t flags);
/* xg_xs.dll is declared by "xg_texture.h". */
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
@@ -651,27 +649,71 @@ void stage_acphal_heap() {
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
/*
* 100x50 R8G8B8A8 with two mips, so both public D3D12 alignments matter. By hand:
* mip 0: 100 * 4 = 400 bytes per row, pitch 512 (256-byte pitch alignment);
* ends at 49 * 512 + 400 = 25488.
* mip 1: starts at the next 512 boundary, 25600; 50 * 4 = 200 bytes per row,
* pitch 256; ends at 25600 + 24 * 256 + 200 = 31944.
* total: 31944 rounded up to 512 = 32256.
*/
void* stage_xg_texture_computer() {
begin_stage("xg_xs_texture_computer");
bx_xg_resource_desc desc = {};
desc.dimension = BX_XG_DIMENSION_TEXTURE2D;
desc.width = 100;
desc.height = 50;
desc.depth_or_array_size = 1;
desc.mip_levels = 2;
desc.format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.sample_desc.count = 1;
desc.layout = BX_XG_LAYOUT_LINEAR;
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
HRESULT hr = XGCreateTextureComputer(&desc, &object);
if (hr != S_OK || !object || object == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer hr=0x%08lx object=%p",
static_cast<unsigned long>(hr), object);
return nullptr;
}
auto* computer = static_cast<bx_xg_texture_computer*>(object);
bx_xg_placed_footprint mips[2] = {};
uint32_t rows[2] = {};
uint64_t row_bytes[2] = {};
uint64_t total = 0;
hr = computer->lpVtbl->GetResourceLayout(computer, 0, 2, 0, mips, rows, row_bytes, &total);
auto shape_is = [](const bx_xg_subresource_footprint& f, uint32_t width, uint32_t height, uint32_t pitch) {
return f.format == DXGI_FORMAT_R8G8B8A8_UNORM && f.width == width && f.height == height && f.depth == 1 &&
f.row_pitch == pitch;
};
const bool mip0 = mips[0].offset == 0 && shape_is(mips[0].footprint, 100, 50, 512) && mips[0].copy_end == 25488 &&
rows[0] == 50 && row_bytes[0] == 400;
const bool mip1 = mips[1].offset == 25600 && shape_is(mips[1].footprint, 50, 25, 256) && mips[1].copy_end == 31944 &&
rows[1] == 25 && row_bytes[1] == 200;
if (hr == S_OK && mip0 && mip1 && total == 32256) {
checkpoint("xg_xs_texture_computer", Status::Pass,
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
} else {
checkpoint("xg_xs_texture_computer", Status::Fail,
"GetResourceLayout hr=0x%08lx mip0_ok=%d mip1_ok=%d total=%llu",
static_cast<unsigned long>(hr), mip0, mip1, static_cast<unsigned long long>(total));
}
return object;
}
void* stage_xg_xs() {
begin_stage("xg_xs_swizzle_mode");
/* D3D12_RESOURCE_DIMENSION_TEXTURE2D / DXGI_FORMAT_R8G8B8A8_UNORM, 256x256, 1 mip, 1 sample. */
uint32_t mode_a = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
uint32_t mode_b = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
if (mode_a == mode_b) {
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode is deterministic for identical inputs (mode=%u)", mode_a);
if (mode_a == BX_XG_LAYOUT_LINEAR && mode_b == mode_a) {
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (mode=%u)", mode_a);
} else {
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u for identical inputs", mode_a, mode_b);
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
}
begin_stage("xg_xs_texture_computer");
void* computer = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
HRESULT hr = XGCreateTextureComputer(nullptr, &computer);
if (computer == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer left the out pointer unwritten (hr=0x%08lx)",
static_cast<unsigned long>(hr));
return nullptr;
}
report_create("xg_xs_texture_computer", "XGCreateTextureComputer", hr, computer, true);
return hr == S_OK ? computer : nullptr;
return stage_xg_texture_computer();
}
/* ---- Stage 14: d3d12_xs ------------------------------------------------------------------- */
@@ -825,7 +867,12 @@ int main(int argc, char** argv) {
/* --- Shutdown (reverse order) ----------------------------------------- */
begin_stage("shutdown");
release_com(device);
release_com(texture_computer);
/* The fixture holds the only reference, so this Release must return 0. */
ULONG texture_refs = 0;
if (texture_computer) {
auto* computer = static_cast<bx_xg_texture_computer*>(texture_computer);
texture_refs = computer->lpVtbl->Release(computer);
}
release_com(game_input);
bool dsp_closed = true;
if (dsp) {
@@ -841,10 +888,11 @@ int main(int argc, char** argv) {
if (runtime_initialized) XGameRuntimeUninitialize();
LONG faults = InterlockedCompareExchange(&g_error_exceptions, 0, 0);
if (dsp_closed && apu_closed && faults == 0) {
if (dsp_closed && apu_closed && texture_refs == 0 && faults == 0) {
checkpoint("shutdown", Status::Pass, "reverse-order teardown completed with 0 error-severity exceptions");
} else {
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d error_exceptions=%ld", dsp_closed, apu_closed, faults);
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d texture_refs=%lu error_exceptions=%ld",
dsp_closed, apu_closed, texture_refs, faults);
}
if (fault_handle) RemoveVectoredExceptionHandler(fault_handle);
SetUnhandledExceptionFilter(g_prev_unhandled_filter);
@@ -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();
}
@@ -0,0 +1,4 @@
# #457: xgameruntime.dll reached by LOAD_LIBRARY_SEARCH_SYSTEM32 after bx-cli run stages it.
# Links no shim: the load under test is the dynamic one GDK titles make.
add_executable(test_system32_staging main.cpp)
target_link_libraries(test_system32_staging PRIVATE kernel32)
@@ -0,0 +1,112 @@
/*
* #457 / #482: clean-room synthetic test for system32 shim staging by `bx-cli run`.
*
* GDK titles load `xgameruntime.dll` and `GameInput.dll` with LoadLibraryExW(...,
* LOAD_LIBRARY_SEARCH_SYSTEM32), which does not search WINEPATH or the executable's folder.
* In addition, Wine pre-populates `system32\gameinput.dll` with a builtin stub whose
* `GameInputCreate` returns E_NOTIMPL.
*
* 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>
#include <cwchar>
namespace {
int g_checks = 0;
int g_failures = 0;
bool check(bool ok, const char* what) {
g_checks++;
if (!ok) {
g_failures++;
std::fprintf(stderr, "FAIL: %s\n", what);
} else {
std::printf("PASS: %s\n", what);
}
return ok;
}
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, needle) != nullptr;
}
} // namespace
int main(int argc, char** argv) {
const bool expect_missing = argc > 1 && std::strcmp(argv[1], "--expect-missing") == 0;
HMODULE sys = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (expect_missing) {
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 xgameruntime.dll load fails");
if (sys) 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;
}
@@ -2,3 +2,6 @@ add_executable(test_veh_clwb main.cpp)
target_include_directories(test_veh_clwb PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_compile_options(test_veh_clwb PRIVATE -mavx2 -mfma)
target_link_libraries(test_veh_clwb PRIVATE bx_runtime_veh xmem kernel32)
add_executable(test_veh_unhandled main_unhandled.cpp)
target_link_libraries(test_veh_unhandled PRIVATE bx_runtime_veh kernel32)
+19 -9
View File
@@ -29,15 +29,25 @@ int main() {
}
}
/* 2. Verify clwb trapping via bx_runtime_veh.dll (both legacy and REX forms) */
alignas(64) uint8_t buf[128] = {0x42};
uint64_t before = bx_veh_get_clwb_trap_count();
__asm__ volatile("clwb (%0)" :: "r"(buf) : "memory");
__asm__ volatile("clwb 64(%0)" :: "r"(buf) : "memory");
uint64_t after = bx_veh_get_clwb_trap_count();
std::printf("clwb traps observed: %llu -> %llu\n",
static_cast<unsigned long long>(before),
static_cast<unsigned long long>(after));
// Fixed registers ensure the assembler emits the intended ModRM/REX forms.
alignas(64) uint8_t buf[512] = {0x42};
const uint64_t before = bx_veh_get_clwb_trap_count();
__asm__ volatile(
"clwb (%%rax)\n\t"
"clwb 64(%%rax)\n\t"
"clwb 256(%%rax)\n\t"
"mov %%rax, %%r8\n\t"
"clwb (%%r8)\n\t"
"clwb 64(%%rax,%%rcx,4)\n\t"
"clwb (%%rip)"
:: "a"(buf), "c"(8) : "r8", "memory");
const uint64_t delta = bx_veh_get_clwb_trap_count() - before;
if (delta != 6) {
std::fprintf(stderr, "FAIL: expected 6 CLWB traps, observed %llu\n",
static_cast<unsigned long long>(delta));
return 4;
}
std::printf("CLWB traps observed: %llu\n", static_cast<unsigned long long>(delta));
/* 3. Verify basic XMem allocation + transfer + stats contract */
void* src = XMemAlloc(4096, 0);
@@ -0,0 +1,16 @@
#include <windows.h>
#include <cstdint>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
// Run in its own process. The launcher should report failure and the trace
// should contain a single unhandled_exception with RAX set to the marker.
int main() {
SetErrorMode(SEM_NOGPFAULTERRORBOX);
// Keep a static import on bx_runtime_veh.dll so its DLL_PROCESS_ATTACH filter is installed.
volatile uint64_t attached_traps = bx_veh_get_clwb_trap_count();
(void)attached_traps;
constexpr uint64_t marker = 0x123456789abcdef0ULL;
__asm__ volatile("ud2" :: "a"(marker) : "memory");
return 1;
}
@@ -0,0 +1,6 @@
add_executable(test_win32_bridge main.cpp)
target_link_libraries(test_win32_bridge PRIVATE kernel32 user32)
add_dependencies(test_win32_bridge
psm_appnotify_1_0 psm_appnotify_1_1
ntuser_msg_1_0 ntuser_msg_ansi_1_0 ntuser_win_1_0 ntuser_win_ansi_1_0
)
@@ -0,0 +1,372 @@
#include <windows.h>
#include <array>
#include <atomic>
#include <bit>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <thread>
#include <unordered_set>
namespace {
constexpr UINT kMessage = WM_APP + 1;
constexpr WPARAM kPayload = 42;
decltype(&DefWindowProcA) g_def_window_proc;
bool g_received_message = false;
std::atomic<bool> g_callback_called{false};
struct ScopedModule {
HMODULE handle = nullptr;
ScopedModule() = default;
explicit ScopedModule(HMODULE h) : handle(h) {}
~ScopedModule() {
if (handle) {
FreeLibrary(handle);
}
}
ScopedModule(const ScopedModule&) = delete;
ScopedModule& operator=(const ScopedModule&) = delete;
explicit operator bool() const { return handle != nullptr; }
HMODULE get() const { return handle; }
};
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
if (message == kMessage) {
g_received_message = wparam == kPayload;
return 0;
}
return g_def_window_proc(window, message, wparam, lparam);
}
void CALLBACK notification_callback(BOOLEAN, PVOID) {
g_callback_called.store(true);
}
HMODULE load_bridge(const wchar_t* dll) {
wchar_t executable[MAX_PATH];
const DWORD length = GetModuleFileNameW(nullptr, executable, MAX_PATH);
if (!length || length == MAX_PATH) {
return nullptr;
}
const std::wstring path(executable, length);
const auto expected = path.substr(0, path.find_last_of(L"\\/") + 1) + dll;
HMODULE module = LoadLibraryW(expected.c_str());
if (!module) {
std::fwprintf(stderr, L"FAIL: could not load built bridge %ls (error %lu)\n",
expected.c_str(), GetLastError());
return nullptr;
}
wchar_t actual[MAX_PATH];
const DWORD actual_length = GetModuleFileNameW(module, actual, MAX_PATH);
if (!actual_length || actual_length == MAX_PATH) {
const DWORD err = GetLastError();
FreeLibrary(module);
std::fwprintf(stderr, L"FAIL: could not query path for bridge %ls (error %lu)\n",
expected.c_str(), err);
return nullptr;
}
if (CompareStringOrdinal(expected.c_str(), -1, actual, -1, TRUE) != CSTR_EQUAL) {
FreeLibrary(module);
std::fwprintf(stderr, L"FAIL: bridge %ls resolved to unexpected path %ls\n",
expected.c_str(), actual);
return nullptr;
}
return module;
}
template<typename Function>
Function lookup(HMODULE module, const char* name) {
return std::bit_cast<Function>(GetProcAddress(module, name));
}
bool test_window() {
const ScopedModule window(load_bridge(L"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll"));
const ScopedModule window_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll"));
const ScopedModule message(load_bridge(L"ext-ms-win-rtcore-ntuser-message-l1-1-0.dll"));
const ScopedModule message_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll"));
if (!window || !window_ansi || !message || !message_ansi) {
return false;
}
const auto show = lookup<decltype(&ShowWindow)>(window.get(), "ShowWindow");
const auto create = lookup<decltype(&CreateWindowExA)>(window_ansi.get(), "CreateWindowExA");
const auto register_class = lookup<decltype(&RegisterClassExA)>(window_ansi.get(), "RegisterClassExA");
g_def_window_proc = lookup<decltype(&DefWindowProcA)>(window_ansi.get(), "DefWindowProcA");
const auto translate = lookup<decltype(&TranslateMessage)>(message.get(), "TranslateMessage");
const auto peek = lookup<decltype(&PeekMessageA)>(message_ansi.get(), "PeekMessageA");
const auto dispatch = lookup<decltype(&DispatchMessageA)>(message_ansi.get(), "DispatchMessageA");
if (!show || !create || !register_class || !g_def_window_proc || !translate || !peek || !dispatch) {
return false;
}
WNDCLASSEXA cls{};
cls.cbSize = sizeof(cls);
cls.lpfnWndProc = window_proc;
cls.hInstance = GetModuleHandleW(nullptr);
cls.lpszClassName = "BetterXenBridgeConformance";
if (!register_class(&cls)) {
return false;
}
const HWND hwnd = create(0, cls.lpszClassName, "BetterXen Win32 Bridge", WS_OVERLAPPEDWINDOW,
0, 0, 100, 100, nullptr, nullptr, cls.hInstance, nullptr);
if (hwnd) {
show(hwnd, SW_HIDE);
if (!IsWindowVisible(hwnd) && PostMessageA(hwnd, kMessage, kPayload, 0)) {
MSG msg{};
while (!g_received_message && peek(&msg, hwnd, 0, 0, PM_REMOVE)) {
translate(&msg);
dispatch(&msg);
}
}
}
const bool destroyed = hwnd && DestroyWindow(hwnd);
const bool unregistered = UnregisterClassA(cls.lpszClassName, cls.hInstance);
return g_received_message && destroyed && unregistered;
}
using RegisterNotification = ULONG (WINAPI*)(decltype(&notification_callback), PVOID, PVOID*);
using UnregisterNotification = VOID (WINAPI*)(PVOID);
struct PsmLogCounts {
size_t state_registered = 0;
size_t constrained_registered = 0;
size_t state_unregistered = 0;
size_t state_foreign = 0;
size_t state_unknown = 0;
size_t constrained_unregistered = 0;
size_t constrained_foreign = 0;
size_t constrained_unknown = 0;
};
int64_t query_file_size(const char* path) {
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (f == INVALID_HANDLE_VALUE) {
return 0;
}
LARGE_INTEGER size{};
const bool ok = GetFileSizeEx(f, &size) != 0;
CloseHandle(f);
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
}
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out) {
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (f == INVALID_HANDLE_VALUE) {
std::fprintf(stderr, "FAIL: could not open PSM log %s (error %lu)\n", path, GetLastError());
return false;
}
LARGE_INTEGER size{};
if (!GetFileSizeEx(f, &size) || size.QuadPart < start_offset) {
CloseHandle(f);
std::fprintf(stderr, "FAIL: invalid PSM log size for %s\n", path);
return false;
}
const int64_t delta = size.QuadPart - start_offset;
if (delta <= 0 || delta > (64LL << 20)) {
CloseHandle(f);
std::fprintf(stderr, "FAIL: unexpected PSM log delta (%lld bytes)\n",
static_cast<long long>(delta));
return false;
}
LARGE_INTEGER seek{};
seek.QuadPart = start_offset;
if (!SetFilePointerEx(f, seek, nullptr, FILE_BEGIN)) {
CloseHandle(f);
return false;
}
std::string data(static_cast<size_t>(delta), '\0');
size_t total_read = 0;
while (total_read < data.size()) {
DWORD chunk = 0;
const DWORD want = static_cast<DWORD>(data.size() - total_read);
if (!ReadFile(f, data.data() + total_read, want, &chunk, nullptr) || chunk == 0) {
break;
}
total_read += chunk;
}
CloseHandle(f);
data.resize(total_read);
size_t pos = 0;
while (pos < data.size()) {
size_t nl = data.find('\n', pos);
if (nl == std::string::npos) {
nl = data.size();
}
const std::string line = data.substr(pos, nl - pos);
pos = nl + 1;
if (line.find("\"sub\":\"win32_bridge\"") == std::string::npos) {
continue;
}
if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
++out.state_registered;
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
++out.constrained_registered;
} else if (line.find("\"event\":\"UnregisterAppStateChangeNotification\"") != std::string::npos) {
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
++out.state_unregistered;
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
++out.state_foreign;
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
++out.state_unknown;
}
} else if (line.find("\"event\":\"UnregisterAppConstrainedChangeNotification\"") != std::string::npos) {
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
++out.constrained_unregistered;
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
++out.constrained_foreign;
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
++out.constrained_unknown;
}
}
}
return true;
}
bool test_psm() {
char log_path[MAX_PATH]{};
bool created_temp_log = false;
const DWORD existing_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
if (existing_len == 0 || existing_len >= sizeof(log_path)) {
char temp_dir[MAX_PATH]{};
const DWORD dir_len = GetTempPathA(sizeof(temp_dir), temp_dir);
if (dir_len == 0 || dir_len >= sizeof(temp_dir) ||
GetTempFileNameA(temp_dir, "bxp", 0, log_path) == 0) {
std::fprintf(stderr, "FAIL: could not create temporary PSM log file\n");
return false;
}
if (!SetEnvironmentVariableA("BX_LOG_FILE", log_path)) {
DeleteFileA(log_path);
return false;
}
created_temp_log = true;
}
const int64_t log_start_offset = query_file_size(log_path);
bool ok = false;
{
const ScopedModule state_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-0.dll"));
const ScopedModule constrained_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-1.dll"));
if (state_dll && constrained_dll) {
const auto register_state = lookup<RegisterNotification>(
state_dll.get(), "RegisterAppStateChangeNotification");
const auto unregister_state = lookup<UnregisterNotification>(
state_dll.get(), "UnregisterAppStateChangeNotification");
const auto register_constrained = lookup<RegisterNotification>(
constrained_dll.get(), "RegisterAppConstrainedChangeNotification");
const auto unregister_constrained = lookup<UnregisterNotification>(
constrained_dll.get(), "UnregisterAppConstrainedChangeNotification");
if (register_state && unregister_state && register_constrained && unregister_constrained) {
PVOID token = reinterpret_cast<PVOID>(1);
PVOID token2 = reinterpret_cast<PVOID>(1);
const bool args_ok =
register_state(nullptr, nullptr, &token) == ERROR_INVALID_PARAMETER && !token &&
register_state(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER &&
register_constrained(nullptr, nullptr, &token2) == ERROR_INVALID_PARAMETER && !token2 &&
register_constrained(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER;
constexpr size_t kThreads = 4;
constexpr size_t kRegistrationsPerThread = 16;
constexpr size_t kPerFamily = kThreads * kRegistrationsPerThread;
struct Tokens {
PVOID state{};
PVOID constrained{};
};
std::array<std::array<Tokens, kRegistrationsPerThread>, kThreads> tokens{};
std::array<std::thread, kThreads> workers;
std::atomic<bool> success{args_ok};
for (size_t i = 0; i < workers.size(); ++i) {
workers[i] = std::thread([&, i] {
for (auto& entry : tokens[i]) {
const auto state_status =
register_state(notification_callback, &entry, &entry.state);
const auto constrained_status =
register_constrained(notification_callback, &entry, &entry.constrained);
if (state_status != ERROR_SUCCESS || constrained_status != ERROR_SUCCESS ||
!entry.state || !entry.constrained) {
success.store(false);
}
// Cross-family unregister calls must log foreign_token and leave live tokens intact.
unregister_constrained(entry.state);
unregister_state(entry.constrained);
// Valid unregister followed by duplicate unregister on each family.
unregister_state(entry.state);
unregister_state(entry.state);
unregister_constrained(entry.constrained);
unregister_constrained(entry.constrained);
}
});
}
for (auto& worker : workers) {
worker.join();
}
// Null and arbitrary invalid tokens must classify as unknown_token, not foreign_token.
unregister_state(nullptr);
unregister_constrained(reinterpret_cast<PVOID>(0x1234));
std::unordered_set<PVOID> seen;
bool unique_ok = true;
for (const auto& entries : tokens) {
for (const auto& entry : entries) {
if (!seen.insert(entry.state).second ||
!seen.insert(entry.constrained).second) {
unique_ok = false;
}
}
}
PsmLogCounts counts{};
const bool log_read_ok = count_psm_log_events(log_path, log_start_offset, counts);
const bool counts_ok = log_read_ok &&
counts.state_registered == kPerFamily &&
counts.constrained_registered == kPerFamily &&
counts.state_unregistered == kPerFamily &&
counts.state_foreign == kPerFamily &&
counts.state_unknown == kPerFamily + 1 &&
counts.constrained_unregistered == kPerFamily &&
counts.constrained_foreign == kPerFamily &&
counts.constrained_unknown == kPerFamily + 1;
if (log_read_ok && !counts_ok) {
std::fprintf(
stderr,
"FAIL: PSM log count mismatch: state(reg=%zu unreg=%zu foreign=%zu unknown=%zu) "
"constrained(reg=%zu unreg=%zu foreign=%zu unknown=%zu)\n",
counts.state_registered, counts.state_unregistered,
counts.state_foreign, counts.state_unknown,
counts.constrained_registered, counts.constrained_unregistered,
counts.constrained_foreign, counts.constrained_unknown);
}
ok = success.load() && unique_ok && !g_callback_called.load() && counts_ok;
}
}
}
if (created_temp_log) {
DeleteFileA(log_path);
}
return ok;
}
} // namespace
int main() {
if (!test_window()) {
std::fprintf(stderr, "FAIL: Win32 bridge window or message pump (error %lu)\n", GetLastError());
return 1;
}
if (!test_psm()) {
std::fprintf(stderr, "FAIL: PSM bridge registration lifecycle\n");
return 2;
}
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, per-event log verified)");
return 0;
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more