Compare commits

...
Author SHA1 Message Date
ates 4cb858e6f5 docs: the working method is in effect; point to the ladder issue
#662 is merged, so the working method no longer says 'proposed'. It
names the pinned ladder issue (#663) and notes that the starting queue
was filed as #664-#680.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:49:50 +03:00
Ateş b36e397681 Merge pull request #638 from MacosPorters/track-f/637-console-shader-abi
[M2-F17] docs: console compute shader entry ABI observed from the Series X|S compiler
2026-11-29 11:48:27 +03:00
ates 5bc4ff5cf4 Merge remote-tracking branch 'origin/main' into fix-638
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:48:08 +03:00
Ateş 5e204bd883 Merge pull request #662 from MacosPorters/docs/game-ladder-roadmap
[Process] Stage-based roadmap and the blocker queue: what an agent does when told "work"
2026-11-29 11:47:11 +03:00
Ateş 5c2e2c9b63 Merge pull request #659 from MacosPorters/track-a/bringup-veh-diagnostics
[M2-A] runtime_veh: opt-in fault context, watches, breakpoints and sampler
2026-11-29 11:36:16 +03:00
ates 77dd9ffef3 Merge remote-tracking branch 'origin/main' into fix-659 2026-11-29 11:35:25 +03:00
Ateş abecde1c39 Merge pull request #635 from MacosPorters/track-a/634-veh-breakpoint
[M2-A16] runtime_veh: record breakpoints and assertion failures a guest crash reporter hides
2026-11-29 11:35:09 +03:00
ates e532fc56ba Merge remote-tracking branch 'origin/main' into fix-635
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:22:18 +03:00
ates 4c5cd55884 Merge remote-tracking branch 'origin/main' into docs/game-ladder-roadmap
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:11:08 +03:00
Ateş ec3dea9942 Merge pull request #661 from MacosPorters/track-f/bringup-review-process
[M2-F] docs: development cycle and review for target-build bring-up
2026-11-29 10:55:05 +03:00
ates 1fed04a80c Merge remote-tracking branch 'origin/main' into fix-661
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 10:51:45 +03:00
Ateş a9efeffc6f Merge pull request #658 from MacosPorters/track-e/bringup-xgameruntime
[M2-E] xgameruntime: offline XPackage installation monitor and enumeration
2026-11-29 10:51:22 +03:00
ates 365b411fed Merge remote-tracking branch 'origin/main' into fix-658
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 10:47:35 +03:00
Ateş 1b4b1bf7d7 Merge pull request #657 from MacosPorters/track-e/bringup-acphal
[M2-E] acphal: IAcpHal slot order and shape contexts
2026-11-29 10:47:06 +03:00
Ateş aeac1892c1 Merge pull request #656 from MacosPorters/track-c/bringup-xg-contract
[M2-C] xg_xs: the documented XG contract, replacing the clean-room interface
2026-11-29 10:46:44 +03:00
Ateş a9674bf9c7 Merge pull request #655 from MacosPorters/track-b/bringup-dstorage-queues
[M2-B] xcrdapi: zlib file requests and AutoSubmitDisabled on Xbox queues
2026-11-29 10:46:14 +03:00
ates eee9a4fcdc docs: how blockers are found once the target build runs
Working method: people play with recording on, agents replay short
routes through the input shim as ten-run regression tests, and picture
bugs are worked on from captured frames replayed offline. Lists the
signals a problem is recognised by and adds the three tools to the
starting queue.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:27:51 +03:00
ates fe28c5c2af docs: rework the proposal for an agent-driven team; stages replace milestone numbers
Collaborators work by telling a coding agent to "work", so the method
now answers what an agent does next without meetings or roles:
- AGENTS.md section 0 is rewritten as that instruction: preflight, then
  exactly one of own pull requests, review, one blocker of the current
  stage, or discovery; "work" authorizes commit, push and a pull request
  for the one item picked.
- docs/process/working-method.md: state lives in GitHub (a pinned ladder
  issue, one blocker issue per signature, claim comments, needs-human),
  the run protocol with per-session bottles and a machine-wide run lock,
  ranked sources of truth, the five-part pull request, and the starting
  queue.
- docs/roadmap.md: the ladder's rungs are named stages (Boot, Picture,
  Menus, World, Fidelity, Playable) instead of M3-M8.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:09:49 +03:00
ates e21f41ae24 docs: propose the game-ladder roadmap and the blocker-loop working method
docs/roadmap.md: M0-M2 become the foundation; M3-M8 are rungs the
project-authorized target build reaches (reliable boot, first correct
picture, front end, into the world, the world renders correctly,
playable), each judged on ten recorded runs on a 16 GB Mac, with
decision gates for the back end, reference images, memory and frame
rate, and a step-forward test for what belongs on main.

docs/process/working-method.md (proposed): the blocker loop, the run
protocol and run report, lanes beside tracks, ranked sources of truth,
one-blocker pull requests with a five-part description, the first two
weeks of work, and the AGENTS.md changes this needs. AGENTS.md itself
is not changed here.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:05:49 +03:00
ates 506defdd45 tests: AcpHal's 64 MB default APU heap in a fresh process
Review on #657: test_audio_input creates its own heap before allocating
shape contexts, so the default-heap branch never ran. The new fixture
allocates shape contexts with no ApuCreateHeap: 64 MiB + 64 bytes fails
with E_OUTOFMEMORY, exactly 64 MiB succeeds as an APU heap allocation,
a later ApuCreateHeap reports busy, and apu_default_heap is logged once.
A 32 MiB or 128 MiB default, or no default heap, each fail it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:15:33 +03:00
ates 64141e9ae6 Merge remote-tracking branch 'origin/main' into track-e/bringup-acphal
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:13:52 +03:00
ates 04148f77f8 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:06:54 +03:00
ates 5a6e786850 docs: console shader ABI review fixes: provenance, class U, NewBE scope
Review on #638:
- a Provenance section records the maintainer's statement that
  Microsoft's authorization covers publishing these derived observations,
  that the material is never committed, and that only a contributor with
  the same authorization can reproduce them;
- CLAIM-XBOX-CS-ENTRY-ABI moves from class A to U (no public source
  establishes it; not yet independently reproduced), names the NewBE
  backend, root buffer descriptors, and the exact host and tool versions;
- the page, changelog and index are scoped to the PIX/NewBE path; the ACO
  comparison cites #650, where it is recorded, instead of #647, and D2 is
  told the ABI is a candidate, not accepted;
- word 3 is decoded from the public GFX10 layout for both 0x11014fac and
  0x31016fac (FORMAT 20/22, OOB_SELECT 1/3), which also explains why the
  record count -1 disables the bounds check;
- eleven probes, not ten; table buffer descriptors 32 bytes apart;
  STRIDE bits 29:16; D3DMetal 4.0b3 named (3.0 not measured); wave64 as
  the default with no declared wave size; odd-SGPR alignment, the
  overflow threshold and ACCC-only output listed as open.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:06:54 +03:00
ates 34f744aa5d CHANGELOG: runtime_veh diagnostic hardening and fixture
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:04:44 +03:00
ates afc093ee54 Merge remote-tracking branch 'origin/track-a/634-veh-breakpoint' into track-a/bringup-veh-diagnostics 2026-11-29 07:03:55 +03:00
ates 224586917f runtime_veh, bx-cli trace: breakpoint record follow-ups from review
From the reviews on #635 (none blocking):
- log_breakpoint saves and restores the thread's last-error value, so a
  resumed first-chance exception leaves the guest's error state as it was
  (test_veh_breakpoint checks it; it fails without the restore);
- past the cap the counter is not advanced again, so it cannot wrap;
- bx-telemetry parses the record's address and bx-cli trace prints it,
  which locates a breakpoint outside any image (module ?);
- the cap note appears when any record reached the cap, not only the
  last line, since threads or processes can write records out of order.

Deduplicating repeated sites stays with #651.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:03:36 +03:00
ates 2af3e7d10a Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:02:00 +03:00
ates 17e2e2a835 runtime_veh: review fixes for the opt-in diagnostics; a fixture for them
Review on #659:
1. the AV context spec is scanned without strtok (no shared cursor
   across faulting threads);
2. every VirtualProtect is checked: a watch or range watch that cannot
   unprotect a page disarms, logs diagnostic_disarmed and passes the
   access violation on instead of looping; failed re-protection, code
   byte restores and int3 re-insertion are logged and disarm;
3. AV context and sampler lines use bounded appends (no length past the
   buffer), JSON-escape the spec and module names, and take module names
   through GetModuleFileNameW and UTF-8;
4. helper threads check a stop flag; detach disarms every diagnostic
   (pages, code bytes, TLS) without waiting, and keeps the log handle and
   lock alive while any helper was started;
5. BX_VEH_AV_CONTEXT/AV_ALL are read once at attach, so with them unset
   an access violation costs nothing;
6. bx-cli lets the named BX_VEH_* switches through its isolated guest
   environment (DIAGNOSTIC_ENV_ALLOWLIST), with a unit test that other
   variables and secrets still do not pass;
7. test_veh_diagnostics runs each mode in a child process (the switches
   are read at attach) and checks the log: no records when off; 16 capped
   av_context records from 4 threads, valid JSON with the spec escaped;
   a non-ASCII module name in UTF-8; one watched write with its value,
   and a failed protection change that disarms and reaches the guest; two
   code hits with a safe string argument; sampler records and a clean
   exit. 21 checks pass; the previous runtime_veh fails 6 of them.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:01:31 +03:00
ates 3ec40ba7fb docs: target-build review: recorded authorization, reproducible offline run
Review on #661:
- authorization is a recorded private note (build, evidence class,
  approving maintainer, lawful access, no circumvention); approval alone
  is not enough, and its ID goes into the PR template and every review;
- a reviewer needs their own recorded authorization for the same
  evidence class and re-derives from their own source;
- the ladder is renamed bring-up checkpoints and stated not to set
  milestone status, which only docs/roadmap.md defines;
- the offline run is copyable: wineserver restart, a curl probe that
  must print BLOCKED inside the profile, and the full bx-cli command
  with --exe, --profile and --inherit-env under env -i (and why);
  sandbox-exec's deprecation is noted;
- the diagnostics table lists only switches on main;
- the rules are cited from CONTRIBUTING.md and docs/legal.md, and the
  hash rule is narrowed to title-derived identifiers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:53:51 +03:00
ates b3aad0d948 Merge remote-tracking branch 'origin/main' into track-f/bringup-review-process
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:52:34 +03:00
ates 277edd592a Merge remote-tracking branch 'origin/main' into track-e/bringup-xgameruntime
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:51:07 +03:00
ates d4996ba9fd xgameruntime: installation monitors in the package state; enumerate this game
Review on #658:
- monitors move to package.cpp, into the mount handles' tagged table
  under mount_mutex: creation checks the runtime generation, rejects a
  null or foreign identifier, closing is idempotent, a closed or stale
  handle reports empty progress and registration on it fails with the
  stale-handle error, and the last uninitialize releases them;
- progress registration is logged as accepted and never fired, with a
  distinct token per registration; unregister reports whether the token
  existed;
- XPackageEnumeratePackages reports this game (its identifier, kind
  Game) for XPackageKind::Game, as documented for ThisOnly, and no
  packages for Content or PublisherContent; invalid kind/scope or a
  null callback is refused.

test_xgameruntime_saves covers slots 5-10 and 28/35/39 through the
public IXPackageImpl object: null and foreign arguments, the progress
values, tokens, double close, closed-handle behaviour, the registration
log record, enumeration per kind, and monitors made stale by
uninitialize.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:51:06 +03:00
ates ca2b48ef83 CHANGELOG: XG tiling per dimension and resource limits
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:45:39 +03:00
ates dc41f00cb3 Merge remote-tracking branch 'origin/main' into track-c/bringup-xg-contract 2026-11-29 06:45:31 +03:00
ates 1b04d6e237 xg_xs: review fixes: comments, 3D bounds, D3D12 limits, tiling per dimension
Review on #656:
- the header comments said other swizzle modes and multi-tile SW_64KB_S
  were refused; they are laid out linearly and reported as LINEAR;
- a 3D subresource past the mip count aliased onto mip 0 in
  CopyInto/FromSubresource; it is refused (E_INVALIDARG);
- XGCreateTextureComputer applies the public D3D12 limits (16384 for
  1D/2D, 2048 for 3D and array sizes) and a 64-bit bound for buffers,
  so widths are never truncated and pitches cannot overflow;
- GetResourceTiling uses the D3D12 standard 3D tile shapes (64x32x32
  one-byte elements down to 16x16x16) with depth tiles, a 64 KiB element
  row for 1D textures and 64 KiB for buffers, instead of 2D shapes.

test_xg_xbox (65 checks) adds hand-computed GetResourceTiling cases for a
2D array with a packed tail, a 3D texture and a 1D texture, the 3D copy
bound, the limits, AddRef/Release, IsTiledResource and the two E_NOTIMPL
methods. Each code fix is caught by the new checks when reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:45:31 +03:00
ates 9116c0a39e Merge remote-tracking branch 'origin/main' into track-b/bringup-dstorage-queues
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:41:34 +03:00
ates b96a9b5978 xcrdapi: a full AutoSubmitDisabled queue stalls until Submit
Review on #655: AutoSubmitDisabled only switched off the half-capacity
submit; a full blocking queue still submitted what was pending before
waiting, so commands ran before the title's Submit. A full queue now
submits by itself only when auto-submit is on. With it off, the enqueuer
waits until Submit is called on another thread and the drain frees a
slot, as DSTORAGE_QUEUE_OPTIONS documents.

test_xcrdapi_xbox fills a capacity-4 disabled queue from a worker
thread: the enqueue past its three slots waits, no destination changes
until Submit, Submit releases the waiter and every request then runs.
It fails with the old full-queue submit.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:41:34 +03:00
Ateş dcec248837 Merge pull request #660 from MacosPorters/track-c/bringup-xbox-first-frame
[M2-C] d3d12_xs: Xbox-layout objects through a target build's frame loop
2026-11-29 06:21:15 +03:00
ates 40b5ee7a8e Merge remote-tracking branch 'origin/main' into HEAD 2026-11-29 06:17:57 +03:00
Ateş b975e6335b Merge pull request #654 from MacosPorters/track-b/bringup-xmem-pages
[M2-B] xmem: page numbers in 4 KiB frames, run mapping, GPU-only windows
2026-11-29 06:17:51 +03:00
ates 8f4786e436 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:14:04 +03:00
Ateş 0c398214fa Merge pull request #645 from MacosPorters/track-c/644-xbox-device-tables
[M2-C14] d3d12_xs: Xbox-layout D3D12 objects, Phase 1 (ADR 0009)
2026-11-29 06:10:40 +03:00
ates 78b56747fb Merge remote-tracking branch 'origin/main' into HEAD 2026-11-29 06:06:38 +03:00
Ateş 63bd059182 Merge pull request #643 from MacosPorters/track-b/636-xmem-signatures
[M2-B6] xmem: follow the documented physical-page and XMemVirtualAlloc signatures
2026-11-29 06:06:24 +03:00
ates 24b124e144 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	tests/conformance/test_m2_first_frame/main.cpp
2026-11-29 06:05:20 +03:00
Ateş cff3e754a9 Merge pull request #640 from MacosPorters/track-c/639-xbox-create-device
[M2-C13] d3d12_xs: D3D12XboxCreateDevice takes the documented four parameters
2026-11-29 06:04:56 +03:00
ates 27bfa17cb1 xgameruntime: offline XPackage installation monitor and enumeration
The installation monitor reports the running package fully installed,
launchable and complete (progress never changes, so registered callbacks
are not called). XPackageEnumeratePackages succeeds offline and reports
no other packages. Both replace stubs a project-authorized target build
calls at startup. The save-container mount path ends with the drive-root
separator; test_xgameruntime_saves expects it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:45 +03:00
ates 261d71d8d1 docs: development cycle and review for target-build bring-up
How any number of contributors run a project-authorized target build
offline, turn each finding into a single-track PR with a conformance
test, and review it independently: roles, the cycle, a PR template,
what a reviewer re-derives, the offline-run procedure, the diagnostic
switches, and what never enters the repository.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:32 +03:00
ates 2cc64bd617 d3d12_xs: Xbox-layout objects through a target build's frame loop
On the Xbox-layout device: descriptor heaps with title-visible storage,
committed and placed resources in title memory with copy coherence,
samplers, page pools, pipelines through the shader gate, opt-in null
rendering (BX_NULL_RENDER=1), fences at GPU addresses, GPU value
writes, PresentX onto a DXGI swapchain, console page mappings
(CopyPageMappingsX/BatchX, ClearPageMappingsX) and the full 1384-byte
Xbox command-list area. BX_PRESENT_DUMP=<folder> dumps presented frames.

With the stacked xmem, XCRDAPI, XG, AcpHal and xgameruntime changes, a
project-authorized target build reaches its frame loop with null
rendering (thousands of frames). test_d3d12_xbox_layout checks the page
mappings (all four range types) and that writing every title-owned
command-list field leaves the list usable; each fails with its fix
reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:32 +03:00
ates d99e35ad42 acphal: IAcpHal slot order and shape contexts
IAcpHal is not COM (authorized GDK documentation): its slots are
Connect, Disconnect, SubmitCommand, PopMessage, GetNumMessages and
Release. AcpHalAllocateShapeContexts and AcpHalReleaseShapeContexts
allocate the documented SHAPE_CONTEXTS arrays from the APU heap, and a
second allocation fails with ACP_E_ALREADY_ALLOCATED; the default APU
heap is 64 MB. A project-authorized target build needs both to start.

test_audio_input checks the slots and the allocation lifecycle;
test_integration_boot releases IAcpHal through its sixth slot instead
of IUnknown::Release.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates f7748387da runtime_veh: opt-in fault context, watches, breakpoints and sampler
All off by default: BX_VEH_AV_CONTEXT / BX_VEH_AV_ALL log an access
violation's memory type, protection, allocation base and unwound stack;
BX_VEH_WATCH and BX_VEH_WATCH_RANGE watch writes to an address, a range
or a pointer chain; BX_VEH_HIT sets software code breakpoints that log
registers and string arguments; BX_VEH_SAMPLE samples every thread.
They were used to find the target build's startup blockers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 28a9c868e6 xg_xs: the documented XG contract, replacing the clean-room interface
xg_xs.dll now implements XGCreateTextureComputer and XGSuggestSwizzleMode
with the documented XG_RESOURCE_DESC and 14-method computer (authorized
GDK documentation): linear layouts by BetterXen's rule, single-tile
SW_64KB_S, other requested swizzles laid out linearly and reported as
LINEAR (refusing crashed a title that ignores the result), and
GetResourceTiling with standard tile shapes and a packed mip tail.

The clean-room xg_xs.cpp, xg_texture.h and test_xg_xs are removed.
test_xg_xbox (42 checks: 32 bpp offsets against the public D3D12
standard swizzle, 8- and 16-byte bijections, BC blocks, linear
fallbacks) replaces them; test_integration_boot stage 13 uses the
documented contract.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 6cfade83fe xcrdapi: zlib file requests and AutoSubmitDisabled on Xbox queues
Zlib requests now get the file handle (every compressed file request
failed), the Xbox request options are decoded and zlib streams inflated.
Xbox CreateQueueX honours DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled
(flags bit 0): such a queue runs nothing before Submit, so a title's
writes no longer land in pages it has not mapped yet; without the flag
the queue submits once half full. BX_DSTORAGE_TRACE=1 traces requests.

test_xcrdapi_xbox covers a file-source zlib request at an offset and
both queue behaviours; each check fails with its fix reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates c963b9bc1a xmem: page numbers in 4 KiB frames, run mapping, GPU-only windows
Physical page numbers count 4 KiB frames (multiples of 16 for 64 KiB
pages, allocations aligned to 0x1000 frames): callers that keep
number >> 4 collapsed 16 consecutive numbers into one page. Pages are
mapped as runs, one view per run, which brought a project-authorized
target build's startup from 36 s to 6 s. Allocation goes through the
title's registered hooks; GPU-only large-page reservations become
mappable placeholders for console page mappings; BX_XMEM_TRACE=1 logs
allocations, frees and maps.

test_xmem_physical checks the page-number units (it fails with
kFramesPerPage = 1); test_xmem_hooks checks the hooks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 30197aa236 d3d12_xs: refuse Xbox-layout objects the host cannot back
bx_xbox_wrap returned the PC object when the host object lacked the
interface an Xbox table forwards to, and D3D12XboxCreateDevice then
logged device=xbox_function_tables and returned S_OK. On vkd3d, which
stops at ID3D12Device9, a title would have called Xbox slot numbers on
a PC table. The wrap now releases the object, logs xbox_wrap_refused and
fails with E_NOINTERFACE for every wrapped family; device creation and
QueryInterface pass that result on.

test_d3d12_xbox_layout verifies the refusal (E_NOINTERFACE, null out
pointer) on such a host and skips with exit 77; on D3DMetal it passes.
With the old fallback restored it fails on vkd3d.

ADR 0009 now states that the fixture's slot numbers come from the same
header as the generator, so it shows agreement, not correctness, and
records the frame-pacing limits (host Sleep, detached thread).

Addresses review points 2 and 4 on #645.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:11:02 +03:00
ates 957b8efb21 d3d12_xs: shadow resources for title-address placed resources (#644)
CreatePlacedResourceX and CreatePlacedResourceX1 place a resource at a
GPU address the title chose. D3DMetal cannot create a resource over
existing memory, so each gets a host shadow: buffers a committed buffer
in a CPU-visible write-back heap filled from the title's memory,
textures a committed texture (contents not filled, logged). The
resource reports the title's address from GetGPUVirtualAddress, and the
record is dropped when the resource is destroyed.

Ongoing synchronisation, GPU-to-CPU copies and address translation in
GPU calls are not implemented yet. test_d3d12_xbox_layout places a
buffer at a title address, checks the reported address and copies its
contents through the GPU.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates e04a3b3f62 d3d12_xs: Xbox-layout command lists and frame pacing, Phase 2 (#644)
Command lists become Xbox objects (ID3D12GraphicsCommandList8, 150
slots) created through CreateCommandListX or CreateCommandList. Their
Xbox field area (put buffer, CPU state, root packet headers) is zeroed,
so the inline fast paths fail their room checks and call through the
table. ResourceBarrier and CopyTextureRegion unwrap the interface
pointers inside their structures.

SetFrameIntervalX, ScheduleFrameEventX and WaitFrameEventX are
emulated from the recorded interval by a host timer that signals the
origin, vblank and flip events and hands out frame tokens.

The generator now handles CRLF lines, a table whose end the boundary
pattern ran past (it hid GraphicsCommandList1), nested SAL arguments and
FLOAT. test_d3d12_xbox_layout records a copy through Xbox command
objects, runs it on the GPU and checks frame pacing.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates ea29d3fc56 d3d12_xs: give titles Xbox-layout D3D12 objects, Phase 1 (#644)
A title built against the Xbox Series D3D12 header calls through
function tables whose slot order differs from PC D3D12, so the PC-layout
proxies sent its calls to the wrong methods. Titles (which set Version
in the device parameter block) now get BxXboxObjects: the Xbox object
layout with m_OutOfLineFlags set and Xbox-order tables that forward to
the existing PC proxies.

tools/gen_xbox_tables.py generates the tables from the Xbox header (slot
order, names, IIDs and types only; the header is not committed) and the
toolchain's <d3d12.h>: typed forwarders where the signatures match,
logged stubs otherwise. Phase 1 covers the device chain to Device11 and
the objects it creates, and implements CreateCommandQueueX. Command
lists follow in Phase 2.

ADR 0009 records the decision. test_d3d12_xbox_layout calls the Xbox
slots by number and fails against the previous DLL.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates d724c6c013 xmem: accept MEM_64K_PAGES as the 64 KB physical-page flag
XMemAllocatePhysicalPages refused MEM_64K_PAGES, which Microsoft's
public samples pass for 64 KB pages: its MEM_PHYSICAL bit was outside
the accepted mask, and its MEM_2MB_PAGES bit reads as XMEM_2MB_CLUSTERS.
MEM_64K_PAGES is MEM_2MB_PAGES | MEM_PHYSICAL, so both bits together now
mean 64 KB pages; the 2 MB bit alone is still XMEM_2MB_CLUSTERS, which
stays unimplemented and logged.

test_xmem_physical adds the samples' shape: a MEM_64K_PAGES page mapped
into a mappable reservation made with PAGE_READWRITE |
PAGE_WRITECOMBINE | PAGE_GRAPHICS_READWRITE (0x2404). It passes on the
D3DMetal and vkd3d hosts and fails with the flag handling reverted.

Addresses review point 1 on #643; point 2 (graphics protection on
mapping) was fixed by the previous commit.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:07:21 +03:00
ates 43cb1aab54 xmem: title-managed placeholders and 32-bit graphics addresses (#636)
A title lays out its descriptor memory by reserving a placeholder with
XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
XMEM_GRAPHICS_32BIT_ADDRESS), splitting it with VirtualFree and
MEM_PRESERVE_PLACEHOLDER, and turning parts into mappable 64 KB ranges
with MEM_REPLACE_PLACEHOLDER | XMEM_MAPPABLE before mapping physical
pages in. All of that is documented; the shim stripped the placeholder
bits and made an ordinary reservation, so the split failed.

Placeholder reservations now honour the 32-bit address limit, a replaced
part is adopted as a mappable range if it is still a placeholder, and
PAGE_GRAPHICS_* protection bits are dropped for the host view. Replacing
a placeholder with committed memory stays a logged stub.
test_xmem_physical replays the sequence.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:05:28 +03:00
ates af869008a0 xmem: follow the documented physical-page and XMemVirtualAlloc signatures (#636)
The authorized GDK documentation gives XMemAllocatePhysicalPages(XMemFlags,
NumberOfPages, PageArray), XMemFreePhysicalPages(NumberOfPages, PageArray),
XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray),
XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)
and the five-argument XMemVirtualAlloc. A title calling them as documented
had its arguments misread, and its XMemAllocatePhysicalPages check broke
into its crash reporter.

Pages are 64 KB; the bandwidth values are accepted; 2 MB clusters and
2 MB-page mappings are stubs. XMEM_MAPPABLE reservations are placeholders
that pages map into, unmap back into, and can be remapped. Scatter
validates every entry before changing any. A NULL map address stays a
BetterXen extension for synthetic fixtures.

test_xmem_physical is rewritten against the documented contracts and
fails against the previous DLL; the other fixtures use the documented
signatures.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:05:28 +03:00
ates 8627285a59 tests: call D3D12XboxCreateDevice with its documented four parameters
test_d3d12_presentx, test_d3d12_vmem_xbox and test_m2_first_frame still
used the old three-argument form. They now pass a NULL adapter and a
zeroed parameter block (Version 0), which keeps the PC-layout proxy they
are written against (ADR 0009). All three pass on the D3DMetal backend.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:00:58 +03:00
ates aec6766b4d d3d12_xs: take the documented four D3D12XboxCreateDevice parameters (#639)
The documented form is (pAdapter, pParameters, riid, ppDevice); the shim
took (params, riid, ppv), so a documented call had its riid written
through as the out pointer. A NULL parameter block now fails with
E_INVALIDARG; a non-NULL adapter is logged and the default host adapter
used; only Version is read from the parameter block. Fixtures pass a
zeroed 80-byte block, and test_d3d12_xs checks the NULL refusal.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:00:40 +03:00
jelly013 84f4370227 Merge main into track-f/637-console-shader-abi
Resolve the CHANGELOG.md conflict under Added by keeping both sides.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-28 17:28:14 +01:00
ates 79e1906c27 docs: note that the console ABI probes describe the NewBE compiler path (#637)
The ACO compiler that emits ACCC containers generates different code for
the same HLSL; its root-buffer descriptor word 3 differs (#647).

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 19:01:10 +03:00
ates d65c12f6a9 Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 19:01:07 +03:00
Bartosz Szczepański b325320549 [M2-C10/C11] d3d12_xs: validate placement on every heap and all three CreatePlacedResource entry points (#554, #572)
CreatePlacedResource (slot 29) validated alignment, extent, buffer clear
value and the UPLOAD/READBACK initial state only on the backing heap.
CreatePlacedResource1 (ID3D12Device8 slot 70) and CreatePlacedResource2
(ID3D12Device10 slot 77) were generated pass-throughs with no validation
and no kPlacedResourceHeap retention, so the shim heap wrapper and its
xmem charge could be dropped while the placed resource was still alive.

All three now share create_placed_common in vmem.cpp. gen_proxy.py gains
a HANDOFF table so the generated slots 70/77 keep their trace and
null-host stub and pass the host interface and unmodified arguments to
vmem.cpp; proxy_generated.{h,cpp} are regenerated. No new vtable slot is
patched.

test_d3d12_placed adds misaligned, aligned-overhang, valid-offset and
UPLOAD-state cases on an ordinary heap for each entry point and runs the
heap-charge retention check through all three.

Closes #554
Closes #572

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 18:39:25 +03:00
atharvranjan 9f8b4c7f69 Merge pull request #646 from MacosPorters/track-e/xsystem-analytics-hdr
[M2-E7] xgameruntime: serve XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode
2026-11-28 09:17:40 -06:00
ates 2e5fbc70b1 xgameruntime: serve XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode through QueryApiImpl
A project-authorized target title requests both during System Init; they were logged as unsupported QueryApiImpl keys. The keys and vtable slots were derived from authorized GDK material; the function contracts follow the public XSystem.h and XDisplay.h documentation.

- XSystemGetAnalyticsInfo (slot 3, returns the 144-byte structure by value): family Xbox, a profile-dependent form, and a synthetic 10.0.26100.0 OS version.
- XDisplayTryEnableHdrMode (slot 4): Disabled, since BetterXen presents SDR. The optional luminance output is cleared.
- test_xgameruntime calls both through QueryApiImpl and checks the public contract.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 18:02:11 +03:00
ates 3f2f2732ed Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 17:49:29 +03:00
ates 7c807d8b3a runtime_veh: address jelly013's review of breakpoint logging
- Say precisely which guest handlers run after bx_veh_handler: the top-level filter and vectored handlers the guest registers last.
- Write module names as UTF-8 via GetModuleFileNameW and WideCharToMultiByte, so a non-ASCII name cannot make the JSONL line invalid.
- bx-telemetry parses record/limit, and bx-cli trace notes when the per-process cap was reached.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 17:49:28 +03:00
Ateş a2d153605d Merge pull request #534 from MacosPorters/track-c/465-presentx-timeout-budget
[M2-C2] Fix PresentX timeouts and post-present fence errors
2026-11-28 11:09:24 +03:00
ates 4a34ec3e50 Integrate main and fix PresentX timeout and recovery handling
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 11:04:23 +03:00
Ateş 2e96d93439 Merge pull request #592 from MacosPorters/track-c/vmem-xbox-config
d3d12_xs: add 32-byte Xbox decoder for D3D12ConfigureVirtualMemoryX
2026-11-28 10:47:39 +03:00
Ateş 30e666b86c Merge pull request #494 from MacosPorters/track-f/469-m2-first-frame-gate
Add end-to-end M2 first-frame conformance fixture
2026-11-28 10:46:04 +03:00
Ateş 41bc72887b Merge pull request #630 from MacosPorters/maint/finish-budget-hook
Finish the combined title budget hook and carry two reviewed PRs
2026-11-28 10:45:31 +03:00
ates c206a3f85d Merge current main into the virtual-memory integration
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:45:08 +03:00
ates c893436269 Combine the virtual memory decoder and shared budget logging
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:44:54 +03:00
Ateş 00b8344a40 Merge pull request #596 from MacosPorters/track-b/xcrdapi-xbox-dstorage
xcrdapi: add Xbox DirectStorage COM interfaces (IDStorage*X)
2026-11-28 10:43:23 +03:00
ates 451c6308c0 Preserve first-frame documentation while merging current main
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:42:40 +03:00
ates 4d69562b59 Merge current main into the combined budget hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:42:29 +03:00
Ateş 656eff8459 Merge pull request #628 from MacosPorters/track-a/627-xbox-drive-map
[M2-A15] bx-cli: map the Xbox title drives G: and T: before launch
2026-11-28 10:41:26 +03:00
Ateş 3ba0eb20d5 Merge pull request #626 from MacosPorters/maint/carry-reviewed-prs
Carry nine reviewed PRs whose head repositories were deleted
2026-11-28 10:41:13 +03:00
ates 8a00743d99 Leave unverified Xbox DirectStorage error output untouched
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:36:28 +03:00
ates ce1940d84c Merge current main into the virtual memory review update
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:35:34 +03:00
ates bd744727bd Validate BXVM inputs before read-only fallback
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:43 +03:00
ates b141c4b261 Count skipped graphics and xmem pairing checks
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:32 +03:00
ates c7a4b4cf19 Clarify conformance exit codes and evidence classes
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:32 +03:00
ates b88ea24a30 Guard the drive manifest temporary file and clarify fixture scope
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:29:37 +03:00
ates b2ae7a604e Merge current main and document the verified M2 pixel control
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:29:35 +03:00
Ateş 901b68ffba Merge pull request #471 from MacosPorters/track-c/465-d3d12-presentx
[M2-C2] Add D3D12 presentation bridge and verified frame conformance fixture
2026-11-28 09:59:09 +03:00
ates 3eb8900442 Merge origin/main into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	tests/conformance/test_audio_input/main.cpp
2026-11-28 09:39:15 +03:00
ates 335e3e4d60 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 09:38:48 +03:00
ates ca2ad143f9 docs: record the console compute shader entry ABI (#637)
Add the compute entry conventions observed from Microsoft's Series X|S
HLSL compiler, used under Microsoft's authorization, on eleven
project-authored probes: wave64 code, root data from s4 in parameter
order, the root-data address in s0:s1 on overflow, IDs after the root
data, inline root buffer descriptors without bounds, table descriptor
sizes and per-load binding metadata. Register roles are marked as
inferences. CLAIM-XBOX-CS-ENTRY-ABI (class A) records the measurement.
No compiler output, binary or documentation text is included.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:25:54 +03:00
Ateş c345ada8e9 Merge pull request #631 from elforeign/track-f/audio-input-log-required
[M2-F] test_audio_input: require BX_LOG_FILE instead of a temp log it can't fill
2026-11-28 09:24:57 +03:00
ates 3154497424 xcrdapi: address devil8blade's review of the Xbox DirectStorage adapters
- IDStorageFactoryX::SetStagingBufferSize logs that the size has no effect, as the public factory does, instead of 'accepted'.
- CreateQueueX documents that the queue priority is ignored on purpose: the Xbox range is not part of the inferred contract.
- test_xcrdapi_xbox requires BX_LOG_FILE and reads only what its own run appended.
- New error-path checks: a memory request on a file queue, a size mismatch, an out-of-range status index, and an enqueue after Close.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:22:06 +03:00
ates 6eaf8faa95 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:19:04 +03:00
ates 3c1ee93df5 Merge origin/main into track-a/627-xbox-drive-map
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:15:51 +03:00
ates 87a03d0421 bx-cli: write the drive manifest atomically and lock the prefix before staging
- write_manifest writes a temporary file and renames it over .bx-drives, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. New test: an interrupted write keeps the previous manifest, and the retry re-points g:.
- The prefix lock is taken before system32 staging, so a refused run has not touched the shared prefix. Runs sharing a prefix are serial, as the changelog now says.
- drives.rs and test_xbox_drives describe the G:/T: roles as an observation of one title plus an inference.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:15:51 +03:00
ates bf9dd7b383 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:11:25 +03:00
ates b59696975a Address devil8blade's review of the budget hook carry
- test_d3d12_placed: the 512 MiB pairing check prints SKIP with the command that runs it, instead of returning silently at other caps.
- vmem.cpp: the release_charge comment and the #552 changelog entry no longer claim the mirror check stops a double release while other heaps are alive. Each wrapper releasing once is what prevents that.
- vmem.cpp: the config log record's xmem_used= is renamed cap_used=, since it already includes graphics heaps.
- test_veh_clwb: parse record fields with a checked strtoull so a malformed record cannot throw.
- CHANGELOG: drop the stale overflow-guard and not-executed lines.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:11:25 +03:00
ates 43bb5636bf test_m2_first_frame: drain the GPU on failure, report the Present HRESULT, reject a malformed control value
- A GpuDrain guard declared just before ExecuteCommandLists signals the queue and waits (bounded) before the queue, back buffer and output resource are released after a failure.
- A failed PresentX reports its HRESULT instead of a fixed message.
- BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH must be unset or exactly 1. Any other value fails, so a mis-armed control cannot pass as an ordinary run, and an armed control is announced.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:05:28 +03:00
ates b7a660d4b9 Address devil8blade's review of the carried PRs
- test_win32_bridge: parse context= from the value, not the key, so the carried #520 round-trip check can pass (it read 0xc for every record).
- test_shader_gate: require every key before comparing positions; a missing hr= was npos and satisfied the order check.
- test_audio_input: a missing BX_LOG_FILE fails instead of printing SKIP and exiting 0.
- acphal: the zero-capacity comments no longer claim ApuAlloc accepted an allocation.
- bx-cli: tests/usage.rs runs the built binary and checks exit codes and output streams for the usage paths.
- CHANGELOG: getpgrp is Perl's built-in, and the new tests are recorded.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:04:11 +03:00
Eterna 10f78645cb win32_bridge: assert the PSM context pointer round-trips
context is observable in the JSONL. But the test only counted
callback_unfired records, so a dropped (context=0x0), swapped or
mis-tagged context would have passed unnoticed -- which makes the
storage decorative.

Parse context=0x<hex> out of the registration records (strtoull base
16; %llx prints lowercase with no leading zeros) and assert:

- every logged context on both families is non-zero and present in
  the set of &entry pointers the test passed;
- at least two distinct pointers appear per family, so one
  registration cannot overwrite another's stored context;
- each family's set covers the whole &entry set, which catches a
  swap or mis-tag between families;
- a record with a missing or malformed context= fails.

Limit, stated rather than asserted: the unregister records carry
only a detail string, so context-drop on unregister is not
observable in the log. The test documents that and prints a note if
a future shim starts logging context there.

Sits on #514, which introduces the context= field; rebases cleanly
once that merges. All existing checks kept and ANDed with the new
result. Cross-compiled and export-verified only; no live CrossOver
run.

Closes #519

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
(cherry picked from commit fa745d5211)
2026-11-28 09:01:48 +03:00
ates 8c4610b51c Merge origin/main into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:54:47 +03:00
ates 3b1d168de7 d3d12_xs: decode the documented Xbox virtual-memory configuration
Replace the inferred segment-count layout with
D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION as the authorized GDK
documentation describes it: flags, a GPU page-table size in 4 MB units
(clamped to 33), a frame-buffer preserve size (clamped to 64 MiB, -1
for the legacy size) and two output addresses. The decoder now writes
the outputs (minimum 2 GiB; maximum 159.375 GiB at the default size,
scaled linearly otherwise and logged as max_estimated=1) and fails with
E_FAIL once a device exists. It still only records the configuration
and keeps BX_STUB_LOG, since the host sizes no GPU page tables.

The fixture checks the documented values instead of the shim's own
constants and fails against the previous decoder.

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

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

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

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:33:39 -07:00
ates 133ffd4c97 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:30:49 +03:00
atharvranjan 0d9997ce66 Merge origin/main into track-c/vmem-xbox-config
Resolve the CHANGELOG.md Added conflict by keeping both the #592
Xbox virtual-memory entry and main's #597 xcrdapi ABI entry. No
technical files changed in this merge.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:29:29 -06:00
ates bfbc84d251 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:27:31 +03:00
ates e96de7c455 Merge origin/main into track-a/627-xbox-drive-map
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:27:25 +03:00
atharvranjan 4b2985114a docs: clarify fixture skip and log evidence
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:26:25 -06:00
ates 0b474941f0 runtime_veh: record breakpoints a guest crash reporter hides (#634)
A guest with its own crash reporter replaces the top-level filter
installed at attach, so its assertions never reached
unhandled_exception. The vectored handler, which runs before any guest
handler, now records EXCEPTION_BREAKPOINT and STATUS_ASSERTION_FAILURE
as breakpoint_exception records with module name, base and RVA. They
are first-chance, handling is unchanged, and at most 16 are written per
process. bx-telemetry parses them and bx-cli trace lists them.

test_veh_breakpoint replaces the top-level filter, resumes from its own
vectored handler and checks the records against the RVA of a labelled
int3 site; it fails against the previous bx_runtime_veh.dll.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:26:19 +03:00
atharvranjan fe749b1436 fix(bx-cli): protect shared Xbox drive mappings
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:25:27 -06:00
Eterna b76066eafb docs_hygiene: slug a heading's rendered text, not its link URL
GitHub slugs the rendered heading, so an inline link contributes only
its text. Slugging the raw source appended the URL, which made a
heading with a link disagree with GitHub's anchor -- including
README.md:53 -- so the first real link to it would be reported as a
broken fragment.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:25:13 -07:00
atharvranjan b7bb7615d8 Merge origin/main into track-c/465-d3d12-presentx
Merge current main (2b2a9e15) with no manual conflict resolution; only
main's additions are brought in.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:20:46 -06:00
Ateş 2b2a9e15a6 Merge pull request #629 from EternaPeptix/track-b/597-xcrdapi-vtable-abi
validate: derive the xcrdapi public DirectStorage slot order and staged-copy fence lifetime (#597)
2026-11-28 08:18:03 +03:00
atharvranjan 3c65b393a4 Merge origin/main into track-c/465-d3d12-presentx
Resolve the proxy.cpp include conflict by keeping main's <vector> (stream
PSO gate) alongside this branch's <type_traits> and presentx.h.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:14:59 -06:00
Eterna 67f3b618ab test: verify xcrdapi public DirectStorage vtable ABI
Closes #597

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

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:13:07 -07:00
atharvranjan b0e40e29ea Merge remote-tracking branch 'origin/main' into pr592-technical-audit
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-27 23:12:23 -06:00
atharvranjan 90dc310b61 fix(d3d12): write VMEM output before applying config
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:11:05 -06:00
ates 4bf52b14a3 test_veh_clwb: require BX_LOG_FILE instead of a temp log it can't fill
The fixture imports bx_runtime_veh.dll, which reads BX_LOG_FILE once in DLL_PROCESS_ATTACH before main runs, so the temp-log fallback could never receive records. Fail with a clear message instead, as #631 does for test_audio_input.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:08:45 +03:00
ates bc7b622018 tmp
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:07:09 +03:00
atharvranjan d8fea7b351 Merge latest origin/main into Xbox drive mapping PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:06:48 -06:00
ates fe50a8edff Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:06:39 +03:00
atharvranjan d47eac809f test: avoid duplicate audio fixture log path
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:06:31 -06:00
atharvranjan 8db5552e32 Merge remote-tracking branch 'origin/main' into pr592-technical-audit
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-27 23:06:17 -06:00
Ateş 297251fb00 Merge pull request #611 from EternaPeptix/track-c/576-stream-pso-gate
[M2-C12] d3d12_xs: run stream pipeline states through the shader gate
2026-11-28 08:06:16 +03:00
atharvranjan 030c63f8c9 Merge origin/main into Xbox drive mapping PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:04:52 -06:00
atharvranjan 9a6f71abbc fix(bx-cli): record Xbox drive ownership before linking
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:04:35 -06:00
atharvranjan ad4bcc66b1 fix: correct carried PR claims and validate chunk offsets
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:03:56 -06:00
atharvranjan 3d244ddcb0 Merge remote-tracking branch 'origin/main' into maint/carry-reviewed-prs
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	launcher/crates/bx-cli/src/main.rs
#	tests/conformance/test_audio_input/main.cpp
2026-11-27 23:03:28 -06:00
ates b29ccc60e1 test_shader_gate: restore the wave64 refusal assertions from #609
The rebase onto main kept the pre-#609 assertions (wave64 PSO only printed, record expected as pass_dxil), so the fixture failed against main's shim. Restore #609's checks: the wave64 PSO returns E_NOTIMPL with no object, and the shader_gate record is reject_wave_wide. The stream PSO checks are unchanged.

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

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

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:56:33 -07:00
elforeign ceaad9aee9 test_audio_input: require BX_LOG_FILE instead of a temp log it can't fill
When BX_LOG_FILE was unset, main created a temp file and set the
variable so the dispatcher log checks had something to read. That is too
late: AcpHal.dll imports bx_runtime_veh.dll, which reads BX_LOG_FILE once
in DLL_PROCESS_ATTACH before main runs. The temp file stayed empty and
the checks failed for the wrong reason.

Fail with a message naming the fix (run under bx-cli run --log) instead.
Also correct the comments that said the log checks catch a leaked
dispatcher: Release updates the counter before delete this, so a missing
delete this leaves the log unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-27 22:52:48 -06:00
ates 6bf2b9ab95 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:50:24 +03:00
ates 527cd6208f Merge #540 into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:50:14 +03:00
Eterna 93a1f12bc6 docs_hygiene: detect the diff3 base marker and gate the unit tests
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
(cherry picked from commit ea9c883fcb)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:50:14 +03:00
Eterna 32b371e55f xg_xs: implement the SW_64KB_S BC family layout
Closes #505

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

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

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

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:49:06 -07:00
atharvranjan 55dfa39600 docs: document M2 pixel mismatch control
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 22:48:26 -06:00
ates c39d33821e xmem/d3d12_xs: apply review fixes to the external charge hook (#550, #552)
Apply the fixes 1Bartosz suggested on #551 and #553:

- Report external charges in XMemGetWorkingSetStatistics and
  bx_xmem_get_internal_stats so reported usage matches the cap.
- Refuse an over-release instead of zeroing other owners' charges.
- Log a failed bookkeeping refresh instead of reporting it as a budget
  rejection.
- Let the xmem hook alone admit graphics heaps; the local pre-check used a
  snapshot outside usage_lock and would count live heaps twice.
- Check the diagnostic mirror before crediting xmem on release.
- Add test_xmem_external_charge and correct the changelog entries.

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

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

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:39:47 +03:00
ates 2d2ee990a7 Merge origin/main into track-a/590-trace-gap-detail
Signed-off-by: ates <ahmetrizaates@hotmail.com>

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

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

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

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

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

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

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:11:52 +03:00
ates 48378f8c35 bx-cli: map the Xbox title drives G: and T: before launch (#627)
An Xbox title opens its package on G: and writes crash logs to T:.
A Wine prefix has neither, so the title stops at startup. bx-cli run
now links dosdevices/g: to the executable's directory and t: to
drive_c/bx_temp. A .bx-drives manifest records the tool's own links;
a mapping it did not make is reported and left unchanged.

test_xbox_drives reads its own executable through G: and round-trips
a file on T:; it fails when G: is absent.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:06:03 +03:00
Ateş 88e6cf00b9 Merge pull request #602 from MacosPorters/track-d/dxbc-accc-nobc-header-only
[M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
2026-11-28 07:05:13 +03:00
ates 0521ea0c6c CHANGELOG: drop the duplicate #535 entry
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:01:52 +03:00
ates ce23d0b2b9 Merge #536 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates d17525c165 Merge #564 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 3cfb9ed690 Merge #556 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 51ac3bd766 Merge #522 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates e816c16495 Merge #514 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 076b354d61 Merge #533 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	launcher/crates/bx-cli/src/main.rs
2026-11-28 07:01:52 +03:00
ates 0bd188e602 Merge #510 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
ates b86be87576 Merge #581 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
ates 62290b2f21 Merge #560 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
Ateş 2d8685681b Merge pull request #610 from EternaPeptix/track-d/586-timeout-overflow
[M2-D6] d3dmetal-harness: saturate an overflowing timeout deadline
2026-11-28 06:56:41 +03:00
ates 25d5240dd0 Merge remote-tracking branch 'origin/main' into pr-610
Signed-off-by: ates <ahmetrizaates@hotmail.com>

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

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

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

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

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

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

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

Closes #500

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

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

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

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

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

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

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

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

Closes #500

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

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

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

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

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

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

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

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

README only; no code, test or abi change.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:49:36 -07:00
atharvranjan 04ad81ee26 Merge branch 'track-c/465-d3d12-presentx' into track-c/465-presentx-timeout-budget
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:49:10 -06:00
atharvranjan e0f8b0e8f6 d3d12_xs: preserve device removal after Present and budget WaitForIdle before Signal
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:45:46 -06:00
atharvranjan 2fc82c4d58 d3d12_xs: distinguish post-present fence wait failures and require WaitForIdle
When wait_locked fails after a successful host Present and signal for a reason other than timeout, log the underlying wait HRESULT as present_next_buffer_wait_failed, require WaitForIdle to succeed before further Present calls (BX_PRESENT_E_NEEDS_IDLE), and return BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED (0x80040205) so callers can distinguish post-present wait failures from pre-present wait failures.

Update test_d3d12_presentx with test-side SetEventOnCompletion E_OUTOFMEMORY fault injection on both sides of host Present, verifying distinct return codes, host present counts, log records, and WaitForIdle recovery, plus a skip-wait-fault negative control in run_controls.sh.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:43:46 -06:00
Eterna c33199264a test_shim_exports: load bx_shader_bridge.dll, covering all 17 DLLs
The fixture that exists to prove every shipped shim loads and
resolves its exports covered 16 DLLs -- the mingw-w64 C++ shims --
and skipped bx_shader_bridge.dll, the Rust-built 17th DLL from
#484. That was the gap #526 documented.

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

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

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

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

Closes #527

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

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

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

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

Closes #537

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

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

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

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

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

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

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

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

Four defects fixed:

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

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

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

Closes #507

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

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

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

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

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

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

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

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

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

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

Closes #515

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

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

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

Closes #515

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

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

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

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

Closes #547

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

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

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

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 04:57:54 +03:00
atharvranjan 989abbdc2c [M2-D] dxbc-accc: deduplicate DXIL state and add NOBC bounds tests
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:29:56 -06:00
atharvranjan 140dce0be1 Merge remote-tracking branch 'origin/main' into track-d/dxbc-accc-nobc-header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:27:40 -06:00
ates 1b25f3422b Merge origin/main into track-f/469-m2-first-frame-gate
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 03:47:21 +03:00
ates 766055e948 Merge origin/main into track-c/vmem-xbox-config
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 03:47:21 +03:00
Ateş 2faadeef7e Merge pull request #600 from MacosPorters/docs/merge-eligibility-policy
Clarify pull request merge eligibility
2026-11-28 03:32:26 +03:00
atharvranjan ce5968a2db Merge pull request #601 from 1Bartosz/track-d/599-fspx-layout-mismatch
[M3-D2] dxbc-accc: report an FSPX layout mismatch apart from out-of-bounds (#599)
2026-11-27 18:30:40 -06:00
atharvranjan 494e53b8fb [M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:29:50 -06:00
ates 54b87f613c test_m2_first_frame: fence the readback, name config fields, state limits
Wait on a queue fence before the CPU reads the backing map instead of
relying on WaitForIdle alone, assign the BXVM config by field name so a
reorder in vmem.h cannot compile silently, tie the expected pixel formula
to fill_cs66.hlsl, and record the fixture's limitations in its header.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:28:58 +03:00
ates bbd3b8a9d4 Merge origin/main into track-c/vmem-xbox-config
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:26:21 +03:00
ates 32d02efc33 d3d12_xs: record the Xbox vmem block without claiming it applied
Nothing consumes the decoded virtual-segment count yet, so the Xbox path
now logs vmem_config_recorded (applied=0 recorded_only=1), keeps
BX_STUB_LOG, and leaves the BXVM record and its cached backing heap
alone instead of evicting it.

Name the source of the layout as a project-authorized target build with
provenance pending review, and have the fixture read only the log bytes
appended by each step, so fixtures sharing one log cannot satisfy or
break its checks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:26:08 +03:00
atharvranjan ac82a55039 Keep PresentX test hook table alive on failure
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:19:39 -06:00
Bartosz Szczepański d6586b1fa3 docs: name FspxLayoutMismatch where ADR 0008 and the roadmap cite the FSPX scan (#599)
ADR 0008 and the roadmap (#588) say dxbc-accc rejects the 29 scanned
FSPX containers with FspxSectionOutOfBounds. The cause they record, a
descriptor offset inside the reserved header-plus-table region, is
FspxLayoutMismatch after this branch. Both now say which error the scan
saw, which one the same cause maps to now, and that the scan was not
re-run. The C ABI still returns BX_SHADER_ERR_INVALID_BLOB for both.

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

# Conflicts:
#	CHANGELOG.md
2026-11-28 01:10:37 +01:00
atharvranjan e40d7293f8 Merge main into M2 first-frame fixture PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:09:56 -06:00
Ateşandatharvranjan 2ef175c0ce Roadmap: prioritize startup diagnosis and define first-frame acceptance (#588)
* docs: prioritize startup diagnosis and define first-frame acceptance

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

* docs: clarify roadmap verification and memory scope

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

* docs: record the target-workload shader corpus scan

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

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

---------

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

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

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

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 00:28:47 +01:00
Jelly 9d4f7dffff Merge pull request #598 from MacosPorters/docs/agents-authorized-compatibility
docs: update AGENTS.md with 3-tier agent task priorities and authorized evidence rules
2026-11-28 00:14:59 +01:00
ates 981bd3c64e xcrdapi: add Xbox DirectStorage COM interfaces (IDStorage*X)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:55:06 +03:00
ates 63b5f5dac6 d3d12_xs: add 32-byte Xbox decoder for D3D12ConfigureVirtualMemoryX
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:28:00 +03:00
Eterna 6484cb70a3 acphal: reject a zero-capacity APU heap
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:46:14 -07:00
Eterna 87da1752ad docs: keep the results table contiguous after the exit-code note
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 1bc42fcaec docs: move the exit-code note below the results table
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 25ceb05230 docs: define the conformance exit-77 skip protocol
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 2bc97a4f68 bx-cli: avoid ps in cleanup process-group test
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:34 -07:00
Eterna f2efeaf79d docs: define claims.toml evidence classes A/B/D/E/U (#549)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:33 -07:00
Erkin Taş ab81b0beca d3d12_xs: distinguish fence wait failures after Present
Signed-off-by: Erkin Taş <erkinemreta@gmail.com>
2026-11-27 23:41:29 +03:00
Eterna b16797f576 test_d3d12_placed: exercise the graphics-first xmem pairing (#552)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 10:38:00 -07:00
Eterna 3409bf4ec0 d3d12_xs: charge graphics heaps through the xmem hook
After #550, xmem could see an external charge, but d3d12_xs still
kept its own private ledger and never registered one, so the
graphics-first overcommit remained. try_charge now calls
bx_xmem_try_charge_external and release_charge calls
bx_xmem_release_charge_external, so both allocation orders obey one
combined cap.

The overflow guards are kept, not traded away. try_charge still
rejects on bytes > cap, xmem_used > cap and
charged_private_bytes > cap - xmem_used before either unsigned
subtraction, and the comment now names which guard protects which
wrap and shows that the two additions cannot overflow given the
guards.

g_record.charged_private_bytes stays as a diagnostic mirror;
xmem's external_bytes is authoritative. release_charge releases
the xmem charge first, which logs and clamps on underflow, then
keeps the mirror in sync.

Lock order checked: try_charge and release_charge hold g_section
and then call into xmem, which takes usage_lock. xmem never calls
back into d3d12_xs (its only mention is a comment), so
g_section -> usage_lock is never inverted.

abi/, xmem.dll and d3d12_xs.dll export counts unchanged (17 / 4).
test_d3d12_placed.exe was NOT executed: no CrossOver on this host.
The two-order arithmetic was checked by simulation, not on host.

Closes #552

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 09:10:51 -07:00
Eterna 420c2329b7 abi: expose an xmem charge hook for the combined title budget
The combined Lockhart/Anaconda budget was one-way. try_charge in
shims/d3d12_xs/vmem.cpp read bx_xmem_get_internal_stats and
subtracted CPU usage before admitting a graphics heap, but
can_commit in shims/xmem/xmem.cpp summed only heap, virtual and
physical bytes and never saw the graphics charge. So graphics-first
(6 GiB) then CPU (3 GiB) admitted 9 GiB against an 8 GiB cap, while
xmem-first was rejected correctly. The header exposed no way for a
second owner to register a charge, so the fix could not live in one
shim; this is the [ABI] change that lands first.

Add bx_xmem_try_charge_external and bx_xmem_release_charge_external
to bx_xmem_internal.h, exported from xmem.dll (15 -> 17). Admission
is atomic under the same usage_lock can_commit takes, so two threads
cannot both pass, and it returns 0 rather than silently succeeding.
The new external_bytes counter is folded into can_commit and
update_peak, so both allocation orders now obey one cap. Release
clamps to zero and logs on underflow, mirroring release_charge.

bx_runtime_config_t is unchanged and there is no ABI version bump:
this is additive only.

shims/d3d12_xs/vmem.cpp still keeps its private
g_record.charged_private_bytes. Switching it to these functions is
the consumer change, a separate PR.

Verified: build-shims.sh reports Verified 17 PE32+ shim DLLs
(113 exact exports) with OK xmem.dll (17 exact exports verified);
fmt, clippy and test pass; docs_hygiene 0 problems; the header
compiles from both C and C++ with -Wall -Wextra -Werror. No live
CrossOver run: none on this host.

Closes #550

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 08:57:57 -07:00
Eterna ae869522ce test_veh_clwb: assert the decoded clwb length, not just the count
The fixture emitted six clwb forms and asserted only delta == 6.
But decode_clwb_length decides len, and the handler does
Rip += len: a wrong len lands the guest mid-instruction while the
trap count stays at 6. The log already carried len=%zu, and no test
read it.

log_sampled_trap logs only counts 1, 2, 4, 8, ..., so six traps
produce exactly three records with total_traps = 1, 2, 4. Assert on
those sampled records only (option (a)); forms 3, 5, 6 are NOT
covered by a len= assertion, and the comment and CHANGELOG say so.

Mapping, re-derived by assembling with x86_64-w64-mingw32-as and
disassembling with x86_64-w64-mingw32-objdump -d:

  total_traps=1 -> clwb (%rax)        -> len 4
  total_traps=2 -> clwb 0x40(%rax)    -> len 5
  total_traps=4 -> clwb (%r8)         -> len 5

clwb (%r8) is 66 41 0f ae 30, ModRM 0x30, confirmed from the
disassembly rather than guessed.

Add a BX_LOG_FILE reader (the fixture did not read it before),
creating a temp log when the variable is unset, initialized before
the clwb block. The AVX2/FMA block runs first but does not trap, so
the first clwb is trap #1. Also assert len >= 4 on every observed
record. The existing delta == 6 check is unchanged.

test_veh_clwb.exe was NOT executed: no CrossOver on this host. The
log-parsing logic was sanity-checked on the host against a synthetic
JSONL sample; a live CrossOver + Rosetta 2 pass is still required.

Closes #539

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 06:55:03 -07:00
Eterna 6e3ef5459b test_shader_gate: assert the log's shape, not a hand reading of it
The bx-cli trace fixtures were typed by hand from reading the
snprintf in shader_gate.cpp. A reviewer asked for a real log; one
was supplied in a PR comment and confirmed the parser, but that
confirmation lived nowhere in the repo, so the next fixture could
drift unnoticed.

This asserts the shape of the log the fixture itself writes:

- at least one shader_gate and one shader_d3dmetal_gap record exist;
- every gate record writes pso=, stage=, decision= and hr= in that
  order, which is the order the summarizer extracts them in;
- an *_unclassified record carries no kind=;
- every gap record has pso=, stage=, wave_lanes_min= and the colon
  that ends its structured part, which is the boundary
  parse_key_values(..., true) needs;
- no key=value value is split by a space, which is what
  parse_key_values(..., false) assumes for the gate records.

Shape, not counts: decision and kind totals vary by GPU. It is the
field order and token boundaries that a hand-typed fixture could get
wrong without any test noticing.

Verified: the assertions compile and link, and their logic was run
in a native harness against a sample log, including a negative
control where an atomic64 value containing a space correctly trips
the check. test_shader_gate.exe itself was not run here -- no
CrossOver on this host.

Closes #535

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 06:35:41 -07:00
Eterna bec15f43b6 bx-cli: test the usage paths in-process, not by spawning the binary
The previous test located the built bx-cli by guessing a path from
current_exe(). That worked locally but failed in CI with
"spawn bx-cli: No such file or directory", because cargo does not
guarantee the bin sits next to the test binary.

Replace it with a testable dispatch: Dispatch::classify(args) returns
Help / NoArgs / Unknown / Sub, plus usage_on_stdout() and
is_usage_error(). main() is now a thin shell over that, so the exit
and stream choices are asserted in-process with no binary lookup and
no dependency on the build layout.

usage_text() returns the string; main() prints it to the stream the
dispatch selects. The five real subcommands are asserted to be
neither usage errors nor usage-printing, and a second test checks
the usage text names every subcommand so the classifier is not
testing a table nothing prints.

Behaviour is unchanged from the intended fix: --help/-h/help exit 0
on stdout, a bare invocation exits 1 on stderr, an unknown
subcommand exits 1 on stderr.

Closes #532

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 05:59:40 -07:00
Erkin Taş 7dde71e2fd d3d12_xs: share the PresentX idle timeout budget
Signed-off-by: Erkin Taş <erkinemreta@gmail.com>
2026-11-27 15:54:54 +03:00
Eterna 33d439f828 bx-cli: fix the inverted help and usage exit codes
--help and -h were never matched, so they fell into the
unknown-subcommand arm: usage text on stderr and exit 1. Meanwhile a
bare bx-cli with no arguments printed usage and returned 0. Both
halves were wrong, and in opposite directions.

--help, -h and help now print usage on stdout and exit 0, so
`bx-cli --help | less` and `bx-cli --help && ...` both work. A bare
invocation is a usage error: text on stderr, exit 1. An unknown
subcommand still exits 1, unchanged.

print_usage takes a UsageStream so the caller chooses the stream
instead of the function hardcoding eprintln!. The subcommand
behaviour of doctor/probe/shader/trace/run is untouched.

Test help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error
runs the built binary and asserts exit code, stdout and stderr for
--help, -h, no arguments and a bogus subcommand. Mutation-checked:
restoring the old dispatch makes it fail at exactly
"--help must exit 0".

Closes #532

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 05:53:12 -07:00
Eterna a27284ab26 dxbc-accc: expose a bounds-checked chunk-lookup API
dxbc-accc already parsed the DXBC chunk table into
ChunkInfo { fourcc, offset, size }, but exposed no public lookup, so
shims/d3d12_xs/shader_gate.cpp:94 re-implements the same
bounds-checked walk in C++ (find_chunk), plus a second variant
has_chunk_tag that ignores the declared size. Two parsers for one
container is how a fix lands in one and not the other.

Add an additive API on ShaderInspection:

- chunk_payload(&container, &fourcc) returns the payload of the
  first chunk tagged fourcc. It reuses the already-parsed chunks
  vector rather than re-walking the raw table, and validates
  offset + 8 + size against BOTH container_size and container.len()
  with checked arithmetic, returning None instead of panicking.
  offset points at the 8-byte chunk header, so the payload begins
  at offset + 8. A zero-size chunk yields Some(&[]); callers needing
  a minimum size must check the returned length. When several chunks
  share a FourCC, the first in table order wins, matching the C++
  find_chunk.
- has_chunk_tag(&fourcc) answers presence WITHOUT trusting the
  declared size, mirroring the C++ has_chunk_tag.

Scope: the C++ gate is NOT migrated here -- find_chunk and
has_chunk_tag in shader_gate.cpp stay for now, and the PR names the
migration as a follow-up, since it is a larger change needing a live
run. abi/defs/bx_shader_bridge.def unchanged (3 exports).

Seven new unit tests: SFI0 and PSV0 payloads returned exactly; a
declared size past the container -> None; an absent FourCC -> None
and has_chunk_tag == false; a zero-size chunk -> Some(&[]); an
exact-fit chunk at the container end (no off-by-one); a truncated
container slice -> None; and duplicate FourCCs -> first wins.

Closes #521

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 04:53:52 -07:00
Eterna 311f4124fa win32_bridge: store the PSM callback and say it is never fired
register_notification validated callback for null and then dropped it:
nothing stored it, nothing ever invoked it, and the context pointer was
discarded as PVOID /*context*/. So ERROR_SUCCESS meant 'token
allocated', not 'you will be notified', and neither the code nor the
log said so.

- Each registration now keeps a (token, callback, context) record
  under the existing SRWLOCK, capped at a fixed kMaxRecords (256) so
  no allocator is needed. The exported wrappers thread context
  through. Unregistering drops the record, so no later event can
  reach a retired registration.
- A comment on register_notification and the JSONL detail (now
  'registered_offline callback_unfired') both state that the callbacks
  are accepted and currently never invoked, because this shim has no
  source of app-state or constrained-change events and the console
  firing contract is not publicly documented. No firing policy was
  invented: the callback is deliberately left unfired rather than
  called spuriously to look implemented.
- test_win32_bridge.exe now also asserts that no callback fires, and
  that every registration's detail carries callback_unfired, counted
  separately for state and constrained. The existing per-event JSONL
  counts still pass, since the detail grep is a substring match.

abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def and -l1-1-1.def are
unchanged at 2 exports each; all six API-set DLLs keep their original
export counts. Cross-compiled and export-verified only; no live
CrossOver run.

Closes #513

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 03:35:42 -07:00
Eterna 46a6a4baca acphal: stop reporting success for shape-context work not done
AcpHalAllocateShapeContexts and AcpHalReleaseShapeContexts logged a
stub and returned a bare S_OK. Allocate discarded its only argument
(unnamed) and Release takes no argument at all, so neither could be
held to anything: a caller was told the work succeeded when nothing
had happened. This is the silent-fallback case AGENTS.md section 5
names.

Both now return E_NOTIMPL and keep their BX_STUB_LOG record, so
bx-cli trace still surfaces the call while a caller is told to fall
back instead of being told the work happened. Release mutates no
state, so calling it twice is safe.

The public Microsoft Learn page for AcpHal is NDA-gated (HTTP 200
with only the membership gate), so the true signatures and the
context layout are unknown, including whether Release should take an
argument. E_NOTIMPL is therefore BetterXen's choice, not the
console's; no signature was invented and abi/defs/AcpHal.def is
unchanged at 9 exports.

test_audio_input.exe now calls both through the DLL: null and
sentinel pointers return E_NOTIMPL without crashing, a second
Release call returns E_NOTIMPL, and when BX_LOG_FILE is set it
asserts both symbols still appear on unimpl_api lines (printing an
explicit SKIP when the variable is unset rather than claiming a
pass).

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

Closes #509

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 00:56:02 -07:00
atharvranjan 8245c30b56 d3d12_xs: keep Present from blocking and recover from a failed signal
Present no longer waits for the swapchain lock, which its holder may keep
across a host Present that depends on the caller's thread. It returns
BX_PRESENT_E_BUSY with nothing presented.

When the fence signal after a host Present fails, return
BX_PRESENT_E_COMPLETION_UNCONFIRMED and refuse further presents with
BX_PRESENT_E_NEEDS_IDLE until WaitForIdle succeeds, so a buffer is not
reported reusable on the strength of an older fence value.

The fixture injects both faults from the test side.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 22:27:19 -06:00
atharvranjan be647332cb Merge main into the PresentX branch
Keep both new d3d12_xs source files in CMakeLists.txt and both sets of CHANGELOG entries.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 22:27:19 -06:00
ates fbd2f8cf43 Gate the M2 fixture target on its provider headers
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 06:00:35 +03:00
ates 6a1451b265 Clarify M2 frame readback and test pixel mismatches
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 05:38:34 +03:00
ates c64534fb21 Add end-to-end M2 first-frame conformance fixture
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 04:21:26 +03:00
atharvranjan b096424f33 d3d12_xs: fix presentation timeout semantics and strengthen the frame test
Present now waits for the current buffer before calling the host, so
ERROR_TIMEOUT means nothing was presented. A timeout after the host
Present returns BX_PRESENT_E_NEXT_BUFFER_BUSY. WaitForIdle counts lock
acquisition against its timeout, and same-thread re-entry is refused. The
leak-on-timeout path now returns the queue proxy reference.

The fixture checks host buffer identity, per-frame present counts, both
timeout results, the leak path, rejection log records and the swapchain
release count against a host-only control. run_controls.sh checks each
negative control's failing stage.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 14:33:13 -06:00
atharvranjan f2af367da6 [M2-C2] d3d12_xs: add a swapchain presentation bridge and frame conformance test
The proxied command queue answers a BetterXen-defined IID with a tear-off
that creates a flip-model swapchain on a Win32 window over the host's
IDXGISwapChain3. This is not the console's PresentX and claims no binary
compatibility with it. No export or abi/ file changes.

The bridge waits (bounded) for the next back buffer, waits for the GPU
before releasing, and refuses presents that D3DMetal 3.0 was observed to
accept with S_OK (sync interval above 4, any flag, destroyed window).

test_d3d12_presentx renders and presents 12 frames, checks every read-back
pixel against CPU-computed values, and compares swapchain lifetime with a
host-DXGI control.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 12:46:56 -06:00
124 changed files with 22201 additions and 2757 deletions

No files matched your search

+2
View File
@@ -29,6 +29,8 @@ jobs:
fetch-depth: 0
- name: Install PyYAML
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
- name: Unit-test the hygiene checks
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
- name: Check documentation and workflow files
run: python3 scripts/audit/docs_hygiene.py --require-yaml
- name: Remind about the changelog (advisory)
+27
View File
@@ -0,0 +1,27 @@
name: Merge policy audit
# Detects a pull request merged by its own author (AGENTS.md §7, "Merge
# eligibility"). GitHub rulesets cannot block this, so the run fails after the
# merge. It is not a required check and never checks out pull request code.
on:
pull_request_target:
types: [closed]
branches: [main]
permissions: {}
jobs:
author-merge:
name: Author did not merge
if: github.event.pull_request.merged == true && github.event.pull_request.merged_by.login == github.event.pull_request.user.login
runs-on: ubuntu-24.04-arm
timeout-minutes: 2
steps:
- name: Report a self-merge
env:
PR: ${{ github.event.pull_request.number }}
AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
echo "::error::Pull request #$PR was merged by its own author, $AUTHOR. A maintainer other than the author must merge (AGENTS.md section 7)."
exit 1
+66 -53
View File
@@ -4,46 +4,59 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
---
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
## 0. What to Do When Told "Work"
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
1. **Preflight host & tools:**
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
2. **Select work in strict priority order:**
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
```
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
- **Priority 2 — Pick an unclaimed open issue:**
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
```sh
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
```
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
- **Priority 3 — Review & independently verify open PRs needing review:**
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
```sh
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
```
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
3. **Claim & isolate (for Priority 2 issue work):**
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
4. **Implement strictly in scope:**
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
5. **Verify locally (including hosts without CrossOver):**
- Run every command in Section 8 and fix all warnings/failures before stopping.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
6. **Review & submit PR:**
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
**"Work" authorizes, for the one item you pick:** posting a claim or a review, committing with DCO sign-off, pushing a branch, and opening a pull request. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
### Step 1 — Preflight
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`. If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`). Verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor`. It must report the toolchain, CrossOver, at least 10 GB of free disk space, and no other game run on this machine.
- Work in your own worktree and your own bottle. Never use a bottle another session is using.
### Step 2 — Pick exactly one thing, in this order
Take the first that applies. Do not skip ahead because a later one looks more interesting.
1. **Your person's pull requests that need attention.**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,statusCheckRollup,mergeStateStatus
```
If one has requested changes, unresolved review comments, failing checks or conflicts: fix that pull request. Resolve every review point, re-run Section 8, push, and reply to each point.
2. **Review someone else's pull request.**
```sh
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
```
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test, confirm the test fails without the fix, read its proof, and post an approval or a change request with what you ran. If it needs deep review (the list is in the working method) and you can give one, do. If it is approved, green and not your person's, merge it (Section 7).
3. **Fix one blocker of the current stage.**
```sh
gh issue list --repo MacosPorters/betterxen --state open --label blocker --label "stage: <current>" --json number,title,labels,comments
```
The current stage is named on the pinned issue labelled `ladder`. Take the top unclaimed blocker: those labelled `first`, then lowest number. A blocker is claimed if it has a `Claiming —` comment less than 3 days old or an open pull request. Then follow Step 3.
4. **Discover.** If the current stage has no unclaimed blocker, run the stage's gate check (ten runs, [run protocol](docs/process/working-method.md#run-protocol)). For each signature in the report that has no issue, open or closed, file a blocker issue in the fixed shape. If the gate passes, post the ten-run result on the ladder issue and label it `needs-human`.
5. **Nothing applies.** Say so and stop. Do not invent work, open research documents, or start on a later stage's blockers while the current stage has claimed, unfinished ones — unless your person tells you to.
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
### Step 3 — Work one blocker
1. **Claim:** comment `Claiming — branch: track-<a..f>/<issue>-<slug>` and branch from `origin/main`.
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. If you cannot explain the blocker in this session, write what you learned on the issue, release the claim, and stop. Do not guess a fix.
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix.
5. **Verify:** every command in Section 8. Without CrossOver you can still run the Rust checks, `scripts/build-shims.sh` and the docs check; say plainly which live checks were not run. Never report an unrun check as passed.
6. **Proof:** ten runs before and ten after, every run reported, with the machine and the `main` commit.
7. **Pull request:** one blocker; the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof); `Closes #<issue>`; DCO sign-off; no AI trailers. Watch CI until `Hybrid build and shim checks` and `Repository hygiene` pass.
8. **Stop.** The next "work" starts again at Step 2.
Nothing from the target build goes into a commit, issue or pull request (Section 6): keep run logs, dumps and captures in your private evidence folder outside the repository.
---
@@ -93,9 +106,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
## 4. Dependencies, Licensing & Provenance
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
- **Provenance first:** Exclude anything (code, data, documentation, or observations) derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific patches, asset-specific workarounds, and decryption-related code are never adopted; general Xbox Game OS, Direct3D, DirectStorage, and runtime ABI contracts established from project-authorized builds that meet every Section 6 condition are in-scope compatibility work.
_Reserved — policy migration in progress._
---
@@ -112,16 +123,6 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
## 6. Compatibility Evidence & Legal Boundaries
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
- **Conditions for target builds:** A build is project-authorized only when a maintainer has approved it for compatibility research **and all** of the following hold. Approval is an additional condition, never a substitute: it cannot grant access or license rights that the project does not hold.
- The person inspecting it obtained it lawfully.
- Its license terms and applicable law permit the inspection performed.
- It is not leaked, stolen, confidential, or otherwise distributed without authorization, and neither are the tools used on it.
- Inspecting it requires no decryption and no circumvention of security, DRM, licensing, or activation controls.
If any condition is unknown, do not use the build. State in the PR which contracts come from target-build observation, without naming the title or build.
- **Never obtain or use** leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or unauthorized game builds and shader collections. Maintainer approval does not change this.
- **Repository & clean-tree boundary:** Never commit or paste proprietary executables, SDKs, confidential vendor documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, proprietary shaders, raw caller memory dumps, executable contents/addresses, private traces, proprietary file names or hashes, personal paths, or secrets into the repository, its Git history, commit messages, issues, or PR descriptions.
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
---
@@ -133,9 +134,21 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
```
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
### Merge eligibility
Four roles are separate: the **original author** (who opened the PR), **corrective contributors** (who later push to its branch), **independent approvers**, and the **merger**.
- The original author never merges their own PR. Any other maintainer may merge once required checks pass, at least one approval is current and blocking review conversations are resolved.
- Maintainers may resolve conflicts, correct defects, update documentation and push fixes to a contributor's PR branch where GitHub permissions allow. Doing so does not disqualify them from merging.
- Any push that changes the PR dismisses earlier approvals. After a **routine** push (conflict resolution that changes no behaviour, changelog correction, minor documentation fix), one new approval is enough and may come from the maintainer who pushed it, if they are not the original author. No further approval is required beyond the ruleset.
- **Substantive** implementation changes need independent review (Section 5): the approval must come from someone who did not write them. A maintainer who wrote substantive corrections may merge after another person has approved those corrections, but may not approve them. If in doubt, treat a change as substantive.
- A coding agent acts as the person it works for and merges only with that person's authorization.
The `Protect main` ruleset enforces pull requests, one approval, dismissal of stale approvals, resolved conversations, the required CI checks and no force push or deletion, with no bypass actors. GitHub cannot enforce two rules above: who may merge (`Merge policy audit` only fails after an author self-merge) and whether an approver wrote part of the change.
---
## 8. Verification Commands (Run Before Every Handoff / PR)
@@ -175,5 +188,5 @@ These rules apply to every coding agent, whatever its model, vendor or plan. Sav
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and meets every required approval and check, instead of stopping at intermediate reports. This grants no permission beyond Section 7.
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and eligible (Section 7), instead of stopping at intermediate reports. This grants no permission beyond Section 7.
- **Escalate real uncertainty:** Raise genuine doubt about ABI compatibility, memory safety, concurrency, security, GPU synchronization, licensing or architecture with a maintainer rather than guessing.
+180 -1
View File
@@ -9,16 +9,172 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Changed
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
### Added
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
- `AcpHal.dll`:
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
- **The default APU heap** is 64 MB.
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
- **Samplers and page pools.**
- **Pipelines** through the shader gate.
- **Opt-in null rendering** (`BX_NULL_RENDER=1`): pipelines that cannot be built become null pipelines, and their draws and dispatches are skipped and logged.
- **Fences** at GPU addresses and GPU value writes.
- **`PresentX`** onto a DXGI swapchain.
- **Console page mappings:** `CopyPageMappingsX`, `CopyPageMappingsBatchX` and `ClearPageMappingsX`.
- **The full 1,384-byte Xbox command-list area.**
- **Opt-in dumps of presented frames** (`BX_PRESENT_DUMP`).
`test_d3d12_xbox_layout` checks the page mappings and the command-list area.
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
- `d3d12_xs.dll` gives titles Xbox-layout D3D12 objects ([ADR 0009](docs/adr/0009-xbox-layout-d3d12-objects.md)). A title built against the Xbox Series D3D12 header calls through function tables whose order differs from PC D3D12. `ID3D12Device` matches only up to slot 43, and `ID3D12Device11` has 139 slots. So before, every call past those slots reached the wrong PC method, and on a project-authorized target build the first such call jumped to address 0.
- **Objects and tables:** `BxXboxObject` (`shims/d3d12_xs/xbox_facade.{h,cpp}`) has the Xbox object layout and sets `m_OutOfLineFlags`. Its Xbox-order table forwards to the PC proxies. `shims/d3d12_xs/tools/gen_xbox_tables.py` generates the tables (`xbox_tables_generated.cpp`) from the Xbox header, used under Microsoft's authorization, and the toolchain's `<d3d12.h>`. It takes only slot order, names, IIDs and parameter types, and the header is not committed.
- **Slots:** a slot with an equivalent PC signature forwards with the PC types, unwrapping interface parameters and wrapping created objects. Every other slot logs `BX_VTABLE_STUB_LOG`.
- **Coverage:** the device chain up to `ID3D12Device11`, plus resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues. Command lists are not covered yet.
- **`CreateCommandQueueX`:** maps the Xbox queue description onto PC `CreateCommandQueue`.
- **Layout choice:** titles set `Version` in the device parameter block and get the Xbox layout. BetterXen's PC-layout fixtures pass a zeroed block and keep the PC proxy. The choice is logged as `xbox_layout`.
- **Phase 2:**
- **Command lists:** `ID3D12GraphicsCommandList8`, created through `CreateCommandListX` or `CreateCommandList`. Their zeroed put-buffer fields force the five inline fast paths through the table.
- **Embedded interface pointers:** `ResourceBarrier` and `CopyTextureRegion` unwrap the interface pointers inside their structures.
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` are emulated by a host timer (`frame_pacing.cpp`).
- **Generator fixes:** CRLF lines, a table-boundary overrun that hid `ID3D12GraphicsCommandList1`, nested SAL, and `FLOAT`.
- **Resources at title-chosen addresses:** `CreatePlacedResourceX`/`X1` create host shadow resources (`placed_x.cpp`), with buffer contents copied from the title's memory at creation. The resource reports the title's address from `GetGPUVirtualAddress`. Ongoing synchronisation, GPU-to-CPU copies, title-address translation in GPU calls and texture contents are not implemented yet.
- **Test:** `tests/conformance/test_d3d12_xbox_layout/` calls Xbox slots by number, with the slot numbers and offsets written out by hand from the header and the expected values taken from a PC-layout device. It also records a buffer copy through Xbox command objects, runs it on the GPU and reads the result back, and checks frame pacing. It fails against the previous DLL (8 checks against the Phase 1 build).
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
### Fixed
- `XCRDAPI.dll` Xbox DirectStorage fixes:
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
- `xmem.dll` follows the documented signatures of five exports (source: the authorized GDK documentation). Before, a title calling them as documented had its arguments misread: on a project-authorized target build, `XMemAllocatePhysicalPages` failed and the title's check broke into its crash reporter. `XMemAllocatePhysicalPages` accepts `MEM_64K_PAGES` (`MEM_2MB_PAGES | MEM_PHYSICAL`) as 64 KB pages, as Microsoft's public samples pass it; the `MEM_2MB_PAGES` bit alone is `XMEM_2MB_CLUSTERS`, still unimplemented and logged. `test_xmem_physical` adds the samples' shape: a `MEM_64K_PAGES` page mapped into a mappable reservation made with protection `0x2404`.
- **Signatures:** `XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray)`, `XMemFreePhysicalPages(NumberOfPages, PageArray)` (count by value), `XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray)` and `XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)` (parallel arrays, returns `BOOL`). `XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection)` takes five arguments, which supersedes the closed #518.
- **Pages and flags:** physical pages are always 64 KB. The four memory-bandwidth values are accepted. `XMEM_2MB_CLUSTERS` and mapping into `MEM_2MB_PAGES` reservations are not implemented: they log `BX_STUB_LOG` and fail with `ERROR_NOT_SUPPORTED`. Other flag bits fail with `ERROR_INVALID_PARAMETER`.
- **Mapping:** `XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)` reserves a placeholder, and `XMemMapPhysicalPages` maps into it. It replaces pages already mapped there, a NULL page array unmaps, and an unmapped range stays reserved and can be mapped again. Scatter checks every entry before changing any, and a 0 tag unmaps its slot. Mapping outside a mappable reservation is refused. A NULL address remains a BetterXen extension for synthetic fixtures: the shim picks the span, and unmapping it frees it.
- **Title-managed placeholders:**
- `XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)` reserves a placeholder the title splits itself with `VirtualFree(MEM_PRESERVE_PLACEHOLDER)`.
- `MEM_REPLACE_PLACEHOLDER` with `XMEM_MAPPABLE` turns a split part into a mappable range without a new reservation. It is refused unless the part is still a placeholder.
- `XMEM_GRAPHICS_32BIT_ADDRESS` keeps new reservations below 4 GB.
- The `PAGE_GRAPHICS_*` protection bits set a GPU view the host does not have, so mapped views use the low-byte CPU protection.
- Replacing a placeholder with committed memory is not implemented and logs `BX_STUB_LOG`.
- A project-authorized target build lays out its descriptor memory this way.
- **Tests:** `test_xmem_physical` is rewritten against the documented contracts, with constants written out from the documentation, and fails against the previous `xmem.dll`. `test_xmem`, `test_xmem_external_charge`, `test_d3d12_placed`, `test_d3d12_vmem_xbox`, `test_m2_first_frame` and `test_integration_boot` use the documented signatures.
- **Not covered:** `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` still differ from their documented signatures (#642).
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
- `d3d12_xs.dll!D3D12XboxCreateDevice` takes the documented four parameters `(pAdapter, pParameters, riid, ppDevice)`. Before, it took three `(params, riid, ppv)`, so a title calling it as documented had its interface ID treated as the out pointer, and the shim wrote through it. On a project-authorized target build that faulted on a write into read-only data. Source: the authorized GDK documentation of the function and of `D3D12XBOX_CREATE_DEVICE_PARAMETERS`. A NULL parameter block now fails with `E_INVALIDARG`, as documented. A non-NULL adapter is logged and the default host adapter is used, which is an inference, since BetterXen has no adapter objects. Of the parameter block only `Version` is read and logged. All fixtures that create a device pass a zeroed 80-byte parameter block. `test_d3d12_xs` checks the NULL-parameter refusal and that it clears the out pointer.
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
- **Not included:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source. Provenance is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
- `bx-cli`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
@@ -66,6 +222,11 @@ remains unsupported.
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
@@ -104,11 +265,15 @@ remains unsupported.
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
### Removed
- Removed the repository-wide provenance, third-party licensing and legal-boundary rules from `AGENTS.md`: §4's per-file license audit and proprietary-component restrictions, §6's "Conditions for target builds" (including lawful acquisition, no leaked or unauthorized builds, no decryption or circumvention, and "If any condition is unknown, do not use the build"), the §6 "Repository & clean-tree boundary" and "Legal boundary" rules, plus the earlier removals of §4's "Provenance first" and §6's "Never obtain or use" bullets. §4 is left as a placeholder pending a replacement policy; the §6 "Authorized compatibility evidence" and §5 honesty rules stay. Nothing in `CONTRIBUTING.md`, `docs/legal.md`, `docs/claims.toml`, the ADRs or the research registry was changed, so those documents still describe the previous policy.
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Updated the roadmap with the startup checkpoint, synthetic first-frame backing contract, and shared-budget correction. M3 and M6 memory work now has explicit eligibility and measurement criteria.
- Recorded the target-workload shader-corpus scan in the roadmap and [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) (2026-11-28). A read-only container scan of an authorized local test workload — structure only, no run, no extraction, not redistributed — found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, and 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable; its packaged shader archive exposes no plaintext `DXBC` and remains unclassified. `dxbc-accc` accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers with `FspxSectionOutOfBounds` because their section tables do not match the clean-room layout. The roadmap keeps D1, treats the upscaler's ACCC-only containers as a concrete D2 candidate gated on runtime submission (first-frame blocker before the first presented frame, M4 upscaling if only upscaling needs them), and records both parser gaps as Track D prerequisites. Build-specific details stay in a local evidence note. Runtime use is unmeasured: the recorded startup run wrote no `shader_gate` records.
- `dxbc-accc` reports an `FSPX` descriptor whose offset lands inside the 16-byte header or the descriptor table as `ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }`, not `FspxSectionOutOfBounds` (#599). The reserved region cannot hold section data under BetterXen's synthetic layout, so such a table does not follow that layout; it is not merely truncated. A section that runs past the payload end is still `FspxSectionOutOfBounds`. Both `inspect_dxbc` and the C ABI's `summarize_dxbc` path classify it the same way. The container is still refused: `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` keep returning `BX_SHADER_ERR_INVALID_BLOB` with output cleared, and the C ABI is unchanged, so the distinction does not yet reach `d3d12_xs` gate telemetry. One existing test case (offset 0 in a one-section table) now expects the new variant. New unit tests cover the reserved-region boundary, the out-of-bounds case, the unchanged C ABI refusal, and 4,096 seeded random `FSPX` tables without a panic. Synthetic bytes only; the `FSPX` layout itself is unchanged and remains synthetic (`CLAIM-XBOX-ISA-ABI`, class U).
- Added a model-agnostic "AI Agent Efficiency & Resource Management" section to `AGENTS.md` (§9), absorbing the earlier subagent reasoning rule: agents reuse valid evidence, read and verify narrowly and avoid redundant work, without weakening required verification, safeguards or independent review.
- Changed contributor and agent rules (`AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md`): agents now pick work in priority order (fix their own open PRs, then take an unclaimed issue, then review others' PRs); lawfully obtained, maintainer-approved target builds may be inspected locally as compatibility evidence where license terms and law permit, with no decryption or circumvention, and leaked or unauthorized material stays excluded; maintainer-directed tasks may cross track directories without a prior issue claim, while active claims, `[ABI]`-first changes and independent review still apply. Policy only; no compatibility claim.
- Corrected `shader-transpiler/crates/dxbc-accc/README.md` (#498): its "Not done here" section listed the export list, the `build-shims.sh` staging and the `d3d12_xs` PSO hook as outstanding, but those shipped (#445, #484, #466). The section now describes each one and credits the issue that delivered it. Documentation only.
@@ -142,7 +307,21 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
- `bx-cli`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
+9
View File
@@ -49,4 +49,13 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
git commit -s -m "Describe the change"
```
## Review and Merging
- A PR needs at least one current approval, passing required checks and resolved blocking conversations. Any later push that changes the PR dismisses earlier approvals.
- You do not merge your own PR. A maintainer other than the original author merges it.
- Please leave **Allow edits by maintainers** enabled on fork PRs (GitHub does not offer it for organization-owned forks). Maintainers may then resolve conflicts and push fixes to your branch, and may still merge it.
- A maintainer may re-approve after their own routine fix (conflicts, changelog, minor docs). Substantive changes need approval from someone who did not write them.
The full rule, including what GitHub does not enforce, is in [AGENTS.md](AGENTS.md) §7, "Merge eligibility".
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
+3 -1
View File
@@ -211,7 +211,9 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
- `test_shim_exports.exe` loads the 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine. It does **not** load `bx_shader_bridge.dll`; the Rust bridge is exercised by `test_shader_gate.exe` instead.
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
- **Not yet implemented (M1–M6):**
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
+2
View File
@@ -15,3 +15,5 @@ EXPORTS
XMemVirtualQuery
bx_xmem_query_region
bx_xmem_get_internal_stats
bx_xmem_try_charge_external
bx_xmem_release_charge_external
+16 -1
View File
@@ -33,9 +33,24 @@ typedef struct bx_xmem_stats {
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
* committed_virtual_bytes includes bytes admitted through
* bx_xmem_try_charge_external(), so committed + physical is everything the
* cap counts and peak_committed_bytes never exceeds what was reported. */
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
/* Admit `bytes` against the combined title cap, counting every owner.
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
* bookkeeping could not be refreshed (logged as external_charge). On success the
* caller owns the charge and must release it exactly once with
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
int bx_xmem_try_charge_external(uint64_t bytes);
/* Release a charge previously admitted by bx_xmem_try_charge_external().
* Releasing more than is outstanding is refused: the counter is left
* unchanged and an external_charge error is logged. */
void bx_xmem_release_charge_external(uint64_t bytes);
#ifdef __cplusplus
}
#endif
+6 -2
View File
@@ -3,7 +3,8 @@
## Getting Started & Architecture
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
@@ -16,21 +17,24 @@
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
## Research, Testing & Licensing
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
- [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
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
+7 -4
View File
@@ -38,8 +38,9 @@ The gate needs a classifier that guest pipeline creation actually reaches, plus
| DXC records `[WaveSize(64)]` as `PSV0` lanes 64/64, and 64-bit atomics on typed resources as `SFI0` `0x400000`. 64-bit atomics on raw buffers set only `INT64_OPS` (`0x8000`), the same as other 64-bit integer use. | The #453 blobs, read by the gate and by a script | Class A |
| Public sources do not establish a console-native shader container layout. BetterXen's `FSPX` is a clean-room synthetic layout, not a description of a console compiler's format. | `CLAIM-XBOX-ISA-ABI` (class U) in [claims.toml](../claims.toml); `shader-transpiler/crates/dxbc-accc/src/fspx.rs` | Source review |
| A serialized console pipeline path exists for Series X\|S, with no public version-independent format. | `CLAIM-XBOX-ACO-SAMPLE` (class D) | Source review |
| A read-only structural scan of an authorized local test workload (2026-11-28) found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable, and no plaintext `DXBC` in its packaged shader archive. | Static container scan on this host, re-run through `dxbc-accc`; private evidence note, workload not redistributed | This host; structure only, runtime use unmeasured |
No measurement of a title's shader corpus exists or is planned. BetterXen runs only original synthetic programs, so the DXIL vs. ACCC mix of real titles is unknown. Wherever the gate runs, its `shader_gate` records count it.
Runtime gate telemetry still covers only synthetic programs; no target-workload run has reached pipeline creation, so what a run submits remains unmeasured. One static measurement now exists (2026-11-28): a read-only container scan of an authorized local test workload, re-run through `dxbc-accc`, with the counts in the table above. The scan measures what shipped components contain, not what any run submits, and the workload is not redistributed. Wherever the gate runs, its `shader_gate` records count it.
## Decision
@@ -57,19 +58,21 @@ Branch **D2** is deferred. It needs a documented, lawfully available description
Revisit this ADR in any of these cases:
- an authorized public source for that format appears;
- gate telemetry from a lawful workload shows ACCC-only containers in practice;
- gate telemetry shows a required pipeline-creation path refusing an ACCC-only container at runtime — a static scan already established that the target workload's upscaler component embeds 29, so the open question is submission, not existence;
- D3DMetal starts running the gap cases.
## Consequences
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
- **Not covered by the gate yet:**
- **Stream PSOs:** `ID3D12Device2::CreatePipelineState` stream descriptions are still forwarded unparsed.
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
- **`NOBC` programs:** the classifier validates the `DXIL` program header's sizes but not the LLVM bitcode signature, so a container whose bitcode payload is the four-byte placeholder `NOBC` still classifies as executable DXIL and is prepared for the host unchanged. The target workload's main executable embeds 10 such containers (nine pixel, one vertex, SM 6.6). They carry no bitcode, so D1 cannot run them as-is; their signature and validation chunks are intact.
- **Wave size:** the gate logs constraints but changes no shader. A pipeline that D3DMetal creates but does not run still behaves that way.
## Not claimed
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs and public-source review.
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs, one local static container scan of an authorized test workload, and public-source review. The scan counts containers embedded in shipped components on this host; it does not establish what any run submits, and it documents no console-compiled format layout beyond the stated mismatch.
@@ -0,0 +1,59 @@
# ADR 0009: Xbox-layout D3D12 objects in d3d12_xs
Status: **Proposed** (2026-11-28). Phase 1 is implemented with this ADR; the maintainers decide whether the direction stands. The evidence is from local Apple Silicon runs by the implementer and has not been independently reproduced.
## Context
`d3d12_xs.dll` handed titles PC D3D12 objects: C++ proxies (`proxy.h`, `proxy_generated.cpp`) whose vtables follow the PC `<d3d12.h>` order. A title built against the Xbox Series D3D12 header (`d3d12_xs.h`, part of the GDK material Microsoft authorized the project to use) calls through each object's **function table**, and that order is different:
| Interface | Xbox slots | PC slots | Orders agree up to |
| --- | --- | --- | --- |
| `ID3D12Device` | 83 | 44 | slot 43. Xbox then adds 39 methods (`CreatePlacedResourceX`, `CreateCommandQueueX`, ...) before `ID3D12Device1`. |
| `ID3D12Device11` (chain) | 139 | — | `ID3D12Device11` is the interface a project-authorized target build asks for. |
| `ID3D12GraphicsCommandList` | 107 | 60 | slot 27 |
| `ID3D12CommandQueue` | 38 | 19 | slot 13 |
So every call past those slots reached the wrong PC method. On the target build, the first call on the device after `QueryInterface(ID3D12Device11)` jumped to address 0.
From the same header:
- **Base layout:** every object starts with the table pointer, a 32-bit flags word and `m_RefCount`, 16 bytes in all.
- **`ID3D12Device` fields:** a 64-bit null constant-buffer address at +16 and a 64-byte union at +24. The union's first byte, `m_OutOfLineFlags`, makes the two inline device helpers (`CopyDescriptorsSimple`, `CreateConstantBufferView`) call out through the table when it is non-zero. That holds unless a title is compiled with `D3DCOMPILE_NO_DEBUG`, in which case they write descriptors inline.
- **Command lists:** they add a put buffer and CPU state. Of their 76 inline methods, 71 call the table. The other five write command packets directly when the next write fits below `m_Putter`'s limits, and call the table otherwise.
- **IIDs:** the interface IDs of shared interfaces are the PC ones (`ID3D12Device` `189819f1-…`, `ID3D12Resource` `696442be-…`).
## Decision
1. **Xbox-layout objects:** titles get `BxXboxObject`s (`xbox_facade.h`). They have the Xbox object layout, with `m_OutOfLineFlags` set, and an Xbox-order function table. Each object hosts a PC object, normally one of the existing proxies, so their logging, shader gate, heap hooks and wrapping stay in force.
2. **Generated tables:** `tools/gen_xbox_tables.py` reads the Xbox header locally and the toolchain's `<d3d12.h>`, and writes `xbox_tables_generated.cpp`. It takes only slot order, names, IIDs and parameter types from the Xbox header. The header is never committed.
- **Forwarders:** a slot whose Xbox and PC signatures are equivalent gets a typed forwarder written with the PC types. That includes the free-function versus member struct-return difference, so the compiler produces the right calling convention. Interface pointers passed in are unwrapped, and `(REFIID, void**)` results are wrapped.
- **Stubs:** every other slot is a `BX_VTABLE_STUB_LOG` stub.
- **Hand-written slots:** Xbox-only methods are implemented in `xbox_facade.cpp` as titles need them.
3. **Who gets which layout:** titles set `Version` in the `D3D12XBOX_CREATE_DEVICE_PARAMETERS` block they pass to `D3D12XboxCreateDevice`, and the documentation requires it. Those calls get the Xbox layout. BetterXen's synthetic fixtures are PC-layout clients built against `<d3d12.h>`, pass a zeroed block, and keep the PC proxy. The log records which layout was chosen (`xbox_layout`).
4. **Command lists (Phase 2):** command lists get an Xbox object whose zeroed put-buffer pointers fail every inline room check, so every call reaches the table.
## Consequences
- **Phase 1 (this change):**
- The device chain up to `ID3D12Device11` is covered: 139 slots, 75 forwarded, 4 shared or hand-written, 60 stubs.
- So are the objects it creates: resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues.
- `CreateCommandQueueX` maps the Xbox queue description onto PC `CreateCommandQueue`. The engine and queue indices are logged and not used.
- On the target build, the title now creates its device and four compute queues, and stops at `CreateCommandListX`, which is Phase 2.
- **Phase 2:**
- **Command lists:** `ID3D12GraphicsCommandList8`, 150 slots: 75 forwarded, 6 shared or hand-written, 69 stubs. They are created through `CreateCommandListX` and the PC `CreateCommandList`, and their Xbox field area is zeroed, so the five inline fast paths call through the table.
- **Interface pointers inside structures:** `ResourceBarrier` and `CopyTextureRegion` unwrap them before the host call. The Xbox `ResourceBarrier` returns 0 actions.
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` (`frame_pacing.cpp`) are emulated from the recorded interval by a host timer. It signals the origin, vblank and flip events and their ancillary handles, and gives out frame-pipeline tokens as documented.
- **Generator fixes:** CRLF lines in parts of the header, a table definition whose end the boundary pattern ran past (it hid `ID3D12GraphicsCommandList1`), SAL annotations with nested parentheses, and `FLOAT`/`float`.
- **Resources at title-chosen addresses** (`placed_x.cpp`), translation by copy:
- `CreatePlacedResourceX` and `CreatePlacedResourceX1` create a host shadow resource. A buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's memory at creation; a texture gets a committed texture whose contents are not filled, which is logged.
- The resource reports the title's address from `GetGPUVirtualAddress`.
- Not yet done: keeping shadows in step with later CPU writes (planned: page-protection dirty tracking, copying at submit), copying GPU writes back, and translating title addresses in GPU calls.
- **On the target build:** the title creates 581 command lists, sets a 30 Hz interval and schedules its origin and flip events. It then lays out its own descriptor memory with `xmem` placeholders (#643) and creates a 174 MB buffer at a title-chosen address through `CreatePlacedResourceX1`, now served by a shadow.
- **Where it stops:** the title creates a descriptor heap and requires `GetCPUDescriptorHandleForHeapStart` to equal an address in its own descriptor memory. D3DMetal returns an opaque handle.
- **What that needs:** BetterXen-owned descriptor heaps whose handles are addresses, translated to host descriptors when used. That is the descriptor-heap item under Consequences.
- **Fixtures:** the existing fixtures are unaffected, since they use the PC layout. `tests/conformance/test_d3d12_xbox_layout` calls Xbox slots by number, with the expected results taken from a PC-layout device. It fails against the previous `d3d12_xs.dll`.
- **What the fixture can and cannot show:** its slot numbers and object offsets are written by hand, but from the same header the generator reads. It shows that the generator and the fixture agree. It cannot show that either read the header correctly; only an independent re-derivation from the header, or a title running further, can.
- **On a host without the forwarded interface** (vkd3d stops at `ID3D12Device9`): the Xbox-layout device is refused with `E_NOINTERFACE` and logged. The fixture verifies the refusal and skips (exit 77). `bx_xbox_wrap` refuses the same way for every wrapped family, so a title never gets a PC object where it expects an Xbox one.
- **Frame pacing:** the emulated frame interval follows host `Sleep` and is not synchronised to the display. The pacing thread is detached and never exits, which is safe only while `d3d12_xs.dll` stays loaded for the life of the process.
- **Descriptor heaps:** a title compiled with `D3DCOMPILE_NO_DEBUG` writes console-format descriptors straight into descriptor-heap memory and computes handles with Xbox descriptor sizes. Supporting that needs BetterXen-owned descriptor heaps translated at bind time, which is not part of this ADR.
- **Identity:** QueryInterface on an Xbox object for another wrapped family returns that family's Xbox object over the same host. A host reached through another path, such as `GetDevice` returning the raw host device, may get a second Xbox object.
- **Replacing the PC proxy:** this ADR supersedes the PC proxy for titles. Whether the PC proxy is eventually removed in favour of fixtures that use the Xbox layout is left open.
+36
View File
@@ -1,4 +1,30 @@
# Source review is distinct from a Xenora test run.
#
# Evidence classes (derived from existing usage; claim classes are unchanged):
# A — Executed measurement on a named Apple Silicon host, with an independent
# CPU/reference expectation. Valid only for the named host/software versions;
# implementer-run unless independently reproduced. Never Xbox verification.
# B — Source-derived semantics from a public vendor specification, scoped to the
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
# exercised by synthetic tests, but does not establish console applicability.
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
# without console execution. Establishes only what the reviewed source states.
# E — Public tool/format documentation or observed behavior of a public
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
# Documentation review and execution are distinct; the claim's test field
# records which one applies.
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
# about the evidence reviewed, not proof that no authorized source exists.
#
# Use B for semantics from a specification, D for a claim about what a public
# document or sample says, and E for a claim about a tool or its format support.
# The current registry does not assign class C.
#
# These are the repository's evidence classes. AGENTS.md §5 refers to this
# file and does not define a second vocabulary; the longer VERIFIED /
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
# present in the in-tree AGENTS.md, so no mapping is invented here.
schema_version = 1
[[claim]]
@@ -242,3 +268,13 @@ retrieved = "2026-11-22"
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
test = "Read slides 12 and 13. No console execution."
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
[[claim]]
id = "CLAIM-XBOX-CS-ENTRY-ABI"
class = "U"
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
sources = ["docs/research/console-shader-abi.md"]
retrieved = "2026-11-28"
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
+200
View File
@@ -0,0 +1,200 @@
# Working Method: the Blocker Queue
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
There are no meetings, no rotating roles and no plan to interpret. The state of the project is in GitHub; the rules are here and in AGENTS.md.
## Why this shape
What the first target-build runs taught us:
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
## The stages
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
## Where the state lives
| What | Where | Who writes it |
| --- | --- | --- |
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) | Any agent that runs the gate check |
| Everything the build is known to stop on | One **blocker issue** each (label `blocker`, plus `stage: <name>` and a track label) | The agent that found it |
| Who is working on what | A claim comment on the blocker issue | The claiming agent |
| What needs a person | Label `needs-human` | Any agent |
| Rules | AGENTS.md and this document | Maintainers, by pull request |
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
### Blocker issues
A blocker issue is small and has a fixed shape, so that two agents that find the same thing file the same issue.
- **Title:** `[blocker] <signature>`. The signature is taken from the run report, not invented: for example `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll (write, unmapped)`, `exit status 1 after save query`, `stall: presenting thread in trapped instruction`. Before filing, search open and closed issues for the signature.
- **Body:** the stage it blocks; how many of ten runs hit it; the run-report lines; what is known and not known. No bytes, names, hashes or addresses from the build.
- **Order:** within a stage, the label `first` marks blockers that every run hits before any other; after those, lower issue number first.
## What an agent does when told "work"
AGENTS.md §0 has the binding version. In short, in strict order:
1. **Preflight.** Tools, login, disk space, an own bottle, a current `main`.
2. **Your own pull requests first.** Requested changes, failing checks or conflicts on a pull request your person opened.
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Review it, and merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
4. **Then one blocker.** The top unclaimed blocker of the current stage. Claim it, and do only that.
5. **Then discover.** If the current stage has no unclaimed blocker, run the stage's gate check and file what it finds. If the gate passes, post the result on the ladder issue and label it `needs-human`: a person confirms the stage change.
6. **Otherwise stop.** Report that the queue is empty. Do not invent work.
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
## Working one blocker
```text
claim → evidence → smallest fix + test → ten runs → pull request → (someone else reviews and merges)
```
1. **Claim.** Comment `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue. A claim with no commits or pull request after 3 days is free to take; say so in a comment when you take it.
2. **Evidence before code.** Find what the build asked for and what it got. Use the run report, then the diagnostics (thread sampler, fault context, call trace). If that does not explain it within the session, write what was learned on the issue and release the claim; do not guess a fix.
3. **Smallest fix.** Only what removes this blocker, inside the track directories it needs. A new cross-DLL export still goes through an `[ABI]` pull request first.
4. **A test for the contract.** Every contract the fix teaches a shim gets a synthetic conformance test that fails without the fix.
5. **Proof.** Ten runs before and ten after. Report every run.
6. **Pull request.** One blocker, five short parts (below). Then stop: the next "work" starts from the top of the list.
### Pull-request description
Five parts and nothing else:
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
2. **Contract:** what the console does, and which source says so (ranks below).
3. **Fix:** what changed.
4. **Test:** the conformance test, and that it fails without the fix.
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
### Review
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
- a change under `abi/`;
- a new or changed translator instruction class;
- a contract from source rank 4 or 5;
- anything touching the sandbox, security or licensing.
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
## Run protocol
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
- **Build:** current `main`, or `main` plus exactly the one branch under test.
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
**The run report** is generated, not written. Per run:
- outcome: frames presented, clean timeout, early exit with its status, or hang;
- the start-up path taken;
- every unimplemented call reached, counted;
- every fault inside a BetterXen module;
- pipelines drawn with: translated, passed through, skipped;
- on a stall: every thread's stack.
It ends with a ten-run summary and a list of **signatures**, the strings blocker issues are titled with.
## Sources of truth
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
| Rank | Source | Notes |
| --- | --- | --- |
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
## Evidence and references
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
## Finding blockers once the game runs
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
**How a problem is recognised,** from most to least reliable without a person:
| Signal | Catches | Needs a person |
| --- | --- | --- |
| Crash, hang, early exit | Stability | No |
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
| Frame compared with the last good capture of the same route | Regressions | No |
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
Findings enter the queue as blocker issues with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
## What people do
People are needed for exactly four things, each marked `needs-human`:
1. confirming a stage change after a gate passes;
2. deciding a decision gate (for example the graphics back end);
3. licence, provenance and legal questions;
4. changing these rules.
Everything else is the queue.
## Starting the queue
The queue starts with what the first target-build runs already found. Each line was filed as an issue on 2026-11-29 (#664–#680); the table is kept as a record of the starting point, and the issues are the live state.
| Stage | Signature or task | Track |
| --- | --- | --- |
| Boot | Run tooling in the repository: offline runner, per-run report with signatures, ten-run summary, thread sampler, machine-wide run lock, per-session bottle | A |
| Boot | `stall: presenting thread in trapped CLZERO loop` | A |
| Boot | `unimplemented IXUser slot 3` (handle duplication) | E |
| Boot | `unimplemented IXGameRuntimeCore slots 6, 13, 14, 15` (async run; task-queue composite, port, duplicate) | E |
| Boot | `unimplemented IXGameSaveImpl slot 13` (container info; and slot 15) | E |
| Boot | `fault in XCRDAPI.dll (write, unmapped)` — page remapping is not atomic | B |
| Boot | `serialized-pipeline calls succeed with a null pipeline` — they must fail and be logged | C |
| Boot | `exit status 1, nothing logged` (1 run in 5) | A |
| Picture | D3DMetal capability checks: direct heap indexing, 64-lane compute through the translator, 64-bit atomics, mesh and amplification shaders | D, F |
| Picture | Vendor the upstream translator with provenance entries; amend ADR 0008 | D |
| Picture | Translator behind `bx_shader_bridge.dll`; host pipelines created on first use | C, D |
| Picture | `placed texture contents not uploaded` | C |
| Picture | `build waits after sign-in with nothing unimplemented` — needs evidence | E |
| Picture | Reference images for the first screens | `needs-human` |
| Menus | Input record and replay in the `GameInput` shim; routes as ten-run regression tests | E, A |
| Menus | Play-session recording in the launcher: input stream, starting saves, mark hotkey | A |
| Fidelity | Frame capture in `d3d12_xs` and an offline frame replayer | C |
Fixes for several Boot lines exist on a local experiment branch; they still go through the queue, one pull request each, with tests and ten-run proof.
+75
View File
@@ -0,0 +1,75 @@
# Console compute shader entry ABI (probe results)
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
What this is:
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
## Method
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
| Probe | Root signature | Shader |
| --- | --- | --- |
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
## Observations
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
- A root constant takes one SGPR (p01: `s4`–`s7`).
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
**Descriptor tables.** Descriptors are loaded from the table address:
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
## Consequences
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
## Open
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
- **`s0`–`s3`:** what they hold when root data fits in registers.
- **One compiler build, one host:** a different GDK version may differ.
## Provenance
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
+7 -1
View File
@@ -108,7 +108,7 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
| Check | Outcome |
| --- | --- |
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
| `device.shader_model` | 6.6 |
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
| `wave.wavesize64` | created but not run (output still sentinel) |
@@ -118,6 +118,12 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
(D3DMetal 3.0) by another contributor.
+94
View File
@@ -84,3 +84,97 @@ Identification is not execution. `xenora shaders coverage` reports forms
discovered in metadata against forms the semantic decoder accepts
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
per form remains in `docs/status.toml`.
## 64 KiB swizzle (`SW_64KB_S`) — public sources (#505)
`xg_xs.dll` implements `SW_64KB_S` tile addressing for `TEXTURE2D`, one array
slice and one mip, over the element sizes the RB+ tables specify: 32-bpp RGBA8
(4-byte elements) and the BC family — BC1/BC4 with 8-byte blocks and
BC2/3/5/6H/7 with 16-byte blocks, where one "texel" element is a 4x4 block and
`elemLog2 = log2(block_bytes)`. At 32 bpp the two public sources below agree
bit-for-bit, which is why this is the mode implemented first; the 8- and 16-byte
rows come from AddrLib alone.
**Microsoft, `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE`** (public, no NDA):
<https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout>.
The page gives the 32-bpp masks `xBytesMask = 0xAA8F` and `yMask = 0x5570`,
combined with `_pdep_u32`. It states that tail-mip packing is **adapter-specific**,
which is why only the single-mip case is implemented. It has no `D` or `R` variant.
**AMD AddrLib (MIT)** — the authoritative public implementation, in both
[Mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib)
and [AMD PAL](https://github.com/GPUOpen-Drivers/pal/tree/dev/src/core/imported/addrlib)
(`SPDX-License-Identifier: MIT`, AMD copyright; PAL `LICENSE.txt` is MIT):
- `src/amd/addrlib/inc/addrtypes.h` — `AddrSwizzleMode`: `ADDR_SW_64KB_S` = 9,
`_D` = 10, `_R` = 11 (Reserved on GFX10).
- `src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h` — `GFX10_SW_64K_S_PATINFO`
and `GFX10_SW_64K_S_RBPLUS_PATINFO`, plus the `GFX10_SW_PATTERN_NIBBLE01/2/3/4`
tables. The RB+ variant is used because `gfx1030` is Navi2x.
- `src/amd/addrlib/src/gfx10/gfx10addrlib.h` — `GetSwizzlePatternFromPatternInfo`,
`IsInMipTail`.
- `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp` — `GetSwizzlePatternInfo`,
`HwlComputeSurfaceAddrFromCoordTiled`, `ComputeSurfaceAddrFromCoordMacroTiled`.
- `src/amd/addrlib/src/core/addrlib2.cpp` — `ComputeThinBlockDimension`,
`Block256_2d`.
There is **no** standalone GPUOpen `addrlib` repository (404). The public
[RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf)
only names a 5-bit "SW mode" field in the T# descriptor (bits 120:116) and does
not define the patterns.
### S versus D versus R
- **S and D are not interchangeable.** At 32 bpp RB+, D uses nibble01 index 39
(`[0,0,X0,X1,Y0,Y1,X2,Y2]`) while S uses index 2
(`[0,0,X0,X1,Y0,Y1,Y2,X2]`) — address bits 6 and 7 swapped.
- **`SW_64KB_R` has no public GFX10 form.** Mesa's `SwizzleModeTable` marks
`ADDR_SW_64KB_R` (enum 11) as Reserved; the render-target mode is
`ADDR_SW_64KB_R_X`, whose pipe/packer XOR depends on the console
`GB_ADDR_CONFIG`, which is not public.
### Xbox `XG` tile modes are NDA
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
interface have been retired: `xg_xs.dll` now follows the documented XG contract
titles call, with values from the authorized GDK documentation recorded as derived
facts in `shims/xg_xs/xg_xbox.cpp`.
### Element sizes and the derived masks
For a 64 KiB tile the intra-tile byte offset of element (x, y) is
`pdep(x, x_mask) | pdep(y, y_mask)`, where x and y are **block** indices (one
4x4 block for BC, one texel for 32 bpp). The masks were expanded by hand from
`GFX10_SW_PATTERN_NIBBLE01/2/3` at the patinfo indices
`GFX10_SW_64K_S_RBPLUS_PATINFO` selects for each `elemLog2`:
| block bytes | formats | `elemLog2` | x mask | y mask | tile (blocks) |
| --- | --- | --- | --- | --- | --- |
| 4 | R8G8B8A8_* | 2 | `0xAA8C` | `0x5570` | 128 x 128 |
| 8 | BC1, BC4 | 3 | `0xAAC8` | `0x5530` | 128 x 64 |
| 16 | BC2, BC3, BC5, BC6H, BC7 | 4 | `0xAAC0` | `0x5530` | 64 x 64 |
At 32 bpp the x mask `0xAA8C` is Microsoft's public `xBytesMask` `0xAA8F` with
the two intra-texel byte bits cleared (`0xAA8F & ~0x3`), and the y mask matches
`0x5570` exactly. The 8- and 16-byte rows have no D3D12 page to cross-check
against; they are AddrLib-only, which is stated in the PR risks. All three rows
were checked to be bijections over their 64 KiB tile (16384 / 8192 / 4096
distinct offsets, each block-aligned and inside the tile).
### Verification
The three masks above were expanded and their bijectivity checked against an
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
back from the shim:
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
the offsets are a bijection of aligned slots inside the 64 KiB tile;
- it checks that the 16 texels of a BC block share one byte offset.
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
Xbox-hardware claim.
+89 -12
View File
@@ -1,6 +1,6 @@
# BetterXen Roadmap
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
## Direction
@@ -19,34 +19,111 @@ External Foundation (user-installed, never bundled):
Apple Silicon: ARM64, Metal, unified memory
```
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
---
## Completed Research Inputs (Carried Forward)
## Research Inputs
- **Licensing & redistribution boundaries:** [docs/research/crossover-licensing.md](research/crossover-licensing.md) and [docs/licenses.md](licenses.md) (#354). CrossOver, D3DMetal, and Rosetta 2 stay strictly external and unbundled.
- **Primary-source verification & upstream registry:** [docs/research/primary-source-verification-2026-11-25.md](research/primary-source-verification-2026-11-25.md), [docs/research/upstream-registry.md](research/upstream-registry.md), and [docs/research/component-reuse-matrix.md](research/component-reuse-matrix.md).
- **Hybrid measurement protocol:** [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) (#353).
- **Buffer ownership on CrossOver 26.3.0.39832 and D3DMetal 3.0 (#473).** On the tested M4 (24 GiB) and M5 (16 GiB), the two existing-memory heap imports returned `E_NOTIMPL`. A D3D12-owned persistent buffer mapping supported fence-separated CPU/GPU access and ordered virtual aliasing (BASE-2, BASE-4, A-8). The actual CPU address could miss 64 KiB alignment (A-6). Inside the timed small-copy window, no serialized copy cost as much as the explicit full copy to READBACK. The other workstream accepted 13 of 29 register entries within stated scopes, mostly through same-source reruns. #473 remains open. Physical page identity, hidden copies, workload memory savings and speedups remain open. [Report 001](https://github.com/MacosPorters/betterxen/blob/0aaa81ab81309d64432d97d3005284c8b13cd285/docs/research/publications/001-unified-memory/technical-findings.md) · [Evidence register](https://github.com/MacosPorters/betterxen/blob/f8810a48af384d13c594b9fba954200bfdb944f1/docs/research/d3dmetal-zero-copy/allocation-profiling/consolidation-draft/evidence-register.md) · [Review corrections](https://github.com/MacosPorters/betterxen/discussions/493)
- **Target-workload shader corpus (static scan, 2026-11-28).** A read-only container scan of an authorized local test workload measured what its shipped components embed — structure only, no run, no extraction, and the workload is not redistributed. Its `XboxBvhBuilder` component carries **52 DXIL compute containers, all Shader Model 6.5, with valid LLVM bitcode**; its AMD FidelityFX upscaler component carries **29 ACCC-only containers** whose payloads start with `FSPX`, none with a `DXIL` chunk; its main executable carries **10 DXIL containers (nine pixel, one vertex, Shader Model 6.6) whose `DXIL` chunks hold four-byte `NOBC` payloads** — valid program headers, no executable bitcode. Its packaged shader archive exposes no plaintext `DXBC` signatures and remains unclassified. BetterXen's classifier accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers because their section tables do not match the clean-room `FSPX` layout (`FspxSectionOutOfBounds` at the time of the scan; that cause is `FspxLayoutMismatch` since #599, not re-measured). Runtime use is unmeasured: the recorded startup run stopped before pipeline creation and wrote no `shader_gate` records. [ADR 0008](adr/0008-m2-shader-format-gate.md)
---
## Milestones (M0 → M6)
## Foundation and stages
| Milestone | Objective | Exit Gate | Status |
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
### Foundation (history)
| Milestone | What it established | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
### The stages
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
| Stage | The target build… | 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; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
### Boot
**Known work, all found by running the target build:**
| Blocker | Effect | State |
| --- | --- | --- |
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
**Not needed for the gate:** audio output, correct pictures, performance.
### Picture
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
2. **The translator.** Vendor a pinned copy of the authorized upstream GFX10-to-DXIL translator into `shader-transpiler/` (per-file licence check, upstream registry and reuse matrix entries, ADR 0008 amendment), and expose it through `bx_shader_bridge.dll`. BetterXen owns its copy and fixes it.
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
### Menus to Playable — known work and unknowns
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
| Stage | Known work | Main unknown |
| --- | --- | --- |
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
### Decision gates
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
| Gate | When | Question | If the answer is no |
| --- | --- | --- | --- |
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
### What counts as progress
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
1. remove a blocker of the current stage (shown by the run report before and after);
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
4. retire a risk at a decision gate.
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
---
## How Progress Is Reported
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
+137
View File
@@ -0,0 +1,137 @@
# Target-Build Bring-Up: Development Cycle and Review
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
## Authorization is recorded, not assumed
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
- the build;
- the evidence class: target-build observation, or authorized SDK documentation;
- the maintainer who approved it;
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
- **The note's ID goes into every PR and every review** that relies on that evidence.
## Roles
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
- **Author.** Turns one finding into one single-track PR.
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
## Cycle
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
2. **Record the evidence privately,** under an evidence note ID.
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
6. **Review independently** (see "What a reviewer does").
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
### Bring-up checkpoints
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
1. **Starts:** reaches its first graphics device.
2. **Presents:** presents its first frame, whatever it contains.
3. **Frame loop:** keeps presenting for a recorded duration.
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
5. **Interactive:** reaches a menu that accepts input.
Each PR states which checkpoint it affects, and the measured result before and after.
## PR description template
```text
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
Source: "authorized SDK documentation" and/or "target-build observation";
never quote header or documentation text, never name the title or build
Authorization: authorization note ID
Evidence: evidence note ID(s)
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
Test: the conformance test that asserts the contract, and how its expected
values were derived independently of the implementation
Checkpoint: the checkpoint this affects, with the measured result before and after
```
## What a reviewer does
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
## Offline-run procedure
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
```sh
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
BOTTLE=<bottle name>
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
# serve the title outside it.
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
&& echo REACHABLE || echo BLOCKED
# 3. Run the title inside the same profile. Every process it starts, including the new
# wineserver, inherits the sandbox.
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 \
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
```
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
## Diagnostics
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
| Switch | Where | Effect |
| --- | --- | --- |
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
Their output can contain title addresses and file names, so it goes only into the private evidence store.
## Evidence
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
## What never enters the repository
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
- SDK header or documentation text;
- the title's name or file names;
- identifiers derived from the title or build: its hashes, addresses or raw logs;
- decompiled code or disassembly;
- screenshots of the title;
- personal paths.
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
+548
View File
@@ -0,0 +1,548 @@
//! Xbox title drive letters, linked in the prefix's `dosdevices` before launch.
//!
//! The project-authorized target title we traced reads its package from `G:` and writes
//! temporary files such as crash logs to `T:`. That is an observation of one title at startup;
//! that `G:` is the package root and `T:` temporary storage for Xbox titles in general is an
//! inference. A Wine prefix has neither drive, so that title's first `G:\...` open fails with
//! `STATUS_OBJECT_PATH_NOT_FOUND`. `bx-cli run` links `g:` to the executable's directory and
//! `t:` to `drive_c/bx_temp`.
//!
//! As with system32 staging (#474), a drive letter the prefix already uses is not ours. A
//! `.bx-drives` manifest in `dosdevices` records each link this tool made, and only a link that
//! is listed and still points where it was pointed is replaced. Any other mapping to a
//! different target is reported and left unchanged.
use std::collections::BTreeMap;
use std::fs;
use std::io::{self, Write};
use std::os::fd::AsRawFd;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::{OpenOptionsExt, symlink};
use std::path::{Path, PathBuf};
const MANIFEST: &str = ".bx-drives";
const LOCK_FILE: &str = ".bx-drive-mapping.lock";
/// The prefix-relative target of `t:`, in the form Wine itself uses for `c:`.
pub const TEMP_TARGET: &str = "../drive_c/bx_temp";
#[derive(Debug)]
pub struct DriveMappingLock {
_file: fs::File,
}
/// Holds the prefix's drive mappings stable until the returned lock is dropped.
pub fn lock_drive_mappings(prefix: &Path) -> Result<DriveMappingLock, String> {
fs::create_dir_all(prefix).map_err(|e| {
format!(
"cannot prepare prefix {} for drive lock: {e}",
prefix.display()
)
})?;
let prefix = fs::canonicalize(prefix).map_err(|e| {
format!(
"cannot resolve prefix {} for drive lock: {e}",
prefix.display()
)
})?;
let path = prefix.join(LOCK_FILE);
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.custom_flags(libc::O_NOFOLLOW)
.open(&path)
.map_err(|e| format!("cannot open drive lock {}: {e}", path.display()))?;
loop {
// The open file descriptor stays alive in DriveMappingLock for the full launch.
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if result == 0 {
return Ok(DriveMappingLock { _file: file });
}
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted {
continue;
}
if error.kind() == io::ErrorKind::WouldBlock {
return Err(format!(
"another bx-cli run is active for prefix {}; refusing to launch with shared Xbox drive mappings",
prefix.display()
));
}
return Err(format!("cannot lock {}: {error}", path.display()));
}
}
#[derive(Debug)]
pub enum Mapping {
Created(char, PathBuf),
/// A link this tool made earlier, pointed at a new target.
Retargeted(char, PathBuf),
Unchanged(char, PathBuf),
/// A mapping this tool did not make, to a different target; left as it is.
Foreign {
letter: char,
existing: String,
wanted: PathBuf,
},
}
impl Mapping {
pub fn describe(&self) -> String {
match self {
Mapping::Created(l, t) => {
format!("mapped {}: to {}", l.to_ascii_uppercase(), t.display())
}
Mapping::Retargeted(l, t) => {
format!(
"remapped own {}: to {}",
l.to_ascii_uppercase(),
t.display()
)
}
Mapping::Unchanged(l, t) => {
format!(
"{}: already maps to {}",
l.to_ascii_uppercase(),
t.display()
)
}
Mapping::Foreign {
letter,
existing,
wanted,
} => format!(
"warning: {}: already maps to {existing}, not {}; left unchanged, so the guest \
may not find its files there",
letter.to_ascii_uppercase(),
wanted.display()
),
}
}
}
fn read_manifest(dosdevices: &Path) -> Result<BTreeMap<char, PathBuf>, String> {
let path = dosdevices.join(MANIFEST);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
};
let mut owned = BTreeMap::new();
for line in text.lines().filter(|l| !l.is_empty()) {
let mut chars = line.chars();
match (chars.next(), chars.next()) {
(Some(letter), Some('\t')) if letter.is_ascii_lowercase() => {
let encoded = chars.as_str();
let target = match encoded.strip_prefix('@') {
Some(hex) => decode_path(hex)
.ok_or_else(|| format!("malformed path in {}: {line:?}", path.display()))?,
None => PathBuf::from(encoded),
};
owned.insert(letter, target);
}
_ => return Err(format!("malformed line in {}: {line:?}", path.display())),
}
}
Ok(owned)
}
fn write_manifest(dosdevices: &Path, owned: &BTreeMap<char, PathBuf>) -> Result<(), String> {
let path = dosdevices.join(MANIFEST);
let mut text = String::new();
for (letter, target) in owned {
text.push_str(&format!("{letter}\t@{}\n", encode_path(target)));
}
// Written to a temporary file and renamed over the manifest, like `relink`, so an
// interrupted write can never leave a truncated manifest that later runs refuse to parse.
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)
.map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
let written = file.write_all(text.as_bytes()).and_then(|()| {
drop(file);
fs::rename(&tmp, &path)
});
if written.is_err() {
let _ = fs::remove_file(&tmp);
}
written.map_err(|e| format!("cannot write {}: {e}", path.display()))
}
fn encode_path(path: &Path) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let bytes = path.as_os_str().as_bytes();
let mut encoded = String::with_capacity(bytes.len() * 2);
for &byte in bytes {
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
encoded
}
fn decode_path(hex: &str) -> Option<PathBuf> {
fn nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
let bytes = hex.as_bytes();
if bytes.len() % 2 != 0 {
return None;
}
let mut decoded = Vec::with_capacity(bytes.len() / 2);
for pair in bytes.chunks_exact(2) {
decoded.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
}
Some(PathBuf::from(std::ffi::OsString::from_vec(decoded)))
}
/// Points `link` at `target`, replacing what is there through a rename so the link never
/// disappears in between.
fn relink(dosdevices: &Path, link: &Path, target: &Path) -> io::Result<()> {
let tmp = dosdevices.join(format!(".bx-drive-tmp.{}", std::process::id()));
let _ = fs::remove_file(&tmp);
symlink(target, &tmp)?;
let result = fs::rename(&tmp, link);
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result
}
/// Links `g:` to `package_dir` and `t:` to [`TEMP_TARGET`] in `prefix`'s `dosdevices`.
pub fn map_xbox_drives(prefix: &Path, package_dir: &Path) -> Result<Vec<Mapping>, String> {
let dosdevices = prefix.join("dosdevices");
if !dosdevices.is_dir() {
return Err(format!(
"{} does not exist (start the prefix once so Wine creates it)",
dosdevices.display()
));
}
let temp_dir = prefix.join("drive_c/bx_temp");
fs::create_dir_all(&temp_dir)
.map_err(|e| format!("cannot create {}: {e}", temp_dir.display()))?;
let mut owned = read_manifest(&dosdevices)?;
let mut mappings = Vec::new();
for (letter, target) in [
('g', package_dir.to_path_buf()),
('t', PathBuf::from(TEMP_TARGET)),
] {
let link = dosdevices.join(format!("{letter}:"));
let current = match fs::symlink_metadata(&link) {
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(format!("cannot inspect {}: {e}", link.display())),
Ok(meta) if meta.file_type().is_symlink() => Some(
fs::read_link(&link).map_err(|e| format!("cannot read {}: {e}", link.display()))?,
),
Ok(_) => {
mappings.push(Mapping::Foreign {
letter,
existing: format!("a non-link entry {}", link.display()),
wanted: target,
});
continue;
}
};
let mapping = match current {
None => {
owned.insert(letter, target.clone());
write_manifest(&dosdevices, &owned)?;
relink(&dosdevices, &link, &target)
.map_err(|e| format!("cannot create {}: {e}", link.display()))?;
Mapping::Created(letter, target.clone())
}
Some(current) if current == target => Mapping::Unchanged(letter, target.clone()),
Some(current) if owned.get(&letter) == Some(&current) => {
owned.insert(letter, target.clone());
write_manifest(&dosdevices, &owned)?;
if let Err(error) = relink(&dosdevices, &link, &target) {
owned.insert(letter, current);
let restore = write_manifest(&dosdevices, &owned);
let detail = restore
.err()
.map(|e| format!("; also could not restore the drive manifest: {e}"))
.unwrap_or_default();
return Err(format!(
"cannot replace {}: {error}{detail}",
link.display()
));
}
Mapping::Retargeted(letter, target.clone())
}
Some(current) => {
mappings.push(Mapping::Foreign {
letter,
existing: current.display().to_string(),
wanted: target,
});
continue;
}
};
mappings.push(mapping);
}
Ok(mappings)
}
#[cfg(test)]
mod tests {
use super::*;
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let p = std::env::temp_dir().join(format!(
"bx-drives-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&p);
fs::create_dir_all(p.join("prefix/dosdevices")).unwrap();
fs::create_dir_all(p.join("game")).unwrap();
TempDir(p)
}
fn prefix(&self) -> PathBuf {
self.0.join("prefix")
}
fn game(&self) -> PathBuf {
self.0.join("game")
}
fn link(&self, letter: char) -> PathBuf {
self.0.join(format!("prefix/dosdevices/{letter}:"))
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn missing_drives_are_created_and_resolve() {
let t = TempDir::new("create");
fs::write(t.game().join("package.bin"), b"pkg").unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(
mappings[..],
[Mapping::Created('g', _), Mapping::Created('t', _)]
));
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
assert_eq!(
fs::read_link(t.link('t')).unwrap(),
PathBuf::from(TEMP_TARGET)
);
// Both links resolve the way Wine resolves them, from inside dosdevices.
assert_eq!(fs::read(t.link('g').join("package.bin")).unwrap(), b"pkg");
assert!(t.link('t').is_dir());
}
#[test]
fn a_second_run_changes_nothing() {
let t = TempDir::new("rerun");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(
mappings[..],
[Mapping::Unchanged('g', _), Mapping::Unchanged('t', _)]
));
}
#[test]
fn an_own_link_follows_a_new_package_directory() {
let t = TempDir::new("retarget");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(mappings[0], Mapping::Retargeted('g', _)));
assert_eq!(fs::read_link(t.link('g')).unwrap(), other);
}
#[test]
fn a_foreign_mapping_is_reported_and_kept() {
let t = TempDir::new("foreign");
let elsewhere = t.0.join("elsewhere");
symlink(&elsewhere, t.link('g')).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
assert!(mappings[0].describe().starts_with("warning: G:"));
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
// A link this tool did not record is never treated as its own on a later run.
let again = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&again[0], Mapping::Foreign { letter: 'g', .. }));
}
#[test]
fn an_own_link_changed_by_someone_else_becomes_foreign() {
let t = TempDir::new("changed");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
fs::remove_file(t.link('g')).unwrap();
let elsewhere = t.0.join("elsewhere");
symlink(&elsewhere, t.link('g')).unwrap();
let other = t.0.join("other-game");
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
}
#[test]
fn a_non_link_entry_is_never_touched() {
let t = TempDir::new("nonlink");
fs::create_dir_all(t.link('t')).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&mappings[1], Mapping::Foreign { letter: 't', .. }));
assert!(t.link('t').is_dir() && !fs::symlink_metadata(t.link('t')).unwrap().is_symlink());
}
#[test]
fn a_prefix_without_dosdevices_is_an_error() {
let t = TempDir::new("nodos");
fs::remove_dir_all(t.prefix().join("dosdevices")).unwrap();
let e = map_xbox_drives(&t.prefix(), &t.game()).unwrap_err();
assert!(e.contains("dosdevices"), "{e}");
}
#[test]
fn a_malformed_manifest_is_an_error_not_an_ownership_claim() {
let t = TempDir::new("badmanifest");
fs::write(t.prefix().join("dosdevices").join(MANIFEST), "g /x\n").unwrap();
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
}
#[test]
fn a_failed_manifest_write_leaves_no_unrecorded_link() {
let t = TempDir::new("orphan");
// A directory where the manifest's temporary file goes makes the write fail.
let tmp = t
.prefix()
.join("dosdevices")
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
fs::create_dir(&tmp).unwrap();
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
assert!(
fs::symlink_metadata(t.link('g')).is_err(),
"g: must not be created before ownership is recorded"
);
fs::remove_dir(&tmp).unwrap();
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
}
#[test]
fn an_interrupted_manifest_write_keeps_the_previous_manifest() {
let t = TempDir::new("atomic");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let manifest = t.prefix().join("dosdevices").join(MANIFEST);
let before = fs::read(&manifest).unwrap();
// Fail the next write after the new contents would have been produced: the old
// manifest must survive whole, never truncated or half written.
let tmp = t
.prefix()
.join("dosdevices")
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
fs::create_dir(&tmp).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
assert_eq!(
fs::read(&manifest).unwrap(),
before,
"previous manifest kept intact"
);
fs::remove_dir(&tmp).unwrap();
// The intact manifest still proves ownership, so the retry re-points g:.
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
assert!(
fs::read_dir(t.prefix().join("dosdevices"))
.unwrap()
.all(|e| !e.unwrap().file_name().to_string_lossy().contains(".tmp."))
);
}
#[test]
fn manifest_temp_does_not_follow_an_existing_symlink() {
let t = TempDir::new("manifest-symlink");
let dosdevices = t.prefix().join("dosdevices");
let target = t.0.join("outside-manifest");
fs::write(&target, b"unchanged").unwrap();
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
symlink(&target, &tmp).unwrap();
assert!(write_manifest(&dosdevices, &BTreeMap::new()).is_err());
assert_eq!(fs::read(&target).unwrap(), b"unchanged");
assert_eq!(fs::read_link(&tmp).unwrap(), target);
}
#[test]
fn a_failed_retarget_restores_the_previous_manifest_and_link() {
let t = TempDir::new("retarget-failure");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let temp_link = t
.prefix()
.join("dosdevices")
.join(format!(".bx-drive-tmp.{}", std::process::id()));
fs::create_dir(&temp_link).unwrap();
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
t.game()
);
}
#[test]
fn a_prefix_lock_rejects_another_launcher_until_released() {
let t = TempDir::new("lock");
let lock = lock_drive_mappings(&t.prefix()).unwrap();
let error = lock_drive_mappings(&t.prefix()).unwrap_err();
assert!(error.contains("another bx-cli run"), "{error}");
drop(lock);
assert!(lock_drive_mappings(&t.prefix()).is_ok());
}
#[test]
fn a_non_utf8_target_round_trips_through_the_manifest() {
let t = TempDir::new("non-utf8");
let mut game_bytes = t.0.as_os_str().as_bytes().to_vec();
game_bytes.extend_from_slice(b"/game-\xff");
let game = PathBuf::from(std::ffi::OsString::from_vec(game_bytes));
let owned = BTreeMap::from([('g', game.clone())]);
write_manifest(&t.prefix().join("dosdevices"), &owned).unwrap();
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
game
);
}
#[test]
fn a_legacy_plain_text_target_still_reads() {
let t = TempDir::new("legacy-manifest");
let legacy_target = t.0.join("old-game");
fs::write(
t.prefix().join("dosdevices").join(MANIFEST),
format!("g\t{}\n", legacy_target.display()),
)
.unwrap();
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
legacy_target
);
}
}
+382 -28
View File
@@ -1,5 +1,6 @@
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
mod drives;
mod stage;
mod supervise;
@@ -13,7 +14,7 @@ use std::process::{Command, ExitCode};
use std::time::{Duration, Instant};
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
use bx_telemetry::{ShaderGap, TraceSummary, TrapCount, summarize_jsonl};
use bx_telemetry::{ShaderGap, ShaderGapGroup, TraceSummary, TrapCount, summarize_jsonl};
use dxbc_accc::inspect_dxbc;
use supervise::{Outcome, Stop};
@@ -40,18 +41,31 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
"XPC_SERVICE_NAME",
];
fn print_usage() {
eprintln!(
"BetterXen Hybrid CLI (bx-cli)\n\
\n\
Usage:\n\
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
);
/// Opt-in `bx_runtime_veh.dll` diagnostic switches. They carry addresses and counts, never
/// credentials, so the isolated guest environment lets them through by name; every other
/// variable is still stripped.
const DIAGNOSTIC_ENV_ALLOWLIST: &[&str] = &[
"BX_VEH_AV_CONTEXT",
"BX_VEH_AV_ALL",
"BX_VEH_WATCH",
"BX_VEH_WATCH_RANGE",
"BX_VEH_WATCH_RANGE_MAX",
"BX_VEH_HIT",
"BX_VEH_HIT_ALL",
"BX_VEH_HIT_RDX",
"BX_VEH_SAMPLE",
];
fn usage_text() -> &'static str {
"BetterXen Hybrid CLI (bx-cli)\n\
\n\
Usage:\n\
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
}
fn run_capture(program: &str, args: &[&str]) -> Option<String> {
@@ -219,6 +233,27 @@ fn format_shader_gap_line(gap: &ShaderGap) -> String {
)
}
/// One `(pso, stage)` group of gap records, with its count and every distinct constraint set
/// (#590). Missing fields say `unknown` rather than being lost.
fn format_shader_gap_group(group: &ShaderGapGroup) -> String {
let mut out = format!(
" {:5}x pso={} stage={}\n",
group.count,
group.pso.as_deref().unwrap_or("unknown"),
group.stage.as_deref().unwrap_or("unknown"),
);
for variant in &group.variants {
let _ = writeln!(
out,
" wave_lanes_min={} atomic64_flags={} ({}x)",
variant.wave_lanes_min.as_deref().unwrap_or("unknown"),
variant.atomic64_flags.as_deref().unwrap_or("unknown"),
variant.count,
);
}
out
}
/// One line per gate record whose decision is not a pass, naming the pipeline,
/// stage, decision and HRESULT. These are the records a reader needs to find a
/// blocker; the counted breakdown alone does not say which pipeline failed
@@ -277,6 +312,28 @@ fn format_shader_gate_section(summary: &TraceSummary) -> String {
for gap in &summary.shader_gaps {
out.push_str(&format_shader_gap_line(gap));
}
// #590: the same records grouped by pipeline and stage, so a reader can tell which
// pipelines are created-but-not-run. Additive: the per-record list above is unchanged.
let _ = writeln!(
out,
"\nD3DMetal gaps by kind/stage ({}):",
summary.shader_gap_groups.len()
);
for group in &summary.shader_gap_groups {
out.push_str(&format_shader_gap_group(group));
}
if summary.shader_gaps_missing_identity > 0 {
out.push_str(&format_shader_line(
"gaps w/o pso/stage",
summary.shader_gaps_missing_identity,
));
}
if summary.shader_gaps_missing_constraints > 0 {
out.push_str(&format_shader_line(
"gaps w/o constraints",
summary.shader_gaps_missing_constraints,
));
}
}
if !summary.shader_bridge_missing.is_empty() {
let _ = writeln!(
@@ -333,6 +390,40 @@ fn render_trace(text: &str) -> String {
);
}
}
if !summary.breakpoint_exceptions.is_empty() {
let _ = writeln!(
out,
"\nBreakpoint/assert exceptions, first chance ({}):",
summary.breakpoint_exceptions.len()
);
for hit in &summary.breakpoint_exceptions {
let _ = writeln!(
out,
" code={} {} + RVA={} (module_base={} address={})",
hit.exception_code.as_deref().unwrap_or("unknown"),
hit.module.as_deref().unwrap_or("?"),
hit.rva.as_deref().unwrap_or("unknown"),
hit.module_base.as_deref().unwrap_or("unknown"),
hit.address.as_deref().unwrap_or("unknown"),
);
}
// Any record at the cap counts: concurrent threads, or several processes appending to one
// log, can write the capped record before a lower-numbered one.
if let Some(limit) =
summary
.breakpoint_exceptions
.iter()
.find_map(|hit| match (hit.record, hit.limit) {
(Some(record), Some(limit)) if limit > 0 && record >= limit => Some(limit),
_ => None,
})
{
let _ = writeln!(
out,
" cap of {limit} records reached; later breakpoints were not recorded"
);
}
}
if !summary.unimpl_apis.is_empty() {
let _ = writeln!(out, "\nUnimplemented APIs:");
for (api, count) in &summary.unimpl_apis {
@@ -360,7 +451,7 @@ where
{
let mut env_map = BTreeMap::new();
env_map.insert("PATH".to_string(), SAFE_CHILD_PATH.to_string());
for &key in HOST_ENV_ALLOWLIST {
for &key in HOST_ENV_ALLOWLIST.iter().chain(DIAGNOSTIC_ENV_ALLOWLIST) {
if let Some(val) = lookup(key) {
env_map.insert(key.to_string(), val);
}
@@ -817,6 +908,18 @@ fn cmd_run(args: &[String]) -> ExitCode {
supervise::install_signal_handlers();
let started = Instant::now();
// Drive links are prefix-global. Keep them stable until this guest exits so another bx-cli
// process cannot retarget G: underneath a running title. Taken before system32 staging, so
// a run refused here has not touched the shared prefix. Runs sharing a prefix are therefore
// serial: a second launcher on the same prefix is refused while the first is running.
let _drive_lock = match drives::lock_drive_mappings(&environment_dir) {
Ok(lock) => lock,
Err(e) => {
diag(format_args!("error: {e}"));
return ExitCode::FAILURE;
}
};
// #457: shims loaded with LOAD_LIBRARY_SEARCH_SYSTEM32 never see WINEPATH, so they are
// copied into the environment's system32 first. A bare prefix is initialized for that.
let system32 = stage::system32_dir(&environment_dir);
@@ -878,6 +981,25 @@ fn cmd_run(args: &[String]) -> ExitCode {
}
}
// An Xbox title opens its package on G: and writes temporary files to T:. A missing drive
// only matters to such a title, so it is reported and the run goes on.
match abs_exe.parent() {
Some(package_dir) => match drives::map_xbox_drives(&environment_dir, package_dir) {
Ok(mappings) => {
for mapping in &mappings {
match mapping {
drives::Mapping::Foreign { .. } => diag(mapping.describe()),
_ => diag(format_args!("bx-cli: {}", mapping.describe())),
}
}
}
Err(e) => diag(format_args!(
"warning: Xbox drives G: and T: not mapped: {e}"
)),
},
None => diag("warning: Xbox drive G: not mapped: the executable has no parent directory"),
}
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname])
@@ -1048,22 +1170,66 @@ fn cmd_shader(path: &str) -> ExitCode {
}
}
/// What a bare invocation of `bx-cli` should do. Split out from `main` so the
/// choice is testable without spawning a process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Dispatch<'a> {
/// An explicit `--help` / `-h` / `help`: usage on stdout, succeed.
Help,
/// Nothing was asked for: usage on stderr, fail as a usage error.
NoArgs,
/// An unrecognised subcommand: usage on stderr, fail.
Unknown(&'a str),
/// A real subcommand.
Sub(&'a str),
}
impl<'a> Dispatch<'a> {
fn classify(args: &'a [String]) -> Self {
let Some(sub) = args.first() else {
return Dispatch::NoArgs;
};
match sub.as_str() {
"--help" | "-h" | "help" => Dispatch::Help,
"doctor" | "probe" | "shader" | "trace" | "run" => Dispatch::Sub(sub.as_str()),
_ => Dispatch::Unknown(sub.as_str()),
}
}
/// True when the usage text goes to stdout rather than stderr.
fn usage_on_stdout(self) -> bool {
matches!(self, Dispatch::Help)
}
/// True when the invocation must not report success.
fn is_usage_error(self) -> bool {
matches!(self, Dispatch::NoArgs | Dispatch::Unknown(_))
}
}
fn main() -> ExitCode {
let args: Vec<String> = env::args().skip(1).collect();
let Some(sub) = args.first() else {
print_usage();
return ExitCode::SUCCESS;
};
match sub.as_str() {
"doctor" => cmd_doctor(),
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
"run" => cmd_run(&args[1..]),
_ => {
print_usage();
ExitCode::FAILURE
}
let dispatch = Dispatch::classify(&args);
if dispatch.usage_on_stdout() {
print!("{}", usage_text());
} else if dispatch.is_usage_error() {
eprint!("{}", usage_text());
}
match dispatch {
Dispatch::Help => ExitCode::SUCCESS,
Dispatch::NoArgs | Dispatch::Unknown(_) => ExitCode::FAILURE,
Dispatch::Sub(sub) => match sub {
"doctor" => cmd_doctor(),
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
"run" => cmd_run(&args[1..]),
// Only reachable when a subcommand that needs an argument got none.
_ => {
eprint!("{}", usage_text());
ExitCode::FAILURE
}
},
}
}
@@ -1540,6 +1706,26 @@ sub setup_bottle_wineprefix {
assert!(!child.contains_key("CX_GRAPHICS_BACKEND"));
}
#[test]
fn isolated_env_passes_only_the_named_veh_diagnostics() {
let host = BTreeMap::from([
("BX_VEH_AV_CONTEXT", "1"),
("BX_VEH_SAMPLE", "5"),
("BX_VEH_UNKNOWN", "x"),
("BX_LOG_FILE", "/tmp/elsewhere.jsonl"),
("GH_TOKEN", "secret_token"),
]);
let child = collect_isolated_host_env(|k| host.get(k).map(|s| (*s).to_string()));
assert_eq!(
child.get("BX_VEH_AV_CONTEXT").map(String::as_str),
Some("1")
);
assert_eq!(child.get("BX_VEH_SAMPLE").map(String::as_str), Some("5"));
assert!(!child.contains_key("BX_VEH_UNKNOWN"));
assert!(!child.contains_key("BX_LOG_FILE"));
assert!(!child.contains_key("GH_TOKEN"));
}
#[test]
fn converts_unix_path_to_wine_z_drive() {
assert_eq!(
@@ -1606,6 +1792,62 @@ sub setup_bottle_wineprefix {
assert_eq!(format_shader_gate_section(&summarize_jsonl(log)), "");
}
#[test]
fn renders_breakpoint_exceptions_with_module_and_rva() {
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(
"\nBreakpoint/assert exceptions, first chance (1):\n code=0x80000003 \
title.exe + RVA=0x0000000002236178 (module_base=0x0000000140000000 \
address=0x0000000142236178)\n"
),
"{rendered}"
);
assert!(!rendered.contains("Unhandled exceptions"), "{rendered}");
assert!(
!rendered.contains("cap of"),
"one of 16 records is not the cap: {rendered}"
);
}
#[test]
fn notes_when_the_breakpoint_record_cap_is_reached() {
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
"{rendered}"
);
}
#[test]
fn notes_the_cap_when_a_capped_record_is_not_the_last_line() {
// Two threads (or processes) appending: the capped record lands before record 15.
let log = r#"{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":16,"limit":16}
{"ts_ms":6,"tid":8,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x10","address":"0x0000000140000010","record":15,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains(" cap of 16 records reached; later breakpoints were not recorded\n"),
"{rendered}"
);
}
#[test]
fn prints_the_address_of_a_breakpoint_outside_any_image() {
let log = r#"{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
"#;
let rendered = render_trace(log);
assert!(
rendered.contains("address=0x0000000000410000"),
"{rendered}"
);
}
#[test]
fn renders_decisions_kinds_stages_gaps_and_missing_bridge() {
// Realistic records, matching the emitter in shims/d3d12_xs/shader_gate.cpp.
@@ -1662,4 +1904,116 @@ sub setup_bottle_wineprefix {
assert!(rendered.contains("unparsed details : 1"), "{rendered}");
assert!(rendered.contains(" 1x pass_dxil"), "{rendered}");
}
/// The usage paths must not be inverted: an explicit `--help` succeeded,
/// a bare invocation did nothing, and an unknown subcommand is an error.
#[test]
fn help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error() {
for flag in ["--help", "-h", "help"] {
let argv = args(&[flag]);
let dispatch = Dispatch::classify(&argv);
assert_eq!(
dispatch,
Dispatch::Help,
"{flag} is an explicit help request"
);
assert!(dispatch.usage_on_stdout(), "{flag} prints usage on stdout");
assert!(!dispatch.is_usage_error(), "{flag} must exit 0");
}
let empty: Vec<String> = Vec::new();
let none = Dispatch::classify(&empty);
assert_eq!(none, Dispatch::NoArgs);
assert!(!none.usage_on_stdout(), "a bare invocation writes stderr");
assert!(
none.is_usage_error(),
"a bare invocation did nothing, so it must not report success"
);
let bogus_argv = args(&["definitely-not-a-subcommand"]);
let bogus = Dispatch::classify(&bogus_argv);
assert_eq!(bogus, Dispatch::Unknown("definitely-not-a-subcommand"));
assert!(
!bogus.usage_on_stdout(),
"an unknown subcommand writes stderr"
);
assert!(bogus.is_usage_error(), "an unknown subcommand is an error");
for real in ["doctor", "probe", "shader", "trace", "run"] {
let argv = args(&[real]);
let dispatch = Dispatch::classify(&argv);
assert_eq!(dispatch, Dispatch::Sub(real), "{real} is a real subcommand");
assert!(!dispatch.usage_on_stdout(), "{real} prints no usage");
assert!(!dispatch.is_usage_error(), "{real} is not a usage error");
}
}
/// The usage text must name every subcommand, so the classifier above is
/// not testing a table that nothing prints.
#[test]
fn the_usage_text_names_every_subcommand() {
let text = usage_text();
assert!(
text.contains("BetterXen Hybrid CLI"),
"usage carries the banner"
);
for sub in ["doctor", "probe", "shader", "trace", "run"] {
assert!(text.contains(sub), "usage documents {sub}");
}
}
/// #590: the grouped view names each `(pso, stage)` pair with its count, wave width and
/// 64-bit-atomic flags, in first-seen order, and says when a record lost its identity.
#[test]
fn renders_gaps_grouped_by_pipeline_and_stage() {
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"garbage"}
"#;
let rendered = render_trace(log);
// The #496 per-record list is unchanged.
assert!(rendered.contains("D3DMetal gaps (4):"), "{rendered}");
assert!(
rendered.contains(" pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000"),
"{rendered}"
);
// The additive grouped view.
assert!(
rendered.contains("D3DMetal gaps by kind/stage (3):"),
"{rendered}"
);
assert!(
rendered.contains(" 1x pso=graphics stage=VS"),
"{rendered}"
);
assert!(
rendered.contains(" 2x pso=compute stage=CS"),
"{rendered}"
);
assert!(
rendered.contains(" wave_lanes_min=64 atomic64_flags=0x400000 (2x)"),
"{rendered}"
);
assert!(
rendered.contains(" 1x pso=unknown stage=unknown"),
"{rendered}"
);
assert!(rendered.contains("gaps w/o pso/stage : 1"), "{rendered}");
assert!(rendered.contains("gaps w/o constraints : 1"), "{rendered}");
// First-seen order: the graphics/VS group comes before the compute/CS one.
let vs = rendered.find("pso=graphics stage=VS").unwrap();
let cs = rendered.find(" 2x pso=compute stage=CS").unwrap();
assert!(vs < cs, "{rendered}");
}
/// #590: a run with no gap records renders no grouped section at all.
#[test]
fn a_run_with_no_gaps_renders_no_grouped_section() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let rendered = render_trace(log);
assert!(rendered.contains("Shader gate:"), "{rendered}");
assert!(!rendered.contains("D3DMetal gaps"), "{rendered}");
assert!(!rendered.contains("gaps w/o"), "{rendered}");
}
}
+80
View File
@@ -433,6 +433,12 @@ where
for (name, bytes, dst, result) in plan {
if !matches!(result, Staged::Unchanged(_)) {
let tmp = tmp_of(name);
// Snapshot what the target holds now, before the rename, so a failed manifest
// write can put the *old* bytes back (not the bytes just written).
let previous: Option<Vec<u8>> = match result {
Staged::Copied(_) => None,
_ => fs::read(&dst).ok(),
};
let published = before_publish(name).and_then(|()| match result {
// Nothing was there at step 1; refuse to replace whatever appeared since.
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
@@ -495,6 +501,19 @@ where
let _ = fs::remove_file(&tmp);
owned.insert(name.clone(), sha256_hex(&bytes));
if let Err(e) = write_manifest(system32, &owned) {
// The file is installed but the manifest on disk does not name it, so the
// next run would call bx-cli's own copy foreign (#573). Roll the publish
// back: a Copied file is removed, a Replaced one is restored from the bytes
// it had before. The manifest is left exactly as it was, so the retry sees
// the same state it would have seen had the publish never happened.
match previous {
None => {
let _ = fs::remove_file(&dst);
}
Some(before) => {
let _ = fs::write(&dst, before);
}
}
discard(&pending);
return Err(e);
}
@@ -875,6 +894,67 @@ mod tests {
);
}
#[test]
fn a_manifest_write_failure_leaves_no_unowned_file() {
let (_t, shims, prefix) = setup("manifest");
let sys = system32_dir(&prefix);
// A directory where the manifest's temporary file has to go makes
// `write_manifest` fail after the first shim has already been published.
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::create_dir(&obstacle).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("cannot write"), "{err}");
assert!(
!sys.join("bx_runtime_veh.dll").exists(),
"the published file was rolled back, so the retry is not refused as foreign"
);
assert!(!sys.join(MANIFEST_NAME).exists());
// Only the obstacle itself is left: no staged copy, no temporary file.
let entries: Vec<String> = fs::read_dir(&sys)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(
entries,
vec![obstacle.file_name().unwrap().to_string_lossy().into_owned()],
"system32 holds nothing but the obstacle that failed the manifest write"
);
fs::remove_dir(&obstacle).unwrap();
// The retry installs everything fresh; nothing is reported as foreign.
let retry = stage(&shims, &sys).unwrap();
assert!(
retry.iter().all(|s| matches!(s, Staged::Copied(_))),
"{retry:?}"
);
// And a shim rebuilt later refreshes bx-cli's own copy rather than failing.
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let update = stage(&shims, &sys).unwrap();
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
}
#[test]
fn a_manifest_write_failure_restores_the_previous_bytes() {
let (_t, shims, prefix) = setup("restore");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
// Rebuild the shim, then make the manifest write fail after the rename.
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::create_dir(&obstacle).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(
fs::read(sys.join("bx_runtime_veh.dll")).unwrap(),
b"veh v1",
"the replaced file must be restored to the bytes it had before the rename"
);
// The manifest still names the old copy, so the retry refreshes it rather than
// calling it foreign.
fs::remove_dir(&obstacle).unwrap();
let retry = stage(&shims, &sys).unwrap();
assert!(retry.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
}
#[test]
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
let (t, shims, prefix) = setup("visible");
+1 -1
View File
@@ -447,7 +447,7 @@ mod tests {
std::fs::write(
&server,
format!(
"#!/bin/sh\n/bin/ps -o pgid= -p $$ >> '{}'\n",
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
seen.display()
),
)
+43
View File
@@ -0,0 +1,43 @@
//! Runs the built `bx-cli` binary to check what `main` prints and returns for the
//! usage paths (#532). The unit tests cover `Dispatch::classify`; these cover the
//! mapping from that classification to the real exit code and output stream.
use std::process::Command;
fn run(args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_bx-cli"))
.args(args)
.env_clear()
.output()
.expect("bx-cli must start")
}
#[test]
fn help_prints_usage_on_stdout_and_succeeds() {
for flag in ["--help", "-h", "help"] {
let out = run(&[flag]);
assert!(out.status.success(), "{flag}: {:?}", out.status);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("bx-cli run --exe"),
"{flag}: usage on stdout: {stdout}"
);
assert!(out.stderr.is_empty(), "{flag}: nothing on stderr");
}
}
#[test]
fn a_bare_invocation_is_a_usage_error_on_stderr() {
let out = run(&[]);
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "nothing on stdout");
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
}
#[test]
fn an_unknown_subcommand_is_a_usage_error_on_stderr() {
let out = run(&["frobnicate"]);
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "nothing on stdout");
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
}
+349 -11
View File
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
}
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeSummary {
pub image_base: u64,
pub size_of_image: u32,
@@ -128,12 +128,21 @@ struct Section {
}
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
}
/// Map an RVA to a file offset and report how many raw bytes remain in that
/// section from the mapped offset. The bound lets callers walk a table without
/// leaving the section that contains it.
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
for s in sections {
let span = s.vsize.max(s.raw_size);
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
let delta = rva - s.vaddr;
if delta < s.raw_size {
return Some((s.raw_ptr + delta) as usize);
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
return Some((off, remaining));
}
}
}
@@ -167,8 +176,36 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
let mut sections = Vec::with_capacity(section_count as usize);
// The import data directory is entry index 1, an 8-byte RVA/size pair at
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
// validated while the optional header is read: a short optional header must
// not let the read fall through into the section table.
const IMPORT_DIR_INDEX: u32 = 1;
const IMPORT_DIR_OFF: usize = 112 + 8;
let mut import_dir: Option<(u32, u32)> = None;
if num_rvas > IMPORT_DIR_INDEX {
let entry = bytes
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
if IMPORT_DIR_OFF + 8 > opt_size {
return Err(ProbeError::NotPe32Plus(
"import directory outside SizeOfOptionalHeader",
));
}
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
import_dir = Some((rva, size));
}
let sec_base = opt + opt_size;
let section_table_size = (section_count as usize)
.checked_mul(40)
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
bytes
.get(sec_base..sec_base + section_table_size)
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
let mut sections = Vec::with_capacity(section_count as usize);
for i in 0..section_count as usize {
let so = sec_base + i * 40;
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
@@ -184,16 +221,22 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
}
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
if num_rvas > 1 {
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
if let Some((imp_rva, imp_size)) = import_dir {
if imp_rva != 0
&& let Some(mut desc_off) = rva_to_off(&sections, imp_rva)
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(&sections, imp_rva)
{
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) {
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
// declared directory Size and the section's raw bytes, whichever
// ends first, so descriptors past the directory are not reported.
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
while desc_bytes_left >= 20 {
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) else {
break;
};
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
break;
}
@@ -225,6 +268,7 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
imports.entry(dll).or_default().extend(syms);
}
desc_off += 20;
desc_bytes_left -= 20;
}
}
}
@@ -242,6 +286,129 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
mod tests {
use super::*;
const PE_OFF: usize = 0x80;
const COFF: usize = PE_OFF + 4;
const OPT: usize = COFF + 20;
const OPT_SIZE: usize = 0xF0;
const SEC: usize = OPT + OPT_SIZE;
const SECTION_RVA: u32 = 0x1000;
const RAW_PTR: u32 = 0x200;
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
}
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
}
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
}
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
put_u32(bytes, base + 8, raw_size);
put_u32(bytes, base + 12, rva);
put_u32(bytes, base + 16, raw_size);
put_u32(bytes, base + 20, raw_ptr);
}
fn minimal_pe32_plus() -> Vec<u8> {
let mut bytes = vec![0u8; 0x400];
bytes[0..2].copy_from_slice(b"MZ");
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
put_u16(&mut bytes, COFF, 0x8664);
put_u16(&mut bytes, COFF + 2, 1);
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
put_u16(&mut bytes, OPT, 0x020B);
put_u32(&mut bytes, OPT + 16, 0x1234);
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
put_u32(&mut bytes, OPT + 56, 0x2000);
put_u32(&mut bytes, OPT + 108, 16);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
bytes
}
fn two_import_pe32_plus() -> Vec<u8> {
let mut bytes = minimal_pe32_plus();
let import_rva = SECTION_RVA;
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
// Two descriptors followed by the required all-zero terminator.
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
put_u64(
&mut bytes,
RAW_PTR as usize + 0x80,
u64::from(SECTION_RVA + 0x60),
);
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
bytes
}
/// Two sections: an import-descriptor section holding exactly two
/// descriptors and no terminator, and a data section for names and thunks.
/// Ellipsis bytes just past the descriptor section spell a third valid
/// descriptor, so an unbounded walk reports a DLL that is not imported.
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
const DATA_PTR: u32 = 0x300;
let mut bytes = minimal_pe32_plus();
put_u16(&mut bytes, COFF + 2, 2);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
// Declare the directory to cover the whole descriptor section, so the
// section bound (not the Size) is what this fixture exercises.
put_u32(&mut bytes, OPT + 112 + 12, 40);
for (base, dll_rva, thunk_rva) in [
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
] {
put_u32(&mut bytes, base, thunk_rva);
put_u32(&mut bytes, base + 12, dll_rva);
put_u32(&mut bytes, base + 16, thunk_rva);
}
// A third, entirely valid descriptor just past the section boundary.
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
for (delta, name) in [
(0x00, &b"ONE.DLL\0"[..]),
(0x20, &b"TWO.DLL\0"[..]),
(0x40, &b"THREE.DLL\0"[..]),
] {
let off = DATA_PTR as usize + delta;
bytes[off..off + name.len()].copy_from_slice(name);
}
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
let off = DATA_PTR as usize + delta;
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
put_u64(&mut bytes, off + 8, 0);
}
bytes
}
#[test]
fn classifies_tracks_accurately() {
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
@@ -263,4 +430,175 @@ mod tests {
);
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
}
#[test]
fn parses_minimal_pe32_plus_without_imports() {
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
assert_eq!(summary.entry_point_rva, 0x1234);
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
assert_eq!(summary.size_of_image, 0x2000);
assert_eq!(summary.section_count, 1);
assert!(summary.imports.is_empty());
}
#[test]
fn parses_named_and_ordinal_imports_from_two_dlls() {
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
#[test]
fn rejects_truncation_at_every_header_boundary() {
let image = minimal_pe32_plus();
for len in 0..=0x100 {
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
}
}
#[test]
fn rejects_section_rva_mapping_that_would_wrap_u32() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
put_u32(&mut image, SEC + 20, u32::MAX);
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
assert!(result.is_ok(), "raw pointer addition panicked");
assert!(result.unwrap().unwrap().imports.is_empty());
}
#[test]
fn rejects_section_count_larger_than_file() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, COFF + 2, u16::MAX);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated section table")
);
}
#[test]
fn rejects_pe32_magic() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, OPT, 0x010B);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
);
}
#[test]
fn import_directory_outside_all_sections_is_safe() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, 0x8000);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
#[test]
fn rejects_truncated_import_directory() {
let mut image = minimal_pe32_plus();
// An empty section table that fits, an optional header long enough to
// declare the import entry, and a file cut after two of the entry's
// RVA bytes.
put_u16(&mut image, COFF + 2, 0);
put_u16(&mut image, COFF + 16, 0xE0);
image.truncate(OPT + 112 + 8 + 2);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated import directory")
);
}
#[test]
fn bounds_unterminated_import_descriptor_walk() {
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
/// past the end of the optional header, so its 8 bytes would otherwise be
/// read from the section table. The entry index is still within
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
#[test]
fn rejects_import_directory_outside_short_optional_header() {
let mut image = two_import_pe32_plus();
// Import entry spans optional-header offsets 120..128; declare the
// optional header to end at 120, inside the entry.
put_u16(&mut image, COFF + 16, 120);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// One byte short of the full 8-byte entry is still out of range.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 127);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// Exactly 128 bytes covers the whole entry, so the import directory is
// read normally. The section table now starts at OPT + 128, so write it
// there for this size.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 128);
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.contains_key("ALPHA.DLL"));
assert!(summary.imports.contains_key("BETA.DLL"));
}
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
/// import entry (index 1) must not be probed even though its bytes are
/// present and inside SizeOfOptionalHeader.
#[test]
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
let mut image = two_import_pe32_plus();
put_u32(&mut image, OPT + 108, 1);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
/// (b) The declared import directory Size is shorter than the containing
/// section, so descriptors past the declared size must not be reported even
/// though they are valid and inside the section's raw bytes.
#[test]
fn bounds_import_descriptor_walk_by_declared_directory_size() {
// Size 40 covers exactly the two real descriptors; the third valid
// descriptor at +40 lies outside the directory but inside the section.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 40);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
assert!(!summary.imports.contains_key("THREE.DLL"));
// Size 20 reports only the first descriptor.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 20);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
// A size that is not a multiple of 20 stops before the next descriptor
// would exceed the directory.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 39);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
}
}
+342 -2
View File
@@ -18,16 +18,54 @@ pub struct TraceSummary {
pub amd_traps: BTreeMap<String, TrapCount>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
pub breakpoint_exceptions: Vec<BreakpointException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
pub shader_gate: ShaderGateSummary,
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
pub shader_gaps: Vec<ShaderGap>,
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
pub shader_gap_groups: Vec<ShaderGapGroup>,
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
/// they are grouped under `unknown`. Counted here so the group counts reconcile
/// with [`TraceSummary::shader_gaps`].
pub shader_gaps_missing_identity: usize,
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
/// value for one). Counted here rather than dropped or assumed.
pub shader_gaps_missing_constraints: usize,
/// `shader_bridge_missing` messages, in log order.
pub shader_bridge_missing: Vec<String>,
}
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapGroup {
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
/// `unknown`).
pub pso: Option<String>,
/// The emitted `stage=` value, or `None` when the record carried none.
pub stage: Option<String>,
/// How many gap records this `(pso, stage)` pair covers.
pub count: usize,
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
/// first-seen order. Two pipelines of the same kind and stage can need different
/// wave widths or atomic features, so a group keeps each constraint set rather than
/// reporting only the first and losing the rest.
pub variants: Vec<ShaderGapVariant>,
}
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapVariant {
pub wave_lanes_min: Option<String>,
pub atomic64_flags: Option<String>,
/// How many records in the group carried exactly these constraints.
pub count: usize,
}
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
/// their emitted string so unknown values are counted rather than dropped.
#[derive(Debug, Default, PartialEq, Eq)]
@@ -147,6 +185,30 @@ pub struct UnhandledException {
pub rip: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct BreakpointException {
pub exception_code: Option<String>,
pub module: Option<String>,
pub module_base: Option<String>,
pub rva: Option<String>,
/// The faulting address, which locates a breakpoint outside any image (module `?`).
pub address: Option<String>,
/// 1-based index of this record and the per-process cap, so a reader can tell a run
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
pub record: Option<u32>,
pub limit: Option<u32>,
}
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
let needle = format!("\"{key}\":");
let start = line.find(&needle)? + needle.len();
let digits: &str = &line[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
@@ -200,18 +262,77 @@ fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
gate.records.push(record);
}
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
/// always writes a value, so an empty one means the record is malformed, not that the
/// pipeline is named "".
fn non_empty(value: Option<String>) -> Option<String> {
value.filter(|v| !v.is_empty())
}
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
///
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
let pso = non_empty(gap.pso.clone());
let stage = non_empty(gap.stage.clone());
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
if pso.is_none() || stage.is_none() {
groups.shader_gaps_missing_identity += 1;
}
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
groups.shader_gaps_missing_constraints += 1;
}
// The group list is small (one entry per affected pipeline stage), so a linear scan
// keeps first-seen order without a second index to keep in sync.
let group_index = match groups
.shader_gap_groups
.iter()
.position(|g| g.pso == pso && g.stage == stage)
{
Some(index) => index,
None => {
groups.shader_gap_groups.push(ShaderGapGroup {
pso,
stage,
count: 0,
variants: Vec::new(),
});
groups.shader_gap_groups.len() - 1
}
};
let group = &mut groups.shader_gap_groups[group_index];
group.count += 1;
match group
.variants
.iter()
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
{
Some(index) => group.variants[index].count += 1,
None => group.variants.push(ShaderGapVariant {
wave_lanes_min,
atomic64_flags,
count: 1,
}),
}
}
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
let pairs = parse_key_values(detail, true);
// The emitter appends `: D3DMetal creates such pipelines ...` directly
// after the flags value, so strip the trailing colon.
let atomic64_flags = get_field(&pairs, "atomic64_flags")
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
summary.shader_gaps.push(ShaderGap {
let gap = ShaderGap {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
atomic64_flags,
});
};
record_shader_gap_group(summary, &gap);
summary.shader_gaps.push(gap);
}
pub fn summarize_jsonl(input: &str) -> TraceSummary {
@@ -250,6 +371,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
});
}
"breakpoint_exception" => {
summary.breakpoint_exceptions.push(BreakpointException {
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
module: extract_json_str(trimmed, "module").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),
address: extract_json_str(trimmed, "address").map(str::to_owned),
record: extract_json_u32(trimmed, "record"),
limit: extract_json_u32(trimmed, "limit"),
});
}
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
"unimpl_vtable" => {
*summary
@@ -326,6 +458,39 @@ mod tests {
assert_eq!(summary.clwb_trap_lower_bound, None);
}
#[test]
fn collects_breakpoint_exceptions_in_log_order() {
let log = r#"
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
"#;
let summary = summarize_jsonl(log);
assert!(summary.unhandled_exceptions.is_empty());
assert_eq!(
summary.breakpoint_exceptions,
[
BreakpointException {
exception_code: Some("0x80000003".into()),
module: Some("title.exe".into()),
module_base: Some("0x0000000140000000".into()),
rva: Some("0x0000000002236178".into()),
address: Some("0x0000000142236178".into()),
record: Some(1),
limit: Some(16),
},
BreakpointException {
exception_code: Some("0xc0000420".into()),
module: Some("?".into()),
module_base: Some("0x0000000000000000".into()),
rva: Some("0x0000000000000000".into()),
address: Some("0x0000000000410000".into()),
record: Some(2),
limit: Some(16),
},
]
);
}
#[test]
fn collects_unhandled_exceptions_in_log_order() {
let log = r#"
@@ -569,4 +734,179 @@ mod tests {
assert_eq!(pairs.len(), 2);
assert_eq!(pairs[1], ("stage", "pixel"));
}
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
/// with its own wave width and 64-bit-atomic flags.
#[test]
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
// Same pso, different stages: grouping on pso alone would collapse these, so the
// test discriminates the (pso, stage) key rather than only the pso.
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
assert_eq!(summary.shader_gap_groups.len(), 3);
let first = &summary.shader_gap_groups[0];
assert_eq!(first.pso.as_deref(), Some("graphics"));
assert_eq!(first.stage.as_deref(), Some("VS"));
assert_eq!(first.count, 1);
assert_eq!(
first.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 1,
}]
);
let second = &summary.shader_gap_groups[1];
assert_eq!(second.pso.as_deref(), Some("compute"));
assert_eq!(second.stage.as_deref(), Some("CS"));
assert_eq!(second.count, 1);
// A second stage of the *same* pso stays its own group, which is what separates a
// (pso, stage) key from a pso-only key.
let third = &summary.shader_gap_groups[2];
assert_eq!(third.pso.as_deref(), Some("graphics"));
assert_eq!(third.stage.as_deref(), Some("PS"));
assert_eq!(third.count, 1);
}
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
/// identical records are not adjacent.
#[test]
fn groups_identical_gaps_together() {
let record = r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let log = format!("{record}\n{other}\n{record}\n");
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gap_groups.len(), 2);
let compute = &summary.shader_gap_groups[0];
assert_eq!(compute.stage.as_deref(), Some("CS"));
assert_eq!(compute.count, 2);
assert_eq!(
compute.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 2,
}]
);
assert_eq!(summary.shader_gap_groups[1].count, 1);
// Every record is in exactly one group.
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
assert_eq!(grouped, summary.shader_gaps.len());
}
/// #590: one pipeline kind and stage can need different wave widths or atomic
/// features, so a group keeps every distinct constraint set, not only the first.
#[test]
fn one_group_keeps_each_distinct_constraint_set() {
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gap_groups.len(), 1);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 3);
assert_eq!(
group.variants,
[
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 2,
},
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 1,
},
]
);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
/// #590: a gap record with a missing or empty field must not panic. It is grouped
/// under `unknown` and counted, never dropped or guessed.
#[test]
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
for (detail, missing_identity, missing_constraints) in [
("", 1, 1),
("garbage", 1, 1),
("pso=compute", 1, 1),
("stage=CS", 1, 1),
(
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
1,
0,
),
("pso=compute stage=CS", 0, 1),
(
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
0,
1,
),
] {
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
assert_eq!(
summary.shader_gap_groups.len(),
1,
"detail={detail:?} lost its record"
);
assert_eq!(
summary.shader_gaps_missing_identity, missing_identity,
"detail={detail:?}"
);
assert_eq!(
summary.shader_gaps_missing_constraints, missing_constraints,
"detail={detail:?}"
);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 1, "detail={detail:?}");
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
assert_eq!(recorded, 1, "detail={detail:?}");
}
}
/// #590: the fields a malformed record does carry are still reported.
#[test]
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
let log =
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
let summary = summarize_jsonl(log);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.pso.as_deref(), Some("compute"));
assert_eq!(group.stage.as_deref(), Some("CS"));
assert_eq!(
group.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: None,
count: 1,
}]
);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 1);
}
/// #590: a run with no gap records produces no groups and no missing-field counts, so
/// the trace renders as it did before the grouping existed.
#[test]
fn a_run_with_no_gaps_has_no_groups() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert!(summary.shader_gaps.is_empty());
assert!(summary.shader_gap_groups.is_empty());
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
}
+117 -21
View File
@@ -4,11 +4,15 @@
Checks only tracked files:
1. no merge-conflict markers in tracked text files;
2. every relative Markdown link points at a tracked file or directory;
3. every workflow file under .github/workflows parses as YAML.
3. every fragment (``#heading``) in a Markdown link resolves to a real
heading in the target Markdown file, including in-page ``](#foo)``
links validated against the same file's headings;
4. every workflow file under .github/workflows parses as YAML.
External URLs and in-page anchors are not fetched or validated, so the result
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
when PyYAML is missing.
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
fetched or validated, so the result does not depend on the network.
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
not skip, when PyYAML is missing.
"""
import re
import subprocess
@@ -17,9 +21,16 @@ from pathlib import Path, PurePosixPath
from urllib.parse import unquote
ROOT = Path(__file__).resolve().parents[2]
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
MARKER = re.compile(r"^(<{7}( |$)|\|{7}( |$)|={7}$|>{7}( |$))")
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
FENCE = re.compile(r"^\s*(```|~~~)")
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
# GitHub slugs the rendered heading, so an inline link contributes only its
# text: ``## See [ADR](x.md)`` slugs as ``see-adr``, not ``see-adrxmd``.
# Link syntax inside a code span stays literal, so those spans are set aside
# before substituting and put back afterwards.
INLINE_LINK = re.compile(r"(?<!\!)\[([^\]]*)\]\([^)]*\)")
CODE_SPAN = re.compile(r"(`+)(.+?)\1")
def tracked():
@@ -35,6 +46,63 @@ def text(path):
return data.decode("utf-8", "replace")
def _slug(text):
"""GitHub-style slug: lowercase, strip non-alnum/-/_/space, spaces -> -."""
text = text.lower()
text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE)
return text.replace(" ", "-")
def _heading_text(text):
"""Rendered text of a heading: link text in, code spans left literal."""
spans = []
def stash(match):
spans.append(match.group(0))
return "\x00%d\x00" % (len(spans) - 1)
stashed = CODE_SPAN.sub(stash, text)
substituted = INLINE_LINK.sub(r"\1", stashed)
for index, span in enumerate(spans):
substituted = substituted.replace("\x00%d\x00" % index, span)
return substituted
def markdown_slugs(body):
"""Return the set of GitHub-style heading slugs in a Markdown document.
Duplicate headings get ``-1``, ``-2``, ... suffixes. Headings inside
fenced code blocks are ignored.
"""
slugs = set()
seen = {}
in_fence = False
for line in body.splitlines():
if FENCE.match(line):
in_fence = not in_fence
continue
if in_fence:
continue
m = HEADING.match(line)
if not m:
continue
base = _slug(_heading_text(m.group(2)))
if not base:
continue
# Advance the numeric suffix until we find a slug that has not
# already been emitted. Counting only identical bases is not
# enough: a literal heading such as ``Foo-1`` may already own
# ``foo-1``, so the next ``Foo`` must become ``foo-2``.
count = seen.get(base, 0)
slug = base if count == 0 else f"{base}-{count}"
while slug in slugs:
count += 1
slug = f"{base}-{count}"
seen[base] = count + 1
slugs.add(slug)
return slugs
def check_markers(files, problems):
for path in files:
if path.endswith((".patch", ".diff")):
@@ -47,9 +115,30 @@ def check_markers(files, problems):
problems.append(f"{path}:{number}: merge conflict marker")
def _resolve_link(path, target):
"""Resolve a relative link target to a repo-root-relative POSIX path."""
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
return "/".join(parts)
def check_links(files, problems):
known = set(files)
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
slug_cache = {}
def slugs_for(md_path):
if md_path not in slug_cache:
slug_cache[md_path] = markdown_slugs(text(md_path) or "")
return slug_cache[md_path]
for path in files:
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
continue
@@ -61,24 +150,31 @@ def check_links(files, problems):
if in_fence:
continue
line = re.sub(r"`[^`]*`", "", line)
for target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
for raw_target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|//)", raw_target, re.I):
continue
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
if not target:
if raw_target == "#":
continue
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
norm = "/".join(parts)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
fragment = ""
if "#" in raw_target:
fragment = unquote(raw_target.split("#", 1)[1])
target = unquote(raw_target.split("#", 1)[0].split("?", 1)[0])
if not target and not fragment:
continue
if target:
norm = _resolve_link(path, target)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
continue
else:
norm = path
if fragment and norm.endswith(".md") and norm in known:
if fragment not in slugs_for(norm):
shown = raw_target
problems.append(
f"{path}:{number}: broken fragment '#{fragment}' "
f"in link '{shown}' (heading not found)"
)
def check_workflows(files, problems, require_yaml):
+296
View File
@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
Run with:
python3 -m unittest scripts/audit/test_docs_hygiene.py
"""
import importlib.util
import sys
import unittest
from pathlib import Path
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
docs_hygiene = importlib.util.module_from_spec(_spec)
sys.modules["docs_hygiene"] = docs_hygiene
_spec.loader.exec_module(docs_hygiene)
class SlugTests(unittest.TestCase):
def test_basic_slug(self):
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
self.assertIn("hello-world", slugs)
def test_strips_punctuation(self):
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
self.assertIn("whats-new-2024", slugs)
def test_keeps_underscore_and_hyphen(self):
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
self.assertIn("foo_bar-baz", slugs)
def test_duplicate_headings(self):
body = "# Setup\n\n# Setup\n\n# Setup\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("setup", slugs)
self.assertIn("setup-1", slugs)
self.assertIn("setup-2", slugs)
def test_suffix_skips_literal_heading_slug(self):
# Regression: counting identical bases alone lets a generated
# suffix collide with a literal heading slug, so the third `Foo`
# also became `foo-1` and a link to the wrong heading validated.
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_suffix_skips_multiple_literal_heading_slugs(self):
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
def test_three_identical_headings(self):
body = "# Foo\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_literal_slug_before_duplicates(self):
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
def test_heading_link_contributes_only_its_text(self):
# GitHub slugs the rendered heading, where the link's URL is gone.
# Slugging the raw source appended the URL and made the first real
# link to the anchor look broken.
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
self.assertEqual(slugs, {"setup-guide-notes"})
def test_heading_link_matches_github_for_the_readme_heading(self):
# The exact heading at README.md:53; GitHub renders
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
def test_heading_link_duplicate_still_gets_a_suffix(self):
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
def test_heading_link_inside_a_code_span_stays_literal(self):
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
# the slug. Substituting links first made this `code-x-span`.
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
self.assertEqual(slugs, {"code-xy-span"})
def test_heading_mixes_a_code_span_and_a_link(self):
# Only the real link loses its URL; the code span keeps its text.
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
self.assertEqual(slugs, {"see-a-and-b"})
def test_heading_double_backtick_code_span(self):
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
# the inner single-backtick run closes the outer span early, so the
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
# observed GitHub anchor keeps this honest rather than assuming the
# "obvious" answer.
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
def test_heading_image_is_not_treated_as_a_link(self):
# An image contributes its alt text through GitHub's rendering, but
# the `(?<!\!)` guard must keep this path unchanged for now.
slugs = docs_hygiene.markdown_slugs("## ![img](a.png) caption\n")
self.assertEqual(len(slugs), 1)
def test_fenced_code_block_ignored(self):
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("real-heading", slugs)
self.assertNotIn("not-a-heading", slugs)
def test_tilde_fence_ignored(self):
body = "~~~\n# Not A Heading\n~~~\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertNotIn("not-a-heading", slugs)
def test_atx_levels(self):
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
slugs = docs_hygiene.markdown_slugs(body)
for s in ("one", "two", "three", "four", "five", "six"):
self.assertIn(s, slugs)
class CheckLinksTests(unittest.TestCase):
"""Exercise check_links with a synthetic in-memory file set."""
def _run(self, files):
"""files: dict mapping repo-relative path -> Markdown body."""
problems = []
original_text = docs_hygiene.text
def fake_text(path):
return files.get(path)
docs_hygiene.text = fake_text
try:
docs_hygiene.check_links(list(files), problems)
finally:
docs_hygiene.text = original_text
return problems
def test_existing_heading_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(problems, [])
def test_in_page_anchor_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
})
self.assertEqual(problems, [])
def test_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "[link](b.md#no-such-heading)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#no-such-heading", problems[0])
self.assertIn("heading not found", problems[0])
def test_in_page_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#this-heading-does-not-exist", problems[0])
def test_duplicate_heading_addressable(self):
problems = self._run({
"docs/a.md": "[link](b.md#setup-1)\n",
"docs/b.md": "# Setup\n\n# Setup\n",
})
self.assertEqual(problems, [])
def test_fenced_heading_not_a_slug(self):
problems = self._run({
"docs/a.md": "[link](b.md#not-a-heading)\n",
"docs/b.md": "```\n# Not A Heading\n```\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#not-a-heading", problems[0])
def test_external_url_with_fragment_not_checked(self):
problems = self._run({
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
})
self.assertEqual(problems, [])
def test_mailto_not_checked(self):
problems = self._run({
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
})
self.assertEqual(problems, [])
def test_protocol_relative_not_checked(self):
problems = self._run({
"docs/a.md": "[link](//example.com/page#frag)\n",
})
self.assertEqual(problems, [])
def test_bare_hash_skipped(self):
problems = self._run({
"docs/a.md": "[link](#)\n",
})
self.assertEqual(problems, [])
def test_missing_file_still_reported(self):
problems = self._run({
"docs/a.md": "[link](nonexistent.md#foo)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("broken relative link", problems[0])
def test_fragment_on_non_markdown_not_checked(self):
problems = self._run({
"docs/a.md": "[link](image.png#foo)\n",
"docs/image.png": None,
})
# image.png is binary (text returns None) but it exists in the
# file list, so the link itself resolves; fragment is not checked.
self.assertEqual(problems, [])
class MarkerTests(unittest.TestCase):
"""The conflict-marker check must catch all four markers, including the diff3 one."""
def _markers(self, text):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "f.md").write_text(text, encoding="utf-8")
previous = docs_hygiene.ROOT
docs_hygiene.ROOT = root
try:
problems = []
docs_hygiene.check_markers({"f.md": text}, problems)
return problems
finally:
docs_hygiene.ROOT = previous
def test_every_marker_kind_is_reported(self):
for line in ["<<<<<<< HEAD", "||||||| merged common ancestors", "=======", ">>>>>>> topic"]:
problems = self._markers(line + "\n")
self.assertEqual(len(problems), 1, f"{line!r} was not reported: {problems}")
self.assertIn("f.md:1", problems[0])
def test_diff3_base_marker_is_reported(self):
base = self._markers("||||||| merged common ancestors\n")
self.assertEqual(len(base), 1, "the diff3 base marker must be reported")
self.assertIn("conflict marker", base[0])
def test_a_diff3_block_reports_all_four_lines(self):
block = "<<<<<<< HEAD\na\n||||||| merged common ancestors\nb\n=======\nc\n>>>>>>> topic\n"
problems = self._markers(block)
self.assertEqual(len(problems), 4, problems)
def test_ordinary_content_is_not_a_marker(self):
for text in ["| a | b |\n", "||||||\n", "======\n", "prose with | pipes\n", "---\n"]:
self.assertEqual(self._markers(text), [], f"{text!r} was wrongly reported")
class WorkflowTests(unittest.TestCase):
"""check_workflows must reject unparseable YAML."""
def _check(self, text):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / ".github" / "workflows").mkdir(parents=True)
(root / ".github" / "workflows" / "a.yml").write_text(text, encoding="utf-8")
previous = docs_hygiene.ROOT
docs_hygiene.ROOT = root
try:
problems = []
docs_hygiene.check_workflows({".github/workflows/a.yml": text}, problems, require_yaml=True)
return problems
finally:
docs_hygiene.ROOT = previous
def test_parses_a_valid_workflow(self):
self.assertEqual(self._check("on: push\njobs:\n b:\n runs-on: ubuntu-latest\n"), [])
def test_reports_invalid_yaml(self):
problems = self._check("on: [push\n")
self.assertEqual(len(problems), 1, problems)
self.assertIn("a.yml", problems[0])
if __name__ == "__main__":
unittest.main()
@@ -80,12 +80,14 @@ fn collect(rx: &Receiver<Event>, until: Instant) -> io::Result<(Vec<u8>, Vec<u8>
Ok((stdout, stderr, true))
}
fn wait_until(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
/// `deadline: None` means the requested timeout is not representable on this clock, so the
/// probe is allowed to run without one (#587).
fn wait_until(child: &mut Child, deadline: Option<Instant>) -> io::Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if Instant::now() >= deadline {
if deadline.is_some_and(|at| Instant::now() >= at) {
child.kill()?;
child.wait()?;
return Ok(None);
@@ -112,7 +114,13 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
command.env(key, value);
}
}
let deadline = Instant::now() + timeout;
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow, so a
// huge value would abort the harness with exit 101 instead of one of its verdict codes
// (#586). Saturate at the platform maximum instead: the probe then simply never times out.
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow. When the
// requested timeout is not representable the probe simply has no deadline; representing
// that as `None` avoids inventing a fallback duration that might also not fit (#587).
let deadline = Instant::now().checked_add(timeout);
let mut child = command.spawn()?;
let (tx, rx) = mpsc::channel();
pump(
@@ -126,8 +134,11 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
tx,
);
let status = wait_until(&mut child, deadline)?;
let (stdout, stderr, output_complete) =
collect(&rx, deadline.max(Instant::now() + DRAIN_GRACE))?;
// With no deadline the probe has already exited, so draining still needs a bound.
let drain_until = deadline
.unwrap_or_else(Instant::now)
.max(Instant::now() + DRAIN_GRACE);
let (stdout, stderr, output_complete) = collect(&rx, drain_until)?;
Ok(ProbeRun {
status,
stdout: String::from_utf8_lossy(&stdout).into_owned(),
@@ -161,6 +172,35 @@ mod tests {
}
}
#[test]
fn an_unrepresentable_deadline_leaves_the_probe_without_a_timeout() {
// `checked_add` returns None for a timeout the clock cannot represent; the runner
// must then wait for the probe normally instead of inventing a fallback duration
// that could itself overflow (#587).
let script = Script::new("nodeadline", "sleep 0.2; exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
)
.expect("an unrepresentable deadline must not abort the run");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
assert!(run.output_complete);
}
#[test]
fn an_overflowing_timeout_does_not_panic() {
// u64::MAX seconds overflows `Instant + Duration`; before #586 this panicked.
let script = Script::new("overflow", "exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
);
let run = run.expect("an overflowing timeout must still run the probe, not panic");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
}
#[test]
fn passes_the_framework_and_only_allowlisted_environment() {
let script = Script::new("env", "echo \"args=$*\"; env; echo oops >&2; exit 3");
@@ -2,6 +2,15 @@
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
## `FSPX` errors
A malformed `FSPX` table fails inspection with a `ParseError`; it never panics. Two bounds errors are kept apart (#599):
- **`FspxLayoutMismatch`:** a descriptor's offset lands inside the 16-byte header or the descriptor table, the region the synthetic layout reserves. The table does not follow BetterXen's clean-room layout. The error carries the section id, the offset and the table length.
- **`FspxSectionOutOfBounds`:** a section starts after the table but runs past the end of the payload.
Both are still errors. Over the C ABI, both are `BX_SHADER_ERR_INVALID_BLOB`, so a caller of `bx_shader_inspect` cannot tell them apart yet; that would need an `[ABI]` change to `abi/include/bx_shader_bridge.h`.
## Guest access: `bx_shader_bridge.dll` (#445)
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
+32 -3
View File
@@ -10,6 +10,13 @@
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
//! count is rejected before any descriptor is compared with another, so
//! inspection stays allocation-free and the pairwise check stays bounded.
//!
//! A descriptor whose offset lands inside the 16-byte header or the
//! descriptor table itself is a layout mismatch, reported apart from a
//! section that runs past the end of the payload. Read through this layout,
//! such a table is not merely truncated or corrupt: its descriptors do not
//! mean `(id, offset, size)` relative to the payload as this module assumes.
//! It is still an error, and the container is still refused.
use super::{ShaderStage, read_u32_le};
@@ -82,9 +89,22 @@ impl FspxInfo {
pub(crate) enum FspxError {
Truncated,
BadVersion(u32),
SectionOutOfBounds { section_id: u32 },
DuplicateSection { section_id: u32 },
Overlap { section_id: u32 },
SectionOutOfBounds {
section_id: u32,
},
/// The descriptor's offset lies inside the header plus descriptor table,
/// the region this layout reserves, so the table does not follow it.
LayoutMismatch {
section_id: u32,
offset: u32,
table_end: u32,
},
DuplicateSection {
section_id: u32,
},
Overlap {
section_id: u32,
},
BadStageConfig,
TooManySections(u32),
}
@@ -217,6 +237,15 @@ fn walk_sections(
) -> Result<(), FspxError> {
for index in 0..header.count {
let (id, offset, size) = descriptor_at(payload, index)?;
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
return Err(FspxError::LayoutMismatch {
section_id: id,
offset,
table_end,
});
}
let end = section_end(offset, size, header.table_end, payload.len())
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
for prev in 0..index {
+685 -56
View File
@@ -9,7 +9,10 @@
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
//! [`ParseError::FspxTooManySections`] before any pairwise comparison.
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
//! descriptor whose offset lands inside the header plus descriptor table is
//! [`ParseError::FspxLayoutMismatch`], kept apart from
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
//! code byte range. The code bytes are not decoded. This layout is synthetic.
@@ -26,13 +29,16 @@
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
//! so preparation does not copy it.
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
//! size and stage metadata but does not classify as executable `DXIL`.
//!
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
//! including when an accompanying `FSPX` table is malformed, and logs only an
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
//! is not implemented.
mod c_abi;
mod fspx;
@@ -94,22 +100,104 @@ pub struct ShaderInspection {
pub chunks: Vec<ChunkInfo>,
}
impl ShaderInspection {
/// Payload of the first chunk tagged `fourcc`, if present and fully
/// inside the container. Returns `None` when absent, when the declared
/// size would run past `container_size` or `container`, or when `offset`
/// points into the DXBC header or chunk-offset table instead of a chunk
/// header.
///
/// `container` must be the same bytes passed to [`inspect_dxbc`]; the
/// inspection only stores chunk metadata, so the original container is
/// required to slice out the payload. `ChunkInfo::offset` is relative to
/// the start of the `DXBC` container and points at the 8-byte chunk
/// header (fourcc + size), so the payload begins at `offset + 8`.
///
/// A zero-size chunk yields `Some(&[])`: the header is present and
/// in-bounds, so an empty payload is a valid result rather than an
/// absence. Callers that require a minimum size must check the returned
/// slice length.
///
/// Only the already-parsed `self.chunks` table is consulted; the raw
/// chunk table is not re-walked. When several chunks share `fourcc`,
/// the first one in table order wins, matching the C++ `find_chunk`.
pub fn chunk_payload<'a>(&self, container: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
let chunk = self.chunks.iter().find(|c| &c.fourcc == fourcc)?;
let table_bytes = u64::try_from(self.chunks.len()).ok()?.checked_mul(4)?;
let table_end = 32u64.checked_add(table_bytes)?;
if u64::from(chunk.offset) < table_end {
return None;
}
let start = u64::from(chunk.offset).checked_add(8)?;
let end = start.checked_add(u64::from(chunk.size))?;
if end > u64::from(self.container_size) {
return None;
}
let start = usize::try_from(start).ok()?;
let end = usize::try_from(end).ok()?;
if end > container.len() {
return None;
}
container.get(start..end)
}
/// True when a chunk header tagged `fourcc` exists, whatever its
/// declared size. Mirrors the C++ `has_chunk_tag`: presence without
/// trusting the size.
pub fn has_chunk_tag(&self, fourcc: &[u8; 4]) -> bool {
self.chunks.iter().any(|c| &c.fourcc == fourcc)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
TooShort,
BadMagic,
UnsupportedVersion(u32),
TruncatedChunkTable,
ChunkOutOfBounds { index: usize },
ChunkOutOfBounds {
index: usize,
},
TruncatedContainer,
FspxTruncated { chunk: usize },
FspxBadVersion { chunk: usize, version: u32 },
FspxSectionOutOfBounds { chunk: usize, section_id: u32 },
FspxDuplicateSection { chunk: usize, section_id: u32 },
FspxSectionOverlap { chunk: usize, section_id: u32 },
FspxBadStageConfig { chunk: usize },
FspxTooManySections { chunk: usize, count: u32 },
BadDxilHeader { chunk: usize },
FspxTruncated {
chunk: usize,
},
FspxBadVersion {
chunk: usize,
version: u32,
},
FspxSectionOutOfBounds {
chunk: usize,
section_id: u32,
},
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
/// table (`table_end` bytes), which the synthetic layout reserves. The
/// table does not follow BetterXen's clean-room layout; it is not reported
/// as an out-of-bounds section. The container is still rejected.
FspxLayoutMismatch {
chunk: usize,
section_id: u32,
offset: u32,
table_end: u32,
},
FspxDuplicateSection {
chunk: usize,
section_id: u32,
},
FspxSectionOverlap {
chunk: usize,
section_id: u32,
},
FspxBadStageConfig {
chunk: usize,
},
FspxTooManySections {
chunk: usize,
count: u32,
},
BadDxilHeader {
chunk: usize,
},
}
impl fmt::Display for ParseError {
@@ -133,6 +221,15 @@ impl fmt::Display for ParseError {
"FSPX section {section_id} out of bounds in chunk {chunk}"
)
}
Self::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
} => write!(
f,
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
),
Self::FspxDuplicateSection { chunk, section_id } => {
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
}
@@ -185,6 +282,16 @@ fn fspx_error(chunk: usize, err: fspx::FspxError) -> ParseError {
fspx::FspxError::SectionOutOfBounds { section_id } => {
ParseError::FspxSectionOutOfBounds { chunk, section_id }
}
fspx::FspxError::LayoutMismatch {
section_id,
offset,
table_end,
} => ParseError::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
},
fspx::FspxError::DuplicateSection { section_id } => {
ParseError::FspxDuplicateSection { chunk, section_id }
}
@@ -209,14 +316,22 @@ fn record_fspx_stage(
}
}
enum DxilProgram {
Executable((ShaderStage, u8, u8)),
HeaderOnly((ShaderStage, u8, u8)),
}
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
///
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
/// and must be at least 16. `BitcodeSize` must be non-zero, and
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
/// bitcode bytes are not decoded.
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
///
/// A bitcode payload beginning with `NOBC` is a header-only container (for
/// example, reflection or signature metadata with bitcode stripped) and is
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
const PROGRAM_PREFIX: u64 = 8;
const BITCODE_HEADER: u64 = 16;
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
@@ -245,7 +360,16 @@ fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
if end > program_bytes {
return Err(());
}
Ok(program_stage(program_version))
let bitcode_start =
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
let stage = program_stage(program_version);
if bitcode.starts_with(b"NOBC") {
Ok(DxilProgram::HeaderOnly(stage))
} else {
Ok(DxilProgram::Executable(stage))
}
}
struct ContainerLimit {
@@ -352,6 +476,37 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
}
}
#[derive(Default)]
struct DxilChunkState {
has_executable: bool,
size: u32,
executable_stage: Option<(ShaderStage, u8, u8)>,
header_only_stage: Option<(ShaderStage, u8, u8)>,
}
impl DxilChunkState {
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
/// header-only placeholders regardless of chunk order.
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
DxilProgram::Executable(stage) => {
self.has_executable = true;
self.size = size;
self.executable_stage = Some(stage);
}
DxilProgram::HeaderOnly(stage) => {
if !self.has_executable {
self.size = size;
}
if self.header_only_stage.is_none() {
self.header_only_stage = Some(stage);
}
}
}
Ok(())
}
}
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
/// keep chunk or section lists.
pub(crate) struct DxbcSummary {
@@ -370,24 +525,16 @@ pub(crate) struct DxbcSummary {
///
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -408,36 +555,40 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
}
Ok(())
})?;
let (stage, shader_model_major, shader_model_minor) = dxil_stage
let (stage, shader_model_major, shader_model_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(DxbcSummary {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major,
shader_model_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
})
}
/// `Ok(Some(container_size))` when the container is structurally valid and
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no `DXIL` chunk.
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no executable `DXIL` chunk.
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
let mut has_dxil = false;
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
if &fourcc == b"DXIL" {
if read_dxil_program(payload).is_err() {
return Err(ParseError::BadDxilHeader { chunk: index });
match read_dxil_program(payload) {
Ok(DxilProgram::Executable(_)) => has_dxil = true,
Ok(DxilProgram::HeaderOnly(_)) => {}
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
}
has_dxil = true;
}
Ok(())
})?;
@@ -457,27 +608,19 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
/// container through.
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
let mut chunks = Vec::new();
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut accc_is_fspx = false;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let mut fspx = None;
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -515,21 +658,22 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
Ok(())
})?;
let (stage, sm_major, sm_minor) =
dxil_stage
.or(legacy_stage)
.or(fspx_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
let (stage, sm_major, sm_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(ShaderInspection {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major: sm_major,
shader_model_minor: sm_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
accc_is_fspx,
fspx,
@@ -868,9 +1012,11 @@ mod tests {
),
(
fspx_header(1, 1, &[(1, 0, 4)], 28),
ParseError::FspxSectionOutOfBounds {
ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 1,
offset: 0,
table_end: 28,
},
),
(
@@ -924,18 +1070,167 @@ mod tests {
#[test]
fn truncated_prefixes_do_not_panic() {
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
nobc_dxil[24..28].copy_from_slice(b"NOBC");
let blobs = [
synthetic_dxil_blob(),
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
vec![0xFF; 64],
];
for blob in blobs {
for len in 0..=blob.len() {
let _ = inspect_dxbc(&blob[..len]);
let _ = summarize_dxbc(&blob[..len]);
let _ = dxil_container_len(&blob[..len]);
}
}
}
/// A two-section table (`table_end` = 16 + 2 * 12 = 40) whose second
/// descriptor's offset is `second_offset`. The first descriptor is a valid
/// 12-byte stage section at 40, and the payload is 64 bytes long.
fn fspx_two_sections(second_offset: u32) -> Vec<u8> {
let mut payload = fspx_header(1, 2, &[(1, 40, 12), (6, second_offset, 4)], 64);
payload[40..44].copy_from_slice(&6u32.to_le_bytes());
payload[44..48].copy_from_slice(&6u32.to_le_bytes());
payload
}
#[test]
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
// Inside the 16-byte header, inside the first descriptor, inside the
// descriptor itself, and the last reserved byte.
for offset in [0u32, 8, 16, 28, 39] {
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
let expected = ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset,
table_end: 40,
};
assert_eq!(
inspect_dxbc(&blob),
Err(expected.clone()),
"offset {offset}"
);
// The C ABI path walks the table through `scan_fspx`, not
// `parse_fspx`, and must classify it the same way.
assert_eq!(
summarize_dxbc(&blob).map(|_| ()),
Err(expected),
"offset {offset}"
);
}
// The first byte after the table is outside the reserved region.
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
assert_eq!(info.kind, ShaderKind::AcccOnly);
assert_eq!(info.stage, ShaderStage::Compute);
assert!(summarize_dxbc(&blob).is_ok());
}
#[test]
fn fspx_layout_mismatch_is_not_out_of_bounds() {
// Past the payload end is still out of bounds, not a layout mismatch.
let mut payload = fspx_two_sections(62);
payload.truncate(64);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let out_of_bounds = ParseError::FspxSectionOutOfBounds {
chunk: 0,
section_id: 6,
};
assert_eq!(inspect_dxbc(&blob), Err(out_of_bounds.clone()));
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(out_of_bounds));
// A reserved offset wins even when the size would also overrun.
let mut payload = fspx_header(1, 1, &[(6, 20, u32::MAX)], 32);
payload.truncate(32);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset: 20,
table_end: 28,
})
);
let message = ParseError::FspxLayoutMismatch {
chunk: 2,
section_id: 6,
offset: 20,
table_end: 28,
}
.to_string();
assert!(message.contains("section 6"), "{message}");
assert!(message.contains("offset 20"), "{message}");
assert!(message.contains("28-byte"), "{message}");
assert!(message.contains("chunk 2"), "{message}");
assert!(!message.contains("out of bounds"), "{message}");
}
#[test]
fn c_abi_still_refuses_fspx_layout_mismatch() {
clear_shader_log();
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]);
let mut c_info = BxShaderInspection {
kind: 99,
..BxShaderInspection::default()
};
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert_eq!(c_info.kind, 0);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn arbitrary_fspx_tables_do_not_panic() {
// Deterministic xorshift so a failure reproduces.
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let mut next = || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for round in 0..4096u32 {
let len = 16 + (next() % 240) as usize;
let mut payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
payload[..4].copy_from_slice(b"FSPX");
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
let count = round % (FSPX_MAX_SECTIONS as u32 + 2);
payload[8..12].copy_from_slice(&count.to_le_bytes());
// Keep some offsets small so the reserved-region branch is hit.
if round % 2 == 0 {
let mut at = 20;
while at + 4 <= len.min(16 + count as usize * 12) {
let small = (next() % 64) as u32;
payload[at..at + 4].copy_from_slice(&small.to_le_bytes());
at += 12;
}
}
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let _ = inspect_dxbc(&blob);
let _ = summarize_dxbc(&blob);
let mut c_info = BxShaderInspection::default();
let _ = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
}
}
#[test]
fn c_abi_inspect_and_passthrough_round_trip() {
clear_shader_log();
@@ -1268,6 +1563,245 @@ mod tests {
assert!(log[0].contains("sm_minor=0"));
}
#[test]
fn nobc_dxil_is_not_classified_as_executable_dxil() {
clear_shader_log();
// Pixel shader (0), SM 6.6, with the four-byte NOBC placeholder instead of LLVM bitcode.
let mut payload = minimal_dxil_program((6u32 << 4) | 6u32);
payload[24..28].copy_from_slice(b"NOBC");
let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &payload)]);
let info = inspect_dxbc(&blob).expect("valid DXBC with NOBC header-only DXIL");
assert_eq!(info.kind, ShaderKind::Unknown);
assert_eq!(info.stage, ShaderStage::Pixel);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6));
assert_eq!(info.dxil_size, 28);
assert!(info.has_root_signature);
let mut c_info = BxShaderInspection::default();
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_OK);
assert_eq!(c_info.kind, 0); // BX_SHADER_UNKNOWN
assert_eq!(c_info.stage, 1); // BX_STAGE_PIXEL
assert_eq!(c_info.shader_model_major, 6);
assert_eq!(c_info.shader_model_minor, 6);
assert_eq!(c_info.dxil_chunk_size, 28);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn nobc_dxil_with_accc_is_classified_as_accc_only_and_rejected() {
clear_shader_log();
let mut dxil = minimal_dxil_program((1u32 << 16) | (6u32 << 4) | 6u32);
dxil[24..28].copy_from_slice(b"NOBC");
let fspx = fspx_compute_stage();
let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil), (b"ACCC", &fspx)]);
let info = inspect_dxbc(&blob).expect("NOBC + ACCC container");
assert_eq!(info.kind, ShaderKind::AcccOnly);
assert_eq!(info.stage, ShaderStage::Compute);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0));
assert_eq!(info.dxil_size, 28);
assert_eq!(info.accc_size, 40);
let mut c_info = BxShaderInspection::default();
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_OK);
assert_eq!(c_info.kind, 3); // BX_SHADER_DXBC_ACCC
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
let log = shader_log_lines();
assert_eq!(log.len(), 1);
assert!(log[0].contains("kind=accc_only(3)"));
}
#[test]
fn nobc_dxil_with_padded_bitcode_is_still_header_only() {
let mut payload = vec![0u8; 32];
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
payload[0..4].copy_from_slice(&prog.to_le_bytes());
payload[4..8].copy_from_slice(&8u32.to_le_bytes());
payload[8..12].copy_from_slice(b"DXIL");
payload[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
payload[16..20].copy_from_slice(&16u32.to_le_bytes());
payload[20..24].copy_from_slice(&8u32.to_le_bytes());
payload[24..28].copy_from_slice(b"NOBC");
let blob = build_synthetic_dxbc(&[(b"DXIL", &payload)]);
let info = inspect_dxbc(&blob).expect("padded NOBC DXIL");
assert_eq!(info.kind, ShaderKind::Unknown);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
}
#[test]
fn mixed_executable_and_nobc_dxil_preserves_executable_metadata() {
let exec = minimal_dxil_program((5u32 << 16) | (6u32 << 4) | 5u32);
let mut nobc = vec![0u8; 32];
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
nobc[0..4].copy_from_slice(&prog.to_le_bytes());
nobc[4..8].copy_from_slice(&8u32.to_le_bytes());
nobc[8..12].copy_from_slice(b"DXIL");
nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
nobc[16..20].copy_from_slice(&16u32.to_le_bytes());
nobc[20..24].copy_from_slice(&8u32.to_le_bytes());
nobc[24..28].copy_from_slice(b"NOBC");
// Executable first, NOBC second: executable stage and size must win.
let blob_exec_first = build_synthetic_dxbc(&[(b"DXIL", &exec), (b"DXIL", &nobc)]);
let info = inspect_dxbc(&blob_exec_first).expect("mixed DXIL");
assert_eq!(info.kind, ShaderKind::Dxil);
assert_eq!(info.stage, ShaderStage::Compute);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 5));
assert_eq!(info.dxil_size, 28);
let mut c_info = BxShaderInspection::default();
assert_eq!(
unsafe {
bx_shader_inspect(blob_exec_first.as_ptr(), blob_exec_first.len(), &mut c_info)
},
BX_SHADER_OK
);
assert_eq!(c_info.kind, 1); // BX_SHADER_DXBC_DXIL
assert_eq!(c_info.stage, 6); // BX_STAGE_COMPUTE
assert_eq!(c_info.dxil_chunk_size, 28);
assert_eq!(
dxil_container_len(&blob_exec_first),
Ok(Some(blob_exec_first.len() as u32))
);
// NOBC first, executable second: executable must still win.
let blob_nobc_first = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"DXIL", &exec)]);
let info2 = inspect_dxbc(&blob_nobc_first).expect("mixed DXIL reversed");
assert_eq!(info2.kind, ShaderKind::Dxil);
assert_eq!(info2.stage, ShaderStage::Compute);
assert_eq!((info2.shader_model_major, info2.shader_model_minor), (6, 5));
assert_eq!(info2.dxil_size, 28);
let summary2 = summarize_dxbc(&blob_nobc_first).expect("mixed DXIL summary");
assert_eq!(summary2.kind, ShaderKind::Dxil);
assert_eq!(summary2.stage, ShaderStage::Compute);
assert_eq!(summary2.dxil_size, 28);
}
#[test]
fn nobc_dxil_with_malformed_fspx_returns_invalid_blob() {
clear_shader_log();
let mut nobc = minimal_dxil_program((6u32 << 4) | 6u32);
nobc[24..28].copy_from_slice(b"NOBC");
let bad_fspx = fspx_header(99, 0, &[], 16);
let blob = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"ACCC", &bad_fspx)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::FspxBadVersion {
chunk: 1,
version: 99,
})
);
assert_eq!(dxil_container_len(&blob), Ok(None));
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn dxil_bitcode_bounds_and_offset_checks() {
let prog = (5u32 << 16) | (6u32 << 4) | 6u32;
// Bitcode shorter than 4 bytes (`NOB`) must not misclassify as `NOBC` or read out of bounds.
let mut short_bitcode = [0u8; 28];
short_bitcode[0..4].copy_from_slice(&prog.to_le_bytes());
short_bitcode[4..8].copy_from_slice(&7u32.to_le_bytes());
short_bitcode[8..12].copy_from_slice(b"DXIL");
short_bitcode[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
short_bitcode[16..20].copy_from_slice(&16u32.to_le_bytes());
short_bitcode[20..24].copy_from_slice(&3u32.to_le_bytes());
short_bitcode[24..27].copy_from_slice(b"NOB");
let blob_short = build_synthetic_dxbc(&[(b"DXIL", &short_bitcode)]);
assert_eq!(
inspect_dxbc(&blob_short).expect("3-byte bitcode").kind,
ShaderKind::Dxil
);
// `NOBC` check follows `BitcodeOffset`, not a fixed offset 24.
let mut shifted_nobc = vec![0u8; 36];
shifted_nobc[0..4].copy_from_slice(&prog.to_le_bytes());
shifted_nobc[4..8].copy_from_slice(&9u32.to_le_bytes());
shifted_nobc[8..12].copy_from_slice(b"DXIL");
shifted_nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
shifted_nobc[16..20].copy_from_slice(&24u32.to_le_bytes());
shifted_nobc[20..24].copy_from_slice(&4u32.to_le_bytes());
shifted_nobc[32..36].copy_from_slice(b"NOBC");
let blob_shifted_nobc = build_synthetic_dxbc(&[(b"DXIL", &shifted_nobc)]);
assert_eq!(
inspect_dxbc(&blob_shifted_nobc).expect("shifted NOBC").kind,
ShaderKind::Unknown
);
assert_eq!(dxil_container_len(&blob_shifted_nobc), Ok(None));
// Bytes before `BitcodeOffset` containing `NOBC` do not make executable bitcode header-only.
let mut shifted_exec = shifted_nobc;
shifted_exec[24..28].copy_from_slice(b"NOBC");
shifted_exec[32..36].copy_from_slice(&[0xD1, 0x11, 0xC0, 0xDE]);
let blob_shifted_exec = build_synthetic_dxbc(&[(b"DXIL", &shifted_exec)]);
assert_eq!(
inspect_dxbc(&blob_shifted_exec)
.expect("shifted executable")
.kind,
ShaderKind::Dxil
);
// Overflowing bitcode offset / size must reject cleanly as `BadDxilHeader`.
for (bitcode_off, bitcode_sz) in [(16u32, u32::MAX), (u32::MAX - 4, 4u32)] {
let mut overflow = minimal_dxil_program(prog);
overflow[16..20].copy_from_slice(&bitcode_off.to_le_bytes());
overflow[20..24].copy_from_slice(&bitcode_sz.to_le_bytes());
let blob = build_synthetic_dxbc(&[(b"DXIL", &overflow)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
assert_eq!(
summarize_dxbc(&blob).map(|_| ()),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
assert_eq!(
dxil_container_len(&blob),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
}
}
fn fspx_table_with_sections(count: u32) -> Vec<u8> {
let count_usize = count as usize;
let table_end = 16 + count_usize * 12;
@@ -1302,4 +1836,99 @@ mod tests {
fn ptr_sentinel() -> *mut u8 {
std::ptr::dangling_mut()
}
#[test]
fn chunk_payload_returns_sfi0_and_psv0_bytes() {
let sfi0: [u8; 8] = [0x00, 0x40, 0, 0, 0, 0, 0, 0];
let psv0: [u8; 28] = [
24, 0, 0, 0, // info_size = 24
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, // lanes_min
64, 0, 0, 0, // lanes_max
];
let blob = build_synthetic_dxbc(&[(b"SFI0", &sfi0), (b"PSV0", &psv0)]);
let info = inspect_dxbc(&blob).expect("valid container");
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(sfi0.as_slice()));
assert_eq!(info.chunk_payload(&blob, b"PSV0"), Some(psv0.as_slice()));
assert!(info.has_chunk_tag(b"SFI0"));
assert!(info.has_chunk_tag(b"PSV0"));
}
#[test]
fn chunk_payload_rejects_declared_size_past_container() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4])]);
let mut info = inspect_dxbc(&blob).expect("valid container");
// A declared size that runs past container_size must yield None, not
// a panic and not a slice clipped to the container.
info.chunks[0].size = u32::MAX;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// Presence without trusting the size still holds.
assert!(info.has_chunk_tag(b"SFI0"));
// A forged public ChunkInfo must not treat the DXBC header or offset
// table as a chunk header.
info.chunks[0].size = 4;
info.chunks[0].offset = 0;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// A header offset past the container must also yield None.
info.chunks[0].offset = u32::MAX;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// A chunk header that would end exactly one byte past the container.
info.chunks[0].offset = info.container_size - 7;
info.chunks[0].size = 0;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
}
#[test]
fn chunk_payload_absent_fourcc() {
let blob = synthetic_dxil_blob();
let info = inspect_dxbc(&blob).expect("valid");
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
assert!(!info.has_chunk_tag(b"SFI0"));
}
#[test]
fn chunk_payload_zero_size_returns_empty_slice() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[])]);
let info = inspect_dxbc(&blob).expect("valid");
assert!(info.has_chunk_tag(b"SFI0"));
let payload = info.chunk_payload(&blob, b"SFI0");
assert_eq!(payload, Some(&[][..]));
}
#[test]
fn chunk_payload_exact_fit_at_container_end() {
let payload = [0xAA, 0xBB, 0xCC, 0xDD];
let blob = build_synthetic_dxbc(&[(b"SFI0", &payload)]);
let info = inspect_dxbc(&blob).expect("valid");
// The chunk is the last thing in the container; payload ends exactly
// at container_size.
let chunk = &info.chunks[0];
assert_eq!(
u64::from(chunk.offset) + 8 + u64::from(chunk.size),
u64::from(info.container_size)
);
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(payload.as_slice()));
}
#[test]
fn chunk_payload_truncated_container_slice() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4, 5, 6, 7, 8])]);
let info = inspect_dxbc(&blob).expect("valid");
// Pass a slice shorter than container_size.
let short = &blob[..blob.len() - 4];
assert_eq!(info.chunk_payload(short, b"SFI0"), None);
}
#[test]
fn chunk_payload_first_duplicate_wins() {
let first = [0x11, 0x22];
let second = [0x33, 0x44, 0x55];
let blob = build_synthetic_dxbc(&[(b"SFI0", &first), (b"SFI0", &second)]);
let info = inspect_dxbc(&blob).expect("valid");
assert_eq!(info.chunks.len(), 2);
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(first.as_slice()));
}
}
+106 -16
View File
@@ -1,29 +1,52 @@
#include <windows.h>
#include <unknwn.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <new>
#include "bx_log.h"
namespace {
class AcpHal final : public IUnknown {
LONG refs = 1;
// IAcpHal (authorized GDK documentation; slot order derived from it): not a COM interface. Its
// six methods are Connect(numCommands, numMessages), Disconnect(), SubmitCommand(command,
// commandId, audioFrame, data, notification), PopMessage(ACP_MESSAGE*), GetNumMessages() and
// Release(). BetterXen has no audio control processor: commands are accepted and logged once,
// and no message ever arrives.
class AcpHal {
UINT32 commands_ = 0, messages_ = 0;
bool connected_ = false;
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown) return E_NOINTERFACE;
AddRef();
*out = this;
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
commands_ = num_commands;
messages_ = num_messages;
connected_ = true;
char detail[96];
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
ULONG left = InterlockedDecrement(&refs);
if (!left) delete this;
return left;
virtual HRESULT WINAPI Disconnect() {
connected_ = false;
return S_OK;
}
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
if (!connected_) return E_UNEXPECTED;
static LONG logged = 0;
if (InterlockedIncrement(&logged) == 1) {
char detail[96];
std::snprintf(detail, sizeof(detail), "first command type %u accepted; ACP commands are not processed", command);
bx_log_emit(BX_LOG_WARN, "acphal", "submit_command", detail);
}
return S_OK;
}
virtual bool WINAPI PopMessage(void*) { return false; }
virtual UINT32 WINAPI GetNumMessages() { return 0; }
virtual void WINAPI Release() { delete this; }
virtual ~AcpHal() = default;
};
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
@@ -47,19 +70,86 @@ HRESULT WINAPI AcpHalCreate(void** out) {
return *out ? S_OK : E_OUTOFMEMORY;
}
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment);
HRESULT WINAPI ApuFree(void* va);
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) / AcpHalReleaseShapeContexts() (authorized GDK
// documentation; layout and element sizes derived from it, no header text): the caller fills six
// counts, the call allocates each array from the APU heap and returns its CPU pointer and APU
// address. Allocating twice without a release fails with ACP_E_ALREADY_ALLOCATED.
struct ShapeContexts {
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
void* arrays[6]; // CPU pointers, same order
uint32_t apu[6]; // APU addresses, same order
};
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS is 96 bytes");
static_assert(offsetof(ShapeContexts, arrays) == 24 && offsetof(ShapeContexts, apu) == 72, "SHAPE_CONTEXTS layout");
constexpr uint32_t kShapeElementBytes[6] = {32, 160, 32, 16, 64, 32};
constexpr HRESULT kAcpAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
constexpr uint32_t kDefaultApuHeapBytes = 64u << 20;
void* shape_arrays[6];
bool shape_allocated = false;
HRESULT WINAPI AcpHalAllocateShapeContexts(void* argument) {
auto* contexts = static_cast<ShapeContexts*>(argument);
if (!contexts) return E_INVALIDARG;
if (shape_allocated) return kAcpAlreadyAllocated;
for (int i = 0; i < 6; ++i) {
if (contexts->counts[i] > (0xFFFFFFFFu / kShapeElementBytes[i])) return E_INVALIDARG;
}
{
// The console has a default non-cached APU heap; create one when the title made none.
std::lock_guard guard(heap_lock);
if (!heap_created) {
capacity = kDefaultApuHeapBytes;
used = 0;
heap_created = true;
bx_log_emit(BX_LOG_INFO, "acphal", "apu_default_heap", "no ApuCreateHeap before shape contexts: 64 MB default heap");
}
}
void* arrays[6] = {};
uint32_t apu[6] = {};
for (int i = 0; i < 6; ++i) {
if (!contexts->counts[i]) continue;
const uint32_t bytes = contexts->counts[i] * kShapeElementBytes[i];
const HRESULT hr = ApuAlloc(&arrays[i], &apu[i], bytes, 64);
if (FAILED(hr)) {
for (int j = 0; j < i; ++j) ApuFree(arrays[j]);
return E_OUTOFMEMORY;
}
std::memset(arrays[i], 0, bytes);
}
for (int i = 0; i < 6; ++i) {
contexts->arrays[i] = arrays[i];
contexts->apu[i] = apu[i];
shape_arrays[i] = arrays[i];
}
shape_allocated = true;
char detail[160];
std::snprintf(detail, sizeof(detail), "src=%u eqcomp=%u filtvol=%u dma=%u xma=%u pcm=%u", contexts->counts[0],
contexts->counts[1], contexts->counts[2], contexts->counts[3], contexts->counts[4], contexts->counts[5]);
bx_log_emit(BX_LOG_INFO, "acphal", "shape_contexts_allocated", detail);
return S_OK;
}
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
if (!shape_allocated) return S_OK;
for (void*& array : shape_arrays) {
ApuFree(array);
array = nullptr;
}
shape_allocated = false;
return S_OK;
}
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
std::lock_guard guard(heap_lock);
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
// A zero-capacity heap must not report S_OK: it can never satisfy an
// allocation, so creating it is a caller error (#580). ApuAlloc already
// refused such requests with E_OUTOFMEMORY.
if (uint64_t(cached) + non_cached == 0) return E_INVALIDARG;
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
used = 0;
capacity = uint64_t(cached) + non_cached;
+13 -1
View File
@@ -1,8 +1,20 @@
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
d3d12_xs.cpp
vmem.cpp
presentx.cpp
proxy.cpp
proxy_generated.cpp
shader_gate.cpp
xbox_facade.cpp
frame_pacing.cpp
placed_x.cpp
descriptor_heaps.cpp
committed.cpp
pipelines.cpp
gpu_writes.cpp
fences.cpp
presentx_xbox.cpp
page_mappings.cpp
xbox_tables_generated.cpp
)
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32 user32 dxguid)
+100
View File
@@ -0,0 +1,100 @@
/*
* Committed resources with title-visible memory (ADR 0009).
*
* On the console the D3D12 runtime allocates a committed resource's memory through XMemAlloc
* with AllocatorId eXALLOCAllocatorId_D3D (128) and ObjectType Resource (4) (authorized GDK
* documentation, "Direct3D 12 XMemAlloc object types"). Titles hook XMemAlloc to place that
* memory themselves, and some check afterwards how much of their own pool those requests used.
*
* Here the host committed resource holds the contents. The resource also gets the same
* XMemAlloc request, and its GPU virtual address is the address that request returned, so title
* hooks and title address checks see what they would see on the console. The page size the
* console runtime requests is not documented: this layer asks for 2 MB pages for allocations of
* at least 2 MB and 64 KB pages otherwise (measured against one title; logged per resource).
*/
#include "xbox_facade.h"
#include <cstdio>
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
namespace {
constexpr ULONGLONG kObjectTypeResource = 4;
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
constexpr ULONGLONG kPageSize64K = 1ull << 14; // XALLOC_ATTRIBUTES.PageSize, bits 14-15
constexpr ULONGLONG kPageSize2M = 2ull << 14;
constexpr UINT64 k2M = 2ull << 20;
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method) {
if (FAILED(hr) || !ppv || !*ppv) return hr;
// *ppv is the host resource as `riid`; every ID3D12Resource* interface pointer is the object.
auto* resource = static_cast<ID3D12Resource*>(*ppv);
const D3D12_RESOURCE_DESC desc = resource->GetDesc();
const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
const UINT64 size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D | (size >= k2M ? kPageSize2M : kPageSize64K);
void* title = XMemAlloc(static_cast<SIZE_T>(size), attributes);
char detail[200];
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu page=%s title_va=%p", method,
static_cast<int>(desc.Dimension), static_cast<unsigned long long>(size),
size >= k2M ? "2MB" : "64KB", title);
bx_log_emit(title ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "committed_title_memory", detail);
if (!title || !bx_xbox_title_memory_attach(resource, reinterpret_cast<uint64_t>(title), size, attributes)) {
resource->Release();
*ppv = nullptr;
return E_OUTOFMEMORY;
}
return bx_xbox_wrap_result(hr, riid, ppv);
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource");
auto* device = bx_xbox_host<ID3D12Device>(self);
return finish(device, device->CreateCommittedResource(heap, flags, desc, state, clear, riid, ppv), riid, ppv,
"CreateCommittedResource");
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource1");
auto* device = bx_xbox_host<ID3D12Device4>(self);
return finish(device, device->CreateCommittedResource1(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
riid, ppv, "CreateCommittedResource1");
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource2");
auto* device = bx_xbox_host<ID3D12Device8>(self);
return finish(device, device->CreateCommittedResource2(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
riid, ppv, "CreateCommittedResource2");
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, UINT32 formats,
DXGI_FORMAT* castable, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource3");
auto* device = bx_xbox_host<ID3D12Device10>(self);
return finish(device,
device->CreateCommittedResource3(heap, flags, desc, layout, clear, bx_xbox_unwrap_as(session), formats,
castable, riid, ppv),
riid, ppv, "CreateCommittedResource3");
}
} // extern "C"
+88 -8
View File
@@ -1,7 +1,10 @@
#include "proxy.h"
#include "vmem.h"
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
/*
@@ -20,6 +23,38 @@ HMODULE get_host_d3d12() {
return mod;
}
// A failed host serialization is the title's error to handle, but it is logged with the host's
// message and the shape of the description so the rejected feature can be found.
void log_serialize_failure(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, HRESULT hr, ID3DBlob* errors) {
static std::atomic<uint32_t> logged{0};
if (logged.fetch_add(1) >= 32) return;
char shape[160] = "desc=null";
if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_1) {
const auto& d = desc->Desc_1_1;
std::snprintf(shape, sizeof(shape), "version=1.1 params=%u samplers=%u flags=0x%x", d.NumParameters,
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
} else if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_0) {
const auto& d = desc->Desc_1_0;
std::snprintf(shape, sizeof(shape), "version=1.0 params=%u samplers=%u flags=0x%x", d.NumParameters,
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
} else if (desc) {
std::snprintf(shape, sizeof(shape), "version=%u", static_cast<unsigned>(desc->Version));
}
char message[160] = "";
if (errors && errors->GetBufferPointer() && errors->GetBufferSize()) {
const size_t n = errors->GetBufferSize() < sizeof(message) - 1 ? errors->GetBufferSize() : sizeof(message) - 1;
std::memcpy(message, errors->GetBufferPointer(), n);
message[n] = '\0';
for (char& ch : message) {
if (ch == '"' || ch == '\\' || static_cast<unsigned char>(ch) < 0x20) ch = ' ';
}
}
char detail[384];
std::snprintf(detail, sizeof(detail), "hr=0x%08lx %s host_error=%s", static_cast<unsigned long>(hr), shape,
message[0] ? message : "(none)");
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "root_signature_serialize_failed", detail);
}
void initialize_trace_flag() {
static std::once_flag initialized;
std::call_once(initialized, [] {
@@ -33,17 +68,29 @@ void initialize_trace_flag() {
extern "C" {
/*
* `params` is the console creation-parameter block. Its layout is not defined in abi/ and is not
* interpreted here: the host device is created on the default adapter at the lowest feature level
* D3D12 accepts, and that fact is logged. `riid` must name an interface the proxy models (or one
* the host device answers); anything else fails with E_NOINTERFACE and a logged IID.
* The documented four-parameter form (authorized GDK documentation, d3d12_x.h / d3d12_xs.h):
* an optional adapter, a required D3D12XBOX_CREATE_DEVICE_PARAMETERS block, the interface ID and
* the device out pointer. A NULL parameter block fails with E_INVALIDARG, as documented.
*
* BetterXen has no adapter objects, so a non-NULL adapter is logged and the default host adapter
* is used (an inference, not a documented fallback). Of the parameter block only `Version`, its
* first UINT, is read and logged; the other fields are not interpreted. The host device is
* created at the lowest feature level D3D12 accepts. `riid` must name an interface the proxy
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
* IID.
*/
HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
if (!ppv) {
return E_POINTER;
}
*ppv = nullptr;
initialize_trace_flag();
if (!params) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "D3D12XboxCreateDevice", "refused: NULL parameter block (E_INVALIDARG)");
return E_INVALIDARG;
}
UINT version = 0;
std::memcpy(&version, params, sizeof(version));
using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
HMODULE d3d12 = get_host_d3d12();
@@ -98,12 +145,40 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
}
char detail[256];
std::snprintf(detail, sizeof(detail),
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
static_cast<void*>(proxy->h_ID3D12Device), highest, params ? "non-null" : "null", g_bx_trace_d3d);
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params_version=%u "
"(other fields not interpreted) adapter=%s trace_d3d=%u",
static_cast<void*>(proxy->h_ID3D12Device), highest, version,
adapter ? "non-null (ignored, default host adapter)" : "default", g_bx_trace_d3d);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
/*
* ADR 0009: a title built against the Xbox header calls through Xbox-order function tables,
* so it gets an Xbox-layout device over the PC proxy. The documentation requires titles to
* set Version (D3D12_SDK_VERSION); BetterXen's synthetic fixtures, which are PC-layout
* clients built against <d3d12.h>, pass a zeroed block and keep the PC proxy.
*/
if (version != 0 && bx_xbox_iface_for(riid) == &bx_xbox_Device) {
void* pc = nullptr;
hr = proxy->QueryInterface(riid, &pc);
proxy->Release();
if (FAILED(hr) || !pc) return FAILED(hr) ? hr : E_NOINTERFACE;
// The wrap fails (E_NOINTERFACE, logged) when the host device lacks the interface the Xbox
// table forwards to: a title must not get a PC-layout device reported as an Xbox one.
HRESULT failure = E_OUTOFMEMORY;
*ppv = bx_xbox_wrap(riid, pc, &failure);
bx_log_emit(*ppv ? BX_LOG_INFO : BX_LOG_ERROR, "d3d12_xs", "xbox_layout",
*ppv ? "device=xbox_function_tables"
: "device=refused: the host device lacks the interface the Xbox device table forwards to "
"(the D3DMetal backend provides it)");
return *ppv ? S_OK : failure;
}
hr = proxy->QueryInterface(riid, ppv);
proxy->Release();
if (SUCCEEDED(hr)) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "xbox_layout",
version == 0 ? "device=pc_layout (params Version 0: synthetic PC-layout client)"
: "device=pc_layout (interface has no Xbox table)");
}
return hr;
}
@@ -122,7 +197,12 @@ HRESULT WINAPI D3D12SerializeVersionedRootSignature(
auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(
GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")));
if (fn) {
return fn(desc, blob, error_blob);
ID3DBlob* local_error = nullptr;
ID3DBlob** errors = error_blob ? error_blob : &local_error;
const HRESULT hr = fn(desc, blob, errors);
if (FAILED(hr)) log_serialize_failure(desc, hr, *errors);
if (local_error) local_error->Release();
return hr;
}
}
BX_STUB_LOG("d3d12_xs.dll", "D3D12SerializeVersionedRootSignature");
+294
View File
@@ -0,0 +1,294 @@
/*
* Descriptor heaps at title-visible addresses (ADR 0009).
*
* On the console a descriptor handle is an address: the runtime allocates a heap's storage as a
* GPU allocation through XMemAlloc (object type Resource, allocator D3D), so a title's allocation
* hooks can place it in the title's own memory, and handles are base + index * descriptor size,
* with the console's sizes (32 bytes CBV/SRV/UAV, 16 sampler, 112 RTV, 128 DSV).
*
* Here each heap has that title-visible storage (allocated the same way, so the title's hooks
* see the same request) and a host D3D12 heap. Title handles are translated to host handles by
* index. The storage is not interpreted: descriptors a title writes there inline (titles built
* with D3DCOMPILE_NO_DEBUG) are not translated, and ID3D12Device's m_OutOfLineFlags keeps the
* other titles' descriptor writes on the out-of-line path, which reaches the host heap.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
namespace {
constexpr ULONGLONG kObjectTypeResource = 4; // D3D12 XMemAlloc object types: GPU "Resource"
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
struct Heap {
uintptr_t base;
UINT count;
UINT xbox_size;
ID3D12DescriptorHeap* host; // not owned: the Xbox object owns the reference
SIZE_T host_cpu;
UINT64 host_gpu;
UINT host_increment;
ULONGLONG attributes;
};
std::mutex g_lock;
Heap* g_heaps = nullptr;
size_t g_count = 0;
size_t g_capacity = 0;
bool add(const Heap& heap) {
std::lock_guard<std::mutex> guard(g_lock);
if (g_count == g_capacity) {
const size_t capacity = g_capacity ? g_capacity * 2 : 32;
auto* grown = new (std::nothrow) Heap[capacity];
if (!grown) return false;
for (size_t i = 0; i < g_count; ++i) grown[i] = g_heaps[i];
delete[] g_heaps;
g_heaps = grown;
g_capacity = capacity;
}
g_heaps[g_count++] = heap;
return true;
}
const Heap* find_locked(uintptr_t address) {
for (size_t i = 0; i < g_count; ++i) {
const Heap& h = g_heaps[i];
if (address >= h.base && address < h.base + static_cast<uintptr_t>(h.count) * h.xbox_size) return &h;
}
return nullptr;
}
void log_untranslated(const char* what, uint64_t value) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) >= 8) return; // the first few are enough to see the pattern
char detail[96];
std::snprintf(detail, sizeof(detail), "%s 0x%llx is in no title descriptor heap", what,
static_cast<unsigned long long>(value));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "descriptor_untranslated", detail);
}
} // namespace
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type) {
switch (type) {
case D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV: return 32;
case D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER: return 16;
case D3D12_DESCRIPTOR_HEAP_TYPE_RTV: return 112;
case D3D12_DESCRIPTOR_HEAP_TYPE_DSV: return 128;
default: return 32;
}
}
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title) {
if (!title.ptr) return title;
std::lock_guard<std::mutex> guard(g_lock);
if (const Heap* h = find_locked(title.ptr)) {
return {h->host_cpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
}
log_untranslated("CPU descriptor handle", title.ptr);
return title;
}
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title) {
if (!title.ptr) return title;
std::lock_guard<std::mutex> guard(g_lock);
if (const Heap* h = find_locked(static_cast<uintptr_t>(title.ptr))) {
if (h->host_gpu) return {h->host_gpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
}
log_untranslated("GPU descriptor handle", title.ptr);
return title;
}
void bx_xbox_descriptor_heap_forget(IUnknown* host) {
Heap gone{};
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (static_cast<IUnknown*>(g_heaps[i].host) == host) {
gone = g_heaps[i];
g_heaps[i] = g_heaps[--g_count];
break;
}
}
}
if (gone.base) XMemFree(reinterpret_cast<void*>(gone.base), gone.attributes);
}
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDescriptorHeap");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device>(self);
ID3D12DescriptorHeap* host = nullptr;
HRESULT hr = device->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&host));
if (FAILED(hr) || !host) return FAILED(hr) ? hr : E_FAIL;
const UINT size = bx_xbox_descriptor_size(desc->Type);
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D;
void* storage = XMemAlloc(static_cast<SIZE_T>(desc->NumDescriptors) * size, attributes);
char detail[200];
std::snprintf(detail, sizeof(detail), "type=%d count=%u xbox_size=%u flags=0x%x title_base=%p",
static_cast<int>(desc->Type), desc->NumDescriptors, size, static_cast<unsigned>(desc->Flags), storage);
bx_log_emit(storage ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "descriptor_heap", detail);
if (!storage) {
host->Release();
return E_OUTOFMEMORY;
}
D3D12_CPU_DESCRIPTOR_HANDLE cpu{};
host->GetCPUDescriptorHandleForHeapStart(&cpu);
D3D12_GPU_DESCRIPTOR_HANDLE gpu{};
if (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) host->GetGPUDescriptorHandleForHeapStart(&gpu);
const Heap heap{reinterpret_cast<uintptr_t>(storage), desc->NumDescriptors, size, host, cpu.ptr, gpu.ptr,
device->GetDescriptorHandleIncrementSize(desc->Type), attributes};
if (!add(heap)) {
XMemFree(storage, attributes);
host->Release();
return E_OUTOFMEMORY;
}
*ppv = host;
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void*, D3D12_DESCRIPTOR_HEAP_TYPE type) {
return bx_xbox_descriptor_size(type);
}
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self) {
auto* host = bx_xbox_host<ID3D12DescriptorHeap>(self);
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_heaps[i].host == host) return {g_heaps[i].base};
}
return {0};
}
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self) {
// On the console the GPU handle of a heap is the same address as its CPU handle.
return {bx_xbox_heap_cpu_start(self).ptr};
}
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateConstantBufferView");
D3D12_CONSTANT_BUFFER_VIEW_DESC host_desc{};
if (desc) {
host_desc = *desc;
host_desc.BufferLocation = bx_xbox_host_gpu_va(desc->BufferLocation);
}
bx_xbox_host<ID3D12Device>(self)->CreateConstantBufferView(desc ? &host_desc : nullptr, bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
const UINT* dest_sizes, UINT src_ranges,
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
D3D12_DESCRIPTOR_HEAP_TYPE type) {
BX_D3D_TRACE("XboxDevice", "CopyDescriptors");
auto* dst = new (std::nothrow) D3D12_CPU_DESCRIPTOR_HANDLE[dest_ranges + src_ranges + 1];
if (!dst) return;
D3D12_CPU_DESCRIPTOR_HANDLE* src = dst + dest_ranges;
for (UINT i = 0; i < dest_ranges; ++i) dst[i] = bx_xbox_host_cpu_handle(dest_starts[i]);
for (UINT i = 0; i < src_ranges; ++i) src[i] = bx_xbox_host_cpu_handle(src_starts[i]);
bx_xbox_host<ID3D12Device>(self)->CopyDescriptors(dest_ranges, dst, dest_sizes, src_ranges, src, src_sizes, type);
delete[] dst;
}
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv) {
BX_D3D_TRACE("XboxGraphicsCommandList", "OMSetRenderTargets");
D3D12_CPU_DESCRIPTOR_HANDLE host_rtvs[8] = {};
const UINT n = count > 8 ? 8 : count;
for (UINT i = 0; rtvs && i < (single_range ? 1u : n); ++i) host_rtvs[i] = bx_xbox_host_cpu_handle(rtvs[i]);
const D3D12_CPU_DESCRIPTOR_HANDLE host_dsv = dsv ? bx_xbox_host_cpu_handle(*dsv) : D3D12_CPU_DESCRIPTOR_HANDLE{};
bx_xbox_host<ID3D12GraphicsCommandList>(self)->OMSetRenderTargets(n, rtvs ? host_rtvs : nullptr, single_range,
dsv ? &host_dsv : nullptr);
}
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
D3D12_VERTEX_BUFFER_VIEW host[32] = {};
const UINT n = count > 32 ? 32 : count;
for (UINT i = 0; views && i < n; ++i) {
host[i] = views[i];
host[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
}
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetIndexBuffer");
D3D12_INDEX_BUFFER_VIEW host{};
if (view) {
host = *view;
host.BufferLocation = bx_xbox_host_gpu_va(view->BufferLocation);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetIndexBuffer(view ? &host : nullptr);
}
} // extern "C"
namespace {
/* The leading fields of D3D12XBOX_SAMPLER_DESC (authorized GDK header; every field is 4 bytes). */
struct XboxSamplerPrefix {
UINT flags;
UINT filter_mag; // D3D12XBOX_TEXTURE_XY_FILTER: 0 point, 1 bilinear, 2 aniso point, 3 aniso bilinear
UINT filter_min;
UINT filter_mip; // D3D12XBOX_TEXTURE_MIP_FILTER: 0 none, 1 point, 2 linear
UINT filter_z;
UINT filter_mode; // D3D12XBOX_TEXTURE_FILTER_MODE: 0 lerp, 1 min, 2 max
D3D12_TEXTURE_ADDRESS_MODE address_u, address_v, address_w;
FLOAT min_lod, max_lod, mip_lod_bias, mip_lod_bias_secondary;
UINT max_anisotropy;
FLOAT anisotropy_bias;
UINT anisotropy_threshold;
D3D12_COMPARISON_FUNC comparison;
FLOAT border_color[4];
};
static_assert(sizeof(XboxSamplerPrefix) == 21 * 4, "D3D12XBOX_SAMPLER_DESC prefix layout");
D3D12_FILTER_TYPE xy_type(UINT filter) { return (filter & 1) ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT; }
} // namespace
extern "C" void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateSamplerX");
if (!xbox_desc) return;
XboxSamplerPrefix x{};
std::memcpy(&x, xbox_desc, sizeof(x));
// A comparison function other than NEVER selects comparison filtering (inference: the console
// description has no separate comparison filter, so the function is the only signal).
const bool compare = x.comparison > D3D12_COMPARISON_FUNC_NEVER;
const D3D12_FILTER_REDUCTION_TYPE reduction = compare ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON
: x.filter_mode == 1 ? D3D12_FILTER_REDUCTION_TYPE_MINIMUM
: x.filter_mode == 2 ? D3D12_FILTER_REDUCTION_TYPE_MAXIMUM
: D3D12_FILTER_REDUCTION_TYPE_STANDARD;
D3D12_SAMPLER_DESC pc{};
const bool aniso = x.filter_mag >= 2 || x.filter_min >= 2;
pc.Filter = aniso ? D3D12_ENCODE_ANISOTROPIC_FILTER(reduction)
: D3D12_ENCODE_BASIC_FILTER(xy_type(x.filter_min), xy_type(x.filter_mag),
x.filter_mip == 2 ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT,
reduction);
pc.AddressU = x.address_u;
pc.AddressV = x.address_v;
pc.AddressW = x.address_w;
pc.MipLODBias = x.mip_lod_bias;
pc.MaxAnisotropy = aniso ? (x.max_anisotropy < 1 ? 1 : x.max_anisotropy > 16 ? 16 : x.max_anisotropy) : 1;
pc.ComparisonFunc = compare ? x.comparison : D3D12_COMPARISON_FUNC_NEVER;
for (int i = 0; i < 4; ++i) pc.BorderColor[i] = x.border_color[i];
pc.MinLOD = x.min_lod;
pc.MaxLOD = x.filter_mip == 0 ? x.min_lod : x.max_lod; // no mip filter: the base level only
bx_xbox_host<ID3D12Device>(self)->CreateSampler(&pc, bx_xbox_host_cpu_handle(dest));
}
+145
View File
@@ -0,0 +1,145 @@
/*
* Fences with a title-visible value (ADR 0009). ID3D12Fence1::GetGpuAddressX returns the GPU
* address of a fence's 64-bit value (authorized GDK documentation); titles read it from the CPU
* and target it with Write*BitValue*X and Wait*BitValueX. Each fence that is asked for its
* address gets an 8-byte slot in memory this layer owns, kept equal to the host fence's value:
* - a CPU Signal stores the value at once;
* - a queue Signal stores it when the host fence completes (a one-shot threadpool wait);
* - a GPU value write to the slot (gpu_writes.cpp) also signals the host fence.
*/
#include "xbox_facade.h"
#include <atomic>
#include <mutex>
#include <vector>
namespace {
struct Slot {
ID3D12Fence* host;
std::atomic<uint64_t>* value;
};
std::mutex g_lock;
std::vector<Slot> g_slots;
std::atomic<uint64_t>* g_page = nullptr;
size_t g_used = 0;
constexpr size_t kSlotsPerPage = 4096 / sizeof(uint64_t);
std::atomic<uint64_t>* allocate_locked() {
if (!g_page || g_used == kSlotsPerPage) {
g_page = static_cast<std::atomic<uint64_t>*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
g_used = 0;
if (!g_page) return nullptr;
}
return &g_page[g_used++];
}
std::atomic<uint64_t>* slot_of(ID3D12Fence* host) {
std::lock_guard<std::mutex> guard(g_lock);
for (const Slot& s : g_slots) {
if (s.host == host) return s.value;
}
return nullptr;
}
void store_max(std::atomic<uint64_t>* slot, uint64_t value) {
uint64_t current = slot->load();
while (current < value && !slot->compare_exchange_weak(current, value)) {
}
}
struct Pending {
std::atomic<uint64_t>* slot;
uint64_t value;
HANDLE event;
HANDLE wait;
};
void CALLBACK on_completed(void* context, BOOLEAN) {
auto* p = static_cast<Pending*>(context);
store_max(p->slot, p->value);
// The wait cannot be unregistered from its own callback with a blocking call; hand it off.
UnregisterWaitEx(p->wait, nullptr);
CloseHandle(p->event);
delete p;
}
} // namespace
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host) {
std::lock_guard<std::mutex> guard(g_lock);
for (const Slot& s : g_slots) {
if (reinterpret_cast<uint64_t>(s.value) == address) {
if (host) *host = s.host;
return true;
}
}
return false;
}
void bx_xbox_fence_forget(IUnknown* host) {
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_slots.size(); ++i) {
if (static_cast<IUnknown*>(g_slots[i].host) == host) { // the slot memory is not reused
g_slots[i] = g_slots.back();
g_slots.pop_back();
return;
}
}
}
extern "C" {
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self) {
BX_D3D_TRACE("XboxFence", "GetGpuAddressX");
auto* host = bx_xbox_host<ID3D12Fence>(self);
if (auto* existing = slot_of(host)) return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(existing);
std::lock_guard<std::mutex> guard(g_lock);
std::atomic<uint64_t>* slot = allocate_locked();
if (!slot) return 0;
slot->store(host->GetCompletedValue());
g_slots.push_back({host, slot});
return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(slot);
}
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value) {
BX_D3D_TRACE("XboxFence", "Signal");
auto* host = bx_xbox_host<ID3D12Fence>(self);
const HRESULT hr = host->Signal(value);
if (SUCCEEDED(hr)) {
if (auto* slot = slot_of(host)) slot->store(value);
}
return hr;
}
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value) {
BX_D3D_TRACE("XboxCommandQueue", "Signal");
ID3D12Fence* host_fence = bx_xbox_unwrap_as(fence);
const HRESULT hr = bx_xbox_host<ID3D12CommandQueue>(self)->Signal(host_fence, value);
std::atomic<uint64_t>* slot = SUCCEEDED(hr) && host_fence ? slot_of(host_fence) : nullptr;
if (!slot) return hr;
if (host_fence->GetCompletedValue() >= value) {
store_max(slot, value);
return hr;
}
auto* p = new (std::nothrow) Pending{slot, value, CreateEventW(nullptr, TRUE, FALSE, nullptr), nullptr};
if (!p || !p->event) {
delete p;
return hr;
}
if (FAILED(host_fence->SetEventOnCompletion(value, p->event)) ||
!RegisterWaitForSingleObject(&p->wait, p->event, on_completed, p, INFINITE, WT_EXECUTEONLYONCE)) {
CloseHandle(p->event);
delete p;
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "fence_slot", "could not arm the completion mirror for a queue Signal");
}
return hr;
}
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value) {
BX_D3D_TRACE("XboxCommandQueue", "Wait");
return bx_xbox_host<ID3D12CommandQueue>(self)->Wait(bx_xbox_unwrap_as(fence), value);
}
} // extern "C"
+173
View File
@@ -0,0 +1,173 @@
/*
* Xbox frame pacing on the host (ADR 0009): ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX
* and WaitFrameEventX, as the authorized GDK documentation describes them.
*
* On the console, display hardware signals the frame events. Here one thread emulates them
* from the recorded frame interval: at the start of each interval it signals the VBLANK and
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
* new frame pipeline token. Each signal also sets the ancillary events given to
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
*/
#include "xbox_facade.h"
#include <cstdio>
#include <mutex>
#include <thread>
namespace {
constexpr UINT kEventTypes = 3; // ORIGIN, DISPLAY_VBLANK, DISPLAY_FLIP
constexpr UINT kOrigin = 0;
constexpr UINT kMaxAncillarySignals = 7;
constexpr UINT kMaxAncillaryWaits = 63;
constexpr UINT kScheduleDisableSignal = 0x1;
constexpr UINT kWaitAll = 0x1;
constexpr UINT kWaitProcessTokenOnTimeout = 0x2;
constexpr UINT kIntervalFlag60FpsPlus = 0x1;
constexpr UINT kSignaledNone = 0xFFFFFFFF;
constexpr UINT kInfinite = 0xFFFFFFFF;
struct Scheduled {
bool active = false;
UINT offset_us = 0;
HANDLE ancillary[kMaxAncillarySignals] = {};
UINT ancillary_count = 0;
};
std::mutex g_lock;
UINT g_interval_us = 0;
UINT g_period = 0;
Scheduled g_events[kEventTypes];
HANDLE g_signal[kEventTypes] = {}; // auto-reset, set at each occurrence
UINT64 g_next_token = 1;
UINT64 g_last_origin_token = 0;
bool g_thread_started = false;
void close_ancillary(Scheduled& e) {
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
e.ancillary_count = 0;
}
void signal(UINT type) {
std::lock_guard<std::mutex> guard(g_lock);
const Scheduled& e = g_events[type];
if (!e.active) return;
if (type == kOrigin) g_last_origin_token = g_next_token++;
SetEvent(g_signal[type]);
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
}
void pacing_thread() {
LARGE_INTEGER frequency, start;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
const auto now_us = [&] {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return static_cast<UINT64>((t.QuadPart - start.QuadPart) * 1000000 / frequency.QuadPart);
};
const auto sleep_until = [&](UINT64 target_us) {
for (UINT64 t = now_us(); t < target_us; t = now_us()) {
const UINT64 ms = (target_us - t) / 1000;
Sleep(ms ? static_cast<DWORD>(ms) : 0);
}
};
UINT64 interval_start = 0;
for (;;) {
UINT interval, origin_offset;
{
std::lock_guard<std::mutex> guard(g_lock);
interval = g_interval_us;
origin_offset = g_events[kOrigin].offset_us;
}
signal(1);
signal(2);
sleep_until(interval_start + (origin_offset < interval ? origin_offset : 0));
signal(kOrigin);
interval_start += interval;
sleep_until(interval_start);
}
}
void log_pacing(const char* event, const char* fmt, UINT a, UINT b, UINT c) {
char detail[160];
std::snprintf(detail, sizeof(detail), fmt, a, b, c);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void*, IDXGIOutput*, UINT length_us, UINT period,
UINT flags) {
BX_D3D_TRACE("XboxDevice", "SetFrameIntervalX");
if (length_us == 0 || period < 1 || period > 4 || (flags & ~kIntervalFlag60FpsPlus) != 0) return E_INVALIDARG;
std::lock_guard<std::mutex> guard(g_lock);
g_interval_us = length_us;
g_period = period;
log_pacing("frame_interval", "length_us=%u period=%u flags=0x%x (host timer, no display sync)", length_us, period, flags);
return S_OK;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void*, UINT type, UINT offset_us,
const BxXboxFrameObjectList* signals, UINT flags) {
BX_D3D_TRACE("XboxDevice", "ScheduleFrameEventX");
if (type >= kEventTypes || (flags & ~kScheduleDisableSignal) != 0) return E_INVALIDARG;
if (signals && (signals->Count > kMaxAncillarySignals || (signals->Count && !signals->pObjects))) return E_INVALIDARG;
std::lock_guard<std::mutex> guard(g_lock);
if (g_interval_us == 0) return E_INVALIDARG; // documented: an interval must be established first
if (offset_us >= g_interval_us) return E_INVALIDARG;
for (UINT i = 0; i < kEventTypes; ++i) {
if (!g_signal[i] && !(g_signal[i] = CreateEventW(nullptr, FALSE, FALSE, nullptr))) return E_OUTOFMEMORY;
}
Scheduled& e = g_events[type];
close_ancillary(e);
e.active = !(flags & kScheduleDisableSignal);
e.offset_us = offset_us;
for (UINT i = 0; signals && i < signals->Count; ++i) {
// The title may close its handle; the scheduled signal keeps its own copy.
if (!DuplicateHandle(GetCurrentProcess(), signals->pObjects[i], GetCurrentProcess(), &e.ancillary[e.ancillary_count],
0, FALSE, DUPLICATE_SAME_ACCESS)) {
close_ancillary(e);
return E_INVALIDARG;
}
++e.ancillary_count;
}
log_pacing("frame_event_scheduled", "type=%u offset_us=%u ancillary=%u", type, offset_us, e.ancillary_count);
if (!g_thread_started) {
std::thread(pacing_thread).detach();
g_thread_started = true;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UINT timeout_ms,
const BxXboxFrameWaitList* waits, UINT flags,
UINT64* token) {
BX_D3D_TRACE("XboxDevice", "WaitFrameEventX");
if (type >= kEventTypes || (flags & ~(kWaitAll | kWaitProcessTokenOnTimeout)) != 0) return E_INVALIDARG;
if (waits && (waits->Count > kMaxAncillaryWaits || (waits->Count && !waits->pObjects))) return E_INVALIDARG;
HANDLE handles[1 + kMaxAncillaryWaits];
{
std::lock_guard<std::mutex> guard(g_lock);
if (!g_events[type].active) return E_INVALIDARG; // documented: the event must be scheduled
handles[0] = g_signal[type];
}
const UINT ancillary = waits ? waits->Count : 0;
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
const DWORD result = WaitForMultipleObjects(1 + ancillary, handles, (flags & kWaitAll) != 0,
timeout_ms == kInfinite ? INFINITE : timeout_ms);
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
if (waits && waits->pSignaledObjectIndex) {
*waits->pSignaledObjectIndex = satisfied && !(flags & kWaitAll) && result > WAIT_OBJECT_0
? result - WAIT_OBJECT_0 - 1 : kSignaledNone;
}
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
std::lock_guard<std::mutex> guard(g_lock);
*token = satisfied ? g_last_origin_token : g_next_token++;
}
return satisfied ? S_OK : S_FALSE;
}
} // extern "C"
+267
View File
@@ -0,0 +1,267 @@
/*
* GPU value writes into title memory (ADR 0009): Write32/64BitValueBottomOfPipeX and
* ...TopOfPipeX record "when the GPU reaches this point, store this value at this address".
* On the console the address is title memory that the CPU polls. The host GPU cannot write
* title memory, so each command list keeps its writes in recording order, and when a queue
* executes lists that carry writes, it waits for the host GPU (an internal fence) and stores the
* values from the CPU, in submission order, before the Execute call returns. Executes with
* writes are therefore synchronous (logged once); executes without writes are not changed.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <mutex>
#include <vector>
namespace {
struct Write {
uint64_t address;
uint64_t value;
bool wide;
bool wait = false; // Wait*BitValueX: value is the reference
D3D12_COMPARISON_FUNC compare = D3D12_COMPARISON_FUNC_GREATER_EQUAL;
uint64_t mask = ~0ull;
};
struct ListWrites {
ID3D12GraphicsCommandList* list;
std::vector<Write> writes;
};
std::mutex g_lock;
std::vector<ListWrites> g_lists;
ListWrites* find_locked(ID3D12GraphicsCommandList* list) {
for (ListWrites& entry : g_lists) {
if (entry.list == list) return &entry;
}
return nullptr;
}
bool writable(uint64_t address, size_t size) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) || region.State != MEM_COMMIT) return false;
constexpr DWORD kWritable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
return (region.Protect & kWritable) && address + size <= reinterpret_cast<uint64_t>(region.BaseAddress) + region.RegionSize;
}
void record(void* self, const Write& op) {
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
std::lock_guard<std::mutex> guard(g_lock);
ListWrites* entry = find_locked(list);
if (!entry) {
g_lists.push_back({list, {}});
entry = &g_lists.back();
}
entry->writes.push_back(op);
}
void record(void* self, uint64_t address, uint64_t value, bool wide) { record(self, Write{address, value, wide}); }
bool satisfied(const Write& w) {
const uint64_t raw = w.wide ? reinterpret_cast<const std::atomic<uint64_t>*>(w.address)->load()
: reinterpret_cast<const std::atomic<uint32_t>*>(w.address)->load();
const uint64_t v = raw & w.mask;
switch (w.compare) {
case D3D12_COMPARISON_FUNC_NEVER: return false;
case D3D12_COMPARISON_FUNC_LESS: return v < w.value;
case D3D12_COMPARISON_FUNC_EQUAL: return v == w.value;
case D3D12_COMPARISON_FUNC_LESS_EQUAL: return v <= w.value;
case D3D12_COMPARISON_FUNC_GREATER: return v > w.value;
case D3D12_COMPARISON_FUNC_NOT_EQUAL: return v != w.value;
case D3D12_COMPARISON_FUNC_GREATER_EQUAL: return v >= w.value;
default: return true;
}
}
// A GPU wait on memory becomes a host queue Wait when the memory is a fence slot and the
// comparison is >=; otherwise the CPU polls the memory before submitting (10 s limit, logged).
void apply_wait(ID3D12CommandQueue* queue, const Write& w) {
ID3D12Fence* fence = nullptr;
if (w.wide && w.compare == D3D12_COMPARISON_FUNC_GREATER_EQUAL && w.mask == ~0ull && bx_xbox_fence_slot(w.address, &fence)) {
queue->Wait(fence, w.value);
return;
}
if (!writable(w.address, w.wide ? 8 : 4)) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", "wait address is not title memory; wait skipped");
return;
}
const ULONGLONG start = GetTickCount64();
while (!satisfied(w)) {
if (GetTickCount64() - start > 10000) {
char detail[128];
std::snprintf(detail, sizeof(detail), "wait on 0x%llx not satisfied after 10 s; submitting anyway",
static_cast<unsigned long long>(w.address));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", detail);
return;
}
SwitchToThread();
}
}
struct QueueFence {
ID3D12CommandQueue* queue;
ID3D12Fence* fence;
uint64_t value;
};
std::vector<QueueFence> g_fences; // guarded by g_lock
HRESULT wait_for_queue(ID3D12CommandQueue* queue) {
ID3D12Fence* fence = nullptr;
uint64_t value = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
for (QueueFence& q : g_fences) {
if (q.queue == queue) {
fence = q.fence;
value = ++q.value;
}
}
if (!fence) {
ID3D12Device* device = nullptr;
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return E_FAIL;
const HRESULT hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
device->Release();
if (FAILED(hr)) return hr;
value = 1;
g_fences.push_back({queue, fence, value});
}
}
HRESULT hr = queue->Signal(fence, value);
if (FAILED(hr)) return hr;
if (fence->GetCompletedValue() >= value) return S_OK;
HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (!event) return E_OUTOFMEMORY;
hr = fence->SetEventOnCompletion(value, event);
if (SUCCEEDED(hr) && WaitForSingleObject(event, 10000) != WAIT_OBJECT_0) hr = HRESULT_FROM_WIN32(WAIT_TIMEOUT);
CloseHandle(event);
return hr;
}
void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
BxXboxUnwrapArray<ID3D12CommandList> host(lists, count);
if (!host.ok()) return;
std::vector<Write> pending;
{
std::lock_guard<std::mutex> guard(g_lock);
for (UINT i = 0; i < count; ++i) {
if (ListWrites* entry = find_locked(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host.data()[i])))) {
pending.insert(pending.end(), entry->writes.begin(), entry->writes.end());
}
}
}
bx_xbox_sync_mapped_buffers();
for (const Write& w : pending) {
if (w.wait) apply_wait(queue, w);
}
queue->ExecuteCommandLists(count, host.data());
bool any_write = false;
for (const Write& w : pending) any_write = any_write || !w.wait;
if (!any_write) return;
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "gpu_value_writes",
"executes carrying Write*BitValue*X wait for the host GPU, then store the values in title memory");
}
const HRESULT hr = wait_for_queue(queue);
if (FAILED(hr)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "waiting for the host GPU failed hr=0x%08lx; values still written",
static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
}
for (const Write& w : pending) {
if (w.wait) continue;
if (!writable(w.address, w.wide ? 8 : 4)) {
static std::atomic<int> bad{0};
if (bad.fetch_add(1) < 8) {
char detail[96];
std::snprintf(detail, sizeof(detail), "address 0x%llx is not writable title memory; value dropped",
static_cast<unsigned long long>(w.address));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
}
continue;
}
if (w.wide) {
reinterpret_cast<std::atomic<uint64_t>*>(w.address)->store(w.value, std::memory_order_release);
} else {
reinterpret_cast<std::atomic<uint32_t>*>(w.address)->store(static_cast<uint32_t>(w.value), std::memory_order_release);
}
ID3D12Fence* fence = nullptr;
if (w.wide && bx_xbox_fence_slot(w.address, &fence)) fence->Signal(w.value);
}
}
} // namespace
void bx_xbox_gpu_writes_reset(IUnknown* host_list) {
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_lists.size(); ++i) {
if (static_cast<IUnknown*>(g_lists[i].list) == host_list) {
g_lists[i] = std::move(g_lists.back());
g_lists.pop_back();
return;
}
}
}
extern "C" {
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueBottomOfPipeX");
record(self, address, value, false);
}
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueBottomOfPipeX");
record(self, address, value, true);
}
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueTopOfPipeX");
record(self, address, value, false);
}
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueTopOfPipeX");
record(self, address, value, true);
}
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT64 reference, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait64BitValueX");
Write op{address, reference, true};
op.wait = true;
op.compare = compare;
record(self, op);
}
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT reference, UINT mask, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait32BitValueX");
Write op{address, reference, false};
op.wait = true;
op.compare = compare;
op.mask = mask;
record(self, op);
}
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists) {
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists");
execute(self, count, lists);
}
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
UINT64 token, UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists2X");
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
char detail[128];
std::snprintf(detail, sizeof(detail), "frame token and kickoff flags (first: token=%llu flags=0x%x) not used by the host",
static_cast<unsigned long long>(token), flags);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "execute_command_lists2_x", detail);
}
execute(self, count, lists);
}
} // extern "C"
+193
View File
@@ -0,0 +1,193 @@
// Console GPU page mappings: ID3D12CommandQueue CopyPageMappingsX, ClearPageMappingsX and
// CopyPageMappingsBatchX (authorized GDK documentation; layouts and semantics derived from it).
//
// A page pool is title memory registered with RegisterPagePoolX; these calls make the 64 KiB (or,
// with D3D12XBOX_PAGE_MAPPING_FLAG_2MB_PAGES, 2 MiB) pages at a destination GPU address show pool
// pages. GPU addresses are title addresses in BetterXen and pool pages are xmem physical pages, so
// each destination page is mapped onto the pool page's physical page with
// XMemMapPhysicalPagesScatter; xmem reports the physical page behind a pool address. Range types:
// incrementing pool pages, one constant pool page, null pages (unmapped) and skipped pages (left as
// they are). The remapping happens when the call is made, not in queue order.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <vector>
#include "bx_log.h"
#include "bx_xmem_internal.h"
#include "xbox_facade.h"
namespace {
struct PageMappingRange {
UINT RangeType;
UINT StartPageIndexInPool;
UINT PageCount;
};
struct PageMappingBatch {
D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress;
UINT RangeCount;
const PageMappingRange* pRanges;
};
static_assert(sizeof(PageMappingRange) == 12, "D3D12XBOX_PAGE_MAPPING_RANGE");
static_assert(sizeof(PageMappingBatch) == 24, "D3D12XBOX_PAGE_MAPPING_BATCH");
enum : UINT { kIncrementing = 0, kConstant = 1, kNullPages = 2, kSkip = 3 };
constexpr UINT kFlag2MbPages = 2;
constexpr uint64_t kSmallPage = 64 * 1024;
using ScatterFn = BOOL(WINAPI*)(PVOID*, ULONG_PTR, PULONG_PTR);
using QueryFn = int (*)(uint64_t, bx_xmem_region_info_t*);
struct Xmem {
ScatterFn scatter = nullptr;
QueryFn query = nullptr;
Xmem() {
if (HMODULE m = GetModuleHandleA("xmem.dll")) {
scatter = reinterpret_cast<ScatterFn>(reinterpret_cast<void*>(GetProcAddress(m, "XMemMapPhysicalPagesScatter")));
query = reinterpret_cast<QueryFn>(reinterpret_cast<void*>(GetProcAddress(m, "bx_xmem_query_region")));
}
}
};
const Xmem& xmem() {
static const Xmem api;
return api;
}
void log_mapping(const char* what, const char* detail) {
static LONG logged = 0;
if (InterlockedIncrement(&logged) <= 64) bx_log_emit(BX_LOG_INFO, "d3d12_xs", what, detail);
}
void log_failure(const char* detail) {
static LONG logged = 0;
if (InterlockedIncrement(&logged) <= 32) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "page_mapping_failed", detail);
}
// Collects destination slots and physical pages (0: unmap), then maps them in one scatter call.
class Mapper {
public:
Mapper(uint64_t pool, UINT pool_pages, UINT flags)
: pool_(pool), pool_pages_(pool_pages), page_(flags & kFlag2MbPages ? 32 * kSmallPage : kSmallPage) {}
// One destination page `dst_page` (index from `dst`) showing pool page `pool_page`, or none.
bool add(uint64_t dst, uint64_t dst_page, bool null_page, UINT pool_page) {
for (uint64_t sub = 0; sub < page_ / kSmallPage; ++sub) {
ULONG_PTR tag = 0;
if (!null_page) {
if (pool_page >= pool_pages_) return fail("pool page index past the pool", dst, pool_page);
bx_xmem_region_info_t info{};
const uint64_t src = pool_ + uint64_t(pool_page) * page_ + sub * kSmallPage;
if (!xmem().query || !xmem().query(src, &info) || !info.physical_tag) {
return fail("pool address has no xmem physical page", dst, pool_page);
}
tag = static_cast<ULONG_PTR>(info.physical_tag);
}
slots_.push_back(reinterpret_cast<PVOID>(static_cast<uintptr_t>(dst + dst_page * page_ + sub * kSmallPage)));
tags_.push_back(tag);
}
return true;
}
bool add_range(uint64_t dst, uint64_t& cursor, const PageMappingRange& range) {
switch (range.RangeType) {
case kSkip:
cursor += range.PageCount;
return true;
case kIncrementing:
case kConstant:
case kNullPages:
for (UINT i = 0; i < range.PageCount; ++i) {
const UINT pool_page = range.RangeType == kIncrementing ? range.StartPageIndexInPool + i
: range.StartPageIndexInPool;
if (!add(dst, cursor + i, range.RangeType == kNullPages, pool_page)) return false;
}
cursor += range.PageCount;
return true;
default:
return fail("unknown range type", dst, range.RangeType);
}
}
HRESULT commit() {
if (slots_.empty()) return S_OK;
if (!xmem().scatter) {
log_failure("xmem.dll!XMemMapPhysicalPagesScatter not available");
return E_NOTIMPL;
}
if (!xmem().scatter(slots_.data(), slots_.size(), tags_.data())) {
char detail[160];
std::snprintf(detail, sizeof(detail), "XMemMapPhysicalPagesScatter of %zu pages at %p failed error=%lu",
slots_.size(), slots_.front(), static_cast<unsigned long>(GetLastError()));
log_failure(detail);
return E_INVALIDARG;
}
return S_OK;
}
size_t pages() const { return slots_.size(); }
private:
bool fail(const char* why, uint64_t dst, UINT value) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s (destination 0x%llx, value %u)", why,
static_cast<unsigned long long>(dst), value);
log_failure(detail);
return false;
}
uint64_t pool_;
UINT pool_pages_;
uint64_t page_;
std::vector<PVOID> slots_;
std::vector<ULONG_PTR> tags_;
};
HRESULT map_batches(UINT count, const PageMappingBatch* batches, uint64_t pool, UINT pool_pages, UINT flags,
const char* method) {
if (count && !batches) return E_INVALIDARG;
Mapper mapper(pool, pool_pages, flags);
for (UINT b = 0; b < count; ++b) {
if (batches[b].RangeCount && !batches[b].pRanges) return E_INVALIDARG;
uint64_t cursor = 0;
for (UINT r = 0; r < batches[b].RangeCount; ++r) {
if (!mapper.add_range(batches[b].DestinationAddress, cursor, batches[b].pRanges[r])) return E_INVALIDARG;
}
}
const HRESULT hr = mapper.commit();
char detail[192];
std::snprintf(detail, sizeof(detail), "%s batches=%u first_destination=0x%llx pool=0x%llx pool_pages=%u flags=0x%x pages=%zu hr=0x%08lx",
method, count, count ? static_cast<unsigned long long>(batches[0].DestinationAddress) : 0ull,
static_cast<unsigned long long>(pool), pool_pages, flags, mapper.pages(), static_cast<unsigned long>(hr));
log_mapping("page_mappings", detail);
return hr;
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void*, UINT batch_count, const void* batches,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsBatchX");
return map_batches(batch_count, static_cast<const PageMappingBatch*>(batches), pool, pool_pages, flags,
"CopyPageMappingsBatchX");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT range_count, const void* ranges,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsX");
const PageMappingBatch batch{destination, range_count, static_cast<const PageMappingRange*>(ranges)};
return map_batches(1, &batch, pool, pool_pages, flags, "CopyPageMappingsX");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT page_count, UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "ClearPageMappingsX");
const PageMappingRange range{kNullPages, 0, page_count};
const PageMappingBatch batch{destination, 1, &range};
return map_batches(1, &batch, 0, 0, flags, "ClearPageMappingsX");
}
+487
View File
@@ -0,0 +1,487 @@
/*
* Pipeline states on the Xbox-layout device (ADR 0009), and the opt-in null-render mode.
*
* Every pipeline creation goes through the M2 shader format gate (shader_gate.h, ADR 0008), so
* each stage writes a `shader_gate` record, and the title's root signature is unwrapped before
* the description reaches the host. The Xbox *X variants take extended descriptions
* (D3D12XBOX_EXTENDED_*_PIPELINE_STATE_DESC) that have no host equivalent; their count is logged
* and the base description is created.
*
* Null-render mode (BX_NULL_RENDER=1, off by default): a pipeline the host refuses, for example
* one whose shaders are console-only, becomes a BetterXen null pipeline instead of a failure.
* Binding it is recorded per command list, and draws and dispatches recorded while it is bound
* are skipped. Everything else still runs, so fences complete and frames present, with the
* skipped work missing from them. Each refusal and each skip is logged: the mode exists to see
* how far a title gets, not to hide what it cannot run.
*/
#include "xbox_facade.h"
#include "proxy.h"
#include "shader_gate.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <vector>
#include <mutex>
namespace {
bool null_render_enabled() {
static const bool enabled = [] {
char value[8] = {};
const DWORD n = GetEnvironmentVariableA("BX_NULL_RENDER", value, sizeof(value));
const bool on = n > 0 && n < sizeof(value) && value[0] == '1';
if (on) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render", "enabled: refused pipelines become null pipelines");
return on;
}();
return enabled;
}
/* A pipeline-state object with no host pipeline behind it. */
class NullPipelineState final : public ID3D12PipelineState {
public:
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12PipelineState)) {
*ppv = static_cast<ID3D12PipelineState*>(this);
AddRef();
return S_OK;
}
*ppv = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
ULONG STDMETHODCALLTYPE Release() override {
const ULONG left = --refs_;
if (!left) {
device_->Release();
delete this;
}
return left;
}
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT* size, void*) override {
if (size) *size = 0;
return DXGI_ERROR_NOT_FOUND;
}
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; }
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; }
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; }
HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override { return device_->QueryInterface(riid, ppv); }
HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override {
if (blob) *blob = nullptr;
return E_NOTIMPL;
}
private:
ID3D12Device* device_;
std::atomic<ULONG> refs_{1};
};
std::mutex g_lock;
NullPipelineState** g_nulls = nullptr; // live null pipelines, so they can be recognised
size_t g_null_count = 0;
size_t g_null_capacity = 0;
ID3D12GraphicsCommandList** g_lists = nullptr; // lists whose bound pipeline is a null pipeline
size_t g_list_count = 0;
size_t g_list_capacity = 0;
template <typename T>
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
if (count == capacity) {
const size_t grown_capacity = capacity ? capacity * 2 : 16;
auto** grown = new (std::nothrow) T*[grown_capacity];
if (!grown) return false;
for (size_t i = 0; i < count; ++i) grown[i] = items[i];
delete[] items;
items = grown;
capacity = grown_capacity;
}
items[count++] = item;
return true;
}
template <typename T>
bool erase(T** items, size_t& count, const T* item) {
for (size_t i = 0; i < count; ++i) {
if (items[i] == item) {
items[i] = items[--count];
return true;
}
}
return false;
}
template <typename T>
bool contains(T* const* items, size_t count, const T* item) {
for (size_t i = 0; i < count; ++i) {
if (items[i] == item) return true;
}
return false;
}
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
std::lock_guard<std::mutex> guard(g_lock);
*is_null = host && contains(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
return *is_null ? nullptr : host;
}
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
std::lock_guard<std::mutex> guard(g_lock);
const bool present = contains(g_lists, g_list_count, list);
if (null_bound && !present) push(g_lists, g_list_count, g_list_capacity, list);
if (!null_bound && present) erase(g_lists, g_list_count, list);
}
bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
{
std::lock_guard<std::mutex> guard(g_lock);
if (!contains(g_lists, g_list_count, list)) return false;
}
static std::atomic<uint64_t> skipped{0};
const uint64_t n = ++skipped;
if ((n & (n - 1)) == 0) { // 1, 2, 4, 8, ...: enough to follow without flooding the log
char detail[96];
std::snprintf(detail, sizeof(detail), "%s with a null pipeline bound; total skipped=%llu", what,
static_cast<unsigned long long>(n));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render_skip", detail);
}
return true;
}
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx%s", kind, static_cast<unsigned long>(hr),
null_render_enabled() ? "; null pipeline returned" : "");
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
if (!null_render_enabled() || !ppv) return hr;
auto* null_pso = new (std::nothrow) NullPipelineState(device);
if (!null_pso) return E_OUTOFMEMORY;
{
std::lock_guard<std::mutex> guard(g_lock);
if (!push(g_nulls, g_null_count, g_null_capacity, null_pso)) {
null_pso->Release();
return E_OUTOFMEMORY;
}
}
*ppv = static_cast<ID3D12PipelineState*>(null_pso);
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
void log_extended(const char* kind, UINT count) {
if (!count) return;
char detail[96];
std::snprintf(detail, sizeof(detail), "%s: %u extended description(s) not applied", kind, count);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_extended_desc", detail);
}
HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device>(self);
BxShaderGate gate;
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
HRESULT hr = gate.admit("compute", "CS", desc->CS, admitted.CS);
if (SUCCEEDED(hr)) hr = device->CreateComputePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device>(self);
BxShaderGate gate;
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
HRESULT hr = gate.admit("graphics", "VS", desc->VS, admitted.VS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "PS", desc->PS, admitted.PS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device2>(self);
std::vector<uint8_t> stream;
std::vector<size_t> offsets;
std::vector<const char*> names;
size_t root_offset = SIZE_MAX;
HRESULT hr = copy_stream(*desc, stream, offsets, names, &root_offset);
if (FAILED(hr)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "stream of %llu bytes not parsed (unknown or console subobject?)",
static_cast<unsigned long long>(desc->SizeInBytes));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pso_stream", detail);
return refused(device, hr, "stream", riid, ppv);
}
if (root_offset != SIZE_MAX) {
ID3D12RootSignature* root = nullptr;
std::memcpy(&root, &stream[root_offset], sizeof(root));
root = bx_xbox_unwrap_as(root);
std::memcpy(&stream[root_offset], &root, sizeof(root));
}
BxShaderGate gate;
for (size_t i = 0; i < offsets.size() && SUCCEEDED(hr); ++i) {
D3D12_SHADER_BYTECODE in{};
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
D3D12_SHADER_BYTECODE out = in;
hr = gate.admit("stream", names[i], in, out);
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
}
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePipelineState");
return create_stream(self, desc, riid, ppv);
}
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title) {
bool is_null = false;
host_pipeline(title, &is_null);
return is_null;
}
void bx_xbox_pipeline_forget(IUnknown* host) {
std::lock_guard<std::mutex> guard(g_lock);
erase(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
}
void bx_xbox_list_forget(IUnknown* host) {
std::lock_guard<std::mutex> guard(g_lock);
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
}
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
return create_compute(self, desc, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineState");
return create_graphics(self, desc, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineStateX");
log_extended("CreateComputePipelineStateX", extended_count);
return create_compute(self, desc, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineStateX");
log_extended("CreateGraphicsPipelineStateX", extended_count);
return create_graphics(self, desc, riid, ppv);
}
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
if (!is_null) list->SetPipelineState(host);
}
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
bx_xbox_gpu_writes_reset(list);
return list->Reset(bx_xbox_unwrap_as(allocator), host);
}
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
}
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
INT base_vertex, UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawIndexedInstanced")) {
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
}
}
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Dispatch");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "Dispatch")) list->Dispatch(x, y, z);
}
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
ID3D12Resource* arguments, UINT64 arguments_offset,
ID3D12Resource* count, UINT64 count_offset) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ExecuteIndirect");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (list_skips(list, "ExecuteIndirect")) return;
list->ExecuteIndirect(bx_xbox_unwrap_as(signature), max_commands, bx_xbox_unwrap_as(arguments), arguments_offset,
bx_xbox_unwrap_as(count), count_offset);
}
} // extern "C"
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
ID3D12RootSignature* root, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommandSignature");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
// D3D12XBOX_INDIRECT_ARGUMENT_TYPE_* values start at 100 and have no PC equivalent, except
// DISPATCH_SINGLE / DISPATCH_L2 (105): a dispatch whose arguments are D3D12_DISPATCH_ARGUMENTS
// and whose D3D12XBOX_DISPATCH_FLAGS are a direct parameter (authorized GDK documentation), so
// the host gets D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. The flags are cache hints and are dropped.
constexpr int kFirstXboxArgument = 100;
constexpr int kXboxDispatchSingle = 105;
constexpr UINT kMaxArguments = 32;
D3D12_INDIRECT_ARGUMENT_DESC host_args[kMaxArguments] = {};
char types[160] = {};
size_t used = 0;
bool console_only = desc->NumArgumentDescs > kMaxArguments;
for (UINT i = 0; i < desc->NumArgumentDescs && i < kMaxArguments && desc->pArgumentDescs; ++i) {
const int type = static_cast<int>(desc->pArgumentDescs[i].Type);
host_args[i] = desc->pArgumentDescs[i];
if (type == kXboxDispatchSingle) {
host_args[i] = {};
host_args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
} else if (type >= kFirstXboxArgument) {
console_only = true;
}
if (used < sizeof(types) - 8) used += std::snprintf(types + used, sizeof(types) - used, "%s%d", i ? "," : "", type);
}
D3D12_COMMAND_SIGNATURE_DESC host_desc = *desc;
host_desc.pArgumentDescs = host_args;
auto* device = bx_xbox_host<ID3D12Device>(self);
HRESULT hr = console_only ? E_NOTIMPL
: device->CreateCommandSignature(&host_desc, bx_xbox_unwrap_as(root), riid, ppv);
char detail[256];
std::snprintf(detail, sizeof(detail), "stride=%u args=[%s] root_signature=%d hr=0x%08lx%s", desc->ByteStride, types,
root ? 1 : 0, static_cast<unsigned long>(hr), console_only ? " (console argument types)" : "");
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "command_signature", detail);
return SUCCEEDED(hr) ? bx_xbox_wrap_result(hr, riid, ppv) : hr;
}
namespace {
void log_once(std::atomic<bool>& flag, const char* event, const char* detail) {
if (!flag.exchange(true)) bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
UINT flags) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ResetX");
static std::atomic<bool> logged{false};
if (flags) log_once(logged, "reset_x_flags", "D3D12XBOX_COMMAND_LIST_RESET_FLAGS have no host meaning; ignored");
return bx_xbox_list_reset(self, allocator, pso);
}
// Console cache synchronisation points. The closest host D3D12 operation is a global UAV
// barrier: all prior UAV work completes before later work starts.
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT, UINT, D3D12_GPU_VIRTUAL_ADDRESS, SIZE_T) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SyncTopOfPipeX/SyncBottomOfPipeX");
static std::atomic<bool> logged{false};
log_once(logged, "sync_x", "SyncTopOfPipeX/SyncBottomOfPipeX recorded as a global UAV barrier");
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(1, &barrier);
}
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, UINT64) {
BX_D3D_TRACE("XboxCommandAllocator", "SetAllocatorCallbackX");
static std::atomic<bool> logged{false};
if (callback) {
log_once(logged, "allocator_callback_x",
"SetAllocatorCallbackX accepted; host command lists do not allocate from title memory, so it is never called");
}
}
} // extern "C"
/*
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
*/
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
}
/*
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
* from a host pipeline needs its creation description, which this layer does not keep yet: that
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
*/
namespace {
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
const bool from_null = bx_xbox_pipeline_is_null(source);
if (!from_null) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_derived",
"deriving from a host pipeline is not implemented (its creation description is not kept)");
}
}
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
return derived(self, source, riid, ppv, "derived graphics");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
return derived(self, source, riid, ppv, "derived compute");
}
+436
View File
@@ -0,0 +1,436 @@
/*
* Resources placed at a title-chosen GPU virtual address (ADR 0009, "translation by copy").
*
* On the console a title maps its own physical pages at an address and places resources there
* with ID3D12Device::CreatePlacedResourceX / CreatePlacedResourceX1; CPU and GPU see the same
* memory. D3DMetal cannot create a resource over existing memory (the existing-memory imports
* measured for #473 return E_NOTIMPL), so each such resource gets a shadow resource on the host:
*
* - a buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's
* memory when it is created;
* - a texture gets a committed texture whose contents are not filled (logged); texture
* contents need the console tiling translation (xg_xs) first.
*
* The title's address and the shadow are recorded, and the resource reports the title's address
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
* title addresses in GPU calls, are not done yet; both are logged when reached.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
namespace {
struct Shadow {
ID3D12Resource* host; // owned by the Xbox object, or (implicit shadows) by this table
uint64_t title_va;
uint64_t size;
bool buffer;
D3D12_RESOURCE_DESC desc;
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
int mapped = 0; // outstanding Map calls on title memory (buffers)
};
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
if (!s.buffer || end <= begin || end > s.size) return false;
void* mapped = nullptr;
const D3D12_RANGE none{0, 0};
if (FAILED(s.host->Map(0, to_host ? &none : nullptr, &mapped)) || !mapped) return false;
auto* host = static_cast<uint8_t*>(mapped) + begin;
auto* title = reinterpret_cast<uint8_t*>(s.title_va) + begin;
if (to_host) std::memcpy(host, title, static_cast<size_t>(end - begin));
else std::memcpy(title, host, static_cast<size_t>(end - begin));
const D3D12_RANGE written{static_cast<SIZE_T>(begin), static_cast<SIZE_T>(end)};
s.host->Unmap(0, to_host ? &written : &none);
return true;
}
std::mutex g_lock;
Shadow* g_shadows = nullptr;
size_t g_count = 0;
size_t g_capacity = 0;
bool remember(const Shadow& shadow) {
std::lock_guard<std::mutex> guard(g_lock);
if (g_count == g_capacity) {
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
auto* grown = new (std::nothrow) Shadow[capacity];
if (!grown) return false;
if (g_count) std::memcpy(grown, g_shadows, g_count * sizeof(Shadow));
delete[] g_shadows;
g_shadows = grown;
g_capacity = capacity;
}
g_shadows[g_count++] = shadow;
return true;
}
bool readable(const void* p, uint64_t size) {
auto cursor = reinterpret_cast<uintptr_t>(p);
const uintptr_t end = cursor + size;
while (cursor < end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(cursor), &region, sizeof(region)) || region.State != MEM_COMMIT
|| (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
return false;
}
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
return true;
}
HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, const char* method,
ID3D12Resource** out) {
*out = nullptr;
const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER;
D3D12_HEAP_PROPERTIES heap{};
if (buffer) {
heap.Type = D3D12_HEAP_TYPE_CUSTOM;
heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
} else {
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
}
D3D12_RESOURCE_DESC host_desc = desc;
// Console tiling layouts and D3D12XBOX_RESOURCE_FLAG_* bits have no PC meaning.
constexpr UINT kPcResourceFlags = 0x1FF;
host_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN;
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc.Flags & kPcResourceFlags);
ID3D12Resource* resource = nullptr;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
char detail[224];
std::snprintf(detail, sizeof(detail), "%s title_va=0x%llx dim=%d width=%llu height=%u format=%d hr=0x%08lx",
method, static_cast<unsigned long long>(title_va), static_cast<int>(desc.Dimension),
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format),
static_cast<unsigned long>(hr));
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", detail);
if (FAILED(hr) || !resource) return FAILED(hr) ? hr : E_FAIL;
const auto* title = reinterpret_cast<const void*>(title_va);
if (buffer) {
void* mapped = nullptr;
if (SUCCEEDED(resource->Map(0, nullptr, &mapped)) && mapped) {
if (readable(title, desc.Width)) {
std::memcpy(mapped, title, static_cast<size_t>(desc.Width));
} else {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "title memory not readable; shadow left zeroed");
}
resource->Unmap(0, nullptr);
}
} else {
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
}
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
resource->Release();
return E_OUTOFMEMORY;
}
*out = resource;
return S_OK;
}
HRESULT create_shadow(void* self, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** ppv,
const char* method) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
ID3D12Resource* resource = nullptr;
const HRESULT hr = make_shadow(bx_xbox_host<ID3D12Device>(self), title_va, desc, method, &resource);
if (FAILED(hr)) return hr;
*ppv = resource;
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
return a.Dimension == b.Dimension && a.Width == b.Width && a.Height == b.Height &&
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
}
// A view of placed memory with no resource object: reuse the shadow made for the same address
// and shape, or make one. These shadows live for the rest of the process (logged).
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
}
}
ID3D12Resource* resource = nullptr;
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
}
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
constexpr size_t kPcViewDescBytes = 40;
static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == kPcViewDescBytes, "PC SRV description size");
static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == kPcViewDescBytes, "PC UAV description size");
uint64_t view_location(const void* xbox_desc) {
uint64_t va = 0;
std::memcpy(&va, static_cast<const char*>(xbox_desc) + kPcViewDescBytes, sizeof(va));
return va;
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX");
if (!desc || !location) return E_INVALIDARG;
return create_shadow(self, location, *desc, riid, ppv, "CreatePlacedResourceX");
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC1* desc1, UINT,
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX1");
if (!desc1 || !location) return E_INVALIDARG;
// D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC followed by SamplerFeedbackMipRegion.
D3D12_RESOURCE_DESC desc{};
std::memcpy(&desc, desc1, sizeof(desc));
return create_shadow(self, location, desc, riid, ppv, "CreatePlacedResourceX1");
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawShaderResourceViewX");
if (!resource_desc || !xbox_desc) return;
auto* device = bx_xbox_host<ID3D12Device>(self);
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
if (!resource) return;
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawUnorderedAccessViewX");
if (!resource_desc || !xbox_desc) return;
auto* device = bx_xbox_host<ID3D12Device>(self);
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
if (!resource) return;
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
device->CreateUnorderedAccessView(resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedShaderResourceViewX");
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr,
bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedUnorderedAccessViewX");
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as(resource), nullptr,
xbox_desc ? &pc : nullptr, bx_xbox_host_cpu_handle(dest));
}
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
if (!title) return title;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const Shadow& s = g_shadows[i];
if (title >= s.title_va && title < s.title_va + s.size) return s.host->GetGPUVirtualAddress() + (title - s.title_va);
}
return title; // not a title address this layer knows: a host address already, or untranslated
}
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes) {
return remember({host, title_va, size, host->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, host->GetDesc(),
attributes});
}
void bx_xbox_placed_forget(IUnknown* host) {
Shadow gone{};
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (static_cast<IUnknown*>(g_shadows[i].host) == host) {
gone = g_shadows[i];
g_shadows[i] = g_shadows[--g_count];
break;
}
}
}
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
}
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self) {
BX_D3D_TRACE("XboxResource", "GetGPUVirtualAddress");
auto* host = bx_xbox_host<ID3D12Resource>(self);
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].host == host) return g_shadows[i].title_va;
}
}
return host->GetGPUVirtualAddress();
}
} // extern "C"
/*
* Page pools (RegisterPagePoolX / UnregisterPagePoolX, authorized GDK documentation): a title
* registers a 64 KB-aligned, fully mapped range of its graphics memory as the source of later
* CopyPageMappingsX calls. Registration is validated and recorded; the handle is the record.
* CopyPageMappingsX itself (a queue method) is not implemented yet and stays a logged stub.
*/
namespace {
struct PagePool {
uint64_t address;
UINT pages;
PagePool* next;
};
PagePool* g_pools = nullptr; // guarded by g_lock
bool fully_mapped(uint64_t address, uint64_t size) {
auto cursor = static_cast<uintptr_t>(address);
const uintptr_t end = cursor + static_cast<uintptr_t>(size);
while (cursor < end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(cursor), &region, sizeof(region)) || region.State != MEM_COMMIT) {
return false;
}
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
return true;
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void*, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
HANDLE* handle) {
BX_D3D_TRACE("XboxDevice", "RegisterPagePoolX");
constexpr uint64_t kPage = 64 * 1024;
const bool valid = handle && pages && address && (address % kPage) == 0 && fully_mapped(address, pages * kPage);
char detail[160];
std::snprintf(detail, sizeof(detail), "address=0x%llx pages=%u %s", static_cast<unsigned long long>(address), pages,
valid ? "registered" : "rejected (unaligned, empty or not fully mapped)");
bx_log_emit(valid ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "page_pool", detail);
if (!valid) return E_INVALIDARG;
auto* pool = new (std::nothrow) PagePool{address, pages, nullptr};
if (!pool) return E_OUTOFMEMORY;
{
std::lock_guard<std::mutex> guard(g_lock);
pool->next = g_pools;
g_pools = pool;
}
*handle = pool;
return S_OK;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void*, HANDLE handle) {
BX_D3D_TRACE("XboxDevice", "UnregisterPagePoolX");
std::lock_guard<std::mutex> guard(g_lock);
for (PagePool** link = &g_pools; *link; link = &(*link)->next) {
if (*link == handle) {
PagePool* gone = *link;
*link = gone->next;
delete gone;
return S_OK;
}
}
return E_INVALIDARG;
}
} // extern "C"
/*
* Map on a resource that has title-visible memory (placed at a title address, or committed with
* XMemAlloc memory) returns that memory, as on the console, where CPU and GPU share it. Other
* resources map their host resource. Writes through the title pointer reach the host resource
* only where this layer copies them (buffers at creation; texture contents are not copied yet,
* logged at creation).
*/
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data) {
BX_D3D_TRACE("XboxResource", "Map");
auto* host = bx_xbox_host<ID3D12Resource>(self);
uint64_t title_va = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
Shadow& s = g_shadows[i];
if (s.host != host) continue;
title_va = s.title_va;
// Make GPU results visible: refresh the read range of title memory from the host.
const uint64_t begin = read ? read->Begin : 0, end = read ? read->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
++s.mapped;
}
}
if (!title_va) {
const HRESULT hr = host->Map(subresource, read, data);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxResource", "Map", hr);
return hr;
}
if (subresource != 0) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_map",
"Map of a non-zero subresource of title memory returns the resource base");
}
}
if (data) *data = reinterpret_cast<void*>(title_va);
return S_OK;
}
extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written) {
BX_D3D_TRACE("XboxResource", "Unmap");
auto* host = bx_xbox_host<ID3D12Resource>(self);
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
Shadow& s = g_shadows[i];
if (s.host != host) continue;
// Hand the CPU's writes to the host resource (a null range means all of it).
const uint64_t begin = written ? written->Begin : 0, end = written ? written->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
if (s.mapped > 0) --s.mapped;
return;
}
}
host->Unmap(subresource, written);
}
/*
* Before a submission, buffers the title keeps mapped (persistent maps) are copied from title
* memory to their host resources, up to 16 MB each; larger ones are logged once and not copied.
*/
void bx_xbox_sync_mapped_buffers() {
constexpr uint64_t kLimit = 16ull << 20;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const Shadow& s = g_shadows[i];
if (!s.mapped || !s.buffer) continue;
if (s.size > kLimit) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
char detail[128];
std::snprintf(detail, sizeof(detail), "persistently mapped buffer of %llu bytes not copied to the host before submit",
static_cast<unsigned long long>(s.size));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_sync", detail);
}
continue;
}
copy_buffer(s, true, 0, s.size);
}
}
+544
View File
@@ -0,0 +1,544 @@
#include "presentx.h"
#include <atomic>
#include <cstdio>
#include <new>
#include "proxy.h"
/*
* Track C (M2-C2, #465). See presentx.h for the contract and for what this is not.
* Host DXGI is loaded on demand, like the host d3d12.dll in d3d12_xs.cpp.
*/
namespace {
constexpr HRESULT kWaitTimedOut = static_cast<HRESULT>(0x800705B4u); /* HRESULT_FROM_WIN32(ERROR_TIMEOUT) */
bool is_device_removed_hr(HRESULT hr) {
return hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ||
hr == DXGI_ERROR_DEVICE_RESET || hr == DXGI_ERROR_DRIVER_INTERNAL_ERROR;
}
void log_hr(bx_log_level_t level, const char* event, const char* what, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
bx_log_emit(level, "d3d12_xs", event, detail);
}
/* Releases an already acquired lock and records its owner, so re-entry can be refused. */
class SrwOwner {
public:
SrwOwner(SRWLOCK& lock, std::atomic<DWORD>& owner) : lock_(lock), owner_(owner) { owner_ = GetCurrentThreadId(); }
~SrwOwner() {
owner_ = 0;
ReleaseSRWLockExclusive(&lock_);
}
SrwOwner(const SrwOwner&) = delete;
SrwOwner& operator=(const SrwOwner&) = delete;
private:
SRWLOCK& lock_;
std::atomic<DWORD>& owner_;
};
class BxPresentSwapChain final : public IBxPresentSwapChain {
public:
/* `queue_proxy` is referenced for the lifetime of the chain; `host_queue` is its host object. */
static HRESULT create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
const BxPresentDesc& desc, IBxPresentSwapChain** out);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
ULONG STDMETHODCALLTYPE AddRef() override;
ULONG STDMETHODCALLTYPE Release() override;
HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) override;
UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() override;
HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) override;
HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) override;
HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) override;
private:
BxPresentSwapChain() = default;
~BxPresentSwapChain() = default;
HRESULT init(HWND window, const BxPresentDesc& desc);
HRESULT signal_locked(UINT64* value);
HRESULT wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms);
HRESULT idle_locked(ULONGLONG start, DWORD timeout_ms);
HRESULT post_present_failure(const char* event, const char* what, HRESULT hr, HRESULT live_device_result);
HRESULT removed_reason();
void destroy();
std::atomic<ULONG> refs_{1};
SRWLOCK lock_ = SRWLOCK_INIT; /* guards the fence counter, the event and Present */
ID3D12CommandQueue* queue_proxy_ = nullptr;
ID3D12CommandQueue* host_queue_ = nullptr;
HWND window_ = nullptr;
IDXGISwapChain3* swap_ = nullptr;
ID3D12Fence* fence_ = nullptr;
HANDLE event_ = nullptr;
std::atomic<DWORD> owner_{0}; /* thread holding lock_ */
UINT64 last_signaled_ = 0;
UINT64 presented_ = 0;
bool needs_idle_ = false; /* post-present signal or wait failed; only an idle queue clears this */
UINT64 buffer_value_[DXGI_MAX_SWAP_CHAIN_BUFFERS] = {};
};
HRESULT BxPresentSwapChain::create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
const BxPresentDesc& desc, IBxPresentSwapChain** out) {
auto* self = new (std::nothrow) BxPresentSwapChain();
if (!self) {
return E_OUTOFMEMORY;
}
queue_proxy->AddRef();
self->queue_proxy_ = queue_proxy;
host_queue->AddRef();
self->host_queue_ = host_queue;
self->window_ = window;
HRESULT hr = self->init(window, desc);
if (FAILED(hr)) {
self->destroy(); /* nothing was submitted, so every partially created object can go */
return hr;
}
*out = self;
return S_OK;
}
HRESULT BxPresentSwapChain::init(HWND window, const BxPresentDesc& desc) {
static HMODULE dxgi = LoadLibraryA("dxgi.dll");
using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**);
auto create_factory = dxgi
? reinterpret_cast<CreateFactoryFn>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")))
: nullptr;
if (!create_factory) {
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_dxgi_missing", "dxgi.dll!CreateDXGIFactory1 not available");
return DXGI_ERROR_UNSUPPORTED;
}
IDXGIFactory4* factory = nullptr;
HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory));
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateDXGIFactory1", hr);
return hr;
}
DXGI_SWAP_CHAIN_DESC1 sd = {};
sd.Width = desc.width;
sd.Height = desc.height;
sd.Format = desc.format;
sd.SampleDesc.Count = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = desc.buffer_count;
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
IDXGISwapChain1* swap1 = nullptr;
/* For D3D12 the "device" argument of CreateSwapChainForHwnd is the command queue. */
hr = factory->CreateSwapChainForHwnd(host_queue_, window, &sd, nullptr, nullptr, &swap1);
if (SUCCEEDED(hr)) {
/* Alt+Enter would require ResizeBuffers handling that the bridge does not have. */
HRESULT assoc = factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER);
if (FAILED(assoc)) {
log_hr(BX_LOG_WARN, "present_window_association", "MakeWindowAssociation", assoc);
}
}
factory->Release();
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateSwapChainForHwnd", hr);
return hr;
}
hr = swap1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&swap_));
swap1->Release();
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "QueryInterface(IDXGISwapChain3)", hr);
return hr;
}
ID3D12Device* device = nullptr;
hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (SUCCEEDED(hr)) {
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence_));
device->Release();
}
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateFence", hr);
return hr;
}
event_ = CreateEventA(nullptr, FALSE, FALSE, nullptr);
if (!event_) {
hr = HRESULT_FROM_WIN32(GetLastError());
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateEvent", hr);
return hr;
}
char detail[128];
std::snprintf(detail, sizeof(detail), "width=%u height=%u format=%d buffers=%u",
desc.width, desc.height, static_cast<int>(desc.format), desc.buffer_count);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_chain_created", detail);
return S_OK;
}
HRESULT BxPresentSwapChain::removed_reason() {
ID3D12Device* device = nullptr;
HRESULT hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (FAILED(hr)) {
return hr;
}
hr = device->GetDeviceRemovedReason();
device->Release();
return hr;
}
HRESULT BxPresentSwapChain::signal_locked(UINT64* value) {
const UINT64 next = last_signaled_ + 1;
HRESULT hr = host_queue_->Signal(fence_, next);
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_signal_failed", "ID3D12CommandQueue::Signal", hr);
return hr;
}
last_signaled_ = next;
*value = next;
return S_OK;
}
HRESULT BxPresentSwapChain::wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms) {
for (;;) {
const UINT64 completed = fence_->GetCompletedValue();
if (completed == UINT64_MAX) { /* the documented value after device removal */
HRESULT reason = removed_reason();
log_hr(BX_LOG_ERROR, "present_device_removed", "fence", reason);
return FAILED(reason) ? reason : DXGI_ERROR_DEVICE_REMOVED;
}
if (completed >= value) {
return S_OK;
}
const ULONGLONG elapsed = GetTickCount64() - start;
if (elapsed >= timeout_ms) {
break;
}
HRESULT hr = fence_->SetEventOnCompletion(value, event_);
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_wait_failed", "SetEventOnCompletion", hr);
return hr;
}
const ULONGLONG elapsed_after_registration = GetTickCount64() - start;
if (elapsed_after_registration >= timeout_ms) {
continue; /* Recheck the fence before reporting a timeout. */
}
/* The event can be left over from an earlier timed-out wait, so the loop re-reads the fence. */
DWORD waited = WaitForSingleObject(event_, static_cast<DWORD>(timeout_ms - elapsed_after_registration));
if (waited == WAIT_FAILED) {
hr = HRESULT_FROM_WIN32(GetLastError());
log_hr(BX_LOG_ERROR, "present_wait_failed", "WaitForSingleObject", hr);
return hr;
}
}
char detail[128];
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=%llu", static_cast<unsigned long>(timeout_ms),
static_cast<unsigned long long>(value), static_cast<unsigned long long>(fence_->GetCompletedValue()));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
return kWaitTimedOut;
}
HRESULT BxPresentSwapChain::post_present_failure(const char* event, const char* what, HRESULT hr,
HRESULT live_device_result) {
const HRESULT removed = removed_reason();
if (FAILED(removed)) {
log_hr(BX_LOG_ERROR, "present_device_removed", what, removed);
return removed;
}
needs_idle_ = true;
if (event) {
log_hr(BX_LOG_ERROR, event, what, hr);
}
if (is_device_removed_hr(hr)) {
log_hr(BX_LOG_ERROR, "present_device_removed", what, hr);
return hr;
}
return live_device_result;
}
HRESULT BxPresentSwapChain::idle_locked(ULONGLONG start, DWORD timeout_ms) {
if (GetTickCount64() - start >= timeout_ms) {
char detail[96];
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=unknown; expired before Signal",
static_cast<unsigned long>(timeout_ms), static_cast<unsigned long long>(last_signaled_ + 1));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
return kWaitTimedOut;
}
UINT64 value = 0;
HRESULT hr = signal_locked(&value);
return FAILED(hr) ? hr : wait_locked(value, start, timeout_ms);
}
void BxPresentSwapChain::destroy() {
if (swap_ && fence_ && event_) {
HRESULT idle = idle_locked(GetTickCount64(), BX_PRESENT_WAIT_MS);
if (FAILED(idle) && SUCCEEDED(removed_reason())) {
/* The device is alive and the GPU may still be using the back buffers. */
log_hr(BX_LOG_ERROR, "present_chain_leaked", "queue not idle; GPU-visible objects deliberately not released", idle);
/*
* swap_, fence_, event_ and host_queue_ stay: pending work may touch them. The proxy
* is only BetterXen's wrapper; host_queue_ keeps the host queue alive without it.
*/
ID3D12CommandQueue* proxy = queue_proxy_;
delete this;
proxy->Release();
return;
}
}
const bool had_swap = swap_ != nullptr;
ULONG swap_refs = 0;
if (swap_) swap_refs = swap_->Release();
if (fence_) fence_->Release();
if (event_) CloseHandle(event_);
if (had_swap) {
/*
* The count the host's Release returned. Non-zero means something else still references
* the swapchain: back buffers or host pointers the caller holds, or the host itself
* (see docs/research/d3dmetal-swapchain-references.md). It is reported, never "fixed up"
* by releasing references this object does not own.
*/
char detail[96];
std::snprintf(detail, sizeof(detail), "presented=%llu swapchain_release_returned=%lu",
static_cast<unsigned long long>(presented_), static_cast<unsigned long>(swap_refs));
bx_log_emit(swap_refs ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "present_chain_destroyed", detail);
}
ID3D12CommandQueue* host_queue = host_queue_;
ID3D12CommandQueue* queue_proxy = queue_proxy_;
delete this;
if (host_queue) host_queue->Release();
if (queue_proxy) queue_proxy->Release();
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::QueryInterface(REFIID riid, void** ppv) {
if (!ppv) {
return E_POINTER;
}
if (IsEqualGUID(riid, __uuidof(IUnknown)) || IsEqualGUID(riid, IID_IBxPresentSwapChain)) {
AddRef();
*ppv = static_cast<IBxPresentSwapChain*>(this);
return S_OK;
}
*ppv = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE BxPresentSwapChain::AddRef() {
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
}
ULONG STDMETHODCALLTYPE BxPresentSwapChain::Release() {
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (left == 0) {
destroy();
}
return left;
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetBuffer(UINT index, REFIID riid, void** ppv) {
if (!ppv) {
return E_POINTER;
}
*ppv = nullptr;
HRESULT hr = swap_->GetBuffer(index, riid, ppv);
if (FAILED(hr)) {
log_hr(BX_LOG_WARN, "present_get_buffer_failed", "IDXGISwapChain::GetBuffer", hr);
}
return hr;
}
UINT STDMETHODCALLTYPE BxPresentSwapChain::GetCurrentBackBufferIndex() {
return swap_->GetCurrentBackBufferIndex();
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::Present(UINT sync_interval, UINT flags) {
BX_D3D_TRACE("IBxPresentSwapChain", "Present");
if (sync_interval > 4 || flags != 0 || !IsWindow(window_)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x window_alive=%d", sync_interval, flags,
IsWindow(window_) ? 1 : 0);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", detail);
return DXGI_ERROR_INVALID_CALL;
}
if (owner_ == GetCurrentThreadId()) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", "re-entered on the same thread");
return DXGI_ERROR_INVALID_CALL;
}
/*
* Never wait for the lock. Its holder may be inside the host's Present, and DXGI can make that
* call wait for the window's thread: the caller here.
*/
if (!TryAcquireSRWLockExclusive(&lock_)) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_busy", "another call holds the swapchain; nothing presented");
return BX_PRESENT_E_BUSY;
}
SrwOwner guard(lock_, owner_);
if (needs_idle_) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_needs_idle", "completion unconfirmed; nothing presented");
return BX_PRESENT_E_NEEDS_IDLE;
}
const UINT presented_index = swap_->GetCurrentBackBufferIndex();
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
/* Busy only after an earlier BX_PRESENT_E_NEXT_BUFFER_BUSY. Nothing is presented then. */
const HRESULT ready = wait_locked(buffer_value_[presented_index], GetTickCount64(), BX_PRESENT_WAIT_MS);
if (FAILED(ready)) {
return ready;
}
}
HRESULT hr = swap_->Present(sync_interval, flags);
if (FAILED(hr)) {
char detail[128];
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x hr=0x%08lx device_removed_reason=0x%08lx", sync_interval,
flags, static_cast<unsigned long>(hr), static_cast<unsigned long>(removed_reason()));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_failed", detail);
return hr;
}
++presented_;
UINT64 value = 0;
HRESULT sync_hr = signal_locked(&value);
if (FAILED(sync_hr)) {
/* signal_locked already logged present_signal_failed when the device stays live. */
return post_present_failure(nullptr, "signal after Present", sync_hr, BX_PRESENT_E_COMPLETION_UNCONFIRMED);
}
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
buffer_value_[presented_index] = value;
}
const UINT next = swap_->GetCurrentBackBufferIndex();
if (next < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
sync_hr = wait_locked(buffer_value_[next], GetTickCount64(), BX_PRESENT_WAIT_MS);
if (sync_hr == kWaitTimedOut) {
return BX_PRESENT_E_NEXT_BUFFER_BUSY;
}
if (FAILED(sync_hr)) {
return post_present_failure("present_next_buffer_wait_failed", "wait_locked", sync_hr,
BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED);
}
}
return hr;
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::WaitForIdle(DWORD timeout_ms) {
if (timeout_ms == 0 || timeout_ms == INFINITE) {
return E_INVALIDARG;
}
if (owner_ == GetCurrentThreadId()) {
return DXGI_ERROR_INVALID_CALL;
}
const ULONGLONG start = GetTickCount64();
while (!TryAcquireSRWLockExclusive(&lock_)) {
if (GetTickCount64() - start >= timeout_ms) {
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", "swapchain busy in another call");
return kWaitTimedOut;
}
Sleep(1);
}
SrwOwner guard(lock_, owner_);
const HRESULT hr = idle_locked(start, timeout_ms);
if (hr == S_OK) {
/* A signal queued after every presented frame has completed. */
needs_idle_ = false;
}
return hr;
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetHostSwapChain(REFIID riid, void** ppv) {
if (!ppv) {
return E_POINTER;
}
*ppv = nullptr;
return swap_->QueryInterface(riid, ppv);
}
bool desc_is_valid(const BxPresentDesc& d) {
const bool format_ok = d.format == DXGI_FORMAT_R8G8B8A8_UNORM || d.format == DXGI_FORMAT_B8G8R8A8_UNORM ||
d.format == DXGI_FORMAT_R10G10B10A2_UNORM || d.format == DXGI_FORMAT_R16G16B16A16_FLOAT;
return format_ok && d.width >= 1 && d.width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.height >= 1 &&
d.height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.buffer_count >= 2 &&
d.buffer_count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
}
/* COM tear-off: its own reference count, one reference on the queue, and the queue's identity. */
class BxPresentQueue final : public IBxPresentQueue {
public:
explicit BxPresentQueue(ID3D12CommandQueue* queue_proxy) : queue_(queue_proxy) { queue_->AddRef(); }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
if (!ppv) {
return E_POINTER;
}
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
AddRef();
*ppv = static_cast<IBxPresentQueue*>(this);
return S_OK;
}
return queue_->QueryInterface(riid, ppv);
}
ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; }
ULONG STDMETHODCALLTYPE Release() override {
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (left == 0) {
ID3D12CommandQueue* queue = queue_;
delete this;
queue->Release();
}
return left;
}
HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) override {
if (!out) {
return E_POINTER;
}
*out = nullptr;
if (!desc) {
return E_POINTER;
}
if (!window || !IsWindow(window) || !desc_is_valid(*desc)) {
log_hr(BX_LOG_WARN, "present_create_rejected", "invalid window or description", DXGI_ERROR_INVALID_CALL);
return DXGI_ERROR_INVALID_CALL;
}
ID3D12CommandQueue* host = nullptr;
HRESULT hr = static_cast<IUnknown*>(bx_unwrap_raw(queue_))
->QueryInterface(__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&host));
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "host command queue", hr);
return hr;
}
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
host->GetDesc(&queue_desc);
if (queue_desc.Type != D3D12_COMMAND_LIST_TYPE_DIRECT) {
log_hr(BX_LOG_WARN, "present_create_rejected", "queue is not a DIRECT queue", DXGI_ERROR_INVALID_CALL);
hr = DXGI_ERROR_INVALID_CALL;
} else {
hr = BxPresentSwapChain::create(queue_, host, window, *desc, out);
}
host->Release();
return hr;
}
private:
~BxPresentQueue() = default;
std::atomic<ULONG> refs_{1};
ID3D12CommandQueue* queue_;
};
} // namespace
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv) {
if (!ppv) {
return E_POINTER;
}
auto* bridge = new (std::nothrow) BxPresentQueue(queue_proxy);
if (!bridge) {
*ppv = nullptr;
return E_OUTOFMEMORY;
}
*ppv = static_cast<IBxPresentQueue*>(bridge);
return S_OK;
}
+138
View File
@@ -0,0 +1,138 @@
#ifndef BETTERXEN_D3D12_XS_PRESENTX_H
#define BETTERXEN_D3D12_XS_PRESENTX_H
/*
* Track C (M2-C2, #465): the PresentX presentation bridge over host DXGI.
*
* THESE INTERFACES ARE DEFINED BY BETTERXEN. They are not the console's PresentX, whose
* signature and structures are not defined in abi/, and no binary compatibility with any Xbox
* interface is claimed. A guest that calls a console-only command queue slot still lands on the
* proxy's logged stub.
*
* Use: QueryInterface the command queue returned by a D3D12XboxCreateDevice device for
* IID_IBxPresentQueue, then create a swapchain on a Win32 window. No new DLL export is involved.
*
* This is a subset of the public DXGI flip model, not all of it: the caller records its own
* resource transitions and every back buffer must be in D3D12_RESOURCE_STATE_PRESENT when it is
* presented. D3D12 offers no way to query a resource's state, so the bridge cannot check this.
* ResizeBuffers and fullscreen are not implemented.
*/
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
#endif
#include <windows.h>
#include <unknwn.h>
#include <d3d12.h>
#include <dxgi1_4.h>
/* {34127279-2D93-4642-88A6-97B834217B8A} */
inline const GUID IID_IBxPresentQueue = {0x34127279, 0x2d93, 0x4642, {0x88, 0xa6, 0x97, 0xb8, 0x34, 0x21, 0x7b, 0x8a}};
/* {DEC9F73E-DE84-4F87-9167-26203B3A1152} */
inline const GUID IID_IBxPresentSwapChain = {0xdec9f73e, 0xde84, 0x4f87, {0x91, 0x67, 0x26, 0x20, 0x3b, 0x3a, 0x11, 0x52}};
/* Longest single GPU wait Present() performs, and the destructor's wait for the GPU. */
inline constexpr DWORD BX_PRESENT_WAIT_MS = 5000;
/*
* Present() result: the frame WAS handed to the host, but the next back buffer is still busy.
* Do not present that frame again. Call WaitForIdle until it returns S_OK before reusing a buffer.
*/
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_BUSY = static_cast<HRESULT>(0x80040201u);
/*
* Present() result: the frame was NOT handed to the host, because another Present or WaitForIdle
* on this swapchain is in progress. Present never waits for that call. Try again after it returns.
*/
inline constexpr HRESULT BX_PRESENT_E_BUSY = static_cast<HRESULT>(0x80040202u);
/*
* Present() result: the frame WAS handed to the host, but the following fence signal failed on
* a live device, so its completion is unknown. Do not present that frame again. Call WaitForIdle
* until it returns S_OK before recording to any back buffer or presenting again. Device removal
* returns the removal HRESULT unchanged instead.
*/
inline constexpr HRESULT BX_PRESENT_E_COMPLETION_UNCONFIRMED = static_cast<HRESULT>(0x80040203u);
/*
* Present() result: the frame was NOT handed to the host, because an earlier Present returned
* BX_PRESENT_E_COMPLETION_UNCONFIRMED or BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED and no WaitForIdle
* has succeeded since.
*/
inline constexpr HRESULT BX_PRESENT_E_NEEDS_IDLE = static_cast<HRESULT>(0x80040204u);
/*
* Present() result: the frame WAS handed to the host and signaled, but waiting on the next back
* buffer failed on a live device (for example SetEventOnCompletion or WaitForSingleObject). Do not
* present that frame again. Call WaitForIdle until it returns S_OK before reusing any back buffer
* or presenting again. Device removal returns the removal HRESULT unchanged instead.
*/
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED = static_cast<HRESULT>(0x80040205u);
struct BxPresentDesc {
UINT width; /* 1..16384; 0 ("use the window size") is not accepted */
UINT height; /* 1..16384 */
DXGI_FORMAT format; /* R8G8B8A8_UNORM, B8G8R8A8_UNORM, R10G10B10A2_UNORM or R16G16B16A16_FLOAT */
UINT buffer_count; /* 2..DXGI_MAX_SWAP_CHAIN_BUFFERS */
};
/*
* One swapchain. Holds a reference on the command queue it was created from.
* The final Release waits (bounded) for the queue to go idle. If that fails and the device
* reports it has not been removed, it logs and deliberately leaks what pending GPU work may
* still touch (swapchain, fence, event, host queue) and releases its queue proxy reference.
* After device removal everything is released. Time spent inside the host's own Release is not bounded: on the
* wined3d/vkd3d path (not D3DMetal) an intermittent stall in it was observed.
*/
struct IBxPresentSwapChain : public IUnknown {
/* Same rules as IDXGISwapChain::GetBuffer. The caller owns the returned reference. */
virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) = 0;
virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() = 0;
/*
* Waits (bounded) until the current back buffer is idle, calls IDXGISwapChain::Present,
* signals a fence on the queue, then waits until the next back buffer is idle. It never waits
* for another thread's call on this swapchain. Results:
* - a DXGI success code, including DXGI_STATUS_OCCLUDED: presented, next buffer idle;
* - HRESULT_FROM_WIN32(ERROR_TIMEOUT): NOT presented (the current buffer is still busy);
* - BX_PRESENT_E_NEXT_BUFFER_BUSY: presented, see its definition;
* - BX_PRESENT_E_BUSY: NOT presented, another call holds the swapchain;
* - BX_PRESENT_E_COMPLETION_UNCONFIRMED: presented, the fence signal failed on a live device;
* - BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED: presented, waiting on the next back buffer failed
* on a live device;
* - BX_PRESENT_E_NEEDS_IDLE: NOT presented, WaitForIdle must succeed first;
* - another failure: the host's Present failure, a pre-Present fence wait or device failure
* (nothing was presented), or a device-removal HRESULT (such as DXGI_ERROR_DEVICE_REMOVED
* or DXGI_ERROR_DEVICE_RESET) observed after host Present, returned unchanged. If the
* device still reports itself as live, WaitForIdle must succeed before the next Present.
* The bounds cover BetterXen's own waits, not time spent inside the host's Present.
*
* The bridge itself returns DXGI_ERROR_INVALID_CALL, without calling the host, for a
* sync_interval above 4, for any flag (none is supported, including DXGI_PRESENT_TEST),
* once the window is destroyed, and when Present or WaitForIdle is re-entered on a thread
* already inside one of them. D3DMetal 3.0 was observed to answer S_OK to the first three.
*/
virtual HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) = 0;
/*
* Waits until everything submitted to the queue before this call has finished. S_OK also ends
* the recovery state left by a post-Present synchronization failure on a live device.
* Only positive, finite timeouts are supported. Zero and INFINITE return E_INVALIDARG
* without signaling. A timeout returns HRESULT_FROM_WIN32(ERROR_TIMEOUT).
* Lock acquisition, fence signaling, and fence waiting share timeout_ms; if lock acquisition
* uses the whole budget, WaitForIdle times out without signaling. Time spent inside host calls
* reduces the remaining wait, but the bridge cannot interrupt those calls.
*/
virtual HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) = 0;
/*
* The host DXGI swapchain, for diagnostics and tests. The caller owns the reference and must
* not call Present or ResizeBuffers on it: the bridge's buffer tracking would not follow.
*/
virtual HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) = 0;
};
/* Tear-off on the command queue proxy; QueryInterface for any other IID returns the queue's answer. */
struct IBxPresentQueue : public IUnknown {
/*
* The queue must be a DIRECT queue and `window` an existing window. Argument errors return
* E_POINTER or DXGI_ERROR_INVALID_CALL; host failures are returned unchanged and logged.
*/
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) = 0;
};
/* Internal to d3d12_xs.dll: the command queue proxy answers IID_IBxPresentQueue with this. */
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv);
#endif /* BETTERXEN_D3D12_XS_PRESENTX_H */
+350
View File
@@ -0,0 +1,350 @@
/*
* ID3D12CommandQueue::PresentX as titles call it on the Xbox-layout queue (authorized GDK
* documentation: PresentX(PlaneCount, const D3D12XBOX_PRESENT_PLANE_PARAMETERS*,
* const D3D12XBOX_PRESENT_PARAMETERS*)). This is separate from presentx.h, BetterXen's own
* swapchain bridge for synthetic fixtures.
*
* On the first present, a host DXGI flip-model swapchain is created on the title's top-level
* window (the visible window owned by this process), sized to plane 0's first resource. Each
* present copies that resource into the current back buffer when formats and sizes match, and
* otherwise leaves the back buffer unchanged (logged once), then presents with sync interval 0: frame pacing
* is the title's own, through the frame events (frame_pacing.cpp). Plane 1, source and
* destination rectangles, colour spaces and scaling are not applied (logged once).
*/
#include "xbox_facade.h"
#include <dxgi1_4.h>
#include <atomic>
#include <cstdio>
#include <mutex>
#include <cstdlib>
#include <cwchar>
#include <cstring>
#include <vector>
namespace {
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
UINT64 Token;
UINT ResourceCount;
ID3D12Resource** ppResources;
D3D12_RECT* pSrcViewRects;
void* pDestPlacementBase;
UINT ColorSpace;
UINT ScaleFilter;
UINT ExtendedDescCount;
void* pExtendedDescs;
UINT Flags;
};
static_assert(sizeof(PlaneParameters) == 72, "D3D12XBOX_PRESENT_PLANE_PARAMETERS layout");
constexpr UINT kBuffers = 3;
struct Presenter {
std::mutex lock;
bool failed = false;
ID3D12CommandQueue* queue = nullptr; // host queue the swapchain was made for
IDXGISwapChain3* swapchain = nullptr;
ID3D12CommandAllocator* allocators[kBuffers] = {};
ID3D12GraphicsCommandList* list = nullptr;
ID3D12Fence* fence = nullptr;
UINT64 fence_values[kBuffers] = {};
UINT64 next_value = 1;
HANDLE event = nullptr;
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
UINT width = 0, height = 0;
UINT64 presents = 0;
};
Presenter g;
struct FindWindow {
DWORD pid;
HWND found;
};
BOOL CALLBACK find_window(HWND window, LPARAM param) {
auto* f = reinterpret_cast<FindWindow*>(param);
DWORD pid = 0;
GetWindowThreadProcessId(window, &pid);
if (pid == f->pid && IsWindowVisible(window) && !GetWindow(window, GW_OWNER)) {
f->found = window;
return FALSE;
}
return TRUE;
}
void log_hr(const char* what, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
}
DXGI_FORMAT swapchain_format(DXGI_FORMAT f) {
switch (f) {
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_R10G10B10A2_UNORM:
case DXGI_FORMAT_R16G16B16A16_FLOAT: return f;
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM;
default: return DXGI_FORMAT_B8G8R8A8_UNORM;
}
}
bool create_locked(ID3D12CommandQueue* queue, const D3D12_RESOURCE_DESC& source) {
FindWindow f{GetCurrentProcessId(), nullptr};
EnumWindows(find_window, reinterpret_cast<LPARAM>(&f));
if (!f.found) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", "no visible window owned by the title; frames not shown");
return false;
}
using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
HMODULE dxgi = LoadLibraryW(L"dxgi.dll");
auto create_factory = dxgi ? reinterpret_cast<CreateFactory2>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory2"))) : nullptr;
IDXGIFactory2* factory = nullptr;
HRESULT hr = create_factory ? create_factory(0, __uuidof(IDXGIFactory2), reinterpret_cast<void**>(&factory)) : E_NOINTERFACE;
if (FAILED(hr)) {
log_hr("CreateDXGIFactory2", hr);
return false;
}
g.width = static_cast<UINT>(source.Width);
g.height = source.Height;
g.format = swapchain_format(source.Format);
DXGI_SWAP_CHAIN_DESC1 desc{};
desc.Width = g.width;
desc.Height = g.height;
desc.Format = g.format;
desc.SampleDesc.Count = 1;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = kBuffers;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
IDXGISwapChain1* chain1 = nullptr;
hr = factory->CreateSwapChainForHwnd(queue, f.found, &desc, nullptr, nullptr, &chain1);
factory->Release();
if (FAILED(hr)) {
log_hr("CreateSwapChainForHwnd", hr);
return false;
}
hr = chain1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&g.swapchain));
chain1->Release();
if (FAILED(hr)) {
log_hr("IDXGISwapChain3", hr);
return false;
}
ID3D12Device* device = nullptr;
hr = queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
for (UINT i = 0; SUCCEEDED(hr) && i < kBuffers; ++i) {
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
reinterpret_cast<void**>(&g.allocators[i]));
}
if (SUCCEEDED(hr)) {
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.allocators[0], nullptr,
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&g.list));
}
if (SUCCEEDED(hr)) hr = g.list->Close();
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g.fence));
if (device) device->Release();
g.event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (FAILED(hr) || !g.event) {
log_hr("present resources", FAILED(hr) ? hr : E_OUTOFMEMORY);
return false;
}
g.queue = queue;
char detail[160];
std::snprintf(detail, sizeof(detail), "swapchain %ux%u format=%d on the title window (title buffer format=%d)", g.width,
g.height, static_cast<int>(g.format), static_cast<int>(source.Format));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox", detail);
return true;
}
void barrier(ID3D12GraphicsCommandList* list, 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;
list->ResourceBarrier(1, &b);
}
// Diagnostics (off unless BX_PRESENT_DUMP=<folder>): every BX_PRESENT_DUMP_EVERY-th present (default
// 64, at most 32 files) the presented buffer is copied to a readback buffer and written as a BMP,
// downscaled 4x, for looking at frames without screen-recording access.
const wchar_t* dump_folder() {
static wchar_t folder[MAX_PATH] = L"";
static const bool on = GetEnvironmentVariableW(L"BX_PRESENT_DUMP", folder, MAX_PATH) > 0;
return on ? folder : nullptr;
}
UINT64 dump_every() {
static const UINT64 every = [] {
char v[16];
const DWORD n = GetEnvironmentVariableA("BX_PRESENT_DUMP_EVERY", v, sizeof(v));
const unsigned long k = (n > 0 && n < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
return static_cast<UINT64>(k ? k : 64);
}();
return every;
}
void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_RESOURCE_DESC& desc, UINT64 frame) {
static int written = 0;
if (written >= 32 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return;
const DXGI_FORMAT f = desc.Format;
const bool bgra = f == DXGI_FORMAT_B8G8R8A8_UNORM || f == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
const bool rgba = f == DXGI_FORMAT_R8G8B8A8_UNORM || f == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
if (!bgra && !rgba) return;
ID3D12Device* device = nullptr;
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return;
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
UINT rows = 0;
UINT64 row_bytes = 0, total = 0;
device->GetCopyableFootprints(&desc, 0, 1, 0, &fp, &rows, &row_bytes, &total);
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_READBACK;
D3D12_RESOURCE_DESC buf{};
buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buf.Width = total;
buf.Height = 1;
buf.DepthOrArraySize = 1;
buf.MipLevels = 1;
buf.SampleDesc.Count = 1;
buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* readback = nullptr;
ID3D12CommandAllocator* alloc = nullptr;
ID3D12GraphicsCommandList* list = nullptr;
ID3D12Fence* fence = nullptr;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&readback));
if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&alloc));
if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, __uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
if (SUCCEEDED(hr)) {
barrier(list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
D3D12_TEXTURE_COPY_LOCATION dst{readback, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
dst.PlacedFootprint = fp;
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
barrier(list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
list->Close();
ID3D12CommandList* lists[] = {list};
queue->ExecuteCommandLists(1, lists);
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
queue->Signal(fence, 1);
fence->SetEventOnCompletion(1, done);
WaitForSingleObject(done, 5000);
CloseHandle(done);
const BYTE* data = nullptr;
if (SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast<void**>(const_cast<BYTE**>(&data))))) {
const UINT w = static_cast<UINT>(desc.Width) / 4, h = desc.Height / 4;
const UINT stride = (w * 3 + 3) & ~3u;
std::vector<BYTE> bmp(54 + static_cast<size_t>(stride) * h, 0);
auto put32 = [&](size_t at, uint32_t v) { std::memcpy(&bmp[at], &v, 4); };
bmp[0] = 'B'; bmp[1] = 'M';
put32(2, static_cast<uint32_t>(bmp.size())); put32(10, 54); put32(14, 40);
put32(18, w); put32(22, h); bmp[26] = 1; bmp[28] = 24; put32(34, static_cast<uint32_t>(stride * h));
uint64_t sum = 0;
for (UINT y = 0; y < h; ++y) {
const BYTE* row = data + fp.Offset + static_cast<UINT64>(y * 4) * fp.Footprint.RowPitch;
BYTE* out = &bmp[54 + static_cast<size_t>(h - 1 - y) * stride];
for (UINT x = 0; x < w; ++x) {
const BYTE* px = row + static_cast<size_t>(x) * 16;
const BYTE r = bgra ? px[2] : px[0], g = px[1], b = bgra ? px[0] : px[2];
out[x * 3 + 0] = b; out[x * 3 + 1] = g; out[x * 3 + 2] = r;
sum += r + g + b;
}
}
readback->Unmap(0, nullptr);
wchar_t path[MAX_PATH];
std::swprintf(path, MAX_PATH, L"%ls\\frame_%06llu.bmp", dump_folder(), static_cast<unsigned long long>(frame));
HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file != INVALID_HANDLE_VALUE) {
DWORD wrote = 0;
WriteFile(file, bmp.data(), static_cast<DWORD>(bmp.size()), &wrote, nullptr);
CloseHandle(file);
++written;
}
char detail[128];
std::snprintf(detail, sizeof(detail), "frame %llu dumped %ux%u, mean channel value %.1f",
static_cast<unsigned long long>(frame), w, h, w && h ? double(sum) / (double(w) * h * 3) : 0.0);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_dump", detail);
}
}
if (fence) fence->Release();
if (list) list->Release();
if (alloc) alloc->Release();
if (readback) readback->Release();
device->Release();
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes_raw,
const void* parameters) {
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
(void)parameters;
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
if (!source) return E_INVALIDARG;
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
std::lock_guard<std::mutex> guard(g.lock);
if (g.failed) return S_OK;
const D3D12_RESOURCE_DESC desc = source->GetDesc();
if (!g.swapchain && !create_locked(queue, desc)) {
g.failed = true;
return S_OK; // the title keeps running; frames are not shown (logged)
}
static std::atomic<bool> logged_extra{false};
if ((plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase) && !logged_extra.exchange(true)) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox",
"plane 1, view rectangles, placement and scaling are not applied; plane 0 is copied as is");
}
const UINT index = g.swapchain->GetCurrentBackBufferIndex();
if (g.fence->GetCompletedValue() < g.fence_values[index]) {
g.fence->SetEventOnCompletion(g.fence_values[index], g.event);
WaitForSingleObject(g.event, 2000);
}
ID3D12Resource* back = nullptr;
HRESULT hr = g.swapchain->GetBuffer(index, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&back));
if (FAILED(hr)) {
log_hr("GetBuffer", hr);
return S_OK;
}
g.allocators[index]->Reset();
g.list->Reset(g.allocators[index], nullptr);
const bool copyable = desc.Width == g.width && desc.Height == g.height && swapchain_format(desc.Format) == g.format &&
desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1;
if (copyable) {
// The title's buffer is assumed to be presentable (PRESENT, i.e. COMMON) when PresentX is called.
barrier(g.list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
barrier(g.list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
D3D12_TEXTURE_COPY_LOCATION dst{back, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
barrier(g.list, back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT);
barrier(g.list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
} else {
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
char detail[160];
std::snprintf(detail, sizeof(detail), "title buffer %llux%u format=%d does not match the swapchain; not copied, the window shows the previous contents",
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
}
}
g.list->Close();
ID3D12CommandList* lists[] = {g.list};
g.queue->ExecuteCommandLists(1, lists);
back->Release();
hr = g.swapchain->Present(0, 0);
g.fence_values[index] = g.next_value++;
g.queue->Signal(g.fence, g.fence_values[index]);
const UINT64 n = ++g.presents;
if (dump_folder() && copyable && n % dump_every() == 0) dump_frame(g.queue, source, desc, n);
if ((n & (n - 1)) == 0) {
char detail[96];
std::snprintf(detail, sizeof(detail), "frames presented=%llu last hr=0x%08lx", static_cast<unsigned long long>(n),
static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_frames", detail);
}
return S_OK;
}
+179 -6
View File
@@ -4,6 +4,10 @@
#include <cstdio>
#include <cstring>
#include <new>
#include <type_traits>
#include <vector>
#include "presentx.h"
#include "shader_gate.h"
@@ -429,6 +433,132 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateComputePipelineState(const D3D12_
return hr;
}
/* Stream PSO subobjects (#576). A stream is a sequence of 8-byte-aligned records, each a
* subobject type and a type-dependent payload. The real layout aligns the record, not the
* payload: a payload whose type is only 4-byte aligned starts at offset 4, not 8. Measured
* with the shim's own toolchain, that is the case for BLEND, SAMPLE_MASK, RASTERIZER,
* DEPTH_STENCIL, DEPTH_STENCIL1, IB_STRIP_CUT_VALUE, PRIMITIVE_TOPOLOGY,
* RENDER_TARGET_FORMATS, DEPTH_STENCIL_FORMAT, SAMPLE_DESC, NODE_MASK and FLAGS. Deriving
* both the payload offset and the record size from the compiler keeps this table honest. */
template<class Payload>
struct alignas(void*) StreamRecord {
/* alignas is on the CLASS, as in CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT: it pads the
* whole record to 8 bytes but does not move a 4-byte-aligned payload off offset 4. */
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
Payload payload;
};
template<class Payload>
constexpr size_t payload_at() { return offsetof(StreamRecord<Payload>, payload); }
template<class Payload>
constexpr size_t record_size() {
return (offsetof(StreamRecord<Payload>, payload) + sizeof(Payload) + 7) & ~static_cast<size_t>(7);
}
struct StreamSubobject {
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
size_t payload_offset;
size_t record_size;
const char* stage; /* non-null only for a shader subobject */
};
#define BX_SUBOBJECT(tag, type, stage) \
{tag, payload_at<type>(), record_size<type>(), stage}
constexpr StreamSubobject kStreamSubobjects[] = {
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, void*, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE, "VS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE, "PS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, D3D12_SHADER_BYTECODE, "DS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, D3D12_SHADER_BYTECODE, "HS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, D3D12_SHADER_BYTECODE, "GS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, D3D12_SHADER_BYTECODE, "CS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, D3D12_STREAM_OUTPUT_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, D3D12_INPUT_LAYOUT_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, UINT, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, UINT, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, UINT, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, D3D12_CACHED_PIPELINE_STATE, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, UINT, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, D3D12_DEPTH_STENCIL_DESC1, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, D3D12_VIEW_INSTANCING_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE, "AS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE, "MS"),
};
#undef BX_SUBOBJECT
/* Pin the layout facts the walker depends on, measured with this toolchain. A header change
* that moves a payload must fail to compile rather than desync the walk (#576 review). */
static_assert(payload_at<D3D12_SHADER_BYTECODE>() == 8, "shader payloads sit at offset 8");
static_assert(record_size<D3D12_SHADER_BYTECODE>() == 24, "a shader record is 24 bytes");
static_assert(payload_at<UINT>() == 4, "4-byte payloads sit at offset 4, not 8");
static_assert(record_size<UINT>() == 8, "a UINT record is 8 bytes");
static_assert(payload_at<D3D12_BLEND_DESC>() == 4, "BLEND payload sits at offset 4");
static_assert(payload_at<D3D12_RASTERIZER_DESC>() == 4, "RASTERIZER payload sits at offset 4");
static_assert(payload_at<D3D12_RT_FORMAT_ARRAY>() == 4, "RT_FORMAT_ARRAY payload sits at offset 4");
static_assert(payload_at<D3D12_DEPTH_STENCIL_DESC1>() == 4, "DEPTH_STENCIL1 payload sits at offset 4");
static_assert(payload_at<void*>() == 8 && record_size<void*>() == 16, "root signature record");
static_assert(payload_at<D3D12_INPUT_LAYOUT_DESC>() == 8, "INPUT_LAYOUT payload sits at offset 8");
const StreamSubobject* find_subobject(uint32_t type) {
for (const StreamSubobject& entry : kStreamSubobjects) {
if (static_cast<uint32_t>(entry.type) == type) return &entry;
}
return nullptr;
}
/* Copies the caller's stream into `copy` so the gate can substitute prepared bytecode without
* touching memory it does not own, and records where each shader payload sits (and, when
* `root_offset` is given, the root-signature payload, or SIZE_MAX without one). An unknown tag,
* or a payload that overruns SizeInBytes, is rejected. */
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
size_t* root_offset) {
if (root_offset) *root_offset = SIZE_MAX;
if (desc.SizeInBytes == 0 || !desc.pPipelineStateSubobjectStream) return E_INVALIDARG;
const auto* source = static_cast<const uint8_t*>(desc.pPipelineStateSubobjectStream);
copy.assign(source, source + desc.SizeInBytes);
size_t offset = 0;
while (offset < copy.size()) {
if (copy.size() - offset < sizeof(SIZE_T)) return E_INVALIDARG;
/* The tag is a 4-byte enum at the start of an 8-byte-aligned record; the rest of
* those 8 bytes is padding a caller may leave uninitialized, so read only the enum
* and step to the payload at offset sizeof(SIZE_T). */
uint32_t raw = 0;
std::memcpy(&raw, &copy[offset], sizeof(raw));
if (raw >= static_cast<uint32_t>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID)) return E_INVALIDARG;
const StreamSubobject* entry = find_subobject(raw);
if (!entry) return E_INVALIDARG;
/* Microsoft's ID3D12Device2 rules reject a duplicated subobject type. */
for (size_t seen = 0; seen < offset; ) {
uint32_t prior = 0;
std::memcpy(&prior, &copy[seen], sizeof(prior));
if (prior == raw) return E_INVALIDARG;
const StreamSubobject* prior_entry = find_subobject(prior);
if (!prior_entry) return E_INVALIDARG;
seen += prior_entry->record_size;
}
const size_t payload = offset + entry->payload_offset;
const size_t record = entry->record_size;
if (copy.size() - offset < record) return E_INVALIDARG;
if (root_offset && entry->type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) *root_offset = payload;
if (entry->stage) {
D3D12_SHADER_BYTECODE code{};
std::memcpy(&code, &copy[payload], sizeof(code));
if (code.BytecodeLength != 0 && !code.pShaderBytecode) return E_INVALIDARG;
stage_offsets.push_back(payload);
stage_names.push_back(entry->stage);
}
offset += record;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
BX_D3D_TRACE("ID3D12Device2", "CreatePipelineState");
if (!h_ID3D12Device2) {
@@ -436,12 +566,50 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
if (ppv) *ppv = nullptr;
return E_NOTIMPL;
}
/* The stream form is forwarded unparsed: only its size is recorded (sub-object walking is M2 work). */
char detail[96];
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=1",
static_cast<unsigned long long>(desc ? desc->SizeInBytes : 0));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
if (ppv) *ppv = nullptr;
if (!desc) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", "pso=stream bytes=0 shaders_not_parsed=1");
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
log_created("stream pipeline state", hr);
return hr;
}
/* M2 shader format gate (#576): the stream form classifies its stages like the desc forms,
* so an ACCC-only container is refused instead of reaching D3DMetal unparsed. */
std::vector<uint8_t> stream;
std::vector<size_t> offsets;
std::vector<const char*> names;
const HRESULT copied = copy_stream(*desc, stream, offsets, names, nullptr);
{
char detail[96];
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=%d",
static_cast<unsigned long long>(desc->SizeInBytes), offsets.empty() ? 1 : 0);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
}
if (FAILED(copied) || offsets.empty()) {
const HRESULT hr = FAILED(copied) ? copied : h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
log_created("stream pipeline state", hr);
return hr;
}
BxShaderGate gate;
HRESULT gated = S_OK;
for (size_t i = 0; i < offsets.size() && SUCCEEDED(gated); ++i) {
D3D12_SHADER_BYTECODE in{};
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
D3D12_SHADER_BYTECODE out = in;
gated = gate.admit("stream", names[i], in, out);
/* `out` is either the caller's bytes or the gate's copy, which lives until `gate`
* is destroyed, so only the pointer/length inside our own copy change. */
if (SUCCEEDED(gated)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
}
if (FAILED(gated)) {
log_created("stream pipeline state", gated);
return gated;
}
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(&admitted, riid, ppv);
log_created("stream pipeline state", hr);
return hr;
}
@@ -525,6 +693,11 @@ HRESULT STDMETHODCALLTYPE BxChildProxy<Gen>::QueryInterface(REFIID riid, void**
*ppv = static_cast<Gen*>(this);
return S_OK;
}
if constexpr (std::is_same_v<Gen, BxCommandQueueProxyImpl>) {
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
return bx_present_query_queue(this, ppv); /* BetterXen's presentation bridge, presentx.h */
}
}
return query_host_unproxied(host_identity_, Gen::kLeafName, riid, ppv);
}
+7
View File
@@ -19,6 +19,7 @@
#include <atomic>
#include <cstdint>
#include <vector>
#include "bx_config.h"
#include "bx_log.h"
@@ -117,3 +118,9 @@ using BxCommandAllocatorProxy = BxChildProxy<BxCommandAllocatorProxyGen>;
using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
#endif /* BETTERXEN_D3D12_XS_PROXY_H */
/* Validates and copies a pipeline-state stream (proxy.cpp, #576): shader payload offsets and
* stage names, and the root-signature payload offset when `root_offset` is given. */
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
size_t* root_offset);
+2 -2
View File
@@ -385,7 +385,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource2(const D3D12
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource1(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
BX_D3D_TRACE("ID3D12Device8", "CreatePlacedResource1");
if (!h_ID3D12Device8) { BX_VTABLE_STUB_LOG("ID3D12Device8", 70u, "CreatePlacedResource1"); return E_NOTIMPL; }
return h_ID3D12Device8->CreatePlacedResource1(bx_unwrap(a0), a1, a2, a3, a4, a5, a6);
return bx_vmem_create_placed_resource1(h_ID3D12Device8, a0, a1, a2, a3, a4, a5, a6);
}
void STDMETHODCALLTYPE BxDeviceProxyGen::CreateSamplerFeedbackUnorderedAccessView(ID3D12Resource * a0, ID3D12Resource * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
@@ -421,7 +421,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource3(const D3D12
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource2(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_BARRIER_LAYOUT a3, const D3D12_CLEAR_VALUE * a4, UINT32 a5, DXGI_FORMAT * a6, REFIID a7, void ** a8) {
BX_D3D_TRACE("ID3D12Device10", "CreatePlacedResource2");
if (!h_ID3D12Device10) { BX_VTABLE_STUB_LOG("ID3D12Device10", 77u, "CreatePlacedResource2"); return E_NOTIMPL; }
return h_ID3D12Device10->CreatePlacedResource2(bx_unwrap(a0), a1, a2, a3, a4, a5, a6, a7, a8);
return bx_vmem_create_placed_resource2(h_ID3D12Device10, a0, a1, a2, a3, a4, a5, a6, a7, a8);
}
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateReservedResource2(const D3D12_RESOURCE_DESC * a0, D3D12_BARRIER_LAYOUT a1, const D3D12_CLEAR_VALUE * a2, ID3D12ProtectedResourceSession * a3, UINT32 a4, DXGI_FORMAT * a5, REFIID a6, void ** a7) {
+4
View File
@@ -2,6 +2,10 @@
#ifndef BETTERXEN_D3D12_XS_PROXY_GENERATED_H
#define BETTERXEN_D3D12_XS_PROXY_GENERATED_H
/* HANDOFF targets: the host interface, then the caller's arguments unmodified. */
HRESULT bx_vmem_create_placed_resource1(ID3D12Device8* host, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6);
HRESULT bx_vmem_create_placed_resource2(ID3D12Device10* host, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_BARRIER_LAYOUT a3, const D3D12_CLEAR_VALUE * a4, UINT32 a5, DXGI_FORMAT * a6, REFIID a7, void ** a8);
class BxDeviceProxyGen : public ID3D12Device10 {
public:
static constexpr const char* kLeafName = "ID3D12Device10";
+38 -3
View File
@@ -149,13 +149,21 @@ constexpr uint64_t kAtomic64Typed = 0x400000;
constexpr uint64_t kAtomic64GroupShared = 0x800000;
constexpr uint64_t kAtomic64Heap = 0x10000000;
/* The [WaveSize(64)] case on its own (#591). A wider-than-32 wave is refused at PSO creation
* rather than handed to a host that creates the pipeline and never runs it: the caller then
* learns from a failed call instead of from a silently absent draw. Lowering 64 lanes to 32 is
* a semantic transform (reductions, lane indices, 64-bit masks, cross-half permutes, barriers)
* and is deferred. 64-bit atomics stay warn-only until their detection is complete (#589). */
bool wave_wider_than_32(const Constraints& c) {
return c.has_lanes && c.lanes_min > 32;
}
/* Measured on D3DMetal (docs/research/d3dmetal-gpu-limits.md): pipelines that require a wave
* wider than 32 lanes, or 64-bit atomics, are created but never run. */
bool known_d3dmetal_gap(const Constraints& c) {
const bool wide_wave = c.has_lanes && c.lanes_min > 32;
return wide_wave || (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
return wave_wider_than_32(c)
|| (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
}
const char* kind_name(bx_shader_kind_t kind) {
switch (kind) {
case BX_SHADER_DXBC_DXIL: return "dxil";
@@ -254,6 +262,26 @@ HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12
++copy_count_;
out.pShaderBytecode = copy;
out.BytecodeLength = copy_len;
/* A wave wider than 32 lanes is refused here (#591): D3DMetal creates such a
* pipeline and never runs it, so returning S_OK would leave the caller with a
* silent no-op. The stage keeps its copy alive via `gate` until the caller's
* PSO call returns. */
if (wave_wider_than_32(constraints)) {
log_gate(pso_kind, stage, len, &info, &constraints, "reject_wave_wide", E_NOTIMPL);
/* Keep the established gap-detail shape: the consumer (#593) strips a trailing
* colon from the last value and treats `atomic64_flags` as always present, so
* `wave_lanes_min` must not be the final field. */
char detail[200];
std::snprintf(detail, sizeof(detail),
"pso=%s stage=%s wave_lanes_min=%lu atomic64_flags=0x%llx: a wave wider "
"than 32 lanes is created but never run on D3DMetal (#453); refused at "
"PSO creation (#591)",
pso_kind, stage, static_cast<unsigned long>(constraints.lanes_min),
static_cast<unsigned long long>(
constraints.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap)));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_d3dmetal_gap", detail);
return E_NOTIMPL;
}
log_gate(pso_kind, stage, len, &info, &constraints, "pass_dxil", S_OK);
if (known_d3dmetal_gap(constraints)) {
char detail[160];
@@ -268,6 +296,13 @@ HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12
return S_OK;
}
default:
// A container with a DXIL part that the classifier cannot call executable DXIL:
// the measured case is a header-only program (a `NOBC` payload, no bitcode), which
// D3DMetal crashes on in CreatePipelineState instead of failing. Refuse it.
if (info.dxil_chunk_size != 0) {
log_gate(pso_kind, stage, len, &info, &constraints, "reject_unclassified_dxil", E_NOTIMPL);
return E_NOTIMPL;
}
log_gate(pso_kind, stage, len, &info, &constraints, "pass_original", S_OK);
return S_OK;
}
+2 -1
View File
@@ -24,7 +24,8 @@ public:
* host gets: the bridge's prepared DXIL copy for DXIL and dual containers, or `in` unchanged
* for legacy DXBC, unclassifiable input, or when the bridge is missing (logged once as
* `shader_bridge_missing`). Returns E_NOTIMPL for an ACCC-only container, which has no
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge. Copies live until this
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge, and for a container whose
* DXIL part the bridge cannot classify (a header-only program). Copies live until this
* object is destroyed.
*/
HRESULT admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
+35
View File
@@ -9,6 +9,9 @@ Only method names, return types and parameter types are taken from the header:
they are what an override must repeat verbatim to compile. Parameters are
renamed positionally (a0, a1, ...). Methods listed in CUSTOM are declared but
left for proxy.cpp to implement by hand (wrapping, unwrapping, logging).
Methods listed in HANDOFF keep the generated trace and null-host stub, then pass
the host interface and the caller's arguments, unmodified, to a free function
whose declaration is generated from the same header signature.
Usage: python3 shims/d3d12_xs/tools/gen_proxy.py [path/to/d3d12.h]
(default: located through `x86_64-w64-mingw32-g++ -E`)
@@ -41,6 +44,16 @@ PROXIES = {
}),
}
# proxy class -> {method: free function}. The function receives the host interface of the method's
# level followed by the caller's arguments; nothing is unwrapped. vmem.cpp implements both below
# with the same placement validation and heap retention as CreatePlacedResource (slot 29).
HANDOFF = {
"BxDeviceProxyGen": {
"CreatePlacedResource1": "bx_vmem_create_placed_resource1",
"CreatePlacedResource2": "bx_vmem_create_placed_resource2",
},
}
# Interfaces that carry no host pointer of their own: their methods forward through the root level.
ABSTRACT = {"IUnknown", "ID3D12Object", "ID3D12DeviceChild", "ID3D12Pageable", "ID3D12CommandList"}
# A single-pointer parameter of one of these types may be one of our proxies and is unwrapped.
@@ -117,6 +130,7 @@ def main():
h = ["// Generated by shims/d3d12_xs/tools/gen_proxy.py from the toolchain's <d3d12.h>. Do not edit by hand.",
"#ifndef BETTERXEN_D3D12_XS_PROXY_GENERATED_H", "#define BETTERXEN_D3D12_XS_PROXY_GENERATED_H", ""]
h_pre = []
c = ["// Generated by shims/d3d12_xs/tools/gen_proxy.py from the toolchain's <d3d12.h>. Do not edit by hand.",
'#include "proxy.h"', ""]
@@ -125,6 +139,10 @@ def main():
levels = [i for i in chain if i not in ABSTRACT]
root = levels[0]
seen_custom = set()
handoff = HANDOFF.get(cls, {})
seen_handoff = set()
if custom & handoff.keys():
sys.exit(f"{cls}: methods in both CUSTOM and HANDOFF: {sorted(custom & handoff.keys())}")
h += [f"class {cls} : public {leaf} {{", "public:",
f' static constexpr const char* kLeafName = "{leaf}";']
@@ -162,6 +180,18 @@ def main():
seen_custom.add(name)
slot += 1
continue
if name in handoff:
seen_handoff.add(name)
fn = handoff[name]
host_type = root if iface in ABSTRACT else iface
h_pre.append(f"{ret} {fn}({host_type}* host{', ' if decl else ''}{decl});")
call = f"{fn}({', '.join([host] + [f'a{n}' for n in range(len(params))])})"
c += [f"{ret} STDMETHODCALLTYPE {cls}::{name}({decl}) {{",
f' BX_D3D_TRACE("{iface}", "{name}");',
f" if (!{host}) {{ {default_return(ret, iface, slot, name)} }}",
f" {'' if ret == 'void' else 'return '}{call};", "}", ""]
slot += 1
continue
args = []
for n, (t, arr) in enumerate(params):
bare = t.replace("const", "").replace(" ", "")
@@ -180,6 +210,9 @@ def main():
missing = custom - seen_custom
if missing:
sys.exit(f"{cls}: custom methods not found in header: {sorted(missing)}")
missing = handoff.keys() - seen_handoff
if missing:
sys.exit(f"{cls}: hand-off methods not found in header: {sorted(missing)}")
h += ["", f" static constexpr unsigned kPublicSlotCount = {slot}u;",
" /*",
@@ -194,6 +227,8 @@ def main():
h += ["", "protected:", f" ~{cls}() = default;", "};", ""]
h += ["#endif"]
if h_pre:
h[4:4] = ["/* HANDOFF targets: the host interface, then the caller's arguments unmodified. */"] + h_pre + [""]
(OUT_DIR / "proxy_generated.h").write_text("\n".join(h) + "\n", encoding="utf-8")
(OUT_DIR / "proxy_generated.cpp").write_text("\n".join(c), encoding="utf-8")
print(f"wrote proxy_generated.h/.cpp from {header}")
+384
View File
@@ -0,0 +1,384 @@
#!/usr/bin/env python3
"""Generate the Xbox-layout function tables of the d3d12_xs proxy objects.
A title built against the Xbox D3D12 headers calls every method through a function table whose
order is not the PC D3D12 order (Xbox-only methods sit between and inside the PC ones). This
script reads two headers:
* the Xbox Series header (d3d12_xs.h from the GDKX, used under Microsoft's authorization). Only
facts are taken from it: interface names and IIDs, the slot order of each function table, and
each method's name, return type and parameter types. Nothing from it is copied into the output
verbatim beyond those names, and the header itself is never committed.
* the toolchain's PC <d3d12.h>, which the shim is compiled against.
For every slot of the chosen Xbox interfaces it emits one of:
* a typed forwarder to the PC method of the same name, when the Xbox and PC signatures are
equivalent (the PC types are used, so the compiler handles struct returns and the calling
convention); interface-pointer parameters are unwrapped and (REFIID, void**) results wrapped;
* a shared IUnknown/GetDevice slot implemented in xbox_facade.cpp;
* a stub that logs BX_VTABLE_STUB_LOG and returns a neutral value, for Xbox-only methods and for
methods whose signatures differ.
Usage: python3 shims/d3d12_xs/tools/gen_xbox_tables.py /path/to/d3d12_xs.h [path/to/pc/d3d12.h]
"""
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import gen_proxy # noqa: E402 (PC header parser shared with the PC proxy generator)
OUT_DIR = Path(__file__).resolve().parents[1]
# Xbox leaf interface -> (PC interface the host object must provide, C++ family tag)
FAMILIES = {
"ID3D12Device11": ("ID3D12Device10", "Device"),
"ID3D12Resource2": ("ID3D12Resource2", "Resource"),
"ID3D12Heap1": ("ID3D12Heap1", "Heap"),
"ID3D12Fence1": ("ID3D12Fence", "Fence"), # D3DMetal answers ID3D12Fence, not Fence1
"ID3D12DescriptorHeap": ("ID3D12DescriptorHeap", "DescriptorHeap"),
"ID3D12RootSignature": ("ID3D12RootSignature", "RootSignature"),
"ID3D12PipelineState": ("ID3D12PipelineState", "PipelineState"),
"ID3D12CommandAllocator": ("ID3D12CommandAllocator", "CommandAllocator"),
"ID3D12QueryHeap": ("ID3D12QueryHeap", "QueryHeap"),
"ID3D12CommandSignature": ("ID3D12CommandSignature", "CommandSignature"),
"ID3D12CommandQueue": ("ID3D12CommandQueue", "CommandQueue"),
"ID3D12GraphicsCommandList8": ("ID3D12GraphicsCommandList7", "GraphicsCommandList"),
}
# Xbox-only slots implemented by hand in xbox_facade.cpp: family -> {method: function}.
CUSTOM = {
"Device": {"CreateCommandQueueX": "bx_xbox_device_create_command_queue_x",
"CreateCommandListX": "bx_xbox_device_create_command_list_x",
"SetFrameIntervalX": "bx_xbox_device_set_frame_interval_x",
"ScheduleFrameEventX": "bx_xbox_device_schedule_frame_event_x",
"WaitFrameEventX": "bx_xbox_device_wait_frame_event_x",
"CreatePlacedResourceX": "bx_xbox_device_create_placed_resource_x",
"CreatePlacedResourceX1": "bx_xbox_device_create_placed_resource_x1",
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
"CreateConstantBufferView": "bx_xbox_device_create_constant_buffer_view",
"CopyDescriptors": "bx_xbox_device_copy_descriptors",
"CreateCommandSignature": "bx_xbox_device_create_command_signature",
"CreatePipelineState": "bx_xbox_device_create_pipeline_state",
"DeserializeGraphicsPipelineStateX": "bx_xbox_device_deserialize_graphics_pipeline_state_x",
"CreateDerivedGraphicsPipelineStateX": "bx_xbox_device_create_derived_graphics_pipeline_state_x",
"CreateDerivedComputePipelineStateX": "bx_xbox_device_create_derived_compute_pipeline_state_x",
"DeserializeComputePipelineStateX": "bx_xbox_device_deserialize_compute_pipeline_state_x",
"CreateSamplerX": "bx_xbox_device_create_sampler_x",
"RegisterPagePoolX": "bx_xbox_device_register_page_pool_x",
"UnregisterPagePoolX": "bx_xbox_device_unregister_page_pool_x",
"CreateComputePipelineState": "bx_xbox_device_create_compute_pipeline_state",
"CreateGraphicsPipelineState": "bx_xbox_device_create_graphics_pipeline_state",
"CreateComputePipelineStateX": "bx_xbox_device_create_compute_pipeline_state_x",
"CreateGraphicsPipelineStateX": "bx_xbox_device_create_graphics_pipeline_state_x",
"CreateCommittedResource": "bx_xbox_device_create_committed_resource",
"CreateCommittedResource1": "bx_xbox_device_create_committed_resource1",
"CreateCommittedResource2": "bx_xbox_device_create_committed_resource2",
"CreateCommittedResource3": "bx_xbox_device_create_committed_resource3",
"CreatePlacedRawShaderResourceViewX": "bx_xbox_device_create_placed_raw_srv_x",
"CreatePlacedRawUnorderedAccessViewX": "bx_xbox_device_create_placed_raw_uav_x",
"CreatePlacedShaderResourceViewX": "bx_xbox_device_create_placed_srv_x",
"CreatePlacedUnorderedAccessViewX": "bx_xbox_device_create_placed_uav_x"},
"Resource": {"GetGPUVirtualAddress": "bx_xbox_resource_get_gpu_virtual_address",
"Map": "bx_xbox_resource_map", "Unmap": "bx_xbox_resource_unmap"},
"Fence": {"GetGpuAddressX": "bx_xbox_fence_get_gpu_address_x", "Signal": "bx_xbox_fence_signal"},
"CommandQueue": {"ExecuteCommandLists": "bx_xbox_queue_execute_command_lists",
"Signal": "bx_xbox_queue_signal", "Wait": "bx_xbox_queue_wait",
"PresentX": "bx_xbox_queue_present_x",
"CopyPageMappingsBatchX": "bx_xbox_queue_copy_page_mappings_batch_x",
"CopyPageMappingsX": "bx_xbox_queue_copy_page_mappings_x",
"ClearPageMappingsX": "bx_xbox_queue_clear_page_mappings_x",
"ExecuteCommandLists2X": "bx_xbox_queue_execute_command_lists2_x"},
"CommandAllocator": {"SetAllocatorCallbackX": "bx_xbox_allocator_set_callback_x"},
"DescriptorHeap": {"GetCPUDescriptorHandleForHeapStart": "bx_xbox_heap_cpu_start",
"GetGPUDescriptorHandleForHeapStart": "bx_xbox_heap_gpu_start"},
"GraphicsCommandList": {"ResourceBarrier": "bx_xbox_list_resource_barrier",
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
"Reset": "bx_xbox_list_reset",
"ResetX": "bx_xbox_list_reset_x",
"Wait64BitValueX": "bx_xbox_list_wait64_x",
"Wait32BitValueX": "bx_xbox_list_wait32_x",
"Write32BitValueBottomOfPipeX": "bx_xbox_list_write32_bop_x",
"Write64BitValueBottomOfPipeX": "bx_xbox_list_write64_bop_x",
"Write32BitValueTopOfPipeX": "bx_xbox_list_write32_top_x",
"Write64BitValueTopOfPipeX": "bx_xbox_list_write64_top_x",
"SyncTopOfPipeX": "bx_xbox_list_sync_x",
"SyncBottomOfPipeX": "bx_xbox_list_sync_x",
"DrawInstanced": "bx_xbox_list_draw_instanced",
"DrawIndexedInstanced": "bx_xbox_list_draw_indexed_instanced",
"Dispatch": "bx_xbox_list_dispatch",
"ExecuteIndirect": "bx_xbox_list_execute_indirect"},
}
SHARED = {"QueryInterface": "bx_xbox_query_interface", "AddRef": "bx_xbox_add_ref",
"Release": "bx_xbox_release", "GetDevice": "bx_xbox_get_device"}
# Interfaces whose pointers a forwarded call must unwrap from an Xbox object to its host.
WRAPPABLE = re.compile(r"^(const\s+)?(ID3D12\w+|IUnknown)\s*\*$")
WRAPPABLE_ARRAY = re.compile(r"^(ID3D12\w+)\s*\*\s*const\s*\*$")
def strip_sal(text):
text = re.sub(r"//[^\n]*", "", text)
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
# SAL annotations, including arguments with nested parentheses such as sizeof(UINT).
out, i = [], 0
for m in re.finditer(r"\b_[A-Za-z]\w*_\b", text):
if m.start() < i:
continue
out.append(text[i:m.start()])
j = m.end()
while j < len(text) and text[j] == " ":
j += 1
if j < len(text) and text[j] == "(":
depth = 0
while j < len(text):
depth += {"(": 1, ")": -1}.get(text[j], 0)
j += 1
if depth == 0:
break
i = j
out.append(text[i:])
return " ".join("".join(out).split())
def canon(t):
"""Canonical spelling for comparing an Xbox and a PC parameter or return type."""
t = " ".join(t.split())
t = re.sub(r"\s*\*\s*", "*", t)
t = re.sub(r"\s*&\s*", "&", t)
t = t.replace("LPCWSTR", "const WCHAR*").replace("LPCSTR", "const char*")
t = re.sub(r"\bWINBOOL\b", "BOOL", t)
t = re.sub(r"\bFLOAT\b", "float", t)
t = re.sub(r"^const IID&$", "REFIID", t)
t = re.sub(r"^const GUID&$", "REFGUID", t)
if "*" not in t and "&" not in t and "[" not in t:
t = re.sub(r"^const ", "", t) # top-level const on a by-value parameter
return t
def xbox_param_type(p):
p = " ".join(p.split())
m = re.match(r"^(.*?)(\w+)(\[[^\]]*\])$", p)
if m:
return canon(m.group(1)) + m.group(3)
m = re.match(r"^(.*[\s\*&])(\w+)$", p)
return canon(m.group(1) if m else p)
def parse_xbox(text):
iids = {m.group(1): m.groups()[1:] for m in re.finditer(
r"^D3DINTERFACE\((\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),"
r"\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+)\)", text, re.M)}
bases = {m.group(1): m.group(2) for m in re.finditer(
r"^D3DINTERFACE\((\w+),[^)]*\)\s*:\s*public\s+(\w+)", text, re.M)}
tables = {}
for m in re.finditer(r"struct\s+(\w+)_Function_Table\s*\{((?:(?!struct\s+\w+_Function_Table\b).)*?)\n\s*\};", text, re.S):
entries = []
for decl in re.split(r";\s*\n", m.group(2) + "\n"):
decl = strip_sal(decl).rstrip(";").strip()
b = re.match(r"^(\w+)_Function_Table\s+\w+$", decl)
if b:
entries.append(("base", b.group(1)))
continue
f = re.match(r"^(.*?)\(\s*D3DAPI\s*\*\s*(\w+)\s*\)\s*\((.*)\)$", decl, re.S)
if f:
params = [x.strip() for x in f.group(3).split(",") if x.strip() and x.strip() != "void"]
entries.append(("fn", (f.group(2), canon(f.group(1)), [xbox_param_type(p) for p in params])))
tables[m.group(1)] = entries
return iids, bases, tables
def flatten(tables, name):
out = []
for kind, v in tables.get(name, []):
out += flatten(tables, v) if kind == "base" else [v]
return out
def table_name(iface):
return "D3D12" + iface[len("ID3D12"):] if iface.startswith("ID3D12") else iface
def pc_methods(interfaces, leaf):
methods = {}
for iface in gen_proxy.chain_of(interfaces, leaf):
for ret, name, params in interfaces[iface][1]:
methods.setdefault(name, (iface, ret, params))
return methods
def classify(xret, xparams, pc):
"""Returns ('forward', struct_return) when the Xbox slot can call the PC method, else None."""
_, pret, pparams = pc
pp = [canon(t) + a for t, a in pparams]
xp = xparams[1:] # drop the explicit Xbox `this`
pr = canon(pret)
if xp == pp and (xret == pr or (xret == "void" and pr in ("void", "HRESULT"))):
return ("forward", False)
if pr.endswith("*") and pp and pp[0] == pr and pr[:-1] == xret and xp == pp[1:]:
return ("forward", True) # Xbox returns by value, PC by pointer
if xret == "void" and pr.endswith("*") and pp and pp[0] == pr and xp == pp:
return ("forward", False) # Xbox out-pointer, PC returns that pointer
return None
def emit_forward(family, slot, name, pc, struct_return):
iface, pret, pparams = pc
params = list(pparams)
ret = pret[:-1].strip() if struct_return else pret
if struct_return:
params = params[1:]
decl, call, pre, post = [], [], [], []
for i, (t, arr) in enumerate(params):
decl.append(f"{t} a{i}{arr}")
translate = {"D3D12_CPU_DESCRIPTOR_HANDLE": "bx_xbox_host_cpu_handle",
"D3D12_GPU_DESCRIPTOR_HANDLE": "bx_xbox_host_gpu_handle",
"D3D12_GPU_VIRTUAL_ADDRESS": "bx_xbox_host_gpu_va"}.get(canon(t)) if not arr else None
if translate:
call.append(f"{translate}(a{i})")
elif WRAPPABLE.match(t) and not arr:
call.append(f"bx_xbox_unwrap_as<{WRAPPABLE.match(t).group(2)}>(a{i})")
elif WRAPPABLE_ARRAY.match(t) and not arr:
elem = WRAPPABLE_ARRAY.match(t).group(1)
pre.append(f"BxXboxUnwrapArray<{elem}> u{i}(a{i}, {find_count(params, i, name)});")
pre.append(f"if (!u{i}.ok()) return {failure_value(ret)};")
call.append(f"u{i}.data()")
else:
call.append(f"a{i}")
wrap_out = len(params) >= 2 and canon(params[-2][0]) == "REFIID" and canon(params[-1][0]) == "void**"
host = f"bx_xbox_host<{iface}>(self)"
lines = [f"static {ret} STDMETHODCALLTYPE x_{family}_{slot}(void* self{''.join(', ' + d for d in decl)}) {{",
f' BX_D3D_TRACE("Xbox{family}", "{name}");']
lines += [" " + p for p in pre]
if struct_return:
lines += [f" {ret} result{{}};", f" {host}->{name}(&result{''.join(', ' + c for c in call)});",
" return result;"]
elif ret == "void":
lines.append(f" {host}->{name}({', '.join(call)});")
elif wrap_out and ret == "HRESULT":
n = len(params)
lines += [f" HRESULT hr = {host}->{name}({', '.join(call)});",
f' if (FAILED(hr)) bx_xbox_log_host_failure("Xbox{family}", "{name}", hr);',
f" return bx_xbox_wrap_result(hr, a{n - 2}, a{n - 1});"]
elif ret == "HRESULT":
lines += [f" HRESULT hr = {host}->{name}({', '.join(call)});",
f' if (FAILED(hr)) bx_xbox_log_host_failure("Xbox{family}", "{name}", hr);',
" return hr;"]
else:
lines.append(f" return {host}->{name}({', '.join(call)});")
return lines + ["}"]
def find_count(params, index, name=""):
# The element count is the nearest UINT parameter, before the array or (as in
# SetEventOnMultipleFenceCompletion) after it.
for j in list(range(index - 1, -1, -1)) + list(range(index + 1, len(params))):
if canon(params[j][0]) in ("UINT", "UINT32"):
return f"a{j}"
sys.exit(f"no element count before array parameter {index} of {name}: {params}")
def failure_value(ret):
return {"HRESULT": "E_OUTOFMEMORY", "void": ""}.get(ret, "{}")
STRUCT_TYPES = set() # filled from the Xbox header's `typedef struct` names
def emit_stub(family, slot, name, xret, reason):
stub = f'BX_VTABLE_STUB_LOG("Xbox{family}", {slot}u, "{name}");'
if xret == "HRESULT":
return [f"/* {reason} */",
f"static HRESULT STDMETHODCALLTYPE x_{family}_{slot}(void*) {{ {stub} return E_NOTIMPL; }}"]
if xret in STRUCT_TYPES:
# A struct returned by value comes back through a hidden pointer passed first; it is
# handed back unfilled (the stub log says so). Structs of 8 bytes or less are returned in
# RAX instead; none of the stubbed slots returns one today.
return [f"/* {reason}; returns struct {xret} */",
f"static void* STDMETHODCALLTYPE x_{family}_{slot}(void* result, void*) {{ {stub} return result; }}"]
# Integers, enums, BOOL and pointers come back zero; a void slot ignores the value.
return [f"/* {reason} */",
f"static UINT64 STDMETHODCALLTYPE x_{family}_{slot}(void*) {{ {stub} return 0; }}"]
def guid_literal(parts):
g = [p.lower() for p in parts]
return (f"{{0x{g[0]}, 0x{g[1]}, 0x{g[2]}, "
f"{{0x{g[3]}, 0x{g[4]}, 0x{g[5]}, 0x{g[6]}, 0x{g[7]}, 0x{g[8]}, 0x{g[9]}, 0x{g[10]}}}}}")
def chain(bases, leaf):
out, cur = [], leaf
while cur in bases:
out.append(cur)
cur = bases[cur]
return out + [cur]
def main():
if len(sys.argv) < 2:
sys.exit(__doc__)
xtext = Path(sys.argv[1]).read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n") # parts of the header use CRLF
pc_header = sys.argv[2] if len(sys.argv) > 2 else gen_proxy.find_header()
interfaces = gen_proxy.parse_interfaces(Path(pc_header).read_text(encoding="utf-8", errors="replace"))
iids, bases, tables = parse_xbox(xtext)
STRUCT_TYPES.update(re.findall(r"typedef\s+struct\s+(\w+)", xtext))
STRUCT_TYPES.update(t for t in re.findall(r"^struct\s+(\w+)\s*$", xtext, re.M))
note = ("// Generated by shims/d3d12_xs/tools/gen_xbox_tables.py from the Xbox Series D3D12 header (slot\n"
"// order, names and types only) and the toolchain's <d3d12.h>. Do not edit by hand.")
h = [note, "#ifndef BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H",
"#define BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H", "", '#include "xbox_facade.h"', ""]
c = [note, '#include "xbox_tables_generated.h"', "", "namespace {", ""]
summary = []
for leaf, (pc_leaf, family) in FAMILIES.items():
slots = flatten(tables, table_name(leaf))
if not slots:
sys.exit(f"no Xbox function table for {leaf}")
pc = pc_methods(interfaces, pc_leaf)
counts = {"forward": 0, "shared": 0, "stub": 0}
names = []
for slot, (name, xret, xparams) in enumerate(slots):
if name in SHARED or name in CUSTOM.get(family, {}):
fn = SHARED.get(name) or CUSTOM[family][name]
names.append(f"reinterpret_cast<const void*>(&{fn})")
counts["shared"] += 1
continue
kind = classify(xret, xparams, pc[name]) if name in pc else None
if kind:
c += emit_forward(family, slot, name, pc[name], kind[1])
counts["forward"] += 1
else:
reason = "signature differs from the PC method" if name in pc else "Xbox-only method"
c += emit_stub(family, slot, name, xret, reason)
counts["stub"] += 1
names.append(f"reinterpret_cast<const void*>(&x_{family}_{slot})")
c += ["", f"const void* const k{family}Table[] = {{"] + [f" {n}," for n in names] + ["};", ""]
family_iids = [i for i in chain(bases, leaf) if i in iids and i not in ("IGraphicsUnknown",)]
c += [f"const IID k{family}Iids[] = {{"] + [f" {guid_literal(iids[i])}, /* {i} */" for i in family_iids]
c += ["};", ""]
h.append(f"extern const BxXboxIface bx_xbox_{family};")
summary.append(f"{family}: {len(slots)} slots, {counts}")
c.append(f"/* {leaf}: {len(slots)} slots ({counts['forward']} forwarded, {counts['shared']} shared, "
f"{counts['stub']} stubs); hosted on {pc_leaf}. */")
c += [f"const IID kHost{family} = __uuidof({pc_leaf});", ""]
c += ["} // namespace", ""]
for leaf, (pc_leaf, family) in FAMILIES.items():
size = len(flatten(tables, table_name(leaf)))
c.append(f'extern const BxXboxIface bx_xbox_{family} = {{"{leaf}", k{family}Iids, '
f"sizeof(k{family}Iids) / sizeof(IID), &kHost{family}, k{family}Table, {size}}};")
c += ["", "extern const BxXboxIface* const bx_xbox_ifaces[] = {"]
c += [f" &bx_xbox_{family}," for _, family in FAMILIES.values()] + ["};",
f"extern const size_t bx_xbox_iface_count = {len(FAMILIES)};"]
h += ["", "extern const BxXboxIface* const bx_xbox_ifaces[];", "extern const size_t bx_xbox_iface_count;",
"", "#endif"]
(OUT_DIR / "xbox_tables_generated.h").write_text("\n".join(h) + "\n")
(OUT_DIR / "xbox_tables_generated.cpp").write_text("\n".join(c) + "\n")
print("\n".join(summary))
if __name__ == "__main__":
main()
+412 -151
View File
@@ -5,6 +5,7 @@
#include <cstdio>
#include <cstring>
#include <limits>
#include <new>
/*
@@ -30,11 +31,18 @@
* vkd3d on CrossOver 26.2 faults on that pointer with or without this shim.
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createheap
*
* CreatePlacedResource forwards the caller's parameters to the host.
* On the backing heap the offset must be a multiple of the alignment
* GetResourceAllocationInfo reports, the resource
* must fit, and an upload or readback heap (not this CUSTOM heap) must use the
* initial state Microsoft Learn requires:
* CreatePlacedResource, CreatePlacedResource1 and CreatePlacedResource2 share one
* path (create_placed_common) and check every heap, not only the backing heap,
* before the host call: heap and desc are non-null, a buffer has no clear value,
* the offset is a multiple of the alignment GetResourceAllocationInfo (or
* GetResourceAllocationInfo2 for the DESC1 entry points) reports, and the
* resource fits in the heap. CreatePlacedResource and CreatePlacedResource1 also
* require the initial state Microsoft Learn gives for an upload or readback heap;
* CreatePlacedResource2 takes a barrier layout, which is not checked. A failure
* returns E_INVALIDARG with *out null and is logged. Research register A-7
* recorded the host accepting an invalid placement, so this check is not left
* to the host. A shim heap is unwrapped for the host call and retained by the
* resource on all three paths:
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getresourceallocationinfo
* Heap alignment values 0, 64 KiB and 4 MiB, and ID3D12Heap1:
@@ -52,6 +60,11 @@ constexpr GUID kPlacedResourceHeap = {0x3a652cbb, 0xb5b3, 0x4e09, {0xb3, 0x6c, 0
struct Record {
bool configured = false;
bool xbox_configured = false;
uint32_t xbox_page_table_4mb_pages = 0;
uint32_t xbox_frame_buffer_preserve_bytes = 0;
/* D3D12ConfigureVirtualMemoryX fails with E_FAIL once a device exists. */
bool device_created = false;
bool backing_opt_in = false;
bx_hardware_profile_t profile = BX_PROFILE_LOCKHART;
uint64_t title_limit = 0;
@@ -60,9 +73,10 @@ struct Record {
uint64_t config_size = 0;
uint64_t config_generation = 0;
bx_xmem_region_info_t region{};
/* Bytes of host heaps still alive. D3DMetal keeps freed memory in its own
pool, so this counts live heaps only: charge on create, credit on the
final Release. It does not assume the OS reclaimed the pages. */
/* Diagnostic mirror of the external xmem charges for live host heaps.
D3DMetal keeps freed memory in its own pool, so this counts live heaps
only: charge on create, credit on the final Release. It does not assume
the OS reclaimed the pages. xmem's external_bytes is authoritative. */
uint64_t charged_private_bytes = 0;
uint64_t cpu_pointer = 0;
class BxChargedHeap* backing = nullptr;
@@ -96,44 +110,43 @@ uint64_t title_limit() {
return 8ull << 30;
}
uint64_t active_cap(const bx_xmem_stats_t& stats) {
uint64_t cap = title_limit();
if (stats.title_limit_bytes != 0 && stats.title_limit_bytes < cap) {
cap = stats.title_limit_bytes;
}
return cap;
}
const char* profile_name(bx_hardware_profile_t profile) {
return profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart";
}
/* Private host heaps count against the same Lockhart/Anaconda cap as xmem. */
/* Private host heaps count against the same Lockhart/Anaconda cap as xmem.
* xmem's external_bytes is the authoritative ledger: bx_xmem_try_charge_external
* admits atomically under usage_lock, against every owner, so no local pre-check
* can add anything correct (a snapshot taken outside that lock would also count
* live graphics heaps twice now that xmem's stats include external charges).
* The local mirror is kept only for the gpu_heap_bytes diagnostic log; it cannot
* wrap, because xmem has already admitted `bytes` under a cap <= UINT64_MAX.
* The hook is called while g_section is held (lock order g_section ->
* usage_lock, matching every other path in both DLLs). */
bool try_charge(uint64_t bytes) {
Guard guard(g_section);
bx_xmem_stats_t stats{};
bx_xmem_get_internal_stats(&stats);
const uint64_t cap = active_cap(stats);
const uint64_t xmem_used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
if (bytes > cap || xmem_used > cap || g_record.charged_private_bytes > cap - xmem_used) {
if (!bx_xmem_try_charge_external(bytes)) {
return false;
}
const uint64_t room = cap - xmem_used - g_record.charged_private_bytes;
if (bytes > room) {
return false;
}
g_record.charged_private_bytes += bytes;
g_record.charged_private_bytes += bytes; /* diagnostic mirror */
return true;
}
/* Each heap wrapper calls this exactly once, on its final Release, which is what
* keeps a heap from being released twice. The mirror check below is a coarse
* guard on the total: it refuses a release larger than all outstanding graphics
* charges (refusing leaves a charge in place, so the cap stays strict), but as a
* single total it cannot tell one heap's double release from another heap's
* charge. */
void release_charge(uint64_t bytes) {
Guard guard(g_section);
if (bytes > g_record.charged_private_bytes) {
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "heap_budget", "GPU heap charge underflow on release");
g_record.charged_private_bytes = 0;
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "heap_budget",
"GPU heap charge underflow on release; xmem charge left unchanged");
return;
}
g_record.charged_private_bytes -= bytes;
bx_xmem_release_charge_external(bytes);
}
/*
@@ -557,41 +570,6 @@ HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFI
return hr;
}
bool is_backing_heap(ID3D12Heap* heap) {
if (!heap) {
return false;
}
BxChargedHeap* backing = nullptr;
{
Guard guard(g_section);
backing = g_record.backing;
if (!backing) {
return false;
}
backing->AddRef();
}
IUnknown* want = nullptr;
IUnknown* got = nullptr;
const HRESULT want_hr = backing->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&want));
const HRESULT got_hr = heap->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&got));
const bool same = SUCCEEDED(want_hr) && SUCCEEDED(got_hr) && want == got;
if (want) {
want->Release();
}
if (got) {
got->Release();
}
backing->Release();
return same;
}
void log_placed(UINT64 offset, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "CreatePlacedResource offset=%llu hr=0x%08lx",
static_cast<unsigned long long>(offset), static_cast<unsigned long>(hr));
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail);
}
HRESULT STDMETHODCALLTYPE create_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out) {
BX_D3D_TRACE("ID3D12Device", "CreateHeap");
if (!self || !self->h_ID3D12Device) {
@@ -621,34 +599,97 @@ HRESULT STDMETHODCALLTYPE create_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC
return host_private_heap(self, desc, riid, out, true);
}
HRESULT validate_backing_placement(ID3D12Device* device, ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) {
if (!heap || !desc) {
/* The inputs that differ between CreatePlacedResource, CreatePlacedResource1 and
CreatePlacedResource2. `state` is null for CreatePlacedResource2, which takes a
barrier layout instead of a resource state. */
struct Placement {
const char* method;
ID3D12Heap* heap;
UINT64 offset;
D3D12_RESOURCE_DIMENSION dimension;
const D3D12_CLEAR_VALUE* clear;
const D3D12_RESOURCE_STATES* state;
D3D12_RESOURCE_ALLOCATION_INFO info;
};
/* Runs on every heap: the backing heap, a heap from CreateHeap, or a host heap the
caller passes directly. The heap desc is read from the host heap; BxChargedHeap
forwards GetDesc to the same object. */
HRESULT validate_placement(const Placement& p) {
if (p.dimension == D3D12_RESOURCE_DIMENSION_BUFFER && p.clear) {
return E_INVALIDARG;
}
if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && clear) {
D3D12_HEAP_DESC heap_desc = bx_unwrap(p.heap)->GetDesc();
if (p.state) {
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && *p.state != D3D12_RESOURCE_STATE_GENERIC_READ) {
return E_INVALIDARG;
}
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_READBACK && *p.state != D3D12_RESOURCE_STATE_COPY_DEST) {
return E_INVALIDARG;
}
}
if (p.info.SizeInBytes == 0 || p.info.SizeInBytes == ~0ull) {
return E_INVALIDARG;
}
D3D12_HEAP_DESC heap_desc = heap->GetDesc();
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && state != D3D12_RESOURCE_STATE_GENERIC_READ) {
if (p.info.Alignment != 0 && (p.offset % p.info.Alignment) != 0) {
return E_INVALIDARG;
}
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_READBACK && state != D3D12_RESOURCE_STATE_COPY_DEST) {
return E_INVALIDARG;
}
D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, desc);
if (info.SizeInBytes == 0 || info.SizeInBytes == ~0ull) {
return E_INVALIDARG;
}
if (info.Alignment != 0 && (offset % info.Alignment) != 0) {
return E_INVALIDARG;
}
if (offset > heap_desc.SizeInBytes || info.SizeInBytes > heap_desc.SizeInBytes - offset) {
if (p.offset > heap_desc.SizeInBytes || p.info.SizeInBytes > heap_desc.SizeInBytes - p.offset) {
return E_INVALIDARG;
}
return S_OK;
}
void log_placed(const char* method, UINT64 offset, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s offset=%llu hr=0x%08lx", method, static_cast<unsigned long long>(offset),
static_cast<unsigned long>(hr));
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail);
}
/*
* The one placement path for slots 29, 70 and 77. `p.heap` and `desc` are already
* known non-null; `p.info` comes from the matching GetResourceAllocationInfo call.
* `host_call(host_heap)` performs the host Create call with the unwrapped heap.
*/
template <typename HostCall>
HRESULT create_placed_common(const Placement& p, void** out, HostCall&& host_call) {
const HRESULT check_hr = validate_placement(p);
if (FAILED(check_hr)) {
log_placed(p.method, p.offset, check_hr);
return check_hr;
}
ID3D12Heap* host_heap = bx_unwrap(p.heap);
HRESULT hr = host_call(host_heap);
if (SUCCEEDED(hr) && out && *out && host_heap != p.heap) {
/* The resource owns a reference to the shim heap through its host
object's private data, including across QueryInterface calls. */
auto* created = static_cast<IUnknown*>(*out);
ID3D12Object* object = nullptr;
HRESULT retain_hr = created->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast<void**>(&object));
if (SUCCEEDED(retain_hr)) {
retain_hr = object->SetPrivateDataInterface(kPlacedResourceHeap, p.heap);
object->Release();
}
if (FAILED(retain_hr)) {
created->Release();
*out = nullptr;
hr = retain_hr;
}
}
log_placed(p.method, p.offset, hr);
return hr;
}
/* Null heap or desc never reaches the host. */
HRESULT reject_null_placement(const char* method, ID3D12Heap* heap, const void* desc, UINT64 offset) {
if (heap && desc) {
return S_OK;
}
log_placed(method, offset, E_INVALIDARG);
return E_INVALIDARG;
}
HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, UINT64 offset,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
@@ -663,83 +704,188 @@ HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, U
if (out) {
*out = nullptr;
}
if (is_backing_heap(heap)) {
const HRESULT check_hr = validate_backing_placement(self->h_ID3D12Device, heap, offset, desc, state, clear);
if (FAILED(check_hr)) {
log_placed(offset, check_hr);
return check_hr;
}
const char* method = "CreatePlacedResource";
const HRESULT null_hr = reject_null_placement(method, heap, desc, offset);
if (FAILED(null_hr)) {
return null_hr;
}
ID3D12Heap* host_heap = bx_unwrap(heap);
HRESULT hr = self->h_ID3D12Device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out);
if (SUCCEEDED(hr) && out && *out && host_heap != heap) {
/* The resource owns a reference to the shim heap through its host
object's private data, including across QueryInterface calls. */
auto* created = static_cast<IUnknown*>(*out);
ID3D12Object* object = nullptr;
HRESULT retain_hr = created->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast<void**>(&object));
if (SUCCEEDED(retain_hr)) {
retain_hr = object->SetPrivateDataInterface(kPlacedResourceHeap, heap);
object->Release();
}
if (FAILED(retain_hr)) {
created->Release();
*out = nullptr;
hr = retain_hr;
}
}
log_placed(offset, hr);
return hr;
ID3D12Device* device = self->h_ID3D12Device;
const Placement p{method, heap, offset, desc->Dimension, clear, &state, device->GetResourceAllocationInfo(0, 1, desc)};
return create_placed_common(p, out, [&](ID3D12Heap* host_heap) {
return device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out);
});
}
} // namespace
HRESULT bx_vmem_create_placed_resource1(ID3D12Device8* host, ID3D12Heap* heap, UINT64 offset,
const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
if (out) {
*out = nullptr;
}
const char* method = "CreatePlacedResource1";
const HRESULT null_hr = reject_null_placement(method, heap, desc, offset);
if (FAILED(null_hr)) {
return null_hr;
}
const Placement p{method, heap, offset, desc->Dimension, clear, &state,
host->GetResourceAllocationInfo2(0, 1, desc, nullptr)};
return create_placed_common(p, out, [&](ID3D12Heap* host_heap) {
return host->CreatePlacedResource1(host_heap, offset, desc, state, clear, riid, out);
});
}
/* The initial barrier layout is not checked against the heap type: only the
resource-state rule for UPLOAD and READBACK heaps is applied, on the other two
entry points. Allocation info comes from GetResourceAllocationInfo2, which
does not take the castable-format list (GetResourceAllocationInfo3 is on
ID3D12Device12, past this proxy's ID3D12Device10). */
HRESULT bx_vmem_create_placed_resource2(ID3D12Device10* host, ID3D12Heap* heap, UINT64 offset,
const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout,
const D3D12_CLEAR_VALUE* clear, UINT32 num_castable, DXGI_FORMAT* castable,
REFIID riid, void** out) {
if (out) {
*out = nullptr;
}
const char* method = "CreatePlacedResource2";
const HRESULT null_hr = reject_null_placement(method, heap, desc, offset);
if (FAILED(null_hr)) {
return null_hr;
}
const Placement p{method, heap, offset, desc->Dimension, clear, nullptr,
host->GetResourceAllocationInfo2(0, 1, desc, nullptr)};
return create_placed_common(p, out, [&](ID3D12Heap* host_heap) {
return host->CreatePlacedResource2(host_heap, offset, desc, layout, clear, num_castable, castable, riid, out);
});
}
namespace {
struct ConfigHeader {
uint32_t magic;
uint32_t struct_size;
};
static_assert(sizeof(ConfigHeader) == 8, "config probe is the 8-byte header");
void write_cpu_pointer(void* config, uint64_t pointer) {
std::memcpy(static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer), &pointer, sizeof(pointer));
bool is_accessible_protect(DWORD protect, bool write) {
if ((protect & (PAGE_GUARD | PAGE_NOACCESS)) != 0) {
return false;
}
switch (protect & 0xFFu) {
case PAGE_READWRITE:
case PAGE_WRITECOPY:
case PAGE_EXECUTE_READWRITE:
case PAGE_EXECUTE_WRITECOPY:
return true;
case PAGE_READONLY:
case PAGE_EXECUTE_READ:
return !write;
default:
return false;
}
}
} // namespace
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
if (!config) {
/* Titles call this before reserving memory and require S_OK. */
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
bool can_access_bytes(const void* ptr, size_t len, bool write) {
if (!ptr || len == 0) {
return false;
}
/*
* PVOID has no size. Read 8 bytes, and only then the rest of a block that
* names this struct. A mismatch is left untouched.
*/
ConfigHeader header{};
std::memcpy(&header, config, sizeof(header));
if (header.magic != BX_D3D12_VMEM_MAGIC || header.struct_size != sizeof(BxD3d12VirtualMemoryConfig)) {
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
if (start > std::numeric_limits<uintptr_t>::max() - len) {
return false;
}
const uintptr_t end = start + len;
uintptr_t cursor = start;
while (cursor < end) {
MEMORY_BASIC_INFORMATION mbi{};
if (VirtualQuery(reinterpret_cast<LPCVOID>(cursor), &mbi, sizeof(mbi)) == 0) {
return false;
}
if (mbi.State != MEM_COMMIT || !is_accessible_protect(mbi.Protect, write) || mbi.RegionSize == 0) {
return false;
}
const uintptr_t region_base = reinterpret_cast<uintptr_t>(mbi.BaseAddress);
if (region_base > cursor || mbi.RegionSize > std::numeric_limits<uintptr_t>::max() - region_base) {
return false;
}
const uintptr_t region_end = region_base + mbi.RegionSize;
if (region_end <= cursor) {
return false;
}
cursor = region_end;
}
return true;
}
bool copy_readable_bytes(const void* source, void* destination, size_t len) {
if (!destination || !can_access_bytes(source, len, false)) {
return false;
}
SIZE_T bytes_read = 0;
return ReadProcessMemory(GetCurrentProcess(), source, destination, len, &bytes_read) != 0 && bytes_read == len;
}
bool write_cpu_pointer(void* config, uint64_t pointer) {
auto* destination = static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer);
if (!can_access_bytes(destination, sizeof(pointer), true)) {
return false;
}
SIZE_T bytes_written = 0;
return WriteProcessMemory(GetCurrentProcess(), destination, &pointer, sizeof(pointer), &bytes_written) != 0 &&
bytes_written == sizeof(pointer);
}
/* Writes `len` bytes at `offset` in caller memory, after checking the range is writable. */
bool write_config_bytes(void* config, size_t offset, const void* source, size_t len) {
auto* destination = static_cast<char*>(config) + offset;
if (!can_access_bytes(destination, len, true)) {
return false;
}
SIZE_T bytes_written = 0;
return WriteProcessMemory(GetCurrentProcess(), destination, source, len, &bytes_written) != 0 &&
bytes_written == len;
}
void log_vmem_fallback(const char* decoder, const char* reason) {
char detail[160];
std::snprintf(detail, sizeof(detail), "decoder=%s applied=0 reason=%s", decoder, reason);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_fallback", detail);
}
void log_vmem_failed(const char* decoder, const char* reason, HRESULT hr) {
char detail[192];
std::snprintf(detail, sizeof(detail), "decoder=%s applied=0 reason=%s hr=0x%08lx", decoder, reason,
static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_failed", detail);
}
HRESULT decode_bxvm_config(void* config) {
BxD3d12VirtualMemoryConfig in{};
std::memcpy(&in, config, sizeof(in));
if (!copy_readable_bytes(config, &in, sizeof(in))) {
log_vmem_fallback("bxvm", "unreadable_tail");
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
}
const uint32_t unknown_flags = in.flags & ~BX_D3D12_VMEM_FLAG_BACKING_HEAP;
if (in.version != kConfigVersion || unknown_flags != 0 || in.reserved != 0) {
/* A console parameter block is not this struct. Leave those bytes alone. */
log_vmem_fallback("bxvm", "unsupported_options");
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
}
const bx_runtime_config_t* cfg = bx_get_runtime_config();
const uint64_t cap = title_limit();
const auto profile = (cfg && cfg->profile == BX_PROFILE_ANACONDA) ? BX_PROFILE_ANACONDA : BX_PROFILE_LOCKHART;
if (in.size_bytes != 0 && (in.size_bytes % k64K != 0 || in.size_bytes > cap)) {
log_vmem_failed("bxvm", "invalid_size", E_INVALIDARG);
return E_INVALIDARG;
}
bx_xmem_stats_t stats{};
bx_xmem_get_internal_stats(&stats);
if (in.size_bytes != 0 && stats.title_limit_bytes != 0 && in.size_bytes > stats.title_limit_bytes) {
log_vmem_failed("bxvm", "exceeds_xmem_limit", E_INVALIDARG);
return E_INVALIDARG;
}
@@ -749,16 +895,19 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
bx_xmem_region_info_t first{};
if (!bx_xmem_query_region(in.base_va, &first) || first.size_bytes == 0 || first.base_va != in.base_va ||
first.base_va % k64K != 0 || first.size_bytes % k64K != 0) {
log_vmem_failed("bxvm", "unknown_xmem_region", E_INVALIDARG);
return E_INVALIDARG;
}
const uint64_t span = in.size_bytes != 0 ? in.size_bytes : first.size_bytes;
if (span < first.size_bytes || span % first.size_bytes != 0) {
log_vmem_failed("bxvm", "unaligned_region_span", E_INVALIDARG);
return E_INVALIDARG;
}
for (uint64_t offset = 0; offset < span; offset += first.size_bytes) {
bx_xmem_region_info_t page{};
if (!bx_xmem_query_region(first.base_va + offset, &page) || page.base_va != first.base_va + offset ||
page.size_bytes != first.size_bytes) {
log_vmem_failed("bxvm", "discontiguous_xmem_region", E_INVALIDARG);
return E_INVALIDARG;
}
}
@@ -767,49 +916,60 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
have_region = true;
}
if (!can_access_bytes(static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer),
sizeof(in.cpu_pointer), true)) {
log_vmem_fallback("bxvm", "unwritable_output");
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
}
const uint64_t new_base = have_region ? region.base_va : in.base_va;
const uint64_t new_size = have_region ? region.size_bytes : in.size_bytes;
const bool backing_opt_in = (in.flags & BX_D3D12_VMEM_FLAG_BACKING_HEAP) != 0;
BxChargedHeap* old_heap = nullptr;
ID3D12Resource* old_buffer = nullptr;
uint64_t published = 0;
bool output_written = false;
{
Guard guard(g_section);
const bool same = g_record.configured && g_record.config_base == new_base && g_record.config_size == new_size;
if (!same) {
take_cached_heap_locked(&old_heap, &old_buffer);
published = same ? g_record.cpu_pointer : 0;
output_written = write_cpu_pointer(config, published);
if (output_written) {
if (!same) {
take_cached_heap_locked(&old_heap, &old_buffer);
}
if (!same || g_record.backing_opt_in != backing_opt_in || g_record.have_region != have_region) {
++g_record.config_generation;
}
g_record.configured = true;
g_record.backing_opt_in = backing_opt_in;
g_record.profile = profile;
g_record.title_limit = cap;
g_record.have_region = have_region;
g_record.config_base = new_base;
g_record.config_size = new_size;
g_record.region = have_region ? region : bx_xmem_region_info_t{};
}
if (!same || g_record.backing_opt_in != backing_opt_in || g_record.have_region != have_region) {
++g_record.config_generation;
}
g_record.configured = true;
g_record.backing_opt_in = backing_opt_in;
g_record.profile = profile;
g_record.title_limit = cap;
g_record.have_region = have_region;
g_record.config_base = new_base;
g_record.config_size = new_size;
g_record.region = have_region ? region : bx_xmem_region_info_t{};
published = g_record.cpu_pointer;
}
/* The only write to caller memory, and it happens before this call returns. */
write_cpu_pointer(config, published);
if (old_buffer) {
old_buffer->Unmap(0, nullptr);
old_buffer->Release();
}
if (old_heap) {
old_heap->Release();
if (!output_written) {
log_vmem_failed("bxvm", "unwritable_output", E_INVALIDARG);
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return E_INVALIDARG;
}
release_backing_pair(old_heap, old_buffer);
uint64_t charged = 0;
{
Guard guard(g_section);
charged = g_record.charged_private_bytes;
}
char detail[384];
char detail[416];
std::snprintf(detail, sizeof(detail),
"profile=%s title_limit=%llu xmem_used=%llu xmem_region=%d base=0x%llx region_bytes=%llu gpu_heap_bytes=%llu",
/* cap_used is everything counted against the title cap, graphics heaps
* included (xmem's stats include external charges); gpu_heap_bytes is the
* graphics part of it, so the two must not be added. */
"decoder=bxvm applied=1 profile=%s title_limit=%llu cap_used=%llu xmem_region=%d base=0x%llx region_bytes=%llu gpu_heap_bytes=%llu",
profile_name(profile), static_cast<unsigned long long>(cap),
static_cast<unsigned long long>(stats.committed_virtual_bytes + stats.allocated_physical_bytes),
have_region ? 1 : 0, static_cast<unsigned long long>(have_region ? region.base_va : 0),
@@ -819,6 +979,105 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
return S_OK;
}
HRESULT decode_xbox_config(void* config) {
/* The structure has no size field, so all 32 bytes must be readable and writable. */
BxXboxVirtualMemoryConfig in{};
if (!copy_readable_bytes(config, &in, sizeof(in))) {
log_vmem_failed("xbox", "unreadable_config", E_INVALIDARG);
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return E_INVALIDARG;
}
if (in.page_table_memory_4mb_page_count == 0u) {
log_vmem_failed("xbox", "zero_page_table_pages", E_INVALIDARG);
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return E_INVALIDARG;
}
{
Guard guard(g_section);
if (g_record.device_created) {
log_vmem_failed("xbox", "device_already_created", E_FAIL);
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return E_FAIL;
}
}
const bool clamped = in.page_table_memory_4mb_page_count > BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES;
const uint32_t pages = clamped ? BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES : in.page_table_memory_4mb_page_count;
uint32_t preserve = in.frame_buffer_preserve_memory_size_bytes;
if (preserve != BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY &&
preserve > BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES) {
preserve = BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES;
}
const uint64_t outputs[2] = {BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS,
static_cast<uint64_t>(pages) * BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE};
if (!write_config_bytes(config, offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address), outputs,
sizeof(outputs))) {
log_vmem_failed("xbox", "unwritable_output", E_INVALIDARG);
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return E_INVALIDARG;
}
/*
* The host sizes no GPU page tables and keeps no cross-process frame buffer, so both
* values are only recorded. This path leaves the BXVM record and its cached backing heap
* untouched, reports applied=0 and keeps BX_STUB_LOG, so `bx-cli trace` still lists
* D3D12ConfigureVirtualMemoryX as unimplemented.
*/
bool repeat = false;
{
Guard guard(g_section);
repeat = g_record.xbox_configured && g_record.xbox_page_table_4mb_pages == pages &&
g_record.xbox_frame_buffer_preserve_bytes == preserve;
g_record.xbox_configured = true;
g_record.xbox_page_table_4mb_pages = pages;
g_record.xbox_frame_buffer_preserve_bytes = preserve;
}
char detail[320];
std::snprintf(detail, sizeof(detail),
"decoder=xbox applied=0 recorded_only=1 page_table_4mb_pages=%u clamped=%d "
"frame_buffer_preserve_bytes=%u min_gpu_va=0x%llx max_gpu_va=0x%llx max_estimated=%d "
"repeat=%d reason=host_ignores_page_table_size",
pages, clamped ? 1 : 0, preserve, static_cast<unsigned long long>(outputs[0]),
static_cast<unsigned long long>(outputs[1]),
pages == BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES ? 0 : 1, repeat ? 1 : 0);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_recorded", detail);
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
}
} // namespace
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
if (!config) {
/* Titles call this before reserving memory and require S_OK. */
log_vmem_fallback("none", "null_config");
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
}
/*
* PVOID has no size. Verify 8 bytes are committed and readable before
* probing the header, and let each decoder verify its own full length.
*/
ConfigHeader header{};
if (!copy_readable_bytes(config, &header, sizeof(header))) {
log_vmem_fallback("none", "unreadable_header");
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
}
if (header.magic == BX_D3D12_VMEM_MAGIC && header.struct_size == sizeof(BxD3d12VirtualMemoryConfig)) {
return decode_bxvm_config(config);
}
if (header.magic == 0u) {
return decode_xbox_config(config);
}
log_vmem_fallback("none", "unrecognized_header");
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
}
bool bx_vmem_final_release(void* device_proxy) {
Guard guard(g_section);
auto* proxy = static_cast<BxDeviceProxy*>(device_proxy);
@@ -856,6 +1115,7 @@ bool bx_vmem_install_device_hooks(void* device) {
static bool installed = false;
Guard guard(g_section);
if (installed) {
g_record.device_created = true;
return true;
}
auto* proxy = static_cast<BxDeviceProxy*>(device);
@@ -871,6 +1131,7 @@ bool bx_vmem_install_device_hooks(void* device) {
DWORD ignored = 0;
VirtualProtect(vtable + 28, sizeof(void*) * 2, old, &ignored);
installed = true;
g_record.device_created = true;
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "vmem_hook", "CreateHeap and CreatePlacedResource installed");
return true;
}
+62 -11
View File
@@ -9,17 +9,20 @@
* BetterXen-defined parameter block for D3D12ConfigureVirtualMemoryX.
*
* The export is PVOID and the frozen ABI has no size argument (abi/ is out of
* scope). The first 8 bytes are therefore the minimum dereference: magic then
* the struct size. Magic is 'BXVM' (0x4D565842). struct_size must equal
* sizeof(BxD3d12VirtualMemoryConfig). Any other pointer, including null, is not
* this struct: the call logs the unimplemented-API stub and returns S_OK. It
* does not read past those 8 bytes and it does not write.
* scope). The first 8 bytes are therefore the initial probe: a magic word and
* the following 32-bit value. Magic is 'BXVM' (0x4D565842); a matching header
* and struct size select the full BetterXen block. A zero first word selects
* the Xbox decoder, which checks the full block and may write its two address
* outputs. Other headers (including unrecognized nonzero Xbox flags) fall
* back with S_OK and no writes. A null pointer is not read.
*
* A block whose magic and size match is then checked in full. version is 1.
* flags may be 0 or BX_D3D12_VMEM_FLAG_BACKING_HEAP. Any other flag bit, or a
* non-zero reserved word, is not this struct either (logged S_OK, no write).
* A recognised block with a bad size or a base_va that bx_xmem_query_region
* does not resolve still returns E_INVALIDARG and is not written.
* does not resolve returns E_INVALIDARG even if its output is read-only. Valid
* inputs with an initially unwritable output fall back with S_OK and a stub
* log. A failed write after the accessibility check returns E_INVALIDARG.
*
* base_va is 0, or an address bx_xmem_query_region resolves. It is not a GPU pointer.
* size_bytes is 0 or a 64 KiB multiple that does not exceed the active title limit.
@@ -47,16 +50,17 @@
* returns HRESULT_FROM_WIN32(ERROR_RETRY) and discards any newly allocated heap.
* Any other CreateHeap is the host CreateHeap. The desc is not modified.
* The live-heap budget charge is taken on create and dropped on the wrapper's
* final Release. A resource created by CreatePlacedResource holds the wrapper
* for its lifetime.
* final Release. A resource created by CreatePlacedResource,
* CreatePlacedResource1 or CreatePlacedResource2 holds the wrapper for its
* lifetime, and all three validate the placement on every heap first.
* GetDevice on every wrapper returns the BxDeviceProxy. An ordinary heap AddRefs
* that proxy until the wrapper's final Release, matching BxChildProxy, so the
* caller can release the device and keep the heap. The process-wide backing heap
* does not AddRef. The cache would keep the device and its charge alive. That
* pointer is weak. It is cleared when the heap leaves the cache (a new region
* or a different host device) and when that proxy's last reference drops.
* CreatePlacedResource1 and CreatePlacedResource2 unwrap the wrapper to the
* host heap before the host call. The cache records the host ID3D12Device
* All three placement methods unwrap the wrapper to the host heap before the
* host call. The cache records the host ID3D12Device
* that built the heap. CreateHeap for a different host device releases the
* heap and its buffer, credits the charge, and builds a new one. CreateHeap
* for the same host device returns the cached heap. The check, the retarget,
@@ -87,9 +91,56 @@ static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_byte
static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 32, "reserved offset");
static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_pointer offset");
/*
* The Xbox virtual-memory configuration (D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION, d3d12_xs.h).
*
* Source: the authorized GDK documentation of D3D12ConfigureVirtualMemoryX and the
* structure. Call-site observation of a project-authorized target build agrees with it: a
* zero-initialized block with 3 or 4 in the page-table field and no flags.
*
* Documented: flags must be none (0); the GPU page table is sized in 4 MB units, at least 1
* and clamped to 33 (default 5, 20 MB); the frame-buffer preserve size is 0 (none), -1 (the
* legacy size, about 10 MB) or a byte count clamped to 64 MB; the two addresses are outputs,
* the minimum always 2 GB; and the call fails with E_FAIL once a D3D12 device exists.
*
* The host does not size GPU page tables or keep a cross-process frame buffer, so the
* decoder records both, writes the outputs and still logs BX_STUB_LOG. The maximum address
* is documented only for the default size; for other sizes it is scaled linearly from that
* value, an inference the log marks as max_estimated=1. A page count of 0 is refused: the
* value of the header's DEFAULT constant is not documented.
*/
struct BxXboxVirtualMemoryConfig {
uint32_t flags;
uint32_t page_table_memory_4mb_page_count;
uint32_t frame_buffer_preserve_memory_size_bytes;
uint32_t padding;
uint64_t minimum_valid_graphics_address;
uint64_t maximum_valid_graphics_address;
};
static_assert(sizeof(BxXboxVirtualMemoryConfig) == 32, "Xbox config block is 32 bytes");
static_assert(offsetof(BxXboxVirtualMemoryConfig, flags) == 0, "flags offset");
static_assert(offsetof(BxXboxVirtualMemoryConfig, page_table_memory_4mb_page_count) == 4,
"page_table_memory_4mb_page_count offset");
static_assert(offsetof(BxXboxVirtualMemoryConfig, frame_buffer_preserve_memory_size_bytes) == 8,
"frame_buffer_preserve_memory_size_bytes offset");
static_assert(offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address) == 16,
"minimum_valid_graphics_address offset");
static_assert(offsetof(BxXboxVirtualMemoryConfig, maximum_valid_graphics_address) == 24,
"maximum_valid_graphics_address offset");
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES = 5u;
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES = 33u;
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY = 0xFFFFFFFFu;
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES = 64u * 1024u * 1024u;
constexpr uint64_t BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS = 2ull * 1024ull * 1024ull * 1024ull;
/* 159.375 GiB at the default 5 pages (20 MB), so 31.875 GiB per 4 MB page. */
constexpr uint64_t BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE = 0x7F8000000ull;
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config);
/* Patches the device proxy vtable so CreateHeap and CreatePlacedResource run the code in vmem.cpp. */
/* Patches the device proxy vtable so CreateHeap and CreatePlacedResource run the code in vmem.cpp.
CreatePlacedResource1 and CreatePlacedResource2 reach the same placement code through the
generated proxy (gen_proxy.py HANDOFF), not through a vtable patch. */
bool bx_vmem_install_device_hooks(void* device);
/* 1->0 Release of a device proxy, under g_section. Compare-exchanges the count from
+316
View File
@@ -0,0 +1,316 @@
#include "xbox_facade.h"
#include <cstdio>
#include <cstring>
#include <mutex>
/*
* ADR 0009: Xbox-layout objects over the PC proxies. See xbox_facade.h for the layout and
* xbox_tables_generated.cpp (tools/gen_xbox_tables.py) for the slot order.
*/
namespace {
constexpr uint8_t kOutOfLineCommon = 0x1; // Xbox OutOfLineFlags_Common
struct Entry {
IUnknown* host;
const BxXboxIface* iface;
BxXboxObject* object;
};
std::mutex g_lock;
Entry* g_entries = nullptr;
size_t g_count = 0;
size_t g_capacity = 0;
bool same_iid(REFIID a, REFIID b) {
return std::memcmp(&a, &b, sizeof(IID)) == 0;
}
bool answers(const BxXboxIface* iface, REFIID riid) {
for (size_t i = 0; i < iface->iid_count; ++i) {
if (same_iid(iface->iids[i], riid)) return true;
}
return false;
}
const BxXboxIface* iface_of_object(const void* p) {
if (!p) return nullptr;
const void* table = *static_cast<const void* const*>(p);
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
if (bx_xbox_ifaces[i]->table == table) return bx_xbox_ifaces[i];
}
return nullptr;
}
void log_iid(const char* event, const char* what, REFIID riid, bx_log_level_t level = BX_LOG_WARN) {
char guid[40];
bx_format_guid(riid, guid, sizeof(guid));
char detail[160];
std::snprintf(detail, sizeof(detail), "%s iid=%s", what, guid);
bx_log_emit(level, "d3d12_xs", event, detail);
}
BxXboxObject* find_locked(IUnknown* host, const BxXboxIface* iface) {
for (size_t i = 0; i < g_count; ++i) {
if (g_entries[i].host == host && g_entries[i].iface == iface) return g_entries[i].object;
}
return nullptr;
}
bool insert_locked(Entry entry) {
if (g_count == g_capacity) {
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
auto* grown = new (std::nothrow) Entry[capacity];
if (!grown) return false;
if (g_count) std::memcpy(grown, g_entries, g_count * sizeof(Entry));
delete[] g_entries;
g_entries = grown;
g_capacity = capacity;
}
g_entries[g_count++] = entry;
return true;
}
void erase_locked(BxXboxObject* object) {
for (size_t i = 0; i < g_count; ++i) {
if (g_entries[i].object == object) {
g_entries[i] = g_entries[--g_count];
return;
}
}
}
} // namespace
const BxXboxIface* bx_xbox_iface_for(REFIID riid) {
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
if (answers(bx_xbox_ifaces[i], riid)) return bx_xbox_ifaces[i];
}
return nullptr;
}
void* bx_xbox_wrap(REFIID riid, void* raw, HRESULT* failure) {
if (failure) *failure = E_OUTOFMEMORY;
if (!raw) return nullptr;
auto* unknown = static_cast<IUnknown*>(raw);
const BxXboxIface* iface = bx_xbox_iface_for(riid);
if (!iface) {
log_iid("xbox_unwrapped", "no Xbox table answers this interface; returning the PC object", riid);
return raw;
}
void* typed = nullptr;
if (FAILED(unknown->QueryInterface(*iface->host_iid, &typed)) || !typed) {
// The Xbox table forwards to an interface this host object lacks. Handing back the PC
// object would let a title call Xbox slot numbers on a PC table, so this fails instead.
log_iid("xbox_wrap_refused", iface->name, *iface->host_iid, BX_LOG_ERROR);
unknown->Release();
if (failure) *failure = E_NOINTERFACE;
return nullptr;
}
unknown->Release();
auto* host = static_cast<IUnknown*>(typed);
std::lock_guard<std::mutex> guard(g_lock);
if (BxXboxObject* existing = find_locked(host, iface)) {
ULONG refs = existing->refs.load();
while (refs != 0 && !existing->refs.compare_exchange_weak(refs, refs + 1)) {
}
if (refs != 0) {
existing->xbox_ref_count = refs + 1;
host->Release();
return existing;
}
}
auto* object = new (std::nothrow) BxXboxObject{};
if (!object) {
host->Release();
return nullptr;
}
object->function_table = iface->table;
object->xbox_ref_count = 1;
if (iface == &bx_xbox_Device) {
object->xbox_fields[kBxXboxDeviceOutOfLineOffset - offsetof(BxXboxObject, xbox_fields)] = kOutOfLineCommon;
}
object->host = host;
object->iface = iface;
object->refs.store(1);
if (!insert_locked({host, iface, object})) {
host->Release();
delete object;
return nullptr;
}
return object;
}
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv) {
if (SUCCEEDED(hr) && ppv && *ppv) {
HRESULT failure = E_OUTOFMEMORY;
void* wrapped = bx_xbox_wrap(riid, *ppv, &failure);
if (!wrapped) {
*ppv = nullptr;
return failure;
}
*ppv = wrapped;
}
return hr;
}
IUnknown* bx_xbox_unwrap(const void* p) {
if (iface_of_object(p)) return static_cast<const BxXboxObject*>(p)->host;
return static_cast<IUnknown*>(const_cast<void*>(p));
}
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s::%s hr=0x%08lx", iface, method, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "host_call_failed", detail);
}
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv) {
auto* object = static_cast<BxXboxObject*>(self);
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (same_iid(riid, IID_BxProxyHost)) {
*ppv = object->host; // by contract, no reference (see bx_unwrap_raw)
return S_OK;
}
if (same_iid(riid, __uuidof(IUnknown)) || answers(object->iface, riid)) {
bx_xbox_add_ref(self);
*ppv = self;
return S_OK;
}
void* raw = nullptr;
HRESULT hr = object->host->QueryInterface(riid, &raw);
if (FAILED(hr) || !raw) return hr;
if (bx_xbox_iface_for(riid)) {
HRESULT failure = E_OUTOFMEMORY;
*ppv = bx_xbox_wrap(riid, raw, &failure);
return *ppv ? S_OK : failure;
}
log_iid("xbox_qi_unwrapped", object->iface->name, riid);
*ppv = raw;
return S_OK;
}
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self) {
auto* object = static_cast<BxXboxObject*>(self);
const ULONG refs = object->refs.fetch_add(1) + 1;
object->xbox_ref_count = refs;
return refs;
}
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self) {
auto* object = static_cast<BxXboxObject*>(self);
std::unique_lock<std::mutex> guard(g_lock);
const ULONG refs = object->refs.fetch_sub(1) - 1;
object->xbox_ref_count = refs;
if (refs != 0) return refs;
erase_locked(object);
guard.unlock();
if (object->iface == &bx_xbox_Resource) bx_xbox_placed_forget(object->host);
if (object->iface == &bx_xbox_DescriptorHeap) bx_xbox_descriptor_heap_forget(object->host);
if (object->iface == &bx_xbox_Fence) bx_xbox_fence_forget(object->host);
if (object->iface == &bx_xbox_PipelineState) bx_xbox_pipeline_forget(object->host);
if (object->iface == &bx_xbox_GraphicsCommandList) {
bx_xbox_list_forget(object->host);
bx_xbox_gpu_writes_reset(object->host);
}
object->host->Release();
delete object;
return 0;
}
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv) {
if (!ppv) return;
*ppv = nullptr;
auto* child = bx_xbox_host<ID3D12DeviceChild>(self);
void* device = nullptr;
if (SUCCEEDED(child->GetDevice(riid, &device)) && device) *ppv = bx_xbox_wrap(riid, device);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommandQueueX");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
D3D12_COMMAND_QUEUE_DESC pc{};
pc.Type = desc->Type;
pc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
pc.Flags = desc->Flags;
char detail[160];
std::snprintf(detail, sizeof(detail), "type=%d flags=0x%x engine_or_pipe=%u queue=%u (indices not used by the host)",
static_cast<int>(desc->Type), static_cast<unsigned>(desc->Flags), desc->EngineOrPipeIndex,
desc->QueueIndex);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandQueueX", detail);
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandQueue(&pc, riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
ID3D12CommandAllocator* allocator,
ID3D12PipelineState* initial_state, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommandListX");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
char detail[160];
std::snprintf(detail, sizeof(detail), "type=%d xbox_flags=0x%x node_mask=0x%x barrier_batch=%u (flags and batch not used by the host)",
static_cast<int>(desc->Type), desc->Flags, desc->NodeMask, desc->ResourceBarrierBatchSize);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandListX", detail);
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandList(
desc->NodeMask, desc->Type, bx_xbox_unwrap_as(allocator),
bx_xbox_pipeline_is_null(initial_state) ? nullptr : bx_xbox_unwrap_as(initial_state), riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateCommandListX", hr);
return bx_xbox_wrap_result(hr, riid, ppv);
}
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ResourceBarrier");
if (!barriers || count == 0) return 0;
constexpr UINT kInline = 32;
D3D12_RESOURCE_BARRIER inline_copy[kInline];
D3D12_RESOURCE_BARRIER* copy = count <= kInline ? inline_copy : new (std::nothrow) D3D12_RESOURCE_BARRIER[count];
if (!copy) return 0;
for (UINT i = 0; i < count; ++i) {
copy[i] = barriers[i];
switch (copy[i].Type) {
case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION:
copy[i].Transition.pResource = bx_xbox_unwrap_as(copy[i].Transition.pResource);
break;
case D3D12_RESOURCE_BARRIER_TYPE_ALIASING:
copy[i].Aliasing.pResourceBefore = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceBefore);
copy[i].Aliasing.pResourceAfter = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceAfter);
break;
case D3D12_RESOURCE_BARRIER_TYPE_UAV:
copy[i].UAV.pResource = bx_xbox_unwrap_as(copy[i].UAV.pResource);
break;
default:
break;
}
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(count, copy);
if (copy != inline_copy) delete[] copy;
return 0;
}
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box) {
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyTextureRegion");
D3D12_TEXTURE_COPY_LOCATION d{}, s{};
if (dst) {
d = *dst;
d.pResource = bx_xbox_unwrap_as(d.pResource);
}
if (src) {
s = *src;
s.pResource = bx_xbox_unwrap_as(s.pResource);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
}
} // extern "C"
+343
View File
@@ -0,0 +1,343 @@
#ifndef BETTERXEN_D3D12_XS_XBOX_FACADE_H
#define BETTERXEN_D3D12_XS_XBOX_FACADE_H
/*
* Xbox-layout objects in front of the PC proxies (ADR 0009).
*
* A title built against the Xbox Series D3D12 header calls every method through the object's
* function table, whose slot order differs from PC D3D12. A BxXboxObject has the Xbox object
* layout and an Xbox-order table (xbox_tables_generated.cpp); each slot forwards to the PC
* object it hosts, which is usually one of the PC proxies in proxy.h.
*
* Layout (from the Xbox header): the function-table pointer, a 32-bit flags word and the
* reference count make up every object's 16-byte base. ID3D12Device adds a 64-bit null constant
* buffer address at +16 and a 64-byte union at +24 whose first byte, m_OutOfLineFlags, makes
* inline helpers call out through the table when non-zero. The same layout is used for every
* interface family; the fields after the base are ignored by the others. Command lists add a
* put buffer and are not wrapped yet.
*/
#include "proxy.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <new>
struct BxXboxIface {
const char* name; // Xbox leaf interface, for logs
const IID* iids; // Xbox interface IDs this table answers
size_t iid_count;
const IID* host_iid; // PC interface the hosted object provides
const void* const* table; // Xbox-order function table
size_t slots;
};
/*
* Interface-specific Xbox fields follow the 16-byte base. ID3D12Device: null constant-buffer
* address at +16, m_OutOfLineFlags at +24. ID3D12GraphicsCommandList: m_Putter at +16 (five
* put-buffer pointers and 256 reserved bytes), CPU state at +312, the graphics and compute root
* packet-header tables at +316 and +828 and the PSO shadow at +1340; the whole object is 1384
* bytes (an 8-byte field at +1376 follows), which the title's inline code writes. Zero put
* pointers make every inline fast path fail its room check and call through the table. The other
* interfaces define no fields here. The area below is the largest Xbox object (the command list)
* plus a margin, so title writes never reach BetterXen's state after it: with 1360 bytes the
* list's last field was BetterXen's host pointer, and the title overwrote it.
*/
constexpr size_t kBxXboxCommandListBytes = 1384;
constexpr size_t kBxXboxFieldBytes = kBxXboxCommandListBytes - 16 + 64;
struct BxXboxObject {
const void* const* function_table;
uint32_t xbox_flags;
uint32_t xbox_ref_count; // kept equal to `refs` for anything reading the Xbox field
uint8_t xbox_fields[kBxXboxFieldBytes];
// BetterXen state, after every field the Xbox layout defines.
IUnknown* host; // owns one reference; typed as iface->host_iid
const BxXboxIface* iface;
std::atomic<ULONG> refs;
};
static_assert(offsetof(BxXboxObject, xbox_ref_count) == 12, "Xbox m_RefCount offset");
static_assert(offsetof(BxXboxObject, xbox_fields) == 16, "Xbox interface fields start after the base");
static_assert(offsetof(BxXboxObject, host) >= kBxXboxCommandListBytes, "BetterXen state lies past every Xbox field");
static_assert(offsetof(BxXboxObject, host) >= 1372, "BetterXen state follows the Xbox command-list fields");
constexpr size_t kBxXboxDeviceOutOfLineOffset = 24;
/* The Xbox table for `riid`, or nullptr when none of the wrapped families answers it. */
const BxXboxIface* bx_xbox_iface_for(REFIID riid);
/* Wraps `host` (consumes the caller's reference) in the Xbox object for `riid`. One Xbox object
exists per host object and family. When no family answers `riid`, `host` is returned as is
and that is logged. */
void* bx_xbox_wrap(REFIID riid, void* host, HRESULT* failure = nullptr);
/* After a (REFIID, void**) creation call: wraps a successful result. */
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv);
/* The hosted PC object when `p` is one of our Xbox objects, otherwise `p` itself. */
IUnknown* bx_xbox_unwrap(const void* p);
template <typename T>
T* bx_xbox_unwrap_as(T* p) {
return static_cast<T*>(static_cast<void*>(bx_xbox_unwrap(p)));
}
template <typename T>
const T* bx_xbox_unwrap_as(const T* p) {
return static_cast<const T*>(static_cast<void*>(bx_xbox_unwrap(p)));
}
template <typename T>
T* bx_xbox_host(void* self) {
return static_cast<T*>(static_cast<BxXboxObject*>(self)->host);
}
/* Unwraps an array of interface pointers for one forwarded call. */
template <typename T>
class BxXboxUnwrapArray {
public:
BxXboxUnwrapArray(T* const* items, UINT count) : count_(count) {
if (!items || count == 0) {
ok_ = true;
return;
}
data_ = count <= kInline ? inline_ : new (std::nothrow) T*[count];
ok_ = data_ != nullptr;
for (UINT i = 0; ok_ && i < count; ++i) data_[i] = bx_xbox_unwrap_as(items[i]);
}
~BxXboxUnwrapArray() {
if (data_ && data_ != inline_) delete[] data_;
}
BxXboxUnwrapArray(const BxXboxUnwrapArray&) = delete;
BxXboxUnwrapArray& operator=(const BxXboxUnwrapArray&) = delete;
bool ok() const { return ok_; }
T* const* data() const { return data_; }
private:
static constexpr UINT kInline = 16;
T* inline_[kInline] = {};
T** data_ = nullptr;
UINT count_ = 0;
bool ok_ = false;
};
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv);
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self);
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self);
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv);
/* Xbox ID3D12Device::CreateCommandQueueX: the Xbox queue description selects a hardware
engine/pipe and queue index; the PC queue gets the same type and flags at normal priority. */
struct BxXboxCommandQueueDesc {
D3D12_COMMAND_LIST_TYPE Type;
D3D12_COMMAND_QUEUE_FLAGS Flags;
UINT EngineOrPipeIndex;
UINT QueueIndex;
};
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
REFIID riid, void** ppv);
/* Xbox ID3D12Device::CreateCommandListX. ResourceBarrierBatchSize sizes an Xbox-side batch and is
not used by the host. */
struct BxXboxCommandListDesc {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags;
UINT NodeMask;
UINT ResourceBarrierBatchSize;
};
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
ID3D12CommandAllocator* allocator,
ID3D12PipelineState* initial_state, REFIID riid,
void** ppv);
/* Frame pacing (frame_pacing.cpp): Xbox ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX and
WaitFrameEventX, emulated with a host timer. Event types: 0 origin, 1 display vblank, 2 flip. */
struct BxXboxFrameObjectList {
UINT Count;
HANDLE* pObjects;
};
struct BxXboxFrameWaitList {
UINT Count;
HANDLE* pObjects;
UINT* pSignaledObjectIndex;
};
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void* self, IDXGIOutput* output, UINT length_us,
UINT period, UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void* self, UINT type, UINT offset_us,
const BxXboxFrameObjectList* signals, UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void* self, UINT type, UINT timeout_ms,
const BxXboxFrameWaitList* waits, UINT flags,
UINT64* token);
/*
* Title memory and host objects (ADR 0009). Everything that maps title-visible GPU memory to
* host objects goes through these functions, so the backend behind them (D3DMetal today) can be
* replaced on its own: title descriptor handles to host handles (descriptor_heaps.cpp) and title
* GPU addresses to host addresses (placed_x.cpp). Unknown values pass through unchanged.
*/
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title);
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title);
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title);
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
void bx_xbox_descriptor_heap_forget(IUnknown* host);
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes);
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
/* Fences with a title-visible value (fences.cpp). */
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host);
void bx_xbox_fence_forget(IUnknown* host);
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self);
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value);
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT64 reference, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT reference, UINT mask, UINT flags);
/* GPU value writes into title memory (gpu_writes.cpp). */
void bx_xbox_gpu_writes_reset(IUnknown* host_list);
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flush, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flush, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flags);
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists);
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
UINT64 token, UINT flags);
/* Pipelines and the opt-in null-render mode (pipelines.cpp). */
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title);
void bx_xbox_pipeline_forget(IUnknown* host);
void bx_xbox_list_forget(IUnknown* host);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void* extended,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void* extended,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
ID3D12RootSignature* root, REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void* state, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void* state, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT count, const void* descs, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT count, const void* descs, REFIID riid,
void** ppv);
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso);
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso);
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT sync_flags, UINT control_flags, D3D12_GPU_VIRTUAL_ADDRESS base,
SIZE_T size);
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void* self, void* callback, UINT64 context);
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance);
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
INT base_vertex, UINT first_instance);
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z);
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
ID3D12Resource* arguments, UINT64 arguments_offset,
ID3D12Resource* count, UINT64 count_offset);
/* Map / Unmap: title memory for resources that have it (placed_x.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data);
void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written);
void bx_xbox_sync_mapped_buffers();
HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes, const void* parameters);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void* self, UINT batch_count, const void* batches,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT range_count, const void* ranges,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages, UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT page_count, UINT flags);
/* Page pools (placed_x.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
HANDLE* handle);
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void* self, HANDLE handle);
/* Committed resources with title-visible memory (committed.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, UINT32 formats,
DXGI_FORMAT* castable, REFIID riid, void** ppv);
/* Descriptor heaps with title-visible storage (descriptor_heaps.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
REFIID riid, void** ppv);
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void* self, D3D12_DESCRIPTOR_HEAP_TYPE type);
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self);
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self);
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* `xbox_desc` is a D3D12XBOX_SAMPLER_DESC. */
void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
const UINT* dest_sizes, UINT src_ranges,
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
D3D12_DESCRIPTOR_HEAP_TYPE type);
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv);
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views);
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view);
/* Resources at a title-chosen GPU address (placed_x.cpp): host shadow resources. */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC1* desc, UINT initial_layout,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self);
/* Xbox views of placed memory; `xbox_desc` is a D3D12XBOX_SHADER/UNORDERED_ACCESS_VIEW_DESC. */
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* Drops the shadow record of a destroyed resource. */
void bx_xbox_placed_forget(IUnknown* host);
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers);
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box);
}
#include "xbox_tables_generated.h"
#endif
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
// Generated by shims/d3d12_xs/tools/gen_xbox_tables.py from the Xbox Series D3D12 header (slot
// order, names and types only) and the toolchain's <d3d12.h>. Do not edit by hand.
#ifndef BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H
#define BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H
#include "xbox_facade.h"
extern const BxXboxIface bx_xbox_Device;
extern const BxXboxIface bx_xbox_Resource;
extern const BxXboxIface bx_xbox_Heap;
extern const BxXboxIface bx_xbox_Fence;
extern const BxXboxIface bx_xbox_DescriptorHeap;
extern const BxXboxIface bx_xbox_RootSignature;
extern const BxXboxIface bx_xbox_PipelineState;
extern const BxXboxIface bx_xbox_CommandAllocator;
extern const BxXboxIface bx_xbox_QueryHeap;
extern const BxXboxIface bx_xbox_CommandSignature;
extern const BxXboxIface bx_xbox_CommandQueue;
extern const BxXboxIface bx_xbox_GraphicsCommandList;
extern const BxXboxIface* const bx_xbox_ifaces[];
extern const size_t bx_xbox_iface_count;
#endif
+116 -4
View File
@@ -2,6 +2,8 @@
#include <unknwn.h>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <new>
#include <unordered_map>
#include "bx_log.h"
@@ -43,14 +45,38 @@ HRESULT unavailable(T* out) {
return E_NOTIMPL;
}
class GameInputDispatcher;
class GameInput final : public IUnknown {
LONG refs = 0;
SRWLOCK callback_lock_ = SRWLOCK_INIT;
uint64_t next_token_ = 1;
std::unordered_map<uint64_t, RegisteredDeviceCallback> callbacks_;
std::atomic<uint32_t> focus_policy_{0};
// Live IGameInputDispatcher reference count. >0 means GameInput is in
// "manual dispatch" mode; 0 means "automatic dispatch" mode.
std::atomic<uint32_t> dispatcher_refs_{0};
public:
// Logs the manual/automatic dispatch mode transition. Purely atomic: it
// never takes callback_lock_, so it cannot introduce lock ordering hazards.
void note_dispatch_mode(const char* mode, uint32_t count) {
char detail[96];
std::snprintf(detail, sizeof(detail), "mode=%s live_dispatchers=%u", mode,
static_cast<unsigned>(count));
bx_log_emit(BX_LOG_INFO, "gameinput", "dispatch_mode", detail);
}
void on_dispatcher_created() {
const uint32_t count = dispatcher_refs_.fetch_add(1, std::memory_order_acq_rel) + 1;
if (count == 1) note_dispatch_mode("manual", count);
}
void on_dispatcher_released() {
const uint32_t count = dispatcher_refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (count == 0) note_dispatch_mode("automatic", count);
}
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
@@ -133,10 +159,9 @@ public:
SrwExclusiveLock guard(callback_lock_);
return callbacks_.erase(token) > 0;
}
virtual HRESULT WINAPI CreateDispatcher(void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
return unavailable(out);
}
// Slot 14. Defined out of line below because it allocates
// GameInputDispatcher, which in turn calls back into this class.
virtual HRESULT WINAPI CreateDispatcher(void** out);
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
return unavailable(out);
@@ -166,6 +191,93 @@ public:
}
};
// IGameInputDispatcher (GameInput v0): IUnknown + Dispatch + OpenWaitHandle.
// Holding a reference puts GameInput in manual dispatch mode; releasing the
// last one returns it to automatic dispatch mode.
class GameInputDispatcher final : public IUnknown {
LONG refs = 1;
GameInput* owner_ = nullptr;
public:
explicit GameInputDispatcher(GameInput* owner) : owner_(owner) {}
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid == IID_IUnknown) {
AddRef();
*out = this;
return S_OK;
}
// The GameInput v0 IGameInputDispatcher IID is not published in the
// public Microsoft Learn / GDK documentation, so it is NOT guessed
// here. Only IID_IUnknown is served; every other queried id is logged
// (never silently ignored) and answered with E_NOINTERFACE.
char guid[40];
std::snprintf(guid, sizeof(guid), "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
static_cast<unsigned long>(iid.Data1), iid.Data2, iid.Data3,
iid.Data4[0], iid.Data4[1], iid.Data4[2], iid.Data4[3],
iid.Data4[4], iid.Data4[5], iid.Data4[6], iid.Data4[7]);
char detail[160];
std::snprintf(detail, sizeof(detail),
"IGameInputDispatcher iid=%s unsupported (v0 dispatcher IID not publicly documented)",
guid);
bx_log_emit(BX_LOG_WARN, "gameinput", "qi_unsupported", detail);
return E_NOINTERFACE;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
const LONG count = InterlockedDecrement(&refs);
if (count == 0) {
GameInput* owner = owner_;
owner_ = nullptr;
if (owner) owner->on_dispatcher_released();
delete this;
}
return static_cast<ULONG>(count);
}
// Slot 3: bool Dispatch(uint64_t quotaInMicroseconds).
// This shim has no real background input work, so the dispatch queue is
// always empty. The documented "flush at least one item even at quota 0"
// shape is honoured trivially: there is nothing to flush, so it returns
// false (no work items remain) for every quota, including 0. No real work
// is scheduled, and it never busy-waits or sleeps.
virtual bool WINAPI Dispatch(uint64_t /*quota_us*/) {
return false;
}
// Slot 4: HRESULT OpenWaitHandle(HANDLE* waitHandle).
// Returns a fresh manual-reset event on every call. The dispatcher owns
// nothing after returning it: the caller closes it via CloseHandle.
// LIMIT: the handle is created non-signaled and this shim never signals
// it, because there is no background input work to make it ready. A
// caller that waits on it with INFINITE will block forever; poll with a
// timeout, or call Dispatch, instead.
virtual HRESULT WINAPI OpenWaitHandle(HANDLE* out) {
if (!out) return E_POINTER;
*out = nullptr;
HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!handle) {
return HRESULT_FROM_WIN32(GetLastError());
}
*out = handle;
return S_OK;
}
};
HRESULT WINAPI GameInput::CreateDispatcher(void** out) {
if (!out) return E_POINTER;
*out = nullptr;
GameInputDispatcher* dispatcher = new (std::nothrow) GameInputDispatcher(this);
if (!dispatcher) return E_OUTOFMEMORY;
*out = dispatcher;
// The GameInput singleton's own refcount is intentionally unchanged:
// the dispatcher only moves the manual-dispatch mode counter.
on_dispatcher_created();
return S_OK;
}
GameInput singleton;
}
+893 -3
View File
@@ -1,8 +1,12 @@
#include <windows.h>
#include <tlhelp32.h>
#include <atomic>
#include <cstdio>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <initializer_list>
#include <intrin.h>
#include "bx_config.h"
@@ -18,6 +22,12 @@ LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
std::atomic_flag g_crash_logged{};
std::atomic<bool> g_crash_in_flight{false};
std::atomic<uint64_t> g_clwb_traps{0};
std::atomic<uint32_t> g_breakpoint_records{0};
// Breakpoint and assertion-failure records per process, so a guest that uses int3 on purpose
// cannot flood the log.
constexpr uint32_t kMaxBreakpointRecords = 16;
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
// counts reach the JSONL trace only: the frozen .def has no export for them.
@@ -354,11 +364,874 @@ LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
return disposition;
}
// A guest with its own crash reporter replaces the top-level filter installed at attach, so
// log_unhandled_exception never sees its assertions. The vectored handler runs before the
// guest's top-level filter and before any vectored handler the guest registers last; a handler
// the guest registers first can resume the exception before this one sees it. It records
// breakpoints and assertion failures with their module offset. They are first-chance, so the
// guest may still handle them; handling is left unchanged.
void log_breakpoint(const EXCEPTION_RECORD& record) {
// Past the cap the counter is not advanced again, so it cannot wrap around to 1.
if (g_breakpoint_records.load(std::memory_order_relaxed) >= kMaxBreakpointRecords) {
return;
}
const uint32_t index = g_breakpoint_records.fetch_add(1, std::memory_order_relaxed) + 1;
if (index > kMaxBreakpointRecords) {
return;
}
// The calls below can change the thread's last-error value; a resumed first-chance exception
// must leave the guest's error state as it was.
const DWORD last_error = GetLastError();
const uintptr_t address = reinterpret_cast<uintptr_t>(record.ExceptionAddress);
MEMORY_BASIC_INFORMATION region{};
uintptr_t module_base = 0;
char module[MAX_PATH] = "?";
if (VirtualQuery(record.ExceptionAddress, &region, sizeof(region)) &&
region.Type == MEM_IMAGE) {
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
// Wide API plus an explicit UTF-8 conversion: the ANSI form returns the name in the
// active code page, which would make a non-ASCII module name invalid UTF-8 in the JSON.
wchar_t path[MAX_PATH];
const DWORD length =
GetModuleFileNameW(reinterpret_cast<HMODULE>(module_base), path, MAX_PATH);
if (length > 0 && length < MAX_PATH) {
const wchar_t* slash = std::wcsrchr(path, L'\\');
const wchar_t* name = slash ? slash + 1 : path;
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, module, sizeof(module), nullptr, nullptr) == 0) {
std::snprintf(module, sizeof(module), "?");
}
}
}
char line[1024];
const int length = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\","
"\"event\":\"breakpoint_exception\",\"exception_code\":\"0x%08lx\","
"\"module\":\"%s\",\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
"\"address\":\"0x%016llx\",\"record\":%u,\"limit\":%u}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
record.ExceptionCode, module, static_cast<unsigned long long>(module_base),
static_cast<unsigned long long>(module_base ? address - module_base : 0),
static_cast<unsigned long long>(address), index, kMaxBreakpointRecords);
if (length > 0 && length < static_cast<int>(sizeof(line))) {
write_log_line(line, static_cast<size_t>(length));
}
SetLastError(last_error);
}
// Diagnostics (off unless BX_VEH_AV_CONTEXT is set): the first access violations in an image
// are logged with the general registers and, for each address in the variable, 64 bytes of
// memory. An entry "*ADDR+OFF" first reads the pointer at ADDR, then dumps at pointer + OFF.
// Reads are guarded by VirtualQuery; handling is left unchanged (first chance, search continues).
bool readable_bytes(uintptr_t address, size_t size) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) || region.State != MEM_COMMIT ||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
return false;
}
return address + size <= reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
// A JSONL line built with bounded appends: an append that does not fit is dropped and marks the
// line truncated, so the length never passes the buffer. Four bytes stay reserved for the closing
// "\"}\n". Text from the environment or module names goes through add_escaped.
class LineBuf {
public:
LineBuf(char* p, size_t cap) : p_(p), cap_(cap - 4) { p_[0] = '\0'; }
void add(const char* fmt, ...) {
if (truncated_) return;
va_list ap;
va_start(ap, fmt);
const int n = std::vsnprintf(p_ + len_, cap_ - len_, fmt, ap);
va_end(ap);
if (n < 0 || static_cast<size_t>(n) >= cap_ - len_) {
p_[len_] = '\0'; // drop the partial append
truncated_ = true;
return;
}
len_ += static_cast<size_t>(n);
}
// JSON string escaping for " \ and control characters; other bytes (UTF-8) pass through.
void add_escaped(const char* text, size_t max) {
for (size_t i = 0; text[i] && i < max && !truncated_; ++i) {
const unsigned char ch = static_cast<unsigned char>(text[i]);
if (ch == '"' || ch == '\\') add("\\%c", ch);
else if (ch < 0x20) add("\\u%04x", ch);
else add("%c", ch);
}
}
bool room(size_t n) const { return !truncated_ && cap_ - len_ > n; }
// Closes the JSON string and object and writes the line.
void finish() {
std::memcpy(p_ + len_, "\"}\n", 4);
write_log_line(p_, len_ + 3);
}
private:
char* p_;
size_t cap_;
size_t len_ = 0;
bool truncated_ = false;
};
// A module's file name (without the directory) in UTF-8, or "?" when it cannot be read.
void module_name_utf8(uintptr_t base, char* out, size_t size) {
wchar_t path[MAX_PATH];
const DWORD n = base ? GetModuleFileNameW(reinterpret_cast<HMODULE>(base), path, MAX_PATH) : 0;
if (n == 0 || n >= MAX_PATH) {
std::snprintf(out, size, "?");
return;
}
const wchar_t* slash = std::wcsrchr(path, L'\\');
const wchar_t* name = slash ? slash + 1 : path;
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, out, static_cast<int>(size), nullptr, nullptr) == 0) {
std::snprintf(out, size, "?");
}
}
// BX_VEH_AV_CONTEXT and BX_VEH_AV_ALL, read once when runtime_veh attaches. With the context
// switch unset the access-violation path does nothing at all.
char g_av_spec[512];
bool g_av_context_on = false;
bool g_av_all = false;
void read_av_switches() {
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_CONTEXT", g_av_spec, sizeof(g_av_spec));
g_av_context_on = n > 0 && n < sizeof(g_av_spec);
char v[4];
const DWORD k = GetEnvironmentVariableA("BX_VEH_AV_ALL", v, sizeof(v));
g_av_all = k > 0 && k < sizeof(v) && v[0] == '1';
}
void log_av_context(const EXCEPTION_POINTERS& ep) {
static std::atomic<uint32_t> logged{0};
if (!g_av_context_on || logged.fetch_add(1) >= 16) return;
const CONTEXT& c = *ep.ContextRecord;
char line[1600];
LineBuf out(line, sizeof(line));
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"av_context\","
"\"detail\":\"rip=%llx fault=%llx rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx "
"rsp=%llx r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)c.Rip,
(unsigned long long)(ep.ExceptionRecord->NumberParameters >= 2 ? ep.ExceptionRecord->ExceptionInformation[1] : 0),
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx,
(unsigned long long)c.Rdx, (unsigned long long)c.Rsi, (unsigned long long)c.Rdi,
(unsigned long long)c.Rbp, (unsigned long long)c.Rsp, (unsigned long long)c.R8,
(unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14,
(unsigned long long)c.R15);
// The comma-separated spec, scanned without shared state (several threads can fault at once).
for (const char* cursor = g_av_spec; *cursor && out.room(220);) {
const char* comma = std::strchr(cursor, ',');
const size_t length = comma ? static_cast<size_t>(comma - cursor) : std::strlen(cursor);
char item[64];
const size_t take = length < sizeof(item) - 1 ? length : sizeof(item) - 1;
std::memcpy(item, cursor, take);
item[take] = '\0';
cursor += length + (comma ? 1 : 0);
// "*A+O": dump at [A]+O. "**A+O1+O2": dump at [[A]+O1]+O2.
const int derefs = item[0] == '*' ? (item[1] == '*' ? 2 : 1) : 0;
char* rest = nullptr;
uintptr_t address = static_cast<uintptr_t>(std::strtoull(item + derefs, &rest, 16));
uintptr_t offsets[2] = {0, 0};
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
bool ok = true;
for (int k = 0; k < derefs && ok; ++k) {
ok = readable_bytes(address, 8);
if (ok) address = *reinterpret_cast<const uintptr_t*>(address) + offsets[k];
}
out.add(" | ");
out.add_escaped(item, sizeof(item));
if (!ok) {
out.add(" unresolved");
continue;
}
if (derefs == 0) address += offsets[0];
out.add(" @%llx:", (unsigned long long)address);
MEMORY_BASIC_INFORMATION mbi{};
if (VirtualQuery(reinterpret_cast<void*>(address), &mbi, sizeof(mbi))) {
out.add(" [type=%lx prot=%lx alloc=%llx region=%llx+%llx]", static_cast<unsigned long>(mbi.Type),
static_cast<unsigned long>(mbi.Protect), (unsigned long long)reinterpret_cast<uintptr_t>(mbi.AllocationBase),
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.BaseAddress), (unsigned long long)mbi.RegionSize);
}
if (!readable_bytes(address, 64)) {
out.add(" unreadable");
continue;
}
const auto* q = reinterpret_cast<const uint64_t*>(address);
for (int i = 0; i < 8; ++i) out.add(" %llx", (unsigned long long)q[i]);
}
// The faulting thread's stack: up to eight frames, unwound from its context, as module+offset.
out.add(" | stack:");
CONTEXT walk = c;
for (int i = 0; i < 8 && walk.Rip && out.room(64); ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(walk.Rip), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char name[96] = "anon";
if (base) module_name_utf8(base, name, sizeof(name));
out.add(" ");
out.add_escaped(name, 24);
out.add("+%llx", (unsigned long long)(walk.Rip - base));
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) {
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) break;
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
out.finish();
}
// A diagnostic that had to stop (a protection change failed): logged once per kind.
void log_disarmed(const char* what, uintptr_t address) {
char line[256];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"diagnostic_disarmed\","
"\"detail\":\"%s address=%llx error=%lu\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), what,
(unsigned long long)address, GetLastError());
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
// Set when runtime_veh detaches: helper threads stop at their next step and log nothing more.
std::atomic<bool> g_diag_stop{false};
std::atomic<int> g_diag_threads{0};
// Diagnostics (off unless BX_VEH_WATCH=ADDR:LEN, hex): a software write watch. A helper thread
// makes the page holding [ADDR, ADDR+LEN) read-only as soon as that page is committed. Each
// write fault in the page is allowed by restoring write access and single-stepping the writing
// instruction; writes inside the range are logged with the instruction's module offset and the
// value after the write, then the page is protected again. Writes by other threads while the
// page is briefly writable are not seen, and system calls that write into the page fail while
// it is protected, so this is for diagnosis only.
uintptr_t g_watch_begin = 0, g_watch_end = 0, g_watch_page = 0;
std::atomic<bool> g_watch_armed{false};
std::atomic<uint32_t> g_watch_logged{0};
DWORD g_watch_tls = TLS_OUT_OF_INDEXES;
// The watched address: "A:LEN", or a pointer chain "*A+O:LEN" / "**A+O1+O2:LEN" that the helper
// thread resolves once every pointer in it is non-null and readable.
uintptr_t g_watch_root = 0, g_watch_offsets[2] = {0, 0}, g_watch_length = 8;
int g_watch_derefs = 0;
bool resolve_watch(uintptr_t* out) {
uintptr_t address = g_watch_root;
for (int k = 0; k < g_watch_derefs; ++k) {
if (!readable_bytes(address, 8)) return false;
const uintptr_t next = *reinterpret_cast<const uintptr_t*>(address);
if (!next) return false;
address = next + g_watch_offsets[k];
}
if (g_watch_derefs == 0) address += g_watch_offsets[0];
*out = address;
return true;
}
DWORD WINAPI watch_arm_thread(LPVOID) {
for (int i = 0; i < 600000 && !g_watch_armed.load() && !g_diag_stop.load(); ++i) {
uintptr_t begin = 0;
DWORD old = 0;
if (resolve_watch(&begin) && readable_bytes(begin, g_watch_length)) {
g_watch_begin = begin;
g_watch_end = begin + g_watch_length;
g_watch_page = begin & ~static_cast<uintptr_t>(4095);
char line[512];
int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watch_armed\","
"\"detail\":\"address=%llx contents:",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)begin);
for (uintptr_t a = begin; a + 8 <= g_watch_end && len < static_cast<int>(sizeof(line)) - 24; a += 8) {
len += std::snprintf(line + len, sizeof(line) - len, " %llx",
(unsigned long long)*reinterpret_cast<const uint64_t*>(a));
}
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
if (VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
g_watch_armed = true;
} else {
log_disarmed("watch: could not protect the page", g_watch_page);
}
break;
}
Sleep(1);
}
return 0;
}
void start_write_watch() {
char spec[96];
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_watch_derefs = spec[0] == '*' ? (spec[1] == '*' ? 2 : 1) : 0;
char* rest = nullptr;
g_watch_root = static_cast<uintptr_t>(std::strtoull(spec + g_watch_derefs, &rest, 16));
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) g_watch_offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
if (rest && *rest == ':') g_watch_length = static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16));
g_watch_tls = TlsAlloc();
if (g_watch_tls == TLS_OUT_OF_INDEXES) return;
if (HANDLE t = CreateThread(nullptr, 0, watch_arm_thread, nullptr, 0, nullptr)) {
++g_diag_threads;
CloseHandle(t);
}
}
void log_watched_write(uintptr_t rip, uintptr_t address, uint64_t value) {
if (g_watch_logged.fetch_add(1) >= 64) return;
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(rip), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char line[256];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watched_write\","
"\"detail\":\"rip=%llx module_base=%llx address=%llx value_after=%llx\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)rip, (unsigned long long)base, (unsigned long long)address,
(unsigned long long)value);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
// Returns true when the exception belonged to the write watch and was handled.
bool handle_write_watch(PEXCEPTION_POINTERS ep) {
if (!g_watch_armed.load() || g_watch_tls == TLS_OUT_OF_INDEXES) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
if ((address & ~static_cast<uintptr_t>(4095)) != g_watch_page) return false;
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old)) {
// Fail open: the write cannot be allowed, so the guest gets its access violation.
g_watch_armed = false;
log_disarmed("watch: could not unprotect the page", g_watch_page);
return false;
}
// Remember the write for the single-step that follows it (+1 so 0 means "none").
TlsSetValue(g_watch_tls, reinterpret_cast<void*>(address + 1));
ep->ContextRecord->EFlags |= 0x100;
return true;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_watch_tls));
if (!pending) return false;
TlsSetValue(g_watch_tls, nullptr);
const uintptr_t address = pending - 1;
if (address >= g_watch_begin && address < g_watch_end) {
const uintptr_t slot = address & ~static_cast<uintptr_t>(7);
log_watched_write(static_cast<uintptr_t>(reinterpret_cast<uintptr_t>(r.ExceptionAddress)), address,
*reinterpret_cast<const uint64_t*>(slot));
}
DWORD old = 0;
if (!g_watch_armed.load() || !VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
if (g_watch_armed.exchange(false)) log_disarmed("watch: could not re-protect the page", g_watch_page);
}
return true;
}
return false;
}
// Diagnostics (off unless BX_VEH_WATCH_RANGE=A:LEN, hex, at most 16 MiB): a write watch over a
// range of pages, for data whose exact address moves between runs. A helper thread makes each
// read-write page in the range read-only as soon as it is committed. A write fault is allowed by
// restoring the page and single-stepping the instruction; the write is logged with its address,
// the value after it and up to six frames of the writing thread, unwound from its context. After
// 64 logged writes the whole range is made writable again and the watch stops.
constexpr size_t kRangeWatchPages = 4096;
uintptr_t g_rw_begin = 0, g_rw_end = 0;
std::atomic<uint8_t> g_rw_armed[kRangeWatchPages];
std::atomic<bool> g_rw_on{false};
std::atomic<uint32_t> g_rw_logged{0};
DWORD g_rw_tls = TLS_OUT_OF_INDEXES;
void range_watch_stop() {
g_rw_on = false;
for (size_t i = 0; i < kRangeWatchPages; ++i) {
if (g_rw_armed[i].exchange(0)) {
DWORD old = 0;
VirtualProtect(reinterpret_cast<void*>(g_rw_begin + i * 4096), 4096, PAGE_READWRITE, &old);
}
}
}
// "*A+O:LEN": the range starts at [A] + O, resolved once the pointer at A is readable and non-zero.
uintptr_t g_rw_root = 0, g_rw_offset = 0, g_rw_length = 0;
DWORD WINAPI range_watch_thread(LPVOID) {
if (g_rw_root) {
for (int i = 0; i < 600000; ++i) {
if (g_diag_stop.load()) return 0;
if (readable_bytes(g_rw_root, 8) && *reinterpret_cast<const uintptr_t*>(g_rw_root)) break;
Sleep(1);
}
if (!readable_bytes(g_rw_root, 8) || !*reinterpret_cast<const uintptr_t*>(g_rw_root)) return 0;
const uintptr_t begin = (*reinterpret_cast<const uintptr_t*>(g_rw_root) + g_rw_offset) & ~static_cast<uintptr_t>(4095);
g_rw_end = (begin + g_rw_length + 4095) & ~static_cast<uintptr_t>(4095);
g_rw_begin = begin;
char line[200];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_watch_resolved\","
"\"detail\":\"begin=%llx end=%llx\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)g_rw_begin, (unsigned long long)g_rw_end);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
const size_t pages = (g_rw_end - g_rw_begin) / 4096;
for (int round = 0; round < 600000 && g_rw_on.load() && !g_diag_stop.load(); ++round) {
bool all = true;
for (size_t i = 0; i < pages && g_rw_on.load(); ++i) {
if (g_rw_armed[i].load()) continue;
all = false;
const uintptr_t page = g_rw_begin + i * 4096;
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(page), &region, sizeof(region)) || region.State != MEM_COMMIT ||
region.Protect != PAGE_READWRITE) {
continue;
}
DWORD old = 0;
if (VirtualProtect(reinterpret_cast<void*>(page), 4096, PAGE_READONLY, &old)) g_rw_armed[i] = 1;
}
if (all) break;
Sleep(1);
}
return 0;
}
void start_range_watch() {
char spec[64];
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
char* rest = nullptr;
const bool chain = spec[0] == '*';
const uintptr_t first = static_cast<uintptr_t>(std::strtoull(spec + (chain ? 1 : 0), &rest, 16));
uintptr_t offset = 0;
if (chain && rest && *rest == '+') offset = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
const uintptr_t length = rest && *rest == ':' ? static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16)) : 0;
if (!first || !length || length > kRangeWatchPages * 4096) return;
g_rw_tls = TlsAlloc();
if (g_rw_tls == TLS_OUT_OF_INDEXES) return;
if (chain) {
g_rw_root = first;
g_rw_offset = offset;
g_rw_length = length;
} else {
g_rw_begin = first & ~static_cast<uintptr_t>(4095);
g_rw_end = (g_rw_begin + length + 4095) & ~static_cast<uintptr_t>(4095);
}
g_rw_on = true;
if (HANDLE t = CreateThread(nullptr, 0, range_watch_thread, nullptr, 0, nullptr)) {
++g_diag_threads;
CloseHandle(t);
}
}
void log_range_write(const CONTEXT& c, uintptr_t address) {
uintptr_t frames[6]{};
int count = 0;
CONTEXT walk = c;
for (; count < 6 && walk.Rip; ++count) {
frames[count] = static_cast<uintptr_t>(walk.Rip);
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) {
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) { ++count; break; }
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
char line[640];
int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_write\","
"\"detail\":\"address=%llx value_after=%llx frames:",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
(unsigned long long)address,
(unsigned long long)*reinterpret_cast<const uint64_t*>(address & ~static_cast<uintptr_t>(7)));
for (int i = 0; i < count && len < static_cast<int>(sizeof(line)) - 48; ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
len += std::snprintf(line + len, sizeof(line) - len, " %llx+%llx", (unsigned long long)base,
(unsigned long long)(frames[i] - base));
}
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
write_log_line(line, static_cast<size_t>(len));
}
}
// Returns true when the exception belonged to the range watch and was handled.
bool handle_range_watch(PEXCEPTION_POINTERS ep) {
if (g_rw_tls == TLS_OUT_OF_INDEXES) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
if (address < g_rw_begin || address >= g_rw_end) return false;
const size_t index = (address - g_rw_begin) / 4096;
if (!g_rw_armed[index].load()) return false;
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READWRITE, &old)) {
g_rw_armed[index] = 0; // fail open: the guest gets its access violation
log_disarmed("range watch: could not unprotect a page", g_rw_begin + index * 4096);
return false;
}
TlsSetValue(g_rw_tls, reinterpret_cast<void*>(address + 1));
ep->ContextRecord->EFlags |= 0x100;
return true;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_rw_tls));
if (!pending) return false;
TlsSetValue(g_rw_tls, nullptr);
const uintptr_t address = pending - 1;
static const uint32_t cap = [] {
char v[16];
const DWORD k = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE_MAX", v, sizeof(v));
const unsigned long want = (k > 0 && k < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
return static_cast<uint32_t>(want == 0 ? 64 : (want > 200000 ? 200000 : want));
}();
const uint32_t n = g_rw_logged.fetch_add(1);
if (n < cap) log_range_write(*ep->ContextRecord, address);
if (n + 1 >= cap) {
range_watch_stop();
} else if (g_rw_on.load()) {
DWORD old = 0;
const size_t index = (address - g_rw_begin) / 4096;
if (g_rw_armed[index].load() &&
!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READONLY, &old)) {
g_rw_armed[index] = 0;
log_disarmed("range watch: could not re-protect a page", g_rw_begin + index * 4096);
}
}
return true;
}
return false;
}
// Diagnostics (off unless BX_VEH_HIT=A1,A2,..., hex, at most 8): software code breakpoints in this
// process. Each address gets an int3 when runtime_veh attaches; a hit logs the registers, puts the
// original byte back, single-steps that instruction and re-inserts the int3. The first 16 hits per
// address are logged, then every 256th. Other threads can pass an address unseen while its byte is
// restored, so this is for diagnosis only.
struct CodeHit {
uintptr_t address;
uint8_t original;
std::atomic<uint32_t> hits;
};
CodeHit g_code_hits[8];
int g_code_hit_count = 0;
DWORD g_code_hit_tls = TLS_OUT_OF_INDEXES;
// False when the byte could not be written. A failure to restore the page's original protection
// is logged: the page then stays writable, which the log record makes visible.
bool write_code_byte(uintptr_t address, uint8_t value) {
DWORD old = 0;
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, PAGE_EXECUTE_READWRITE, &old)) return false;
*reinterpret_cast<volatile uint8_t*>(address) = value;
DWORD unused = 0;
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, old, &unused)) {
log_disarmed("code hit: could not restore the page protection", address);
}
FlushInstructionCache(GetCurrentProcess(), reinterpret_cast<void*>(address), 1);
return true;
}
// Diagnostics (off unless BX_VEH_SAMPLE=MS, decimal): a sampling profiler for every thread in the
// process. Every MS milliseconds a helper thread visits each other thread: while it is suspended
// only its context and up to 64 KiB of its stack are copied (no heap or loader calls, so a thread
// suspended inside either cannot deadlock the sampler). After it resumes, up to eight frames are
// unwound against the copy with the images' unwind data and logged as module base + offset, with
// the thread id. At most 20000 samples are logged. For diagnosis only.
DWORD g_sample_interval = 0;
DWORD g_sample_self = 0;
alignas(16) uint8_t g_sample_stack[64 * 1024];
void sample_thread(DWORD tid) {
HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, tid);
if (!h) return;
CONTEXT c{};
c.ContextFlags = CONTEXT_FULL;
uintptr_t stack_lo = 0;
size_t copied = 0;
bool got = false;
if (SuspendThread(h) != static_cast<DWORD>(-1)) {
got = GetThreadContext(h, &c) != FALSE;
MEMORY_BASIC_INFORMATION region{};
if (got && VirtualQuery(reinterpret_cast<void*>(c.Rsp), &region, sizeof(region)) && region.State == MEM_COMMIT) {
stack_lo = static_cast<uintptr_t>(c.Rsp);
const uintptr_t end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
copied = end - stack_lo < sizeof(g_sample_stack) ? end - stack_lo : sizeof(g_sample_stack);
std::memcpy(g_sample_stack, reinterpret_cast<const void*>(stack_lo), copied);
}
ResumeThread(h);
}
CloseHandle(h);
if (!got) return;
// Unwind against the copy: stack addresses (rsp, and rbp when it points into the stack) are
// rebased into g_sample_stack; return addresses read from it are the thread's real ones.
const uintptr_t copy = reinterpret_cast<uintptr_t>(g_sample_stack);
auto in_stack = [&](DWORD64 a) { return a >= stack_lo && a < stack_lo + copied; };
CONTEXT walk = c;
walk.Rsp = copy;
if (in_stack(c.Rbp)) walk.Rbp = copy + (c.Rbp - stack_lo);
uintptr_t frames[8]{};
int count = 0;
for (; count < 8 && walk.Rip; ++count) {
frames[count] = static_cast<uintptr_t>(walk.Rip);
if (walk.Rsp < copy || walk.Rsp + 8 > copy + copied) { ++count; break; }
DWORD64 image = 0;
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
if (!fn) { // leaf function: the return address is at rsp
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
walk.Rsp += 8;
continue;
}
PVOID handler_data = nullptr;
DWORD64 frame = 0;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
}
char line[760];
LineBuf out(line, sizeof(line));
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"sample\",\"detail\":\"thread=%lu",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), tid);
for (int i = 0; i < count && out.room(64); ++i) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t base = 0;
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), &region, sizeof(region)) && region.Type == MEM_IMAGE) {
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
// The thread runs again, so the loader lock taken by GetModuleFileNameW cannot be held by it.
char name[96] = "anon";
if (base) module_name_utf8(base, name, sizeof(name));
out.add(" ");
out.add_escaped(name, 24);
out.add("+%llx", (unsigned long long)(frames[i] - base));
}
if (!g_diag_stop.load()) out.finish();
}
DWORD WINAPI sampler_main(LPVOID) {
const DWORD pid = GetCurrentProcessId();
for (int logged = 0; logged < 20000 && !g_diag_stop.load();) {
Sleep(g_sample_interval);
if (g_diag_stop.load()) break;
DWORD tids[256];
int n = 0;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (snap == INVALID_HANDLE_VALUE) continue;
THREADENTRY32 te{};
te.dwSize = sizeof(te);
for (BOOL ok = Thread32First(snap, &te); ok && n < 256; ok = Thread32Next(snap, &te)) {
if (te.th32OwnerProcessID == pid && te.th32ThreadID != g_sample_self) tids[n++] = te.th32ThreadID;
}
CloseHandle(snap);
for (int i = 0; i < n; ++i, ++logged) sample_thread(tids[i]);
}
return 0;
}
void start_sampler() {
char spec[16];
const DWORD n = GetEnvironmentVariableA("BX_VEH_SAMPLE", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_sample_interval = static_cast<DWORD>(std::strtoul(spec, nullptr, 10));
if (g_sample_interval == 0) return;
if (HANDLE t = CreateThread(nullptr, 0, sampler_main, nullptr, 0, &g_sample_self)) {
++g_diag_threads;
CloseHandle(t);
}
}
void start_code_hits() {
char spec[256];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return;
g_code_hit_tls = TlsAlloc();
if (g_code_hit_tls == TLS_OUT_OF_INDEXES) return;
for (const char* item = spec; *item && g_code_hit_count < 8;) {
char* end = nullptr;
const uintptr_t address = static_cast<uintptr_t>(std::strtoull(item, &end, 16));
const char* comma = std::strchr(item, ',');
item = comma ? comma + 1 : item + std::strlen(item);
MEMORY_BASIC_INFORMATION region{};
if (!address || !VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) ||
region.Type != MEM_IMAGE || region.State != MEM_COMMIT) {
continue;
}
CodeHit& hit = g_code_hits[g_code_hit_count];
hit.address = address;
hit.original = *reinterpret_cast<const uint8_t*>(address);
if (write_code_byte(address, 0xCC)) ++g_code_hit_count;
}
char line[160];
const int len = std::snprintf(line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hits_armed\","
"\"detail\":\"count=%d\"}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), g_code_hit_count);
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
}
void log_code_hit(const CodeHit& hit, uint32_t count, const CONTEXT& c) {
char line[2048];
int len = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hit\","
"\"detail\":\"address=%llx hit=%u rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx rsp=%llx "
"r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), (unsigned long long)hit.address, count,
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx, (unsigned long long)c.Rdx,
(unsigned long long)c.Rsi, (unsigned long long)c.Rdi, (unsigned long long)c.Rbp, (unsigned long long)c.Rsp,
(unsigned long long)c.R8, (unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14, (unsigned long long)c.R15);
// The first 16 bytes behind the three argument registers, when they point at readable memory.
const struct {
const char* name;
DWORD64 value;
} args[] = {{"rcx", c.Rcx}, {"rdx", c.Rdx}, {"r8", c.R8}};
for (const auto& a : args) {
if (len <= 0 || len >= static_cast<int>(sizeof(line)) - 64 || !readable_bytes(static_cast<uintptr_t>(a.value), 16)) continue;
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(a.value));
len += std::snprintf(line + len, sizeof(line) - len, " [%s]=%016llx %016llx", a.name, (unsigned long long)q[0],
(unsigned long long)q[1]);
// Printable text (a path or name argument): up to 96 characters of it.
const auto* s = reinterpret_cast<const unsigned char*>(static_cast<uintptr_t>(a.value));
if (s[0] >= 0x20 && s[0] < 0x7f && s[1] >= 0x20 && s[1] < 0x7f && readable_bytes(static_cast<uintptr_t>(a.value), 96)) {
char text[97];
int n = 0;
while (n < 96 && s[n] >= 0x20 && s[n] < 0x7f) {
text[n] = (s[n] == '"' || s[n] == '\\') ? '_' : static_cast<char>(s[n]);
++n;
}
text[n] = '\0';
if (len < static_cast<int>(sizeof(line)) - 120) {
len += std::snprintf(line + len, sizeof(line) - len, " [%s]s=%s", a.name, text);
}
}
}
// BX_VEH_HIT_RDX=LEN (hex, at most 0x200): also dump LEN bytes of the object rdx points to.
static const size_t rdx_len = [] {
char v[16];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_RDX", v, sizeof(v));
if (n == 0 || n >= sizeof(v)) return static_cast<size_t>(0);
const size_t want = static_cast<size_t>(std::strtoull(v, nullptr, 16)) & ~static_cast<size_t>(7);
return want > 0x200 ? static_cast<size_t>(0x200) : want;
}();
if (rdx_len && len > 0 && readable_bytes(static_cast<uintptr_t>(c.Rdx), rdx_len)) {
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(c.Rdx));
len += std::snprintf(line + len, sizeof(line) - len, " rdx_obj:");
for (size_t i = 0; i < rdx_len / 8 && len < static_cast<int>(sizeof(line)) - 24; ++i) {
len += std::snprintf(line + len, sizeof(line) - len, " %llx", (unsigned long long)q[i]);
}
}
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
write_log_line(line, static_cast<size_t>(len));
}
}
// Returns true when the exception belonged to a code breakpoint and was handled.
bool handle_code_hit(PEXCEPTION_POINTERS ep) {
if (g_code_hit_count == 0) return false;
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
CONTEXT& c = *ep->ContextRecord;
if (r.ExceptionCode == EXCEPTION_BREAKPOINT) {
const uintptr_t at = reinterpret_cast<uintptr_t>(r.ExceptionAddress);
for (int i = 0; i < g_code_hit_count; ++i) {
CodeHit& hit = g_code_hits[i];
if (at != hit.address && c.Rip - 1 != hit.address) continue;
const uint32_t count = hit.hits.fetch_add(1) + 1;
static const bool every = [] {
char v[4];
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_ALL", v, sizeof(v));
return n > 0 && n < sizeof(v) && v[0] == '1';
}();
if (count <= 16 || count % 256 == 0 || (every && count <= 20000)) log_code_hit(hit, count, c);
if (!write_code_byte(hit.address, hit.original)) {
// The original instruction cannot be put back: stop handling this address and let
// the breakpoint reach the guest instead of looping on it.
log_disarmed("code hit: could not restore the original byte", hit.address);
hit.address = 0;
return false;
}
c.Rip = hit.address;
c.EFlags |= 0x100;
TlsSetValue(g_code_hit_tls, reinterpret_cast<void*>(static_cast<uintptr_t>(i + 1)));
return true;
}
return false;
}
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_code_hit_tls));
if (!pending) return false;
TlsSetValue(g_code_hit_tls, nullptr);
CodeHit& hit = g_code_hits[pending - 1];
if (hit.address && !g_diag_stop.load() && !write_code_byte(hit.address, 0xCC)) {
log_disarmed("code hit: could not re-insert the breakpoint", hit.address);
hit.address = 0;
}
return true;
}
return false;
}
// Restores every page and code byte the diagnostics changed (used at detach).
void disarm_diagnostics() {
if (g_watch_armed.exchange(false)) {
DWORD old = 0;
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old);
}
if (g_rw_on.load() || g_rw_begin) range_watch_stop();
for (int i = 0; i < g_code_hit_count; ++i) {
CodeHit& hit = g_code_hits[i];
if (hit.address && *reinterpret_cast<const volatile uint8_t*>(hit.address) == 0xCC) {
write_code_byte(hit.address, hit.original);
}
hit.address = 0;
}
for (DWORD* tls : {&g_watch_tls, &g_rw_tls, &g_code_hit_tls}) {
if (*tls != TLS_OUT_OF_INDEXES) {
TlsFree(*tls);
*tls = TLS_OUT_OF_INDEXES;
}
}
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
return EXCEPTION_CONTINUE_SEARCH;
}
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
if (handle_code_hit(ep)) return EXCEPTION_CONTINUE_EXECUTION;
if (handle_range_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
if (handle_write_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
log_breakpoint(*ep->ExceptionRecord);
return EXCEPTION_CONTINUE_SEARCH;
}
if (code == EXCEPTION_ACCESS_VIOLATION) {
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
MEMORY_BASIC_INFORMATION region{};
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, &region, sizeof(region)) && region.Type == MEM_IMAGE)) {
log_av_context(*ep);
}
return EXCEPTION_CONTINUE_SEARCH;
}
if (code != EXCEPTION_ILLEGAL_INSTRUCTION) {
return EXCEPTION_CONTINUE_SEARCH;
}
@@ -479,6 +1352,15 @@ const bx_runtime_config_t* bx_get_runtime_config(void) {
int bx_veh_install(void) {
if (!g_veh_handle) {
g_veh_handle = AddVectoredExceptionHandler(1, bx_veh_handler);
if (g_veh_handle) {
read_av_switches();
// The helper threads below start running only after the loader lock is released; nothing
// here waits for them. They check g_diag_stop and stop at detach.
start_write_watch();
start_code_hits();
start_sampler();
start_range_watch();
}
}
return g_veh_handle != nullptr ? 1 : 0;
}
@@ -503,15 +1385,23 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
if (current_filter != log_unhandled_exception) {
SetUnhandledExceptionFilter(current_filter);
}
// Stop the diagnostics and take them out of the guest's memory: restore watched pages and
// original code bytes. Nothing waits for the helper threads (that would deadlock on the
// loader lock); they stop at their next step.
g_diag_stop = true;
disarm_diagnostics();
if (g_veh_handle) {
RemoveVectoredExceptionHandler(g_veh_handle);
g_veh_handle = nullptr;
}
if (g_log_handle != INVALID_HANDLE_VALUE) {
// A helper thread may still be inside write_log_line when this runs. While any helper was
// started, the log handle and its lock are left alive (the process is ending, or the DLL is
// being unloaded with threads that only touch them); otherwise they are released.
if (g_diag_threads.load() == 0 && g_log_handle != INVALID_HANDLE_VALUE) {
CloseHandle(g_log_handle);
g_log_handle = INVALID_HANDLE_VALUE;
}
if (g_log_lock_ready) {
if (g_diag_threads.load() == 0 && g_log_lock_ready) {
DeleteCriticalSection(&g_log_lock);
g_log_lock_ready = false;
}
+88 -34
View File
@@ -1,6 +1,7 @@
#include <windows.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include "bx_log.h"
@@ -23,10 +24,25 @@ struct SrwLockGuard {
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
};
// Exception-free open-addressed hash set backed by the Win32 process heap so
// One accepted registration, stored beside the token that names it.
//
// The callback and its context are kept together because the PSM contract is a
// callback plus a caller context: a caller passes `context` expecting the same
// value back as the callback's second argument if that callback ever fires.
// Dropping it would make even a future firing unable to deliver faithfully, so
// the shim owns both values for exactly as long as the token is live.
struct Entry {
uintptr_t token; // kEmptySlot == unused, kTombstoneSlot == erased
PVOID callback;
PVOID context;
};
// Exception-free open-addressed hash table backed by the Win32 process heap so
// both PSM DLLs stay on -fno-exceptions and map OOM to ERROR_NOT_ENOUGH_MEMORY.
// The record lives in the table slot, so an erase drops the callback with the
// token and a reset (DllMain detach) frees them together.
struct TokenSet {
uintptr_t* slots = nullptr;
Entry* slots = nullptr;
size_t capacity = 0;
size_t count = 0;
size_t used = 0; // active entries + tombstones
@@ -42,24 +58,24 @@ struct TokenSet {
}
bool rehash(size_t new_capacity) {
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(uintptr_t)) {
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(Entry)) {
return false;
}
HANDLE heap = GetProcessHeap();
if (!heap) {
return false;
}
auto* fresh = static_cast<uintptr_t*>(
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(uintptr_t)));
auto* fresh = static_cast<Entry*>(
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(Entry)));
if (!fresh) {
return false;
}
const size_t mask = new_capacity - 1;
for (size_t i = 0; i < capacity; ++i) {
const uintptr_t entry = slots[i];
if (entry != kEmptySlot && entry != kTombstoneSlot) {
size_t idx = hash(entry) & mask;
while (fresh[idx] != kEmptySlot) {
const Entry entry = slots[i];
if (entry.token != kEmptySlot && entry.token != kTombstoneSlot) {
size_t idx = hash(entry.token) & mask;
while (fresh[idx].token != kEmptySlot) {
idx = (idx + 1) & mask;
}
fresh[idx] = entry;
@@ -74,13 +90,15 @@ struct TokenSet {
return true;
}
bool insert(uintptr_t token) {
// Inserts the token with its callback/context and returns the stored slot so
// the caller can log back exactly what was retained. nullptr means OOM.
Entry* insert(uintptr_t token, PVOID callback, PVOID context) {
if (capacity == 0 || (used + 1) * 4 >= capacity * 3) {
size_t next_capacity = 64;
if (capacity != 0) {
if (count * 2 >= capacity) {
if (capacity > (SIZE_MAX / sizeof(uintptr_t)) / 2) {
return false;
if (capacity > (SIZE_MAX / sizeof(Entry)) / 2) {
return nullptr;
}
next_capacity = capacity * 2;
} else {
@@ -89,28 +107,36 @@ struct TokenSet {
}
}
if (!rehash(next_capacity)) {
return false;
return nullptr;
}
}
const size_t mask = capacity - 1;
size_t idx = hash(token) & mask;
size_t first_tombstone = capacity;
while (true) {
const uintptr_t entry = slots[idx];
if (entry == token) {
return true;
Entry& entry = slots[idx];
if (entry.token == token) {
entry.callback = callback;
entry.context = context;
return &entry;
}
if (entry == kEmptySlot) {
if (entry.token == kEmptySlot) {
if (first_tombstone != capacity) {
slots[first_tombstone] = token;
} else {
slots[idx] = token;
++used;
Entry& reused = slots[first_tombstone];
reused.token = token;
reused.callback = callback;
reused.context = context;
++count;
return &reused;
}
entry.token = token;
entry.callback = callback;
entry.context = context;
++used;
++count;
return true;
return &entry;
}
if (entry == kTombstoneSlot && first_tombstone == capacity) {
if (entry.token == kTombstoneSlot && first_tombstone == capacity) {
first_tombstone = idx;
}
idx = (idx + 1) & mask;
@@ -124,12 +150,16 @@ struct TokenSet {
const size_t mask = capacity - 1;
size_t idx = hash(token) & mask;
for (size_t probed = 0; probed < capacity; ++probed) {
const uintptr_t entry = slots[idx];
if (entry == kEmptySlot) {
Entry& entry = slots[idx];
if (entry.token == kEmptySlot) {
return false;
}
if (entry == token) {
slots[idx] = kTombstoneSlot;
if (entry.token == token) {
// Drop the stored callback and context with the token, so a
// later firing can never reach a retired registration.
entry.token = kTombstoneSlot;
entry.callback = nullptr;
entry.context = nullptr;
--count;
return true;
}
@@ -166,7 +196,15 @@ struct Registrations {
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
ULONG register_notification(Registrations& registrations, PVOID callback,
// Accepts a registration and records the callback and context that came with it.
//
// LIMITATION: the stored callbacks are currently NEVER INVOKED. This shim has
// no source of app-state or constrained-change transitions of its own, so no
// firing policy is invented here rather than firing the callback spuriously.
// ERROR_SUCCESS therefore means "the registration was recorded (bookkeeping
// only)", not "you will be notified". The JSONL detail says `callback_unfired`
// for the same reason, so `bx-cli trace` states the limitation too.
ULONG register_notification(Registrations& registrations, PVOID callback, PVOID context,
PVOID* out_reg, const char* event) {
if (!out_reg) {
return ERROR_INVALID_PARAMETER;
@@ -177,6 +215,8 @@ ULONG register_notification(Registrations& registrations, PVOID callback,
}
uintptr_t token = 0;
PVOID stored_callback = nullptr;
PVOID stored_context = nullptr;
{
const SrwLockGuard guard(registrations.lock);
// Never recycle a token that a caller may still retain.
@@ -184,14 +224,24 @@ ULONG register_notification(Registrations& registrations, PVOID callback,
return ERROR_NOT_ENOUGH_MEMORY;
}
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
if (!registrations.active.insert(token)) {
const Entry* stored = registrations.active.insert(token, callback, context);
if (!stored) {
return ERROR_NOT_ENOUGH_MEMORY;
}
// Log what the table actually retained for this token, not the
// arguments, so the record is evidence of the stored state.
stored_callback = stored->callback;
stored_context = stored->context;
++registrations.next_seq;
}
*out_reg = reinterpret_cast<PVOID>(token);
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, "registered_offline");
char detail[192];
std::snprintf(detail, sizeof(detail),
"registered_offline callback_unfired callback=0x%llx context=0x%llx",
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(stored_callback)),
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(stored_context)));
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
return ERROR_SUCCESS;
}
@@ -218,6 +268,8 @@ extern "C" {
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
if (reason == DLL_PROCESS_DETACH && reserved == nullptr) {
// reset() frees the slot table, so no stored callback or context
// outlives process teardown to be invoked against a dying image.
{
const SrwLockGuard guard(g_state.lock);
g_state.active.reset();
@@ -230,16 +282,18 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
return TRUE;
}
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
return register_notification(g_state, callback, out_reg, "RegisterAppStateChangeNotification");
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID context, PVOID* out_reg) {
return register_notification(g_state, callback, context, out_reg,
"RegisterAppStateChangeNotification");
}
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
}
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
return register_notification(g_constrained, callback, out_reg, "RegisterAppConstrainedChangeNotification");
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID context, PVOID* out_reg) {
return register_notification(g_constrained, callback, context, out_reg,
"RegisterAppConstrainedChangeNotification");
}
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID reg) {
+1
View File
@@ -1,5 +1,6 @@
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
xcrdapi.cpp
zlib_inflate.cpp
)
target_include_directories(xcrdapi PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/dstorage")
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32 uuid)
+3
View File
@@ -55,12 +55,15 @@ struct Request {
UINT compression;
ID3D12Resource* resource = nullptr;
UINT64 resource_offset = 0;
DWORD output_size = 0; // compression_zlib: bytes the stream inflates to at `destination`
};
inline constexpr UINT compression_none = 0;
inline constexpr UINT compression_lz = 1;
inline constexpr UINT compression_bcpack = 2;
inline constexpr UINT compression_gdeflate = 3;
// RFC 1950 zlib streams (Xbox DSTORAGE_REQUEST_OPTIONS.ZlibDecompress); decoded by zlib_inflate.cpp.
inline constexpr UINT compression_zlib = 4;
struct ErrorRecord {
HRESULT first_error;
+537 -16
View File
@@ -1,4 +1,5 @@
#include "synthetic_storage.h"
#include "zlib_inflate.h"
// Public PC DirectStorage contract: Microsoft.Direct3D.DirectStorage 1.4.0,
// MIT per file, vendored unmodified under dstorage/ (see dstorage/README.md).
@@ -8,6 +9,8 @@
#include <cstring>
#include <limits>
#include <new>
#include <mutex>
#include <atomic>
#include "bx_log.h"
@@ -415,7 +418,65 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
return staged.finish(win32_error());
}
HRESULT inflate_request(HANDLE file, const Request& request) {
if (!request.destination || !request.output_size || request.size >= request.output_size) return E_INVALIDARG;
auto* compressed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
if (!compressed) return E_OUTOFMEMORY;
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
if (SUCCEEDED(hr)) {
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
if (r != BxInflateResult::ok) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes to %lu bytes: %s", request.size,
request.output_size, bx_inflate_result_name(r));
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_zlib_failed", detail);
}
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
}
}
HeapFree(GetProcessHeap(), 0, compressed);
return hr;
}
CopyResult fulfill_request(HANDLE file, const Request& request);
// Diagnostics (off unless BX_DSTORAGE_TRACE=1): one line per memory-destination request with its
// destination range, sizes, file offset, result and the first 16 bytes written, up to 20000.
bool dstorage_trace_enabled() {
static const bool on = [] {
char value[8];
const DWORD n = GetEnvironmentVariableA("BX_DSTORAGE_TRACE", value, sizeof(value));
return n > 0 && n < sizeof(value) && value[0] == '1';
}();
return on;
}
CopyResult fulfill(HANDLE file, const Request& request) {
const CopyResult result = fulfill_request(file, request);
if (!dstorage_trace_enabled() || request.resource) return result;
static std::atomic<UINT> traced{0};
if (traced.fetch_add(1) >= 20000) return result;
const DWORD out = request.compression == compression_zlib ? request.output_size : request.size;
uint64_t head[2] = {0, 0};
if (SUCCEEDED(result.hr) && request.destination && out >= 16) std::memcpy(head, request.destination, 16);
char detail[220];
std::snprintf(detail, sizeof(detail), "dst=%p..%p out=%lu src=%lu offset=0x%llx compression=%u hr=0x%08lx head=%016llx %016llx",
request.destination, static_cast<const uint8_t*>(request.destination) + out, out, request.size,
static_cast<unsigned long long>(request.file_offset), request.compression,
static_cast<unsigned long>(result.hr), static_cast<unsigned long long>(head[0]),
static_cast<unsigned long long>(head[1]));
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request", detail);
return result;
}
CopyResult fulfill_request(HANDLE file, const Request& request) {
if (request.compression == compression_zlib) {
if (request.resource) return {E_NOTIMPL, false};
return {inflate_request(file, request), false};
}
if (request.compression) {
log_compression(request.compression);
return {E_NOTIMPL, false};
@@ -443,9 +504,12 @@ CopyResult fulfill(HANDLE file, const Request& request) {
}
// Each queue is drained serially, in FIFO order, by a single threadpool work item.
// A `blocking` queue makes a full enqueue wait for a free slot (submitting what is
// pending first) instead of failing with ERROR_BUSY. A non-zero `auto_submit`
// submits once that many entries are waiting. The public DirectStorage queues use
// A `blocking` queue makes a full enqueue wait for a free slot instead of failing
// with ERROR_BUSY. A non-zero `auto_submit` submits once that many entries are
// waiting, and a full queue submits what is pending before it waits. With
// `auto_submit` 0 (Xbox DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled) nothing runs
// before Submit: a full queue stalls the enqueuer until Submit is called on
// another thread and the drain frees a slot. The public DirectStorage queues use
// both; the BetterXen synthetic queues use neither.
class WorkQueue final : public Object<Queue, queue_iid> {
public:
@@ -471,7 +535,8 @@ public:
}
Entry entry{Kind::request, *request};
if (request->resource) request->resource->AddRef();
if (request->file && !request->compression) {
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
if (request->file && (request->compression == compression_none || request->compression == compression_zlib)) {
const HRESULT result = request->file->GetHandle(&entry.handle);
if (FAILED(result)) {
if (request->resource) request->resource->Release();
@@ -613,7 +678,7 @@ private:
if (closed_) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
if (size_ < capacity_) return S_OK;
if (!blocking_) return HRESULT_FROM_WIN32(ERROR_BUSY);
if (submitted_ < size_) submit();
if (auto_submit_ && submitted_ < size_) submit();
SleepConditionVariableSRW(&space_, &mutex_, INFINITE, 0);
}
}
@@ -913,6 +978,17 @@ bool reserved_fields_clear(const DSTORAGE_REQUEST_OPTIONS& options) {
// (the header: an empty queue reports capacity - 1 empty slots), and requests
// are submitted automatically once N / 2 are waiting (the header: "until the
// queue is half full").
// Maps the engine's command kind onto the header's DSTORAGE_COMMAND_TYPE for
// RetrieveErrorRecord on the public PC queue.
DSTORAGE_COMMAND_TYPE command_type(Kind kind) {
switch (kind) {
case Kind::status: return DSTORAGE_COMMAND_TYPE_STATUS;
case Kind::signal: return DSTORAGE_COMMAND_TYPE_SIGNAL;
case Kind::event: return DSTORAGE_COMMAND_TYPE_EVENT;
default: return DSTORAGE_COMMAND_TYPE_REQUEST;
}
}
class PublicQueue final : public PublicObject<IDStorageQueue4> {
public:
PublicQueue(WorkQueue* queue, const DSTORAGE_QUEUE_DESC1& desc) : queue_(queue), desc_(desc) {
@@ -1045,15 +1121,6 @@ private:
|| IsEqualIID(riid, __uuidof(IDStorageQueue4));
}
static DSTORAGE_COMMAND_TYPE command_type(Kind kind) {
switch (kind) {
case Kind::status: return DSTORAGE_COMMAND_TYPE_STATUS;
case Kind::signal: return DSTORAGE_COMMAND_TYPE_SIGNAL;
case Kind::event: return DSTORAGE_COMMAND_TYPE_EVENT;
default: return DSTORAGE_COMMAND_TYPE_REQUEST;
}
}
// Maps a DSTORAGE_REQUEST onto the engine's Request. Only uncompressed
// file/memory sources into memory or buffer destinations are supported.
HRESULT translate(const DSTORAGE_REQUEST* request, Request* out) const {
@@ -1264,11 +1331,459 @@ private:
return publish(wrapper, riid, ppv);
}
};
// ---------------------------------------------------------------------------
// Xbox Series DirectStorage COM interfaces (IDStorage*X), inferred from call-site
// observation of a project-authorized target build (provenance pending maintainer
// review; not a public contract), layered over the same WorkQueue / StorageFile /
// StatusArray engine. Unimplemented vtable slots log through BX_VTABLE_STUB_LOG
// so any newly reached slot surfaces immediately in bx-cli trace.
// ---------------------------------------------------------------------------
constexpr IID kXboxFactoryIid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
constexpr IID kXboxFileIid{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
constexpr IID kXboxStatusArrayIid{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
constexpr IID kXboxQueueIid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
struct XboxQueueDesc {
UINT64 source_type;
UINT16 capacity;
INT8 priority;
UINT8 reserved_pad[5];
PCSTR name;
UINT64 flags;
};
static_assert(sizeof(XboxQueueDesc) == 32, "XboxQueueDesc must be 32 bytes");
static_assert(offsetof(XboxQueueDesc, source_type) == 0x00, "source_type offset");
static_assert(offsetof(XboxQueueDesc, capacity) == 0x08, "capacity offset");
static_assert(offsetof(XboxQueueDesc, priority) == 0x0a, "priority offset");
static_assert(offsetof(XboxQueueDesc, name) == 0x10, "name offset");
static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
struct XboxRequest {
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
void* destination; // +0x08
UINT64 destination_pad; // +0x10
UINT32 destination_size; // +0x18
UINT32 reserved1c; // +0x1c
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
UINT64 file_offset; // +0x28
UINT32 source_size; // +0x30
UINT32 reserved34; // +0x34
};
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size offset");
static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
static_assert(offsetof(XboxRequest, source_size) == 0x30, "source_size offset");
// DSTORAGE_REQUEST_OPTIONS (authorized GDK documentation): ZlibDecompress:1, BcpackMode:4,
// SwizzleMode:16, DestinationIsPhysicalPages:1, SourceType:1, SourceIsPhysicalPages:1.
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull; // SourceType, bit 22
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull; // ZlibDecompress, bit 0
constexpr UINT64 kXboxRequestBcpackMask = 0xFull << 1;
constexpr UINT64 kXboxRequestSwizzleMask = 0xFFFFull << 5;
constexpr UINT64 kXboxRequestDestinationPagesBit = 1ull << 21;
constexpr UINT64 kXboxRequestSourcePagesBit = 1ull << 23;
// Logs each distinct option combination once, so a run shows which MDU stages a title uses.
void log_request_options(UINT64 options, UINT32 source_size, UINT32 destination_size, UINT32 intermediate_size) {
static std::mutex lock;
static UINT64 seen[64];
static size_t count = 0;
const UINT64 key = options & ~kXboxRequestSourceMemoryBit;
{
std::lock_guard<std::mutex> guard(lock);
for (size_t i = 0; i < count; ++i) {
if (seen[i] == key) return;
}
if (count < 64) seen[count++] = key;
}
char detail[200];
std::snprintf(detail, sizeof(detail),
"options=0x%llx zlib=%d bcpack_mode=%llu swizzle_mode=%llu dest_pages=%d source_memory=%d source_pages=%d "
"first sizes: source=%u destination=%u intermediate=%u",
static_cast<unsigned long long>(options), static_cast<int>(options & 1),
static_cast<unsigned long long>((options & kXboxRequestBcpackMask) >> 1),
static_cast<unsigned long long>((options & kXboxRequestSwizzleMask) >> 5),
(options & kXboxRequestDestinationPagesBit) ? 1 : 0, (options & kXboxRequestSourceMemoryBit) ? 1 : 0,
(options & kXboxRequestSourcePagesBit) ? 1 : 0, source_size, destination_size, intermediate_size);
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request_options", detail);
}
struct IXboxDStorageFile : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
};
struct IXboxDStorageStatusArray : IUnknown {
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
};
struct IXboxDStorageQueue : IUnknown {
virtual void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) = 0;
virtual void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) = 0;
virtual void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) = 0;
virtual void STDMETHODCALLTYPE Submit() = 0;
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(void* record) = 0;
virtual void STDMETHODCALLTYPE Query(void* info) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot13() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot14() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot15() = 0;
};
struct IXboxDStorageFactory : IUnknown {
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot11() = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
};
class XboxFile final : public PublicObject<IXboxDStorageFile> {
public:
explicit XboxFile(StorageFile* file) : file_(file) {}
void STDMETHODCALLTYPE Close() override { (void)file_->Close(); }
HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) override {
return file_->GetFileInformation(info);
}
HRESULT STDMETHODCALLTYPE StubSlot5() override {
BX_VTABLE_STUB_LOG("IDStorageFileX", 5u, "Slot5");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot6() override {
BX_VTABLE_STUB_LOG("IDStorageFileX", 6u, "Slot6");
return E_NOTIMPL;
}
File* inner() const { return file_; }
private:
~XboxFile() override { file_->Release(); }
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFileIid); }
StorageFile* file_;
};
class XboxStatusArray final : public PublicObject<IXboxDStorageStatusArray> {
public:
explicit XboxStatusArray(StatusArray* array) : array_(array) {}
bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return array_->GetResult(index) != E_PENDING; }
HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { return array_->GetResult(index); }
HRESULT STDMETHODCALLTYPE StubSlot5() override {
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 5u, "Slot5");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot6() override {
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 6u, "Slot6");
return E_NOTIMPL;
}
StatusArray* inner() const { return array_; }
private:
~XboxStatusArray() override { array_->Release(); }
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxStatusArrayIid); }
StatusArray* array_;
};
class XboxQueue final : public PublicObject<IXboxDStorageQueue> {
public:
XboxQueue(WorkQueue* queue, UINT64 source_type) : queue_(queue), source_type_(source_type) {}
void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) override {
if (!request) {
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
return;
}
const bool is_memory = (request->options & kXboxRequestSourceMemoryBit) != 0;
if ((is_memory && source_type_ == 0) || (!is_memory && source_type_ != 0)) {
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
return;
}
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
if (request->options & kXboxRequestBcpackMask) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
if (request->options & kXboxRequestSwizzleMask) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_swizzle");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
if (request->options & (kXboxRequestDestinationPagesBit | kXboxRequestSourcePagesBit)) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_pages");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
if (!request->destination || (zlib ? request->source_size >= request->destination_size
: request->source_size != request->destination_size)) {
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
return;
}
Request translated{};
translated.destination = request->destination;
translated.size = request->source_size;
if (zlib) {
translated.compression = compression_zlib;
translated.output_size = request->destination_size;
}
if (is_memory) {
if (!request->source_ptr) {
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
return;
}
translated.source = request->source_ptr;
} else {
auto* file = public_impl<XboxFile>(static_cast<IXboxDStorageFile*>(request->source_ptr));
if (!file) {
reject(E_DSTORAGE_FILE_NOT_OPEN, Kind::request, "EnqueueRequest");
return;
}
translated.file = file->inner();
translated.file_offset = request->file_offset;
}
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
}
void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) override {
auto* array = public_impl<XboxStatusArray>(status_array);
if (!array) {
reject(E_DSTORAGE_INVALID_STATUS_ARRAY, Kind::status, "EnqueueStatus");
return;
}
HRESULT hr = queue_->EnqueueStatus(array->inner(), index);
if (hr == E_INVALIDARG) hr = E_DSTORAGE_INDEX_BOUND;
accept(hr, Kind::status, "EnqueueStatus");
}
void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override {
if (!fence) {
reject(E_DSTORAGE_INVALID_FENCE, Kind::signal, "EnqueueSignal");
return;
}
accept(queue_->EnqueueSignal(fence, value), Kind::signal, "EnqueueSignal");
}
void STDMETHODCALLTYPE Submit() override {
if (FAILED(queue_->Submit())) {
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "Submit after Close; nothing submitted");
}
}
void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64, UINT64) override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 7u, "CancelRequestsWithTag");
}
void STDMETHODCALLTYPE Close() override { (void)queue_->Close(); }
HANDLE STDMETHODCALLTYPE GetErrorEvent() override { return queue_->error_event(); }
void STDMETHODCALLTYPE RetrieveErrorRecord(void*) override {
// The size and layout of the Xbox caller's output are unverified.
// Do not write the public PC record into it.
BX_VTABLE_STUB_LOG("IDStorageQueueX", 10u, "RetrieveErrorRecord");
}
void STDMETHODCALLTYPE Query(void*) override { BX_VTABLE_STUB_LOG("IDStorageQueueX", 11u, "Query"); }
HRESULT STDMETHODCALLTYPE StubSlot12() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 12u, "Slot12");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot13() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 13u, "Slot13");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot14() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 14u, "Slot14");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot15() override {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 15u, "Slot15");
return E_NOTIMPL;
}
private:
~XboxQueue() override { queue_->Release(); }
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxQueueIid); }
void reject(HRESULT hr, Kind kind, const char* method) {
char detail[96];
std::snprintf(detail, sizeof(detail), "xbox %s hr=0x%08lx", method, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_enqueue_rejected", detail);
if (FAILED(queue_->enqueue_failure(hr, kind))) {
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "enqueue after Close; command dropped");
}
}
void accept(HRESULT hr, Kind kind, const char* method) {
if (SUCCEEDED(hr)) return;
if (queue_->closed()) {
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "enqueue after Close; command dropped");
return;
}
reject(hr, kind, method);
}
WorkQueue* queue_;
UINT64 source_type_;
};
class XboxFactory final : public PublicObject<IXboxDStorageFactory> {
public:
HRESULT STDMETHODCALLTYPE CreateQueue(const void*, REFIID, void** ppv) override {
if (ppv) *ppv = nullptr;
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 3u, "CreateQueue");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (!path || !*path) return E_INVALIDARG;
HANDLE handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, nullptr);
if (handle == INVALID_HANDLE_VALUE) return win32_error();
auto* file = new (std::nothrow) StorageFile(handle);
if (!file) {
CloseHandle(handle);
return E_OUTOFMEMORY;
}
auto* wrapper = new (std::nothrow) XboxFile(file);
if (!wrapper) {
file->Release();
return E_OUTOFMEMORY;
}
return publish(wrapper, riid, ppv);
}
HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (!capacity || capacity > 65535) return E_INVALIDARG;
auto* slots = new (std::nothrow) StatusArray::Slot[capacity];
if (!slots) return E_OUTOFMEMORY;
auto* array = new (std::nothrow) StatusArray(slots, capacity);
if (!array) {
delete[] slots;
return E_OUTOFMEMORY;
}
auto* wrapper = new (std::nothrow) XboxStatusArray(array);
if (!wrapper) {
array->Release();
return E_OUTOFMEMORY;
}
return publish(wrapper, riid, ppv);
}
void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override {
if (flags) BX_VTABLE_STUB_LOG("IDStorageFactoryX", 6u, "SetDebugFlags");
}
HRESULT STDMETHODCALLTYPE StubSlot7() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 7u, "Slot7");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override {
char detail[80];
/* Like the public factory: the engine has no staging buffer to size. */
std::snprintf(detail, sizeof(detail), "xbox size=%lu has no effect", static_cast<unsigned long>(size));
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_staging_buffer_size", detail);
return S_OK;
}
HRESULT STDMETHODCALLTYPE StubSlot9() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 9u, "Slot9");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (!desc) return E_INVALIDARG;
if (desc->capacity < 2 || desc->capacity > DSTORAGE_MAX_QUEUE_CAPACITY) {
return E_DSTORAGE_INVALID_QUEUE_CAPACITY;
}
if (desc->source_type > 1) {
return E_DSTORAGE_INVALID_SOURCE_TYPE;
}
/* desc->priority is ignored on purpose: the Xbox priority range is not part of
* the inferred contract, so no value is rejected (the public queue's
* E_DSTORAGE_INVALID_QUEUE_PRIORITY range check is not assumed to apply). */
const UINT slots = desc->capacity - 1u;
auto* entries = new (std::nothrow) Entry[slots];
if (!entries) return E_OUTOFMEMORY;
// desc->flags is DSTORAGE_QUEUE_OPTIONS (authorized GDK documentation): bit 0,
// AutoSubmitDisabled, makes the queue wait for Submit. A title maps a request's
// destination pages after enqueueing it and before submitting, so starting work at half
// capacity wrote into pages that were not mapped yet.
constexpr UINT64 kAutoSubmitDisabled = 1;
const UINT auto_submit = (desc->flags & kAutoSubmitDisabled) ? 0u : desc->capacity / 2u;
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, auto_submit);
if (!queue) {
delete[] entries;
return E_OUTOFMEMORY;
}
char detail[128];
std::snprintf(detail, sizeof(detail), "xbox queue '%s' capacity=%u source=%llu auto_submit=%s",
desc->name ? desc->name : "", static_cast<unsigned>(desc->capacity),
static_cast<unsigned long long>(desc->source_type), auto_submit ? "half capacity" : "disabled");
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_queue", detail);
if (!queue->create_work()) {
const HRESULT error = win32_error();
queue->Release();
return error;
}
auto* wrapper = new (std::nothrow) XboxQueue(queue, desc->source_type);
if (!wrapper) {
queue->Release();
return E_OUTOFMEMORY;
}
return publish(wrapper, riid, ppv);
}
HRESULT STDMETHODCALLTYPE StubSlot11() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 11u, "Slot11");
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE StubSlot12() override {
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 12u, "Slot12");
return E_NOTIMPL;
}
private:
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFactoryIid); }
};
} // namespace
// Accepts BetterXen's synthetic factory IID and IUnknown (the synthetic factory),
// and the public PC IDStorageFactory / IDStorageFactory1. Any other IID is logged
// with its value so `bx-cli trace` names the interface a guest asked for.
// the public PC IDStorageFactory / IDStorageFactory1, and the inferred Xbox
// IDStorageFactoryX IID. Any other IID is logged with its value so `bx-cli trace`
// names the interface a guest asked for.
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
@@ -1276,6 +1791,12 @@ extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
auto* factory = new (std::nothrow) PublicFactory;
return factory ? publish(factory, riid, ppv) : E_OUTOFMEMORY;
}
if (IsEqualIID(riid, kXboxFactoryIid)) {
auto* factory = new (std::nothrow) XboxFactory;
if (!factory) return E_OUTOFMEMORY;
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_get_factory", "dispatch xbox_com=IDStorageFactoryX");
return publish(factory, riid, ppv);
}
if (!IsEqualIID(riid, factory_iid) && !IsEqualIID(riid, IID_IUnknown)) {
char iid[40];
format_iid(riid, iid);
+249
View File
@@ -0,0 +1,249 @@
/* zlib (RFC 1950) / deflate (RFC 1951) decoder; see zlib_inflate.h. */
#include "zlib_inflate.h"
namespace {
struct Bits {
const uint8_t* data;
size_t size;
size_t pos = 0; // next byte
uint32_t buffer = 0;
int count = 0; // valid bits in buffer
bool overrun = false;
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
uint32_t get(int n) {
while (count < n) {
if (pos >= size) {
overrun = true;
return 0;
}
buffer |= static_cast<uint32_t>(data[pos++]) << count;
count += 8;
}
const uint32_t value = buffer & ((n == 32) ? 0xFFFFFFFFu : ((1u << n) - 1u));
buffer >>= n;
count -= n;
return value;
}
void align_to_byte() {
buffer >>= (count & 7);
count -= (count & 7);
}
};
constexpr int kMaxBits = 15;
// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length and symbols sorted by code.
struct Huffman {
uint16_t counts[kMaxBits + 1] = {};
uint16_t symbols[320] = {};
// Returns false for an over-subscribed set of lengths. An incomplete set is allowed (a
// single distance code is legal), and decoding an unassigned code then fails.
bool build(const uint8_t* lengths, int n) {
for (int i = 0; i <= kMaxBits; ++i) counts[i] = 0;
for (int i = 0; i < n; ++i) ++counts[lengths[i]];
counts[0] = 0;
int left = 1;
for (int len = 1; len <= kMaxBits; ++len) {
left <<= 1;
left -= counts[len];
if (left < 0) return false;
}
uint16_t offsets[kMaxBits + 2] = {};
for (int len = 1; len <= kMaxBits; ++len) offsets[len + 1] = offsets[len] + counts[len];
for (int i = 0; i < n; ++i) {
if (lengths[i]) symbols[offsets[lengths[i]]++] = static_cast<uint16_t>(i);
}
return true;
}
// Huffman codes are packed most significant bit first, one bit at a time.
int decode(Bits& in) const {
int code = 0, first = 0, index = 0;
for (int len = 1; len <= kMaxBits; ++len) {
code |= static_cast<int>(in.get(1));
if (in.overrun) return -1;
const int count = counts[len];
if (code - first < count) return symbols[index + (code - first)];
index += count;
first += count;
first <<= 1;
code <<= 1;
}
return -1;
}
};
// RFC 1951 3.2.5 length and distance tables.
constexpr uint16_t kLengthBase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
constexpr uint8_t kLengthExtra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
struct Output {
uint8_t* data;
size_t size;
size_t pos = 0;
};
BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman& dist) {
for (;;) {
const int symbol = lit.decode(in);
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
if (symbol < 256) {
if (out.pos >= out.size) return BxInflateResult::output_mismatch;
out.data[out.pos++] = static_cast<uint8_t>(symbol);
continue;
}
if (symbol == 256) return BxInflateResult::ok;
const int li = symbol - 257;
if (li >= 29) return BxInflateResult::bad_data;
const size_t length = kLengthBase[li] + in.get(kLengthExtra[li]);
const int ds = dist.decode(in);
if (ds < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
if (ds >= 30) return BxInflateResult::bad_data;
const size_t distance = kDistBase[ds] + in.get(kDistExtra[ds]);
if (in.overrun) return BxInflateResult::truncated;
if (distance > out.pos) return BxInflateResult::bad_data;
if (length > out.size - out.pos) return BxInflateResult::output_mismatch;
for (size_t i = 0; i < length; ++i, ++out.pos) out.data[out.pos] = out.data[out.pos - distance];
}
}
BxInflateResult fixed_block(Bits& in, Output& out) {
static Huffman lit, dist;
static bool built = [] {
uint8_t lengths[288];
int i = 0;
for (; i < 144; ++i) lengths[i] = 8;
for (; i < 256; ++i) lengths[i] = 9;
for (; i < 280; ++i) lengths[i] = 7;
for (; i < 288; ++i) lengths[i] = 8;
lit.build(lengths, 288);
uint8_t dl[30];
for (int d = 0; d < 30; ++d) dl[d] = 5;
dist.build(dl, 30);
return true;
}();
(void)built;
return codes(in, out, lit, dist);
}
BxInflateResult dynamic_block(Bits& in, Output& out) {
const int hlit = static_cast<int>(in.get(5)) + 257;
const int hdist = static_cast<int>(in.get(5)) + 1;
const int hclen = static_cast<int>(in.get(4)) + 4;
if (in.overrun) return BxInflateResult::truncated;
if (hlit > 286 || hdist > 30) return BxInflateResult::bad_data;
static constexpr uint8_t kOrder[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
uint8_t lengths[320] = {};
for (int i = 0; i < hclen; ++i) lengths[kOrder[i]] = static_cast<uint8_t>(in.get(3));
if (in.overrun) return BxInflateResult::truncated;
Huffman code_lengths;
if (!code_lengths.build(lengths, 19)) return BxInflateResult::bad_data;
int index = 0;
while (index < hlit + hdist) {
int symbol = code_lengths.decode(in);
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
if (symbol < 16) {
lengths[index++] = static_cast<uint8_t>(symbol);
continue;
}
uint8_t value = 0;
int repeat;
if (symbol == 16) {
if (index == 0) return BxInflateResult::bad_data;
value = lengths[index - 1];
repeat = 3 + static_cast<int>(in.get(2));
} else if (symbol == 17) {
repeat = 3 + static_cast<int>(in.get(3));
} else {
repeat = 11 + static_cast<int>(in.get(7));
}
if (in.overrun) return BxInflateResult::truncated;
if (index + repeat > hlit + hdist) return BxInflateResult::bad_data;
while (repeat--) lengths[index++] = value;
}
if (lengths[256] == 0) return BxInflateResult::bad_data; // no end-of-block code
Huffman lit, dist;
if (!lit.build(lengths, hlit) || !dist.build(lengths + hlit, hdist)) return BxInflateResult::bad_data;
return codes(in, out, lit, dist);
}
uint32_t adler32(const uint8_t* data, size_t size) {
uint32_t a = 1, b = 0;
while (size) {
size_t chunk = size < 5552 ? size : 5552; // largest n with no 32-bit overflow before the modulo
size -= chunk;
while (chunk--) {
a += *data++;
b += a;
}
a %= 65521u;
b %= 65521u;
}
return (b << 16) | a;
}
} // namespace
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
const uint8_t cmf = input[0], flg = input[1];
if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) {
return BxInflateResult::bad_header;
}
Bits in{input + 2, input_size - 2};
Output out{output, output_size};
for (;;) {
const uint32_t final_block = in.get(1);
const uint32_t type = in.get(2);
if (in.overrun) return BxInflateResult::truncated;
BxInflateResult r;
if (type == 0) {
in.align_to_byte();
const uint32_t len = in.get(16), nlen = in.get(16);
if (in.overrun) return BxInflateResult::truncated;
if ((len ^ 0xFFFFu) != nlen) return BxInflateResult::bad_data;
// After aligning, the bit buffer is empty: copy straight from the byte stream.
if (len > in.size - in.pos) return BxInflateResult::truncated;
if (len > out.size - out.pos) return BxInflateResult::output_mismatch;
for (uint32_t i = 0; i < len; ++i) out.data[out.pos++] = in.data[in.pos++];
r = BxInflateResult::ok;
} else if (type == 1) {
r = fixed_block(in, out);
} else if (type == 2) {
r = dynamic_block(in, out);
} else {
return BxInflateResult::bad_data;
}
if (r != BxInflateResult::ok) return r;
if (final_block) break;
}
if (out.pos != out.size) return BxInflateResult::output_mismatch;
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
in.align_to_byte();
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
if (input_size - 2 - trailer < 4) return BxInflateResult::truncated;
const uint8_t* t = in.data + trailer;
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
(static_cast<uint32_t>(t[2]) << 8) | t[3];
return adler32(output, output_size) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
}
const char* bx_inflate_result_name(BxInflateResult result) {
switch (result) {
case BxInflateResult::ok: return "ok";
case BxInflateResult::bad_header: return "bad_header";
case BxInflateResult::bad_data: return "bad_data";
case BxInflateResult::truncated: return "truncated";
case BxInflateResult::output_mismatch: return "output_mismatch";
case BxInflateResult::bad_checksum: return "bad_checksum";
}
return "unknown";
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
/*
* A zlib stream decoder written from the public specifications: IETF RFC 1950 (the zlib
* wrapper and its Adler-32 check) and RFC 1951 (deflate: stored, fixed-Huffman and
* dynamic-Huffman blocks, 32 KiB window). No third-party code.
*
* Used for DirectStorage requests whose DSTORAGE_REQUEST_OPTIONS.ZlibDecompress bit is set
* (authorized GDK documentation: RFC 1950 streams, full 32 KiB window, compressed size smaller
* than the decompressed size).
*/
#include <cstddef>
#include <cstdint>
enum class BxInflateResult {
ok,
bad_header, // not an RFC 1950 header, or a preset dictionary is required
bad_data, // malformed deflate data
truncated, // the input ended before the final block
output_mismatch, // the stream does not produce exactly `output_size` bytes
bad_checksum, // Adler-32 of the output does not match the stream trailer
};
/* Decodes `input` into exactly `output_size` bytes at `output`. */
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size);
const char* bx_inflate_result_name(BxInflateResult result);
+1 -1
View File
@@ -1,4 +1,4 @@
bx_add_shim_dll(xg_xs xg_xs xg_xs.def
xg_xs.cpp
xg_xbox.cpp
)
target_link_libraries(xg_xs PRIVATE bx_runtime_veh kernel32)
-195
View File
@@ -1,195 +0,0 @@
#ifndef BETTERXEN_XG_TEXTURE_H
#define BETTERXEN_XG_TEXTURE_H
/*
* BetterXen M1 linear texture-address contract for xg_xs.dll.
*
* Field meanings follow the public D3D12 resource and footprint documents
* (D3D12_RESOURCE_DIMENSION, D3D12_SUBRESOURCE_FOOTPRINT, and
* D3D12_TEXTURE_DATA_PITCH_ALIGNMENT / D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT).
* Block-compressed footprint width and height are texels rounded up to the
* 4x4 block, the same rounding D3D12 uses for a copyable footprint.
* Format numbers are the public DXGI_FORMAT values. This is not the Xbox
* GDK XG interface and it is not an Xbox hardware result.
*/
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <stdint.h>
#include <dxgiformat.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Public D3D12_RESOURCE_DIMENSION values used by this shim. */
#define BX_XG_DIMENSION_BUFFER 1u
#define BX_XG_DIMENSION_TEXTURE1D 2u
#define BX_XG_DIMENSION_TEXTURE2D 3u
#define BX_XG_DIMENSION_TEXTURE3D 4u
/* Public D3D12 texture copy alignments, in bytes. */
#define BX_XG_LINEAR_PITCH_ALIGNMENT 256u
#define BX_XG_LINEAR_PLACEMENT_ALIGNMENT 512u
/* Public D3D12 texture size limits used as the acceptance cap. */
#define BX_XG_MAX_TEXTURE_EDGE 16384u
#define BX_XG_MAX_ARRAY_SLICES 2048u
/*
* Layout selectors for this shim. LINEAR is computed exactly.
* SW_64KB_S / D / R are named RDNA 2 tile modes reserved for M3. They are
* accepted by XGCreateTextureComputer and every layout or copy call on them
* returns E_NOTIMPL without writing an address.
* XGSuggestSwizzleMode never returns a tile mode. It returns LINEAR or NONE.
*/
typedef enum bx_xg_layout_mode {
BX_XG_LAYOUT_LINEAR = 0,
BX_XG_LAYOUT_SW_64KB_S = 1,
BX_XG_LAYOUT_SW_64KB_D = 2,
BX_XG_LAYOUT_SW_64KB_R = 3,
BX_XG_LAYOUT_NONE = 0xFFFFFFFFu
} bx_xg_layout_mode;
typedef struct bx_xg_sample_desc {
uint32_t count;
uint32_t quality;
} bx_xg_sample_desc;
typedef struct bx_xg_resource_desc {
uint32_t dimension;
uint32_t alignment; /* 0 or BX_XG_LINEAR_PLACEMENT_ALIGNMENT */
uint64_t width; /* texels */
uint32_t height; /* texels */
uint16_t depth_or_array_size;
uint16_t mip_levels; /* 0 selects the full chain, down to 1x1 */
uint32_t format; /* DXGI_FORMAT */
bx_xg_sample_desc sample_desc;
uint32_t layout; /* bx_xg_layout_mode */
uint32_t flags; /* must be 0 */
} bx_xg_resource_desc;
typedef struct bx_xg_subresource_footprint {
uint32_t format;
uint32_t width; /* texels, rounded up to the format block width */
uint32_t height; /* texels, rounded up to the format block height */
uint32_t depth;
uint32_t row_pitch; /* bytes, multiple of BX_XG_LINEAR_PITCH_ALIGNMENT */
} bx_xg_subresource_footprint;
typedef struct bx_xg_placed_footprint {
uint64_t offset;
bx_xg_subresource_footprint footprint;
/*
* Absolute byte just past this subresource's last payload byte:
* offset + (row_count - 1) * row_pitch + row_bytes.
* That is the D3D12 GetCopyableFootprints end. It does not include the
* last row's pitch padding or the 512-byte tail. The copy span of a
* GetResourceLayout call is layouts[last].copy_end - base_offset.
*/
uint64_t copy_end;
} bx_xg_placed_footprint;
/* {B7E4C8A1-6F2D-4C55-8A19-3D0E5F7B91C4} BetterXen IXGTextureAddressComputer */
static const GUID BX_IID_IXGTextureAddressComputer = {
0xB7E4C8A1u, 0x6F2Du, 0x4C55u, {0x8Au, 0x19u, 0x3Du, 0x0Eu, 0x5Fu, 0x7Bu, 0x91u, 0xC4u}};
/* Public COM IUnknown IID. */
static const GUID BX_IID_IUnknown = {
0x00000000u, 0x0000u, 0x0000u, {0xC0u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x46u}};
/*
* GetResourceLayout places every subresource at its absolute offset from
* base_offset, including subresources before first_subresource. total_bytes
* is the BetterXen allocation span: the 512-aligned end of the last requested
* subresource, measured from base_offset, so a partial range still covers the
* earlier subresources and a 1x1 RGBA8 texture reports 512. copy_end on each
* footprint is the separate D3D12-style copy span end described above.
*/
typedef struct bx_xg_texture_computer bx_xg_texture_computer;
typedef struct bx_xg_texture_computer_vtbl {
HRESULT(WINAPI* QueryInterface)(bx_xg_texture_computer* self, const GUID* riid, void** object);
ULONG(WINAPI* AddRef)(bx_xg_texture_computer* self);
ULONG(WINAPI* Release)(bx_xg_texture_computer* self);
HRESULT(WINAPI* GetResourceLayout)(
bx_xg_texture_computer* self,
uint32_t first_subresource,
uint32_t subresource_count,
uint64_t base_offset,
bx_xg_placed_footprint* layouts,
uint32_t* row_counts,
uint64_t* row_sizes_in_bytes,
uint64_t* total_bytes);
HRESULT(WINAPI* GetResourceSizeBytes)(bx_xg_texture_computer* self, uint64_t* size_bytes);
HRESULT(WINAPI* GetResourceBaseAlignmentBytes)(bx_xg_texture_computer* self, uint64_t* alignment_bytes);
HRESULT(WINAPI* GetMipLevelOffsetBytes)(
bx_xg_texture_computer* self,
uint32_t array_slice,
uint32_t mip_level,
uint64_t* offset_bytes);
HRESULT(WINAPI* GetTexelElementOffsetBytes)(
bx_xg_texture_computer* self,
uint32_t array_slice,
uint32_t mip_level,
uint32_t x,
uint32_t y,
uint32_t z,
uint64_t* offset_bytes);
HRESULT(WINAPI* CopyIntoSubresource)(
bx_xg_texture_computer* self,
void* destination,
uint64_t destination_size,
uint32_t subresource,
const void* source,
uint64_t source_size,
uint32_t source_row_pitch,
uint32_t source_depth_pitch);
HRESULT(WINAPI* CopyFromSubresource)(
bx_xg_texture_computer* self,
void* destination,
uint64_t destination_size,
uint32_t destination_row_pitch,
uint32_t destination_depth_pitch,
const void* source,
uint64_t source_size,
uint32_t subresource);
} bx_xg_texture_computer_vtbl;
struct bx_xg_texture_computer {
const bx_xg_texture_computer_vtbl* lpVtbl;
};
/*
* On success, *computer is an IXGTextureAddressComputer with a reference
* count of 1. On failure, *computer is NULL when computer itself is non-NULL.
* Subresource index is mip_level + array_slice * mip_levels.
* A row pitch of 0 on a copy selects the tight logical row size.
*/
HRESULT WINAPI XGCreateTextureComputer(const bx_xg_resource_desc* desc, void** computer);
/*
* Returns BX_XG_LAYOUT_LINEAR when this shim can lay the texture out, and
* BX_XG_LAYOUT_NONE otherwise. The same arguments always return the same mode.
*/
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);
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_XG_TEXTURE_H */
+683
View File
@@ -0,0 +1,683 @@
/*
* The XG texture-address contract as titles call it (authorized GDK documentation, xg_xs.h):
* XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**) and
* XGSuggestSwizzleMode(const XG_RESOURCE_DESC*, flags, XG_TEXTURE_LAYOUT*). Only the structure
* layouts, enum values and the method order are taken from there; no header text is reproduced.
*
* The layout this computer reports is BetterXen's, not the console's: every texture is laid out
* linearly (swizzle mode LINEAR), mip-major (each mip holds all of its array or depth slices),
* rows aligned to 256 bytes, mips to 512 bytes, the resource to 64 KB. Depth-stencil formats
* get a separate depth plane and stencil plane. Every method uses the same layout, so sizes,
* offsets, texel addresses and copies agree with each other. Data a title stores pre-tiled for
* the console's swizzle modes is not detiled by this layer.
*
* The one exception is an explicit request for XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S on a 2D
* texture that fits in one 64 KiB tile (one mip, one slice, 4-, 8- or 16-byte elements): that
* gets the RDNA 2 SW_64KB_S addresses (see Sw64kbS). Any other explicit swizzle mode, and
* SW_64KB_S on a texture larger than one tile, is laid out linearly, reported as LINEAR
* (SwizzleMode 0) and logged once per mode: titles do not check XGCreateTextureComputer for a
* mode they request, so refusing it crashed one.
*/
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <dxgiformat.h>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <new>
#include "bx_log.h"
namespace {
// --- XG types (layouts from xg_xs.h) -------------------------------------------------------
enum : uint32_t {
kDimBuffer = 1,
kDimTexture1D = 2,
kDimTexture2D = 3,
kDimTexture3D = 4,
};
// XG_TEXTURE_LAYOUT: 0 default (XG chooses), 1 row major, 2 64 KB with an undefined swizzle, or
// 0x100 | XG_SWIZZLE_MODE to request one swizzle mode.
constexpr uint32_t kLayoutSwizzleFlag = 0x100;
constexpr uint32_t kLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
constexpr uint32_t kSwizzleModeLinear = 0;
constexpr uint32_t kSwizzleMode64KbS = 9; // XG_SWIZZLE_MODE_64KB_S
enum : uint32_t { kPlaneUnused = 0, kPlaneDefault = 1, kPlaneDepth = 7, kPlaneStencil = 8 };
// --- RDNA 2 SW_64KB_S (clean-room, ported from the earlier xg_xs.cpp) ---------------------
// Within one 64 KiB tile, the byte offset of element (x, y) is pdep(x, x_mask) | pdep(y, y_mask),
// x and y in elements (texels, or 4x4 blocks for BC). The masks come from the public AddrLib RB+
// pattern tables (GFX10_SW_64K_S_RBPLUS_PATINFO, MIT); at 4 bytes per element the x mask equals
// the public D3D12 standard-swizzle xBytesMask 0xAA8F without its two intra-texel bits, and the y
// mask equals D3D12's 0x5570. Each row is a bijection over its tile. How tiles are ordered across a
// larger surface is not established from public sources, so only surfaces that fit in one tile
// are addressed; larger ones fall back to the logged linear layout.
struct Sw64kbS {
uint32_t bytes;
uint32_t x_mask;
uint32_t y_mask;
uint32_t tile_x; // elements per tile row
uint32_t tile_y; // element rows per tile
};
bool sw64kb_s_params(uint32_t bytes, Sw64kbS* out) {
switch (bytes) {
case 4: *out = {4, 0xAA8Cu, 0x5570u, 128, 128}; return true;
case 8: *out = {8, 0xAAC8u, 0x5530u, 128, 64}; return true;
case 16: *out = {16, 0xAAC0u, 0x5530u, 64, 64}; return true;
default: return false;
}
}
uint32_t pdep(uint32_t value, uint32_t mask) {
uint32_t out = 0;
for (uint32_t bit = 1; mask; bit <<= 1) {
const uint32_t lowest = mask & (0u - mask);
if (value & bit) out |= lowest;
mask ^= lowest;
}
return out;
}
uint32_t pext(uint32_t value, uint32_t mask) {
uint32_t out = 0;
for (uint32_t bit = 1; mask; bit <<= 1) {
const uint32_t lowest = mask & (0u - mask);
if (value & lowest) out |= bit;
mask ^= lowest;
}
return out;
}
constexpr uint64_t kTileBytes = 64 * 1024;
struct XgSampleDesc {
UINT Count;
UINT Quality;
};
struct XgResourceDesc {
uint32_t Dimension;
UINT64 Alignment;
UINT64 Width;
UINT Height;
UINT16 DepthOrArraySize;
UINT16 MipLevels;
uint32_t Format;
XgSampleDesc SampleDesc;
uint32_t Layout;
uint32_t MiscFlags;
};
struct XgMipLevelLayout {
UINT64 SizeBytes;
UINT64 OffsetBytes;
UINT64 Slice2DSizeBytes;
UINT32 PitchPixels;
UINT32 PitchBytes;
UINT32 AlignmentBytes;
UINT32 PaddedWidthElements;
UINT32 PaddedHeightElements;
UINT32 PaddedDepthOrArraySize;
UINT32 WidthElements;
UINT32 HeightElements;
UINT32 WidthPixels;
UINT32 HeightPixels;
UINT32 DepthOrArraySize;
UINT32 SampleCount;
uint32_t SwizzleMode;
UINT64 BankRotationAddressBitMask;
UINT64 BankRotationBytesPerSlice;
UINT32 SliceDepthElements;
UINT32 IsMipTail;
UINT32 MipTailOffsetElementsX : 11;
UINT32 MipTailOffsetElementsY : 11;
UINT32 MipTailOffsetElementsZ : 10;
};
constexpr int kMaxMips = 15;
constexpr int kMaxPlanes = 4;
struct XgPlaneLayout {
uint32_t Usage;
UINT64 SizeBytes;
UINT64 SliceSizeBytes;
UINT64 BaseOffsetBytes;
UINT64 BaseAlignmentBytes;
UINT32 BytesPerElement;
UINT32 StandardMipCount;
UINT32 MipTailMipCount;
XgMipLevelLayout MipLayout[kMaxMips];
};
struct XgResourceLayout {
UINT64 SizeBytes;
UINT64 BaseAlignmentBytes;
UINT32 MipLevels;
UINT32 Planes;
XgPlaneLayout Plane[kMaxPlanes];
uint32_t Dimension;
};
// Pinned against the layouts derived from the GDK header (natural x64 alignment).
static_assert(sizeof(XgResourceDesc) == 56, "XG_RESOURCE_DESC size");
static_assert(offsetof(XgResourceDesc, Alignment) == 8 && offsetof(XgResourceDesc, Width) == 16, "XG_RESOURCE_DESC");
static_assert(sizeof(XgMipLevelLayout) == 112, "XG_MIPLEVEL_LAYOUT size");
static_assert(offsetof(XgPlaneLayout, MipLayout) == 56 && sizeof(XgPlaneLayout) == 1736, "XG_PLANE_LAYOUT size");
static_assert(offsetof(XgResourceLayout, Plane) == 24 && sizeof(XgResourceLayout) == 6976, "XG_RESOURCE_LAYOUT size");
struct XgPackedMipDesc {
UINT8 NumStandardMips;
UINT8 NumPackedMips;
UINT32 NumTilesForPackedMips;
UINT32 StartTileIndexInOverallResource;
};
struct XgTileShape {
UINT32 WidthInTexels;
UINT32 HeightInTexels;
UINT32 DepthInTexels;
};
struct XgSubresourceTiling {
UINT32 WidthInTiles;
UINT16 HeightInTiles;
UINT16 DepthInTiles;
UINT32 StartTileIndexInOverallResource;
};
// --- Formats -------------------------------------------------------------------------------
struct FormatInfo {
uint32_t block; // texels per element edge: 1, or 4 for block compression
uint32_t bytes; // bytes per element
uint32_t stencil; // 1 when the format carries a stencil plane
};
bool format_info(uint32_t f, FormatInfo* out) {
auto set = [&](uint32_t block, uint32_t bytes, uint32_t stencil = 0) {
*out = {block, bytes, stencil};
return true;
};
if (f >= DXGI_FORMAT_R32G32B32A32_TYPELESS && f <= DXGI_FORMAT_R32G32B32A32_SINT) return set(1, 16);
if (f >= DXGI_FORMAT_R32G32B32_TYPELESS && f <= DXGI_FORMAT_R32G32B32_SINT) return set(1, 12);
if (f >= DXGI_FORMAT_R16G16B16A16_TYPELESS && f <= DXGI_FORMAT_R32G32_SINT) return set(1, 8);
if (f >= DXGI_FORMAT_R32G8X24_TYPELESS && f <= DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) return set(1, 4, 1);
if (f >= DXGI_FORMAT_R10G10B10A2_TYPELESS && f <= DXGI_FORMAT_R32_SINT) return set(1, 4);
if (f >= DXGI_FORMAT_R24G8_TYPELESS && f <= DXGI_FORMAT_X24_TYPELESS_G8_UINT) return set(1, 4, 1);
if (f >= DXGI_FORMAT_R8G8_TYPELESS && f <= DXGI_FORMAT_R16_SINT) return set(1, 2);
if (f >= DXGI_FORMAT_R8_TYPELESS && f <= DXGI_FORMAT_A8_UNORM) return set(1, 1);
if (f == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || f == DXGI_FORMAT_R8G8_B8G8_UNORM || f == DXGI_FORMAT_G8R8_G8B8_UNORM) return set(1, 4);
if ((f >= DXGI_FORMAT_BC1_TYPELESS && f <= DXGI_FORMAT_BC1_UNORM_SRGB) ||
(f >= DXGI_FORMAT_BC4_TYPELESS && f <= DXGI_FORMAT_BC4_SNORM)) {
return set(4, 8);
}
if ((f >= DXGI_FORMAT_BC2_TYPELESS && f <= DXGI_FORMAT_BC3_UNORM_SRGB) ||
(f >= DXGI_FORMAT_BC5_TYPELESS && f <= DXGI_FORMAT_BC5_SNORM) ||
(f >= DXGI_FORMAT_BC6H_TYPELESS && f <= DXGI_FORMAT_BC7_UNORM_SRGB)) {
return set(4, 16);
}
if (f >= DXGI_FORMAT_B5G6R5_UNORM && f <= DXGI_FORMAT_B5G5R5A1_UNORM) return set(1, 2);
if (f >= DXGI_FORMAT_B8G8R8A8_UNORM && f <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return set(1, 4);
if (f == DXGI_FORMAT_B4G4R4A4_UNORM) return set(1, 2);
return false;
}
uint64_t align_up(uint64_t v, uint64_t a) { return (v + a - 1) / a * a; }
uint32_t mip_extent(uint64_t base, uint32_t mip) {
const uint64_t v = base >> mip;
return v ? static_cast<uint32_t>(v) : 1u;
}
constexpr uint64_t kRowAlign = 256;
constexpr uint64_t kMipAlign = 512;
constexpr uint64_t kResourceAlign = 64 * 1024;
void log_rejected(const XgResourceDesc* d, const char* why) {
char detail[200];
std::snprintf(detail, sizeof(detail), "%s: dim=%u width=%llu height=%u depth_or_array=%u mips=%u format=%u samples=%u layout=0x%x",
why, d->Dimension, static_cast<unsigned long long>(d->Width), d->Height, d->DepthOrArraySize,
d->MipLevels, d->Format, d->SampleDesc.Count, d->Layout);
bx_log_emit(BX_LOG_WARN, "xg_xs", "texture_computer_rejected", detail);
}
// A requested swizzle mode this layer does not implement: laid out (and reported) linearly; the
// first request for each mode is logged, with the description.
void log_linear_instead(const XgResourceDesc* d) {
static std::atomic<uint32_t> seen[32];
const uint32_t mode = d->Layout & 0x1F;
if (seen[mode].exchange(1)) return;
log_rejected(d, "requested swizzle mode is not implemented; laid out and reported as LINEAR");
}
// --- The computer ---------------------------------------------------------------------------
class XGTextureAddressComputer {
public:
virtual ULONG AddRef() = 0;
virtual ULONG Release() = 0;
virtual HRESULT GetResourceLayout(XgResourceLayout* layout) = 0;
virtual UINT64 GetResourceSizeBytes() = 0;
virtual UINT64 GetResourceBaseAlignmentBytes() = 0;
virtual UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) = 0;
virtual UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z_or_slice,
UINT32 sample, UINT32* bit_position) = 0;
virtual HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y,
UINT32* z_or_slice, UINT32* sample) = 0;
virtual HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear,
UINT32 row_pitch, UINT32 slice_pitch) = 0;
virtual HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
const void* base, UINT32 row_pitch, UINT32 slice_pitch) = 0;
virtual HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape,
UINT32* subresource_count, UINT32 first_subresource,
XgSubresourceTiling* tilings) = 0;
virtual HRESULT GetTextureViewDescriptor(UINT32 plane, void* descriptor) = 0;
virtual bool IsTiledResource() = 0;
virtual HRESULT GetSwizzlePatternInfo(UINT32 plane, void* info) = 0;
};
class LayoutComputer final : public XGTextureAddressComputer {
public:
static HRESULT create(const XgResourceDesc& desc, XGTextureAddressComputer** out);
ULONG AddRef() override { return ++refs_; }
ULONG Release() override {
const ULONG left = --refs_;
if (!left) delete this;
return left;
}
HRESULT GetResourceLayout(XgResourceLayout* layout) override {
if (!layout) return E_POINTER;
*layout = layout_;
return S_OK;
}
UINT64 GetResourceSizeBytes() override { return layout_.SizeBytes; }
UINT64 GetResourceBaseAlignmentBytes() override { return layout_.BaseAlignmentBytes; }
UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) override {
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
return layout_.Plane[plane].MipLayout[mip].OffsetBytes;
}
UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z, UINT32 sample,
UINT32* bit_position) override {
if (bit_position) *bit_position = 0;
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
const XgPlaneLayout& p = layout_.Plane[plane];
const XgMipLevelLayout& m = p.MipLayout[mip];
const uint64_t ex = x / block_, ey = y / block_;
if (swizzled_) {
if (ex >= sw_.tile_x || ey >= sw_.tile_y) return 0;
return m.OffsetBytes + element_offset(static_cast<uint32_t>(ex), static_cast<uint32_t>(ey));
}
return m.OffsetBytes + z * m.Slice2DSizeBytes + ey * m.PitchBytes +
(ex * m.SampleCount + sample) * p.BytesPerElement;
}
HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y, UINT32* z,
UINT32* sample) override {
for (UINT32 pi = 0; pi < layout_.Planes; ++pi) {
const XgPlaneLayout& p = layout_.Plane[pi];
for (UINT32 mi = 0; mi < layout_.MipLevels; ++mi) {
const XgMipLevelLayout& m = p.MipLayout[mi];
if (offset < m.OffsetBytes || offset >= m.OffsetBytes + m.SizeBytes) continue;
const uint64_t rel = offset - m.OffsetBytes;
if (swizzled_) {
const uint32_t in_tile = static_cast<uint32_t>(rel);
if (plane) *plane = pi;
if (mip) *mip = mi;
if (z) *z = 0;
if (y) *y = pext(in_tile, sw_.y_mask) * block_;
if (x) *x = static_cast<UINT64>(pext(in_tile, sw_.x_mask)) * block_;
if (sample) *sample = 0;
return S_OK;
}
const uint64_t in_slice = rel % m.Slice2DSizeBytes;
const uint64_t element = (in_slice % m.PitchBytes) / p.BytesPerElement;
if (plane) *plane = pi;
if (mip) *mip = mi;
if (z) *z = static_cast<UINT32>(rel / m.Slice2DSizeBytes);
if (y) *y = static_cast<UINT32>(in_slice / m.PitchBytes * block_);
if (x) *x = element / m.SampleCount * block_;
if (sample) *sample = static_cast<UINT32>(element % m.SampleCount);
return S_OK;
}
}
return E_INVALIDARG;
}
HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear, UINT32 row_pitch,
UINT32 slice_pitch) override {
return copy(static_cast<uint8_t*>(base), plane, subresource, static_cast<const uint8_t*>(linear), row_pitch,
slice_pitch, true);
}
HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32, const void* base,
UINT32 row_pitch, UINT32 slice_pitch) override {
return copy(static_cast<uint8_t*>(const_cast<void*>(base)), plane, subresource, static_cast<uint8_t*>(linear),
row_pitch, slice_pitch, false);
}
HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape, UINT32* count,
UINT32 first, XgSubresourceTiling* tilings) override {
// D3D12 standard 64 KB tiles (the public D3D12 tiled-resource rules): the tile shape follows
// the element size (256x256 one-byte elements down to 64x64 sixteen-byte ones, in blocks for
// block-compressed formats). Leading mips at least one tile wide and high are standard; the
// smaller rest are packed into a mip tail per array slice, as on the console, whose titles
// expect few standard mips. Tiles are numbered over the subresources in order (mip-major
// within a slice), each slice's packed tail after its standard mips.
// 3D resources use the D3D12 standard 3D tile shapes (64x32x32 one-byte elements down to
// 16x16x16 sixteen-byte ones), 1D textures a 64 KiB row of elements, buffers 64 KiB.
const uint32_t bpe = layout_.Plane[0].BytesPerElement;
const bool volume = layout_.Dimension == kDimTexture3D;
uint32_t tile_w = 128, tile_h = 128, tile_d = 1;
if (layout_.Dimension == kDimBuffer) {
tile_w = 65536;
tile_h = 1;
} else if (layout_.Dimension == kDimTexture1D) {
tile_w = 65536 / (bpe ? bpe : 1) * block_;
tile_h = 1;
} else if (volume) {
switch (bpe) {
case 1: tile_w = 64; tile_h = 32; tile_d = 32; break;
case 2: tile_w = 32; tile_h = 32; tile_d = 32; break;
case 4: tile_w = 32; tile_h = 32; tile_d = 16; break;
case 8: tile_w = 32; tile_h = 16; tile_d = 16; break;
case 16: tile_w = 16; tile_h = 16; tile_d = 16; break;
default: tile_w = 32; tile_h = 32; tile_d = 16; break;
}
tile_w *= block_;
tile_h *= block_;
} else {
switch (bpe) {
case 1: tile_w = 256; tile_h = 256; break;
case 2: tile_w = 256; tile_h = 128; break;
case 4: tile_w = 128; tile_h = 128; break;
case 8: tile_w = 128; tile_h = 64; break;
case 16: tile_w = 64; tile_h = 64; break;
default: break;
}
tile_w *= block_;
tile_h *= block_;
}
auto depth_of = [&](UINT32 m) { return volume ? layout_.Plane[0].MipLayout[m].DepthOrArraySize : 1u; };
const UINT32 mips = layout_.MipLevels;
UINT32 standard = 0;
while (standard < mips && layout_.Plane[0].MipLayout[standard].WidthPixels >= tile_w &&
layout_.Plane[0].MipLayout[standard].HeightPixels >= tile_h && depth_of(standard) >= tile_d) {
++standard;
}
uint64_t tail_bytes = 0;
for (UINT32 m = standard; m < mips; ++m) {
tail_bytes += volume ? layout_.Plane[0].MipLayout[m].SizeBytes : layout_.Plane[0].MipLayout[m].Slice2DSizeBytes;
}
const UINT32 tail_tiles = standard < mips ? static_cast<UINT32>((tail_bytes + kResourceAlign - 1) / kResourceAlign) : 0;
auto tiles_of = [&](UINT32 m) {
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
return ((l.WidthPixels + tile_w - 1) / tile_w) * ((l.HeightPixels + tile_h - 1) / tile_h) *
((depth_of(m) + tile_d - 1) / tile_d);
};
UINT32 per_slice = tail_tiles;
for (UINT32 m = 0; m < standard; ++m) per_slice += tiles_of(m);
if (total_tiles) *total_tiles = per_slice * slices_;
UINT32 standard_tiles = 0;
for (UINT32 m = 0; m < standard; ++m) standard_tiles += tiles_of(m);
if (packed) {
*packed = {static_cast<UINT8>(standard), static_cast<UINT8>(mips - standard), tail_tiles,
standard < mips ? standard_tiles : 0};
}
if (shape) *shape = {tile_w, tile_h, tile_d};
if (count) {
const UINT32 total = mips * slices_;
UINT32 written = 0;
for (UINT32 i = first; i < total && written < *count && tilings; ++i, ++written) {
const UINT32 m = i % mips, slice = i / mips;
if (m >= standard) {
tilings[written] = {0, 0, 0, 0xFFFFFFFFu}; // packed: no tiling of its own
continue;
}
UINT32 start = slice * per_slice;
for (UINT32 k = 0; k < m; ++k) start += tiles_of(k);
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
tilings[written] = {(l.WidthPixels + tile_w - 1) / tile_w,
static_cast<UINT16>((l.HeightPixels + tile_h - 1) / tile_h),
static_cast<UINT16>((depth_of(m) + tile_d - 1) / tile_d), start};
}
*count = written;
}
return S_OK;
}
HRESULT GetTextureViewDescriptor(UINT32, void*) override {
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetTextureViewDescriptor");
return E_NOTIMPL;
}
bool IsTiledResource() override { return false; }
HRESULT GetSwizzlePatternInfo(UINT32, void*) override {
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetSwizzlePatternInfo");
return E_NOTIMPL;
}
private:
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, uint8_t* linear_rw, UINT32 row_pitch,
UINT32 slice_pitch, bool into) {
return copy(tiled, plane, subresource, static_cast<const uint8_t*>(linear_rw), row_pitch, slice_pitch, into,
linear_rw);
}
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, const uint8_t* linear, UINT32 row_pitch,
UINT32 slice_pitch, bool into, uint8_t* linear_out = nullptr) {
if (!tiled || !linear || plane >= layout_.Planes) return E_INVALIDARG;
const UINT32 mip = subresource % layout_.MipLevels;
const UINT32 slice = subresource / layout_.MipLevels;
const XgPlaneLayout& p = layout_.Plane[plane];
const XgMipLevelLayout& m = p.MipLayout[mip];
const bool volume = layout_.Dimension == kDimTexture3D;
if (slice >= slices_) return E_INVALIDARG; // slices_ is 1 for a volume: its subresources are its mips
const UINT32 depth = volume ? m.DepthOrArraySize : 1;
if (swizzled_) { // one 2D tile, one mip, one slice: element by element
if (subresource != 0) return E_INVALIDARG;
for (UINT32 row = 0; row < m.HeightElements; ++row) {
for (UINT32 col = 0; col < m.WidthElements; ++col) {
uint8_t* t = tiled + m.OffsetBytes + element_offset(col, row);
const uint64_t lin = static_cast<uint64_t>(row) * row_pitch + static_cast<uint64_t>(col) * sw_.bytes;
if (into) std::memcpy(t, linear + lin, sw_.bytes);
else std::memcpy(linear_out + lin, t, sw_.bytes);
}
}
return S_OK;
}
const uint64_t row_bytes = static_cast<uint64_t>(m.WidthElements) * m.SampleCount * p.BytesPerElement;
for (UINT32 z = 0; z < depth; ++z) {
uint8_t* dst_slice = tiled + m.OffsetBytes + (volume ? z : slice) * m.Slice2DSizeBytes;
for (UINT32 row = 0; row < m.HeightElements; ++row) {
uint8_t* t = dst_slice + static_cast<uint64_t>(row) * m.PitchBytes;
const uint64_t lin = static_cast<uint64_t>(z) * slice_pitch + static_cast<uint64_t>(row) * row_pitch;
if (into) std::memcpy(t, linear + lin, row_bytes);
else std::memcpy(linear_out + lin, t, row_bytes);
}
}
return S_OK;
}
uint32_t element_offset(uint32_t ex, uint32_t ey) const { return pdep(ex, sw_.x_mask) | pdep(ey, sw_.y_mask); }
XgResourceLayout layout_{};
uint32_t block_ = 1;
uint32_t slices_ = 1;
bool swizzled_ = false; // SW_64KB_S, one tile (see Sw64kbS)
Sw64kbS sw_{};
std::atomic<ULONG> refs_{1};
};
HRESULT LayoutComputer::create(const XgResourceDesc& d, XGTextureAddressComputer** out) {
FormatInfo fi{1, 1, 0};
const bool buffer = d.Dimension == kDimBuffer;
if (!buffer && !format_info(d.Format, &fi)) {
log_rejected(&d, "format not in the BetterXen XG table");
return E_INVALIDARG;
}
if (d.Dimension < kDimBuffer || d.Dimension > kDimTexture3D || d.Width == 0) {
log_rejected(&d, "invalid description");
return E_INVALIDARG;
}
// The public D3D12 resource limits (D3D12_REQ_TEXTURE1D/2D_U_DIMENSION 16384,
// D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION 2048, D3D12_REQ_TEXTURE1D/2D_ARRAY_AXIS_DIMENSION
// 2048). Within them every pitch fits 32 bits and no size computation overflows. A buffer
// only needs its 64 KiB-aligned size to fit 64 bits.
{
const bool volume = d.Dimension == kDimTexture3D;
const uint64_t max_xy = volume ? 2048 : 16384;
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : d.Height;
const bool too_big = buffer ? d.Width > UINT64_MAX - kResourceAlign
: d.Width > max_xy || height > max_xy || d.DepthOrArraySize > 2048;
if (too_big) {
log_rejected(&d, "dimension past the D3D12 resource limits");
return E_INVALIDARG;
}
}
auto* c = new (std::nothrow) LayoutComputer();
if (!c) return E_OUTOFMEMORY;
XgResourceLayout& L = c->layout_;
L.Dimension = d.Dimension;
L.BaseAlignmentBytes = d.Alignment > kResourceAlign ? d.Alignment : kResourceAlign;
if (buffer) {
L.MipLevels = 1;
L.Planes = 1;
XgPlaneLayout& p = L.Plane[0];
p.Usage = kPlaneDefault;
p.BytesPerElement = 1;
p.StandardMipCount = 1;
p.SizeBytes = p.SliceSizeBytes = d.Width;
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
XgMipLevelLayout& m = p.MipLayout[0];
m.SizeBytes = m.Slice2DSizeBytes = d.Width;
m.PitchBytes = static_cast<UINT32>(d.Width > UINT32_MAX ? UINT32_MAX : d.Width);
m.WidthElements = m.WidthPixels = m.PitchPixels = m.PaddedWidthElements = m.PitchBytes;
m.HeightElements = m.HeightPixels = m.PaddedHeightElements = 1;
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
m.AlignmentBytes = static_cast<UINT32>(kRowAlign);
L.SizeBytes = align_up(d.Width, kResourceAlign);
*out = c;
return S_OK;
}
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : (d.Height ? d.Height : 1);
const uint32_t depth_or_array = d.DepthOrArraySize ? d.DepthOrArraySize : 1;
uint32_t full = 1;
for (uint64_t w = d.Width, h = height, z = d.Dimension == kDimTexture3D ? depth_or_array : 1; w > 1 || h > 1 || z > 1;
w >>= 1, h >>= 1, z >>= 1) {
++full;
}
uint32_t mips = d.MipLevels ? d.MipLevels : full;
if (mips > full) mips = full;
if (mips > kMaxMips) {
log_rejected(&d, "more than 15 mip levels");
delete c;
return E_INVALIDARG;
}
const uint32_t samples = d.SampleDesc.Count ? d.SampleDesc.Count : 1;
c->block_ = fi.block;
c->slices_ = d.Dimension == kDimTexture3D ? 1 : depth_or_array;
// Default, row-major and undefined-swizzle requests leave the choice to XG: BetterXen picks
// linear and reports it. A request for SW_64KB_S on one 2D tile gets that layout. Any other
// requested swizzle mode is laid out linearly and reported as LINEAR (titles do not expect
// XGCreateTextureComputer to fail for a mode they ask for); each such mode is logged once.
const uint32_t width_el = static_cast<uint32_t>((d.Width + fi.block - 1) / fi.block);
const uint32_t height_el = (height + fi.block - 1) / fi.block;
Sw64kbS sw{};
const bool requested = (d.Layout & kLayoutSwizzleFlag) && d.Layout != kLayoutSwizzleLinear;
const bool single_tile_s = d.Layout == (kLayoutSwizzleFlag | kSwizzleMode64KbS) && d.Dimension == kDimTexture2D &&
mips == 1 && depth_or_array == 1 && samples == 1 && !fi.stencil &&
sw64kb_s_params(fi.bytes, &sw) && width_el <= sw.tile_x && height_el <= sw.tile_y;
if (requested && !single_tile_s) log_linear_instead(&d);
if (single_tile_s) {
c->swizzled_ = true;
c->sw_ = sw;
L.MipLevels = 1;
L.Planes = 1;
L.BaseAlignmentBytes = d.Alignment > kTileBytes ? d.Alignment : kTileBytes;
XgPlaneLayout& p = L.Plane[0];
p.Usage = kPlaneDefault;
p.BytesPerElement = fi.bytes;
p.StandardMipCount = 1;
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
p.SizeBytes = p.SliceSizeBytes = kTileBytes;
XgMipLevelLayout& m = p.MipLayout[0];
m.WidthPixels = static_cast<UINT32>(d.Width);
m.HeightPixels = height;
m.WidthElements = width_el;
m.HeightElements = height_el;
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
m.PitchBytes = sw.tile_x * sw.bytes;
m.PitchPixels = sw.tile_x * fi.block;
m.PaddedWidthElements = sw.tile_x;
m.PaddedHeightElements = sw.tile_y;
m.AlignmentBytes = static_cast<UINT32>(kTileBytes);
m.SwizzleMode = kSwizzleMode64KbS;
m.SizeBytes = m.Slice2DSizeBytes = kTileBytes;
L.SizeBytes = kTileBytes;
*out = c;
return S_OK;
}
L.MipLevels = mips;
L.Planes = fi.stencil ? 2 : 1;
uint64_t cursor = 0;
for (uint32_t pi = 0; pi < L.Planes; ++pi) {
XgPlaneLayout& p = L.Plane[pi];
p.Usage = fi.stencil ? (pi == 0 ? kPlaneDepth : kPlaneStencil) : kPlaneDefault;
p.BytesPerElement = fi.stencil && pi == 1 ? 1 : fi.bytes;
p.StandardMipCount = mips;
p.MipTailMipCount = 0;
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
cursor = align_up(cursor, kResourceAlign);
p.BaseOffsetBytes = cursor;
for (uint32_t mi = 0; mi < mips; ++mi) {
XgMipLevelLayout& m = p.MipLayout[mi];
m.WidthPixels = mip_extent(d.Width, mi);
m.HeightPixels = mip_extent(height, mi);
m.DepthOrArraySize = d.Dimension == kDimTexture3D ? mip_extent(depth_or_array, mi) : depth_or_array;
m.WidthElements = (m.WidthPixels + fi.block - 1) / fi.block;
m.HeightElements = (m.HeightPixels + fi.block - 1) / fi.block;
m.SampleCount = samples;
m.PitchBytes = static_cast<UINT32>(align_up(static_cast<uint64_t>(m.WidthElements) * samples * p.BytesPerElement, kRowAlign));
m.PitchPixels = m.PitchBytes / (p.BytesPerElement * samples) * fi.block;
m.PaddedWidthElements = m.PitchBytes / (p.BytesPerElement * samples);
m.PaddedHeightElements = m.HeightElements;
m.PaddedDepthOrArraySize = m.DepthOrArraySize;
m.SliceDepthElements = 1;
m.AlignmentBytes = static_cast<UINT32>(kMipAlign);
m.SwizzleMode = kSwizzleModeLinear;
m.Slice2DSizeBytes = static_cast<uint64_t>(m.PitchBytes) * m.HeightElements;
m.SizeBytes = m.Slice2DSizeBytes * m.DepthOrArraySize;
cursor = align_up(cursor, kMipAlign);
m.OffsetBytes = cursor;
cursor += m.SizeBytes;
}
p.SizeBytes = cursor - p.BaseOffsetBytes;
p.SliceSizeBytes = p.MipLayout[0].Slice2DSizeBytes;
}
L.SizeBytes = align_up(cursor, kResourceAlign);
*out = c;
return S_OK;
}
} // namespace
extern "C" {
__declspec(dllexport) HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, XGTextureAddressComputer** out) {
if (!desc || !out) return E_INVALIDARG;
*out = nullptr;
const HRESULT hr = LayoutComputer::create(*desc, out);
if (SUCCEEDED(hr)) {
static std::atomic<uint64_t> created{0};
const uint64_t n = ++created;
if ((n & (n - 1)) == 0) {
char detail[200];
std::snprintf(detail, sizeof(detail),
"BetterXen linear layout (not console tiling): dim=%u %llux%u x%u mips=%u format=%u layout=0x%x size=%llu; total created=%llu",
desc->Dimension, static_cast<unsigned long long>(desc->Width), desc->Height,
desc->DepthOrArraySize, desc->MipLevels, desc->Format, desc->Layout,
static_cast<unsigned long long>((*out)->GetResourceSizeBytes()), static_cast<unsigned long long>(n));
bx_log_emit(BX_LOG_INFO, "xg_xs", "texture_computer", detail);
}
}
return hr;
}
__declspec(dllexport) HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t, uint32_t* layout) {
if (!desc || !layout) return E_INVALIDARG;
*layout = kLayoutSwizzleLinear; // this layer lays every texture out linearly
return S_OK;
}
} // extern "C"
File diff suppressed because it is too large. Load diff
+94 -20
View File
@@ -34,6 +34,8 @@ HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, vo
void WINAPI XTaskQueueCloseHandle(void*);
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
void (CALLBACK*)(void*, bool));
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
HRESULT WINAPI XAsyncGetStatus(void*, bool);
@@ -103,6 +105,11 @@ constexpr GUID kNetworkingClsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36
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}};
// XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode reach the runtime through these keys
// (from authorized GDK material; see the CHANGELOG). The function contracts are public.
constexpr GUID kAnalyticsGuid = {0xB884675D, 0xB738, 0x4A9C, {0x81, 0x5D, 0x9A, 0x9A, 0x1E, 0x0C, 0x6C, 0x9B}};
constexpr GUID kDisplayClsid = {0x03F0FE74, 0xFDD9, 0x4E5C, {0xB6, 0x30, 0xF9, 0x33, 0x9C, 0x47, 0xAC, 0xC5}};
constexpr GUID kDisplayIid = {0x35F07670, 0x706E, 0x4BFB, {0x94, 0x76, 0x09, 0x07, 0x98, 0xC5, 0xEB, 0xF3}};
bool guid_eq(const GUID& a, const GUID& b) {
return std::memcmp(&a, &b, sizeof(GUID)) == 0;
@@ -184,9 +191,11 @@ HRESULT WINAPI core_tq_submit(void*, void* queue, Port port, void* ctx, void (CA
HRESULT WINAPI core_tq_submit_delayed(void*, void* queue, Port port, uint32_t delay_ms, void* ctx,
void (CALLBACK* cb)(void*, bool)) {
if (delay_ms > 0) {
BX_VTABLE_STUB_LOG("IXGameRuntimeCore", 19, "XTaskQueueSubmitDelayedCallback(nonzero_delay)");
char detail[96];
std::snprintf(detail, sizeof(detail), "queued delay_ms=%lu", static_cast<unsigned long>(delay_ms));
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XTaskQueueSubmitDelayedCallback", detail);
}
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
return XTaskQueueSubmitDelayedCallback(queue, port, delay_ms, ctx, cb);
}
bool WINAPI core_tq_get_process(void*, void** out) {
return XTaskQueueGetCurrentProcessTaskQueue(out);
@@ -292,6 +301,78 @@ const std::array<const void*, 12> kSystemVtbl = [] {
}();
ComSingleton kSystemObj{kSystemVtbl.data(), &kSystemIid, "IXSystem"};
// --- XSystemGetAnalyticsInfo (public XSystem.h contract) ---
// Public XVersion: four uint16_t fields in this order, overlaid on a uint64_t.
struct XVersionLayout {
uint16_t major;
uint16_t minor;
uint16_t build;
uint16_t revision;
};
// Public XSystemAnalyticsInfo.
struct XSystemAnalyticsInfoLayout {
XVersionLayout osVersion;
XVersionLayout hostingOsVersion;
char family[64];
char form[64];
};
static_assert(sizeof(XSystemAnalyticsInfoLayout) == 0x90, "XSystemAnalyticsInfo is 144 bytes");
// Slot 3 returns the structure by value: MSVC passes the result buffer after `this` and
// returns the same pointer.
XSystemAnalyticsInfoLayout* WINAPI analytics_get_info(void*, XSystemAnalyticsInfoLayout* out) {
if (!out) return out;
std::memset(out, 0, sizeof(*out));
// BetterXen's own synthetic title and system OS version; not a console build number.
out->osVersion = {10, 0, 26100, 0};
out->hostingOsVersion = {10, 0, 26100, 0};
std::snprintf(out->family, sizeof(out->family), "Xbox");
// Series S for the Lockhart profile, Series X for Anaconda (XSystemGetDeviceType 6 / 7).
std::snprintf(out->form, sizeof(out->form), "%s",
XSystemGetDeviceType() == 7u ? "Xbox Series X" : "Xbox Series S");
char detail[160];
std::snprintf(detail, sizeof(detail), "family=%s form='%s' os=10.0.26100.0 synthetic=1", out->family,
out->form);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XSystemGetAnalyticsInfo", detail);
return out;
}
const std::array<const void*, 8> kAnalyticsVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&analytics_get_info);
return v;
}();
ComSingleton kAnalyticsObj{kAnalyticsVtbl.data(), &kAnalyticsGuid, "IXSystemAnalytics"};
// --- XDisplayTryEnableHdrMode (public XDisplay.h contract) ---
// Public XDisplayHdrModeInfo.
struct XDisplayHdrModeInfoLayout {
float minToneMapLuminance;
float maxToneMapLuminance;
float maxFullFrameToneMapLuminance;
};
constexpr uint32_t kHdrModeResultDisabled = 2; // XDisplayHdrModeResult::Disabled
// BetterXen presents SDR through the host swap chain, so HDR is reported as not enabled:
// a successful Disabled answer, not the failure value Unknown. The output is only meaningful
// when HDR is enabled, so it is cleared.
uint32_t WINAPI display_try_enable_hdr(void*, uint32_t preference, XDisplayHdrModeInfoLayout* info) {
if (info) std::memset(info, 0, sizeof(*info));
char detail[96];
std::snprintf(detail, sizeof(detail), "preference=%u result=disabled reason=sdr_presentation", preference);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XDisplayTryEnableHdrMode", detail);
return kHdrModeResultDisabled;
}
const std::array<const void*, 8> kDisplayVtbl = [] {
auto v = make_default_vtbl<8>();
v[4] = reinterpret_cast<const void*>(&display_try_enable_hdr);
return v;
}();
ComSingleton kDisplayObj{kDisplayVtbl.data(), &kDisplayIid, "IXDisplay"};
// --- XError ---
void WINAPI err_set_callback(void*, void*, void*) {}
@@ -670,12 +751,6 @@ BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWith
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
BX_HR(pk_create_monitor, "IXPackageImpl", 5, "XPackageCreateInstallationMonitor")
BX_VOID(pk_close_monitor, "IXPackageImpl", 6, "XPackageCloseInstallationMonitorHandle")
BX_VOID(pk_get_progress, "IXPackageImpl", 7, "XPackageGetInstallationProgress")
BX_BOOL(pk_update_monitor, "IXPackageImpl", 8, "XPackageUpdateInstallationMonitor")
BX_HR(pk_reg_progress, "IXPackageImpl", 9, "XPackageRegisterInstallationProgressChanged")
BX_BOOL(pk_unreg_progress, "IXPackageImpl", 10, "XPackageUnregisterInstallationProgressChanged")
BX_HR(pk_locale, "IXPackageImpl", 11, "XPackageGetUserLocale")
BX_HR(pk_find_chunk, "IXPackageImpl", 12, "XPackageFindChunkAvailability")
BX_HR(pk_enum_chunk, "IXPackageImpl", 13, "XPackageEnumerateChunkAvailability")
@@ -689,16 +764,13 @@ BX_HR(pk_unknown_20, "IXPackageImpl", 20, "unknown")
BX_HR(pk_unknown_21, "IXPackageImpl", 21, "unknown")
BX_BOOL(pk_unreg_installed, "IXPackageImpl", 22, "XPackageUnregisterPackageInstalled")
BX_HR(pk_unknown_27, "IXPackageImpl", 27, "unknown")
BX_HR(pk_enum_packages, "IXPackageImpl", 28, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed, "IXPackageImpl", 29, "XPackageRegisterPackageInstalled")
BX_HR(pk_write_stats, "IXPackageImpl", 30, "XPackageGetWriteStats")
BX_HR(pk_unknown_31, "IXPackageImpl", 31, "unknown")
BX_HR(pk_uninstall_uwp, "IXPackageImpl", 32, "XPackageUninstallUWPInstance")
BX_HR(pk_enum_features, "IXPackageImpl", 33, "XPackageEnumerateFeatures")
BX_HR(pk_uninstall, "IXPackageImpl", 34, "XPackageUninstallPackage")
BX_HR(pk_enum_packages_2, "IXPackageImpl2", 35, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
BX_HR(pk_enum_packages_3, "IXPackageImpl3", 39, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalled")
#undef BX_HR
#undef BX_VOID
@@ -746,12 +818,12 @@ const std::array<const void*, 42> kPackageVtbl = [] {
v[0] = reinterpret_cast<const void*>(&package_query_interface);
v[3] = reinterpret_cast<const void*>(&get_current_process_package_identifier);
v[4] = reinterpret_cast<const void*>(&is_packaged_process);
v[5] = reinterpret_cast<const void*>(&pk_create_monitor);
v[6] = reinterpret_cast<const void*>(&pk_close_monitor);
v[7] = reinterpret_cast<const void*>(&pk_get_progress);
v[8] = reinterpret_cast<const void*>(&pk_update_monitor);
v[9] = reinterpret_cast<const void*>(&pk_reg_progress);
v[10] = reinterpret_cast<const void*>(&pk_unreg_progress);
v[5] = reinterpret_cast<const void*>(&create_installation_monitor);
v[6] = reinterpret_cast<const void*>(&close_installation_monitor);
v[7] = reinterpret_cast<const void*>(&get_installation_progress);
v[8] = reinterpret_cast<const void*>(&update_installation_monitor);
v[9] = reinterpret_cast<const void*>(&register_installation_progress);
v[10] = reinterpret_cast<const void*>(&unregister_installation_progress);
v[11] = reinterpret_cast<const void*>(&pk_locale);
v[12] = reinterpret_cast<const void*>(&pk_find_chunk);
v[13] = reinterpret_cast<const void*>(&pk_enum_chunk);
@@ -769,18 +841,18 @@ const std::array<const void*, 42> kPackageVtbl = [] {
v[25] = reinterpret_cast<const void*>(&get_mount_path);
v[26] = reinterpret_cast<const void*>(&close_mount_handle);
v[27] = reinterpret_cast<const void*>(&pk_unknown_27);
v[28] = reinterpret_cast<const void*>(&pk_enum_packages);
v[28] = reinterpret_cast<const void*>(&enumerate_packages);
v[29] = reinterpret_cast<const void*>(&pk_reg_installed);
v[30] = reinterpret_cast<const void*>(&pk_write_stats);
v[31] = reinterpret_cast<const void*>(&pk_unknown_31);
v[32] = reinterpret_cast<const void*>(&pk_uninstall_uwp);
v[33] = reinterpret_cast<const void*>(&pk_enum_features);
v[34] = reinterpret_cast<const void*>(&pk_uninstall);
v[35] = reinterpret_cast<const void*>(&pk_enum_packages_2);
v[35] = reinterpret_cast<const void*>(&enumerate_packages);
v[36] = reinterpret_cast<const void*>(&pk_reg_installed_2);
v[37] = reinterpret_cast<const void*>(&mount_with_ui_async);
v[38] = reinterpret_cast<const void*>(&mount_with_ui_result);
v[39] = reinterpret_cast<const void*>(&pk_enum_packages_3);
v[39] = reinterpret_cast<const void*>(&enumerate_packages);
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
v[41] = reinterpret_cast<const void*>(&get_package_kind);
return v;
@@ -797,6 +869,8 @@ const PublicEntry kPublicEntries[] = {
{&kCoreGuid, &kCoreGuid, &kCoreObj},
{&kFeatureGuid, &kFeatureGuid, &kFeatureObj},
{&kSystemClsid, &kSystemIid, &kSystemObj},
{&kAnalyticsGuid, &kAnalyticsGuid, &kAnalyticsObj},
{&kDisplayClsid, &kDisplayIid, &kDisplayObj},
{&kErrorGuid, &kErrorGuid, &kErrorObj},
{&kPlsClsid, &kPlsIid, &kPlsObj},
{&kUserClsid, &kUserClsid, &kUserObj},
+154 -1
View File
@@ -22,9 +22,18 @@
* mounted; BetterXen allows the game's own package so titles can locate their files. Offline
* there is no license or parental-consent prompt, so the asynchronous form shows no UI; an
* identifier mismatch is reported as the operation's status (ERROR_NOT_FOUND).
* - The last XGameRuntimeUninitialize closes every mount handle.
* - The last XGameRuntimeUninitialize closes every mount handle and installation monitor.
* - Installation monitors (XPackageCreateInstallationMonitor and the functions taking its
* handle) accept only that identifier. The package is fully on local storage, so progress is
* {1, 1, 1, launchable, completed} and never changes: a registered progress callback is
* accepted, logged and never called. Handles share the mount table's lock and generation, so
* a closed or stale handle is rejected and closing twice is harmless.
* - XPackageEnumeratePackages reports this game for XPackageKind::Game in every scope (the
* documented ThisOnly output is the calling game; offline there are no related or publisher
* games), and no packages for Content or PublisherContent: none are installed offline.
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
*/
#include "bx_log.h"
#include "runtime_internal.h"
#include "synthetic_keys.h"
@@ -37,6 +46,7 @@
#include <new>
#include <string>
#include <unordered_map>
#include <vector>
namespace bx::gdk {
namespace {
@@ -250,6 +260,148 @@ void WINAPI close_mount_handle(void*, void* handle) {
namespace {
struct Monitor {
uint32_t generation;
std::vector<uint64_t> tokens;
};
// Guarded by mount_mutex, like the mount handles. Tag 5 in bits 40-43 keeps these handles apart
// from mount handles (tag 4) and XGameSave handles.
std::unordered_map<void*, Monitor> monitors;
constexpr uintptr_t kMonitorTag = 5;
uint64_t token_counter = 0;
// Caller holds mount_mutex.
Monitor* find_monitor(void* handle, uint32_t generation) {
const auto found = monitors.find(handle);
if (found == monitors.end() || generation == 0 || found->second.generation != generation) return nullptr;
return &found->second;
}
} // namespace
HRESULT WINAPI create_installation_monitor(void*, const char* identifier, uint32_t, const void*, uint32_t, void*,
void** monitor) {
if (!monitor) return E_POINTER;
*monitor = nullptr;
if (!identifier) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!generation) return kRuntimeNotInitialized;
bool match = false;
const auto hr = is_current_package(identifier, match);
if (FAILED(hr)) return hr;
if (!match) return kNotFound;
try {
std::lock_guard lock(mount_mutex);
++handle_counter;
void* handle = reinterpret_cast<void*>(kMonitorTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
monitors.emplace(handle, Monitor{generation, {}});
*monitor = handle;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageCreateInstallationMonitor",
"monitor for the running package: fully installed, progress never changes (offline)");
return S_OK;
}
void WINAPI close_installation_monitor(void*, void* monitor) {
std::lock_guard lock(mount_mutex);
monitors.erase(monitor); // an unknown or already closed handle is ignored
}
void WINAPI get_installation_progress(void*, void* monitor, XPackageInstallationProgress* progress) {
if (!progress) return;
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
*progress = find_monitor(monitor, generation) ? XPackageInstallationProgress{1, 1, 1, true, true}
: XPackageInstallationProgress{};
}
bool WINAPI update_installation_monitor(void*, void*) {
return false; // progress never changes offline
}
HRESULT WINAPI register_installation_progress(void*, void* monitor, void*, void* callback, uint64_t* token) {
if (!token) return E_POINTER;
*token = 0;
if (!callback) return E_INVALIDARG;
const auto generation = active_runtime_generation();
try {
std::lock_guard lock(mount_mutex);
Monitor* open = find_monitor(monitor, generation);
if (!open) return stale_handle_error(generation);
*token = ++token_counter;
open->tokens.push_back(*token);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
char detail[128];
std::snprintf(detail, sizeof(detail), "token=%llu accepted; offline progress never changes, so the callback is never called",
static_cast<unsigned long long>(*token));
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageRegisterInstallationProgressChanged", detail);
return S_OK;
}
bool WINAPI unregister_installation_progress(void*, void* monitor, uint64_t token, bool) {
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
Monitor* open = find_monitor(monitor, generation);
if (!open) return false;
for (auto it = open->tokens.begin(); it != open->tokens.end(); ++it) {
if (*it == token) {
open->tokens.erase(it);
return true;
}
}
return false;
}
namespace {
struct XVersionValue {
uint16_t major, minor, build, revision;
};
struct XPackageDetails {
const char* packageIdentifier;
XVersionValue version;
uint32_t kind;
const char* displayName;
const char* description;
const char* publisher;
const char* storeId;
bool installing;
uint32_t index;
uint32_t count;
bool ageRestricted;
const char* titleId;
};
using EnumerationCallback = bool(CALLBACK*)(void* context, const XPackageDetails* details);
constexpr uint32_t kKindGame = 0, kScopeThisPublisher = 2;
} // namespace
HRESULT WINAPI enumerate_packages(void*, uint32_t kind, uint32_t scope, void* context, void* callback) {
if (!callback) return E_INVALIDARG;
if (!active_runtime_generation()) return kRuntimeNotInitialized;
if (kind > 2 || scope > kScopeThisPublisher) return E_INVALIDARG;
char detail[128];
if (kind != kKindGame) {
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: no content packages installed (offline)", kind, scope);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
return S_OK;
}
char id[kIdBytes];
const auto hr = current_identifier(id);
if (FAILED(hr)) return hr;
const XPackageDetails details{id, {}, kKindGame, "", "", "", "", false, 0, 1, false, ""};
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: reported the running game only (offline)", kind, scope);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
reinterpret_cast<EnumerationCallback>(callback)(context, &details);
return S_OK;
}
namespace {
// --- COM object ---
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
@@ -301,6 +453,7 @@ const void* const package_object = &kObject;
void release_package_state() {
std::lock_guard lock(mount_mutex);
mounts.clear();
monitors.clear();
}
} // namespace bx::gdk
+19
View File
@@ -106,4 +106,23 @@ HRESULT WINAPI get_mount_path_size(void* self, void* handle, size_t* size);
HRESULT WINAPI get_mount_path(void* self, void* handle, size_t size, char* path);
void WINAPI close_mount_handle(void* self, void* handle);
// Installation monitors and enumeration (package.cpp), served on IXPackageImpl slots 5-10 and
// the XPackageEnumeratePackages slots. Layouts follow the documented XPackage structures.
struct XPackageInstallationProgress {
uint64_t totalBytes;
uint64_t installedBytes;
uint64_t launchBytes;
bool launchable;
bool completed;
};
HRESULT WINAPI create_installation_monitor(void* self, const char* identifier, uint32_t selector_count,
const void* selectors, uint32_t interval_ms, void* queue, void** monitor);
void WINAPI close_installation_monitor(void* self, void* monitor);
void WINAPI get_installation_progress(void* self, void* monitor, XPackageInstallationProgress* progress);
bool WINAPI update_installation_monitor(void* self, void* monitor);
HRESULT WINAPI register_installation_progress(void* self, void* monitor, void* context, void* callback,
uint64_t* token);
bool WINAPI unregister_installation_progress(void* self, void* monitor, uint64_t token, bool wait);
HRESULT WINAPI enumerate_packages(void* self, uint32_t kind, uint32_t scope, void* context, void* callback);
} // namespace bx::gdk
+67 -4
View File
@@ -1,5 +1,6 @@
#include "task_queue.h"
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <mutex>
@@ -43,7 +44,11 @@ public:
std::unique_lock lock(mutex);
if (closed && !is_completion) return false;
if (mode == DispatchMode::immediate || (closed && mode == DispatchMode::manual)) {
// No lane storage on these paths, so the submitting thread waits out
// the remainder of the delay and then runs the callback itself.
const uint64_t due_ms = task->due_ms;
lock.unlock();
wait_until(due_ms);
task->run(owner->shared_from_this());
return true;
}
@@ -62,6 +67,30 @@ public:
SubmitThreadpoolWork(worker);
}
bool due() const { return first && (first->due_ms == 0 || GetTickCount64() >= first->due_ms); }
// Sleep out the remainder of a GetTickCount64 deadline. Saturating: the
// deadline can pass between the check and the clock read, and an unsigned
// subtraction there would wrap to ~584 million years.
static void wait_until(uint64_t due_ms) {
for (;;) {
const uint64_t now = GetTickCount64();
if (due_ms == 0 || now >= due_ms) return;
const uint64_t left = due_ms - now;
// INFINITE would mean "wait forever", so a `left` of exactly
// 0xFFFFFFFF would never wake to re-check the deadline.
Sleep(finite_sleep_chunk_ms(left));
}
}
// FIFO: the head holds the lane until it is due, so a later task never
// overtakes a delayed one. Wait only until that deadline, never spin.
std::chrono::steady_clock::time_point head_due() const {
const uint64_t now = GetTickCount64();
const uint64_t left = first->due_ms > now ? first->due_ms - now : 0;
return std::chrono::steady_clock::now() + std::chrono::milliseconds(left);
}
void schedule_serial() {
if (mode == DispatchMode::serialized && first && !serial_running && workers == 0) {
schedule();
@@ -92,11 +121,25 @@ public:
bool dispatch(uint32_t timeout) {
if (mode == DispatchMode::immediate) return false;
std::unique_lock lock(mutex);
const auto has_task = [this] { return closed || (first && !serial_running); };
const auto has_task = [this] { return closed || (due() && !serial_running); };
if (timeout == INFINITE) {
ready.wait(lock, has_task);
} else if (!ready.wait_for(lock, std::chrono::milliseconds(timeout), has_task)) {
return false;
while (!has_task()) {
if (first && !serial_running) {
ready.wait_until(lock, head_due());
} else {
ready.wait(lock);
}
}
} else {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout);
while (!has_task()) {
if (std::chrono::steady_clock::now() >= deadline) return false;
auto wake = deadline;
if (first && !serial_running) {
wake = std::min(wake, head_due());
}
ready.wait_until(lock, wake);
}
}
if (closed) return false;
auto task = pop();
@@ -118,6 +161,14 @@ public:
std::unique_lock lock(lane.mutex);
queue = lane.worker_owner;
while (lane.first && !lane.serial_running) {
// A delayed head must not run early. Wait on the condition variable
// until its deadline (or a push changes the head) instead of popping
// it, so FIFO order holds and nothing is dropped. Close drains what
// was already accepted, as it did before delays existed.
if (!lane.closed && !lane.due()) {
lane.ready.wait_until(lock, lane.head_due());
continue;
}
auto task = lane.pop();
const bool serial = lane.mode == DispatchMode::serialized;
lane.serial_running = serial;
@@ -190,6 +241,7 @@ bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool i
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
}
} // namespace bx::gdk
using namespace bx::gdk;
@@ -237,12 +289,23 @@ bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
}
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
CallbackTask::Callback callback);
HRESULT WINAPI XTaskQueueSubmitCallback(void* handle, Port port, void* context, CallbackTask::Callback callback) {
return XTaskQueueSubmitDelayedCallback(handle, port, 0, context, callback);
}
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
CallbackTask::Callback callback) {
if (!handle || port > Port::completion || !callback) return E_INVALIDARG;
const auto queue = acquire_queue(handle);
if (!queue) return E_HANDLE;
auto task = std::unique_ptr<Task>(new (std::nothrow) CallbackTask(callback, context));
if (!task) return E_OUTOFMEMORY;
// delay_ms == 0 is due now, which is the common case and matches the old
// immediate-submit behaviour. A nonzero delay is a GetTickCount64 deadline.
task->due_ms = delay_ms == 0 ? 0 : GetTickCount64() + delay_ms;
return submit(queue, port, std::move(task)) ? S_OK : E_HANDLE;
}
+16
View File
@@ -17,10 +17,26 @@ struct Task {
virtual void run(const QueueRef& queue) = 0;
virtual void cancel(const QueueRef& queue) { run(queue); }
// GetTickCount64 deadline; zero means due immediately.
uint64_t due_ms = 0;
std::unique_ptr<Task> next;
};
QueueRef acquire_queue(void* handle);
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion = false);
// Largest finite Sleep() chunk. INFINITE (0xFFFFFFFF) means "wait forever", so
// a delay whose remaining time is exactly INFINITE must never be passed to
// Sleep: the wait would never wake to re-check the deadline, and the callback
// would never run. Clamp every chunk to at most INFINITE - 1.
inline constexpr uint32_t kMaxFiniteSleepMs = INFINITE - 1;
// Split a GetTickCount64 remainder into one finite Sleep() chunk. `left` is
// uint64_t because a deadline subtraction can exceed 32 bits; the result is
// always in [1, INFINITE - 1] for any positive `left`, so the caller's loop
// always wakes up and re-checks the deadline.
inline uint32_t finite_sleep_chunk_ms(uint64_t left) {
return static_cast<uint32_t>(left < kMaxFiniteSleepMs ? left : kMaxFiniteSleepMs);
}
}
+2
View File
@@ -798,6 +798,8 @@ HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, vo
void WINAPI XTaskQueueCloseHandle(void*);
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
void (CALLBACK*)(void*, bool));
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
HRESULT WINAPI InitializeApiImpl(uint32_t gdk_ver, uint32_t gs_ver) {
+598 -122
View File
@@ -1,6 +1,7 @@
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <new>
@@ -10,35 +11,86 @@
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 allocated;
bool releasing;
};
// One XMemAllocatePhysicalPages call: a single pagefile-backed section holding all its pages,
// page i at offset i * 64 KB. One section per call, not per page, keeps a title that asks for
// gigabytes at once (about 100,000 pages) within the host's open-file limit. A freed page stays
// backed by the section until every page of its block is freed.
struct PageBlock {
ULONG_PTR first_tag;
SIZE_T count;
SIZE_T size;
SIZE_T live;
HANDLE section;
Page* entries;
PageBlock* next;
};
ULONG64 page_offset(const Page* page) {
return static_cast<ULONG64>(page - page->block->entries) * small_page;
}
// A run of `pages` consecutive pages of one block (offsets page..page+pages-1), mapped as one view
// at `address`. A title maps its page pool in long runs; one view per run keeps the number of
// placeholder splits and MapViewOfFile3 calls (each a Wine server round trip) proportional to the
// runs, not the pages. Unmapping part of a run unmaps the view and maps the remaining sub-runs again.
struct View {
Page* page;
SIZE_T pages;
BYTE* address;
View* next;
// Mapped into an XMEM_MAPPABLE reservation: unmapping restores the placeholder so the
// range stays reserved and can be mapped again.
bool preserve;
};
uintptr_t view_begin(const View* view) { return reinterpret_cast<uintptr_t>(view->address); }
uintptr_t view_end(const View* view) { return view_begin(view) + view->pages * small_page; }
bool follows(const Page* before, const Page* after) {
return after->block == before->block && after == before + 1;
}
// An XMemVirtualAlloc(MEM_RESERVE, XMEM_MAPPABLE) range, held as a placeholder.
struct Reservation {
uintptr_t begin;
uintptr_t end;
SIZE_T page;
DWORD protect;
Reservation* next;
};
SRWLOCK memory_lock = SRWLOCK_INIT;
PageBlock* blocks = nullptr;
View* views = nullptr;
ULONG_PTR next_tag = 1;
Reservation* reservations = nullptr;
// Page tags are physical page numbers, which count 4 KiB frames: a 64 KiB page's number is a
// multiple of 16. Titles rely on that: the target build keeps a page as the 21-bit `number >> 4`
// and rebuilds it with `<< 4`, so consecutive numbers per 64 KiB page made sixteen pages collapse
// into one. Each allocation also starts on a kTagAlignment boundary, so a title rounding its first
// number down to a large page stays inside it; 0 stays unused, and every number fits the 25 bits
// (21 + 4) the title keeps.
constexpr ULONG_PTR kFramesPerPage = small_page / 4096; // 16
constexpr ULONG_PTR kTagAlignment = 0x1000; // 256 pages = 16 MB, in frames
constexpr ULONG_PTR kTagLimit = ULONG_PTR{1} << 25;
ULONG_PTR next_tag = kTagAlignment;
// XMemAllocatePhysicalPages flags (authorized GDK documentation): 2 MB clusters, and the four
// memory-bandwidth values, which only the Series X Advanced memory mode uses.
// XMEM_2MB_CLUSTERS is MEM_2MB_PAGES; MEM_64K_PAGES is MEM_2MB_PAGES | MEM_PHYSICAL (authorized GDK
// headers). Public samples pass MEM_64K_PAGES for 64 KB pages, so both bits together mean 64 KB
// pages, and the 2 MB bit alone means 2 MB clusters.
constexpr uint64_t xmem_2mb_clusters = 0x20000000;
constexpr uint64_t mem_physical = 0x00400000;
constexpr uint64_t mem_64k_pages = xmem_2mb_clusters | mem_physical;
constexpr uint64_t xmem_bandwidth_bits = 0x380;
struct Lock {
Lock() { AcquireSRWLockExclusive(&memory_lock); }
@@ -49,11 +101,13 @@ 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);
using UnmapPreserving = BOOL (WINAPI*)(HANDLE, PVOID, ULONG);
struct PlaceholderApi {
HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
ReservePlaceholder reserve = resolve<ReservePlaceholder>("VirtualAlloc2");
ReplacePlaceholder replace = resolve<ReplacePlaceholder>("MapViewOfFile3");
UnmapPreserving unmap = resolve<UnmapPreserving>("UnmapViewOfFile2");
template<class Function>
Function resolve(const char* name) const {
@@ -61,35 +115,36 @@ struct PlaceholderApi {
}
};
// 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;
const PlaceholderApi& placeholder_api() {
static const PlaceholderApi api;
return api;
}
// The reservation holding all of [begin, end), or nullptr.
Reservation* find_reservation(uintptr_t begin, uintptr_t end) {
for (Reservation* r = reservations; r; r = r->next) {
if (begin >= r->begin && end <= r->end && begin < end) return r;
}
return nullptr;
}
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;
if (tag >= block->first_tag && (tag - block->first_tag) % kFramesPerPage == 0 &&
(tag - block->first_tag) / kFramesPerPage < block->count) {
Page* page = &block->entries[(tag - block->first_tag) / kFramesPerPage];
return page->allocated ? page : nullptr;
}
}
return nullptr;
}
ULONG_PTR page_tag(const Page* page) {
return page->block->first_tag + (page - page->block->entries);
return page->block->first_tag + static_cast<ULONG_PTR>(page - page->block->entries) * kFramesPerPage;
}
void delete_block(PageBlock* block) {
for (SIZE_T i = 0; i < block->count; ++i) {
if (block->entries[i].section) CloseHandle(block->entries[i].section);
}
if (block->section) CloseHandle(block->section);
delete[] block->entries;
delete block;
}
@@ -110,7 +165,11 @@ bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
bool remove_view(View** link) {
View* view = *link;
if (!UnmapViewOfFile(view->address)) return false;
const bool unmapped = view->preserve
? placeholder_api().unmap && placeholder_api().unmap(GetCurrentProcess(), view->address,
MEM_PRESERVE_PLACEHOLDER)
: UnmapViewOfFile(view->address) != 0;
if (!unmapped) return false;
*link = view->next;
delete view;
return true;
@@ -129,9 +188,8 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T 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 (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
matched += view->pages;
}
}
if (matched != count) {
@@ -141,8 +199,7 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
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 (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
if (!remove_view(link)) return nullptr;
} else {
link = &view->next;
@@ -151,50 +208,236 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
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);
// Builds one unlinked View per tag, in order, after checking that every tag names a live page.
bool build_views(const ULONG_PTR* tags, SIZE_T count, bool preserve, View** out) {
View* first = nullptr;
View** tail = &first;
for (SIZE_T i = 0; i < count; ++i) {
Page* page = find_page(tags[i]);
if (!page) {
destroy_views(first);
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
auto* view = new (std::nothrow) View{page, 1, nullptr, nullptr, preserve};
if (!view) {
destroy_views(first);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return false;
}
*tail = view;
tail = &view->next;
}
*out = first;
return true;
}
void publish(View* pending) {
while (pending) {
View* next = pending->next;
pending->next = views;
views = pending;
pending = next;
}
}
// Maps the run [first, first + pages) at `address` inside a reservation. The range may cover one
// placeholder or several (left by earlier mappings); each placeholder piece inside it is split out
// where it extends past the range and replaced with one view, so a range inside one placeholder
// becomes one view. Returns the unlinked chain of views (through `next`) and its tail in *tail,
// or nullptr with the error set and nothing mapped.
View* map_run(Page* first, SIZE_T pages, BYTE* address, DWORD protect, View** tail = nullptr) {
const PlaceholderApi& api = placeholder_api();
const uintptr_t begin = reinterpret_cast<uintptr_t>(address);
const uintptr_t end = begin + pages * small_page;
View* head = nullptr;
View** link = &head;
View* last = nullptr;
for (uintptr_t at = begin; at < end;) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t piece_end = end;
if (VirtualQuery(reinterpret_cast<void*>(at), &region, sizeof(region)) && region.State == MEM_RESERVE) {
const uintptr_t region_end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
if (region_end < piece_end) piece_end = region_end;
}
const SIZE_T piece_pages = (piece_end - at) / small_page;
Page* piece_first = first + (at - begin) / small_page;
auto* view = new (std::nothrow) View{piece_first, piece_pages, reinterpret_cast<BYTE*>(at), nullptr, true};
if (!view) SetLastError(ERROR_NOT_ENOUGH_MEMORY);
if (view) VirtualFree(reinterpret_cast<void*>(at), piece_end - at, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
if (!view || !api.replace(first->block->section, GetCurrentProcess(), reinterpret_cast<void*>(at),
page_offset(piece_first), piece_end - at, MEM_REPLACE_PLACEHOLDER, protect,
nullptr, 0)) {
const DWORD error = GetLastError();
delete view;
while (head) {
View* next = head->next;
api.unmap(GetCurrentProcess(), head->address, MEM_PRESERVE_PLACEHOLDER);
delete head;
head = next;
}
SetLastError(error);
return nullptr;
}
auto* view = new (std::nothrow) View{page, nullptr, pending};
*link = view;
link = &view->next;
last = view;
at = piece_end;
}
if (tail) *tail = last;
return head;
}
// The protection of the reservation holding `view` (the view was mapped with it).
DWORD view_protect(const View* view) {
const Reservation* r = find_reservation(view_begin(view), view_end(view));
return r ? r->protect : PAGE_READWRITE;
}
// Unmaps the pages of *link for which removed(page, page_address) is true. A view losing every
// page is removed; one losing some (only in a reservation) is unmapped and its remaining sub-runs
// are mapped again in its place. On return *link is the first view after the ones handled.
template <class Removed>
bool drop_pages(View**& link, Removed removed) {
View* view = *link;
SIZE_T gone = 0;
for (SIZE_T i = 0; i < view->pages; ++i) gone += removed(view->page + i, view_begin(view) + i * small_page);
if (gone == 0) {
link = &view->next;
return true;
}
if (gone == view->pages) return remove_view(link);
if (!view->preserve) { // a span mapped without a reservation is unmapped as a whole
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
const DWORD protect = view_protect(view);
Page* first = view->page;
const SIZE_T pages = view->pages;
BYTE* address = view->address;
if (!remove_view(link)) return false;
for (SIZE_T i = 0; i < pages;) {
if (removed(first + i, reinterpret_cast<uintptr_t>(address) + i * small_page)) {
++i;
continue;
}
SIZE_T j = i + 1;
while (j < pages && !removed(first + j, reinterpret_cast<uintptr_t>(address) + j * small_page)) ++j;
View* kept_tail = nullptr;
View* kept = map_run(first + i, j - i, address + i * small_page, protect, &kept_tail);
if (!kept) {
char detail[128];
std::snprintf(detail, sizeof(detail), "remapping %llu kept pages after a partial unmap failed error=%lu",
static_cast<unsigned long long>(j - i), static_cast<unsigned long>(GetLastError()));
bx_log_emit(BX_LOG_ERROR, "xmem", "physical_remap_failed", detail);
return false;
}
kept_tail->next = *link;
*link = kept;
link = &kept_tail->next;
i = j;
}
return true;
}
// Unmaps every mapped page in [begin, end). Views in a reservation keep its placeholder.
bool unmap_range(uintptr_t begin, uintptr_t end) {
for (View** link = &views; *link;) {
View* view = *link;
if (view_end(view) <= begin || view_begin(view) >= end) {
link = &view->next;
continue;
}
if (!drop_pages(link, [&](const Page*, uintptr_t at) { return at >= begin && at < end; })) return false;
}
return true;
}
// Maps `count` pages (any order, duplicates allowed) at consecutive slots from `address`, one view
// per run of consecutive pages of one block. On failure nothing stays mapped and the error is set.
bool map_pages(Page* const* pages, SIZE_T count, BYTE* address, DWORD protect) {
View* done = nullptr;
for (SIZE_T i = 0; i < count;) {
SIZE_T j = i + 1;
while (j < count && follows(pages[j - 1], pages[j])) ++j;
View* view_tail = nullptr;
View* view = map_run(pages[i], j - i, address + i * small_page, protect, &view_tail);
if (!view) {
destroy_views(pending);
const DWORD error = GetLastError();
while (done) {
View* next = done->next;
placeholder_api().unmap(GetCurrentProcess(), done->address, MEM_PRESERVE_PLACEHOLDER);
delete done;
done = next;
}
SetLastError(error);
return false;
}
view_tail->next = done;
done = view;
i = j;
}
publish(done);
return true;
}
// XMemMapPhysicalPages into an XMEM_MAPPABLE reservation. Pages already mapped in the range are
// unmapped first; a NULL `tags` only unmaps. Duplicate tags alias one page at several offsets.
PVOID map_reserved(Reservation* reservation, BYTE* base, SIZE_T count, const ULONG_PTR* tags) {
if (reservation->page != small_page) {
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPages(MEM_2MB_PAGES)");
SetLastError(ERROR_NOT_SUPPORTED);
return nullptr;
}
const auto begin = reinterpret_cast<uintptr_t>(base);
Page** pages = nullptr;
if (tags) {
pages = new (std::nothrow) Page*[count];
if (!pages) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
pending = view;
for (SIZE_T i = 0; i < count; ++i) {
pages[i] = find_page(tags[i]);
if (!pages[i]) {
delete[] pages;
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
}
}
if (!unmap_range(begin, begin + count * small_page)) {
const DWORD error = GetLastError();
delete[] pages;
SetLastError(error);
return nullptr;
}
if (pages) {
const bool mapped = map_pages(pages, count, base, reservation->protect);
const DWORD error = GetLastError();
delete[] pages;
if (!mapped) {
SetLastError(error);
return nullptr;
}
}
return base;
}
// BetterXen extension, used by synthetic fixtures: with no address, reserve a fresh
// placeholder of `count` pages and map `tags` into it. Unmapping such a span frees it.
PVOID map_unreserved(SIZE_T count, const ULONG_PTR* tags) {
const PlaceholderApi& api = placeholder_api();
View* pending = nullptr;
if (!build_views(tags, count, false, &pending)) return nullptr;
MEM_ADDRESS_REQUIREMENTS requirements{};
requirements.Alignment = size;
requirements.Alignment = small_page;
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));
auto* base = static_cast<BYTE*>(api.reserve(nullptr, nullptr, count * small_page,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, &alignment, 1));
if (!base) {
const DWORD error = GetLastError();
destroy_views(pending);
@@ -205,13 +448,13 @@ PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* ta
BYTE* cursor = base;
SIZE_T remaining = count;
View* view = pending;
for (; view; view = view->next, cursor += size, --remaining) {
for (; view; view = view->next, cursor += small_page, --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,
if (split && !VirtualFree(cursor, small_page, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
if (!api.replace(view->page->block->section, GetCurrentProcess(), cursor, page_offset(view->page), small_page,
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
const DWORD error = GetLastError();
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
if (split) VirtualFree(cursor + small_page, 0, MEM_RELEASE);
SetLastError(error);
break;
}
@@ -228,31 +471,151 @@ PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* ta
SetLastError(error);
return nullptr;
}
while (pending) {
View* next = pending->next;
pending->next = views;
views = pending;
pending = next;
}
publish(pending);
return base;
}
bool have_placeholder_api() {
const PlaceholderApi& api = placeholder_api();
if (api.reserve && api.replace && api.unmap) return true;
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return false;
}
} // 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)) {
namespace bx_xmem {
PVOID reserve_placeholder(PVOID address, SIZE_T size, uintptr_t highest) {
const PlaceholderApi& api = placeholder_api();
if (!have_placeholder_api()) return nullptr;
const auto requested = reinterpret_cast<uintptr_t>(address);
const uintptr_t begin = requested - requested % small_page;
if (!size || size > std::numeric_limits<uintptr_t>::max() - requested - small_page) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
return nullptr;
}
const uintptr_t end = (requested + size + small_page - 1) / small_page * small_page;
MEM_ADDRESS_REQUIREMENTS requirements{};
requirements.Alignment = small_page;
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
MEM_EXTENDED_PARAMETER parameter{};
parameter.Type = MemExtendedParameterAddressRequirements;
parameter.Pointer = &requirements;
return api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr, end - begin,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, begin ? nullptr : &parameter,
begin ? 0 : 1);
}
PVOID reserve_mappable(PVOID address, SIZE_T size, SIZE_T page, DWORD protect, bool adopt, uintptr_t highest) {
const PlaceholderApi& api = placeholder_api();
const auto requested = reinterpret_cast<uintptr_t>(address);
if (!have_placeholder_api()) return nullptr;
if (adopt && (!address || requested % page != 0 || size % page != 0)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
if (!size || size > std::numeric_limits<uintptr_t>::max() - requested - page) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
// A reservation's base rounds down to its page size and its end rounds up.
const uintptr_t begin = requested - requested % page;
const uintptr_t end = (requested + size + page - 1) / page * page;
MEM_ADDRESS_REQUIREMENTS requirements{};
requirements.Alignment = page;
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
MEM_EXTENDED_PARAMETER alignment{};
alignment.Type = MemExtendedParameterAddressRequirements;
alignment.Pointer = &requirements;
auto* reservation = new (std::nothrow) Reservation{};
if (!reservation) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
PVOID base = nullptr;
if (adopt) {
// MEM_REPLACE_PLACEHOLDER: the title split this range out of its own placeholder; it
// stays as it is and becomes mappable.
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(address, &region, sizeof(region)) || region.State != MEM_RESERVE
|| reinterpret_cast<uintptr_t>(region.BaseAddress) != requested || region.RegionSize < size) {
delete reservation;
SetLastError(ERROR_INVALID_ADDRESS);
return nullptr;
}
base = address;
} else {
base = api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr,
end - begin, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
begin ? nullptr : &alignment, begin ? 0 : 1);
}
if (!base) {
delete reservation;
return nullptr;
}
Lock lock;
const auto b = reinterpret_cast<uintptr_t>(base);
// A range the title released with VirtualFree may come back: drop stale records over it.
for (Reservation** link = &reservations; *link;) {
if ((*link)->begin < b + (end - begin) && b < (*link)->end) {
Reservation* stale = *link;
*link = stale->next;
delete stale;
} else {
link = &(*link)->next;
}
}
*reservation = {b, b + (end - begin), page, protect, reservations};
reservations = reservation;
return base;
}
} // namespace bx_xmem
// Diagnostics (off unless BX_XMEM_TRACE=1): one line per map call (address, count, first and last
// tag; Scatter: first and last slot too), up to 4000 calls.
bool xmem_trace_on() {
static const bool on = [] {
char v[4];
const DWORD n = GetEnvironmentVariableA("BX_XMEM_TRACE", v, sizeof(v));
return n > 0 && n < sizeof(v) && v[0] == '1';
}();
return on;
}
void trace_map(const char* kind, const void* first_address, const void* last_address, ULONG_PTR count,
const ULONG_PTR* tags) {
static LONG traced = 0;
if (!xmem_trace_on() || InterlockedIncrement(&traced) > 4000) return;
char detail[200];
std::snprintf(detail, sizeof(detail), "%s va=%p..%p count=%llu tags=%llx..%llx", kind, first_address, last_address,
static_cast<unsigned long long>(count), tags ? static_cast<unsigned long long>(tags[0]) : 0ull,
tags ? static_cast<unsigned long long>(tags[count - 1]) : 0ull);
bx_log_emit(BX_LOG_INFO, "xmem", "map_trace", detail);
}
// Authorized GDK documentation: XMemAllocatePhysicalPages(XMemFlags, NumberOfPages,
// PageArray), in 64 KB pages. XMEM_2MB_CLUSTERS is not implemented.
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR num_pages,
PULONG_PTR page_array) {
if ((flags & mem_64k_pages) == mem_64k_pages) flags &= ~mem_64k_pages; // 64 KB pages: the default
if ((flags & ~(xmem_2mb_clusters | xmem_bandwidth_bits)) != 0 || !num_pages || !page_array
|| !valid_span(nullptr, *num_pages, small_page)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (flags & xmem_2mb_clusters) {
BX_STUB_LOG("xmem.dll", "XMemAllocatePhysicalPages(XMEM_2MB_CLUSTERS)");
SetLastError(ERROR_NOT_SUPPORTED);
return FALSE;
}
const SIZE_T size = small_page;
Lock lock;
const SIZE_T count = *num_pages;
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
if (count > (kTagLimit - next_tag) / kFramesPerPage
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|| count > std::numeric_limits<uint64_t>::max() / size) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
@@ -260,6 +623,10 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR p
}
const uint64_t total_bytes = static_cast<uint64_t>(count) * size;
if (!bx_xmem::try_reserve_physical(total_bytes)) {
char detail[128];
std::snprintf(detail, sizeof(detail), "XMemAllocatePhysicalPages flags=0x%llx pages=%llu exceeds the physical budget",
static_cast<unsigned long long>(flags), static_cast<unsigned long long>(count));
bx_log_emit(BX_LOG_WARN, "xmem", "physical_budget_exceeded", detail);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
@@ -270,49 +637,64 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR p
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, entries, blocks};
const HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
static_cast<DWORD>(total_bytes >> 32),
static_cast<DWORD>(total_bytes & 0xFFFFFFFFu), nullptr);
if (!section) {
const DWORD error = GetLastError();
char detail[128];
std::snprintf(detail, sizeof(detail), "CreateFileMappingW for %llu pages failed error=%lu",
static_cast<unsigned long long>(count), static_cast<unsigned long>(error));
bx_log_emit(BX_LOG_WARN, "xmem", "physical_pages_failed", detail);
delete[] entries;
bx_xmem::release_physical(total_bytes);
SetLastError(error);
return FALSE;
}
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, section, entries, blocks};
if (!block) {
CloseHandle(section);
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};
}
for (SIZE_T i = 0; i < count; ++i) entries[i] = {block, true, false};
blocks = block;
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
next_tag += count;
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i * kFramesPerPage;
if (xmem_trace_on()) {
char detail[160];
std::snprintf(detail, sizeof(detail), "allocate flags=0x%llx count=%llu tags=%llx..%llx",
static_cast<unsigned long long>(flags), static_cast<unsigned long long>(count),
static_cast<unsigned long long>(next_tag),
static_cast<unsigned long long>(next_tag + (count - 1) * kFramesPerPage));
bx_log_emit(BX_LOG_INFO, "xmem", "alloc_trace", detail);
}
next_tag += count * kFramesPerPage;
next_tag = (next_tag + kTagAlignment - 1) & ~(kTagAlignment - 1);
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)) {
// XMemFreePhysicalPages(NumberOfPages, PageArray). Unknown or duplicate tags in `page_array`
// fail with ERROR_INVALID_PARAMETER without changing `page_array` or live views.
extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_array) {
if (xmem_trace_on() && page_array && count) {
char detail[160];
std::snprintf(detail, sizeof(detail), "free count=%llu tags=%llx..%llx", static_cast<unsigned long long>(count),
static_cast<unsigned long long>(page_array[0]), static_cast<unsigned long long>(page_array[count - 1]));
bx_log_emit(BX_LOG_INFO, "xmem", "free_trace", detail);
}
if (!page_array || !valid_span(nullptr, count, small_page)) {
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;
if (!page || page->releasing) break;
page->releasing = true;
}
if (validated != count) {
@@ -322,22 +704,17 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_
}
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;
if (!drop_pages(link, [](const Page* page, uintptr_t) { return page->releasing; })) {
const DWORD error = GetLastError();
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
SetLastError(error);
return FALSE;
}
}
for (SIZE_T i = 0; i < count; ++i) {
Page* page = find_page(page_array[i]);
CloseHandle(page->section);
page->section = nullptr;
page->allocated = false;
--page->block->live;
page_array[i] = 0;
}
@@ -350,18 +727,115 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_
delete_block(block);
}
}
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
bx_xmem::release_physical(static_cast<uint64_t>(count) * small_page);
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);
// XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray). The address must lie in an
// XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE) reservation. A NULL address is a
// BetterXen extension (see map_unreserved); a span mapped that way is unmapped as a whole.
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PULONG_PTR page_array) {
if (count) trace_map("map", address, static_cast<BYTE*>(address) + (count - 1) * small_page, count, page_array);
if (!valid_span(address, count, small_page)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
if (!have_placeholder_api()) return nullptr;
Lock lock;
auto* base = static_cast<BYTE*>(address);
const auto begin = reinterpret_cast<uintptr_t>(address);
if (address) {
if (Reservation* reservation = find_reservation(begin, begin + count * small_page)) {
return map_reserved(reservation, base, count, page_array);
}
if (!page_array) return unmap_span(base, count, small_page);
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
if (!page_array) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
return map_unreserved(count, 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);
// XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray): parallel arrays of
// 64 KB slots in XMEM_MAPPABLE reservations and page tags. A NULL `page_array`, or a 0 tag,
// unmaps the slot. All entries are checked before any is changed.
static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_array);
extern "C" BOOL WINAPI XMemMapPhysicalPagesScatter(PVOID* addresses, ULONG_PTR count,
PULONG_PTR page_array) {
const BOOL ok = scatter_impl(addresses, count, page_array);
if (!ok) {
const DWORD error = GetLastError();
static LONG logged = 0;
if (InterlockedIncrement(&logged) <= 32) {
// The first entry that is not a mappable 64 KB slot or names an unknown page.
ULONG_PTR bad = count;
for (ULONG_PTR k = 0; addresses && k < count; ++k) {
const auto slot = reinterpret_cast<uintptr_t>(addresses[k]);
Lock lock;
const bool slot_ok = slot % small_page == 0 && find_reservation(slot, slot + small_page);
const bool page_ok = !page_array || !page_array[k] || find_page(page_array[k]);
if (!slot_ok || !page_ok) { bad = k; break; }
}
char detail[200];
std::snprintf(detail, sizeof(detail), "scatter of %llu slots failed error=%lu; first bad entry %llu: slot %p tag 0x%llx",
static_cast<unsigned long long>(count), static_cast<unsigned long>(error),
static_cast<unsigned long long>(bad), bad < count ? addresses[bad] : nullptr,
bad < count && page_array ? static_cast<unsigned long long>(page_array[bad]) : 0ull);
bx_log_emit(BX_LOG_WARN, "xmem", "scatter_failed", detail);
}
SetLastError(error);
}
return ok;
}
static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_array) {
if (addresses && count) trace_map("scatter", addresses[0], addresses[count - 1], count, page_array);
if (!addresses || !count) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (!have_placeholder_api()) return FALSE;
Lock lock;
for (ULONG_PTR i = 0; i < count; ++i) {
const auto slot = reinterpret_cast<uintptr_t>(addresses[i]);
Reservation* reservation = slot % small_page == 0 ? find_reservation(slot, slot + small_page) : nullptr;
if (!reservation || (page_array && page_array[i] && !find_page(page_array[i]))) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (reservation->page != small_page) {
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPagesScatter(MEM_2MB_PAGES)");
SetLastError(ERROR_NOT_SUPPORTED);
return FALSE;
}
}
// Entries whose slots and pages both advance by one form a run, unmapped and mapped at once.
for (ULONG_PTR i = 0; i < count;) {
auto* slot = static_cast<BYTE*>(addresses[i]);
const auto begin = reinterpret_cast<uintptr_t>(slot);
const ULONG_PTR tag = page_array ? page_array[i] : 0;
const Reservation* reservation = find_reservation(begin, begin + small_page);
ULONG_PTR j = i + 1;
while (j < count && reinterpret_cast<uintptr_t>(addresses[j]) == begin + (j - i) * small_page &&
find_reservation(begin, begin + (j - i + 1) * small_page) == reservation &&
(tag ? page_array[j] == tag + (j - i) * kFramesPerPage && find_page(page_array[j]) &&
follows(find_page(page_array[j - 1]), find_page(page_array[j]))
: !(page_array && page_array[j]))) {
++j;
}
if (!unmap_range(begin, begin + (j - i) * small_page)) return FALSE;
if (tag) {
View* view = map_run(find_page(tag), j - i, slot, reservation->protect);
if (!view) return FALSE;
publish(view);
}
i = j;
}
return TRUE;
}
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
@@ -369,15 +843,17 @@ extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info
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) {
if (va >= view_begin(view) && va < view_end(view)) {
// Reported per 64 KB page, as when every page had its own view.
const SIZE_T index = (va - view_begin(view)) / small_page;
const uintptr_t base = view_begin(view) + index * small_page;
const SIZE_T size = view->page->block->size;
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(view->address, &region, sizeof(region))
if (!VirtualQuery(reinterpret_cast<void*>(base), &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)};
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page + index)};
return 1;
}
}
+134 -20
View File
@@ -2,6 +2,7 @@
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
@@ -63,6 +64,10 @@ CommitTable virtual_commits;
uint64_t heap_bytes = 0;
uint64_t virtual_bytes = 0;
uint64_t physical_bytes = 0;
/* Bytes admitted through bx_xmem_try_charge_external() on behalf of other
* DLLs (e.g. d3d12_xs private host heaps). Counted in can_commit so both
* allocation orders (graphics-first or xmem-first) obey one title cap. */
uint64_t external_bytes = 0;
uint64_t peak_bytes = 0;
uint64_t title_limit() {
@@ -72,12 +77,12 @@ uint64_t title_limit() {
bool can_commit(uint64_t bytes) {
const uint64_t limit = title_limit();
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes + external_bytes;
return used <= limit && bytes <= limit - used;
}
void update_peak() {
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes + external_bytes);
}
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
@@ -110,14 +115,29 @@ bool refresh_virtual_commits() {
return true;
}
void report_unsupported_host_hooks() {
static const bool reported = [] {
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
// XMEM_SET_ALLOCATION_HOOKS (xmem.h, authorized GDK documentation): the title exports
// `__XMemAllocationHooks__ = { AllocRoutine, FreeRoutine }`, and XMemAlloc / XMemFree call those
// routines instead of the default allocator. A hook usually handles the allocations it cares
// about and passes the rest to XMemAllocDefault / XMemFreeDefault.
struct AllocationHooks {
PVOID (WINAPI* alloc)(SIZE_T size, ULONGLONG attributes);
VOID (WINAPI* free)(PVOID address, ULONGLONG attributes);
};
const AllocationHooks& title_hooks() {
static const AllocationHooks hooks = [] {
AllocationHooks found{};
const auto* exported = reinterpret_cast<const AllocationHooks*>(
reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")));
if (exported) found = *exported;
if (found.alloc || found.free) {
char detail[96];
std::snprintf(detail, sizeof(detail), "alloc=%d free=%d", found.alloc ? 1 : 0, found.free ? 1 : 0);
bx_log_emit(BX_LOG_INFO, "xmem", "allocation_hooks", detail);
}
return true;
return found;
}();
(void)reported;
return hooks;
}
SIZE_T page_size() {
@@ -168,29 +188,94 @@ VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
}
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
report_unsupported_host_hooks();
if (const auto alloc = title_hooks().alloc) return alloc(size, attributes);
return XMemAllocDefault(size, attributes);
}
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
report_unsupported_host_hooks();
if (const auto free_routine = title_hooks().free) {
free_routine(address, attributes);
return;
}
XMemFreeDefault(address, attributes);
}
PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect) {
/*
* XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection), as the
* authorized GDK documentation gives it. AllocationType may carry MEM_64K_PAGES (0x20400000) or
* MEM_2MB_PAGES (0x20000000). An XMEM_MAPPABLE (0x20) reservation is a placeholder for
* XMemMapPhysicalPages. The other XMemFlags (CPU, graphics, address-width limits) select
* console memory types the host does not distinguish, so plain reservations and commits
* ignore them.
*/
PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
DWORD protect) {
constexpr DWORD mem_64k_pages = 0x20400000;
constexpr DWORD mem_2mb_pages = 0x20000000;
constexpr DWORD mem_reserve_placeholder = 0x00040000;
constexpr DWORD mem_replace_placeholder = 0x00004000;
constexpr uint64_t xmem_mappable = 0x20;
constexpr uint64_t xmem_graphics_32bit_address = 0x7;
// PAGE_GRAPHICS_* bits (0x800 and up) set the GPU view, which the host does not have; the
// CPU protection is the low byte.
const DWORD cpu_protect = protect & 0xFF;
const uintptr_t highest = (xmem_flags & xmem_graphics_32bit_address) == xmem_graphics_32bit_address
? 0xFFFFFFFFull : 0;
if (xmem_flags & xmem_mappable) {
const SIZE_T mappable_page = (alloc_type & mem_64k_pages) == mem_64k_pages ? 64 * 1024
: (alloc_type & mem_2mb_pages) ? 2 * 1024 * 1024 : 0;
if (!mappable_page || !(alloc_type & MEM_RESERVE) || (alloc_type & MEM_COMMIT)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
return bx_xmem::reserve_mappable(address, size, mappable_page, cpu_protect,
(alloc_type & mem_replace_placeholder) != 0, highest);
}
// A GPU-only reservation of 64 KiB or 2 MiB pages (no CPU access, a PAGE_GRAPHICS_* bit set) is
// a GPU address window the title fills with CopyPageMappingsX / CopyPageMappingsBatchX. It is
// reserved as a mappable placeholder so the page-pool pages can be mapped into it; the views
// are CPU readable and writable, since BetterXen works the GPU side through CPU addresses.
const bool large_pages = (alloc_type & mem_64k_pages) == mem_64k_pages || (alloc_type & mem_2mb_pages);
if (large_pages && (alloc_type & MEM_RESERVE) && !(alloc_type & (MEM_COMMIT | mem_replace_placeholder)) &&
cpu_protect == PAGE_NOACCESS && (protect & ~0xFFu) != 0) {
const SIZE_T window_page = (alloc_type & mem_64k_pages) == mem_64k_pages ? 64 * 1024 : 2 * 1024 * 1024;
PVOID window = bx_xmem::reserve_mappable(address, size, window_page, PAGE_READWRITE, false, highest);
char detail[200];
std::snprintf(detail, sizeof(detail), "GPU window %p size=0x%llx page=0x%llx flags=0x%llx protect=0x%lx -> %p",
address, static_cast<unsigned long long>(size), static_cast<unsigned long long>(window_page),
static_cast<unsigned long long>(xmem_flags), static_cast<unsigned long>(protect), window);
bx_log_emit(window ? BX_LOG_INFO : BX_LOG_WARN, "xmem", "gpu_window", detail);
return window;
}
if (alloc_type & mem_reserve_placeholder) {
if ((alloc_type & (MEM_COMMIT | mem_replace_placeholder)) || !(alloc_type & MEM_RESERVE)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
return bx_xmem::reserve_placeholder(address, size, highest);
}
if (alloc_type & mem_replace_placeholder) {
// Committing over a title-managed placeholder is not implemented (no caller seen yet).
BX_STUB_LOG("xmem.dll", "XMemVirtualAlloc(MEM_REPLACE_PLACEHOLDER)");
SetLastError(ERROR_NOT_SUPPORTED);
return nullptr;
}
/* Strip console-only high bits before forwarding to standard Win32 VirtualAlloc. */
DWORD win_alloc = alloc_type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN);
if (win_alloc == 0) win_alloc = MEM_COMMIT | MEM_RESERVE;
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
DWORD low_prot = protect & 0xFFu;
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
: PAGE_READWRITE;
const DWORD win_prot = protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE);
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
* early here cannot commit pages outside the working-set budget. */
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
return VirtualAlloc(address, size, win_alloc, win_prot);
PVOID result = VirtualAlloc(address, size, win_alloc, win_prot);
if (size >= (SIZE_T{256} << 20)) {
char detail[200];
std::snprintf(detail, sizeof(detail), "reserve %p size=0x%llx type=0x%lx flags=0x%llx protect=0x%lx -> %p",
address, static_cast<unsigned long long>(size), static_cast<unsigned long>(alloc_type),
static_cast<unsigned long long>(xmem_flags), static_cast<unsigned long>(protect), result);
bx_log_emit(BX_LOG_INFO, "xmem", "large_reservation", detail);
}
return result;
}
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
@@ -290,7 +375,7 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
std::memset(out_stats, 0, stats_size);
std::memcpy(out_stats, &stats, sizeof(stats));
return TRUE;
@@ -306,10 +391,39 @@ void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
// The internal ABI has no error return. Preserve the most recent
// accounting snapshot if refreshing it runs out of bookkeeping memory.
std::lock_guard guard(usage_lock);
*out_stats = {title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
*out_stats = {title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
}
}
int bx_xmem_try_charge_external(uint64_t bytes) {
std::lock_guard guard(usage_lock);
if (!can_commit(bytes)) {
if (!refresh_virtual_commits()) {
// Bookkeeping ran out of memory: not a budget decision, so say so.
bx_log_emit(BX_LOG_ERROR, "xmem", "external_charge",
"refresh_virtual_commits failed; charge refused without a budget check");
return 0;
}
if (!can_commit(bytes)) {
return 0;
}
}
external_bytes += bytes;
update_peak();
return 1;
}
void bx_xmem_release_charge_external(uint64_t bytes) {
std::lock_guard guard(usage_lock);
if (bytes > external_bytes) {
// Refuse: zeroing would also drop other owners' outstanding charges.
bx_log_emit(BX_LOG_ERROR, "xmem", "external_charge",
"release exceeds outstanding external charge; counter left unchanged");
return;
}
external_bytes -= bytes;
}
} // extern "C"
namespace bx_xmem {
+14
View File
@@ -1,6 +1,8 @@
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
#include <windows.h>
#include <cstdint>
namespace bx_xmem {
@@ -10,6 +12,18 @@ namespace bx_xmem {
bool try_reserve_physical(uint64_t bytes);
void release_physical(uint64_t bytes);
// Reserves an XMEM_MAPPABLE range as a placeholder that XMemMapPhysicalPages maps into, and
// records its page size and the protection mapped views get. Returns the base, or NULL with
// the Win32 error set.
// With `adopt`, `address` is already a placeholder the title split out of its own
// MEM_RESERVE_PLACEHOLDER reservation (MEM_REPLACE_PLACEHOLDER) and is only recorded. A non-zero
// `highest` keeps a new reservation at or below that address (XMEM_GRAPHICS_32BIT_ADDRESS).
PVOID reserve_mappable(PVOID address, SIZE_T size, SIZE_T page, DWORD protect, bool adopt, uintptr_t highest);
// A MEM_RESERVE_PLACEHOLDER reservation the title manages itself (split with VirtualFree and
// MEM_PRESERVE_PLACEHOLDER). It is not recorded.
PVOID reserve_placeholder(PVOID address, SIZE_T size, uintptr_t highest);
} // namespace bx_xmem
#endif // BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
+62
View File
@@ -10,3 +10,65 @@ Every directory matching `test_*/CMakeLists.txt` is **auto-discovered** by `test
```sh
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_<shim>.exe
```
## Exit Status: Pass, Fail, and Unavailable
`bx-cli run` normally returns the guest's exit status. A timeout returns 124, a signal
returns 128 plus its number, and a cleanup failure raises an otherwise successful status
to at least 1. Fixtures that cannot reach a conclusion on the host report **exit 77**
and print `SKIP: <reason>` on stdout; for example
`test_d3dmetal_gpu_limits` skips when `d3d12.dll`, device creation, or shader model 6.6 is
unavailable.
A skip is **not** a pass and **not** a failure. AGENTS.md §5 forbids counting a skipped test
as a pass, so record the three outcomes separately:
```sh
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin \
--log /tmp/bx-test.jsonl --exe build-shims/bin/test_<shim>.exe
status=$?
case $status in
0) echo "PASS: test_<shim>" ;;
77) echo "UNAVAILABLE (skip): test_<shim> — see the SKIP line above" ;;
*) echo "FAIL: test_<shim> (exit $status)" ;;
esac
```
`bx-cli` does not itself reinterpret 77 (it is the guest's own status, and other fixtures use
their own conventions), so always read the status before reporting a run. For a fixture that
adopts this protocol, printing a `SKIP:` line without exit 77, or exiting 77 without one, is a
defect. Older per-check skip conventions, such as `test_d3d12_xs`, are separate: its `SKIP:`
lines are informational and the fixture exits according to `g_failures`.
## M2 First-Frame Fixture
The M2 fixture requires both the placed-resource and PresentX headers. Its CMake target fails
configuration if either provider contract is missing; the fixture must not be silently skipped.
Run it with a D3DMetal bottle:
```sh
target/debug/bx-cli run --bottle <d3dmetal_bottle> --backend d3dmetal \
--shims build-shims/bin --log /tmp/bx-m2-first-frame.jsonl \
--exe build-shims/bin/test_m2_first_frame.exe
```
Replace `<d3dmetal_bottle>` with the installed CrossOver bottle name.
To verify that the pixel comparison detects a mismatch, set the injection variable in the
launcher environment and opt into environment inheritance. `env -i` keeps this test-only
variable and the listed runtime essentials from exposing unrelated host environment values to
the guest:
```sh
env -i HOME="$HOME" USER="$USER" LOGNAME="$LOGNAME" TMPDIR=/tmp LANG=C \
PATH=/usr/bin:/bin:/usr/sbin:/sbin \
BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1 \
target/debug/bx-cli run --inherit-env --bottle <d3dmetal_bottle> --backend d3dmetal \
--shims build-shims/bin --log /tmp/bx-m2-first-frame-negative.jsonl \
--exe build-shims/bin/test_m2_first_frame.exe
```
Replace `<d3dmetal_bottle>` with the installed CrossOver bottle name.
The negative control should print `NOTE: pixel mismatch control armed` and exit 1.
The `pixel_readback` checkpoint should report `pixel (0,0) expected 01234567 got 9f598b46`.
@@ -0,0 +1,2 @@
add_executable(test_acphal_default_heap main.cpp)
target_link_libraries(test_acphal_default_heap PRIVATE acphal kernel32)
@@ -0,0 +1,90 @@
// AcpHal's default APU heap, in a fresh process: a title that allocates shape contexts before
// any ApuCreateHeap gets a 64 MB default heap (BetterXen's stand-in for the console's default
// non-cached APU heap). test_audio_input creates its own heap first, so this branch needs a
// process of its own.
//
// Expected values come from this file: 64 MiB is the documented-in-CHANGELOG default, so shape
// contexts of exactly 64 MiB must fit and 64 MiB + 64 bytes must not.
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <string>
extern "C" {
HRESULT WINAPI AcpHalAllocateShapeContexts(void*);
HRESULT WINAPI AcpHalReleaseShapeContexts(void);
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
void* WINAPI ApuMapApuAddress(uint32_t);
}
namespace {
int g_failures = 0;
void check(bool ok, const char* what) {
if (!ok) {
++g_failures;
std::printf("FAIL: test_acphal_default_heap: %s\n", what);
}
}
struct ShapeContexts {
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
void* arrays[6];
uint32_t apu[6];
};
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS");
constexpr uint32_t kXmaBytes = 64;
constexpr uint32_t kDefaultHeap = 64u << 20;
std::string read_log() {
char path[MAX_PATH];
std::string text;
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return text;
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
if (f == INVALID_HANDLE_VALUE) return text;
char buf[65536];
DWORD got = 0;
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
CloseHandle(f);
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++n;
return n;
}
} // namespace
int main() {
char probe[8];
if (GetEnvironmentVariableA("BX_LOG_FILE", probe, sizeof(probe)) == 0) {
std::printf("FAIL: test_acphal_default_heap: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
return 1;
}
// No ApuCreateHeap. One XMA element more than 64 MiB holds does not fit the default heap...
ShapeContexts too_big{};
too_big.counts[4] = kDefaultHeap / kXmaBytes + 1;
check(AcpHalAllocateShapeContexts(&too_big) == E_OUTOFMEMORY, "64 MiB + 64 bytes exceeds the default heap");
// ...and exactly 64 MiB does (the failed attempt above left nothing allocated).
ShapeContexts exact{};
exact.counts[4] = kDefaultHeap / kXmaBytes;
check(AcpHalAllocateShapeContexts(&exact) == S_OK && exact.arrays[4] && exact.apu[4],
"exactly 64 MiB of shape contexts fits the default heap");
check(exact.apu[4] && ApuMapApuAddress(exact.apu[4]) == exact.arrays[4], "the shape array is an APU heap allocation");
// The default heap is the heap: a later ApuCreateHeap finds one already created.
check(ApuCreateHeap(64, 64) == HRESULT_FROM_WIN32(ERROR_BUSY), "ApuCreateHeap after the default heap reports busy");
check(AcpHalReleaseShapeContexts() == S_OK, "release");
const std::string log = read_log();
check(count_of(log, "\"event\":\"apu_default_heap\"") == 1, "the default heap is created once and logged");
if (g_failures) {
std::printf("FAIL: test_acphal_default_heap (%d failed)\n", g_failures);
return 1;
}
std::printf("PASS: test_acphal_default_heap\n");
return 0;
}
+210 -5
View File
@@ -1,12 +1,17 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <thread>
extern "C" {
HRESULT WINAPI AcpHalCreate(void**);
HRESULT WINAPI AcpHalAllocateShapeContexts(void*);
HRESULT WINAPI AcpHalReleaseShapeContexts(void);
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
HRESULT WINAPI ApuFree(void*);
@@ -29,17 +34,133 @@ HRESULT WINAPI XDspDisconnect(void*);
namespace {
void WINAPI dummy_device_callback(uint64_t, void*, void*, uint64_t, uint32_t, uint32_t) {}
bool file_contains(const char* path, uint64_t offset, const char* needle_a, const char* needle_b) {
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (f == INVALID_HANDLE_VALUE) {
return false;
}
bool found = false;
LARGE_INTEGER size = {};
if (GetFileSizeEx(f, &size) && size.QuadPart >= 0 &&
offset <= static_cast<uint64_t>(size.QuadPart) &&
static_cast<uint64_t>(size.QuadPart) - offset < (64ull << 20)) {
LARGE_INTEGER pos{};
pos.QuadPart = static_cast<LONGLONG>(offset);
if (!SetFilePointerEx(f, pos, nullptr, FILE_BEGIN)) {
CloseHandle(f);
return false;
}
const DWORD remaining = static_cast<DWORD>(static_cast<uint64_t>(size.QuadPart) - offset);
auto* buf = static_cast<char*>(HeapAlloc(GetProcessHeap(), 0, static_cast<SIZE_T>(remaining) + 1));
DWORD total = 0;
while (buf && total < remaining) {
DWORD got = 0;
if (!ReadFile(f, buf + total, remaining - total, &got, nullptr) || got == 0) break;
total += got;
}
if (buf && total == remaining) {
buf[total] = '\0';
/* Both needles must sit on the same JSONL line. */
for (char* line = buf; line && *line && !found;) {
char* end = std::strchr(line, '\n');
if (end) *end = '\0';
found = std::strstr(line, needle_a) && std::strstr(line, needle_b);
line = end ? end + 1 : nullptr;
}
}
if (buf) HeapFree(GetProcessHeap(), 0, buf);
}
CloseHandle(f);
return found;
}
} // namespace
// Read the JSONL log the shim wrote, so the dispatcher's live-reference
// count can be checked rather than assumed. The log is the only place the
// count is observable: `Release` returning 0 proves the reference count
// reached zero, and the `dispatch_mode` lines prove the live-dispatcher
// counter followed it. They do not prove the object was freed: `Release`
// updates the counter before `delete this`, so a leak would not show here.
// `bx-cli run` appends to the supplied BX_LOG_FILE, so a re-run with the
// same log can pass from stale lines even if this run emits none. Capture
// the file's size before the run and assert only on the bytes appended by
// this run.
static uint64_t log_file_size(const char* path) {
if (!path || !*path) return 0;
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (f == INVALID_HANDLE_VALUE) return 0;
LARGE_INTEGER size{};
const BOOL ok = GetFileSizeEx(f, &size);
CloseHandle(f);
return ok ? static_cast<uint64_t>(size.QuadPart) : 0;
}
static std::string read_log_file_from(const char* path, uint64_t offset) {
std::string text;
if (!path || !*path) return text;
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (f == INVALID_HANDLE_VALUE) return text;
LARGE_INTEGER pos{};
pos.QuadPart = static_cast<LONGLONG>(offset);
if (!SetFilePointerEx(f, pos, nullptr, FILE_BEGIN)) {
CloseHandle(f);
return text;
}
char buf[4096];
DWORD got = 0;
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got > 0) {
text.append(buf, got);
}
CloseHandle(f);
return text;
}
int main() {
// The dispatcher checks below read the shim's JSONL log, so BX_LOG_FILE
// must name it before the process starts (`bx-cli run --log`). Setting it
// here would be too late: AcpHal.dll imports bx_runtime_veh.dll, which
// reads BX_LOG_FILE once in DLL_PROCESS_ATTACH, before main runs.
char dispatcher_log_path[MAX_PATH]{};
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", dispatcher_log_path, sizeof(dispatcher_log_path));
if (n == 0 || n >= sizeof(dispatcher_log_path)) {
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
return 1;
}
const uint64_t log_start = log_file_size(dispatcher_log_path);
// IAcpHal is not a COM interface (authorized GDK documentation): slots Connect(numCommands,
// numMessages), Disconnect(), SubmitCommand(command, id, audioFrame, data, notification),
// PopMessage(message), GetNumMessages() and Release(). BetterXen has no ACP: commands are
// accepted and no message arrives.
void* object = nullptr;
CHECK(AcpHalCreate(&object) == S_OK && object);
auto* hal = static_cast<IUnknown*>(object);
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
CHECK(hal->Release() == 1);
void* hal = object;
const void* const* acp = *static_cast<const void* const* const*>(hal);
using ConnectFn = HRESULT(WINAPI*)(void*, uint32_t, uint32_t);
using DisconnectFn = HRESULT(WINAPI*)(void*);
using SubmitFn = HRESULT(WINAPI*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
using PopFn = bool(WINAPI*)(void*, void*);
using CountFn = uint32_t(WINAPI*)(void*);
using ReleaseFn = void(WINAPI*)(void*);
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == E_UNEXPECTED); // before Connect
CHECK(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000) == S_OK);
CHECK(FAILED(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000)));
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == S_OK);
unsigned char message[64]{};
CHECK(!reinterpret_cast<PopFn>(acp[3])(hal, message) && reinterpret_cast<CountFn>(acp[4])(hal) == 0);
CHECK(reinterpret_cast<DisconnectFn>(acp[1])(hal) == S_OK);
void *va = nullptr, *second = nullptr;
uint32_t base = 0, other = 0;
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
// A zero-capacity heap must not report S_OK: it can never satisfy an
// allocation (#580). ApuAlloc still refuses with E_OUTOFMEMORY.
CHECK(ApuCreateHeap(0, 0) == E_INVALIDARG);
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
CHECK(ApuCreateHeap(64, 64) == S_OK);
CHECK(ApuAlloc(&va, nullptr, 64, 64) == S_OK && va);
CHECK(ApuFree(va) == S_OK);
@@ -61,7 +182,48 @@ int main() {
CHECK(ApuFree(tail) == E_INVALIDARG);
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
CHECK(ApuFree(second) == S_OK);
reinterpret_cast<ReleaseFn>(acp[5])(hal);
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) (authorized GDK documentation): six counts in
// (SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM), six CPU pointers and six APU addresses out, the
// arrays from the APU heap (XMA elements are 64 bytes). A second allocation without a release
// fails with ACP_E_ALREADY_ALLOCATED (0x8AC80001).
struct ShapeContexts {
uint32_t counts[6];
void* arrays[6];
uint32_t apu[6];
};
static_assert(sizeof(ShapeContexts) == 96 && offsetof(ShapeContexts, arrays) == 24 &&
offsetof(ShapeContexts, apu) == 72,
"SHAPE_CONTEXTS layout");
constexpr HRESULT kAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_INVALIDARG);
CHECK(AcpHalReleaseShapeContexts() == S_OK); // nothing allocated
ShapeContexts shape{};
shape.counts[4] = 2; // two XMA contexts: 128 bytes, the whole 64 + 64 heap
CHECK(AcpHalAllocateShapeContexts(&shape) == S_OK);
CHECK(shape.arrays[4] && shape.apu[4] && ApuMapApuAddress(shape.apu[4]) == shape.arrays[4]);
CHECK(!shape.arrays[0] && !shape.arrays[5] && !shape.apu[0]);
CHECK(static_cast<const unsigned char*>(shape.arrays[4])[127] == 0); // zero-filled
ShapeContexts again{};
again.counts[4] = 1;
CHECK(AcpHalAllocateShapeContexts(&again) == kAlreadyAllocated);
CHECK(AcpHalReleaseShapeContexts() == S_OK && !ApuMapApuAddress(shape.apu[4]));
CHECK(AcpHalAllocateShapeContexts(&again) == S_OK && again.arrays[4]);
CHECK(AcpHalReleaseShapeContexts() == S_OK);
char log_path[MAX_PATH];
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
if (log_len > 0 && log_len < sizeof(log_path)) {
CHECK(file_contains(log_path, log_start, "\"event\":\"shape_contexts_allocated\"", "xma=2"));
CHECK(file_contains(log_path, log_start, "\"event\":\"connect\"", "commands=4096"));
} else {
// Unreachable under `bx-cli run --log`. A SKIP that still exits 0 would
// contradict the exit-77 protocol, so a missing log is a failure.
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
return 1;
}
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
@@ -186,8 +348,51 @@ int main() {
CHECK(!unreg_cb(v0, tok2, 0));
set_focus(v0, 0x2);
// Slot 14: IGameInput::CreateDispatcher. The singleton refcount is checked
// below via the pre-existing GameInput release sequence, which must be
// unchanged by dispatcher creation.
using CreateDispatcherFn = HRESULT (WINAPI*)(IUnknown*, void**);
using DispatchFn = bool (WINAPI*)(IUnknown*, uint64_t);
using OpenWaitHandleFn = HRESULT (WINAPI*)(IUnknown*, HANDLE*);
auto create_dispatcher = reinterpret_cast<CreateDispatcherFn>(table[14]);
CHECK(create_dispatcher(v0, nullptr) == E_POINTER);
void* dispatcher = reinterpret_cast<void*>(uintptr_t{1});
CHECK(create_dispatcher(v0, &dispatcher) == S_OK && dispatcher);
auto* disp_unknown = static_cast<IUnknown*>(dispatcher);
auto** disp_table = *reinterpret_cast<void***>(disp_unknown);
void* disp_qi = nullptr;
CHECK(reinterpret_cast<HRESULT (WINAPI*)(IUnknown*, REFIID, void**)>(disp_table[0])(
disp_unknown, IID_IUnknown, &disp_qi) == S_OK && disp_qi == dispatcher);
CHECK(disp_unknown->Release() == 1);
void* disp_other = reinterpret_cast<void*>(uintptr_t{1});
CHECK(reinterpret_cast<HRESULT (WINAPI*)(IUnknown*, REFIID, void**)>(disp_table[0])(
disp_unknown, kUnknownIid, &disp_other) == E_NOINTERFACE && !disp_other);
auto dispatch = reinterpret_cast<DispatchFn>(disp_table[3]);
CHECK(!dispatch(disp_unknown, 0));
CHECK(!dispatch(disp_unknown, 1000000));
auto open_wait = reinterpret_cast<OpenWaitHandleFn>(disp_table[4]);
CHECK(open_wait(disp_unknown, nullptr) == E_POINTER);
HANDLE wait1 = nullptr, wait2 = nullptr;
CHECK(open_wait(disp_unknown, &wait1) == S_OK && wait1);
CHECK(WaitForSingleObject(wait1, 0) == WAIT_TIMEOUT);
CHECK(open_wait(disp_unknown, &wait2) == S_OK && wait2 && wait2 != wait1);
CHECK(CloseHandle(wait1) && CloseHandle(wait2));
CHECK(disp_unknown->Release() == 0);
// `dispatch_mode` logs each manual/automatic transition with the live
// dispatcher count. These checks catch a Release that never calls
// `on_dispatcher_released` (no `live_dispatchers=0` line). They cannot
// catch a missing `delete this`, which runs after the counter update.
{
const std::string log = read_log_file_from(dispatcher_log_path, log_start);
CHECK(log.find("live_dispatchers=1") != std::string::npos);
CHECK(log.find("live_dispatchers=0") != std::string::npos);
CHECK(log.find("mode=manual") != std::string::npos);
CHECK(log.find("mode=automatic") != std::string::npos);
}
CHECK(v0->Release() == 1);
CHECK(input->Release() == 0);
FreeLibrary(dll);
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1 and device callbacks");
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1, device callbacks, dispatcher");
}
+264 -32
View File
@@ -25,12 +25,27 @@
extern "C" {
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void* params, REFIID riid, void** ppv);
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* count, PULONG_PTR pages, uint64_t flags);
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(SIZE_T* count, PULONG_PTR pages, uint64_t flags);
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags, PULONG_PTR pages);
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
__declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes);
__declspec(dllimport) VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR count, PULONG_PTR pages);
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages);
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, ULONG_PTR count, PULONG_PTR pages);
__declspec(dllimport) BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size);
}
struct bx_xmem_stats_t {
uint64_t title_limit_bytes;
uint64_t committed_virtual_bytes;
uint64_t allocated_physical_bytes;
uint64_t peak_committed_bytes;
};
static_assert(sizeof(bx_xmem_stats_t) == 32, "xmem stats struct is 32 bytes");
/* D3D12XboxCreateDevice requires a D3D12XBOX_CREATE_DEVICE_PARAMETERS block (80 bytes on Xbox
Series); a zeroed one asks for defaults. Only its Version field is read by the shim. */
alignas(8) static const unsigned char kCreateParams[80] = {};
struct BxD3d12VirtualMemoryConfig {
uint32_t magic;
uint32_t struct_size;
@@ -77,6 +92,7 @@ static_assert(kFootprint <= kAlign, "texture footprint fits in one 64 KiB page")
static_assert(kRegionBytes == 128ull * 1024ull, "configured region is 128 KiB");
int g_checks = 0;
int g_skipped = 0;
int g_failures = 0;
__attribute__((format(gnu_printf, 2, 3)))
@@ -331,7 +347,7 @@ DWORD WINAPI check_device_startup(LPVOID context) {
return 1;
}
ID3D12Device* device = nullptr;
result.device_hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
result.device_hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (SUCCEEDED(result.device_hr) && device) {
const auto desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, 600ull << 20, D3D12_HEAP_FLAG_NONE);
ID3D12Heap* heap = nullptr;
@@ -365,7 +381,62 @@ void check_concurrent_device_startup() {
CloseHandle(start);
}
void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64_t region_base, uint64_t cap) {
/* #554/#572: the three placement entry points. `entry` 0 is CreatePlacedResource
(slot 29), 1 is CreatePlacedResource1 (ID3D12Device8 slot 70), 2 is
CreatePlacedResource2 (ID3D12Device10 slot 77). A buffer on entry 2 uses the
UNDEFINED layout that enhanced barriers require for buffers. Returns false in
*available when the device does not expose that entry point. */
const char* const kPlaceName[3] = {"CreatePlacedResource", "CreatePlacedResource1", "CreatePlacedResource2"};
HRESULT place_buffer(ID3D12Device* device, int entry, ID3D12Heap* heap, UINT64 offset, uint64_t bytes,
D3D12_RESOURCE_STATES state, ID3D12Resource** out, bool* available) {
*out = reinterpret_cast<ID3D12Resource*>(static_cast<uintptr_t>(0x1));
*available = true;
const D3D12_RESOURCE_DESC desc = buffer_desc(bytes);
if (entry == 0) {
return device->CreatePlacedResource(heap, offset, &desc, state, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(out));
}
D3D12_RESOURCE_DESC1 desc1{};
desc1.Dimension = desc.Dimension;
desc1.Width = desc.Width;
desc1.Height = desc.Height;
desc1.DepthOrArraySize = desc.DepthOrArraySize;
desc1.MipLevels = desc.MipLevels;
desc1.Format = desc.Format;
desc1.SampleDesc = desc.SampleDesc;
desc1.Layout = desc.Layout;
HRESULT hr = E_NOINTERFACE;
if (entry == 1) {
ID3D12Device8* dev8 = nullptr;
if (device->QueryInterface(__uuidof(ID3D12Device8), reinterpret_cast<void**>(&dev8)) == S_OK && dev8) {
hr = dev8->CreatePlacedResource1(heap, offset, &desc1, state, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(out));
dev8->Release();
return hr;
}
} else {
ID3D12Device10* dev10 = nullptr;
if (device->QueryInterface(__uuidof(ID3D12Device10), reinterpret_cast<void**>(&dev10)) == S_OK && dev10) {
hr = dev10->CreatePlacedResource2(heap, offset, &desc1, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 0,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(out));
dev10->Release();
return hr;
}
}
*out = nullptr;
*available = false;
return hr;
}
void skip_case(const char* what, const char* why) {
++g_skipped;
std::printf("SKIP: %s: %s\n", what, why);
std::fflush(stdout);
}
void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64_t region_base, uint64_t cap,
int entry) {
const bool capped = cap == (512ull << 20);
const uint64_t heap_bytes = capped ? 300ull << 20 : kAlign;
const auto heap_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, heap_bytes, D3D12_HEAP_FLAG_NONE);
@@ -375,11 +446,17 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
return;
}
ID3D12Resource* resource = nullptr;
const auto desc = buffer_desc(kBufBytes);
hr = device->CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
bool available = true;
hr = place_buffer(device, entry, heap, 0, kBufBytes, D3D12_RESOURCE_STATE_GENERIC_READ, &resource, &available);
heap->Release();
if (!check(hr == S_OK && resource, "placed resource can outlive the caller's heap reference hr=0x%08lx", ul(hr))) {
if (!available) {
skip_case(kPlaceName[entry], "the device does not expose this entry point for the heap-charge check");
return;
}
if (!check(hr == S_OK && resource, "%s resource can outlive the caller's heap reference hr=0x%08lx",
kPlaceName[entry], ul(hr))) {
if (hr != S_OK) resource = nullptr;
if (resource) resource->Release();
return;
}
@@ -392,7 +469,7 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
auto cfg = make_block(region_base, kRegionBytes, kFlagBacking);
hr = D3D12ConfigureVirtualMemoryX(&cfg);
check(hr == S_OK && last_log_u64(log_path, "gpu_heap_bytes=") == kRegionBytes + heap_bytes,
"live placed resource keeps the original heap charge");
"live %s resource keeps the original heap charge", kPlaceName[entry]);
if (capped) {
ID3D12Heap* second = nullptr;
@@ -404,7 +481,7 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
resource->Release();
hr = D3D12ConfigureVirtualMemoryX(&cfg);
check(hr == S_OK && last_log_u64(log_path, "gpu_heap_bytes=") == kRegionBytes,
"final placed resource release credits the original heap");
"final %s resource release credits the original heap", kPlaceName[entry]);
if (capped) {
ID3D12Heap* second = nullptr;
@@ -414,6 +491,150 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
}
}
/* #552: graphics-first / xmem-first pairing through the public exports.
* With a 512 MiB cap, a 300 MiB D3D12 heap registers an external charge in
* xmem. A 300 MiB XMemAlloc must then fail (300+300 > 512), and a 200 MiB
* XMemAlloc must succeed (300+200 <= 512). After releasing the heap the
* 300 MiB XMemAlloc must succeed. This is the graphics-first overcommit
* that the private-ledger version allowed. */
void check_graphics_xmem_pairing(ID3D12Device* device, uint64_t cap) {
if (cap != (512ull << 20)) {
/* The pairing sizes are fixed against a 512 MiB cap, so at any other cap the
* cross-DLL budget check does not run. Say so rather than pass silently. */
++g_skipped;
std::printf("SKIP: graphics/xmem pairing needs a 512 MiB cap "
"(BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env ...); this run's cap is %llu MiB\n",
static_cast<unsigned long long>(cap >> 20));
return;
}
const uint64_t heap_bytes = 300ull << 20;
const auto heap_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, heap_bytes, D3D12_HEAP_FLAG_NONE);
ID3D12Heap* heap = nullptr;
HRESULT hr = device->CreateHeap(&heap_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
if (!check(hr == S_OK && heap, "pairing: 300 MiB graphics heap hr=0x%08lx", ul(hr))) {
return;
}
bx_xmem_stats_t stats{};
check(XMemGetWorkingSetStatistics(&stats, sizeof(stats)) != 0, "pairing: xmem stats readable");
/* 300 MiB heap + 300 MiB xmem = 600 MiB > 512 MiB cap. */
void* too_much = XMemAlloc(300ull << 20, 0);
check(too_much == nullptr, "pairing: 300 MiB XMemAlloc on top of 300 MiB heap exceeds the 512 MiB cap");
if (too_much) XMemFree(too_much, 0);
/* 300 MiB heap + 200 MiB xmem = 500 MiB <= 512 MiB cap. */
void* fits = XMemAlloc(200ull << 20, 0);
check(fits != nullptr, "pairing: 200 MiB XMemAlloc fits beside the 300 MiB heap");
if (fits) XMemFree(fits, 0);
heap->Release();
/* After the heap charge is released the 300 MiB allocation must fit. */
void* after = XMemAlloc(300ull << 20, 0);
check(after != nullptr, "pairing: 300 MiB XMemAlloc fits after releasing the graphics heap");
if (after) XMemFree(after, 0);
}
/* #554/#572: an ordinary heap from CreateHeap gets the same placement checks as
the backing heap on every entry point. Each case is guarded by the alignment the
host reports for the buffer, so a host alignment that would make the offset
legal skips that case instead of passing it. */
void check_ordinary_placement(ID3D12Device* device) {
const uint64_t heap_bytes = 2 * kAlign;
const D3D12_HEAP_DESC def_desc = heap_of(D3D12_HEAP_TYPE_DEFAULT, heap_bytes, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS);
const D3D12_HEAP_DESC up_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, kAlign, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS);
ID3D12Heap* heap = nullptr;
ID3D12Heap* upload = nullptr;
HRESULT hr = device->CreateHeap(&def_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
if (!check(hr == S_OK && heap, "ordinary DEFAULT heap for placement checks hr=0x%08lx", ul(hr))) {
return;
}
hr = device->CreateHeap(&up_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&upload));
check(hr == S_OK && upload, "ordinary UPLOAD heap for placement checks hr=0x%08lx", ul(hr));
const D3D12_RESOURCE_DESC one = buffer_desc(kAlign);
const D3D12_RESOURCE_DESC two = buffer_desc(2 * kAlign);
const D3D12_RESOURCE_ALLOCATION_INFO one_info = device->GetResourceAllocationInfo(0, 1, &one);
const D3D12_RESOURCE_ALLOCATION_INFO two_info = device->GetResourceAllocationInfo(0, 1, &two);
std::printf("ordinary_buffer_alloc align=%llu one=%llu two=%llu\n",
static_cast<unsigned long long>(one_info.Alignment),
static_cast<unsigned long long>(one_info.SizeInBytes),
static_cast<unsigned long long>(two_info.SizeInBytes));
std::fflush(stdout);
const bool info_ok = one_info.SizeInBytes != 0 && one_info.SizeInBytes != ~0ull && two_info.SizeInBytes != 0 &&
two_info.SizeInBytes != ~0ull;
const uint64_t align = one_info.Alignment;
const bool misaligned_real = info_ok && align != 0 && (256ull % align) != 0;
/* kAlign is aligned, and a 2*kAlign buffer at kAlign ends past a 2*kAlign heap. */
const bool overhang_real = info_ok && align != 0 && (kAlign % align) == 0 && two_info.SizeInBytes > kAlign;
const bool valid_real = info_ok && align != 0 && (kAlign % align) == 0 && one_info.SizeInBytes <= kAlign;
for (int entry = 0; entry < 3; ++entry) {
const char* name = kPlaceName[entry];
char what[96];
ID3D12Resource* res = nullptr;
bool available = true;
std::snprintf(what, sizeof(what), "%s misaligned offset on an ordinary heap", name);
if (misaligned_real) {
hr = place_buffer(device, entry, heap, 256, kAlign, D3D12_RESOURCE_STATE_COMMON, &res, &available);
if (!available) {
skip_case(name, "the device does not expose this entry point");
continue;
}
check(hr == E_INVALIDARG && res == nullptr, "%s returns E_INVALIDARG and null (alignment %llu) hr=0x%08lx",
what, static_cast<unsigned long long>(align), ul(hr));
if (hr == S_OK && res) res->Release();
} else {
skip_case(what, "the host's buffer alignment makes offset 256 legal");
}
std::snprintf(what, sizeof(what), "%s aligned overhang on an ordinary heap", name);
if (overhang_real) {
hr = place_buffer(device, entry, heap, kAlign, 2 * kAlign, D3D12_RESOURCE_STATE_COMMON, &res, &available);
if (!available) {
skip_case(name, "the device does not expose this entry point");
continue;
}
check(hr == E_INVALIDARG && res == nullptr, "%s returns E_INVALIDARG and null hr=0x%08lx", what, ul(hr));
if (hr == S_OK && res) res->Release();
} else {
skip_case(what, "the host's buffer alignment or size does not make it an aligned overhang");
}
std::snprintf(what, sizeof(what), "%s valid nonzero offset on an ordinary heap", name);
if (valid_real) {
hr = place_buffer(device, entry, heap, kAlign, kAlign, D3D12_RESOURCE_STATE_COMMON, &res, &available);
if (!available) {
skip_case(name, "the device does not expose this entry point");
continue;
}
check(hr == S_OK && res != nullptr, "%s succeeds hr=0x%08lx", what, ul(hr));
if (res && hr == S_OK) res->Release();
} else {
skip_case(what, "the host's buffer alignment or size does not fit offset 64 KiB");
}
if (entry == 2) {
/* CreatePlacedResource2 takes a barrier layout; the state rule does not apply. */
continue;
}
std::snprintf(what, sizeof(what), "%s UPLOAD heap with COPY_DEST state", name);
if (upload) {
hr = place_buffer(device, entry, upload, 0, 256, D3D12_RESOURCE_STATE_COPY_DEST, &res, &available);
if (!available) {
skip_case(name, "the device does not expose this entry point");
continue;
}
check(hr == E_INVALIDARG && res == nullptr, "%s returns E_INVALIDARG and null hr=0x%08lx", what, ul(hr));
if (hr == S_OK && res) res->Release();
}
}
if (upload) upload->Release();
heap->Release();
}
/* CreatePlacedResource1 must accept a heap from CreateHeap. CreatePlacedResource2
is checked only when the host device implements ID3D12Device10. */
void check_newer_placement(ID3D12Device* device) {
@@ -571,6 +792,9 @@ int main() {
return 1;
}
const char* profile = cfg->profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart";
char log_path[MAX_PATH];
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
check(D3D12ConfigureVirtualMemoryX(nullptr) == S_OK, "null configuration is a logged stub that returns S_OK");
@@ -664,9 +888,9 @@ int main() {
SIZE_T page_count = 2;
ULONG_PTR pages[2] = {};
uint8_t* view = nullptr;
bool mapped = XMemAllocatePhysicalPages(&page_count, pages, 0) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
bool mapped = XMemAllocatePhysicalPages(0, &page_count, pages) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
if (mapped) {
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, 0, pages));
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, pages));
mapped = view != nullptr && (reinterpret_cast<uintptr_t>(view) % kAlign) == 0;
if (mapped) {
view[kAlign] = 0x5A;
@@ -680,7 +904,7 @@ int main() {
check_concurrent_device_startup();
}
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(hr == S_OK && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) {
std::fprintf(stderr, "FAIL: test_d3d12_placed (no device. %d of %d checks failed)\n", g_failures, g_checks);
return 1;
@@ -1239,9 +1463,6 @@ int main() {
}
}
char log_path[MAX_PATH];
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
std::printf("RESULT: cpu_va=0x%llx map=0x%llx buffer_gpu_va=0x%llx flush=%d copy_buffer=%u/%u copy_texture=%u/%u "
"texture_path=%s cpu_after_gpu=%u/%u small_align=%llu upload_100000=%llu\n",
static_cast<unsigned long long>(cpu_va), static_cast<unsigned long long>(map_pointer),
@@ -1291,7 +1512,13 @@ int main() {
if (placed_buf) placed_buf->Release();
if (mapped && backing && have_log) {
check_placed_heap_charge(device, log_path, region_base, cfg->title_memory_limit_bytes);
for (int entry = 0; entry < 3; ++entry) {
check_placed_heap_charge(device, log_path, region_base, cfg->title_memory_limit_bytes, entry);
}
}
if (device) {
check_graphics_xmem_pairing(device, cfg->title_memory_limit_bytes);
}
/*
@@ -1299,7 +1526,7 @@ int main() {
* caller's device reference must leave the proxy alive for GetDevice.
*/
ID3D12Device* side = nullptr;
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&side));
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&side));
check(hr == S_OK && side, "side device for the ordinary-heap lifetime check hr=0x%08lx", ul(hr));
if (side) {
D3D12_HEAP_DESC side_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, kAlign, D3D12_HEAP_FLAG_NONE);
@@ -1338,7 +1565,11 @@ int main() {
* section. There is no timing stress test for those windows.
*/
check_newer_placement(device);
check_ordinary_placement(device);
uint64_t host_before = 0;
uint64_t host_ignored = 0;
int host_before_count = 0;
if (backing) {
BxD3d12VirtualMemoryConfig detached = make_block(0, 0, kFlagBacking);
const HRESULT away = D3D12ConfigureVirtualMemoryX(&detached);
@@ -1351,7 +1582,7 @@ int main() {
device = nullptr;
backing->Release();
backing = nullptr;
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
check(hr == S_OK && device, "device recreated after the detach check hr=0x%08lx", ul(hr));
if (device && mapped) {
BxD3d12VirtualMemoryConfig again = make_block(region_base, kRegionBytes, kFlagBacking);
@@ -1370,6 +1601,10 @@ int main() {
SetEnvironmentVariableA("BX_D3D12_FORCE_BACKING_REPLACE", nullptr);
check(hr == S_OK && replaced && !same_object(replaced, backing),
"forced host replacement publishes a different backing heap hr=0x%08lx", ul(hr));
if (have_log) {
/* Capture the device whose forced replacement heap remains in the cache. */
log_u64_ends(log_path, "host_device=", &host_ignored, &host_before, &host_before_count);
}
check(get_device_closed(backing), "GetDevice on the heap replaced by another host device fails closed");
const ULONG left = device->Release();
check(left == 0, "proxy released to zero while the replaced heap is still held (refs=%lu)", left);
@@ -1377,7 +1612,7 @@ int main() {
backing->Release();
backing = replaced;
device = nullptr;
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
check(hr == S_OK && device, "device recreated after the replacement check hr=0x%08lx", ul(hr));
if (device && mapped && backing) {
/* The replacement already published a heap for this region. A same-host
@@ -1405,16 +1640,14 @@ int main() {
if (dead) dead->Release();
}
uint64_t host_before = 0;
uint64_t host_ignored = 0;
int host_before_count = 0;
uint64_t latest_host_before_b = 0;
if (have_log) {
log_u64_ends(log_path, "host_device=", &host_ignored, &host_before, &host_before_count);
log_u64_ends(log_path, "host_device=", &host_ignored, &latest_host_before_b, &host_before_count);
}
check(SetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", "1") != 0,
"test hook BX_D3D12_REUSE_BACKING_HOST=1 is set");
ID3D12Device* device_b = nullptr;
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device_b));
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device_b));
SetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", nullptr);
check(hr == S_OK && device_b, "device B is a new proxy on the cached host device hr=0x%08lx", ul(hr));
uint64_t host_after = 0;
@@ -1455,11 +1688,10 @@ int main() {
}
if (view) {
XMemMapPhysicalPages(view, page_count, 0, nullptr);
XMemMapPhysicalPages(view, page_count, nullptr);
}
if (pages[0] || pages[1]) {
SIZE_T free_count = 2;
XMemFreePhysicalPages(&free_count, pages, 0);
XMemFreePhysicalPages(2, pages);
}
if (sync.ready) CloseHandle(sync.ready);
if (sync.done) CloseHandle(sync.done);
@@ -1468,9 +1700,9 @@ int main() {
std::fprintf(stderr, "FAIL: test_d3d12_placed (%d of %d checks failed)\n", g_failures, g_checks);
return 1;
}
std::printf("PASS: test_d3d12_placed (%d checks passed, buffer %u/%u bytes, texture %u/%u bytes, "
std::printf("PASS: test_d3d12_placed (%d checks passed, %d skipped, buffer %u/%u bytes, texture %u/%u bytes, "
"texture_path=%s, cpu_after_gpu %u/%u, small_align=%llu, upload_100000=%llu)\n",
g_checks, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes,
g_checks, g_skipped, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes,
static_cast<unsigned long long>(small_align), static_cast<unsigned long long>(odd_size));
return 0;
}
@@ -0,0 +1,4 @@
# M2-C2 (#465): rendered frames through d3d12_xs.dll's presentation bridge, verified by readback.
add_executable(test_d3d12_presentx main.cpp)
target_include_directories(test_d3d12_presentx PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/d3d12_xs")
target_link_libraries(test_d3d12_presentx PRIVATE d3d12_xs bx_runtime_veh user32 kernel32)
File diff suppressed because it is too large. Load diff
+64
View File
@@ -0,0 +1,64 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Runs test_d3d12_presentx once normally and once per negative control, and checks that each
# control fails in its own stage with its own evidence. Needs build-shims/ and bx-cli built.
# Usage (from the repository root): tests/conformance/test_d3d12_presentx/run_controls.sh <bottle>
set -u
bottle=${1:?usage: run_controls.sh <d3dmetal_bottle>}
dir=$(mktemp -d) || exit 1
bad=0
run() { # name injection
BX_PRESENTX_INJECT=$2 target/debug/bx-cli run --inherit-env --bottle "$bottle" --backend d3dmetal \
--shims build-shims/bin --log "$dir/$1.jsonl" --timeout 90 \
--exe build-shims/bin/test_d3d12_presentx.exe >"$dir/$1.out" 2>&1
status=$?
}
expect() { # name file pattern
grep -aq -- "$3" "$dir/$1.$2" || { echo "$1: missing in $2: $3"; bad=1; }
}
must_fail() { # name stage
[ "$status" -ne 0 ] || { echo "$1: exited 0"; bad=1; }
expect "$1" out "first failing stage: $2)"
}
run normal ""
[ "$status" -eq 0 ] || { echo "normal: exit $status"; bad=1; }
expect normal out "^PASS: test_d3d12_presentx (.* 0 skipped)"
run bad-window bad-window
must_fail bad-window create
expect bad-window out "FAIL \[create\]: CreateSwapChain hr=0x887a0001"
# The contract stage logs seven argument rejections; the injected window must add the eighth.
n=$(grep -ac '"event":"present_create_rejected".*invalid window or description' "$dir/bad-window.jsonl")
[ "$n" -eq 8 ] || { echo "bad-window: $n argument rejections logged, expected 8"; bad=1; }
run skip-draw skip-draw
must_fail skip-draw pixels
expect skip-draw out "frame 5: 2432 of 6000 pixels differ"
expect skip-draw out "pixels_wrong=2432 "
run wrong-expectation wrong-expectation
must_fail wrong-expectation pixels
expect wrong-expectation out "pixels_wrong=29184 "
run skip-wait-fault skip-wait-fault
must_fail skip-wait-fault sync
expect skip-wait-fault out "SetEventOnCompletion fault was not injected"
run wrong-removed-hr wrong-removed-hr
must_fail wrong-removed-hr sync
expect wrong-removed-hr out "post-present device reset must return DXGI_ERROR_DEVICE_RESET: hr=0x80040205"
run zero-timeout-overrun zero-timeout-overrun
must_fail zero-timeout-overrun sync
expect zero-timeout-overrun out "WaitForIdle(0) must reject zero without signaling:"
if [ "$bad" -ne 0 ]; then
echo "FAIL: run_controls (output kept in $dir)"
exit 1
fi
rm -rf "$dir"
echo "PASS: run_controls (1 normal run, 6 negative controls)"
@@ -0,0 +1,4 @@
# Synthetic conformance test for the Xbox 32-byte D3D12ConfigureVirtualMemoryX decoder.
add_executable(test_d3d12_vmem_xbox main.cpp)
target_include_directories(test_d3d12_vmem_xbox PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_d3d12_vmem_xbox PRIVATE d3d12_xs xmem bx_runtime_veh kernel32)
@@ -0,0 +1,529 @@
/*
* Conformance test for the Xbox virtual-memory configuration decoder in
* d3d12_xs.dll!D3D12ConfigureVirtualMemoryX (D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION).
*
* Expected values come from the authorized GDK documentation of the function and the
* structure, written out here rather than taken from the shim's header:
* - the default page-table size (5 x 4 MB) reports a minimum graphics address of 2 GiB and
* a maximum of 159.375 GiB; the input fields are left as the caller set them;
* - the page-table size is clamped to 33, the frame-buffer preserve size to 64 MiB, and -1
* (the legacy size) is kept;
* - after a D3D12 device exists the call fails with E_FAIL and writes nothing;
* - every accepted configuration is recorded only (applied=0) and still emits the
* unimplemented-API stub, and leaves a cached BXVM backing heap untouched.
* Inferred, and marked as such in the log: the maximum for other page-table sizes scales
* linearly (max_estimated=1), and a page-table size of 0, an unreadable configuration and
* unwritable outputs fail with E_INVALIDARG.
*
* Several fixtures share one BX_LOG_FILE, so every log check reads only the
* bytes appended since the step it checks began.
*/
#include <d3d12.h>
#include <windows.h>
#include <cstddef>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include "bx_config.h"
#include "bx_log.h"
#include "bx_xmem_internal.h"
extern "C" {
// The documented four parameters (adapter, parameters, riid, device); a zeroed block (Version 0)
// keeps the PC-layout proxy this test is written against (ADR 0009).
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void* adapter, const void* params, REFIID riid, void** ppv);
alignas(8) static const unsigned char kPcLayoutParams[80] = {};
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
__declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
DWORD protect);
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR page_count, PULONG_PTR pages);
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR page_count, PULONG_PTR pages);
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR page_count, PULONG_PTR pages);
}
namespace {
constexpr uint32_t kBxvmMagic = 0x4D565842u;
constexpr uint32_t kBxvmFlagBacking = 0x1u;
constexpr uint64_t k64K = 64ull * 1024ull;
struct BxvmConfig {
uint32_t magic;
uint32_t struct_size;
uint32_t version;
uint32_t flags;
uint64_t base_va;
uint64_t size_bytes;
uint64_t reserved;
uint64_t cpu_pointer;
};
struct XboxConfig {
uint32_t flags;
uint32_t page_table_4mb_pages;
uint32_t frame_buffer_preserve_bytes;
uint32_t padding;
uint64_t min_gpu_va;
uint64_t max_gpu_va;
};
static_assert(sizeof(BxvmConfig) == 48);
static_assert(offsetof(BxvmConfig, magic) == 0);
static_assert(offsetof(BxvmConfig, struct_size) == 4);
static_assert(offsetof(BxvmConfig, version) == 8);
static_assert(offsetof(BxvmConfig, flags) == 12);
static_assert(offsetof(BxvmConfig, base_va) == 16);
static_assert(offsetof(BxvmConfig, size_bytes) == 24);
static_assert(offsetof(BxvmConfig, reserved) == 32);
static_assert(offsetof(BxvmConfig, cpu_pointer) == 40);
static_assert(sizeof(XboxConfig) == 32);
static_assert(offsetof(XboxConfig, flags) == 0);
static_assert(offsetof(XboxConfig, page_table_4mb_pages) == 4);
static_assert(offsetof(XboxConfig, frame_buffer_preserve_bytes) == 8);
static_assert(offsetof(XboxConfig, padding) == 12);
static_assert(offsetof(XboxConfig, min_gpu_va) == 16);
static_assert(offsetof(XboxConfig, max_gpu_va) == 24);
/* From the documentation: 2 GB minimum, about 159.375 GB maximum at the default size. */
constexpr uint64_t kMinGpuVa = 0x80000000ull;
constexpr uint64_t kDefaultMaxGpuVa = 0x27D8000000ull;
constexpr uint64_t kOutputSentinel = 0xA5A5A5A5A5A5A5A5ull;
int g_failed = 0;
void check(bool cond, const char* fmt, ...) {
if (cond) {
return;
}
++g_failed;
va_list args;
va_start(args, fmt);
std::fprintf(stderr, "FAIL: ");
std::vfprintf(stderr, fmt, args);
std::fprintf(stderr, "\n");
va_end(args);
}
unsigned long ul(HRESULT hr) {
return static_cast<unsigned long>(hr);
}
bool read_file_from(const char* path, long start, std::string& out) {
out.clear();
FILE* f = std::fopen(path, "rb");
if (!f) {
return false;
}
if (start > 0 && std::fseek(f, start, SEEK_SET) != 0) {
std::fclose(f);
return false;
}
char buf[4096];
size_t n = 0;
while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0) {
out.append(buf, n);
}
std::fclose(f);
return true;
}
/* Current size of the log, used as the start offset of the next step. */
long log_size(const char* path) {
FILE* f = std::fopen(path, "rb");
if (!f) {
return 0;
}
long size = 0;
if (std::fseek(f, 0, SEEK_END) == 0) {
size = std::ftell(f);
}
std::fclose(f);
return size < 0 ? 0 : size;
}
bool log_contains_since(const char* path, long start, const char* needle) {
std::string text;
return read_file_from(path, start, text) && text.find(needle) != std::string::npos;
}
constexpr const char* kStubNeedle = "d3d12_xs.dll!D3D12ConfigureVirtualMemoryX";
BxvmConfig make_bxvm(uint64_t base_va, uint64_t size_bytes, uint32_t flags) {
BxvmConfig cfg{};
cfg.magic = kBxvmMagic;
cfg.struct_size = sizeof(BxvmConfig);
cfg.version = 1;
cfg.flags = flags;
cfg.base_va = base_va;
cfg.size_bytes = size_bytes;
cfg.reserved = 0;
cfg.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull;
return cfg;
}
XboxConfig make_xbox(uint32_t pages, uint32_t preserve = 0) {
XboxConfig cfg{};
cfg.page_table_4mb_pages = pages;
cfg.frame_buffer_preserve_bytes = preserve;
cfg.min_gpu_va = kOutputSentinel;
cfg.max_gpu_va = kOutputSentinel;
return cfg;
}
/* The caller's input fields, which the decoder must not change. */
bool inputs_unchanged(const XboxConfig& after, const XboxConfig& before) {
return after.flags == before.flags && after.page_table_4mb_pages == before.page_table_4mb_pages &&
after.frame_buffer_preserve_bytes == before.frame_buffer_preserve_bytes &&
after.padding == before.padding;
}
} // namespace
int main() {
const bx_runtime_config_t* cfg = bx_get_runtime_config();
if (!cfg) {
std::fprintf(stderr, "FAIL: test_d3d12_vmem_xbox (no runtime config)\n");
return 1;
}
char log_path[MAX_PATH] = {};
const DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
check(have_log, "BX_LOG_FILE must be set");
long mark = have_log ? log_size(log_path) : 0;
const long test_start = mark;
/* 1. The default configuration reports the documented address range. */
XboxConfig def = make_xbox(5);
const XboxConfig def_before = def;
HRESULT hr = D3D12ConfigureVirtualMemoryX(&def);
check(hr == S_OK, "default Xbox config must return S_OK (hr=0x%08lx)", ul(hr));
check(inputs_unchanged(def, def_before), "Xbox decoder must not change the input fields");
check(def.min_gpu_va == kMinGpuVa, "minimum graphics address must be 2 GiB (got 0x%llx)",
static_cast<unsigned long long>(def.min_gpu_va));
check(def.max_gpu_va == kDefaultMaxGpuVa, "default maximum graphics address must be 159.375 GiB (got 0x%llx)",
static_cast<unsigned long long>(def.max_gpu_va));
if (have_log) {
check(log_contains_since(log_path, mark,
"decoder=xbox applied=0 recorded_only=1 page_table_4mb_pages=5 clamped=0 "
"frame_buffer_preserve_bytes=0 min_gpu_va=0x80000000 max_gpu_va=0x27d8000000 "
"max_estimated=0 repeat=0"),
"log must record the default Xbox config as recorded only");
check(log_contains_since(log_path, mark, kStubNeedle),
"a recorded-only Xbox config must still emit the unimplemented-API stub");
check(!log_contains_since(log_path, mark, "applied=1"),
"a recorded-only Xbox config must not report applied=1");
mark = log_size(log_path);
}
/* 2. Repeated identical call (repeat=1). */
hr = D3D12ConfigureVirtualMemoryX(&def);
check(hr == S_OK, "repeated identical Xbox config must return S_OK (hr=0x%08lx)", ul(hr));
if (have_log) {
check(log_contains_since(log_path, mark, "page_table_4mb_pages=5 clamped=0") &&
log_contains_since(log_path, mark, "repeat=1"),
"repeated identical Xbox config must log repeat=1");
mark = log_size(log_path);
}
/* 3. The page-table sizes observed at title startup, 4 and 3: the maximum is estimated. */
for (uint32_t pages : {4u, 3u}) {
XboxConfig cfg = make_xbox(pages);
const XboxConfig before = cfg;
hr = D3D12ConfigureVirtualMemoryX(&cfg);
check(hr == S_OK, "Xbox config with %u pages must return S_OK (hr=0x%08lx)", pages, ul(hr));
check(inputs_unchanged(cfg, before), "%u-page config input fields must stay unchanged", pages);
check(cfg.min_gpu_va == kMinGpuVa, "%u-page config minimum must be 2 GiB", pages);
check(cfg.max_gpu_va == kDefaultMaxGpuVa / 5u * pages, "%u-page config maximum must scale from the default",
pages);
if (have_log) {
char needle[96];
std::snprintf(needle, sizeof(needle), "page_table_4mb_pages=%u clamped=0", pages);
check(log_contains_since(log_path, mark, needle) &&
log_contains_since(log_path, mark, "max_estimated=1 repeat=0"),
"%u-page config must log its size, max_estimated=1 and repeat=0", pages);
mark = log_size(log_path);
}
}
/* 4. Documented clamps: page table to 33, frame-buffer preserve to 64 MiB; -1 is the legacy size. */
XboxConfig big = make_xbox(100u, 128u * 1024u * 1024u);
hr = D3D12ConfigureVirtualMemoryX(&big);
check(hr == S_OK, "oversized Xbox config must be clamped, not refused (hr=0x%08lx)", ul(hr));
check(big.page_table_4mb_pages == 100u, "clamping must not rewrite the caller's page count");
check(big.max_gpu_va == kDefaultMaxGpuVa / 5u * 33u, "clamped maximum must use 33 pages");
if (have_log) {
check(log_contains_since(log_path, mark,
"page_table_4mb_pages=33 clamped=1 frame_buffer_preserve_bytes=67108864"),
"oversized config must log the clamped page count and preserve size");
mark = log_size(log_path);
}
XboxConfig legacy = make_xbox(5u, 0xFFFFFFFFu);
hr = D3D12ConfigureVirtualMemoryX(&legacy);
check(hr == S_OK, "legacy frame-buffer preserve size must be accepted (hr=0x%08lx)", ul(hr));
if (have_log) {
check(log_contains_since(log_path, mark, "frame_buffer_preserve_bytes=4294967295"),
"the legacy preserve size (-1) must be recorded as given");
mark = log_size(log_path);
}
/* 5. Refused configurations write nothing. */
XboxConfig zero = make_xbox(0);
const XboxConfig zero_before = zero;
hr = D3D12ConfigureVirtualMemoryX(&zero);
check(hr == E_INVALIDARG, "a page-table size of 0 must fail with E_INVALIDARG (hr=0x%08lx)", ul(hr));
check(std::memcmp(&zero, &zero_before, sizeof(zero)) == 0, "a refused config must not be written");
SYSTEM_INFO ro_sys{};
GetSystemInfo(&ro_sys);
const SIZE_T ro_bytes = ro_sys.dwPageSize ? ro_sys.dwPageSize : 4096;
void* ro_page = VirtualAlloc(nullptr, ro_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
check(ro_page != nullptr, "VirtualAlloc for the read-only Xbox probe must succeed");
if (ro_page) {
const XboxConfig ro_cfg = make_xbox(5);
std::memcpy(ro_page, &ro_cfg, sizeof(ro_cfg));
DWORD old_protect = 0;
if (VirtualProtect(ro_page, ro_bytes, PAGE_READONLY, &old_protect)) {
hr = D3D12ConfigureVirtualMemoryX(ro_page);
check(hr == E_INVALIDARG, "read-only Xbox outputs must fail with E_INVALIDARG (hr=0x%08lx)", ul(hr));
check(std::memcmp(ro_page, &ro_cfg, sizeof(ro_cfg)) == 0, "read-only Xbox config must stay unchanged");
DWORD ignored = 0;
VirtualProtect(ro_page, ro_bytes, old_protect, &ignored);
} else {
check(false, "Xbox config page must become read-only");
}
VirtualFree(ro_page, 0, MEM_RELEASE);
}
void* edge_mem = VirtualAlloc(nullptr, ro_bytes * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
check(edge_mem != nullptr, "VirtualAlloc for the Xbox page-edge probe must succeed");
if (edge_mem) {
auto* edge_base = static_cast<uint8_t*>(edge_mem);
DWORD old_prot = 0;
check(VirtualProtect(edge_base + ro_bytes, ro_bytes, PAGE_NOACCESS, &old_prot) != 0,
"second page must be PAGE_NOACCESS");
uint8_t* edge = edge_base + ro_bytes - 8;
const uint32_t header[2] = {0u, 5u};
std::memcpy(edge, header, sizeof(header));
hr = D3D12ConfigureVirtualMemoryX(edge);
check(hr == E_INVALIDARG, "an Xbox config cut off by an unreadable page must fail (hr=0x%08lx)", ul(hr));
VirtualProtect(edge_base + ro_bytes, ro_bytes, PAGE_READWRITE, &old_prot);
VirtualFree(edge_mem, 0, MEM_RELEASE);
}
if (have_log) {
for (const char* needle : {"decoder=xbox applied=0 reason=zero_page_table_pages hr=0x80070057",
"decoder=xbox applied=0 reason=unwritable_output hr=0x80070057",
"decoder=xbox applied=0 reason=unreadable_config hr=0x80070057"}) {
check(log_contains_since(log_path, mark, needle), "missing refused-config log: %s", needle);
}
mark = log_size(log_path);
}
/*
* 4. Verify XMemVirtualAlloc reservation works after Xbox configuration
* (matching the caller's MEM_RESERVE + console high-bit pattern).
*/
PVOID reserved_va = XMemVirtualAlloc(nullptr, 2ull * 1024ull * 1024ull, 0x20402000u, 0x21u, PAGE_READWRITE);
check(reserved_va != nullptr, "XMemVirtualAlloc reservation after Xbox config must succeed");
if (reserved_va) {
check(VirtualFree(reserved_va, 0, MEM_RELEASE) != 0, "release the XMemVirtualAlloc reservation");
}
/*
* 5. Configure a BXVM backing heap, create and cache it, then apply an Xbox
* configuration. The Xbox path does not apply a backing configuration, so the
* cached BXVM backing heap, its cpu_pointer and its device link must
* survive.
*/
ID3D12Device* device = nullptr;
hr = D3D12XboxCreateDevice(nullptr, kPcLayoutParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
check(hr == S_OK && device != nullptr, "D3D12XboxCreateDevice must succeed (hr=0x%08lx)", ul(hr));
SIZE_T page_count = 2;
ULONG_PTR pages[2] = {};
const BOOL phys_ok = XMemAllocatePhysicalPages(0, &page_count, pages);
check(phys_ok && page_count == 2, "XMemAllocatePhysicalPages(2) must succeed");
uint8_t* mapped_region = phys_ok ? static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, 2, pages)) : nullptr;
check(mapped_region != nullptr, "XMemMapPhysicalPages(2) must succeed");
if (device && mapped_region) {
const uint64_t region_va = reinterpret_cast<uint64_t>(mapped_region);
const uint64_t region_bytes = 2ull * k64K;
BxvmConfig bxvm = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
hr = D3D12ConfigureVirtualMemoryX(&bxvm);
check(hr == S_OK, "BXVM backing config must succeed (hr=0x%08lx)", ul(hr));
check(bxvm.cpu_pointer == 0, "BXVM cpu_pointer must start at 0 before CreateHeap");
D3D12_HEAP_DESC backing_desc{};
backing_desc.SizeInBytes = region_bytes;
backing_desc.Alignment = k64K;
backing_desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
backing_desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
backing_desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
backing_desc.Flags = D3D12_HEAP_FLAG_NONE;
ID3D12Heap* backing_heap = nullptr;
hr = device->CreateHeap(&backing_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&backing_heap));
check(hr == S_OK && backing_heap != nullptr, "CreateHeap for BXVM backing must succeed (hr=0x%08lx)", ul(hr));
BxvmConfig query = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
hr = D3D12ConfigureVirtualMemoryX(&query);
check(hr == S_OK && query.cpu_pointer != 0,
"BXVM query after CreateHeap must return non-zero cached cpu_pointer (hr=0x%08lx)", ul(hr));
/* Once a device exists the Xbox call fails, writes nothing and leaves the cached heap alone. */
XboxConfig switch_cfg = make_xbox(4);
const XboxConfig switch_before = switch_cfg;
const long switch_mark = have_log ? log_size(log_path) : 0;
hr = D3D12ConfigureVirtualMemoryX(&switch_cfg);
check(hr == E_FAIL, "Xbox config after device creation must fail with E_FAIL (hr=0x%08lx)", ul(hr));
check(std::memcmp(&switch_cfg, &switch_before, sizeof(switch_cfg)) == 0,
"Xbox config refused after device creation must not be written");
if (have_log) {
check(log_contains_since(log_path, switch_mark,
"decoder=xbox applied=0 reason=device_already_created hr=0x80004005"),
"Xbox config after device creation must log device_already_created");
}
if (backing_heap) {
ID3D12Device* still_dev = nullptr;
const HRESULT dev_hr = backing_heap->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&still_dev));
check(SUCCEEDED(dev_hr) && still_dev != nullptr,
"cached BXVM backing heap must keep its device after an Xbox config (hr=0x%08lx)", ul(dev_hr));
if (still_dev) {
still_dev->Release();
}
}
BxvmConfig after_xbox = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
hr = D3D12ConfigureVirtualMemoryX(&after_xbox);
check(hr == S_OK && after_xbox.cpu_pointer == query.cpu_pointer,
"BXVM cpu_pointer must be unchanged after an Xbox config (hr=0x%08lx)", ul(hr));
if (backing_heap) {
backing_heap->Release();
backing_heap = nullptr;
}
/* Ordinary D3D12 heap creation still works after the refused Xbox call. */
D3D12_HEAP_DESC ordinary_desc{};
ordinary_desc.SizeInBytes = k64K;
ordinary_desc.Alignment = k64K;
ordinary_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
ordinary_desc.Flags = D3D12_HEAP_FLAG_NONE;
ID3D12Heap* ordinary_heap = nullptr;
hr = device->CreateHeap(&ordinary_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&ordinary_heap));
check(hr == S_OK && ordinary_heap != nullptr,
"ordinary CreateHeap must succeed after a refused Xbox config (hr=0x%08lx)", ul(hr));
if (ordinary_heap) {
ordinary_heap->Release();
}
}
if (mapped_region) {
XMemMapPhysicalPages(mapped_region, 2, nullptr);
}
if (phys_ok) {
XMemFreePhysicalPages(2, pages);
}
if (device) {
device->Release();
}
/* 6. Malformed and page-edge unreadable inputs to the shared entry point. */
if (have_log) {
mark = log_size(log_path);
}
check(D3D12ConfigureVirtualMemoryX(nullptr) == S_OK, "null config must fall back with S_OK");
uint32_t unknown_hdr[8] = {0x11223344u, 4u, 0u, 0u, 0u, 0u, 0u, 0u};
uint32_t unknown_hdr_before[8];
std::memcpy(unknown_hdr_before, unknown_hdr, sizeof(unknown_hdr));
check(D3D12ConfigureVirtualMemoryX(unknown_hdr) == S_OK, "unrecognized header must fall back with S_OK");
check(std::memcmp(unknown_hdr, unknown_hdr_before, sizeof(unknown_hdr)) == 0,
"unrecognized header bytes must stay unchanged");
BxvmConfig readonly_bxvm = make_bxvm(0, 0, 0);
SYSTEM_INFO readonly_sys{};
GetSystemInfo(&readonly_sys);
const SIZE_T readonly_page_bytes = readonly_sys.dwPageSize ? readonly_sys.dwPageSize : 4096;
void* readonly_page =
VirtualAlloc(nullptr, readonly_page_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
check(readonly_page != nullptr, "VirtualAlloc for read-only BXVM probe must succeed");
if (readonly_page) {
std::memcpy(readonly_page, &readonly_bxvm, sizeof(readonly_bxvm));
DWORD old_protect = 0;
const bool protected_readonly =
VirtualProtect(readonly_page, readonly_page_bytes, PAGE_READONLY, &old_protect) != 0;
check(protected_readonly, "BXVM config page must become read-only");
if (protected_readonly) {
check(D3D12ConfigureVirtualMemoryX(readonly_page) == S_OK,
"read-only BXVM output must fall back with S_OK");
check(std::memcmp(readonly_page, &readonly_bxvm, sizeof(readonly_bxvm)) == 0,
"read-only BXVM config bytes must stay unchanged");
DWORD ignored_protect = 0;
const bool writable =
VirtualProtect(readonly_page, readonly_page_bytes, old_protect, &ignored_protect) != 0;
check(writable, "make the BXVM page writable for the invalid-size case");
if (writable) {
const BxvmConfig invalid_bxvm = make_bxvm(0, 1, 0);
std::memcpy(readonly_page, &invalid_bxvm, sizeof(invalid_bxvm));
const bool readonly_again =
VirtualProtect(readonly_page, readonly_page_bytes, PAGE_READONLY, &ignored_protect) != 0;
check(readonly_again, "protect the invalid-size BXVM page");
if (readonly_again) {
check(D3D12ConfigureVirtualMemoryX(readonly_page) == E_INVALIDARG,
"invalid BXVM size must be rejected before the read-only fallback");
check(std::memcmp(readonly_page, &invalid_bxvm, sizeof(invalid_bxvm)) == 0,
"rejected BXVM config bytes must stay unchanged");
}
}
}
VirtualFree(readonly_page, 0, MEM_RELEASE);
}
SYSTEM_INFO sys{};
GetSystemInfo(&sys);
const SIZE_T page_bytes = sys.dwPageSize ? sys.dwPageSize : 4096;
void* guard_mem = VirtualAlloc(nullptr, page_bytes * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
check(guard_mem != nullptr, "VirtualAlloc for page-edge probe must succeed");
if (guard_mem) {
DWORD old_prot = 0;
auto* base = static_cast<uint8_t*>(guard_mem);
check(VirtualProtect(base + page_bytes, page_bytes, PAGE_NOACCESS, &old_prot) != 0,
"second page must be PAGE_NOACCESS");
/* Unreadable header directly on NOACCESS page. */
check(D3D12ConfigureVirtualMemoryX(base + page_bytes) == S_OK,
"unreadable header must not fault and must return S_OK");
VirtualProtect(base + page_bytes, page_bytes, PAGE_READWRITE, &old_prot);
VirtualFree(guard_mem, 0, MEM_RELEASE);
}
if (have_log) {
constexpr const char* expected_fallbacks[] = {
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=null_config\"",
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=unrecognized_header\"",
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=unreadable_header\"",
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=bxvm applied=0 reason=unwritable_output\"",
};
for (const char* needle : expected_fallbacks) {
check(log_contains_since(log_path, mark, needle), "missing expected fallback log: %s", needle);
}
check(log_contains_since(log_path, test_start, "\"event\":\"vmem_config_recorded\""),
"the Xbox path must log vmem_config_recorded");
}
if (g_failed != 0) {
std::fprintf(stderr, "FAIL: test_d3d12_vmem_xbox (%d failed)\n", g_failed);
return 1;
}
std::printf("PASS: test_d3d12_vmem_xbox\n");
return 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_xbox_layout main.cpp)
target_compile_definitions(test_d3d12_xbox_layout PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_xbox_layout PRIVATE d3d12_xs xmem kernel32 uuid)
@@ -0,0 +1,414 @@
/*
* ADR 0009: d3d12_xs.dll hands a title an Xbox-layout device, and the objects it creates are
* Xbox-layout too. This program calls them the way a title built against the Xbox Series D3D12
* header does: through the object's function table, by slot number.
*
* The slot numbers and object offsets below were written out by hand from that header (used
* under Microsoft's authorization). They are not taken from the shim's generated tables.
* Expected results come from a second device created in the PC layout (Version 0) and called
* through <d3d12.h>, not from the Xbox objects.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR count, PULONG_PTR pages);
extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages);
extern "C" __declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PULONG_PTR pages);
extern "C" __declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD type, uint64_t flags,
DWORD protect);
namespace {
// Xbox function-table slots (Series header).
constexpr int kQueryInterface = 0, kAddRef = 1, kRelease = 2;
constexpr int kDevGetNodeCount = 7, kDevCheckFeatureSupport = 13, kDevGetResourceAllocationInfo = 25;
constexpr int kDevCreateHeap = 28, kDevCreatePlacedResource = 29, kDevGetAdapterLuid = 43;
constexpr int kDevCreateComponentPlacedResourceX = 45; // an Xbox-only slot still stubbed
constexpr int kDevCreateCommittedResource1 = 92; // ID3D12Device4; PC places it elsewhere
constexpr int kResMap = 8, kResGetDesc = 10, kResGetGpuVirtualAddress = 11;
// Object offsets (Series header): m_RefCount at +12; ID3D12Device's m_OutOfLineFlags at +24.
constexpr size_t kRefCountOffset = 12, kOutOfLineOffset = 24;
const IID kIidDevice11 = {0x5405c344, 0xd457, 0x444e, {0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39}};
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_xbox_layout:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using QueryInterfaceFn = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**);
using RefFn = ULONG(STDMETHODCALLTYPE*)(void*);
using GetNodeCountFn = UINT(STDMETHODCALLTYPE*)(void*);
using CheckFeatureSupportFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_FEATURE, void*, UINT);
using GetAllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT,
const D3D12_RESOURCE_DESC*);
using GetAdapterLuidFn = LUID(STDMETHODCALLTYPE*)(void*);
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_DESC*, REFIID, void**);
using CreatePlacedFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64, const D3D12_RESOURCE_DESC*,
D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**);
using StubFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using CreateCommitted1Fn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, void*, REFIID, void**);
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
using GetDescFn = void(STDMETHODCALLTYPE*)(void*, D3D12_RESOURCE_DESC*);
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = bytes;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
return desc;
}
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
} // namespace
int main() {
// A title sets Version (the GDK documentation asks for D3D12_SDK_VERSION); a zeroed block is
// BetterXen's synthetic PC-layout client.
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004;
std::memcpy(title_params, &version, sizeof(version));
alignas(8) static const unsigned char pc_params[80] = {};
ID3D12Device* pc = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, pc_params, __uuidof(ID3D12Device), reinterpret_cast<void**>(&pc));
CHECK(hr == S_OK && pc, "PC-layout device hr=0x%08lx", static_cast<unsigned long>(hr));
void* dev = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
// A host device without the interface the Xbox table forwards to (vkd3d stops at
// ID3D12Device9) must refuse the Xbox-layout device rather than return the PC one.
CHECK(dev == nullptr, "a refused Xbox-layout device clears the out pointer");
if (pc) pc->Release();
if (g_failed) return 1;
std::printf("SKIP: test_d3d12_xbox_layout: this host cannot back an Xbox-layout device; the refusal "
"(E_NOINTERFACE, null device) was verified, the layout checks need the D3DMetal backend\n");
return 77;
}
CHECK(hr == S_OK && dev, "Xbox-layout device hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev || !pc) return 1;
CHECK(*reinterpret_cast<void**>(dev) != *reinterpret_cast<void**>(pc), "Xbox device must not use the PC table");
// Object layout a title can read.
CHECK(*reinterpret_cast<uint32_t*>(static_cast<char*>(dev) + kRefCountOffset) == 1, "m_RefCount starts at 1");
CHECK(static_cast<uint8_t*>(dev)[kOutOfLineOffset] != 0, "m_OutOfLineFlags makes inline helpers call out");
// IUnknown slots; QueryInterface for the interface the title asks for returns the same object.
void* dev11 = nullptr;
CHECK(slot<QueryInterfaceFn>(dev, kQueryInterface)(dev, kIidDevice11, &dev11) == S_OK && dev11 == dev,
"QueryInterface(ID3D12Device11) returns the Xbox device");
CHECK(slot<RefFn>(dev, kAddRef)(dev) == 3, "AddRef counts the QueryInterface reference");
CHECK(*reinterpret_cast<uint32_t*>(static_cast<char*>(dev) + kRefCountOffset) == 3, "m_RefCount mirrors AddRef");
slot<RefFn>(dev, kRelease)(dev);
slot<RefFn>(dev, kRelease)(dev);
// Shared ID3D12Device slots, including the two struct-return conventions.
CHECK(slot<GetNodeCountFn>(dev, kDevGetNodeCount)(dev) == pc->GetNodeCount(), "GetNodeCount at slot 7");
D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
CHECK(slot<CheckFeatureSupportFn>(dev, kDevCheckFeatureSupport)(dev, D3D12_FEATURE_D3D12_OPTIONS, &options,
sizeof(options)) == S_OK,
"CheckFeatureSupport at slot 13");
LUID pc_luid{};
pc->GetAdapterLuid(&pc_luid);
const LUID luid = slot<GetAdapterLuidFn>(dev, kDevGetAdapterLuid)(dev);
CHECK(luid.LowPart == pc_luid.LowPart && luid.HighPart == pc_luid.HighPart,
"GetAdapterLuid (8-byte struct, returned in RAX) matches the PC device");
const D3D12_RESOURCE_DESC desc = buffer_desc(64 * 1024);
D3D12_RESOURCE_ALLOCATION_INFO pc_info{};
pc->GetResourceAllocationInfo(&pc_info, 0, 1, &desc);
const D3D12_RESOURCE_ALLOCATION_INFO info =
slot<GetAllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &desc);
CHECK(info.SizeInBytes == pc_info.SizeInBytes && info.Alignment == pc_info.Alignment && info.SizeInBytes >= 65536,
"GetResourceAllocationInfo (16-byte struct, hidden pointer) matches the PC device");
// An Xbox-only slot without an implementation is a logged stub.
CHECK(slot<StubFn>(dev, kDevCreateComponentPlacedResourceX)(dev) == E_NOTIMPL, "CreateComponentPlacedResourceX is a stub");
// A Device4 method at its Xbox slot creates an Xbox-layout resource.
D3D12_HEAP_PROPERTIES upload{};
upload.Type = D3D12_HEAP_TYPE_UPLOAD;
void* resource = nullptr;
hr = slot<CreateCommitted1Fn>(dev, kDevCreateCommittedResource1)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
nullptr, __uuidof(ID3D12Resource), &resource);
CHECK(hr == S_OK && resource, "CreateCommittedResource1 at slot 92 hr=0x%08lx", static_cast<unsigned long>(hr));
if (resource) {
D3D12_RESOURCE_DESC got{};
slot<GetDescFn>(resource, kResGetDesc)(resource, &got);
CHECK(got.Width == desc.Width && got.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, "resource GetDesc at slot 10");
CHECK(slot<GetGpuVaFn>(resource, kResGetGpuVirtualAddress)(resource) != 0, "resource GPU VA at slot 11");
void* mapped = nullptr;
CHECK(slot<MapFn>(resource, kResMap)(resource, 0, nullptr, &mapped) == S_OK && mapped, "resource Map at slot 8");
if (mapped) static_cast<unsigned char*>(mapped)[0] = 0x5a;
CHECK(slot<RefFn>(resource, kRelease)(resource) == 0, "resource Release at slot 2");
}
// An Xbox heap passed back into a forwarded call is unwrapped to its host.
D3D12_HEAP_DESC heap_desc{};
heap_desc.SizeInBytes = 64 * 1024;
heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
void* heap = nullptr;
hr = slot<CreateHeapFn>(dev, kDevCreateHeap)(dev, &heap_desc, __uuidof(ID3D12Heap), &heap);
CHECK(hr == S_OK && heap, "CreateHeap at slot 28 hr=0x%08lx", static_cast<unsigned long>(hr));
if (heap) {
void* placed = nullptr;
hr = slot<CreatePlacedFn>(dev, kDevCreatePlacedResource)(dev, heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON,
nullptr, __uuidof(ID3D12Resource), &placed);
CHECK(hr == S_OK && placed, "CreatePlacedResource on an Xbox heap hr=0x%08lx", static_cast<unsigned long>(hr));
if (placed) slot<RefFn>(placed, kRelease)(placed);
slot<RefFn>(heap, kRelease)(heap);
}
// Command recording through Xbox objects: queue, allocator and list from the Xbox methods, a
// copy between two Xbox buffers with a barrier, execution and a fence wait.
{
struct QueueDescX { D3D12_COMMAND_LIST_TYPE Type; UINT Flags, EngineOrPipeIndex, QueueIndex; };
struct ListDescX { D3D12_COMMAND_LIST_TYPE Type; UINT Flags, NodeMask, ResourceBarrierBatchSize; };
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
using GetTypeFn = D3D12_COMMAND_LIST_TYPE(STDMETHODCALLTYPE*)(void*);
using CopyBufferFn = void(STDMETHODCALLTYPE*)(void*, void*, UINT64, void*, UINT64, UINT64);
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateFence = 36;
constexpr int kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
constexpr int kListGetType = 8, kListClose = 9, kListCopyBufferRegion = 15, kListResourceBarrier = 26;
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
constexpr size_t kPutBufferOffset = 16, kPutBufferPointers = 5;
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
"CreateCommandQueueX at slot 48");
CHECK(slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT,
__uuidof(ID3D12CommandAllocator), &allocator) == S_OK,
"CreateCommandAllocator at slot 9");
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
hr = slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr,
__uuidof(ID3D12GraphicsCommandList), &list);
CHECK(hr == S_OK && list, "CreateCommandListX at slot 73 hr=0x%08lx", static_cast<unsigned long>(hr));
D3D12_HEAP_PROPERTIES readback{};
readback.Type = D3D12_HEAP_TYPE_READBACK;
void* src = nullptr;
void* dst = nullptr;
CHECK(slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), &src) == S_OK,
"upload buffer at slot 27");
CHECK(slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &readback, D3D12_HEAP_FLAG_NONE, &desc,
D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
__uuidof(ID3D12Resource), &dst) == S_OK,
"readback buffer at slot 27");
void* fence = nullptr;
CHECK(slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence) == S_OK,
"CreateFence at slot 36");
// A buffer placed at a title-chosen address (CreatePlacedResourceX, slot 44) reports that
// address and carries the title memory's contents to the GPU: it replaces `src` below.
using CreatePlacedXFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, const D3D12_RESOURCE_DESC*,
D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**);
constexpr int kDevCreatePlacedResourceXSlot = 44;
auto* title_memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, 64 * 1024, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE));
void* placed_x = nullptr;
if (title_memory) {
std::memset(title_memory, 0xa7, 256);
const auto title_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(title_memory);
hr = slot<CreatePlacedXFn>(dev, kDevCreatePlacedResourceXSlot)(dev, title_va, &desc, D3D12_RESOURCE_STATE_COMMON,
nullptr, __uuidof(ID3D12Resource), &placed_x);
CHECK(hr == S_OK && placed_x, "CreatePlacedResourceX at slot 44 hr=0x%08lx", static_cast<unsigned long>(hr));
if (placed_x) {
CHECK(slot<GetGpuVaFn>(placed_x, kResGetGpuVirtualAddress)(placed_x) == title_va,
"a resource placed at a title address reports that address");
if (src) slot<RefFn>(src, kRelease)(src);
src = placed_x;
}
}
if (queue && allocator && list && src && dst && fence) {
// Zero put-buffer pointers make the title's inline fast paths call through the table.
const auto* put = reinterpret_cast<const uint64_t*>(static_cast<char*>(list) + kPutBufferOffset);
bool zero = true;
for (size_t i = 0; i < kPutBufferPointers; ++i) zero = zero && put[i] == 0;
CHECK(zero, "command-list put-buffer pointers are zero");
// The Xbox command list is 1384 bytes and header-inline code writes its fields, up to
// the last one (authorized GDK documentation). Every field after the 16-byte base is
// title-owned: overwriting all of them (with zeros, which the put-buffer pointers must
// hold anyway) must not disturb BetterXen's state, so the list must still record,
// close and execute below.
constexpr size_t kXboxCommandListBytes = 1384, kXboxBaseBytes = 16;
std::memset(static_cast<char*>(list) + kXboxBaseBytes, 0, kXboxCommandListBytes - kXboxBaseBytes);
CHECK(slot<GetTypeFn>(list, kListGetType)(list) == D3D12_COMMAND_LIST_TYPE_DIRECT, "list GetType at slot 8");
if (!placed_x) {
void* mapped = nullptr;
CHECK(slot<MapFn>(src, kResMap)(src, 0, nullptr, &mapped) == S_OK && mapped, "upload Map");
if (mapped) std::memset(mapped, 0xa7, 256);
}
D3D12_RESOURCE_BARRIER uav{};
uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
uav.UAV.pResource = static_cast<ID3D12Resource*>(src); // an Xbox object, unwrapped by the shim
CHECK(slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &uav) == 0, "ResourceBarrier at slot 26 returns 0");
slot<CopyBufferFn>(list, kListCopyBufferRegion)(list, dst, 0, src, 0, 256);
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close at slot 9");
void* lists[] = {list};
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal at slot 16");
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event at slot 9");
CHECK(WaitForSingleObject(done, 5000) == WAIT_OBJECT_0, "GPU work completes");
CloseHandle(done);
void* result = nullptr;
CHECK(slot<MapFn>(dst, kResMap)(dst, 0, nullptr, &result) == S_OK && result, "readback Map");
CHECK(result && static_cast<unsigned char*>(result)[0] == 0xa7 && static_cast<unsigned char*>(result)[255] == 0xa7,
"the copy recorded through Xbox objects reached the readback buffer (source: the title-address shadow)");
}
for (void* object : {fence, dst, src, list, allocator, queue}) {
if (object) slot<RefFn>(object, kRelease)(object);
}
if (title_memory) VirtualFree(title_memory, 0, MEM_RELEASE);
}
// Console GPU page mappings (authorized GDK documentation): CopyPageMappingsX (queue slot 29),
// ClearPageMappingsX (30); D3D12XBOX_PAGE_MAPPING_RANGE {RangeType, StartPageIndexInPool,
// PageCount}, range types 0 incrementing, 1 constant, 2 null, 3 skip; 64 KiB pages. GPU
// addresses are CPU addresses in BetterXen, so the result is visible through the CPU view.
{
struct Range {
UINT type, start, count;
};
static_assert(sizeof(Range) == 12, "D3D12XBOX_PAGE_MAPPING_RANGE");
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const void*, REFIID, void**);
using CopyMappingsFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, UINT, const Range*,
D3D12_GPU_VIRTUAL_ADDRESS, UINT, UINT);
using ClearMappingsFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, UINT, UINT);
constexpr int kDevCreateCommandQueueX = 48, kQueueCopyPageMappingsX = 29, kQueueClearPageMappingsX = 30;
constexpr size_t kPage = 64 * 1024;
const UINT qdesc[4] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
"page-mapping queue");
ULONG_PTR pool_pages[2] = {};
ULONG_PTR two = 2;
CHECK(XMemAllocatePhysicalPages(0, &two, pool_pages), "physical pages for the pool");
auto* pool = static_cast<unsigned char*>(XMemMapPhysicalPages(nullptr, 2, pool_pages));
// The destination is a GPU-only reservation with 64 KB pages (MEM_RESERVE | MEM_64K_PAGES,
// CPU protection PAGE_NOACCESS with a GPU protection bit), the kind titles fill with page
// mappings. BetterXen keeps it CPU-visible, so the mapping can be checked here.
constexpr DWORD kMem64kPages = 0x20400000, kGpuOnly = PAGE_NOACCESS | 0x800;
auto* dst = static_cast<unsigned char*>(XMemVirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | kMem64kPages, 0, kGpuOnly));
CHECK(dst != nullptr, "GPU-only 64 KB-page reservation");
if (queue && pool && dst) {
pool[0] = 0x11;
pool[kPage] = 0x22;
const auto dva = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(dst);
const auto pva = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(pool);
auto copy = slot<CopyMappingsFn>(queue, kQueueCopyPageMappingsX);
const Range constant[] = {{1, 1, 2}}; // both destination pages show pool page 1
CHECK(copy(queue, dva, 1, constant, pva, 2, 0) == S_OK, "CopyPageMappingsX constant range");
CHECK(dst[0] == 0x22 && dst[kPage] == 0x22, "a constant range maps every page onto one pool page");
const Range ranges[] = {{0, 0, 1}, {3, 0, 1}}; // page 0 <- pool page 0, page 1 skipped
CHECK(copy(queue, dva, 2, ranges, pva, 2, 0) == S_OK, "CopyPageMappingsX incrementing + skip");
CHECK(dst[0] == 0x11 && dst[kPage] == 0x22, "incrementing maps pool page 0; skip leaves page 1 as it was");
pool[0] = 0x33;
CHECK(dst[0] == 0x33, "the destination shows the pool page, not a copy of it");
CHECK(copy(queue, dva, 1, constant, pva, 1, 0) == E_INVALIDARG, "a pool page past PoolPageCount is refused");
const Range null_page[] = {{2, 0, 1}};
CHECK(copy(queue, dva + kPage, 1, null_page, pva, 2, 0) == S_OK, "CopyPageMappingsX null range");
MEMORY_BASIC_INFORMATION mbi{};
CHECK(VirtualQuery(dst + kPage, &mbi, sizeof(mbi)) && mbi.State != MEM_COMMIT, "a null range unmaps the page");
CHECK(slot<ClearMappingsFn>(queue, kQueueClearPageMappingsX)(queue, dva, 1, 0) == S_OK &&
VirtualQuery(dst, &mbi, sizeof(mbi)) && mbi.State != MEM_COMMIT,
"ClearPageMappingsX unmaps the page");
}
if (queue) slot<RefFn>(queue, kRelease)(queue);
if (dst) VirtualFree(dst, 0, MEM_RELEASE); // xmem has no XMemVirtualFree; titles use VirtualFree
XMemFreePhysicalPages(2, pool_pages);
}
// Frame pacing: an interval, an origin event, and waits that return new frame tokens.
{
using SetIntervalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT, UINT, UINT);
using ScheduleFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, void*, UINT);
using WaitFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, void*, UINT, UINT64*);
constexpr int kDevSetFrameIntervalX = 78, kDevScheduleFrameEventX = 79, kDevWaitFrameEventX = 80;
constexpr UINT kOrigin = 0, kVblank = 1;
UINT64 token = 0;
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kVblank, 0, nullptr, 0, &token) == E_INVALIDARG,
"waiting on an unscheduled event fails");
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == E_INVALIDARG,
"scheduling before an interval exists fails");
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 5, 0) == E_INVALIDARG,
"a period above 4 is refused");
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 1, 0) == S_OK, "SetFrameIntervalX at slot 78");
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == S_OK, "ScheduleFrameEventX at slot 79");
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kOrigin, 1000, nullptr, 0, &token) == S_OK && token != 0,
"WaitFrameEventX at slot 80 returns a frame token");
UINT64 next = 0;
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kOrigin, 1000, nullptr, 0, &next) == S_OK && next > token,
"the next origin produces a newer token");
}
CHECK(slot<RefFn>(dev, kRelease)(dev) == 0, "device Release at slot 2");
pc->Release();
const std::string log = read_log();
if (!log.empty()) {
CHECK(log.find("device=xbox_function_tables") != std::string::npos, "log records the Xbox layout");
CHECK(log.find("XboxDevice[45]::CreateComponentPlacedResourceX") != std::string::npos, "the stub slot is logged");
}
if (g_failed) return 1;
std::printf("PASS: test_d3d12_xbox_layout\n");
return 0;
}
+91 -5
View File
@@ -23,7 +23,11 @@
#include "bx_log.h"
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
/* D3D12XboxCreateDevice requires a D3D12XBOX_CREATE_DEVICE_PARAMETERS block (80 bytes on Xbox
Series); a zeroed one asks for defaults. Only its Version field is read by the shim. */
alignas(8) static const unsigned char kCreateParams[80] = {};
namespace {
@@ -68,6 +72,38 @@ bool vtable_in_shim(IUnknown* obj) {
/* An IID that no interface uses (generated for this test). */
const GUID kUnusedIid = {0x4f0c2f6b, 0x91d3, 0x4d7e, {0xb2, 0x1a, 0x7e, 0x55, 0x03, 0xc9, 0x6a, 0x18}};
/*
* #547: the generator (shims/d3d12_xs/tools/gen_proxy.py, PAD_SLOTS = 32) appends
* 32 `BxBeyondPublicVtableNN` stubs after each generated proxy's public vtable so
* that a caller indexing past the interface it was handed lands on a logged
* E_NOTIMPL stub. The first padded slot sits at index `kPublicSlotCount`
* (gen_proxy.py emits `slot + k` for k in [0, 32)); the last is
* `kPublicSlotCount + 31`. The expected indices below are derived from the
* public D3D12 interface inheritance chains (IUnknown + every level up to the
* leaf), which is exactly what the generator walks; they match the
* `kPublicSlotCount` constants in proxy_generated.h.
*
* Each stub is `HRESULT STDMETHODCALLTYPE fn()` with no arguments, so it is
* callable through the vtable as `HRESULT (WINAPI*)()`. The stub logs
* BX_VTABLE_STUB_LOG("<leaf>", <slot>u, "beyond_public_vtable"), which
* bx_log_unimpl_vtable writes as
* {"sub":"com_vtable","event":"unimpl_vtable","detail":"<leaf>[<slot>]::beyond_public_vtable"}
*/
struct PaddedVtableExpectation {
const char* what; /* fixture-facing name for messages */
const char* leaf; /* generator's leaf interface name, used in the log detail */
unsigned first_slot; /* index of BxBeyondPublicVtable00 */
};
/* PAD_SLOTS in gen_proxy.py. */
constexpr unsigned kPaddedSlotCount = 32;
HRESULT call_vtable_slot(IUnknown* obj, unsigned index) {
void** vtbl = *reinterpret_cast<void***>(obj);
auto fn = reinterpret_cast<HRESULT(WINAPI*)()>(vtbl[index]);
return fn();
}
bool file_contains(const char* path, const char* needle_a, const char* needle_b) {
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
@@ -101,16 +137,22 @@ int main() {
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
/* --- 1. Argument contract ------------------------------------------------------------------ */
check(D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), nullptr) == E_POINTER,
check(D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), nullptr) == E_POINTER,
"D3D12XboxCreateDevice(ppv=null) must return E_POINTER");
{
void* unset = reinterpret_cast<void*>(0x1);
check(D3D12XboxCreateDevice(nullptr, nullptr, __uuidof(ID3D12Device), &unset) == E_INVALIDARG,
"D3D12XboxCreateDevice(params=null) must return E_INVALIDARG (documented)");
check(unset == nullptr, "D3D12XboxCreateDevice(params=null) must clear the out pointer");
}
void* bogus = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
HRESULT hr = D3D12XboxCreateDevice(nullptr, kUnusedIid, &bogus);
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, kUnusedIid, &bogus);
check(hr == E_NOINTERFACE && bogus == nullptr,
"unknown riid must yield E_NOINTERFACE and a null object (hr=0x%08lx obj=%p)", ul(hr), bogus);
/* --- 2. Device creation and identity ------------------------------------------------------- */
ID3D12Device* device = nullptr;
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(hr == S_OK && device, "D3D12XboxCreateDevice hr=0x%08lx device=%p", ul(hr), static_cast<void*>(device))) {
std::fprintf(stderr, "FAIL: test_d3d12_xs (no device; %d of %d checks failed)\n", g_failures, g_checks);
return 1;
@@ -297,7 +339,51 @@ int main() {
skip("BX_LOG_FILE is not set; pso_shader log record not verified");
}
/* --- 10. Teardown: every reference must come back ------------------------------------------- */
/* --- 10. Padded vtable slots (#547) ---------------------------------------------------------- */
/*
* First padded slot = 3 (IUnknown) + every public method in the leaf's
* inheritance chain, which is how gen_proxy.py counts `slot`. Derived
* natively from the toolchain's d3d12.h with the generator's own
* chain_of()/parse_interfaces(); matches kPublicSlotCount in
* proxy_generated.h (79/19/9/81).
*/
const PaddedVtableExpectation padded[] = {
{"device", "ID3D12Device10", 79u},
{"command queue", "ID3D12CommandQueue", 19u},
{"command allocator", "ID3D12CommandAllocator", 9u},
{"command list", "ID3D12GraphicsCommandList7", 81u},
};
IUnknown* const padded_objs[] = {device, queue, allocator, list};
for (unsigned i = 0; i < 4; ++i) {
IUnknown* obj = padded_objs[i];
if (!obj) {
check(false, "%s proxy missing; padded vtable slots not callable", padded[i].what);
continue;
}
const unsigned first = padded[i].first_slot;
const unsigned last = first + kPaddedSlotCount - 1;
hr = call_vtable_slot(obj, first);
check(hr == E_NOTIMPL, "%s padded vtable slot %u (BxBeyondPublicVtable00) hr=0x%08lx, want E_NOTIMPL",
padded[i].what, first, ul(hr));
hr = call_vtable_slot(obj, last);
check(hr == E_NOTIMPL, "%s padded vtable slot %u (BxBeyondPublicVtable%02u, the %u-th) hr=0x%08lx, want E_NOTIMPL",
padded[i].what, last, kPaddedSlotCount - 1, kPaddedSlotCount, ul(hr));
}
if (log_len > 0 && log_len < sizeof(log_path)) {
for (unsigned i = 0; i < 4; ++i) {
if (!padded_objs[i]) continue;
char needle[96];
std::snprintf(needle, sizeof(needle), "%s[%u]::beyond_public_vtable", padded[i].leaf,
padded[i].first_slot);
check(file_contains(log_path, "\"event\":\"unimpl_vtable\"", needle),
"BX_LOG_FILE must contain an unimpl_vtable record with %s", needle);
}
} else {
skip("BX_LOG_FILE is not set; beyond_public_vtable log records not verified");
}
/* --- 11. Teardown: every reference must come back ------------------------------------------- */
if (rs_error) rs_error->Release();
if (rs_blob) rs_blob->Release();
if (root_signature) root_signature->Release();
@@ -25,7 +25,8 @@
*
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
* fixture deliberately invents no console structure layouts. The xg_xs
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
* descriptor and method order are the documented XG contract recorded in
* shims/xg_xs/xg_xbox.cpp (derived facts, no header text).
*/
#include <windows.h>
#include <unknwn.h>
@@ -33,6 +34,7 @@
#include <immintrin.h>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
@@ -41,7 +43,6 @@
#include "bx_config.h"
#include "bx_log.h"
#include "bx_xmem_internal.h"
#include "xg_texture.h"
#define BX_IMPORT __declspec(dllimport)
@@ -54,7 +55,8 @@ BX_IMPORT uint64_t bx_veh_get_clwb_trap_count(void);
BX_IMPORT PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes);
BX_IMPORT VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
BX_IMPORT BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t flags);
BX_IMPORT PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect);
BX_IMPORT PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
DWORD protect);
BX_IMPORT SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len);
/* xgameruntime.dll */
@@ -96,10 +98,31 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
/* GameInput.dll (ordinal 1) */
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
/* xg_xs.dll is declared by "xg_texture.h". */
/* xg_xs.dll: the documented XG_RESOURCE_DESC (56 bytes) and XGTextureAddressComputer, whose
methods are AddRef, Release, GetResourceLayout, GetResourceSizeBytes,
GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes, ... (no IUnknown QueryInterface). */
struct XgResourceDesc {
uint32_t Dimension;
UINT64 Alignment;
UINT64 Width;
UINT Height;
UINT16 DepthOrArraySize;
UINT16 MipLevels;
uint32_t Format;
UINT SampleCount;
UINT SampleQuality;
uint32_t Layout;
uint32_t MiscFlags;
};
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, void** computer);
BX_IMPORT HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t flags, uint32_t* layout);
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
/* D3D12XboxCreateDevice requires a D3D12XBOX_CREATE_DEVICE_PARAMETERS block (80 bytes on Xbox
Series); a zeroed one asks for defaults. Only its Version field is read by the shim. */
alignas(8) static const unsigned char kCreateParams[80] = {};
} // extern "C"
namespace {
@@ -437,7 +460,7 @@ void stage_xmem(const bx_runtime_config_t* cfg) {
std::memset(dst, 0, kHeapBytes);
bool transfer_ok = XMemTransferMemory(dst, src, kHeapBytes, 0) && std::memcmp(src, dst, kHeapBytes) == 0;
auto* vmem = static_cast<uint8_t*>(XMemVirtualAlloc(nullptr, kVirtualBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
auto* vmem = static_cast<uint8_t*>(XMemVirtualAlloc(nullptr, kVirtualBytes, MEM_COMMIT | MEM_RESERVE, 0x1 /* XMEM_CPU */, PAGE_READWRITE));
bool virtual_ok = false;
if (vmem) {
vmem[0] = 0xA5;
@@ -649,25 +672,34 @@ void stage_acphal_heap() {
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
static_assert(sizeof(XgResourceDesc) == 56 && offsetof(XgResourceDesc, Alignment) == 8, "XG_RESOURCE_DESC");
constexpr uint32_t kXgTexture2D = 3; // XG_RESOURCE_DIMENSION_TEXTURE2D
constexpr uint32_t kXgLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
enum : int { kXgAddRef = 0, kXgRelease = 1, kXgSizeBytes = 3, kXgBaseAlignment = 4, kXgMipOffset = 5 };
template <typename Fn>
Fn xg_slot(void* computer, int slot) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(computer))[slot]);
}
/*
* 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.
* 100x50 R8G8B8A8 with two mips under BetterXen's linear rule (shims/xg_xs/xg_xbox.cpp: rows aligned
* to 256 bytes, mips to 512, the resource to 64 KiB). By hand:
* mip 0: 100 * 4 = 400 bytes per row, pitch 512; 50 rows = 25600 bytes at offset 0.
* mip 1: offset 25600 (already 512-aligned); 50 * 4 = 200 bytes per row, pitch 256;
* 25 rows = 6400 bytes, ending at 32000.
* resource: 32000 rounded up to 64 KiB = 65536, base alignment 65536.
*/
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;
XgResourceDesc desc = {};
desc.Dimension = kXgTexture2D;
desc.Width = 100;
desc.Height = 50;
desc.DepthOrArraySize = 1;
desc.MipLevels = 2;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleCount = 1;
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
HRESULT hr = XGCreateTextureComputer(&desc, &object);
@@ -676,41 +708,41 @@ void* stage_xg_texture_computer() {
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) {
using U64Fn = UINT64(WINAPI*)(void*);
using MipFn = UINT64(WINAPI*)(void*, UINT32, UINT32);
const UINT64 size = xg_slot<U64Fn>(object, kXgSizeBytes)(object);
const UINT64 alignment = xg_slot<U64Fn>(object, kXgBaseAlignment)(object);
const UINT64 mip0 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 0);
const UINT64 mip1 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 1);
if (size == 65536 && alignment == 65536 && mip0 == 0 && mip1 == 25600) {
checkpoint("xg_xs_texture_computer", Status::Pass,
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
"100x50 RGBA8 two-mip linear layout matches hand-computed size, alignment and mip offsets");
} 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));
checkpoint("xg_xs_texture_computer", Status::Fail, "size=%llu alignment=%llu mip0=%llu mip1=%llu",
static_cast<unsigned long long>(size), static_cast<unsigned long long>(alignment),
static_cast<unsigned long long>(mip0), static_cast<unsigned long long>(mip1));
}
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 == 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);
XgResourceDesc desc = {};
desc.Dimension = kXgTexture2D;
desc.Width = 256;
desc.Height = 256;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleCount = 1;
uint32_t mode_a = 0, mode_b = 0;
const HRESULT hr_a = XGSuggestSwizzleMode(&desc, 0, &mode_a);
const HRESULT hr_b = XGSuggestSwizzleMode(&desc, 0, &mode_b);
if (hr_a == S_OK && hr_b == S_OK && mode_a == kXgLayoutSwizzleLinear && mode_b == mode_a) {
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (layout=0x%x)", mode_a);
} else {
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode hr=0x%08lx/0x%08lx layout=0x%x then 0x%x, expected linear",
static_cast<unsigned long>(hr_a), static_cast<unsigned long>(hr_b), mode_a, mode_b);
}
return stage_xg_texture_computer();
@@ -751,7 +783,7 @@ void stage_d3d12_root_signature() {
void* stage_d3d12_create_device() {
begin_stage("d3d12xbox_create_device");
void* device = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), &device);
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), &device);
if (device == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
checkpoint("d3d12xbox_create_device", Status::Fail, "D3D12XboxCreateDevice left the out pointer unwritten (hr=0x%08lx)",
static_cast<unsigned long>(hr));
@@ -870,8 +902,7 @@ int main(int argc, char** argv) {
/* 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);
texture_refs = xg_slot<ULONG(WINAPI*)(void*)>(texture_computer, kXgRelease)(texture_computer);
}
release_com(game_input);
bool dsp_closed = true;
@@ -880,7 +911,8 @@ int main(int argc, char** argv) {
dsp_closed = deact_hr == S_OK && XDspDisconnect(dsp) == S_OK;
}
bool apu_closed = apu_conn ? XApuDisconnect(apu_conn) == S_OK : true;
release_com(acp_hal);
/* IAcpHal is not COM: Release is its sixth slot and returns nothing. */
if (acp_hal) reinterpret_cast<void(WINAPI*)(void*)>((*static_cast<void* const* const*>(acp_hal))[5])(acp_hal);
release_com(dstorage_factory);
if (psm_constrained_reg) UnregisterAppConstrainedChangeNotification(psm_constrained_reg);
if (psm_state_reg) UnregisterAppStateChangeNotification(psm_state_reg);
@@ -0,0 +1,13 @@
set(d3d12_xs_headers "${BX_ROOT_DIR}/shims/d3d12_xs")
if(NOT EXISTS "${d3d12_xs_headers}/vmem.h" OR NOT EXISTS "${d3d12_xs_headers}/presentx.h")
message(FATAL_ERROR "test_m2_first_frame requires the placed-resource and PresentX contracts (#486 and #471)")
endif()
add_executable(test_m2_first_frame main.cpp)
target_include_directories(test_m2_first_frame PRIVATE
"${BX_ABI_INCLUDE_DIR}"
"${d3d12_xs_headers}"
"${BX_ROOT_DIR}/shader-transpiler/crates/d3dmetal-harness/probe/shaders"
)
target_link_libraries(test_m2_first_frame PRIVATE d3d12_xs xmem bx_runtime_veh user32)
target_compile_options(test_m2_first_frame PRIVATE -fexceptions)
@@ -0,0 +1,363 @@
// Original synthetic M2 workload. The compute output is copied into the flip
// buffer and read back through a placed D3D12 buffer before the host flip.
//
// Limitations: the frame is a compute write copied into the back buffer, not a
// rasterized draw. The shader-gate stage covers only the DXIL fast path. The
// pixel compare reads pre-flip back-buffer contents, not what reached the
// screen. The readback lives in the D3D12 WRITE_BACK backing heap's own map;
// the xmem page only names the configured region and is checked to stay
// untouched, so this does not show xmem-backed placed memory (#469).
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
#include <windows.h>
#include <d3d12.h>
#include <wrl/client.h>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <string>
#include "bx_log.h"
#include "fill_cs66.h"
#include "presentx.h"
#include "vmem.h"
using Microsoft::WRL::ComPtr;
extern "C" {
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void*);
// The documented four parameters (adapter, parameters, riid, device); a zeroed block (Version 0)
// keeps the PC-layout proxy this test is written against (ADR 0009).
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void*, const void*, REFIID, void**);
alignas(8) static const unsigned char kPcLayoutParams[80] = {};
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR);
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
}
namespace {
const char* stage = "gdk_boot";
unsigned seq = 0;
void checkpoint(bool ok, const char* detail) {
std::printf(
"{\"bx_checkpoint\":\"test_m2_first_frame\",\"seq\":%u,\"stage\":\"%s\",\"status\":\"%s\",\"detail\":\"%s\"}\n",
++seq, stage, ok ? "pass" : "fail", detail);
std::fflush(stdout);
char message[384];
std::snprintf(message, sizeof(message), "%s: %s", stage, detail);
bx_log_emit(ok ? BX_LOG_INFO : BX_LOG_ERROR, "m2_first_frame", ok ? "stage_pass" : "stage_fail", message);
}
bool cleanup_ok = true;
void cleanup(bool ok, const char* call) {
if (!ok) {
cleanup_ok = false;
checkpoint(false, call);
}
}
struct Failure {};
void require(bool ok, const char* detail) {
if (!ok) {
checkpoint(false, detail);
throw Failure{};
}
}
void checked(HRESULT hr, const char* call) {
if (FAILED(hr)) {
char detail[192];
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", call, static_cast<unsigned long>(hr));
require(false, detail);
}
}
template <class T> T symbol(HMODULE module, const char* name) {
auto address = GetProcAddress(module, name);
require(address != nullptr, name);
T result;
std::memcpy(&result, &address, sizeof(result));
return result;
}
struct Runtime {
HMODULE module = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
HRESULT(WINAPI* uninit)() = nullptr;
bool active = false;
~Runtime() {
if (active)
cleanup(uninit() == S_OK, "UninitializeApiImpl");
if (module)
cleanup(FreeLibrary(module), "FreeLibrary");
}
};
struct Region {
static constexpr size_t page_bytes = 65536;
static constexpr unsigned char sentinel = 0xa5;
SIZE_T count = 1;
ULONG_PTR page = 0;
void* view = nullptr;
BxD3d12VirtualMemoryConfig config = [] {
// Assigned by name so a field reorder in vmem.h cannot compile silently.
BxD3d12VirtualMemoryConfig c{};
c.magic = BX_D3D12_VMEM_MAGIC;
c.struct_size = sizeof(BxD3d12VirtualMemoryConfig);
c.version = 1;
c.flags = BX_D3D12_VMEM_FLAG_BACKING_HEAP;
c.base_va = 0;
c.size_bytes = page_bytes;
c.reserved = 0;
c.cpu_pointer = 0;
return c;
}();
~Region() {
if (config.base_va) {
config.base_va = config.size_bytes = 0;
cleanup(D3D12ConfigureVirtualMemoryX(&config) == S_OK, "clear configured region");
}
if (view)
cleanup(XMemMapPhysicalPages(view, count, nullptr) == view, "unmap physical page");
if (page)
cleanup(XMemFreePhysicalPages(count, &page), "free physical page");
}
};
// Declared just before ExecuteCommandLists, so on a failure after the submit it is
// destroyed before the queue, back buffer and output resource it protects: it
// signals the queue and waits (bounded) so nothing is released while the GPU may
// still be using it. Disarmed once the readback fence has completed.
struct GpuDrain {
ID3D12CommandQueue* queue = nullptr;
ID3D12Fence* fence = nullptr;
bool armed = false;
~GpuDrain() {
if (!armed) return;
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
bool drained = done && SUCCEEDED(queue->Signal(fence, 2)) &&
(fence->GetCompletedValue() >= 2 ||
(SUCCEEDED(fence->SetEventOnCompletion(2, done)) &&
WaitForSingleObject(done, 5000) == WAIT_OBJECT_0));
if (done) CloseHandle(done);
cleanup(drained, "drain the queue before releasing resources after a failure");
}
};
struct Window {
HWND hwnd = CreateWindowExW(0, L"STATIC", L"BetterXen M2", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT,
CW_USEDEFAULT, 320, 240, nullptr, nullptr, nullptr, nullptr);
~Window() {
if (hwnd)
cleanup(DestroyWindow(hwnd), "destroy window");
}
};
void run(bool inject_pixel_mismatch) {
Runtime rt;
require(rt.module, "LoadLibraryExW system32");
auto init = symbol<HRESULT(WINAPI*)(uint32_t, uint32_t)>(rt.module, "InitializeApiImpl");
rt.uninit = symbol<decltype(rt.uninit)>(rt.module, "UninitializeApiImpl");
auto query = symbol<HRESULT(WINAPI*)(const GUID*, const GUID*, void**)>(rt.module, "QueryApiImpl");
checked(init(1, 1), "InitializeApiImpl");
rt.active = true;
const GUID core_guid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
const GUID sys_clsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
const GUID sys_iid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
const GUID user_guid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
ComPtr<IUnknown> core, system, user;
checked(query(&core_guid, &core_guid, reinterpret_cast<void**>(core.GetAddressOf())), "IXGameRuntimeCore");
checked(query(&sys_clsid, &sys_iid, reinterpret_cast<void**>(system.GetAddressOf())), "IXSystem");
checked(query(&user_guid, &user_guid, reinterpret_cast<void**>(user.GetAddressOf())), "IXUser");
require(core && system && user, "GDK COM interfaces");
checkpoint(true, "runtime initialized and three public interfaces acquired");
stage = "placed_resource";
Region region;
require(XMemAllocatePhysicalPages(0, &region.count, &region.page) && region.count == 1, "allocate physical page");
region.view = XMemMapPhysicalPages(nullptr, 1, &region.page);
require(region.view, "map physical page");
std::memset(region.view, Region::sentinel, Region::page_bytes);
region.config.base_va = reinterpret_cast<uintptr_t>(region.view);
checked(D3D12ConfigureVirtualMemoryX(&region.config), "configure xmem region");
ComPtr<ID3D12Device> device;
checked(D3D12XboxCreateDevice(nullptr, kPcLayoutParams, IID_PPV_ARGS(&device)), "create Xbox device");
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = region.config.size_bytes;
hd.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
hd.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
ComPtr<ID3D12Heap> heap;
checked(device->CreateHeap(&hd, IID_PPV_ARGS(&heap)), "create configured heap");
checked(D3D12ConfigureVirtualMemoryX(&region.config), "query backing map");
require(region.config.cpu_pointer != 0, "configured heap must publish its backing map");
require(region.config.cpu_pointer != reinterpret_cast<uintptr_t>(region.view),
"D3D12 backing map must be distinct from the xmem region view");
constexpr UINT width = 64, height = 4, pitch = 256;
D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = height * pitch;
buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ComPtr<ID3D12Resource> readback;
checked(device->CreatePlacedResource(heap.Get(), 0, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
IID_PPV_ARGS(&readback)),
"place readback buffer");
checkpoint(true, "xmem region configured; readback placed in a separate D3D12 WRITE_BACK heap");
stage = "shader_gate";
char path[MAX_PATH];
DWORD length = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
require(length && length < sizeof(path), "BX_LOG_FILE required");
// Start at EOF before PSO creation so stale shader_gate records cannot pass this check.
std::ifstream log(path, std::ios::binary | std::ios::ate);
require(log.good(), "open launch log");
D3D12_ROOT_PARAMETER param{};
param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
D3D12_VERSIONED_ROOT_SIGNATURE_DESC signature{};
signature.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
signature.Desc_1_0.NumParameters = 1;
signature.Desc_1_0.pParameters = &param;
ComPtr<ID3DBlob> blob;
checked(D3D12SerializeVersionedRootSignature(&signature, &blob, nullptr), "serialize root signature");
ComPtr<ID3D12RootSignature> root;
checked(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)),
"root signature");
D3D12_COMPUTE_PIPELINE_STATE_DESC ps{};
ps.pRootSignature = root.Get();
ps.CS = {g_fill_cs66, sizeof(g_fill_cs66)};
ComPtr<ID3D12PipelineState> pso;
checked(device->CreateComputePipelineState(&ps, IID_PPV_ARGS(&pso)), "SM 6.6 compute PSO");
bool inspected = false;
for (std::string line; std::getline(log, line);) {
if (line.find("\"event\":\"shader_gate\"") != line.npos && line.find("decision=pass_dxil") != line.npos &&
line.find("pso=compute") != line.npos && line.find("sm=6.6") != line.npos)
inspected = true;
}
require(inspected, "missing SM 6.6 pass_dxil telemetry for PSO");
checkpoint(true, "inspected SM 6.6 compute PSO");
stage = "present";
Window window;
require(window.hwnd, "create window");
D3D12_COMMAND_QUEUE_DESC qd{};
ComPtr<ID3D12CommandQueue> queue;
checked(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue)), "direct queue");
ComPtr<IBxPresentQueue> bridge;
checked(queue->QueryInterface(IID_IBxPresentQueue, reinterpret_cast<void**>(bridge.GetAddressOf())),
"PresentX queue interface");
BxPresentDesc desc{width, height, DXGI_FORMAT_R8G8B8A8_UNORM, 2};
ComPtr<IBxPresentSwapChain> chain;
checked(bridge->CreateSwapChain(window.hwnd, &desc, &chain), "create flip chain");
ComPtr<ID3D12Resource> back;
checked(chain->GetBuffer(chain->GetCurrentBackBufferIndex(), IID_PPV_ARGS(&back)), "get current backbuffer");
D3D12_HEAP_PROPERTIES props{};
props.Type = D3D12_HEAP_TYPE_DEFAULT;
buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
ComPtr<ID3D12Resource> output;
checked(device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &buffer,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&output)),
"shader output");
ComPtr<ID3D12CommandAllocator> alloc;
ComPtr<ID3D12GraphicsCommandList> list;
checked(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc)), "command allocator");
checked(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), pso.Get(), IID_PPV_ARGS(&list)),
"command list");
list->SetComputeRootSignature(root.Get());
list->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress());
list->Dispatch(height, 1, 1);
auto transition = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) {
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to};
list->ResourceBarrier(1, &barrier);
};
transition(output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
transition(back.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
D3D12_TEXTURE_COPY_LOCATION texture{}, linear{};
texture.pResource = back.Get();
texture.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
linear.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
linear.PlacedFootprint.Footprint = {desc.format, width, height, 1, pitch};
linear.pResource = output.Get();
list->CopyTextureRegion(&texture, 0, 0, 0, &linear, nullptr);
if (inject_pixel_mismatch) {
const D3D12_BOX second_pixel{1, 0, 0, 2, 1, 1};
list->CopyTextureRegion(&texture, 0, 0, 0, &linear, &second_pixel);
}
transition(back.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
linear.pResource = readback.Get();
list->CopyTextureRegion(&linear, 0, 0, 0, &texture, nullptr);
transition(back.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_PRESENT);
checked(list->Close(), "close command list");
ID3D12CommandList* commands[] = {list.Get()};
ComPtr<IDXGISwapChain1> host;
checked(chain->GetHostSwapChain(IID_PPV_ARGS(&host)), "get host swapchain");
UINT before = 0, after = 0;
checked(host->GetLastPresentCount(&before), "initial host present count");
ComPtr<ID3D12Fence> fence;
checked(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "readback fence");
GpuDrain drain{queue.Get(), fence.Get(), true};
queue->ExecuteCommandLists(1, commands);
const HRESULT present_hr = chain->Present(0, 0);
if (present_hr != S_OK) {
char detail[96];
std::snprintf(detail, sizeof(detail), "PresentX hr=0x%08lx", static_cast<unsigned long>(present_hr));
require(false, detail);
}
checked(chain->WaitForIdle(5000), "wait for frame");
// Wait on our own queue fence before the CPU reads the backing map, so the
// readback does not depend on what WaitForIdle covers.
checked(queue->Signal(fence.Get(), 1), "signal readback fence");
if (fence->GetCompletedValue() < 1) {
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
require(done != nullptr, "readback fence event");
const HRESULT wait_hr = fence->SetEventOnCompletion(1, done);
const DWORD waited = SUCCEEDED(wait_hr) ? WaitForSingleObject(done, 5000) : WAIT_FAILED;
cleanup(CloseHandle(done) != 0, "close readback fence event");
checked(wait_hr, "readback fence SetEventOnCompletion");
require(waited == WAIT_OBJECT_0, "readback fence wait timed out");
}
drain.armed = false; // everything submitted has completed
checked(host->GetLastPresentCount(&after), "final host present count");
require(after == before + 1, "host must present exactly once");
checkpoint(true, "one host present completed");
stage = "pixel_readback";
auto pixels = reinterpret_cast<const uint32_t*>(region.config.cpu_pointer);
for (UINT i = 0; i < width * height; ++i) {
// Mirrors fill_cs66.hlsl in shader-transpiler/crates/d3dmetal-harness/probe/shaders;
// a change to that shader must change this formula too.
uint32_t v = i * 0x9e3779b1u;
uint32_t expected = (v ^ (v >> 15)) + 0x01234567u;
if (pixels[i] != expected) {
char detail[128];
std::snprintf(detail, sizeof(detail), "pixel (%u,%u) expected %08x got %08x", i % width, i / width,
expected, pixels[i]);
require(false, detail);
}
}
const auto* xmem_bytes = static_cast<const unsigned char*>(region.view);
require(std::all_of(xmem_bytes, xmem_bytes + Region::page_bytes,
[](unsigned char byte) { return byte == Region::sentinel; }),
"xmem region bytes changed during frame readback");
checkpoint(true, "256 pre-flip RGBA8 pixels matched in the D3D12 map; xmem region sentinel intact");
stage = "teardown";
}
} // namespace
int main() {
// The mismatch control is armed only by exactly "1". Any other value is a
// configuration error rather than a silently ignored control, so a run that
// meant to arm it cannot pass as an ordinary run.
char inject[16];
const DWORD inject_len =
GetEnvironmentVariableA("BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH", inject, sizeof(inject));
const bool inject_pixel_mismatch = inject_len == 1 && inject[0] == '1';
if (inject_len != 0 && !inject_pixel_mismatch) {
std::fprintf(stderr, "FAIL: BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH must be unset or exactly 1\n");
return 1;
}
if (inject_pixel_mismatch) {
std::printf("NOTE: pixel mismatch control armed; this run must fail at pixel_readback\n");
}
try {
run(inject_pixel_mismatch);
} catch (const Failure&) {
return 1;
}
if (!cleanup_ok)
return 1;
checkpoint(true, "resources released and runtime shut down");
return 0;
}
+272 -7
View File
@@ -9,7 +9,8 @@
* with no object and no call reaching the host device;
* 3. creates PSOs from the #453 [WaveSize(64)] and 64-bit typed-atomic blobs and requires the
* gate to log their constraints;
* 4. checks the structured `shader_gate` JSONL records.
* 4. checks the structured `shader_gate` JSONL records, including the field order and
* space-free values bx-telemetry's key=value parser relies on (#535).
*
* It then runs a copy of itself with --no-bridge from a directory holding d3d12_xs.dll but not
* the bridge, which must still run DXIL and refuse ACCC-only with E_NOTIMPL.
@@ -39,7 +40,12 @@
#include "fill_cs66.h" // g_fill_cs66, d3dmetal-harness
#include "wave64_lanes.h" // g_wave64_lanes_cs, #453
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
/* D3D12XboxCreateDevice requires a D3D12XBOX_CREATE_DEVICE_PARAMETERS block (80 bytes on Xbox
Series); a zeroed one asks for defaults. Only its Version field is read by the shim. */
alignas(8) static const unsigned char kCreateParams[80] = {};
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12SerializeVersionedRootSignature(
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error);
@@ -140,6 +146,51 @@ bool log_has(const std::string& log, std::initializer_list<const char*> needles)
return false;
}
/* Every JSONL line whose text holds `needle`, so shape checks can loop over
* the records the shim actually wrote rather than the lines typed by hand in
* the trace-summary fixtures. */
std::vector<std::string> log_lines_with(const std::string& log, const char* needle) {
std::vector<std::string> lines;
size_t start = 0;
while (start < log.size()) {
size_t end = log.find('\n', start);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(start, end - start);
if (line.find(needle) != std::string::npos) lines.push_back(line);
start = end + 1;
}
return lines;
}
/* The `detail` value of one JSONL line, or empty when there is none. */
std::string detail_of(const std::string& line) {
const char* key = "\"detail\":\"";
const size_t at = line.find(key);
if (at == std::string::npos) return {};
const size_t begin = at + std::strlen(key);
size_t end = begin;
while (end < line.size() && !(line[end] == '"' && line[end - 1] != '\\')) ++end;
return line.substr(begin, end - begin);
}
/* The structured part of a `shader_gate` detail: everything before the first
* token that has no `=`. The gap record ends in prose, so it stops there. */
std::vector<std::string> structured_tokens(const std::string& detail, bool stop_at_free_text) {
std::vector<std::string> tokens;
size_t i = 0;
while (i < detail.size()) {
while (i < detail.size() && detail[i] == ' ') ++i;
if (i >= detail.size()) break;
size_t end = detail.find(' ', i);
if (end == std::string::npos) end = detail.size();
const std::string token = detail.substr(i, end - i);
if (token.find('=') == std::string::npos && stop_at_free_text) break;
tokens.push_back(token);
i = end;
}
return tokens;
}
ID3D12RootSignature* make_root(ID3D12Device* device, const D3D12_ROOT_PARAMETER& param) {
D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = {};
desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
@@ -188,6 +239,49 @@ HRESULT create_compute(ID3D12Device* device, ID3D12RootSignature* root, const vo
return device->CreateComputePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso));
}
/* Builds a stream PSO using the REAL subobject layout: alignas(void*) on the class, so a
* 4-byte-aligned payload sits at offset 4, not 8. Encoding the layout from the compiler,
* rather than from the shim's own assumption, is what lets these tests catch a desync in the
* shim's walker (#576 review). */
template<class Payload>
struct alignas(void*) TestSubobject {
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
Payload payload;
};
struct StreamBuilder {
std::vector<uint8_t> bytes;
template<class Payload>
void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const Payload& payload) {
using Record = TestSubobject<Payload>;
const size_t at = bytes.size();
bytes.resize(at + sizeof(Record), 0);
std::memcpy(bytes.data() + at + offsetof(Record, type), &type, sizeof(type));
std::memcpy(bytes.data() + at + offsetof(Record, payload), &payload, sizeof(payload));
}
D3D12_PIPELINE_STATE_STREAM_DESC desc() const {
D3D12_PIPELINE_STATE_STREAM_DESC d = {};
d.SizeInBytes = bytes.size();
d.pPipelineStateSubobjectStream = const_cast<uint8_t*>(bytes.data());
return d;
}
};
StreamBuilder compute_stream(const void* code, size_t size, ID3D12RootSignature* root) {
StreamBuilder stream;
D3D12_SHADER_BYTECODE cs = {code, size};
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, cs);
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root);
return stream;
}
HRESULT create_stream(ID3D12Device* device, const D3D12_PIPELINE_STATE_STREAM_DESC& desc,
ID3D12PipelineState** pso) {
*pso = nullptr;
auto* device2 = static_cast<ID3D12Device2*>(device);
return device2->CreatePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso));
}
/* Runs fill_cs66 and checks every output word. */
void run_dxil(ID3D12Device* device, ID3D12RootSignature* root, ID3D12PipelineState* pso) {
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
@@ -273,7 +367,7 @@ std::wstring directory_of(const wchar_t* path) {
* bx_shader_bridge.dll. DXIL must still run and ACCC-only must still be refused. */
int no_bridge_main() {
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "no-bridge: D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
D3D12_ROOT_PARAMETER uav = {};
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
@@ -302,6 +396,12 @@ int no_bridge_main() {
hr = device->CreateGraphicsPipelineState(&graphics, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
check(hr == E_NOTIMPL && !pso, "no-bridge: ACCC-only graphics VS hr=0x%08lx (want E_NOTIMPL)", ul(hr));
if (pso) pso->Release();
// The stream form refuses ACCC-only with or without the bridge (#576).
StreamBuilder accc_stream = compute_stream(accc.data(), accc.size(), root);
const D3D12_PIPELINE_STATE_STREAM_DESC accc_desc = accc_stream.desc();
hr = create_stream(device, accc_desc, &pso);
check(hr == E_NOTIMPL && !pso, "no-bridge: ACCC-only stream CS hr=0x%08lx (want E_NOTIMPL)", ul(hr));
if (pso) pso->Release();
root->Release();
device->Release();
return finish();
@@ -362,7 +462,7 @@ int main() {
}
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
D3D12_ROOT_PARAMETER uav = {};
@@ -425,9 +525,88 @@ int main() {
check(SUCCEEDED(hr) && pso, "DXIL PSO after a refusal hr=0x%08lx", ul(hr));
if (pso) pso->Release();
// 2b. The stream form (ID3D12Device2::CreatePipelineState) is gated too (#576): the same
// ACCC-only container is refused through the stream, and DXIL passes and runs.
{
StreamBuilder refused = compute_stream(accc.data(), accc.size(), root_uav);
const D3D12_PIPELINE_STATE_STREAM_DESC stream = refused.desc();
hr = create_stream(device, stream, &pso);
check(hr == E_NOTIMPL && !pso,
"ACCC-only stream PSO: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr), static_cast<void*>(pso));
if (pso) pso->Release();
StreamBuilder accepted = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
const D3D12_PIPELINE_STATE_STREAM_DESC stream_dxil = accepted.desc();
hr = create_stream(device, stream_dxil, &pso);
check(SUCCEEDED(hr) && pso, "DXIL stream PSO hr=0x%08lx", ul(hr));
if (pso) {
run_dxil(device, root_uav, pso);
pso->Release();
}
// A truncated stream, and an unknown subobject type, are rejected before the host.
StreamBuilder truncated = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
D3D12_PIPELINE_STATE_STREAM_DESC short_desc = truncated.desc();
short_desc.SizeInBytes -= 8;
hr = create_stream(device, short_desc, &pso);
check(hr == E_INVALIDARG && !pso, "truncated stream hr=0x%08lx (want E_INVALIDARG)", ul(hr));
if (pso) pso->Release();
StreamBuilder unknown = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
/* Append a record whose type tag is not a known subobject. */
const size_t at = unknown.bytes.size();
const uint32_t bogus = 0x7f;
unknown.bytes.resize(at + 8, 0);
std::memcpy(unknown.bytes.data() + at, &bogus, sizeof(bogus));
const D3D12_PIPELINE_STATE_STREAM_DESC bogus_desc = unknown.desc();
hr = create_stream(device, bogus_desc, &pso);
check(hr == E_INVALIDARG && !pso, "unknown-subobject stream hr=0x%08lx (want E_INVALIDARG)", ul(hr));
if (pso) pso->Release();
// A graphics stream whose non-shader payloads are 4-byte aligned (SAMPLE_MASK,
// RENDER_TARGET_FORMATS, RASTERIZER, BLEND, FLAGS) must still reach the host. The
// first version of this change assumed every payload sat at offset 8 and desynced
// here, rejecting a valid stream with E_INVALIDARG (#576 review).
{
// A *compute* stream carrying 4-byte-aligned payloads. The first version used
// `g_fill_cs66` as a VS, which is a compute execution model and not a valid
// vertex shader, so the host could reject it for a reason unrelated to payload
// alignment (review on #577). NODE_MASK and FLAGS are UINT payloads at offset 4
// and are legal subobjects for a compute PSO, so this exercises the layout
// without depending on a vertex-stage fixture.
StreamBuilder aligned_stream;
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root_uav);
D3D12_SHADER_BYTECODE cs = {g_fill_cs66, sizeof(g_fill_cs66)};
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, cs);
UINT node_mask = 0;
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, node_mask);
UINT stream_flags = 0;
aligned_stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, stream_flags);
const D3D12_PIPELINE_STATE_STREAM_DESC aligned_desc = aligned_stream.desc();
hr = create_stream(device, aligned_desc, &pso);
check(SUCCEEDED(hr) && pso, "compute stream with 4-byte-aligned payloads hr=0x%08lx", ul(hr));
if (pso) pso->Release();
}
// A duplicated subobject type is rejected by ID3D12Device2's own rules.
StreamBuilder duplicate = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root_uav);
D3D12_SHADER_BYTECODE again = {g_fill_cs66, sizeof(g_fill_cs66)};
duplicate.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, again);
const D3D12_PIPELINE_STATE_STREAM_DESC dup_desc = duplicate.desc();
hr = create_stream(device, dup_desc, &pso);
check(hr == E_INVALIDARG && !pso, "duplicate-CS stream hr=0x%08lx (want E_INVALIDARG)", ul(hr));
if (pso) pso->Release();
}
// 3. Constraint-carrying DXIL still passes; its constraints are logged (results not dispatched).
// A wave wider than 32 lanes is refused at creation (#591): D3DMetal creates the PSO
// and never runs it, so an S_OK here would be a silent no-op. The fixture asserts the
// failure rather than only reading the log, because the log alone cannot tell a caller
// what happened.
hr = create_compute(device, root_uav, g_wave64_lanes_cs, sizeof(g_wave64_lanes_cs), &pso);
std::printf("wave64 PSO hr=0x%08lx\n", ul(hr));
check(hr == E_NOTIMPL && !pso,
"wave64 PSO is refused at creation: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr),
static_cast<void*>(pso));
if (pso) pso->Release();
hr = create_compute(device, root_table, g_atomic64_image_cs, sizeof(g_atomic64_image_cs), &pso);
std::printf("atomic64 typed PSO hr=0x%08lx\n", ul(hr));
@@ -438,6 +617,81 @@ int main() {
// 5. The JSONL records.
const std::string log = read_log();
// The trace-summary fixtures in bx-telemetry/bx-cli are typed by hand from
// reading shader_gate.cpp. These checks pin the shape the parser assumes,
// against the log this fixture actually wrote, so the two cannot drift
// apart silently (#535).
{
const std::vector<std::string> gate_lines = log_lines_with(log, "\"event\":\"shader_gate\"");
check(!gate_lines.empty(), "the fixture wrote at least one shader_gate record");
bool order_ok = true;
bool classified_has_kind = true;
bool unclassified_lacks_kind = true;
bool values_have_no_space = true;
for (const std::string& line : gate_lines) {
const std::string detail = detail_of(line);
const size_t pso = detail.find("pso=");
const size_t stage = detail.find("stage=");
const size_t decision = detail.find("decision=");
const size_t hr = detail.find("hr=");
// The summarizer extracts these by key, so the order the emitter
// writes them is the order it relies on. Every key must be present:
// a missing one is npos, the largest value, which would satisfy `<`.
const bool all_present = pso != std::string::npos && stage != std::string::npos &&
decision != std::string::npos && hr != std::string::npos;
if (!(all_present && pso < stage && stage < decision && decision < hr)) {
order_ok = false;
}
const bool unclassified = detail.find("unclassified") != std::string::npos;
const bool has_kind = detail.find("kind=") != std::string::npos;
/* A record with an inspection always logs a kind; the no-bridge records
* (`*_unclassified`) and `pass_uninspected` have none. */
const bool classified = !unclassified &&
(detail.find("decision=pass_dxil") != std::string::npos ||
detail.find("decision=reject_accc_only") != std::string::npos ||
detail.find("decision=pass_original") != std::string::npos ||
detail.find("decision=prepare_failed") != std::string::npos ||
detail.find("decision=copy_limit") != std::string::npos);
if (unclassified && has_kind) unclassified_lacks_kind = false;
if (classified && !has_kind) classified_has_kind = false;
for (const std::string& token : structured_tokens(detail, false)) {
if (token.find('=') == std::string::npos) values_have_no_space = false;
}
}
check(order_ok, "every shader_gate record writes pso, stage, decision, hr in that order");
check(classified_has_kind, "a classified shader_gate record carries kind=");
check(unclassified_lacks_kind, "an unclassified record carries no kind=");
check(values_have_no_space,
"no key=value in a shader_gate record is split by a space, which is what "
"parse_key_values(..., false) assumes");
const std::vector<std::string> gap_lines = log_lines_with(log, "\"event\":\"shader_d3dmetal_gap\"");
check(!gap_lines.empty(), "the fixture wrote at least one gap record");
bool gap_ok = true;
bool gap_values_have_no_space = true;
for (const std::string& line : gap_lines) {
const std::string detail = detail_of(line);
if (detail.find("pso=") == std::string::npos ||
detail.find("stage=") == std::string::npos ||
detail.find("wave_lanes_min=") == std::string::npos ||
detail.find(':') == std::string::npos) {
gap_ok = false;
}
// parse_key_values(..., true) stops at the first token without
// '=', so every structured token must be a key=value pair.
for (const std::string& token : structured_tokens(detail, true)) {
if (token.find('=') == std::string::npos) gap_values_have_no_space = false;
}
}
check(gap_ok,
"every gap record carries pso=, stage=, wave_lanes_min= and the colon "
"that ends its structured part");
check(gap_values_have_no_space,
"no key=value in a gap record's structured part is split by a space, which is "
"what parse_key_values(..., true) assumes");
}
char fill_bytes[32];
std::snprintf(fill_bytes, sizeof(fill_bytes), "bytes=%u ", static_cast<unsigned>(sizeof(g_fill_cs66)));
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=pass_dxil", "kind=dxil", "sm=6.6",
@@ -448,8 +702,19 @@ int main() {
"shader_gate record rejecting the ACCC-only compute shader");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=graphics", "stage=VS", "decision=reject_accc_only"}),
"shader_gate record rejecting the ACCC-only vertex shader");
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=pass_dxil", "wave_ops=1", "wave_lanes=64-64"}),
"shader_gate record with WaveSize(64)");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=stream", "stage=CS", "decision=reject_accc_only"}),
"shader_gate record rejecting the ACCC-only stream compute shader");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=stream", "stage=CS", "decision=pass_dxil"}),
"shader_gate record passing the DXIL stream compute shader");
check(log_has(log, {"\"event\":\"pso_stream\"", "shaders_not_parsed=0"}),
"pso_stream record says the stream's shaders were parsed");
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=reject_wave_wide", "hr=0x80004001"}),
"shader_gate record refusing the wave64 stage");
// The wave64 stage is now refused before `pass_dxil` is logged (#591), so the record to
// assert is the rejection, carrying the same wave constraints the gap was measured on.
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=reject_wave_wide", "wave_ops=1",
"wave_lanes=64-64"}),
"shader_gate record with WaveSize(64), refused");
check(log_has(log, {"\"event\":\"shader_d3dmetal_gap\"", "wave_lanes_min=64"}),
"shader_d3dmetal_gap record for WaveSize(64)");
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=pass_dxil", "int64_ops=1", "atomic64=typed,"}),
+26 -1
View File
@@ -1,5 +1,6 @@
#include <windows.h>
#include <cstdio>
#include <cstring>
struct ShimExpectation {
const char* dll;
@@ -32,8 +33,31 @@ static const ShimExpectation kChecks[] = {
{"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll", "PeekMessageA"},
{"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow"},
{"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA"},
/* The 17th shipped DLL: the Rust-built bridge from abi/defs/bx_shader_bridge.def. */
{"bx_shader_bridge.dll", "bx_shader_inspect"},
{"bx_shader_bridge.dll", "bx_shader_prepare_for_d3dmetal"},
{"bx_shader_bridge.dll", "bx_shader_free_buffer"},
};
/* Distinct DLLs named in kChecks, so the summary reports a counted number. */
static size_t DistinctDllCount() {
const size_t count = sizeof(kChecks) / sizeof(kChecks[0]);
size_t distinct = 0;
for (size_t i = 0; i < count; ++i) {
bool seen = false;
for (size_t j = 0; j < i; ++j) {
if (std::strcmp(kChecks[i].dll, kChecks[j].dll) == 0) {
seen = true;
break;
}
}
if (!seen) {
++distinct;
}
}
return distinct;
}
int main() {
int failures = 0;
for (const auto& check : kChecks) {
@@ -56,6 +80,7 @@ int main() {
std::fprintf(stderr, "FAIL: %d shim export check(s) failed\n", failures);
return 1;
}
std::printf("PASS: test_shim_exports (%zu checks verified)\n", sizeof(kChecks) / sizeof(kChecks[0]));
std::printf("PASS: test_shim_exports (%zu checks verified across %zu shim DLLs)\n",
sizeof(kChecks) / sizeof(kChecks[0]), DistinctDllCount());
return 0;
}
@@ -0,0 +1,2 @@
add_executable(test_veh_breakpoint main.cpp)
target_link_libraries(test_veh_breakpoint PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,155 @@
/*
* runtime_veh records breakpoints and assertion failures even when the guest has replaced the
* top-level exception filter, as a title with its own crash reporter does.
*
* The test installs its own top-level filter and a last-registered vectored handler that
* resumes after each int3, then raises breakpoints at a labelled site and one
* STATUS_ASSERTION_FAILURE. The expected RVA is the label's address minus this module's base,
* computed here, not by the shim. Needs BX_LOG_FILE (bx-cli --log).
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <string>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
extern "C" void bx_breakpoint_site(void);
__asm__(".text\n"
".globl bx_breakpoint_site\n"
"bx_breakpoint_site:\n"
" int3\n"
" ret\n");
namespace {
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
constexpr int kRecordLimit = 16;
int g_failures = 0;
volatile LONG g_resumed = 0;
volatile LONG g_filter_calls = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "FAIL: test_veh_breakpoint: %s\n", what);
++g_failures;
}
}
LONG WINAPI guest_filter(PEXCEPTION_POINTERS) {
InterlockedIncrement(&g_filter_calls);
return EXCEPTION_CONTINUE_SEARCH;
}
LONG CALLBACK resume(PEXCEPTION_POINTERS ep) {
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT) {
ep->ContextRecord->Rip =
reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress) + 1;
InterlockedIncrement(&g_resumed);
return EXCEPTION_CONTINUE_EXECUTION;
}
if (code == kStatusAssertionFailure) {
InterlockedIncrement(&g_resumed);
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
std::string read_log_from(long offset) {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* file = std::fopen(path, "rb")) {
if (std::fseek(file, offset, SEEK_SET) == 0) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
}
std::fclose(file);
}
return text;
}
long log_size() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return -1;
long size = 0;
if (FILE* file = std::fopen(path, "rb")) {
if (std::fseek(file, 0, SEEK_END) == 0) size = std::ftell(file);
std::fclose(file);
}
return size < 0 ? 0 : size;
}
int count_lines_with(const std::string& log, const char* a, const char* b = nullptr) {
int count = 0;
size_t start = 0;
while (start < log.size()) {
size_t end = log.find('\n', start);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(start, end - start);
if (line.find(a) != std::string::npos && (!b || line.find(b) != std::string::npos)) {
++count;
}
start = end + 1;
}
return count;
}
} // namespace
int main() {
// Keep a static import on bx_runtime_veh.dll so its handler is installed at attach.
volatile uint64_t attached = bx_veh_get_clwb_trap_count();
(void)attached;
const long mark = log_size();
if (mark < 0) {
std::fprintf(stderr, "FAIL: test_veh_breakpoint: BX_LOG_FILE must be set\n");
return 1;
}
// A title's crash reporter takes over the top-level filter after runtime_veh attached.
SetUnhandledExceptionFilter(guest_filter);
PVOID handler = AddVectoredExceptionHandler(0, resume);
check(handler != nullptr, "AddVectoredExceptionHandler");
// A recorded breakpoint leaves the guest thread's last-error value as it was.
SetLastError(0x12345678);
bx_breakpoint_site();
check(GetLastError() == 0x12345678, "a recorded breakpoint preserves the thread's last-error value");
RaiseException(kStatusAssertionFailure, 0, 0, nullptr);
for (int i = 0; i < kRecordLimit + 4; ++i) bx_breakpoint_site();
RemoveVectoredExceptionHandler(handler);
check(g_resumed == kRecordLimit + 6, "every exception reached the guest's own handler");
check(g_filter_calls == 0, "no exception went unhandled");
const uintptr_t base = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
const uintptr_t site = reinterpret_cast<uintptr_t>(&bx_breakpoint_site);
char rva[64];
std::snprintf(rva, sizeof(rva), "\"rva\":\"0x%016llx\"",
static_cast<unsigned long long>(site - base));
const std::string log = read_log_from(mark);
const int records = count_lines_with(log, "\"event\":\"breakpoint_exception\"");
check(records == kRecordLimit, "records stop at the per-process limit of 16");
check(count_lines_with(log, "\"exception_code\":\"0x80000003\"", rva) == kRecordLimit - 1,
"each recorded int3 names the labelled site's RVA");
check(count_lines_with(log, "\"exception_code\":\"0xc0000420\"") == 1,
"the assertion failure is recorded");
// RaiseException reports an address inside kernelbase, so only the int3 records name this
// module.
check(count_lines_with(log, "\"module\":\"test_veh_breakpoint.exe\"") == kRecordLimit - 1,
"int3 records name this module");
check(count_lines_with(log, "\"event\":\"unhandled_exception\"") == 0,
"nothing was reported as unhandled");
if (g_failures) return 1;
std::printf("PASS: test_veh_breakpoint (%d records, cap %d)\n", records, kRecordLimit);
return 0;
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more