Compare commits

..
Author SHA1 Message Date
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
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
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
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
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
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 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
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 ab696f1f07 Map xmem physical pages into shared aliases
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:52:04 +03:00
61 changed files with 11312 additions and 201 deletions

No files matched your search

+45
View File
@@ -10,6 +10,47 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- 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).
- 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-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).
@@ -69,6 +110,10 @@ 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
- `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.
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"
+16 -16
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 cross-compiled PE32+ shims, 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 |
@@ -132,7 +132,7 @@ The repository is organized into disjoint track directories around a single froz
| [`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 |
| `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 |
+2
View File
@@ -2,6 +2,8 @@
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.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
## External Host Tools & Runtime Dependencies (Never Bundled)
| Component | Role | Licensing & Provenance |
+6
View File
@@ -43,3 +43,9 @@ EXPORTS
XGameUiShowTextEntryAsync
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
XNetworkingQuerySecurityInformationForUrlAsync
InitializeApiImpl
InitializeApiImplEx
InitializeApiImplEx2
UninitializeApiImpl
QueryApiImpl
XErrorReport
+3
View File
@@ -14,6 +14,7 @@
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
## Research, Testing & Licensing
@@ -21,6 +22,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) — One-host observation to check before M2 presentation work.
- [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
@@ -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.
+1 -1
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 |
+1
View File
@@ -20,5 +20,6 @@ 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). |
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,20 @@
# D3D12 swapchain references under D3DMetal
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. Not independently reproduced, and not an
Xbox hardware result.
| | 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.
+1
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)
+4 -4
View File
@@ -36,10 +36,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; 16/16 PE32+ DLLs 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
+746 -58
View File
@@ -1,20 +1,29 @@
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
mod stage;
mod supervise;
use std::collections::BTreeMap;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::time::{Duration, Instant};
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
use bx_telemetry::summarize_jsonl;
use dxbc_accc::inspect_dxbc;
use supervise::{Outcome, Stop};
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
api-ms-win-core-psm-appnotify-l1-1-0,api-ms-win-core-psm-appnotify-l1-1-1,\
ext-ms-win-rtcore-ntuser-message-l1-1-0,ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0,\
ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0=n,b";
/// Accepted `--backend` values. CrossOver ignores an unknown value silently, so one is refused.
const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"];
const SAFE_CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
const HOST_ENV_ALLOWLIST: &[&str] = &[
@@ -39,7 +48,8 @@ fn print_usage() {
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env]\n"
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
);
}
@@ -153,6 +163,16 @@ fn cmd_probe(path: &str) -> ExitCode {
ExitCode::SUCCESS
}
fn format_clwb_line(clwb_events: usize, clwb_trap_lower_bound: Option<u64>) -> String {
if let Some(lower_bound) = clwb_trap_lower_bound {
format!("clwb VEH traps : at least {lower_bound} (sampled)")
} else if clwb_events == 0 {
"clwb VEH traps : 0".to_string()
} else {
format!("clwb VEH samples : {clwb_events}")
}
}
fn cmd_trace(path: &str) -> ExitCode {
let text = match fs::read_to_string(path) {
Ok(s) => s,
@@ -161,23 +181,50 @@ fn cmd_trace(path: &str) -> ExitCode {
return ExitCode::FAILURE;
}
};
let summary = summarize_jsonl(&text);
println!("Trace events : {}", summary.total_lines);
println!("clwb VEH traps : {}", summary.clwb_events);
println!("ADX illegal ops : {}", summary.adx_errors);
print!("{}", render_trace(&text));
ExitCode::SUCCESS
}
fn render_trace(text: &str) -> String {
let mut out = String::new();
let summary = summarize_jsonl(text);
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
let _ = writeln!(
out,
"{}",
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
);
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
if !summary.unhandled_exceptions.is_empty() {
let _ = writeln!(
out,
"\nUnhandled exceptions ({}):",
summary.unhandled_exceptions.len()
);
for crash in summary.unhandled_exceptions {
let _ = writeln!(
out,
" code={} module_base={} + RVA={} RIP={}",
crash.exception_code.as_deref().unwrap_or("unknown"),
crash.module_base.as_deref().unwrap_or("unknown"),
crash.rva.as_deref().unwrap_or("unknown"),
crash.rip.as_deref().unwrap_or("unknown"),
);
}
}
if !summary.unimpl_apis.is_empty() {
println!("\nUnimplemented APIs:");
let _ = writeln!(out, "\nUnimplemented APIs:");
for (api, count) in summary.unimpl_apis {
println!(" {count:5}x {api}");
let _ = writeln!(out, " {count:5}x {api}");
}
}
if !summary.unimpl_vtables.is_empty() {
println!("\nUnimplemented COM vtable slots:");
let _ = writeln!(out, "\nUnimplemented COM vtable slots:");
for (slot, count) in summary.unimpl_vtables {
println!(" {count:5}x {slot}");
let _ = writeln!(out, " {count:5}x {slot}");
}
}
ExitCode::SUCCESS
out
}
fn unix_to_wine_z_path(path: &Path) -> String {
@@ -199,7 +246,20 @@ where
env_map
}
fn cmd_run(args: &[String]) -> ExitCode {
#[derive(Debug)]
struct RunArgs {
exe: PathBuf,
shims_dir: PathBuf,
profile: String,
bottle: Option<String>,
prefix: Option<PathBuf>,
log: Option<PathBuf>,
inherit_env: bool,
timeout: Option<Duration>,
backend: Option<String>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut exe_path: Option<PathBuf> = None;
let mut shims_dir = PathBuf::from("build-shims/bin");
let mut profile = String::from("lockhart");
@@ -207,6 +267,8 @@ fn cmd_run(args: &[String]) -> ExitCode {
let mut wine_prefix: Option<PathBuf> = None;
let mut log_file: Option<PathBuf> = None;
let mut inherit_env = false;
let mut timeout = None;
let mut backend: Option<String> = None;
let mut i = 0;
while i < args.len() {
@@ -235,21 +297,265 @@ fn cmd_run(args: &[String]) -> ExitCode {
log_file = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--timeout" if i + 1 < args.len() => {
let seconds: u64 = args[i + 1]
.parse()
.ok()
.filter(|s| *s > 0)
.ok_or("--timeout needs a whole number of seconds above 0")?;
timeout = Some(Duration::from_secs(seconds));
i += 2;
}
"--backend" if i + 1 < args.len() => {
let name = args[i + 1].clone();
if !BACKENDS.contains(&name.as_str()) {
return Err(format!(
"unknown backend {name:?}; use one of {}",
BACKENDS.join(", ")
));
}
backend = Some(name);
i += 2;
}
"--inherit-env" => {
inherit_env = true;
i += 1;
}
other => {
eprintln!("unknown argument: {other}");
return ExitCode::FAILURE;
}
other => return Err(format!("unknown argument: {other}")),
}
}
let Some(exe) = exe_path else {
eprintln!("error: --exe <path> is required");
return ExitCode::FAILURE;
if let Some(name) = &bottle
&& (name.is_empty() || name.starts_with(['-', '.']) || name.contains('/'))
{
return Err(format!("invalid bottle name {name:?}"));
}
if backend.is_some() && bottle.is_none() {
// A bare prefix loads Wine's own D3D12 whatever CX_GRAPHICS_BACKEND says (observed on
// CrossOver 26.3), so accepting it would claim a backend that is not in use.
return Err("--backend needs --bottle; a bare prefix cannot be made to use it".into());
}
Ok(RunArgs {
exe: exe_path.ok_or("error: --exe <path> is required")?,
shims_dir,
profile,
bottle,
prefix: wine_prefix,
log: log_file,
inherit_env,
timeout,
backend,
})
}
/// Asks CrossOver's installed `CXBottle` module where `--bottle` points, so cleanup targets the
/// prefix the launch uses. `bin/wine` searches `CX_BOTTLE_PATH`, configured paths and managed
/// bottles, so a fixed directory would be wrong for some bottles.
const BOTTLE_PREFIX_QUERY: &str = r#"
use lib "$ENV{CX_ROOT}/lib/perl";
require CXBottle;
CXBottle::get_crossover_config();
my ($scope, $found) = CXBottle::setup_bottle_wineprefix(undef);
die "$@\n" unless defined $scope;
print $ENV{WINEPREFIX};
"#;
/// The environment `bin/wine` starts from, shared by the launch and the bottle lookup.
fn apply_host_env(command: &mut Command, inherit_env: bool) {
if !inherit_env {
command.env_clear();
for (k, v) in collect_isolated_host_env(|k| env::var(k).ok()) {
command.env(k, v);
}
}
// Inherited values must not point the launcher at a different bottle than cleanup does.
command.env_remove("WINEPREFIX").env_remove("CX_BOTTLE");
}
fn resolve_bottle_prefix(
cx_root: &Path,
mut command: Command,
name: &str,
) -> Result<PathBuf, String> {
let output = command
.env("CX_ROOT", cx_root)
.env("CX_BOTTLE", name)
.args(["-e", BOTTLE_PREFIX_QUERY])
.output()
.map_err(|e| format!("cannot ask CrossOver where bottle {name:?} is: {e}"))?;
let path = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
if !output.status.success() || !path.is_absolute() || !path.is_dir() {
return Err(format!(
"CrossOver cannot locate bottle {name:?}: {}",
String::from_utf8_lossy(&output.stderr).trim()
));
}
Ok(path)
}
fn resolve_bottle_prefix_with_host_env(
cx_root: &Path,
name: &str,
inherit_env: bool,
) -> Result<PathBuf, String> {
let mut query = Command::new("/usr/bin/perl");
apply_host_env(&mut query, inherit_env);
resolve_bottle_prefix(cx_root, query, name)
}
/// Collects the prefixes that cleanup must stop. Re-resolving a named bottle after launch catches
/// the case where a managed-only bottle caused CrossOver's `bin/wine` to create and launch inside
/// a new private stub bottle.
fn cleanup_prefixes_for_stop<F>(
initial_prefix: &Path,
bottle: Option<&str>,
mut re_resolve: F,
) -> Result<Vec<PathBuf>, String>
where
F: FnMut(&str) -> Result<PathBuf, String>,
{
let mut prefixes = Vec::new();
if let Some(name) = bottle {
let current = re_resolve(name)?;
prefixes.push(current);
}
if !prefixes.iter().any(|p| p == initial_prefix) {
prefixes.push(initial_prefix.to_path_buf());
}
Ok(prefixes)
}
/// The prefix a named bottle resolves to now, if that is no longer `staged_prefix`.
///
/// For a managed-only bottle CrossOver's `bin/wine` may create a private stub bottle and launch
/// the guest there. Shims staged before launch then sit in a prefix the guest never used; this
/// detects that so the run can say so instead of reporting "staged" (#474).
fn staging_prefix_mismatch<F>(
staged_prefix: &Path,
bottle: Option<&str>,
mut re_resolve: F,
) -> Result<Option<PathBuf>, String>
where
F: FnMut(&str) -> Result<PathBuf, String>,
{
let Some(name) = bottle else {
return Ok(None);
};
let current = re_resolve(name)?;
let same = |a: &Path, b: &Path| {
a == b || matches!((fs::canonicalize(a), fs::canonicalize(b)), (Ok(x), Ok(y)) if x == y)
};
Ok((!same(&current, staged_prefix)).then_some(current))
}
/// What is left of `--timeout` for the guest after initialization took `used`. `Ok(None)` means
/// no limit. An error means initialization used all of it: the guest must not be started only to
/// be reported as timed out, as if it had hung (#474).
fn guest_time_left(timeout: Option<Duration>, used: Duration) -> Result<Option<Duration>, String> {
match timeout {
None => Ok(None),
Some(limit) if used < limit => Ok(Some(limit - used)),
Some(limit) => Err(format!(
"initialization (prefix setup and shim staging) took {:.1}s and used the whole \
--timeout of {:.1}s; the guest was not started",
used.as_secs_f64(),
limit.as_secs_f64()
)),
}
}
/// `bin/wine` deletes an inherited `WINEDLLOVERRIDES` and applies the bottle's
/// `[EnvironmentVariables]` over what it is given, so bottle mode passes both as options.
fn bottle_options(backend: Option<&str>) -> Vec<String> {
let mut options = vec!["--dll".to_string(), SHIM_DLL_OVERRIDES.to_string()];
if let Some(backend) = backend {
options.push("--env".to_string());
options.push(format!("CX_GRAPHICS_BACKEND={backend}"));
}
options
}
/// The CrossOver Wine environment for a bare `--prefix` (bottles get theirs from `bin/wine`).
fn apply_prefix_env(command: &mut Command, cx_root: &Path, prefix: &Path, wineloader: &Path) {
command
.env("WINEPREFIX", prefix)
.env("WINESERVER", cx_root.join("bin/wineserver"))
.env("WINELOADER", wineloader)
.env(
"WINEDLLPATH",
format!(
"{}:{}",
cx_root.join("lib/wine").display(),
cx_root.join("lib64/wine").display()
),
)
.env(
"DYLD_FALLBACK_LIBRARY_PATH",
format!(
"{}:{}:/usr/lib",
cx_root.join("lib64").display(),
cx_root.join("lib").display()
),
);
}
/// Reports a timeout or signal and stops the environment's `wineserver`. True if cleanup failed.
fn stop_environment(
stop: Stop,
cx_root: &Path,
environment_dir: &Path,
bottle: Option<&str>,
inherit_env: bool,
) -> bool {
match stop {
Stop::TimedOut => eprintln!("timed out; stopping the environment"),
Stop::Signalled(signal) => {
eprintln!("received signal {signal}; stopping the environment");
}
}
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
.into_iter()
.collect();
let mut cleanup_failed = false;
let prefixes_to_stop = match cleanup_prefixes_for_stop(environment_dir, bottle, |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(prefixes) => prefixes,
Err(e) => {
eprintln!("cleanup failed to re-resolve bottle prefix: {e}");
cleanup_failed = true;
vec![environment_dir.to_path_buf()]
}
};
for prefix in &prefixes_to_stop {
if let Err(e) = supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
{
eprintln!("cleanup failed, programs may still be running: {e}");
cleanup_failed = true;
}
}
cleanup_failed
}
fn cmd_run(args: &[String]) -> ExitCode {
let run = match parse_run_args(args) {
Ok(run) => run,
Err(e) => {
eprintln!("{e}");
return ExitCode::FAILURE;
}
};
let RunArgs {
exe,
shims_dir,
profile,
bottle,
prefix: wine_prefix,
log: log_file,
inherit_env,
timeout,
backend,
} = run;
let cx_root = Path::new("/Applications/CrossOver.app/Contents/SharedSupport/CrossOver");
let wine_wrapper = cx_root.join("bin/wine");
@@ -266,9 +572,85 @@ fn cmd_run(args: &[String]) -> ExitCode {
let resolved_prefix =
wine_prefix.unwrap_or_else(|| PathBuf::from("/tmp/betterxen-wine-prefix"));
// The environment a timeout or signal has to stop.
let environment_dir = match &bottle {
Some(name) => match resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env) {
Ok(path) => path,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
},
None => resolved_prefix.clone(),
};
// Handled from here on, so that prefix initialization is cleaned up like the guest is.
supervise::install_signal_handlers();
let started = Instant::now();
// #457: shims loaded with LOAD_LIBRARY_SEARCH_SYSTEM32 never see WINEPATH, so they are
// copied into the environment's system32 first. A bare prefix is initialized for that.
let system32 = stage::system32_dir(&environment_dir);
if bottle.is_none() && !system32.is_dir() && stage::has_system32_shims(&abs_shims) {
let _ = fs::create_dir_all(&resolved_prefix);
let mut boot = Command::new(&wineloader);
boot.args(["wineboot", "--init"]);
apply_host_env(&mut boot, inherit_env);
apply_prefix_env(&mut boot, cx_root, &resolved_prefix, &wineloader);
boot.env("WINEDEBUG", "-all");
match supervise::supervise(boot, timeout, supervise::received_signal) {
Ok(Outcome::Exited(st)) if st.success() => {}
Ok(Outcome::Exited(st)) => {
eprintln!(
"error: wineboot --init failed for {}: {st}",
resolved_prefix.display()
);
return ExitCode::FAILURE;
}
Ok(outcome @ Outcome::Stopped(stop)) => {
let failed = stop_environment(stop, cx_root, &environment_dir, None, inherit_env);
let code = outcome.exit_code();
return ExitCode::from(if failed { code.max(1) } else { code });
}
Err(e) => {
eprintln!(
"error: cannot run wineboot for {}: {e}",
resolved_prefix.display()
);
return ExitCode::FAILURE;
}
}
}
let mut staged_names: Vec<String> = Vec::new();
match stage::stage_system32(&abs_shims, &system32) {
Ok(staged) => {
for item in &staged {
if let stage::Staged::Copied(path)
| stage::Staged::Replaced(path)
| stage::Staged::Unchanged(path) = item
&& let Some(name) = path.file_name()
{
staged_names.push(name.to_string_lossy().into_owned());
}
eprintln!("bx-cli: {}", item.describe());
}
}
Err(e) => {
let hint = if bottle.is_some() && !system32.is_dir() {
" (start the bottle once so CrossOver creates it)"
} else {
""
};
eprintln!("error: cannot stage system32 shims: {e}{hint}");
return ExitCode::FAILURE;
}
}
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname]).arg(&abs_exe);
c.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()))
.arg(&abs_exe);
c
} else {
let _ = fs::create_dir_all(&resolved_prefix);
@@ -277,33 +659,10 @@ fn cmd_run(args: &[String]) -> ExitCode {
c
};
if !inherit_env {
cmd.env_clear();
for (k, v) in collect_isolated_host_env(|k| env::var(k).ok()) {
cmd.env(k, v);
}
}
apply_host_env(&mut cmd, inherit_env);
if bottle.is_none() {
cmd.env("WINEPREFIX", &resolved_prefix)
.env("WINESERVER", cx_root.join("bin/wineserver"))
.env("WINELOADER", &wineloader)
.env(
"WINEDLLPATH",
format!(
"{}:{}",
cx_root.join("lib/wine").display(),
cx_root.join("lib64/wine").display()
),
)
.env(
"DYLD_FALLBACK_LIBRARY_PATH",
format!(
"{}:{}:/usr/lib",
cx_root.join("lib64").display(),
cx_root.join("lib").display()
),
);
apply_prefix_env(&mut cmd, cx_root, &resolved_prefix, &wineloader);
}
cmd.env("ROSETTA_ADVERTISE_AVX", "1")
@@ -312,26 +671,112 @@ fn cmd_run(args: &[String]) -> ExitCode {
.env("BX_PROFILE", &profile)
.env("WINEDEBUG", "-all");
if let Some(ref lf) = log_file {
let abs_log = if lf.is_absolute() {
lf.clone()
let abs_log = log_file.map(|lf| {
if lf.is_absolute() {
lf
} else {
env::current_dir().unwrap_or_default().join(lf)
};
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(&abs_log));
}
});
if let Some(log) = &abs_log {
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(log));
}
let log_size = |log: &PathBuf| fs::metadata(log).map_or(0, |m| m.len());
let log_size_before = abs_log.as_ref().map_or(0, log_size);
// `--timeout` bounds the whole run, including any prefix initialization above.
let remaining = match guest_time_left(timeout, started.elapsed()) {
Ok(remaining) => remaining,
Err(e) => {
eprintln!("timed out during initialization: {e}");
return ExitCode::from(124);
}
};
let outcome = supervise::supervise(cmd, remaining, supervise::received_signal);
let code = match &outcome {
Ok(outcome) => outcome.exit_code(),
Err(e) => {
eprintln!("failed to run CrossOver wine: {e}");
1
}
};
let mut cleanup_failed = false;
match &outcome {
Ok(Outcome::Exited(status)) if !status.success() => {
eprintln!("guest exited with status: {status}");
}
Ok(Outcome::Stopped(stop)) => {
cleanup_failed = stop_environment(
*stop,
cx_root,
&environment_dir,
bottle.as_deref(),
inherit_env,
);
}
_ => {}
}
match cmd.status() {
Ok(st) if st.success() => ExitCode::SUCCESS,
Ok(st) => {
eprintln!("guest exited with status: {st}");
ExitCode::FAILURE
}
Err(e) => {
eprintln!("failed to launch CrossOver wine: {e}");
ExitCode::FAILURE
// Printed for failed and stopped runs too, which is when it matters most.
if let Some(log) = &abs_log
&& log_size(log) > log_size_before
&& let Ok(bytes) = fs::read(log)
{
// Guest text may not be valid UTF-8; a summary is still worth printing.
print!(
"\nTrace summary of {}:\n{}",
log.display(),
render_trace(&String::from_utf8_lossy(&bytes))
);
}
// #474: the shims were staged into the prefix resolved before launch. If CrossOver launched
// the bottle from a different prefix that does not expose them, the guest never saw them,
// and the run must not pass quietly. A different prefix alone is not a failure: a private
// stub of a managed bottle links its system32 entries back to the managed prefix.
let mut staged_elsewhere = false;
if !staged_names.is_empty() {
match staging_prefix_mismatch(&environment_dir, bottle.as_deref(), |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(None) => {}
Ok(Some(launched)) => {
let missing = stage::shims_not_visible_in(
&system32,
&stage::system32_dir(&launched),
&staged_names,
);
if missing.is_empty() {
eprintln!(
"bx-cli: bottle launched in {}; the shims staged in {} are visible there",
launched.display(),
environment_dir.display()
);
} else {
staged_elsewhere = true;
eprintln!(
"error: system32 shims were staged in {} but CrossOver launched the \
bottle in {}, where {} cannot be found as staged; the guest did not \
see them. Run again: staging will now use the prefix the bottle \
launches in",
environment_dir.display(),
launched.display(),
missing.join(", ")
);
}
}
Err(e) => eprintln!(
"warning: cannot confirm which prefix the bottle launched in, so the staged \
system32 shims may not have been used: {e}"
),
}
}
// The reason for the stop is kept; a failed cleanup or misplaced staging only turns success
// into failure.
ExitCode::from(if cleanup_failed || staged_elsewhere {
code.max(1)
} else {
code
})
}
fn cmd_shader(path: &str) -> ExitCode {
@@ -388,6 +833,239 @@ fn main() -> ExitCode {
mod tests {
use super::*;
#[test]
fn staging_into_a_prefix_the_bottle_did_not_launch_in_is_reported() {
let resolved_before = Path::new("/bottles/managed/corp");
let stub = PathBuf::from("/bottles/private/corp");
// CrossOver created a private stub during launch: the bottle now resolves there.
let moved = staging_prefix_mismatch(resolved_before, Some("corp"), |name| {
assert_eq!(name, "corp");
Ok(stub.clone())
});
assert_eq!(moved, Ok(Some(stub)));
// The usual case: the bottle still resolves to where the shims went.
let same = staging_prefix_mismatch(resolved_before, Some("corp"), |_| {
Ok(resolved_before.to_path_buf())
});
assert_eq!(same, Ok(None));
// A bare --prefix is launched exactly where it was staged; nothing is re-resolved.
let bare = staging_prefix_mismatch(resolved_before, None, |_| {
panic!("a bare prefix must not be re-resolved")
});
assert_eq!(bare, Ok(None));
// A resolver failure is passed on, not mistaken for a match.
let failed = staging_prefix_mismatch(resolved_before, Some("corp"), |_| {
Err("cannot locate".to_string())
});
assert_eq!(failed, Err("cannot locate".to_string()));
}
#[test]
fn the_guest_is_not_started_when_initialization_used_the_whole_timeout() {
let limit = Some(Duration::from_secs(30));
assert_eq!(guest_time_left(None, Duration::from_secs(999)), Ok(None));
assert_eq!(
guest_time_left(limit, Duration::from_secs(12)),
Ok(Some(Duration::from_secs(18)))
);
for used in [Duration::from_secs(30), Duration::from_secs(45)] {
let err = guest_time_left(limit, used).unwrap_err();
assert!(err.contains("initialization"), "{err}");
assert!(err.contains("guest was not started"), "{err}");
}
}
fn args(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}
#[test]
fn parses_run_arguments() {
for bare in [&["--prefix", "/tmp/p"][..], &[]] {
let mut list = args(&["--exe", "a.exe", "--backend", "d3dmetal"]);
list.extend(args(bare));
let error = parse_run_args(&list).unwrap_err();
assert!(error.contains("--backend needs --bottle"), "{error}");
}
let run = parse_run_args(&args(&[
"--exe",
"a.exe",
"--bottle",
"b",
"--timeout",
"30",
"--backend",
"d3dmetal",
]))
.unwrap();
assert_eq!(run.timeout, Some(Duration::from_secs(30)));
assert_eq!(run.backend.as_deref(), Some("d3dmetal"));
assert_eq!(run.shims_dir, PathBuf::from("build-shims/bin"));
assert_eq!(run.profile, "lockhart");
let plain = parse_run_args(&args(&["--exe", "a.exe"])).unwrap();
assert!(plain.timeout.is_none() && plain.bottle.is_none() && plain.prefix.is_none());
for bad in [
&["--exe", "a.exe", "--timeout", "0"][..],
&["--exe", "a.exe", "--timeout", "soon"],
&["--exe", "a.exe", "--backend", "dmxt2"],
&["--exe", "a.exe", "--bottle", "../x"],
&["--exe", "a.exe", "--timeout"],
&["--bottle", "b"],
] {
assert!(parse_run_args(&args(bad)).is_err(), "{bad:?}");
}
}
// A stub CXBottle stands in for CrossOver's: this checks the lookup's environment and that
// a timeout's cleanup is aimed at the prefix it returns, not at the default directory.
#[test]
fn a_timeout_cleans_up_a_bottle_outside_the_default_directory() {
use std::os::unix::fs::PermissionsExt;
let root = env::temp_dir().join(format!("bx-cli-altbottle-{}", std::process::id()));
let bottle = root.join("elsewhere/mine");
fs::create_dir_all(&bottle).unwrap();
fs::create_dir_all(root.join("cx/lib/perl")).unwrap();
fs::write(
root.join("cx/lib/perl/CXBottle.pm"),
r#"package CXBottle;
sub get_crossover_config {}
sub setup_bottle_wineprefix {
my $p = "$ENV{CX_BOTTLE_PATH}/$ENV{CX_BOTTLE}";
return (undef, undef) unless -d $p;
$ENV{WINEPREFIX} = $p;
return ('private', $p);
}
1;
"#,
)
.unwrap();
let query = |name: &str| {
let mut command = Command::new("/usr/bin/perl");
command.env("CX_BOTTLE_PATH", root.join("elsewhere"));
resolve_bottle_prefix(&root.join("cx"), command, name)
};
assert!(query("absent").is_err());
let prefix = query("mine").unwrap();
assert_eq!(prefix, bottle);
let server = root.join("wineserver");
let seen = root.join("seen");
fs::write(
&server,
format!(
"#!/bin/sh\necho \"$1 $WINEPREFIX\" >> '{}'\n",
seen.display()
),
)
.unwrap();
fs::set_permissions(&server, fs::Permissions::from_mode(0o755)).unwrap();
let mut sleeper = Command::new("/bin/sh");
sleeper.args(["-c", "sleep 30"]);
let outcome =
supervise::supervise(sleeper, Some(Duration::from_millis(200)), || 0).unwrap();
assert!(matches!(outcome, Outcome::Stopped(Stop::TimedOut)));
supervise::stop_server(&server, &prefix, &[]).unwrap();
let expected = format!("-k {0}\n-w {0}\n", bottle.display());
assert_eq!(fs::read_to_string(&seen).unwrap(), expected);
fs::remove_dir_all(root).unwrap();
}
// Regression test starting with only a managed bottle and no private stub: the launch creates
// the private stub, and timeout cleanup re-resolves via CXBottle so wineserver stops the stub.
#[test]
fn a_timeout_cleans_up_a_managed_bottle_private_stub_created_on_first_launch() {
use std::os::unix::fs::PermissionsExt;
let root = env::temp_dir().join(format!("bx-cli-managed-stub-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let managed = root.join("managed/corp");
let private_dir = root.join("private");
let private_stub = private_dir.join("corp");
fs::create_dir_all(&managed).unwrap();
fs::create_dir_all(&private_dir).unwrap();
fs::create_dir_all(root.join("cx/lib/perl")).unwrap();
fs::write(
root.join("cx/lib/perl/CXBottle.pm"),
r#"package CXBottle;
sub get_crossover_config {}
sub setup_bottle_wineprefix {
my $priv = "$ENV{CX_BOTTLE_PATH}/$ENV{CX_BOTTLE}";
if (-f "$priv/system.reg") {
$ENV{WINEPREFIX} = $priv;
return ('private', $priv);
}
my $mgmt = "$ENV{CX_MANAGED_BOTTLE_PATH}/$ENV{CX_BOTTLE}";
if (-d $mgmt) {
$ENV{WINEPREFIX} = $mgmt;
return ('managed', $mgmt);
}
return (undef, undef);
}
1;
"#,
)
.unwrap();
let query = |name: &str| {
let mut command = Command::new("/usr/bin/perl");
command
.env("CX_BOTTLE_PATH", &private_dir)
.env("CX_MANAGED_BOTTLE_PATH", root.join("managed"));
resolve_bottle_prefix(&root.join("cx"), command, name)
};
// Before launch there is no private stub, so CXBottle reports the managed bottle.
assert!(!private_stub.exists());
let initial = query("corp").unwrap();
assert_eq!(initial, managed);
// Simulated first launch creates the private stub before hanging until timeout.
let mut launcher = Command::new("/bin/sh");
launcher.args([
"-c",
&format!(
"mkdir -p '{0}' && touch '{0}/system.reg' && exec sleep 30",
private_stub.display()
),
]);
let outcome =
supervise::supervise(launcher, Some(Duration::from_millis(300)), || 0).unwrap();
assert!(matches!(outcome, Outcome::Stopped(Stop::TimedOut)));
let prefixes = cleanup_prefixes_for_stop(&initial, Some("corp"), query).unwrap();
assert_eq!(prefixes, vec![private_stub.clone(), managed.clone()]);
let server = root.join("wineserver");
let seen = root.join("seen");
fs::write(
&server,
format!(
"#!/bin/sh\necho \"$1 $WINEPREFIX\" >> '{}'\n",
seen.display()
),
)
.unwrap();
fs::set_permissions(&server, fs::Permissions::from_mode(0o755)).unwrap();
for prefix in &prefixes {
supervise::stop_server(&server, prefix, &[]).unwrap();
}
let expected = format!(
"-k {0}\n-w {0}\n-k {1}\n-w {1}\n",
private_stub.display(),
managed.display()
);
assert_eq!(fs::read_to_string(&seen).unwrap(), expected);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn bottle_mode_passes_overrides_and_backend_as_launcher_options() {
assert_eq!(bottle_options(None), ["--dll", SHIM_DLL_OVERRIDES]);
assert_eq!(
bottle_options(Some("dxvk"))[2..],
["--env", "CX_GRAPHICS_BACKEND=dxvk"]
);
}
#[test]
fn isolated_env_strips_secrets_and_pins_path() {
let host = BTreeMap::from([
@@ -414,4 +1092,14 @@ mod tests {
"Z:\\tmp\\bx-test.jsonl"
);
}
#[test]
fn formats_clwb_summary_lines() {
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
assert_eq!(
format_clwb_line(3, Some(4)),
"clwb VEH traps : at least 4 (sampled)"
);
}
}
+902
View File
@@ -0,0 +1,902 @@
//! #457: shims a guest loads by system-directory search, staged into the prefix's `system32`.
//!
//! The GDK bootstrap that titles link statically loads `xgameruntime.dll` with
//! `LoadLibraryExW(name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32)`. That search never consults
//! `WINEPATH`, where `bx-cli run` otherwise exposes the shims, so those shims are copied into
//! `drive_c/windows/system32` of the prefix or bottle before launch.
//!
//! The same search flags apply to the DLL's own imports, so every BetterXen shim it imports
//! (for example `bx_runtime_veh.dll`) is staged too. Otherwise the load fails unless the guest
//! happened to load that dependency earlier.
//!
//! #474: a bottle's `system32` is not ours. Staging records what it wrote in a `.bx-staged`
//! manifest there (one SHA-256 per file) and afterwards replaces only files that are listed and
//! still have the recorded hash. A file of the same name that the bottle already had, or that
//! was changed since, is never modified: staging stops with an error that names it.
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`.
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll"];
/// `roots` plus, transitively, every import that is itself a file in the shim folder
/// (`is_shim`). Names are compared case-insensitively, as the Windows loader does, and returned
/// lowercased in a stable order.
pub fn shim_closure<I, S>(
roots: &[&str],
is_shim: S,
mut imports_of: I,
) -> Result<Vec<String>, String>
where
I: FnMut(&str) -> Result<Vec<String>, String>,
S: Fn(&str) -> bool,
{
let mut done = BTreeSet::new();
let mut todo: Vec<String> = roots.iter().map(|r| r.to_ascii_lowercase()).collect();
while let Some(name) = todo.pop() {
if !done.insert(name.clone()) {
continue;
}
for dep in imports_of(&name)? {
let dep = dep.to_ascii_lowercase();
if is_shim(&dep) && !done.contains(&dep) {
todo.push(dep);
}
}
}
Ok(done.into_iter().collect())
}
/// The shim file in `shims_dir` named `name`, matched case-insensitively.
fn find_shim(shims_dir: &Path, name: &str) -> Option<PathBuf> {
let exact = shims_dir.join(name);
if exact.is_file() {
return Some(exact);
}
fs::read_dir(shims_dir)
.ok()?
.filter_map(|e| e.ok())
.find_map(|e| {
let file = e.file_name();
(file.to_string_lossy().eq_ignore_ascii_case(name) && e.path().is_file())
.then(|| e.path())
})
}
/// DLL names a PE32+ file imports, read with `bx-probe`.
fn pe_imports(path: &Path) -> Result<Vec<String>, String> {
let bytes = fs::read(path).map_err(|e| format!("cannot read shim {}: {e}", path.display()))?;
let summary = bx_probe::probe_pe32_plus(&bytes)
.map_err(|e| format!("cannot read imports of {}: {e:?}", path.display()))?;
Ok(summary.imports.into_keys().collect())
}
/// The 64-bit system directory of a Wine prefix.
pub fn system32_dir(prefix: &Path) -> PathBuf {
prefix.join("drive_c").join("windows").join("system32")
}
/// SHA-256 (FIPS 180-4), used only to recognize files this tool staged earlier.
pub fn sha256_hex(data: &[u8]) -> String {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
let mut message = data.to_vec();
message.push(0x80);
while message.len() % 64 != 56 {
message.push(0);
}
message.extend_from_slice(&((data.len() as u64).wrapping_mul(8)).to_be_bytes());
for block in message.chunks_exact(64) {
let mut w = [0u32; 64];
for (i, word) in block.chunks_exact(4).enumerate() {
w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ (!e & g);
let t1 = hh
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
hh = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
for (state, value) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
*state = state.wrapping_add(value);
}
}
h.iter().map(|word| format!("{word:08x}")).collect()
}
/// Name of the ownership record kept in `system32`.
pub const MANIFEST_NAME: &str = ".bx-staged";
/// The files this tool staged into a `system32`, as lowercase name -> SHA-256 of what it wrote.
///
/// A file is BetterXen's to refresh only while it is listed here and still has the recorded
/// hash. Anything else in `system32` belongs to the bottle and is never modified (#474).
fn read_manifest(system32: &Path) -> Result<BTreeMap<String, String>, String> {
let path = system32.join(MANIFEST_NAME);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
};
let mut owned = BTreeMap::new();
for line in text.lines() {
// "<64 hex digits> <name>", as `shasum -a 256` prints. Other lines are ignored, which
// only ever makes a file look foreign.
if let Some((hash, name)) = line.split_once(" ")
&& hash.len() == 64
&& hash.bytes().all(|b| b.is_ascii_hexdigit())
&& !name.is_empty()
{
owned.insert(name.to_ascii_lowercase(), hash.to_ascii_lowercase());
}
}
Ok(owned)
}
fn write_manifest(system32: &Path, owned: &BTreeMap<String, String>) -> Result<(), String> {
let mut text = String::from(
"# Files staged by bx-cli (sha256, two spaces, name). bx-cli replaces only these.\n",
);
for (name, hash) in owned {
text.push_str(&format!("{hash} {name}\n"));
}
let path = system32.join(MANIFEST_NAME);
let tmp = system32.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::write(&tmp, text).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("cannot write {}: {e}", tmp.display())
})?;
fs::rename(&tmp, &path).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("cannot replace {}: {e}", path.display())
})
}
/// Names from `names` that a guest in `launched_system32` would not find as staged: the entry
/// there is missing or, read through any link, does not have the bytes of the staged copy in
/// `staged_system32`.
///
/// CrossOver may launch a managed bottle from a private stub whose `system32` links back to the
/// managed prefix, so a different directory alone does not mean the shims were missed (#474).
pub fn shims_not_visible_in(
staged_system32: &Path,
launched_system32: &Path,
names: &[String],
) -> Vec<String> {
names
.iter()
.filter(|name| {
let staged = fs::read(staged_system32.join(name));
let seen = fs::read(launched_system32.join(name));
!matches!((staged, seen), (Ok(a), Ok(b)) if a == b)
})
.cloned()
.collect()
}
/// What staging did to one file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Staged {
Copied(PathBuf),
/// An earlier copy staged by this tool, refreshed because the shim changed.
Replaced(PathBuf),
Unchanged(PathBuf),
/// A [`SYSTEM32_SHIMS`] file the shim folder does not have.
Absent(PathBuf),
}
impl Staged {
pub fn describe(&self) -> String {
match self {
Staged::Copied(p) => format!("staged {}", p.display()),
Staged::Replaced(p) => format!("refreshed own earlier copy {}", p.display()),
Staged::Unchanged(p) => format!("already current {}", p.display()),
Staged::Absent(p) => format!("not staged, {} not found", p.display()),
}
}
}
/// True if the shim folder has any [`SYSTEM32_SHIMS`] file, so there is something to stage.
pub fn has_system32_shims(shims_dir: &Path) -> bool {
SYSTEM32_SHIMS
.iter()
.any(|name| find_shim(shims_dir, name).is_some())
}
/// Copies every [`SYSTEM32_SHIMS`] file, and the shims they import, from `shims_dir` into
/// `system32`. The directory must already exist (an uninitialized prefix is a caller error, not
/// something to skip). A shim the folder does not have is reported as [`Staged::Absent`], so a
/// run with a partial `--shims` folder still starts. A copy already identical byte for byte is
/// left alone. A different one is replaced only if this tool staged it and it is unchanged since
/// (see [`MANIFEST_NAME`]); any other existing entry, including a symbolic link that points
/// nowhere, is an error and nothing is written, so a DLL the bottle already had is never
/// modified or deleted. New files are installed without replacing anything, and each installed
/// file is recorded before the next one is touched. Nothing outside `system32` is written.
pub fn stage_system32(shims_dir: &Path, system32: &Path) -> Result<Vec<Staged>, String> {
stage_system32_with(shims_dir, system32, pe_imports)
}
fn stage_system32_with<I>(
shims_dir: &Path,
system32: &Path,
imports_of: I,
) -> Result<Vec<Staged>, String>
where
I: FnMut(&Path) -> Result<Vec<String>, String>,
{
stage_system32_hooked(shims_dir, system32, imports_of, |_| Ok(()))
}
/// Puts `bytes` at `dst` only if nothing is there, not even a dangling symbolic link.
///
/// `tmp` already holds the bytes. A hard link either creates `dst` whole or fails because the
/// name is taken; where links are not supported the file is created exclusively instead.
fn install_new(tmp: &Path, dst: &Path, bytes: &[u8]) -> io::Result<()> {
match fs::hard_link(tmp, dst) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Err(e),
Err(_) => {
use std::io::Write as _;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(dst)?;
file.write_all(bytes)
}
}
}
/// [`stage_system32_with`] with a hook called for each file just before it is put in place, so
/// tests can make something go wrong between the checks and the installation.
fn stage_system32_hooked<I, H>(
shims_dir: &Path,
system32: &Path,
mut imports_of: I,
mut before_publish: H,
) -> Result<Vec<Staged>, String>
where
I: FnMut(&Path) -> Result<Vec<String>, String>,
H: FnMut(&str) -> Result<(), String>,
{
let (roots, absent): (Vec<&str>, Vec<&str>) = SYSTEM32_SHIMS
.iter()
.copied()
.partition(|name| find_shim(shims_dir, name).is_some());
let mut staged: Vec<Staged> = absent
.iter()
.map(|name| Staged::Absent(shims_dir.join(name)))
.collect();
if roots.is_empty() {
return Ok(staged);
}
if !system32.is_dir() {
return Err(format!(
"{} does not exist; the prefix is not initialized",
system32.display()
));
}
let names = shim_closure(
&roots,
|dep| find_shim(shims_dir, dep).is_some(),
|name| match find_shim(shims_dir, name) {
Some(path) => imports_of(&path),
None => Err(format!(
"cannot read shim {}: not found",
shims_dir.join(name).display()
)),
},
)?;
let mut owned = read_manifest(system32)?;
let foreign = |dst: &Path, name: &str, what: &str| {
format!(
"{} {what}; it is left untouched. Use a bottle or prefix without its own {name}, \
or move that entry aside yourself, then run again",
dst.display()
)
};
// 1. Decide everything before writing anything, so a foreign entry stops the run with
// `system32` exactly as it was.
let mut plan = Vec::new();
for name in &names {
let src = find_shim(shims_dir, name).unwrap_or_else(|| shims_dir.join(name));
let bytes =
fs::read(&src).map_err(|e| format!("cannot read shim {}: {e}", src.display()))?;
let dst = system32.join(name);
// The directory entry itself is inspected, without following links: a dangling
// symbolic link has no contents to read but is still the bottle's entry.
let result = match fs::symlink_metadata(&dst) {
Err(e) if e.kind() == io::ErrorKind::NotFound => Staged::Copied(dst.clone()),
Err(e) => return Err(format!("cannot inspect {}: {e}", dst.display())),
Ok(meta) => {
let existing = match fs::read(&dst) {
Ok(existing) => Some(existing),
Err(_) if !meta.is_file() => None,
Err(e) => return Err(format!("cannot read {}: {e}", dst.display())),
};
if existing.as_deref() == Some(bytes.as_slice()) {
Staged::Unchanged(dst.clone())
} else if !meta.is_file() {
// bx-cli only ever writes regular files, so a link or anything else here
// was not staged by it.
return Err(foreign(
&dst,
name,
"already exists and is not a regular file (for example a symbolic link)",
));
} else if existing.as_deref().map(sha256_hex).as_ref() == owned.get(name) {
Staged::Replaced(dst.clone())
} else {
return Err(foreign(
&dst,
name,
"already exists and was not staged by bx-cli (or was changed since)",
));
}
}
};
plan.push((name, bytes, dst, result));
}
// 2. Write every new file beside its target first. A failure here publishes nothing.
let tmp_of = |name: &str| system32.join(format!(".{name}.{}.bx-staging", std::process::id()));
let pending: Vec<PathBuf> = plan
.iter()
.filter(|(_, _, _, result)| !matches!(result, Staged::Unchanged(_)))
.map(|(name, _, _, _)| tmp_of(name))
.collect();
let discard = |tmps: &[PathBuf]| {
for tmp in tmps {
let _ = fs::remove_file(tmp);
}
};
for (name, bytes, _, result) in &plan {
if !matches!(result, Staged::Unchanged(_)) {
let tmp = tmp_of(name);
if let Err(e) = fs::write(&tmp, bytes) {
discard(&pending);
return Err(format!("cannot write {}: {e}", tmp.display()));
}
}
}
// 3. Put the files in place one at a time, recording each in the manifest as soon as it is
// there. If a later file fails, the earlier ones are installed and owned, not orphaned.
for (name, bytes, dst, result) in plan {
if !matches!(result, Staged::Unchanged(_)) {
let tmp = tmp_of(name);
let published = before_publish(name).and_then(|()| match result {
// Nothing was there at step 1; refuse to replace whatever appeared since.
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
if e.kind() == io::ErrorKind::AlreadyExists {
foreign(
&dst,
name,
"appeared while staging and was not staged by bx-cli",
)
} else {
format!("cannot install {}: {e}", dst.display())
}
}),
// Still our own earlier copy? Then the rename replaces it in one step.
_ => match fs::read(&dst) {
Ok(now) if owned.get(name) == Some(&sha256_hex(&now)) => fs::rename(&tmp, &dst)
.map_err(|e| format!("cannot replace {}: {e}", dst.display())),
_ => Err(foreign(&dst, name, "changed while staging")),
},
});
if let Err(e) = published {
discard(&pending);
return Err(e);
}
let _ = fs::remove_file(&tmp);
owned.insert(name.clone(), sha256_hex(&bytes));
if let Err(e) = write_manifest(system32, &owned) {
discard(&pending);
return Err(e);
}
}
staged.push(result);
}
Ok(staged)
}
#[cfg(test)]
mod tests {
use super::*;
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let p = std::env::temp_dir().join(format!(
"bx-stage-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&p);
fs::create_dir_all(&p).unwrap();
TempDir(p)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn setup(tag: &str) -> (TempDir, PathBuf, PathBuf) {
let t = TempDir::new(tag);
let shims = t.0.join("shims");
let prefix = t.0.join("prefix");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(system32_dir(&prefix)).unwrap();
for name in SYSTEM32_SHIMS {
fs::write(shims.join(name), b"shim v1").unwrap();
}
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v1").unwrap();
fs::write(shims.join("unrelated.dll"), b"not imported").unwrap();
(t, shims, prefix)
}
/// The import graph of the fake shims: the runtime imports the VEH logger and a system DLL.
fn fake_imports(path: &Path) -> Result<Vec<String>, String> {
let name = path
.file_name()
.unwrap()
.to_string_lossy()
.to_ascii_lowercase();
Ok(match name.as_str() {
"xgameruntime.dll" => vec!["BX_RUNTIME_VEH.dll".into(), "KERNEL32.dll".into()],
_ => vec!["KERNEL32.dll".into()],
})
}
fn stage(shims: &Path, sys: &Path) -> Result<Vec<Staged>, String> {
stage_system32_with(shims, sys, fake_imports)
}
#[test]
fn closure_follows_shim_imports_only() {
let shims: BTreeSet<&str> = ["a.dll", "b.dll", "c.dll"].into();
let graph = |n: &str| -> Result<Vec<String>, String> {
Ok(match n {
"a.dll" => vec!["B.DLL".into(), "kernel32.dll".into()],
"b.dll" => vec!["c.dll".into(), "a.dll".into()],
_ => vec![],
})
};
let got = shim_closure(&["A.dll"], |d| shims.contains(d), graph).unwrap();
assert_eq!(got, vec!["a.dll", "b.dll", "c.dll"]);
}
#[test]
fn stages_the_runtime_and_its_shim_dependency() {
let (_t, shims, prefix) = setup("deps");
let sys = system32_dir(&prefix);
let staged = stage(&shims, &sys).unwrap();
assert_eq!(staged.len(), 2, "{staged:?}");
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
assert!(
!sys.join("unrelated.dll").exists(),
"only imported shims are staged"
);
}
#[test]
fn system32_is_under_drive_c() {
assert_eq!(
system32_dir(Path::new("/p")),
PathBuf::from("/p/drive_c/windows/system32")
);
}
#[test]
fn copies_then_leaves_identical_copy_alone() {
let (_t, shims, prefix) = setup("idem");
let sys = system32_dir(&prefix);
let first = stage(&shims, &sys).unwrap();
assert!(first.iter().all(|s| matches!(s, Staged::Copied(_))));
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
let second = stage(&shims, &sys).unwrap();
assert!(second.iter().all(|s| matches!(s, Staged::Unchanged(_))));
}
#[test]
fn sha256_matches_the_published_test_vectors() {
// FIPS 180-4 / NIST example values.
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
// Padding boundaries (one block, two blocks, exactly one block of data); expected
// values computed independently with Python's hashlib.
for (len, expected) in [
(
55usize,
"9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318",
),
(
56usize,
"b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a",
),
(
64usize,
"ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb",
),
(
1000usize,
"41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3",
),
] {
assert_eq!(sha256_hex(&vec![b'a'; len]), expected, "{len} bytes");
}
}
/// Every regular file in `dir` with its bytes, for before/after comparison.
fn snapshot(dir: &Path) -> BTreeMap<String, Vec<u8>> {
fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap())
.map(|e| {
(
e.file_name().to_string_lossy().into_owned(),
fs::read(e.path()).unwrap(),
)
})
.collect()
}
#[test]
fn a_foreign_file_with_different_bytes_is_never_modified() {
let (_t, shims, prefix) = setup("foreign");
let sys = system32_dir(&prefix);
// The bottle's own runtime, put there by something other than bx-cli.
fs::write(sys.join("xgameruntime.dll"), b"the bottle's own runtime").unwrap();
let before = snapshot(&sys);
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("xgameruntime.dll"), "{err}");
assert!(err.contains("not staged by bx-cli"), "{err}");
// Nothing changed: not the foreign file, no dependency copied beside it, no manifest.
assert_eq!(snapshot(&sys), before);
// Still refused on the next run.
assert!(stage(&shims, &sys).is_err());
assert_eq!(snapshot(&sys), before);
}
#[test]
fn a_foreign_dependency_blocks_staging_before_anything_is_written() {
let (_t, shims, prefix) = setup("foreign-dep");
let sys = system32_dir(&prefix);
fs::write(sys.join("bx_runtime_veh.dll"), b"someone else's file").unwrap();
let before = snapshot(&sys);
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("bx_runtime_veh.dll"), "{err}");
assert_eq!(
snapshot(&sys),
before,
"xgameruntime.dll must not be staged either"
);
}
#[test]
fn an_owned_copy_changed_by_someone_else_is_not_replaced() {
let (_t, shims, prefix) = setup("tampered");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
// Something else (an installer) replaced our copy after we staged it.
fs::write(sys.join("xgameruntime.dll"), b"installed over ours").unwrap();
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
let before = snapshot(&sys);
assert!(stage(&shims, &sys).is_err());
assert_eq!(snapshot(&sys), before);
}
#[test]
fn an_identical_foreign_file_is_left_alone_and_not_claimed() {
let (_t, shims, prefix) = setup("identical");
let sys = system32_dir(&prefix);
fs::write(sys.join("xgameruntime.dll"), b"shim v1").unwrap();
let staged = stage(&shims, &sys).unwrap();
assert!(staged.contains(&Staged::Unchanged(sys.join("xgameruntime.dll"))));
assert!(
!read_manifest(&sys)
.unwrap()
.contains_key("xgameruntime.dll")
);
// Not ours, so a later shim change must not replace it.
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
}
#[test]
fn refreshes_a_stale_copy_it_staged_itself() {
let (_t, shims, prefix) = setup("replace");
let sys = system32_dir(&prefix);
let first = stage(&shims, &sys).unwrap();
assert!(first.iter().all(|s| matches!(s, Staged::Copied(_))));
let manifest = fs::read_to_string(sys.join(MANIFEST_NAME)).unwrap();
assert!(
manifest.contains(&format!("{} xgameruntime.dll\n", sha256_hex(b"shim v1"))),
"{manifest}"
);
// The shim is rebuilt; the copy in system32 is now stale but still ours.
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
let staged = stage(&shims, &sys).unwrap();
assert!(staged.contains(&Staged::Replaced(sys.join("xgameruntime.dll"))));
assert!(staged.contains(&Staged::Unchanged(sys.join("bx_runtime_veh.dll"))));
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v2");
let owned = read_manifest(&sys).unwrap();
assert_eq!(owned.get("xgameruntime.dll"), Some(&sha256_hex(b"shim v2")));
assert_eq!(
owned.get("bx_runtime_veh.dll"),
Some(&sha256_hex(b"veh v1"))
);
let leftovers: Vec<_> = fs::read_dir(&sys)
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().contains("bx-staging"))
.collect();
assert!(leftovers.is_empty(), "temporary file left behind");
}
#[test]
fn a_dangling_symlink_is_a_foreign_entry_and_stays() {
let (_t, shims, prefix) = setup("dangling");
let sys = system32_dir(&prefix);
let link = sys.join("xgameruntime.dll");
std::os::unix::fs::symlink(sys.join("no-such-target.dll"), &link).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("xgameruntime.dll"), "{err}");
assert!(err.contains("symbolic link"), "{err}");
// Still the same dangling link, and nothing else was staged beside it.
assert_eq!(
fs::read_link(&link).unwrap(),
sys.join("no-such-target.dll")
);
assert!(!sys.join("bx_runtime_veh.dll").exists());
assert!(!sys.join(MANIFEST_NAME).exists());
}
#[test]
fn a_symlink_is_never_replaced_whatever_it_points_to() {
let (t, shims, prefix) = setup("symlink");
let sys = system32_dir(&prefix);
let link = sys.join("xgameruntime.dll");
// Pointing at a file with other contents: foreign, and the target is not written to.
let target = t.0.join("elsewhere.dll");
fs::write(&target, b"the bottle's own runtime").unwrap();
std::os::unix::fs::symlink(&target, &link).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(&target).unwrap(), b"the bottle's own runtime");
assert_eq!(fs::read_link(&link).unwrap(), target);
// Pointing at identical contents: already current, left as a link and not claimed.
fs::write(&target, b"shim v1").unwrap();
let staged = stage(&shims, &sys).unwrap();
assert!(staged.contains(&Staged::Unchanged(link.clone())));
assert_eq!(fs::read_link(&link).unwrap(), target);
assert!(
!read_manifest(&sys)
.unwrap()
.contains_key("xgameruntime.dll")
);
}
#[test]
fn an_entry_that_appears_after_the_checks_is_not_replaced() {
let (_t, shims, prefix) = setup("late");
let sys = system32_dir(&prefix);
let dst = sys.join("xgameruntime.dll");
let late = dst.clone();
let err = stage_system32_hooked(&shims, &sys, fake_imports, |name| {
if name == "xgameruntime.dll" {
fs::write(&late, b"installed meanwhile").unwrap();
}
Ok(())
})
.unwrap_err();
assert!(err.contains("appeared while staging"), "{err}");
assert_eq!(fs::read(&dst).unwrap(), b"installed meanwhile");
assert!(
!read_manifest(&sys)
.unwrap()
.contains_key("xgameruntime.dll")
);
assert!(no_temporary_files(&sys));
}
#[test]
fn a_later_failure_leaves_earlier_copies_installed_and_owned() {
let (_t, shims, prefix) = setup("partial");
let sys = system32_dir(&prefix);
// Files are installed in name order: the VEH logger first, then the runtime.
let err = stage_system32_hooked(&shims, &sys, fake_imports, |name| {
if name == "xgameruntime.dll" {
return Err("disk full".to_string());
}
Ok(())
})
.unwrap_err();
assert_eq!(err, "disk full");
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
assert!(!sys.join("xgameruntime.dll").exists());
let owned = read_manifest(&sys).unwrap();
assert_eq!(
owned.get("bx_runtime_veh.dll"),
Some(&sha256_hex(b"veh v1"))
);
assert!(no_temporary_files(&sys));
// The retry completes, and the first file is still ours: a later update refreshes it.
let retry = stage(&shims, &sys).unwrap();
assert!(retry.contains(&Staged::Unchanged(sys.join("bx_runtime_veh.dll"))));
assert!(retry.contains(&Staged::Copied(sys.join("xgameruntime.dll"))));
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let update = stage(&shims, &sys).unwrap();
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
}
#[test]
fn a_failed_temporary_write_publishes_nothing() {
let (_t, shims, prefix) = setup("prepare");
let sys = system32_dir(&prefix);
// A directory where the second file's temporary copy has to go makes that write fail.
let obstacle = sys.join(format!(
".xgameruntime.dll.{}.bx-staging",
std::process::id()
));
fs::create_dir(&obstacle).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("cannot write"), "{err}");
assert!(
!sys.join("bx_runtime_veh.dll").exists(),
"first file was published"
);
assert!(!sys.join("xgameruntime.dll").exists());
assert!(!sys.join(MANIFEST_NAME).exists());
fs::remove_dir(&obstacle).unwrap();
assert!(
stage(&shims, &sys)
.unwrap()
.iter()
.all(|s| matches!(s, Staged::Copied(_)))
);
}
#[test]
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
let (t, shims, prefix) = setup("visible");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
let names = vec![
"bx_runtime_veh.dll".to_string(),
"xgameruntime.dll".to_string(),
];
// A private stub whose system32 links back to the managed prefix, as CrossOver creates.
let stub = system32_dir(&t.0.join("stub"));
fs::create_dir_all(&stub).unwrap();
for name in &names {
std::os::unix::fs::symlink(sys.join(name), stub.join(name)).unwrap();
}
assert!(shims_not_visible_in(&sys, &stub, &names).is_empty());
// A stub that really lacks one shim, or has other bytes under that name.
fs::remove_file(stub.join("xgameruntime.dll")).unwrap();
assert_eq!(
shims_not_visible_in(&sys, &stub, &names),
vec!["xgameruntime.dll"]
);
fs::write(stub.join("xgameruntime.dll"), b"something else").unwrap();
assert_eq!(
shims_not_visible_in(&sys, &stub, &names),
vec!["xgameruntime.dll"]
);
// An empty stub sees none of them.
let empty = system32_dir(&t.0.join("empty"));
fs::create_dir_all(&empty).unwrap();
assert_eq!(shims_not_visible_in(&sys, &empty, &names), names);
}
fn no_temporary_files(sys: &Path) -> bool {
fs::read_dir(sys)
.unwrap()
.filter_map(|e| e.ok())
.all(|e| !e.file_name().to_string_lossy().contains("bx-staging"))
}
#[test]
fn a_damaged_manifest_only_makes_files_look_foreign() {
let (_t, shims, prefix) = setup("manifest");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
fs::write(
sys.join(MANIFEST_NAME),
"not a manifest\nabc xgameruntime.dll\n",
)
.unwrap();
assert!(read_manifest(&sys).unwrap().is_empty());
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
}
#[test]
fn missing_shim_is_reported_and_nothing_is_staged() {
let (t, shims, prefix) = setup("missing");
fs::remove_file(shims.join("xgameruntime.dll")).unwrap();
assert!(!has_system32_shims(&shims));
let sys = system32_dir(&prefix);
let expected = vec![Staged::Absent(shims.join("xgameruntime.dll"))];
assert_eq!(stage(&shims, &sys).unwrap(), expected);
assert_eq!(fs::read_dir(&sys).unwrap().count(), 0);
// With nothing to stage, a prefix without system32 is not an error either.
let fresh = system32_dir(&t.0.join("fresh"));
assert_eq!(stage(&shims, &fresh).unwrap(), expected);
assert!(!fresh.exists());
}
#[test]
fn uninitialized_prefix_is_an_error_not_a_skip() {
let (t, shims, _prefix) = setup("uninit");
let sys = system32_dir(&t.0.join("fresh"));
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("not initialized"), "{err}");
assert!(!sys.exists(), "staging must not create the prefix itself");
}
#[test]
fn writes_only_inside_system32() {
let (_t, shims, prefix) = setup("scope");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
let windows: Vec<_> = fs::read_dir(prefix.join("drive_c/windows"))
.unwrap()
.map(|e| e.unwrap().file_name())
.collect();
assert_eq!(windows, vec![std::ffi::OsString::from("system32")]);
}
}
+245
View File
@@ -0,0 +1,245 @@
//! 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::{AtomicI32, 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);
static SIGNAL: AtomicI32 = AtomicI32::new(0);
extern "C" fn note_signal(signal: libc::c_int) {
SIGNAL.store(signal, Ordering::SeqCst);
}
/// Records SIGINT, SIGTERM and SIGHUP instead of dying, so the run can be cleaned up.
pub fn install_signal_handlers() {
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
// SAFETY: the handler only stores to an atomic, which is async-signal-safe.
unsafe {
libc::signal(
signal,
note_signal as extern "C" fn(libc::c_int) as libc::sighandler_t,
);
}
}
}
pub fn received_signal() -> i32 {
SIGNAL.load(Ordering::SeqCst)
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Stop {
TimedOut,
Signalled(i32),
}
#[derive(Debug)]
pub enum Outcome {
Exited(ExitStatus),
Stopped(Stop),
}
impl Outcome {
/// 0 or 1 for the guest's own result, 124 for a timeout (as `timeout(1)`), 128 + N for a
/// signal.
pub fn exit_code(&self) -> u8 {
match self {
Outcome::Exited(status) => u8::from(!status.success()),
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.
pub fn supervise(
mut command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
) -> 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 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 timeout.is_some_and(|limit| started.elapsed() >= 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.
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)
.stdout(Stdio::null())
.stderr(Stdio::null())
.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(), 1);
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();
}
#[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();
}
}
+93 -3
View File
@@ -1,20 +1,32 @@
//! 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>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
}
#[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> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
@@ -34,8 +46,23 @@ 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;
let sample = detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok());
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
}
"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 +91,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 +104,65 @@ 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()),
},
]
);
}
}
@@ -0,0 +1,59 @@
# 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.
### Not done here (other owners)
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`):** the frozen export list for the DLL. Linking with it would also set the export directory's internal name, which is `dxbc_accc.dll` today. Wine loads by file name, so this does not affect loading.
- **Staging in `scripts/build-shims.sh` (Track A):** building the DLL there and verifying it with the other shims, so `build-shims/bin` ships it. That would also make CI build it; today nothing does, and `rustup target add x86_64-pc-windows-gnu` is a manual step.
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (#466):** today `bx_shader_prepare_for_d3dmetal` reports an ACCC-only container on the guest's stderr (`bx-shader event=prepare status=unsupported …`), not through `bx_log_emit`.
+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;
}
+70 -10
View File
@@ -1,6 +1,8 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstdint>
#include <unordered_map>
#include "bx_log.h"
@@ -10,6 +12,30 @@ constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
using Callback = void (WINAPI*)();
// 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;
@@ -19,6 +45,11 @@ HRESULT unavailable(T* out) {
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;
@@ -54,9 +85,32 @@ public:
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterDeviceCallback(void*, uint32_t, uint32_t, uint32_t, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback");
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");
@@ -66,12 +120,18 @@ public:
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
return unavailable(out);
}
virtual void WINAPI StopCallback(uint64_t) {
BX_VTABLE_STUB_LOG("IGameInput", 12, "StopCallback");
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, uint64_t) {
BX_VTABLE_STUB_LOG("IGameInput", 13, "UnregisterCallback");
return false;
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");
@@ -101,8 +161,8 @@ public:
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
return E_NOTIMPL;
}
virtual void WINAPI SetFocusPolicy(uint32_t) {
BX_VTABLE_STUB_LOG("IGameInput", 21, "SetFocusPolicy");
virtual void WINAPI SetFocusPolicy(uint32_t policy) {
focus_policy_.store(policy, std::memory_order_relaxed);
}
};
+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"
+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)
+616
View File
@@ -0,0 +1,616 @@
/*
* 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.
*/
#include "com_dispatch.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) {}
const std::array<const void*, 8> kErrorVtbl = [] {
auto v = make_default_vtbl<8>();
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"};
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},
};
} // 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
+930
View File
@@ -0,0 +1,930 @@
/*
* Offline XGameSave over bottle-local storage (#468).
*
* Reached only through QueryApiImpl with the BetterXen synthetic xgamesave key; the key and
* the vtable slot order are in synthetic_keys.h. Nothing here is exported.
*
* 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"
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;
}
// --- Slots ---
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, Blob* blobs, uint32_t* count) {
if (!count) return E_POINTER;
*count = 0;
return consume_async_op(async, kReadBlobsOp, [&](AsyncOp& base) {
const auto& op = static_cast<const ReadBlobsOp&>(base);
if (size < op.bytes) return kProvidedBufferTooSmall;
if (op.bytes && !blobs) return E_POINTER;
op.copy_to(blobs);
*count = static_cast<uint32_t>(op.found.size());
return S_OK;
});
}
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, ContainerInfoCallback callback) {
if (!callback) return E_INVALIDARG;
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 (!callback(&info, context)) break;
}
return S_OK;
}
// --- 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
+236
View File
@@ -0,0 +1,236 @@
/*
* Offline XPackage identity and mount queries (#468).
*
* Reached only through QueryApiImpl with the BetterXen synthetic xpackage key; the key and
* the vtable slot order are in synthetic_keys.h. Nothing here is exported.
*
* 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) accepts 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.
* - 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 <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;
}
// --- Slots ---
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;
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 {
std::string path(static_cast<size_t>(bytes), '\0');
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, path.data(), bytes, nullptr, nullptr);
path.pop_back(); // The terminator is added back on copy-out.
std::lock_guard lock(mount_mutex);
++handle_counter;
void* handle = reinterpret_cast<void*>(kMountTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
mounts.emplace(handle, Mount{generation, std::move(path)});
*out = handle;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
return S_OK;
}
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);
}
// --- 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
+75
View File
@@ -0,0 +1,75 @@
#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
} // namespace bx::gdk
+90
View File
@@ -0,0 +1,90 @@
#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 until a
* properly sourced mapping exists. 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;
}
+25 -31
View File
@@ -10,6 +10,7 @@
#include "bx_log.h"
#include "bx_xmem_internal.h"
#include "xmem_accounting.h"
namespace {
constexpr SIZE_T heap_alignment = 64;
@@ -61,6 +62,7 @@ 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() {
@@ -70,12 +72,12 @@ uint64_t title_limit() {
bool can_commit(uint64_t bytes) {
const uint64_t limit = title_limit();
const uint64_t used = heap_bytes + virtual_bytes;
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);
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
}
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
@@ -268,29 +270,6 @@ SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, S
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 (bytes == 0) return TRUE;
if (!dst || !src) {
@@ -311,7 +290,7 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
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;
@@ -321,18 +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;
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, 0, peak_bytes};
*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;
}
+39 -1
View File
@@ -27,6 +27,10 @@ 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);
@@ -148,8 +152,42 @@ int main() {
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");
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1 and device callbacks");
}
@@ -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,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,65 @@
/*
* #457: clean-room synthetic test for system32 shim staging by `bx-cli run`.
*
* GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll", NULL,
* LOAD_LIBRARY_SEARCH_SYSTEM32), which does not search WINEPATH or the executable's folder.
* This test makes that load and requires that BetterXen's shim answers it:
* - the module loads, from a path under system32;
* - it exports QueryApiImpl (a BetterXen xgameruntime export, absent from Wine builtins);
* - LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR gives the same module.
*
* `--expect-missing` is the negative control for an unstaged prefix: the load must fail.
* Exit 0 on pass, 1 on failure.
*/
#include <windows.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) {
wchar_t path[MAX_PATH * 2] = {};
const DWORD n = GetModuleFileNameW(m, path, MAX_PATH * 2);
if (n == 0 || n >= MAX_PATH * 2) return false;
for (DWORD i = 0; i < n; ++i) path[i] = static_cast<wchar_t>(towlower(path[i]));
std::printf("INFO: loaded from %ls\n", path);
return std::wcsstr(path, L"\\windows\\system32\\xgameruntime.dll") != nullptr;
}
} // 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 load fails");
if (sys) FreeLibrary(sys);
} else if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) {
check(path_in_system32(sys), "module path is under system32");
check(GetProcAddress(sys, "QueryApiImpl") != nullptr, "module exports QueryApiImpl (BetterXen shim)");
HMODULE both = LoadLibraryExW(L"xgameruntime.dll", nullptr,
LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR);
check(both == sys, "SYSTEM32 | APPLICATION_DIR search returns the same module");
if (both) FreeLibrary(both);
FreeLibrary(sys);
}
std::printf("SUMMARY: %d checks, %d failed\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 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;
}
@@ -136,6 +136,29 @@ void check_storage() {
} // namespace
bool valid_utf8(const unsigned char* s, size_t n) {
size_t i = 0;
while (i < n) {
const unsigned char c = s[i];
size_t len = 0;
if (c < 0x80) len = 1;
else 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 false;
if (i + len > n) return false;
for (size_t k = 1; k < len; ++k) {
if ((s[i + k] & 0xC0) != 0x80) return false;
}
if (c == 0xE0 && s[i + 1] < 0xA0) return false;
if (c == 0xED && s[i + 1] > 0x9F) return false;
if (c == 0xF0 && s[i + 1] < 0x90) return false;
if (c == 0xF4 && s[i + 1] > 0x8F) return false;
i += len;
}
return true;
}
#ifndef BX_TEST_UNENTITLED
extern "C" __declspec(dllexport) void BetterXenSyntheticStoreFixture() {}
#endif
@@ -277,6 +300,279 @@ int main() {
check_storage();
XGameRuntimeUninitialize();
CHECK(FAILED(XUserAddAsync(1, &uninitialized)));
// Dynamic loader entry points. Synthetic family GUIDs match xgameruntime.cpp:
// Data2 = 0x5853, Data3 = 0x4000, Data4 = 80 00 00 00 00 00 00 01.
HMODULE module = GetModuleHandleA("xgameruntime.dll");
CHECK(module);
const char* names[] = {"InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2",
"UninitializeApiImpl", "QueryApiImpl", "XErrorReport"};
FARPROC procs[6]{};
for (int i = 0; i < 6; ++i) {
procs[i] = GetProcAddress(module, names[i]);
CHECK(procs[i]);
}
const auto load = [](FARPROC proc, auto& fn) { std::memcpy(&fn, &proc, sizeof(fn)); };
using InitFn = HRESULT(WINAPI*)(uint32_t, uint32_t);
using InitExFn = HRESULT(WINAPI*)(uint32_t, uint32_t, char);
using InitEx2Fn = HRESULT(WINAPI*)(uint32_t, uint32_t, char, const void*);
using UninitFn = HRESULT(WINAPI*)();
using QueryFn = HRESULT(WINAPI*)(const GUID*, const GUID*, void**);
using ErrorFn = void(WINAPI*)(HRESULT, const char*);
InitFn init_api{};
InitExFn init_ex{};
InitEx2Fn init_ex2{};
UninitFn uninit_api{};
QueryFn query_api{};
ErrorFn error_report{};
load(procs[0], init_api);
load(procs[1], init_ex);
load(procs[2], init_ex2);
load(procs[3], uninit_api);
load(procs[4], query_api);
load(procs[5], error_report);
struct ApiInitOptions {
uint32_t unknown;
uint8_t is_inline;
uint8_t pad[3];
const char* game_config;
};
static_assert(offsetof(ApiInitOptions, game_config) == 8);
const auto family_guid = [](uint32_t data1) {
GUID guid{};
guid.Data1 = data1;
guid.Data2 = 0x5853;
guid.Data3 = 0x4000;
guid.Data4[0] = 0x80;
guid.Data4[7] = 0x01;
return guid;
};
const GUID xsystem = family_guid(0xB7581401);
const GUID xsystem_iid = family_guid(0xB7581402);
const GUID wrong_iid = family_guid(0xB75814FF);
GUID bogus{};
bogus.Data1 = 0xDEADBEEF;
bogus.Data4[0] = 0x11;
constexpr HRESULT not_initialized = static_cast<HRESULT>(0x89240100u);
auto* sentinel = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
void* api = sentinel;
CHECK(query_api(&xsystem, &xsystem_iid, nullptr) == E_POINTER);
CHECK(api == sentinel);
api = sentinel;
CHECK(query_api(nullptr, &xsystem_iid, &api) == E_INVALIDARG && !api);
api = sentinel;
CHECK(query_api(&xsystem, nullptr, &api) == E_INVALIDARG && !api);
api = sentinel;
CHECK(query_api(&xsystem, &xsystem_iid, &api) == not_initialized && !api);
CHECK(init_api(0, 1) == E_INVALIDARG);
CHECK(init_ex(1, 0, 2) == E_INVALIDARG);
const ApiInitOptions broken{1u, 1u, {0, 0, 0}, nullptr};
CHECK(init_ex2(1, 1, 2, &broken) == E_INVALIDARG);
const ApiInitOptions file_opt{1u, 0u, {0, 0, 0}, "C:\\bx_synthetic\\MicrosoftGame.config"};
CHECK(init_ex2(1, 1, 2, &file_opt) == E_NOTIMPL);
void* probe = nullptr;
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
CHECK(init_api(1, 1) == S_OK);
CHECK(XGameRuntimeInitialize() == S_OK);
CHECK(uninit_api() == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == S_OK && probe);
XStoreCloseContextHandle(probe);
XGameRuntimeUninitialize();
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
CHECK(uninit_api() == not_initialized);
CHECK(init_ex(1, 1, 2) == S_OK);
CHECK(init_ex2(1, 1, 6, nullptr) == S_OK);
CHECK(uninit_api() == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == S_OK && probe);
XStoreCloseContextHandle(probe);
XGameRuntimeUninitialize();
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
const ApiInitOptions default_opts{1u, 0u, {0, 0, 0}, nullptr};
CHECK(init_ex2(1, 1, 6, &default_opts) == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == S_OK && probe);
XStoreCloseContextHandle(probe);
CHECK(uninit_api() == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
CHECK(init_api(1, 1) == S_OK);
const uint32_t families[][2] = {
{0xB7581001, 0xB7581002}, {0xB7581101, 0xB7581102}, {0xB7581201, 0xB7581202},
{0xB7581301, 0xB7581302}, {0xB7581401, 0xB7581402}, {0xB7581501, 0xB7581502},
};
struct SystemHead {
uint32_t(WINAPI* get_device_type)();
};
for (const auto& ids : families) {
const GUID clsid = family_guid(ids[0]);
const GUID iid = family_guid(ids[1]);
void* table = nullptr;
CHECK(query_api(&clsid, &iid, &table) == S_OK && table);
if (ids[0] == 0xB7581401) {
CHECK(static_cast<SystemHead*>(table)->get_device_type() == XSystemGetDeviceType());
}
}
struct LogSpan {
bool from_file = false;
char path[512]{};
long mark = 0;
HANDLE pipe_read = nullptr;
HANDLE pipe_write = nullptr;
HANDLE saved_err = nullptr;
char text[64 * 1024]{};
bool start() {
const auto n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n > 0 && n < sizeof(path)) {
from_file = true;
if (auto* file = std::fopen(path, "rb")) {
std::fseek(file, 0, SEEK_END);
mark = std::ftell(file);
std::fclose(file);
}
return true;
}
if (!CreatePipe(&pipe_read, &pipe_write, nullptr, sizeof(text))) return false;
saved_err = GetStdHandle(STD_ERROR_HANDLE);
return SetStdHandle(STD_ERROR_HANDLE, pipe_write) != 0;
}
void finish() {
size_t got = 0;
if (from_file) {
if (auto* file = std::fopen(path, "rb")) {
std::fseek(file, mark, SEEK_SET);
got = std::fread(text, 1, sizeof(text) - 1, file);
std::fclose(file);
}
} else if (pipe_read) {
SetStdHandle(STD_ERROR_HANDLE, saved_err);
CloseHandle(pipe_write);
DWORD chunk = 0;
while (got + 1 < sizeof(text) &&
ReadFile(pipe_read, text + got, static_cast<DWORD>(sizeof(text) - 1 - got), &chunk, nullptr) &&
chunk) {
got += chunk;
}
CloseHandle(pipe_read);
}
text[got] = '\0';
}
bool has(const char* needle) const { return std::strstr(text, needle) != nullptr; }
} span;
CHECK(span.start());
api = sentinel;
const auto mismatched = query_api(&xsystem, &wrong_iid, &api);
CHECK(mismatched == E_NOINTERFACE && !api);
api = sentinel;
const auto unsupported = query_api(&bogus, &bogus, &api);
error_report(E_FAIL, "synthetic-gdk-error");
error_report(E_FAIL, nullptr);
error_report(E_FAIL, "err \"quoted\" \\path\nline2");
error_report(E_FAIL, "caf\xE9");
char long_msg[701];
long_msg[0] = 'x';
size_t long_n = 1;
while (long_n + 2 <= 700) {
long_msg[long_n++] = '\xC3';
long_msg[long_n++] = '\xA9';
}
long_msg[long_n] = '\0';
error_report(E_FAIL, long_msg);
span.finish();
CHECK(unsupported == E_NOINTERFACE && !api);
CHECK(span.has("\"sub\":\"xgameruntime\",\"event\":\"QueryApiImpl\"") && span.has("unsupported clsid=DEADBEEF"));
CHECK(span.has("\"event\":\"unimpl_api\"") &&
span.has("xgameruntime.dll!QueryApiImpl(B7581401-5853-4000-8000-000000000001/"
"B75814FF-5853-4000-8000-000000000001)") &&
span.has("xgameruntime.dll!QueryApiImpl(DEADBEEF-0000-0000-1100-000000000000/"
"DEADBEEF-0000-0000-1100-000000000000)"));
CHECK(span.has("\"sub\":\"xgameruntime\",\"event\":\"XErrorReport\"") &&
span.has("hr=0x80004005 msg=synthetic-gdk-error"));
CHECK(span.has("hr=0x80004005 msg=(null)"));
CHECK(span.has("msg=err \\\"quoted\\\" \\\\path\\u000Aline2"));
CHECK(span.has("caf\\u00E9"));
CHECK(std::memchr(span.text, static_cast<unsigned char>(0xE9), std::strlen(span.text)) == nullptr);
CHECK(valid_utf8(reinterpret_cast<const unsigned char*>(span.text), std::strlen(span.text)));
size_t eacute = 0;
const auto* bytes = reinterpret_cast<const unsigned char*>(span.text);
const size_t nbytes = std::strlen(span.text);
for (size_t i = 0; i + 1 < nbytes; ++i) {
if (bytes[i] == 0xC3 && bytes[i + 1] == 0xA9) ++eacute;
}
CHECK(eacute > 0 && eacute < (long_n - 1) / 2);
// Public Microsoft.GDK.Windows 2610.0.9661 COM IUnknown QueryApiImpl dispatch checks (#456).
{
const GUID core_guid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
const GUID sys_clsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
const GUID sys_iid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
const GUID game_clsid = {0x973A344E, 0x24BF, 0x4D0F, {0x84, 0x57, 0x56, 0xC5, 0x34, 0x89, 0x2B, 0x29}};
const GUID game_iid = {0x2549F142, 0x6419, 0x4A06, {0x97, 0xB5, 0x93, 0x1A, 0xAB, 0x7C, 0x2F, 0x34}};
const GUID net_clsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36, 0xED, 0xB1, 0x85, 0x33, 0x1A}};
const GUID net_iid = {0xBF2346B2, 0x39AF, 0x4658, {0xB5, 0xEA, 0x44, 0x71, 0x3C, 0x7E, 0x83, 0xB3}};
const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
void* com_core = nullptr;
CHECK(SUCCEEDED(query_api(&core_guid, &core_guid, &com_core)) && com_core);
auto** core_vtbl = *static_cast<void***>(com_core);
auto qi = reinterpret_cast<HRESULT(WINAPI*)(void*, const GUID*, void**)>(core_vtbl[0]);
auto release = reinterpret_cast<ULONG(WINAPI*)(void*)>(core_vtbl[2]);
auto tq_create = reinterpret_cast<HRESULT(WINAPI*)(void*, uint32_t, uint32_t, void**)>(core_vtbl[12]);
auto tq_close = reinterpret_cast<void(WINAPI*)(void*, void*)>(core_vtbl[17]);
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[14]);
void* qi_out = nullptr;
CHECK(SUCCEEDED(qi(com_core, &iunknown, &qi_out)) && qi_out == com_core);
void* q = nullptr;
CHECK(SUCCEEDED(tq_create(com_core, 2, 2, &q)) && q);
tq_close(com_core, q);
CHECK(unimpl_slot(com_core) == E_NOTIMPL);
CHECK(release(com_core) >= 1);
void* com_sys = nullptr;
CHECK(SUCCEEDED(query_api(&sys_clsid, &sys_iid, &com_sys)) && com_sys);
auto** sys_vtbl = *static_cast<void***>(com_sys);
auto get_cid = reinterpret_cast<HRESULT(WINAPI*)(void*, size_t, char*, size_t*)>(sys_vtbl[3]);
char cid[64]{};
size_t cid_used = 0;
CHECK(SUCCEEDED(get_cid(com_sys, sizeof(cid), cid, &cid_used)) && cid_used > 1);
void* com_game = nullptr;
CHECK(SUCCEEDED(query_api(&game_clsid, &game_iid, &com_game)) && com_game);
auto** game_vtbl = *static_cast<void***>(com_game);
auto get_tid = reinterpret_cast<HRESULT(WINAPI*)(void*, uint32_t*)>(game_vtbl[3]);
uint32_t title_id = 0;
CHECK(SUCCEEDED(get_tid(com_game, &title_id)) && title_id != 0);
void* com_net = nullptr;
CHECK(SUCCEEDED(query_api(&net_clsid, &net_iid, &com_net)) && com_net);
auto** net_vtbl = *static_cast<void***>(com_net);
struct NetHint { uint32_t lvl, cost, iana; bool init, app, over, roam; };
auto get_hint = reinterpret_cast<HRESULT(WINAPI*)(void*, NetHint*)>(net_vtbl[15]);
NetHint hint{};
CHECK(SUCCEEDED(get_hint(com_net, &hint)) && hint.init);
const GUID user_guid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
void* com_user = nullptr;
CHECK(SUCCEEDED(query_api(&user_guid, &user_guid, &com_user)) && com_user);
auto** user_vtbl = *static_cast<void***>(com_user);
auto reg_ev = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void*, void*, uint64_t*)>(user_vtbl[33]);
auto unreg_ev = reinterpret_cast<bool(WINAPI*)(void*, uint64_t, bool)>(user_vtbl[34]);
uint64_t ev_tok = 0;
auto dummy_cb = [](void*, uint64_t, uint32_t) {};
CHECK(SUCCEEDED(reg_ev(com_user, nullptr, nullptr, reinterpret_cast<void*>(+dummy_cb), &ev_tok)) && ev_tok != 0);
CHECK(unreg_ev(com_user, ev_tok, false));
CHECK(!unreg_ev(com_user, ev_tok, false));
}
XGameRuntimeUninitialize();
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
std::printf("xgameruntime conformance passed (%s, synthetic license %s)\n",
profile, entitled ? "active" : "inactive");
return 0;
@@ -0,0 +1,2 @@
add_executable(test_xgameruntime_saves main.cpp)
target_link_libraries(test_xgameruntime_saves PRIVATE xgameruntime kernel32 shell32)
@@ -0,0 +1,880 @@
// Offline XGameSave and XPackage through QueryApiImpl (#468).
//
// This fixture declares its own copies of the BetterXen synthetic keys and slot orders, of
// the public structures, and of the documented storage layout, instead of including the
// shim's headers, so a mistake there fails here. The keys must match
// shims/xgameruntime/synthetic_keys.h. Structure layouts and error values follow the Microsoft
// Learn XGameSave and XPackage reference pages; the file layout and naming follow the header
// comment of shims/xgameruntime/game_save.cpp.
//
// Run with no arguments. "--writer <id> <count> <event>" is the child mode used by the
// cross-process check.
#include <windows.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <ctime>
#include <string>
#include <vector>
namespace {
#define CHECK(expr) do { \
if (!(expr)) { std::fprintf(stderr, "FAIL: test_xgameruntime_saves line %d: %s\n", __LINE__, #expr); std::exit(1); } \
} while (false)
struct Async {
void* queue;
void* context;
void (CALLBACK* callback)(Async*);
unsigned char reserved[32];
};
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(offsetof(ContainerInfo, total_size) == 24 && offsetof(ContainerInfo, needs_sync) == 40);
struct Blob { // XGameSaveBlob { XGameSaveBlobInfo { name, size }, data }
const char* name;
uint32_t size;
uint8_t* data;
};
static_assert(sizeof(Blob) == 24 && offsetof(Blob, data) == 16);
extern "C" {
HRESULT WINAPI XGameRuntimeInitialize();
void WINAPI XGameRuntimeUninitialize();
HRESULT WINAPI XTaskQueueCreate(uint32_t, uint32_t, void**);
void WINAPI XTaskQueueCloseHandle(void*);
bool WINAPI XTaskQueueDispatch(void*, uint32_t, uint32_t);
HRESULT WINAPI XUserAddAsync(uint32_t, Async*);
HRESULT WINAPI XUserAddResult(Async*, void**);
void WINAPI XUserCloseHandle(void*);
HRESULT WINAPI XAsyncGetStatus(Async*, bool);
HRESULT WINAPI XAsyncGetResultSize(Async*, size_t*);
void WINAPI XAsyncCancel(Async*);
HRESULT WINAPI XPersistentLocalStorageGetPath(size_t, char*, size_t*);
HRESULT WINAPI QueryApiImpl(const GUID*, const GUID*, void**);
}
// Expected values, from the public reference pages and the existing runtime.
constexpr HRESULT kInvalidContainerName = static_cast<HRESULT>(0x80830001u);
constexpr HRESULT kUpdateTooBig = static_cast<HRESULT>(0x80830005u);
constexpr HRESULT kBufferTooSmall = static_cast<HRESULT>(0x80830007u);
constexpr HRESULT kBlobNotFound = static_cast<HRESULT>(0x80830008u);
constexpr HRESULT kInvalidHandle = static_cast<HRESULT>(0x8924010cu);
constexpr HRESULT kNotInitialized = static_cast<HRESULT>(0x89240100u);
constexpr HRESULT kIllegalCall = static_cast<HRESULT>(0x8000000eu);
constexpr HRESULT kInsufficient = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
constexpr HRESULT kCorrupt = HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT);
constexpr uint32_t kManual = 0, kWork = 0;
constexpr size_t kMiB16 = 16u * 1024u * 1024u;
constexpr const char* kScid = "00000000-0000-0000-0000-000000000000";
GUID synthetic(uint32_t data1) {
return {data1, 0x5853, 0x4000, {0x80, 0, 0, 0, 0, 0, 0, 0x01}};
}
// Slot numbers from the synthetic_keys.h contract, written out independently.
enum : int {
kQueryInterface = 0, kAddRef = 1, kRelease = 2,
kInitAsync = 3, kInitResult = 4, kCloseProvider = 5, kCreateContainer = 6, kCloseContainer = 7,
kCreateUpdate = 8, kCloseUpdate = 9, kSubmitBlobWrite = 10, kSubmitUpdateAsync = 11,
kSubmitUpdateResult = 12, kReadAsync = 13, kReadResult = 14, kEnumerate = 15,
};
enum : int { kGetId = 3, kGetKind = 4, kMount = 5, kGetMountPathSize = 6, kGetMountPath = 7, kCloseMount = 8 };
template <typename Fn>
Fn slot(void* object, int index) {
void** vtbl = *static_cast<void***>(object);
Fn fn;
std::memcpy(&fn, &vtbl[index], sizeof(fn));
return fn;
}
using QiFn = HRESULT(WINAPI*)(void*, const GUID*, void**);
using RefFn = ULONG(WINAPI*)(void*);
using InitAsyncFn = HRESULT(WINAPI*)(void*, void*, const char*, bool, Async*);
using InitResultFn = HRESULT(WINAPI*)(void*, Async*, void**);
using CloseFn = void(WINAPI*)(void*, void*);
using CreateContainerFn = HRESULT(WINAPI*)(void*, void*, const char*, void**);
using CreateUpdateFn = HRESULT(WINAPI*)(void*, void*, const char*, void**);
using BlobWriteFn = HRESULT(WINAPI*)(void*, void*, const char*, const uint8_t*, size_t);
using SubmitAsyncFn = HRESULT(WINAPI*)(void*, void*, Async*);
using AsyncResultFn = HRESULT(WINAPI*)(void*, Async*);
using ReadAsyncFn = HRESULT(WINAPI*)(void*, void*, const char**, uint32_t, Async*);
using ReadResultFn = HRESULT(WINAPI*)(void*, Async*, size_t, Blob*, uint32_t*);
using InfoCallback = bool(CALLBACK*)(const ContainerInfo*, void*);
using EnumerateFn = HRESULT(WINAPI*)(void*, void*, void*, InfoCallback);
using GetIdFn = HRESULT(WINAPI*)(void*, size_t, char*);
using GetKindFn = HRESULT(WINAPI*)(void*, const char*, uint32_t*);
using MountFn = HRESULT(WINAPI*)(void*, const char*, void**);
using PathSizeFn = HRESULT(WINAPI*)(void*, void*, size_t*);
using PathFn = HRESULT(WINAPI*)(void*, void*, size_t, char*);
using Blobs = std::vector<std::pair<std::string, std::string>>;
void* query(uint32_t clsid, uint32_t iid) {
const GUID c = synthetic(clsid), i = synthetic(iid);
void* api = nullptr;
CHECK(QueryApiImpl(&c, &i, &api) == S_OK && api);
return api;
}
void* add_user(void* queue) {
Async async{queue, nullptr, nullptr, {}};
void* user = nullptr;
CHECK(XUserAddAsync(0, &async) == S_OK);
if (queue) CHECK(XTaskQueueDispatch(queue, kWork, 0));
else CHECK(XAsyncGetStatus(&async, true) == S_OK);
CHECK(XUserAddResult(&async, &user) == S_OK && user);
return user;
}
// queue null: the process task queue (thread pool); otherwise a manual queue run inline.
struct Saves {
void* api;
void* queue;
void wait(Async& async) const {
if (queue) CHECK(XTaskQueueDispatch(queue, kWork, 0));
else XAsyncGetStatus(&async, true);
}
void* provider(void* user, const char* scid = kScid) const {
Async async{queue, nullptr, nullptr, {}};
CHECK(slot<InitAsyncFn>(api, kInitAsync)(api, user, scid, false, &async) == S_OK);
if (queue) CHECK(XAsyncGetStatus(&async, false) == E_PENDING);
wait(async);
size_t size = 0;
CHECK(XAsyncGetResultSize(&async, &size) == S_OK && size == sizeof(void*));
void* provider = nullptr;
CHECK(slot<InitResultFn>(api, kInitResult)(api, &async, &provider) == S_OK && provider);
void* again = nullptr;
CHECK(slot<InitResultFn>(api, kInitResult)(api, &async, &again) == kIllegalCall && !again);
return provider;
}
void* container(void* provider, const char* name) const {
void* handle = nullptr;
CHECK(slot<CreateContainerFn>(api, kCreateContainer)(api, provider, name, &handle) == S_OK && handle);
return handle;
}
void* update(void* container, const char* display_name) const {
void* handle = nullptr;
CHECK(slot<CreateUpdateFn>(api, kCreateUpdate)(api, container, display_name, &handle) == S_OK && handle);
return handle;
}
HRESULT write(void* update, const char* blob, const void* data, size_t size) const {
return slot<BlobWriteFn>(api, kSubmitBlobWrite)(api, update, blob, static_cast<const uint8_t*>(data), size);
}
HRESULT submit_status(void* update) const {
Async async{queue, nullptr, nullptr, {}};
const auto hr = slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &async);
if (FAILED(hr)) return hr;
wait(async);
const auto status = XAsyncGetStatus(&async, false);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &async) == status);
return status;
}
void submit(void* update) const {
const auto status = submit_status(update);
if (status != S_OK) std::fprintf(stderr, "submit status 0x%08lx\n", static_cast<unsigned long>(status));
CHECK(status == S_OK);
}
// One update writing one blob, submitted and closed.
void put(void* container, const char* blob, const std::string& data) const {
void* staged = update(container, nullptr);
CHECK(write(staged, blob, data.data(), data.size()) == S_OK);
submit(staged);
close(kCloseUpdate, staged);
}
void close(int which, void* handle) const { slot<CloseFn>(api, which)(api, handle); }
// Reads blobs (all when names is empty) and returns them as name -> bytes.
Blobs read(void* container, std::vector<const char*> names) const {
Async async{queue, nullptr, nullptr, {}};
CHECK(slot<ReadAsyncFn>(api, kReadAsync)(api, container, names.empty() ? nullptr : names.data(),
static_cast<uint32_t>(names.size()), &async) == S_OK);
wait(async);
size_t size = 0;
CHECK(XAsyncGetResultSize(&async, &size) == S_OK);
std::vector<unsigned char> buffer(size + 16, 0xCD);
auto* blobs = reinterpret_cast<Blob*>(buffer.data());
uint32_t count = 7;
const auto read_result = slot<ReadResultFn>(api, kReadResult);
if (size) CHECK(read_result(api, &async, size - 1, blobs, &count) == kBufferTooSmall && count == 0);
CHECK(read_result(api, &async, size, size ? blobs : nullptr, &count) == S_OK);
uint32_t consumed = 7;
CHECK(read_result(api, &async, size, blobs, &consumed) == kIllegalCall && consumed == 0);
for (size_t i = size; i < buffer.size(); ++i) CHECK(buffer[i] == 0xCD);
Blobs out;
size_t expected = count * sizeof(Blob);
const auto* base = reinterpret_cast<const unsigned char*>(buffer.data());
for (uint32_t i = 0; i < count; ++i) {
CHECK(reinterpret_cast<const unsigned char*>(blobs[i].name) >= base &&
reinterpret_cast<const unsigned char*>(blobs[i].name) < base + size);
CHECK(blobs[i].size == 0 || (blobs[i].data >= base && blobs[i].data + blobs[i].size <= base + size));
out.emplace_back(blobs[i].name, std::string(reinterpret_cast<const char*>(blobs[i].data), blobs[i].size));
expected += std::strlen(blobs[i].name) + 1 + blobs[i].size;
}
CHECK(expected == size);
return out;
}
HRESULT read_status(void* container, std::vector<const char*> names) const {
Async async{queue, nullptr, nullptr, {}};
const auto hr = slot<ReadAsyncFn>(api, kReadAsync)(api, container, names.empty() ? nullptr : names.data(),
static_cast<uint32_t>(names.size()), &async);
if (FAILED(hr)) return hr;
wait(async);
uint32_t count = 0;
const auto status = XAsyncGetStatus(&async, false);
size_t size = 0;
if (SUCCEEDED(status)) CHECK(XAsyncGetResultSize(&async, &size) == S_OK);
std::vector<unsigned char> buffer(size);
CHECK(slot<ReadResultFn>(api, kReadResult)(api, &async, size,
size ? reinterpret_cast<Blob*>(buffer.data()) : nullptr,
&count) == status);
return status;
}
};
const std::string* find_blob(const Blobs& blobs, const char* name) {
for (const auto& [blob, bytes] : blobs) {
if (blob == name) return &bytes;
}
return nullptr;
}
struct Seen {
std::string name, display_name;
uint32_t blob_count;
uint64_t total_size;
time_t modified;
bool needs_sync;
};
struct Listing {
std::vector<Seen> seen;
size_t stop_after = SIZE_MAX;
};
bool CALLBACK collect(const ContainerInfo* info, void* context) {
auto& listing = *static_cast<Listing*>(context);
listing.seen.push_back({info->name, info->display_name, info->blob_count, info->total_size,
info->last_modified_time, info->needs_sync});
return listing.seen.size() < listing.stop_after;
}
Listing list(const Saves& saves, void* provider) {
Listing listing;
CHECK(slot<EnumerateFn>(saves.api, kEnumerate)(saves.api, provider, &listing, collect) == S_OK);
return listing;
}
// --- The documented storage layout, re-derived here ---
// FNV-1a (64-bit) over each byte widened to a UTF-16 code unit, printed as 16 hex digits.
std::string hex_id(const std::string& text) {
uint64_t hash = 14695981039346656037ULL;
for (unsigned char c : text) {
hash ^= c;
hash *= 1099511628211ULL;
}
char out[17];
std::snprintf(out, sizeof(out), "%016llx", static_cast<unsigned long long>(hash));
return out;
}
std::string saves_directory(const char* scid) {
char path[MAX_PATH * 4]{};
CHECK(XPersistentLocalStorageGetPath(sizeof(path), path, nullptr) == S_OK);
return std::string(path) + "\\saves\\" + hex_id(scid);
}
std::string container_path(const std::string& dir, const std::string& name) {
return dir + "\\" + hex_id(name) + ".bxgs";
}
void put32(std::string& out, uint32_t value) {
for (int i = 0; i < 4; ++i) out.push_back(static_cast<char>(value >> (8 * i)));
}
void put_str(std::string& out, const std::string& text) {
put32(out, static_cast<uint32_t>(text.size()));
out += text;
}
// "BXGS", version 1, name, display name, i64 time, blob count, then name / size / bytes.
std::string container_bytes(const std::string& name, const std::vector<std::pair<std::string, std::string>>& blobs) {
std::string out = "BXGS";
put32(out, 1);
put_str(out, name);
put_str(out, "crafted");
put32(out, 1700000000);
put32(out, 0);
put32(out, static_cast<uint32_t>(blobs.size()));
for (const auto& [blob, data] : blobs) {
put_str(out, blob);
put_str(out, data);
}
return out;
}
void write_file(const std::string& path, const std::string& bytes) {
const HANDLE file = CreateFileA(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
nullptr);
CHECK(file != INVALID_HANDLE_VALUE);
DWORD wrote = 0;
CHECK(WriteFile(file, bytes.data(), static_cast<DWORD>(bytes.size()), &wrote, nullptr) && wrote == bytes.size());
CHECK(CloseHandle(file));
}
// Files matching pattern in dir; optionally deletes them.
size_t files(const std::string& dir, const char* pattern, bool remove) {
WIN32_FIND_DATAA found;
const HANDLE search = FindFirstFileA((dir + "\\" + pattern).c_str(), &found);
if (search == INVALID_HANDLE_VALUE) return 0;
size_t count = 0;
do {
if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
++count;
if (remove) CHECK(DeleteFileA((dir + "\\" + found.cFileName).c_str()));
} while (FindNextFileA(search, &found));
FindClose(search);
return count;
}
void check_com(void* object, const GUID& own, const GUID& other) {
const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
void* out = nullptr;
CHECK(slot<QiFn>(object, kQueryInterface)(object, &iunknown, &out) == S_OK && out == object);
CHECK(slot<QiFn>(object, kQueryInterface)(object, &own, &out) == S_OK && out == object);
CHECK(slot<QiFn>(object, kQueryInterface)(object, &other, &out) == E_NOINTERFACE && !out);
CHECK(slot<QiFn>(object, kQueryInterface)(object, &own, nullptr) == E_POINTER);
CHECK(slot<RefFn>(object, kAddRef)(object) >= 1 && slot<RefFn>(object, kRelease)(object) >= 1);
}
// Committed private memory, summed over the address space (Wine reports PrivateUsage as 0).
uint64_t private_bytes() {
uint64_t total = 0;
MEMORY_BASIC_INFORMATION region{};
for (auto* at = static_cast<const char*>(nullptr);
VirtualQuery(at, &region, sizeof(region)) == sizeof(region);
at = static_cast<const char*>(region.BaseAddress) + region.RegionSize) {
if (region.State == MEM_COMMIT && region.Type == MEM_PRIVATE) total += region.RegionSize;
if (region.RegionSize == 0) break;
}
return total;
}
std::string utf8(const wchar_t* text) {
const int bytes = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
CHECK(bytes > 0);
std::string out(static_cast<size_t>(bytes), '\0');
WideCharToMultiByte(CP_UTF8, 0, text, -1, out.data(), bytes, nullptr, nullptr);
out.pop_back();
return out;
}
// --- Concurrency ---
constexpr char kShared[] = "shared/race";
struct ThreadJob {
void* api;
void* container;
int id;
int count;
};
DWORD WINAPI thread_writer(void* context) {
const auto& job = *static_cast<ThreadJob*>(context);
const Saves saves{job.api, nullptr};
for (int k = 0; k < job.count; ++k) {
char blob[32];
std::snprintf(blob, sizeof(blob), "t%d_%d", job.id, k);
saves.put(job.container, blob, blob);
}
return 0;
}
// Cross-process payload: the blob name, then padding to 64 KiB so each rewrite takes a while.
std::string payload(const char* blob) {
std::string data(blob);
data.resize(64 * 1024, '.');
return data;
}
// Child process: submits count blobs "w<id>_<k>" to kShared once the parent's event is set.
int writer_main(int id, int count, const wchar_t* event_name) {
CHECK(XGameRuntimeInitialize() == S_OK);
const Saves saves{query(0xB7581601, 0xB7581602), nullptr};
void* user = add_user(nullptr);
void* provider = saves.provider(user);
void* container = saves.container(provider, kShared);
const HANDLE go = OpenEventW(SYNCHRONIZE, FALSE, event_name);
CHECK(go && WaitForSingleObject(go, 30000) == WAIT_OBJECT_0);
CloseHandle(go);
for (int k = 0; k < count; ++k) {
char blob[32];
std::snprintf(blob, sizeof(blob), "w%d_%d", id, k);
saves.put(container, blob, payload(blob));
}
XGameRuntimeUninitialize();
return 0;
}
void check_blobs(const Blobs& blobs, char prefix, int writers, int count) {
for (int id = 0; id < writers; ++id) {
for (int k = 0; k < count; ++k) {
char blob[32];
std::snprintf(blob, sizeof(blob), "%c%d_%d", prefix, id, k);
const auto* data = find_blob(blobs, blob);
CHECK(data && *data == (prefix == 'w' ? payload(blob) : std::string(blob)));
}
}
}
} // namespace
int main() {
int argc = 0;
wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argc == 5 && std::wcscmp(argv[1], L"--writer") == 0) {
return writer_main(std::wcstol(argv[2], nullptr, 10), std::wcstol(argv[3], nullptr, 10), argv[4]);
}
const time_t started = std::time(nullptr);
CHECK(XGameRuntimeInitialize() == S_OK);
// --- QueryApiImpl reaches both families as COM objects ---
const GUID save_clsid = synthetic(0xB7581601), save_iid = synthetic(0xB7581602);
const GUID package_clsid = synthetic(0xB7581701), package_iid = synthetic(0xB7581702);
const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
void* api = query(0xB7581601, 0xB7581602);
void* package = query(0xB7581701, 0xB7581702);
CHECK(package != api);
void* wrong = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(QueryApiImpl(&save_clsid, &package_iid, &wrong) == E_NOINTERFACE && !wrong);
void* via_unknown = nullptr;
CHECK(QueryApiImpl(&save_clsid, &iunknown, &via_unknown) == S_OK && via_unknown == api);
CHECK(QueryApiImpl(&package_clsid, &iunknown, &via_unknown) == S_OK && via_unknown == package);
check_com(api, save_iid, package_iid);
check_com(package, package_iid, save_iid);
void* queue = nullptr;
CHECK(XTaskQueueCreate(kManual, kManual, &queue) == S_OK && queue);
const Saves saves{api, queue};
void* user = add_user(queue);
const std::string dir = saves_directory(kScid);
const std::string other_dir = saves_directory("scid-b");
files(dir, "*", true);
files(other_dir, "*", true);
// --- Provider ---
Async async{queue, nullptr, nullptr, {}};
const auto init_async = slot<InitAsyncFn>(api, kInitAsync);
CHECK(init_async(api, nullptr, kScid, false, &async) == kInvalidHandle);
CHECK(init_async(api, user, nullptr, false, &async) == E_INVALIDARG);
CHECK(init_async(api, user, kScid, false, nullptr) == E_POINTER);
void* provider = saves.provider(user);
// --- Container names (XGameSaveCreateContainer rules) ---
const auto create_container = slot<CreateContainerFn>(api, kCreateContainer);
const std::string too_long(257, 'a');
for (const char* bad : {"", "a..b", "trail.", "has space", "dir.x/file", "dir/", "semi;colon", too_long.c_str()}) {
void* handle = nullptr;
CHECK(create_container(api, provider, bad, &handle) == kInvalidContainerName && !handle);
}
void* handle = nullptr;
CHECK(create_container(api, provider, nullptr, &handle) == kInvalidContainerName);
CHECK(create_container(api, nullptr, "slot", &handle) == kInvalidHandle);
const std::string longest(256, 'a');
for (const char* good : {"slot_1", "profiles/main", "/a", "a-b.c_d", longest.c_str()}) {
saves.close(kCloseContainer, saves.container(provider, good));
}
// --- A container that was never submitted ---
void* main_container = saves.container(provider, "profiles/main");
CHECK(saves.read(main_container, {}).empty());
CHECK(saves.read_status(main_container, {"progress"}) == kBlobNotFound);
CHECK(saves.read_status(main_container, {"progress", "progress"}) == E_INVALIDARG);
{
Async read{queue, nullptr, nullptr, {}};
CHECK(slot<ReadAsyncFn>(api, kReadAsync)(api, main_container, nullptr, 1, &read) == E_INVALIDARG);
}
CHECK(files(dir, "*.bxgs", false) == 0);
// --- Write, then read back ---
std::string progress(300, '\0');
for (size_t i = 0; i < progress.size(); ++i) progress[i] = static_cast<char>(i * 7 + 3);
const std::string settings = "volume=7";
void* update = saves.update(main_container, "Main profile");
CHECK(saves.write(update, "progress", progress.data(), progress.size()) == S_OK);
CHECK(saves.write(update, "progress", progress.data(), progress.size()) == E_INVALIDARG);
CHECK(saves.write(update, "", "x", 1) == E_INVALIDARG);
CHECK(saves.write(update, std::string(257, 'n').c_str(), "x", 1) == E_INVALIDARG); // 256-byte name limit
CHECK(saves.write(update, "settings", settings.data(), settings.size()) == S_OK);
{
Async submit{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &submit) == S_OK);
Async twice{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &twice) == kIllegalCall); // pending
CHECK(saves.write(update, "late", "x", 1) == kIllegalCall);
saves.wait(submit);
size_t size = 1;
CHECK(XAsyncGetResultSize(&submit, &size) == S_OK && size == 0);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &submit) == S_OK);
}
saves.close(kCloseUpdate, update);
CHECK(saves.write(update, "closed", "x", 1) == kInvalidHandle); // CloseUpdate closes it
auto blobs = saves.read(main_container, {});
CHECK(blobs.size() == 2);
CHECK(find_blob(blobs, "progress") && *find_blob(blobs, "progress") == progress);
CHECK(find_blob(blobs, "settings") && *find_blob(blobs, "settings") == settings);
blobs = saves.read(main_container, {"settings"});
CHECK(blobs.size() == 1 && blobs[0].first == "settings" && blobs[0].second == settings);
// The 16 MiB limit counts blob names: "big" (3 bytes) plus 16 MiB - 3 bytes fills it exactly.
{
std::vector<char> big(kMiB16);
void* full = saves.update(main_container, nullptr);
CHECK(saves.write(full, "big", big.data(), kMiB16 - 3 + 1) == kUpdateTooBig);
CHECK(saves.write(full, "big", big.data(), kMiB16 - 3) == S_OK);
CHECK(saves.write(full, "x", nullptr, 0) == kUpdateTooBig);
saves.close(kCloseUpdate, full);
}
// --- A second container, then enumeration ---
void* slot_container = saves.container(provider, "slot_1");
saves.put(slot_container, "a", "A");
saves.close(kCloseContainer, slot_container);
CHECK(files(dir, "*.bxgs", false) == 2);
const auto enumerate = slot<EnumerateFn>(api, kEnumerate);
Listing listing = list(saves, provider);
CHECK(listing.seen.size() == 2);
const time_t now = std::time(nullptr);
for (const auto& seen : listing.seen) {
CHECK(!seen.needs_sync && seen.modified >= started - 5 && seen.modified <= now + 5);
if (seen.name == "profiles/main") {
CHECK(seen.display_name == "Main profile" && seen.blob_count == 2 &&
seen.total_size == progress.size() + settings.size());
} else {
CHECK(seen.name == "slot_1" && seen.display_name.empty() && seen.blob_count == 1 && seen.total_size == 1);
}
}
CHECK(listing.seen[0].name != listing.seen[1].name);
Listing first_only;
first_only.stop_after = 1;
CHECK(enumerate(api, provider, &first_only, collect) == S_OK && first_only.seen.size() == 1);
CHECK(enumerate(api, provider, nullptr, nullptr) == E_INVALIDARG);
// --- Saves are separated by SCID ---
{
void* other = saves.provider(user, "scid-b");
CHECK(list(saves, other).seen.empty());
void* same_name = saves.container(other, "profiles/main");
CHECK(saves.read(same_name, {}).empty());
saves.put(same_name, "progress", "other scid");
CHECK(files(other_dir, "*.bxgs", false) == 1);
void* staged = saves.update(same_name, nullptr);
{
std::vector<char> big(kMiB16 - 16);
CHECK(saves.write(staged, "staged", big.data(), big.size()) == S_OK);
}
const uint64_t open_bytes = private_bytes();
saves.close(kCloseProvider, other);
// Closing a provider closes its containers and their updates, and frees what they staged.
CHECK(private_bytes() + 8 * (1u << 20) < open_bytes);
CHECK(saves.read_status(same_name, {}) == kInvalidHandle);
CHECK(saves.write(staged, "x", "x", 1) == kInvalidHandle);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress);
}
// --- Files that are damaged, foreign or unreadable ---
{
const auto crafted = [&](const char* name, std::string bytes) {
write_file(container_path(dir, name), bytes);
void* container = saves.container(provider, name);
const auto status = saves.read_status(container, {});
saves.close(kCloseContainer, container);
return status;
};
CHECK(crafted("craft_ok", container_bytes("craft_ok", {{"a", "1"}})) == S_OK); // the format is as documented
CHECK(crafted("craft_tail", container_bytes("craft_tail", {{"a", "1"}}) + "!") == kCorrupt);
CHECK(crafted("craft_dup", container_bytes("craft_dup", {{"a", "1"}, {"a", "2"}})) == kCorrupt);
std::string truncated = container_bytes("craft_cut", {{"a", "12345"}});
truncated.pop_back();
CHECK(crafted("craft_cut", truncated) == kCorrupt);
CHECK(crafted("craft_nul", container_bytes(std::string("craft_nul\0x", 11), {})) == kCorrupt);
CHECK(crafted("craft_blobnul", container_bytes("craft_blobnul", {{std::string("a\0b", 3), "1"}})) == kCorrupt);
CHECK(crafted("craft_badname", container_bytes("bad name", {})) == kCorrupt);
// Enumeration lists the two real containers and the valid crafted one, skipping the rest.
CHECK(list(saves, provider).seen.size() == 3);
// A file another process holds exclusively is skipped, not fatal to enumeration.
const HANDLE locked = CreateFileA(container_path(dir, "craft_ok").c_str(), GENERIC_READ, 0, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(locked != INVALID_HANDLE_VALUE);
CHECK(list(saves, provider).seen.size() == 2);
CloseHandle(locked);
CHECK(files(dir, "*.bxgs", false) == 9);
for (const char* name : {"craft_ok", "craft_tail", "craft_dup", "craft_cut", "craft_nul", "craft_blobnul",
"craft_badname"}) {
CHECK(DeleteFileA(container_path(dir, name).c_str()));
}
}
// --- A failed replace keeps the old save; a successful one replaces the file ---
{
const auto file_id = [&] {
const HANDLE file = CreateFileA(container_path(dir, "profiles/main").c_str(), 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(file != INVALID_HANDLE_VALUE);
BY_HANDLE_FILE_INFORMATION info{};
CHECK(GetFileInformationByHandle(file, &info));
CloseHandle(file);
return (static_cast<uint64_t>(info.nFileIndexHigh) << 32) | info.nFileIndexLow;
};
const uint64_t original = file_id();
// A reader that allows writes but not deletion blocks the rename, not an in-place write.
const HANDLE reader = CreateFileA(container_path(dir, "profiles/main").c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(reader != INVALID_HANDLE_VALUE);
void* blocked = saves.update(main_container, nullptr);
CHECK(saves.write(blocked, "progress", "BLOCKED", 7) == S_OK);
CHECK(FAILED(saves.submit_status(blocked)));
CloseHandle(reader);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress);
CHECK(files(dir, "*.tmp", false) == 0);
// The failed update was not consumed: submitting it again now succeeds.
CHECK(file_id() == original);
saves.submit(blocked);
saves.close(kCloseUpdate, blocked);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == "BLOCKED");
CHECK(file_id() != original); // written to a new file and renamed over, not in place
}
// --- Persistence across provider close and reopen ---
saves.close(kCloseContainer, main_container);
saves.close(kCloseProvider, provider);
CHECK(create_container(api, provider, "slot_1", &handle) == kInvalidHandle && !handle);
provider = saves.provider(user);
main_container = saves.container(provider, "profiles/main");
blobs = saves.read(main_container, {"settings", "progress"});
CHECK(blobs.size() == 2 && *find_blob(blobs, "progress") == "BLOCKED" && *find_blob(blobs, "settings") == settings);
// Overwrite one blob through the process task queue; the other blob and the display name stay.
const std::string progress2 = "lvl=9";
{
const Saves pooled{api, nullptr};
pooled.put(main_container, "progress", progress2);
}
blobs = saves.read(main_container, {});
CHECK(blobs.size() == 2 && *find_blob(blobs, "progress") == progress2 && *find_blob(blobs, "settings") == settings);
for (const auto& seen : list(saves, provider).seen) {
if (seen.name == "profiles/main") CHECK(seen.display_name == "Main profile");
}
// A canceled submit writes nothing, and the update can then be submitted again.
update = saves.update(main_container, nullptr);
CHECK(saves.write(update, "progress", "X", 1) == S_OK);
{
Async canceled{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &canceled) == S_OK);
XAsyncCancel(&canceled);
saves.wait(canceled);
CHECK(XAsyncGetStatus(&canceled, false) == E_ABORT);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &canceled) == E_ABORT);
}
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress2);
saves.submit(update);
saves.close(kCloseUpdate, update);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == "X");
// A closed container handle is rejected, and so are its updates.
void* orphan = saves.update(main_container, nullptr);
saves.close(kCloseContainer, main_container);
CHECK(saves.read_status(main_container, {}) == kInvalidHandle);
CHECK(saves.write(orphan, "x", "x", 1) == kInvalidHandle);
update = nullptr;
CHECK(slot<CreateUpdateFn>(api, kCreateUpdate)(api, main_container, "x", &update) == kInvalidHandle && !update);
// --- Concurrent submits to one container: threads, then processes ---
void* shared = saves.container(provider, kShared);
{
constexpr int kThreads = 8, kEach = 8;
ThreadJob jobs[kThreads];
HANDLE threads[kThreads];
for (int i = 0; i < kThreads; ++i) {
jobs[i] = {api, shared, i, kEach};
threads[i] = CreateThread(nullptr, 0, thread_writer, &jobs[i], 0, nullptr);
CHECK(threads[i]);
}
CHECK(WaitForMultipleObjects(kThreads, threads, TRUE, 60000) == WAIT_OBJECT_0);
for (HANDLE thread : threads) CloseHandle(thread);
blobs = saves.read(shared, {});
CHECK(blobs.size() == kThreads * kEach);
check_blobs(blobs, 't', kThreads, kEach);
}
{
constexpr int kWriters = 4, kEach = 40;
wchar_t event_name[64];
std::swprintf(event_name, 64, L"Local\\bx_saves_go_%lu", GetCurrentProcessId());
const HANDLE go = CreateEventW(nullptr, TRUE, FALSE, event_name);
CHECK(go);
wchar_t exe[MAX_PATH];
CHECK(GetModuleFileNameW(nullptr, exe, MAX_PATH) > 0);
PROCESS_INFORMATION children[kWriters];
for (int id = 0; id < kWriters; ++id) {
wchar_t command[MAX_PATH + 128];
std::swprintf(command, MAX_PATH + 128, L"\"%ls\" --writer %d %d %ls", exe, id, kEach, event_name);
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
CHECK(CreateProcessW(exe, command, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &children[id]));
}
CHECK(SetEvent(go));
for (auto& child : children) {
DWORD code = 99;
CHECK(WaitForSingleObject(child.hProcess, 120000) == WAIT_OBJECT_0);
CHECK(GetExitCodeProcess(child.hProcess, &code) && code == 0);
CloseHandle(child.hProcess);
CloseHandle(child.hThread);
}
CloseHandle(go);
blobs = saves.read(shared, {});
CHECK(blobs.size() == 8 * 8 + kWriters * kEach);
check_blobs(blobs, 'w', kWriters, kEach);
}
saves.close(kCloseContainer, shared);
// --- XPackage ---
char id[64]{};
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(id), id) == S_OK);
CHECK(std::strncmp(id, "BXPKG", 5) == 0 && std::strlen(id) == 21);
for (const char* c = id + 5; *c; ++c) CHECK((*c >= '0' && *c <= '9') || (*c >= 'a' && *c <= 'f'));
char again[64]{};
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(again), again) == S_OK && std::strcmp(id, again) == 0);
CHECK(slot<GetIdFn>(package, kGetId)(package, std::strlen(id), again) == kInsufficient);
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(again), nullptr) == E_POINTER);
uint32_t kind = 99;
CHECK(slot<GetKindFn>(package, kGetKind)(package, id, &kind) == S_OK && kind == 0); // XPackageKind::Game
CHECK(slot<GetKindFn>(package, kGetKind)(package, "BXPKG0000000000000000", &kind) == kNotFound);
// The mount path is the executable's directory in UTF-8 (W API, so non-ASCII paths work).
wchar_t exe_w[MAX_PATH]{};
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
*std::wcsrchr(exe_w, L'\\') = L'\0';
const std::string exe_dir = utf8(exe_w);
void* mount = nullptr;
CHECK(slot<MountFn>(package, kMount)(package, "BXPKG0000000000000000", &mount) == kNotFound && !mount);
CHECK(slot<MountFn>(package, kMount)(package, id, &mount) == S_OK && mount);
size_t path_size = 0;
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == S_OK);
CHECK(path_size == exe_dir.size() + 1);
std::vector<char> path(path_size);
CHECK(slot<PathFn>(package, kGetMountPath)(package, mount, path_size - 1, path.data()) == kInsufficient);
CHECK(slot<PathFn>(package, kGetMountPath)(package, mount, path_size, path.data()) == S_OK);
CHECK(exe_dir == path.data());
// Handle types do not overlap: a mount handle is not a provider handle.
saves.close(kCloseProvider, mount);
CHECK(list(saves, provider).seen.size() == 3);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == S_OK);
slot<CloseFn>(package, kCloseMount)(package, mount);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == kInvalidHandle);
// --- Uninitialize then reinitialize: old handles stay dead, queued work does not run ---
{
void* old_container = saves.container(provider, "profiles/main");
void* old_update = saves.update(old_container, nullptr);
CHECK(saves.write(old_update, "progress", "STALE", 5) == S_OK);
void* old_mount = nullptr;
CHECK(slot<MountFn>(package, kMount)(package, id, &old_mount) == S_OK);
// Results and staged data held across the uninitialize must be released by it.
std::vector<char> big(kMiB16 - 8);
void* heavy = saves.update(old_container, nullptr);
CHECK(saves.write(heavy, "heavy", big.data(), big.size()) == S_OK);
std::vector<Async> unread(6, Async{queue, nullptr, nullptr, {}});
void* big_container = saves.container(provider, "big");
{
void* filler = saves.update(big_container, nullptr);
CHECK(saves.write(filler, "data", big.data(), big.size()) == S_OK);
saves.submit(filler);
saves.close(kCloseUpdate, filler);
}
big = {};
const uint64_t before = private_bytes();
for (auto& read : unread) {
CHECK(slot<ReadAsyncFn>(api, kReadAsync)(api, big_container, nullptr, 0, &read) == S_OK);
CHECK(XTaskQueueDispatch(queue, kWork, 0));
}
const uint64_t held = private_bytes();
// Queued last on the manual queue, so the dispatches above do not run it.
Async pending{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, old_update, &pending) == S_OK);
XGameRuntimeUninitialize();
CHECK(XGameRuntimeInitialize() == S_OK);
const uint64_t after = private_bytes();
std::printf("memory: before reads %llu MiB, with 6 unread results %llu MiB, after uninitialize %llu MiB\n",
static_cast<unsigned long long>(before >> 20), static_cast<unsigned long long>(held >> 20),
static_cast<unsigned long long>(after >> 20));
// The measurement sees the six results (about 16 MiB each)...
CHECK(held > before + 80 * (1u << 20));
// ...and uninitialize released them and the open 16 MiB update counted in "before".
CHECK(after + 8 * (1u << 20) < before);
// The submit queued before uninitialize must not write now.
CHECK(XTaskQueueDispatch(queue, kWork, 0));
CHECK(XAsyncGetStatus(&pending, false) == kNotInitialized);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &pending) == kNotInitialized);
CHECK(slot<CreateContainerFn>(api, kCreateContainer)(api, provider, "slot_1", &handle) == kInvalidHandle);
CHECK(saves.read_status(old_container, {}) == kInvalidHandle);
CHECK(saves.write(old_update, "x", "x", 1) == kInvalidHandle);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, old_mount, &path_size) == kInvalidHandle);
void* fresh_user = add_user(queue);
void* fresh = saves.provider(fresh_user);
void* check = saves.container(fresh, "profiles/main");
CHECK(*find_blob(saves.read(check, {"progress"}), "progress") == "X");
XUserCloseHandle(fresh_user);
}
// --- After the last uninitialize, handles are stale ---
XUserCloseHandle(user);
XTaskQueueCloseHandle(queue);
XGameRuntimeUninitialize();
CHECK(create_container(api, provider, "slot_1", &handle) == kNotInitialized);
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(id), id) == kNotInitialized);
std::printf("PASS: test_xgameruntime_saves (round trip, SCID isolation, damaged files, failed replace, "
"64 threaded + 160 cross-process submits, uninitialize; package %s)\n", id);
return 0;
}
@@ -0,0 +1,3 @@
add_executable(test_xmem_physical main.cpp)
target_include_directories(test_xmem_physical PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_xmem_physical PRIVATE xmem kernel32)
@@ -0,0 +1,148 @@
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include "bx_xmem_internal.h"
extern "C" {
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID, SIZE_T, uint64_t, PULONG_PTR);
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
}
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::fprintf(stderr, "xmem physical:%d: %s (Win32 error %lu)\n", \
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
return false; \
} \
} while (false)
bool check_aliases(SIZE_T page_size, uint64_t flags) {
bx_xmem_stats_t stats{};
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
CHECK(stats.allocated_physical_bytes == 0);
SIZE_T count = 2;
ULONG_PTR pages[2]{};
// Invalid flags must be rejected cleanly before touching stats or tags.
CHECK(!XMemAllocatePhysicalPages(&count, pages, 0x12345));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
CHECK(XMemAllocatePhysicalPages(&count, pages, flags));
CHECK(count == 2 && pages[0] && pages[1] && pages[0] != pages[1]);
// Working-set statistics and internal stats must both reflect physical pages.
bx_xmem_get_internal_stats(&stats);
CHECK(stats.allocated_physical_bytes == count * page_size);
CHECK(stats.peak_committed_bytes >= count * page_size);
bx_xmem_stats_t ws_stats{};
CHECK(XMemGetWorkingSetStatistics(&ws_stats, sizeof(ws_stats)));
CHECK(ws_stats.allocated_physical_bytes == count * page_size);
// Shared title budget cap: existing physical pages must block both full-cap
// physical and full-cap heap allocations without allocating gigabytes.
SIZE_T cap_pages = static_cast<SIZE_T>(stats.title_limit_bytes / page_size);
CHECK(!XMemAllocatePhysicalPages(&cap_pages, pages, flags));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
CHECK(!XMemAllocDefault(static_cast<SIZE_T>(stats.title_limit_bytes), 0));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.allocated_physical_bytes == count * page_size);
CHECK(!XMemMapPhysicalPages(nullptr, count, 0x12345, pages));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
auto* linear = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, count, flags, pages));
CHECK(linear && reinterpret_cast<uintptr_t>(linear) % page_size == 0);
ULONG_PTR reversed[] = {pages[1], pages[0]};
auto* scatter = static_cast<BYTE*>(
XMemMapPhysicalPagesScatter(nullptr, count, flags, reversed));
CHECK(scatter && scatter != linear && reinterpret_cast<uintptr_t>(scatter) % page_size == 0);
linear[7] = 0x41;
linear[page_size + 7] = 0x73;
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
scatter[page_size + 30] = 0xf2;
CHECK(linear[30] == 0xf2);
// Duplicate tags are valid when mapping (intra-span ring-buffer/tile aliasing).
ULONG_PTR dup_map[] = {pages[0], pages[0]};
auto* dup_view = static_cast<BYTE*>(
XMemMapPhysicalPagesScatter(nullptr, count, flags, dup_map));
CHECK(dup_view && reinterpret_cast<uintptr_t>(dup_view) % page_size == 0);
dup_view[13] = 0x9b;
CHECK(dup_view[page_size + 13] == 0x9b && linear[13] == 0x9b);
bx_xmem_region_info_t dup0{};
bx_xmem_region_info_t dup1{};
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view + page_size), &dup1));
CHECK(dup0.physical_tag == pages[0] && dup1.physical_tag == pages[0]);
CHECK(XMemMapPhysicalPagesScatter(dup_view, count, flags, nullptr) == dup_view);
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
bx_xmem_region_info_t first{};
bx_xmem_region_info_t alias{};
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear + 7), &first));
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter + page_size + 7), &alias));
CHECK(first.base_va == reinterpret_cast<uintptr_t>(linear));
CHECK(alias.base_va == reinterpret_cast<uintptr_t>(scatter + page_size));
CHECK(alias.physical_tag == first.physical_tag && first.physical_tag == pages[0]);
CHECK(first.size_bytes == page_size && alias.page_size_bytes == page_size);
CHECK(first.protect_flags == PAGE_READWRITE && first.mem_type_flags == MEM_MAPPED);
// Rejected frees (stale or duplicate tags) must fail without modifying
// page_array or disturbing live mappings.
ULONG_PTR stale[] = {pages[0], 0};
CHECK(!XMemFreePhysicalPages(&count, stale, flags));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && stale[0] == pages[0] && stale[1] == 0);
CHECK(linear[7] == 0x41);
ULONG_PTR dup_free[] = {pages[0], pages[0]};
CHECK(!XMemFreePhysicalPages(&count, dup_free, flags));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER
&& dup_free[0] == pages[0] && dup_free[1] == pages[0]);
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
CHECK(!XMemMapPhysicalPagesScatter(nullptr, count, flags, stale));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
CHECK(!XMemMapPhysicalPages(linear, count, flags, pages));
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
// Partial/over-wide unmap must fail cleanly and leave mapped pages intact.
CHECK(!XMemMapPhysicalPagesScatter(scatter, count + 1, flags, nullptr));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
// Exact unmap succeeds; repeating unmap on the now-empty span must fail.
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr) == scatter);
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
CHECK(!XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, reversed) == scatter);
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
CHECK(XMemFreePhysicalPages(&count, pages, flags));
CHECK(!pages[0] && !pages[1]);
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear), &first));
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
CHECK(!XMemMapPhysicalPages(nullptr, count, flags, reversed));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.allocated_physical_bytes == 0);
return true;
}
int main() {
if (!check_aliases(64 * 1024, 0) || !check_aliases(2 * 1024 * 1024, 2 * 1024 * 1024)) {
return 1;
}
std::puts("test_xmem_physical: passed");
}