mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 06:31:11 +00:00
Compare commits
129
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dcec248837 | ||
|
|
40b5ee7a8e | ||
|
|
b975e6335b | ||
|
|
8f4786e436 | ||
|
|
0c398214fa | ||
|
|
78b56747fb | ||
|
|
63bd059182 | ||
|
|
24b124e144 | ||
|
|
cff3e754a9 | ||
|
|
2cc64bd617 | ||
|
|
c963b9bc1a | ||
|
|
30197aa236 | ||
|
|
957b8efb21 | ||
|
|
e04a3b3f62 | ||
|
|
ea29d3fc56 | ||
|
|
d724c6c013 | ||
|
|
43cb1aab54 | ||
|
|
af869008a0 | ||
|
|
8627285a59 | ||
|
|
aec6766b4d | ||
|
|
b325320549 | ||
|
|
9f8b4c7f69 | ||
|
|
2e5fbc70b1 | ||
|
|
a2d153605d | ||
|
|
4a34ec3e50 | ||
|
|
2e96d93439 | ||
|
|
30e666b86c | ||
|
|
41bc72887b | ||
|
|
c206a3f85d | ||
|
|
c893436269 | ||
|
|
00b8344a40 | ||
|
|
451c6308c0 | ||
|
|
4d69562b59 | ||
|
|
656eff8459 | ||
|
|
3ba0eb20d5 | ||
|
|
ce1940d84c | ||
|
|
bd744727bd | ||
|
|
b141c4b261 | ||
|
|
c7a4b4cf19 | ||
|
|
b88ea24a30 | ||
|
|
b2ae7a604e | ||
|
|
901b68ffba | ||
|
|
3eb8900442 | ||
|
|
335e3e4d60 | ||
|
|
c345ada8e9 | ||
|
|
3c1ee93df5 | ||
|
|
87a03d0421 | ||
|
|
bf9dd7b383 | ||
|
|
b59696975a | ||
|
|
43bb5636bf | ||
|
|
b7a660d4b9 | ||
|
|
10f78645cb | ||
|
|
8c4610b51c | ||
|
|
3b1d168de7 | ||
|
|
0d9997ce66 | ||
|
|
bfbc84d251 | ||
|
|
e96de7c455 | ||
|
|
4b2985114a | ||
|
|
fe749b1436 | ||
|
|
b7bb7615d8 | ||
|
|
3c65b393a4 | ||
|
|
b0e40e29ea | ||
|
|
90dc310b61 | ||
|
|
4bf52b14a3 | ||
|
|
bc7b622018 | ||
|
|
d8fea7b351 | ||
|
|
fe50a8edff | ||
|
|
d47eac809f | ||
|
|
8db5552e32 | ||
|
|
030c63f8c9 | ||
|
|
9a6f71abbc | ||
|
|
ad4bcc66b1 | ||
|
|
3d244ddcb0 | ||
|
|
ceaad9aee9 | ||
|
|
6bf2b9ab95 | ||
|
|
527cd6208f | ||
|
|
93a1f12bc6 | ||
|
|
55dfa39600 | ||
|
|
c39d33821e | ||
|
|
085e0d450e | ||
|
|
48378f8c35 | ||
|
|
0521ea0c6c | ||
|
|
ce23d0b2b9 | ||
|
|
d17525c165 | ||
|
|
3cfb9ed690 | ||
|
|
51ac3bd766 | ||
|
|
e816c16495 | ||
|
|
076b354d61 | ||
|
|
0bd188e602 | ||
|
|
b86be87576 | ||
|
|
62290b2f21 | ||
|
|
30c071845f | ||
|
|
781f473ea3 | ||
|
|
04ad81ee26 | ||
|
|
e0f8b0e8f6 | ||
|
|
2fc82c4d58 | ||
|
|
1b25f3422b | ||
|
|
766055e948 | ||
|
|
54b87f613c | ||
|
|
bbd3b8a9d4 | ||
|
|
32d02efc33 | ||
|
|
ac82a55039 | ||
|
|
e40d7293f8 | ||
|
|
63b5f5dac6 | ||
|
|
6484cb70a3 | ||
|
|
87da1752ad | ||
|
|
1bc42fcaec | ||
|
|
25ceb05230 | ||
|
|
2bc97a4f68 | ||
|
|
f2efeaf79d | ||
|
|
ab81b0beca | ||
|
|
b16797f576 | ||
|
|
3409bf4ec0 | ||
|
|
420c2329b7 | ||
|
|
ae869522ce | ||
|
|
6e3ef5459b | ||
|
|
bec15f43b6 | ||
|
|
7dde71e2fd | ||
|
|
33d439f828 | ||
|
|
a27284ab26 | ||
|
|
311f4124fa | ||
|
|
46a6a4baca | ||
|
|
8245c30b56 | ||
|
|
be647332cb | ||
|
|
fbd2f8cf43 | ||
|
|
6a1451b265 | ||
|
|
c64534fb21 | ||
|
|
b096424f33 | ||
|
|
f2af367da6 |
No files matched your search
@@ -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)
|
||||
|
||||
@@ -10,17 +10,70 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- `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
|
||||
- `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
|
||||
- `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.
|
||||
@@ -61,8 +114,36 @@ remains unsupported.
|
||||
- **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.
|
||||
@@ -110,6 +191,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.
|
||||
@@ -190,10 +276,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).
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
+2
-1
@@ -16,6 +16,7 @@
|
||||
- [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
|
||||
|
||||
@@ -31,6 +32,6 @@
|
||||
|
||||
- [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.
|
||||
@@ -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.
|
||||
@@ -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]]
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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(¤t) => {
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
|
||||
|
||||
mod drives;
|
||||
mod stage;
|
||||
mod supervise;
|
||||
|
||||
@@ -40,18 +41,16 @@ 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"
|
||||
);
|
||||
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> {
|
||||
@@ -860,6 +859,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);
|
||||
@@ -921,6 +932,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])
|
||||
@@ -1091,22 +1121,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
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1706,6 +1780,63 @@ sub setup_bottle_wineprefix {
|
||||
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]
|
||||
|
||||
@@ -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()
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -21,7 +21,7 @@ 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*$")
|
||||
|
||||
@@ -227,5 +227,70 @@ class CheckLinksTests(unittest.TestCase):
|
||||
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()
|
||||
@@ -100,6 +100,55 @@ 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,
|
||||
@@ -1787,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()));
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -47,19 +47,28 @@ HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
|
||||
// NDA constraint: the public Microsoft Learn page for AcpHal is gated behind
|
||||
// an Xbox developer NDA, so the true signatures and context layout are unknown
|
||||
// from public sources. BetterXen therefore returns E_NOTIMPL (not the console's
|
||||
// behaviour) and keeps the stub log so bx-cli trace still surfaces the call.
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* context) {
|
||||
(void)context;
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
|
||||
return S_OK;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
|
||||
return S_OK;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -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)
|
||||
@@ -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"
|
||||
@@ -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");
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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), ®ion, 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"
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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), ®ion, 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), ®ion, 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 */
|
||||
@@ -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;
|
||||
}
|
||||
@@ -4,8 +4,11 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "presentx.h"
|
||||
|
||||
#include "shader_gate.h"
|
||||
|
||||
/* {6B1D5C0E-2F4A-4E0B-9A57-3C0E5D7B1A42}: private to this DLL, never handed to a host object. */
|
||||
@@ -510,10 +513,13 @@ const StreamSubobject* find_subobject(uint32_t type) {
|
||||
}
|
||||
|
||||
/* Copies the caller's stream into `copy` so the gate can substitute prepared bytecode without
|
||||
* touching memory it does not own, and records where each shader payload sits. An unknown tag,
|
||||
* 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) {
|
||||
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);
|
||||
@@ -540,6 +546,7 @@ HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<ui
|
||||
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, ©[payload], sizeof(code));
|
||||
@@ -572,7 +579,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
const HRESULT copied = copy_stream(*desc, stream, offsets, 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",
|
||||
@@ -686,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
@@ -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) {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -296,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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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"
|
||||
@@ -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
@@ -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
|
||||
@@ -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) {
|
||||
|
||||
@@ -105,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;
|
||||
@@ -296,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*) {}
|
||||
@@ -801,6 +878,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},
|
||||
|
||||
+598
-122
@@ -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), ®ion, 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 : ¶meter,
|
||||
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, ®ion, 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, ®ion, sizeof(region))
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(base), ®ion, 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
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
@@ -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`.
|
||||
@@ -9,6 +9,8 @@
|
||||
|
||||
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*);
|
||||
@@ -31,19 +33,60 @@ 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 count reached zero,
|
||||
// not that the object was freed. Removing `delete this` would leave the
|
||||
// count correct while leaking, so this assertion is what catches it.
|
||||
// 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. This works whether the log path came from the runner or from
|
||||
// the temp file the fixture creates below.
|
||||
// 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,
|
||||
@@ -77,19 +120,17 @@ static std::string read_log_file_from(const char* path, uint64_t offset) {
|
||||
}
|
||||
|
||||
int main() {
|
||||
// `bx-cli run` sets BX_LOG_FILE for the guest. When the fixture is
|
||||
// run directly there is no such variable, so create a temp log and
|
||||
// point the shim at it; otherwise the assertions below would read an
|
||||
// empty file and fail for the wrong reason.
|
||||
char log_path[MAX_PATH]{};
|
||||
DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (n == 0 || n >= sizeof(log_path)) {
|
||||
char temp_dir[MAX_PATH]{};
|
||||
CHECK(GetTempPathA(sizeof(temp_dir), temp_dir) > 0);
|
||||
CHECK(GetTempFileNameA(temp_dir, "bxg", 0, log_path) != 0);
|
||||
CHECK(SetEnvironmentVariableA("BX_LOG_FILE", log_path));
|
||||
}
|
||||
const uint64_t log_start = log_file_size(log_path);
|
||||
// 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);
|
||||
|
||||
void* object = nullptr;
|
||||
CHECK(AcpHalCreate(&object) == S_OK && object);
|
||||
@@ -99,6 +140,10 @@ int main() {
|
||||
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);
|
||||
@@ -122,6 +167,25 @@ int main() {
|
||||
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
|
||||
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
|
||||
|
||||
// AcpHal shape-context stubs: NDA-gated contract, so BetterXen returns
|
||||
// E_NOTIMPL and logs the symbol. Null and sentinel pointers must not crash.
|
||||
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_NOTIMPL);
|
||||
CHECK(AcpHalAllocateShapeContexts(reinterpret_cast<void*>(uintptr_t{0xDEADBEEF})) == E_NOTIMPL);
|
||||
CHECK(AcpHalReleaseShapeContexts() == E_NOTIMPL);
|
||||
CHECK(AcpHalReleaseShapeContexts() == E_NOTIMPL);
|
||||
|
||||
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\":\"unimpl_api\"", "AcpHal.dll!AcpHalAllocateShapeContexts"));
|
||||
CHECK(file_contains(log_path, log_start, "\"event\":\"unimpl_api\"", "AcpHal.dll!AcpHalReleaseShapeContexts"));
|
||||
} 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);
|
||||
unsigned result = 0;
|
||||
@@ -276,13 +340,12 @@ int main() {
|
||||
CHECK(CloseHandle(wait1) && CloseHandle(wait2));
|
||||
CHECK(disp_unknown->Release() == 0);
|
||||
|
||||
// The live-dispatcher count is the only observable evidence that the
|
||||
// dispatcher was destroyed: `Release` returning 0 proves the count, not
|
||||
// the deallocation. `dispatch_mode` logs `mode=manual live_dispatchers=N`
|
||||
// on every transition, so a `delete this` removal that leaks the object
|
||||
// would leave `live_dispatchers=1` behind and fail here.
|
||||
// `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(log_path, log_start);
|
||||
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);
|
||||
|
||||
@@ -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) {
|
||||
@@ -667,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;
|
||||
@@ -683,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;
|
||||
@@ -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,6 +1565,7 @@ 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;
|
||||
@@ -1354,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);
|
||||
@@ -1384,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
|
||||
@@ -1419,7 +1647,7 @@ int main() {
|
||||
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;
|
||||
@@ -1460,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);
|
||||
@@ -1473,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
@@ -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;
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -133,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;
|
||||
|
||||
@@ -54,7 +54,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 */
|
||||
@@ -99,7 +100,11 @@ BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
|
||||
/* xg_xs.dll is declared by "xg_texture.h". */
|
||||
|
||||
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
|
||||
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
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 +442,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;
|
||||
@@ -751,7 +756,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));
|
||||
|
||||
@@ -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, ®ion.count, ®ion.page) && region.count == 1, "allocate physical page");
|
||||
region.view = XMemMapPhysicalPages(nullptr, 1, ®ion.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(®ion.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(®ion.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 = ¶m;
|
||||
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;
|
||||
}
|
||||
@@ -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;
|
||||
@@ -316,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;
|
||||
@@ -411,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 = {};
|
||||
@@ -566,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",
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
#include <immintrin.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
@@ -15,6 +18,132 @@ VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
|
||||
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t flags);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BX_LOG_FILE reader. BX_LOG_FILE must name the log before the process
|
||||
// starts (`bx-cli run --log`): this EXE imports bx_runtime_veh.dll, which reads
|
||||
// the variable once in DLL_PROCESS_ATTACH, before main runs, so setting it here
|
||||
// would be too late and the checks would read an empty file.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct LogReader {
|
||||
char path[MAX_PATH]{};
|
||||
int64_t start_offset = 0;
|
||||
|
||||
bool init() {
|
||||
const DWORD existing_len =
|
||||
GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (existing_len == 0 || existing_len >= sizeof(path)) {
|
||||
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
|
||||
return false;
|
||||
}
|
||||
start_offset = query_file_size(path);
|
||||
return true;
|
||||
}
|
||||
|
||||
static int64_t query_file_size(const char* p) {
|
||||
HANDLE f = CreateFileA(p, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
return 0;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
const bool ok = GetFileSizeEx(f, &size) != 0;
|
||||
CloseHandle(f);
|
||||
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
|
||||
}
|
||||
|
||||
// Read only the bytes appended after start_offset.
|
||||
bool read_new(std::string& out) const {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
std::fprintf(stderr, "FAIL: could not open CLWB log %s (error %lu)\n",
|
||||
path, GetLastError());
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
if (!GetFileSizeEx(f, &size) || size.QuadPart < start_offset) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: invalid CLWB log size for %s\n", path);
|
||||
return false;
|
||||
}
|
||||
const int64_t delta = size.QuadPart - start_offset;
|
||||
if (delta < 0 || delta > (64LL << 20)) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: unexpected CLWB log delta (%lld bytes)\n",
|
||||
static_cast<long long>(delta));
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER seek{};
|
||||
seek.QuadPart = start_offset;
|
||||
if (!SetFilePointerEx(f, seek, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return false;
|
||||
}
|
||||
out.assign(static_cast<size_t>(delta), '\0');
|
||||
size_t total_read = 0;
|
||||
while (total_read < out.size()) {
|
||||
DWORD chunk = 0;
|
||||
const DWORD want = static_cast<DWORD>(out.size() - total_read);
|
||||
if (!ReadFile(f, out.data() + total_read, want, &chunk, nullptr) || chunk == 0) {
|
||||
break;
|
||||
}
|
||||
total_read += chunk;
|
||||
}
|
||||
CloseHandle(f);
|
||||
out.resize(total_read);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// One parsed `clwb_trapped` record.
|
||||
struct ClwbRecord {
|
||||
uint64_t total_traps = 0;
|
||||
size_t len = 0;
|
||||
};
|
||||
|
||||
// Parse every `"event":"clwb_trapped"` line for `len=` and `total_traps=`.
|
||||
static std::vector<ClwbRecord> parse_clwb_records(const std::string& data) {
|
||||
std::vector<ClwbRecord> records;
|
||||
size_t pos = 0;
|
||||
while (pos < data.size()) {
|
||||
size_t nl = data.find('\n', pos);
|
||||
if (nl == std::string::npos) {
|
||||
nl = data.size();
|
||||
}
|
||||
const std::string line = data.substr(pos, nl - pos);
|
||||
pos = nl + 1;
|
||||
|
||||
if (line.find("\"event\":\"clwb_trapped\"") == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
ClwbRecord rec{};
|
||||
// len=%zu
|
||||
const size_t len_key = line.find("len=");
|
||||
if (len_key == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
// strtoull, not stoull: a malformed record must not throw past the FAIL message.
|
||||
char* len_end = nullptr;
|
||||
rec.len = std::strtoull(line.c_str() + len_key + 4, &len_end, 10);
|
||||
if (len_end == line.c_str() + len_key + 4) {
|
||||
continue;
|
||||
}
|
||||
// total_traps=%llu
|
||||
const size_t tt_key = line.find("total_traps=");
|
||||
if (tt_key == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
char* tt_end = nullptr;
|
||||
rec.total_traps = std::strtoull(line.c_str() + tt_key + 12, &tt_end, 10);
|
||||
if (tt_end == line.c_str() + tt_key + 12) {
|
||||
continue;
|
||||
}
|
||||
records.push_back(rec);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
int main() {
|
||||
/* 1. Verify AVX2 + FMA execution under Rosetta 2 */
|
||||
__m256 a = _mm256_set1_ps(3.0f);
|
||||
@@ -29,6 +158,15 @@ int main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Set up the log reader BEFORE the clwb block so we capture every
|
||||
// clwb_trapped record the VEH emits. The AVX2/FMA block above runs
|
||||
// first but does not trap (bx_veh_get_clwb_trap_count counts only
|
||||
// clwb), so the first clwb below is trap #1.
|
||||
LogReader log;
|
||||
if (!log.init()) {
|
||||
return 5;
|
||||
}
|
||||
|
||||
// Fixed registers ensure the assembler emits the intended ModRM/REX forms.
|
||||
alignas(64) uint8_t buf[512] = {0x42};
|
||||
const uint64_t before = bx_veh_get_clwb_trap_count();
|
||||
@@ -49,6 +187,92 @@ int main() {
|
||||
}
|
||||
std::printf("CLWB traps observed: %llu\n", static_cast<unsigned long long>(delta));
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Verify the decoded instruction length (`len=`) that the VEH logs and
|
||||
// uses to advance RIP. A wrong `len` lands the guest mid-instruction
|
||||
// while `delta` still reads 6, so this is the field that decides whether
|
||||
// the guest resumes correctly.
|
||||
//
|
||||
// log_sampled_trap() logs only when count == 1 or count is a power of
|
||||
// two, i.e. traps 1, 2, 4, 8, ... Six traps therefore produce exactly
|
||||
// three records with total_traps = 1, 2, 4. We assert on those three
|
||||
// sampled records only (option (a)); we do NOT see a `len=` for forms
|
||||
// 3, 5, 6 and make no claim about them here.
|
||||
//
|
||||
// Expected lengths, re-verified by assembling with
|
||||
// x86_64-w64-mingw32-as and disassembling with
|
||||
// x86_64-w64-mingw32-objdump -d:
|
||||
//
|
||||
// 0: 66 0f ae 30 clwb (%rax) -> 4
|
||||
// 4: 66 0f ae 70 40 clwb 0x40(%rax) -> 5
|
||||
// 9: 66 0f ae b0 00 01 00 00 clwb 0x100(%rax) -> 8
|
||||
// 11: 66 41 0f ae 30 clwb (%r8) -> 5 (REX.B, ModRM 0x30)
|
||||
// 16: 66 0f ae 74 88 40 clwb 0x40(%rax,%rcx,4) -> 6 (SIB + disp8)
|
||||
// 1c: 66 0f ae 35 00 00 00 00 clwb 0x0(%rip) -> 7 (disp32)
|
||||
//
|
||||
// Mapping sampled count -> ordinal -> expected len:
|
||||
// total_traps=1 -> ordinal 1 -> clwb (%rax) -> len 4
|
||||
// total_traps=2 -> ordinal 2 -> clwb 0x40(%rax)-> len 5
|
||||
// total_traps=4 -> ordinal 4 -> clwb (%r8) -> len 5
|
||||
// -----------------------------------------------------------------------
|
||||
{
|
||||
std::string log_data;
|
||||
if (!log.read_new(log_data)) {
|
||||
return 6;
|
||||
}
|
||||
const std::vector<ClwbRecord> records = parse_clwb_records(log_data);
|
||||
if (records.empty()) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: no clwb_trapped records found in log %s "
|
||||
"(BX_LOG_FILE must be readable)\n", log.path);
|
||||
return 7;
|
||||
}
|
||||
|
||||
// Every observed record must have len >= 4 (the shortest form,
|
||||
// 66 0F AE /6 with ModRM mod=00 rm=000, is 4 bytes).
|
||||
for (const auto& r : records) {
|
||||
if (r.len < 4) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: clwb_trapped total_traps=%llu has len=%zu < 4\n",
|
||||
static_cast<unsigned long long>(r.total_traps), r.len);
|
||||
return 8;
|
||||
}
|
||||
}
|
||||
|
||||
// Exact expectations for the three sampled counts.
|
||||
struct Expected { uint64_t total_traps; size_t len; const char* form; };
|
||||
static const Expected kExpected[] = {
|
||||
{1, 4, "clwb (%rax)"},
|
||||
{2, 5, "clwb 0x40(%rax)"},
|
||||
{4, 5, "clwb (%r8)"},
|
||||
};
|
||||
for (const auto& exp : kExpected) {
|
||||
bool found = false;
|
||||
for (const auto& r : records) {
|
||||
if (r.total_traps == exp.total_traps) {
|
||||
found = true;
|
||||
if (r.len != exp.len) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: clwb_trapped total_traps=%llu (%s): "
|
||||
"expected len=%zu, got len=%zu\n",
|
||||
static_cast<unsigned long long>(exp.total_traps),
|
||||
exp.form, exp.len, r.len);
|
||||
return 9;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: missing clwb_trapped record with total_traps=%llu (%s)\n",
|
||||
static_cast<unsigned long long>(exp.total_traps), exp.form);
|
||||
return 10;
|
||||
}
|
||||
}
|
||||
std::printf("CLWB decoded lengths verified for sampled traps 1, 2, 4 "
|
||||
"(%zu records)\n", records.size());
|
||||
}
|
||||
|
||||
/* 3. Verify basic XMem allocation + transfer + stats contract */
|
||||
void* src = XMemAlloc(4096, 0);
|
||||
void* dst = XMemAlloc(4096, 0);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -138,8 +139,44 @@ struct PsmLogCounts {
|
||||
size_t constrained_unregistered = 0;
|
||||
size_t constrained_foreign = 0;
|
||||
size_t constrained_unknown = 0;
|
||||
size_t state_callback_unfired = 0;
|
||||
size_t constrained_callback_unfired = 0;
|
||||
};
|
||||
|
||||
// Observed `context=0x...` values from the JSONL registration records. The
|
||||
// shim logs the context pointer it actually stored for each token, so these
|
||||
// are evidence of the round-trip, not of the arguments the test passed.
|
||||
struct PsmContextObservations {
|
||||
std::unordered_set<uintptr_t> state_contexts;
|
||||
std::unordered_set<uintptr_t> constrained_contexts;
|
||||
bool saw_context_field = false;
|
||||
bool parse_error = false;
|
||||
// The current shim's unregister records only carry a detail string, so no
|
||||
// context is observable there. Record it instead of asserting the invisible.
|
||||
bool unregister_carries_context = false;
|
||||
};
|
||||
|
||||
// Extract the `context=0x<hex>` value from a single JSONL line. `%llx` prints
|
||||
// lowercase hex with a `0x` prefix and no leading zeros, so strtoull base 16
|
||||
// (which accepts the optional `0x`) parses it exactly. Returns false when the
|
||||
// field is absent or malformed; `value` is only written on success.
|
||||
bool parse_context_field(const std::string& line, uintptr_t& value) {
|
||||
const size_t key = line.find("context=0x");
|
||||
if (key == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
// Parse from the value, after "context=". Starting at the key would make
|
||||
// strtoull read the hex digit 'c' from "context" and stop at 'o' (#520).
|
||||
const char* start = line.c_str() + key + std::strlen("context=");
|
||||
char* end = nullptr;
|
||||
const unsigned long long parsed = std::strtoull(start, &end, 16);
|
||||
if (end == start) {
|
||||
return false;
|
||||
}
|
||||
value = static_cast<uintptr_t>(parsed);
|
||||
return true;
|
||||
}
|
||||
|
||||
int64_t query_file_size(const char* path) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
@@ -152,7 +189,8 @@ int64_t query_file_size(const char* path) {
|
||||
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
|
||||
}
|
||||
|
||||
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out) {
|
||||
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out,
|
||||
PsmContextObservations& contexts) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
@@ -204,12 +242,37 @@ bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts&
|
||||
continue;
|
||||
}
|
||||
if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
|
||||
line.find("callback_unfired") != std::string::npos) {
|
||||
++out.state_callback_unfired;
|
||||
++out.state_registered;
|
||||
uintptr_t ctx = 0;
|
||||
if (parse_context_field(line, ctx)) {
|
||||
contexts.saw_context_field = true;
|
||||
contexts.state_contexts.insert(ctx);
|
||||
} else {
|
||||
contexts.parse_error = true;
|
||||
}
|
||||
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
|
||||
line.find("callback_unfired") != std::string::npos) {
|
||||
++out.constrained_callback_unfired;
|
||||
++out.constrained_registered;
|
||||
uintptr_t ctx = 0;
|
||||
if (parse_context_field(line, ctx)) {
|
||||
contexts.saw_context_field = true;
|
||||
contexts.constrained_contexts.insert(ctx);
|
||||
} else {
|
||||
contexts.parse_error = true;
|
||||
}
|
||||
} else if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.state_registered;
|
||||
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.constrained_registered;
|
||||
} else if (line.find("\"event\":\"UnregisterAppStateChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("context=0x") != std::string::npos) {
|
||||
contexts.unregister_carries_context = true;
|
||||
}
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.state_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
@@ -218,6 +281,9 @@ bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts&
|
||||
++out.state_unknown;
|
||||
}
|
||||
} else if (line.find("\"event\":\"UnregisterAppConstrainedChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("context=0x") != std::string::npos) {
|
||||
contexts.unregister_carries_context = true;
|
||||
}
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.constrained_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
@@ -324,7 +390,9 @@ bool test_psm() {
|
||||
}
|
||||
|
||||
PsmLogCounts counts{};
|
||||
const bool log_read_ok = count_psm_log_events(log_path, log_start_offset, counts);
|
||||
PsmContextObservations contexts{};
|
||||
const bool log_read_ok =
|
||||
count_psm_log_events(log_path, log_start_offset, counts, contexts);
|
||||
const bool counts_ok = log_read_ok &&
|
||||
counts.state_registered == kPerFamily &&
|
||||
counts.constrained_registered == kPerFamily &&
|
||||
@@ -345,7 +413,113 @@ bool test_psm() {
|
||||
counts.constrained_foreign, counts.constrained_unknown);
|
||||
}
|
||||
|
||||
ok = success.load() && unique_ok && !g_callback_called.load() && counts_ok;
|
||||
/* The callbacks are accepted and stored but never invoked, so the
|
||||
* JSONL detail must say so: ERROR_SUCCESS is bookkeeping only. */
|
||||
const bool fired_never = !g_callback_called.load();
|
||||
if (!fired_never) {
|
||||
std::fprintf(stderr, "FAIL: a PSM callback fired; the shim has no event source\n");
|
||||
}
|
||||
if (counts.state_callback_unfired != counts.state_registered) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: %zu of %zu state registrations omit 'callback_unfired'\n",
|
||||
counts.state_registered - counts.state_callback_unfired,
|
||||
counts.state_registered);
|
||||
}
|
||||
if (counts.constrained_callback_unfired != counts.constrained_registered) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: %zu of %zu constrained registrations omit 'callback_unfired'\n",
|
||||
counts.constrained_registered - counts.constrained_callback_unfired,
|
||||
counts.constrained_registered);
|
||||
}
|
||||
const bool limitation_logged = counts.state_callback_unfired == counts.state_registered &&
|
||||
counts.constrained_callback_unfired ==
|
||||
counts.constrained_registered;
|
||||
|
||||
/* Context round-trip: the JSONL registration record must print
|
||||
* the exact context pointer the test passed (&entry), non-zero,
|
||||
* on BOTH families. A dropped (context=0x0), swapped, or
|
||||
* mis-tagged context would fail here. */
|
||||
std::unordered_set<uintptr_t> expected_contexts;
|
||||
for (const auto& entries : tokens) {
|
||||
for (const auto& entry : entries) {
|
||||
expected_contexts.insert(reinterpret_cast<uintptr_t>(&entry));
|
||||
}
|
||||
}
|
||||
bool context_roundtrip_ok = contexts.saw_context_field && !contexts.parse_error;
|
||||
if (!contexts.saw_context_field) {
|
||||
std::fprintf(stderr, "FAIL: no context=0x field observed in PSM registration records\n");
|
||||
}
|
||||
if (contexts.parse_error) {
|
||||
std::fprintf(stderr, "FAIL: a PSM registration record had a missing/malformed context=\n");
|
||||
}
|
||||
// (1) Every context logged on the state family must be a real
|
||||
// &entry the test passed, and non-zero.
|
||||
for (const uintptr_t ctx : contexts.state_contexts) {
|
||||
if (ctx == 0) {
|
||||
std::fprintf(stderr, "FAIL: state registration logged context=0x0 (dropped context)\n");
|
||||
context_roundtrip_ok = false;
|
||||
} else if (expected_contexts.find(ctx) == expected_contexts.end()) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: state registration logged context=0x%llx that matches no &entry\n",
|
||||
static_cast<unsigned long long>(ctx));
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
}
|
||||
// (1b) Same for the constrained family.
|
||||
for (const uintptr_t ctx : contexts.constrained_contexts) {
|
||||
if (ctx == 0) {
|
||||
std::fprintf(stderr, "FAIL: constrained registration logged context=0x0 (dropped context)\n");
|
||||
context_roundtrip_ok = false;
|
||||
} else if (expected_contexts.find(ctx) == expected_contexts.end()) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: constrained registration logged context=0x%llx that matches no &entry\n",
|
||||
static_cast<unsigned long long>(ctx));
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
}
|
||||
// (2) At least two distinct context pointers must appear per
|
||||
// family, so one registration cannot overwrite another's.
|
||||
if (contexts.state_contexts.size() < 2) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: only %zu distinct state context pointer(s) logged; expected >=2\n",
|
||||
contexts.state_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
if (contexts.constrained_contexts.size() < 2) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: only %zu distinct constrained context pointer(s) logged; expected >=2\n",
|
||||
contexts.constrained_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
// (3) Family tagging: the test passes the SAME &entry to both
|
||||
// families, so the constrained record for an entry must
|
||||
// carry that entry's pointer too. With 64 registrations per
|
||||
// family the full set of &entry pointers must round-trip on
|
||||
// each family independently.
|
||||
if (contexts.state_contexts != expected_contexts) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: state contexts (%zu) do not cover all %zu &entry pointers\n",
|
||||
contexts.state_contexts.size(), expected_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
if (contexts.constrained_contexts != expected_contexts) {
|
||||
std::fprintf(stderr,
|
||||
"FAIL: constrained contexts (%zu) do not cover all %zu &entry pointers\n",
|
||||
contexts.constrained_contexts.size(), expected_contexts.size());
|
||||
context_roundtrip_ok = false;
|
||||
}
|
||||
// (4) Unregister context: the shim's unregister records carry
|
||||
// only a detail string, so context-drop on unregister is
|
||||
// not observable in the log. Assert nothing invisible; just
|
||||
// document the limitation.
|
||||
if (contexts.unregister_carries_context) {
|
||||
std::fprintf(stderr,
|
||||
"NOTE: unregister records unexpectedly carry context=; "
|
||||
"context-drop on unregister is now observable\n");
|
||||
}
|
||||
|
||||
ok = success.load() && unique_ok && fired_never && counts_ok && limitation_logged &&
|
||||
context_roundtrip_ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -367,6 +541,7 @@ int main() {
|
||||
std::fprintf(stderr, "FAIL: PSM bridge registration lifecycle\n");
|
||||
return 2;
|
||||
}
|
||||
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, per-event log verified)");
|
||||
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, "
|
||||
"per-event log + context round-trip verified)");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_xbox_drives main.cpp)
|
||||
target_link_libraries(test_xbox_drives PRIVATE kernel32)
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Check BetterXen's inferred Xbox drive layout through synthetic file operations.
|
||||
*
|
||||
* The project-authorized target title we traced opens its package on G: and writes crash logs
|
||||
* to T:, and stops at startup when either is missing; that these roles hold for Xbox titles in
|
||||
* general is an inference. The fixture checks the resulting layout. The expected contents
|
||||
* of G: come from this program's own path (GetModuleFileNameW).
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <vector>
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "FAIL: test_xbox_drives:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
static bool read_all(const wchar_t* path, std::vector<char>& out) {
|
||||
HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file == INVALID_HANDLE_VALUE) return false;
|
||||
LARGE_INTEGER size{};
|
||||
bool ok = GetFileSizeEx(file, &size) && size.QuadPart > 0 && size.QuadPart < (1 << 28);
|
||||
if (ok) {
|
||||
out.resize(static_cast<size_t>(size.QuadPart));
|
||||
DWORD got = 0;
|
||||
ok = ReadFile(file, out.data(), static_cast<DWORD>(out.size()), &got, nullptr) &&
|
||||
got == out.size();
|
||||
}
|
||||
CloseHandle(file);
|
||||
return ok;
|
||||
}
|
||||
|
||||
int main() {
|
||||
wchar_t self[MAX_PATH]{};
|
||||
DWORD len = GetModuleFileNameW(nullptr, self, MAX_PATH);
|
||||
CHECK(len > 0 && len < MAX_PATH);
|
||||
const wchar_t* name = std::wcsrchr(self, L'\\');
|
||||
CHECK(name != nullptr);
|
||||
++name;
|
||||
|
||||
// G: resolves to this executable's directory: the same file, byte for byte.
|
||||
wchar_t on_g[MAX_PATH]{};
|
||||
std::swprintf(on_g, MAX_PATH, L"G:\\%ls", name);
|
||||
std::vector<char> expected, actual;
|
||||
CHECK(read_all(self, expected));
|
||||
CHECK(read_all(on_g, actual));
|
||||
CHECK(actual == expected);
|
||||
|
||||
// T: is a directory a title can create, read back and delete a file in.
|
||||
DWORD attrs = GetFileAttributesW(L"T:\\");
|
||||
CHECK(attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY));
|
||||
wchar_t probe[MAX_PATH]{};
|
||||
std::swprintf(probe, MAX_PATH, L"T:\\bx_drive_probe_%lu.tmp",
|
||||
static_cast<unsigned long>(GetCurrentProcessId()));
|
||||
static const char payload[] = "bx-drive-probe";
|
||||
HANDLE file = CreateFileW(probe, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
CHECK(file != INVALID_HANDLE_VALUE);
|
||||
DWORD wrote = 0;
|
||||
BOOL written = WriteFile(file, payload, sizeof(payload), &wrote, nullptr);
|
||||
CloseHandle(file);
|
||||
CHECK(written && wrote == sizeof(payload));
|
||||
std::vector<char> back;
|
||||
CHECK(read_all(probe, back));
|
||||
CHECK(back.size() == sizeof(payload) && std::memcmp(back.data(), payload, sizeof(payload)) == 0);
|
||||
CHECK(DeleteFileW(probe));
|
||||
|
||||
std::printf("PASS: test_xbox_drives\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -8,7 +8,11 @@
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
|
||||
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] = {};
|
||||
|
||||
using namespace bx::storage;
|
||||
|
||||
@@ -270,7 +274,7 @@ int check_batched_buffer_transfers(Factory* factory) {
|
||||
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
Com<ID3D12Device> device;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), device.out());
|
||||
if (hr != S_OK || !device.value) {
|
||||
std::fprintf(stderr, "xcrdapi: D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
@@ -433,7 +437,7 @@ int check_unconfirmed_staged_copy(Factory* factory) {
|
||||
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
Com<ID3D12Device> device;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), device.out());
|
||||
if (hr != S_OK || !device.value) {
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
@@ -826,7 +830,7 @@ int check_public_interfaces(const WCHAR* path, const char* contents) {
|
||||
int check_public_buffer_destination() {
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
Com<ID3D12Device> device;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), device.out());
|
||||
if (hr != S_OK || !device.value) {
|
||||
std::fprintf(stderr, "xcrdapi: public D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
|
||||
@@ -739,6 +739,42 @@ int main() {
|
||||
size_t cid_used = 0;
|
||||
CHECK(SUCCEEDED(get_cid(com_sys, sizeof(cid), cid, &cid_used)) && cid_used > 1);
|
||||
|
||||
// XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode: called through the same
|
||||
// QueryApiImpl keys and slots the console runtime library uses. Expected values come
|
||||
// from the public XSystem.h / XDisplay.h documentation, not from the shim.
|
||||
{
|
||||
const GUID analytics = {0xB884675D, 0xB738, 0x4A9C, {0x81, 0x5D, 0x9A, 0x9A, 0x1E, 0x0C, 0x6C, 0x9B}};
|
||||
struct Version { uint16_t major, minor, build, revision; };
|
||||
struct AnalyticsInfo { Version os, hosting; char family[64]; char form[64]; };
|
||||
static_assert(sizeof(AnalyticsInfo) == 0x90, "XSystemAnalyticsInfo is 144 bytes");
|
||||
void* com_analytics = nullptr;
|
||||
CHECK(SUCCEEDED(query_api(&analytics, &analytics, &com_analytics)) && com_analytics);
|
||||
auto** av = *static_cast<void***>(com_analytics);
|
||||
auto get_info = reinterpret_cast<AnalyticsInfo*(WINAPI*)(void*, AnalyticsInfo*)>(av[3]);
|
||||
AnalyticsInfo info;
|
||||
std::memset(&info, 0xA5, sizeof(info));
|
||||
CHECK(get_info(com_analytics, &info) == &info);
|
||||
CHECK(std::strcmp(info.family, "Xbox") == 0);
|
||||
CHECK(std::strncmp(info.form, "Xbox Series ", 12) == 0);
|
||||
CHECK(info.os.major == 10 && info.hosting.major == 10);
|
||||
CHECK(std::memchr(info.form, 0, sizeof(info.form)) != nullptr);
|
||||
CHECK(reinterpret_cast<ULONG(WINAPI*)(void*)>(av[2])(com_analytics) >= 1);
|
||||
|
||||
const GUID display_clsid = {0x03F0FE74, 0xFDD9, 0x4E5C, {0xB6, 0x30, 0xF9, 0x33, 0x9C, 0x47, 0xAC, 0xC5}};
|
||||
const GUID display_iid = {0x35F07670, 0x706E, 0x4BFB, {0x94, 0x76, 0x09, 0x07, 0x98, 0xC5, 0xEB, 0xF3}};
|
||||
struct HdrInfo { float min_lum, max_lum, max_full_frame_lum; };
|
||||
void* com_display = nullptr;
|
||||
CHECK(SUCCEEDED(query_api(&display_clsid, &display_iid, &com_display)) && com_display);
|
||||
auto** dv = *static_cast<void***>(com_display);
|
||||
auto try_hdr = reinterpret_cast<uint32_t(WINAPI*)(void*, uint32_t, HdrInfo*)>(dv[4]);
|
||||
HdrInfo hdr{1.0f, 2.0f, 3.0f};
|
||||
// XDisplayHdrModeResult: Unknown 0, Enabled 1, Disabled 2. PreferHdr is 0.
|
||||
CHECK(try_hdr(com_display, 0u, &hdr) == 2u);
|
||||
CHECK(hdr.min_lum == 0.0f && hdr.max_lum == 0.0f && hdr.max_full_frame_lum == 0.0f);
|
||||
CHECK(try_hdr(com_display, 1u, nullptr) == 2u); // the info pointer is optional
|
||||
CHECK(reinterpret_cast<ULONG(WINAPI*)(void*)>(dv[2])(com_display) >= 1);
|
||||
}
|
||||
|
||||
void* com_game = nullptr;
|
||||
CHECK(SUCCEEDED(query_api(&game_clsid, &game_iid, &com_game)) && com_game);
|
||||
auto** game_vtbl = *static_cast<void***>(com_game);
|
||||
|
||||
@@ -12,13 +12,16 @@ PVOID WINAPI XMemAlloc(SIZE_T, uint64_t);
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFree(PVOID, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
SIZE_T WINAPI XMemVirtualQuery(LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T);
|
||||
BOOL WINAPI XMemTransferMemory(PVOID, LPCVOID, SIZE_T, uint64_t);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
BOOL WINAPI XMemIsToolsMemAvailable();
|
||||
}
|
||||
|
||||
/* XMEM_CPU from the authorized GDK documentation of XMemVirtualAlloc. */
|
||||
constexpr uint64_t kXMemCpu = 0x1;
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
@@ -68,17 +71,17 @@ int main() {
|
||||
CHECK(!XMemAllocDefault(stats.title_limit_bytes, 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, stats.title_limit_bytes,
|
||||
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
MEM_COMMIT | MEM_RESERVE, kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
|
||||
XMemFreeDefault(empty, 0);
|
||||
XMemFree(ordinary, 0);
|
||||
|
||||
auto* reserved = static_cast<unsigned char*>(
|
||||
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, PAGE_READWRITE));
|
||||
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(reserved && reinterpret_cast<uintptr_t>(reserved) % page == 0);
|
||||
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, PAGE_READWRITE) == reserved);
|
||||
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, PAGE_READWRITE)
|
||||
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, kXMemCpu, PAGE_READWRITE) == reserved);
|
||||
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, kXMemCpu, PAGE_READWRITE)
|
||||
== reserved + page);
|
||||
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
@@ -100,11 +103,15 @@ int main() {
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.committed_virtual_bytes == 0 && stats.peak_committed_bytes == page * 3);
|
||||
|
||||
// Console callers pass multi-bit attributes (e.g. 0x21) in arg 4 and high bits in alloc_type.
|
||||
// Documented form: XMem flags in argument 4, page protection in argument 5, and a page-size
|
||||
// bit (MEM_64K_PAGES, 0x20400000) in the allocation type.
|
||||
auto* console_res = static_cast<unsigned char*>(
|
||||
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, 0x21u));
|
||||
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(console_res != nullptr);
|
||||
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, 0x21u) == console_res);
|
||||
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, kXMemCpu, PAGE_READWRITE) == console_res);
|
||||
MEMORY_BASIC_INFORMATION console_region{};
|
||||
CHECK(VirtualQuery(console_res, &console_region, sizeof(console_region)));
|
||||
CHECK(console_region.Protect == PAGE_READWRITE);
|
||||
console_res[0] = 0x5Au;
|
||||
CHECK(console_res[0] == 0x5Au);
|
||||
CHECK(VirtualFree(console_res, 0, MEM_RELEASE));
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_xmem_external_charge main.cpp)
|
||||
target_include_directories(test_xmem_external_charge PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_xmem_external_charge PRIVATE xmem bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,71 @@
|
||||
// Synthetic check for bx_xmem_try_charge_external / bx_xmem_release_charge_external
|
||||
// (#550): an external charge counts against the same title cap as XMem's own
|
||||
// allocations, shows up in the reported stats, and an over-release is refused.
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xmem_external:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, \
|
||||
static_cast<unsigned long>(GetLastError())); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
int main() {
|
||||
SYSTEM_INFO sys{};
|
||||
GetSystemInfo(&sys);
|
||||
const SIZE_T page = sys.dwPageSize;
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
const uint64_t used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
|
||||
CHECK(used < stats.title_limit_bytes);
|
||||
// Only bookkeeping is charged; nothing of this size is allocated on the host.
|
||||
const uint64_t headroom = stats.title_limit_bytes - used;
|
||||
|
||||
// Graphics-first order: an external charge fills the cap...
|
||||
CHECK(bx_xmem_try_charge_external(headroom) == 1);
|
||||
CHECK(bx_xmem_try_charge_external(1) == 0);
|
||||
|
||||
// ...is visible in the reported usage, and peak never exceeds it...
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.committed_virtual_bytes + stats.allocated_physical_bytes == stats.title_limit_bytes);
|
||||
CHECK(stats.peak_committed_bytes <= stats.title_limit_bytes);
|
||||
bx_xmem_stats_t internal{};
|
||||
bx_xmem_get_internal_stats(&internal);
|
||||
CHECK(internal.committed_virtual_bytes == stats.committed_virtual_bytes);
|
||||
|
||||
// ...and a later XMem commit is refused against the same cap.
|
||||
SetLastError(0);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, 0x1 /* XMEM_CPU */, PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
|
||||
// An over-release is refused and leaves the outstanding charge in place.
|
||||
bx_xmem_release_charge_external(headroom + 1);
|
||||
CHECK(bx_xmem_try_charge_external(1) == 0);
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.committed_virtual_bytes + stats.allocated_physical_bytes == stats.title_limit_bytes);
|
||||
|
||||
// Releasing the real charge admits the same XMem commit again.
|
||||
bx_xmem_release_charge_external(headroom);
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.committed_virtual_bytes + stats.allocated_physical_bytes == used);
|
||||
void* block = XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, 0x1 /* XMEM_CPU */, PAGE_READWRITE);
|
||||
CHECK(block != nullptr);
|
||||
CHECK(VirtualFree(block, 0, MEM_RELEASE));
|
||||
|
||||
std::printf("PASS: test_xmem_external_charge\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_xmem_hooks main.cpp)
|
||||
target_link_libraries(test_xmem_hooks PRIVATE xmem kernel32)
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* XMEM_SET_ALLOCATION_HOOKS (authorized GDK documentation, xmem.h): a title exports
|
||||
* `__XMemAllocationHooks__ = { AllocRoutine, FreeRoutine }` and XMemAlloc / XMemFree call them.
|
||||
* This program is such a title: its hook serves one object type from its own buffer and passes
|
||||
* everything else to XMemAllocDefault / XMemFreeDefault.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
extern "C" {
|
||||
__declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
__declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
__declspec(dllimport) PVOID WINAPI XMemAllocDefault(SIZE_T size, ULONGLONG attributes);
|
||||
__declspec(dllimport) VOID WINAPI XMemFreeDefault(PVOID address, ULONGLONG attributes);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kObjectTypeMask = 0x3fff; // XALLOC_ATTRIBUTES.ObjectType, bits 0-13
|
||||
constexpr ULONGLONG kServedType = 4;
|
||||
alignas(64) unsigned char g_reserved[4096];
|
||||
int g_allocs = 0;
|
||||
int g_frees = 0;
|
||||
|
||||
PVOID WINAPI alloc_hook(SIZE_T size, ULONGLONG attributes) {
|
||||
++g_allocs;
|
||||
if ((attributes & kObjectTypeMask) == kServedType && size <= sizeof(g_reserved)) return g_reserved;
|
||||
return XMemAllocDefault(size, attributes);
|
||||
}
|
||||
|
||||
VOID WINAPI free_hook(PVOID address, ULONGLONG attributes) {
|
||||
++g_frees;
|
||||
if (address != g_reserved) XMemFreeDefault(address, attributes);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct AllocationHooks {
|
||||
PVOID (WINAPI* alloc)(SIZE_T, ULONGLONG);
|
||||
VOID (WINAPI* free)(PVOID, ULONGLONG);
|
||||
};
|
||||
extern "C" __declspec(dllexport) AllocationHooks __XMemAllocationHooks__ = {alloc_hook, free_hook};
|
||||
|
||||
int main() {
|
||||
int failed = 0;
|
||||
auto check = [&](bool ok, const char* what) {
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "FAIL: test_xmem_hooks: %s\n", what);
|
||||
++failed;
|
||||
}
|
||||
};
|
||||
const ULONGLONG allocator_d3d = 128ull << 16; // AllocatorId, bits 16-23
|
||||
void* served = XMemAlloc(256, allocator_d3d | kServedType);
|
||||
check(served == g_reserved, "XMemAlloc goes through the title's AllocRoutine");
|
||||
void* passed = XMemAlloc(256, allocator_d3d | 1);
|
||||
check(passed && passed != g_reserved, "the hook passes other object types to XMemAllocDefault");
|
||||
check(g_allocs == 2, "both XMemAlloc calls reached the hook");
|
||||
XMemFree(served, allocator_d3d | kServedType);
|
||||
XMemFree(passed, allocator_d3d | 1);
|
||||
check(g_frees == 2, "XMemFree goes through the title's FreeRoutine");
|
||||
void* direct = XMemAllocDefault(64, 0);
|
||||
check(direct && g_allocs == 2, "XMemAllocDefault does not call the hook");
|
||||
XMemFreeDefault(direct, 0);
|
||||
if (failed) return 1;
|
||||
std::printf("PASS: test_xmem_hooks\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* Physical pages in xmem.dll, against the signatures and rules of the authorized GDK
|
||||
* documentation: XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray) in 64 KB pages,
|
||||
* XMemFreePhysicalPages(NumberOfPages, PageArray), XMemMapPhysicalPages(VirtualAddress,
|
||||
* NumberOfPages, PageArray) and XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages,
|
||||
* PageArray), mapping into XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)
|
||||
* reservations. The constants below are written out from that documentation.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
@@ -8,13 +16,28 @@
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemMapPhysicalPagesScatter(PVOID*, ULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr SIZE_T kPage = 64 * 1024;
|
||||
constexpr DWORD kMem64KPages = 0x20400000;
|
||||
constexpr DWORD kMem2MBPages = 0x20000000;
|
||||
constexpr uint64_t kXMemCpu = 0x1;
|
||||
constexpr uint64_t kXMemMappable = 0x20;
|
||||
constexpr uint64_t kXMem2MBClusters = 0x20000000;
|
||||
constexpr uint64_t kXMemGpuOptimalBandwidthRequired = 0x280;
|
||||
constexpr uint64_t kXMemGraphics32BitAddress = 0x7;
|
||||
constexpr DWORD kMemReservePlaceholder = 0x40000;
|
||||
constexpr DWORD kMemReplacePlaceholder = 0x4000;
|
||||
constexpr DWORD kPageGraphicsReadWrite = 0x2000;
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
@@ -24,124 +47,183 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
bool check_aliases(SIZE_T page_size, uint64_t flags) {
|
||||
DWORD state_of(const void* address) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
return VirtualQuery(address, ®ion, sizeof(region)) ? region.State : 0;
|
||||
}
|
||||
|
||||
bool check_physical_pages() {
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
|
||||
SIZE_T count = 2;
|
||||
ULONG_PTR pages[2]{};
|
||||
// Invalid flags must be rejected cleanly before touching stats or tags.
|
||||
CHECK(!XMemAllocatePhysicalPages(&count, pages, 0x12345));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
// Flags outside 2 MB clusters and the bandwidth values are refused before anything changes.
|
||||
ULONG_PTR count = 4;
|
||||
ULONG_PTR pages[4]{};
|
||||
CHECK(!XMemAllocatePhysicalPages(0x12345, &count, pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && count == 4 && !pages[0]);
|
||||
CHECK(!XMemAllocatePhysicalPages(kXMem2MBClusters, &count, pages));
|
||||
CHECK(GetLastError() == ERROR_NOT_SUPPORTED && !pages[0]);
|
||||
|
||||
CHECK(XMemAllocatePhysicalPages(&count, pages, flags));
|
||||
CHECK(count == 2 && pages[0] && pages[1] && pages[0] != pages[1]);
|
||||
|
||||
// Working-set statistics and internal stats must both reflect physical pages.
|
||||
// A bandwidth value is accepted; pages are 64 KB and counted against the title budget.
|
||||
CHECK(XMemAllocatePhysicalPages(kXMemGpuOptimalBandwidthRequired, &count, pages));
|
||||
CHECK(count == 4 && pages[0] && pages[1] && pages[2] && pages[3]);
|
||||
CHECK(pages[0] != pages[1] && pages[1] != pages[2] && pages[2] != pages[3]);
|
||||
// Page numbers count 4 KiB frames, so a 64 KiB page's number is a multiple of 16 (target-build
|
||||
// observation: callers keep number >> 4 and rebuild it with << 4). Distinct pages must stay
|
||||
// distinct after that shift: consecutive numbers collapsed 16 pages into one.
|
||||
for (int i = 0; i < 4; ++i) CHECK(pages[i] % 16 == 0 && ((pages[i] >> 4) << 4) == pages[i]);
|
||||
CHECK((pages[0] >> 4) != (pages[1] >> 4) && (pages[1] >> 4) != (pages[2] >> 4) && (pages[2] >> 4) != (pages[3] >> 4));
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
CHECK(stats.peak_committed_bytes >= count * page_size);
|
||||
CHECK(stats.allocated_physical_bytes == 4 * kPage);
|
||||
bx_xmem_stats_t ws_stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&ws_stats, sizeof(ws_stats)));
|
||||
CHECK(ws_stats.allocated_physical_bytes == count * page_size);
|
||||
CHECK(ws_stats.allocated_physical_bytes == 4 * kPage);
|
||||
|
||||
// Shared title budget cap: existing physical pages must block both full-cap
|
||||
// physical and full-cap heap allocations without allocating gigabytes.
|
||||
SIZE_T cap_pages = static_cast<SIZE_T>(stats.title_limit_bytes / page_size);
|
||||
CHECK(!XMemAllocatePhysicalPages(&cap_pages, pages, flags));
|
||||
ULONG_PTR cap_pages = static_cast<ULONG_PTR>(stats.title_limit_bytes / kPage);
|
||||
CHECK(!XMemAllocatePhysicalPages(0, &cap_pages, pages));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemAllocDefault(static_cast<SIZE_T>(stats.title_limit_bytes), 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, 0x12345, pages));
|
||||
// A mappable reservation stays reserved, uncommitted, until pages are mapped into it.
|
||||
auto* base = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, 8 * kPage, MEM_RESERVE | kMem64KPages,
|
||||
kXMemMappable | kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(base && reinterpret_cast<uintptr_t>(base) % kPage == 0);
|
||||
CHECK(state_of(base) == MEM_RESERVE && state_of(base + 7 * kPage) == MEM_RESERVE);
|
||||
CHECK(!XMemVirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT | kMem64KPages, kXMemMappable,
|
||||
PAGE_READWRITE));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
auto* linear = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, count, flags, pages));
|
||||
CHECK(linear && reinterpret_cast<uintptr_t>(linear) % page_size == 0);
|
||||
ULONG_PTR reversed[] = {pages[1], pages[0]};
|
||||
auto* scatter = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, reversed));
|
||||
CHECK(scatter && scatter != linear && reinterpret_cast<uintptr_t>(scatter) % page_size == 0);
|
||||
// Map four pages, then alias them in reverse order in the next four slots.
|
||||
CHECK(XMemMapPhysicalPages(base, 4, pages) == base);
|
||||
for (int i = 0; i < 4; ++i) base[i * kPage + 9] = static_cast<BYTE>(0x40 + i);
|
||||
ULONG_PTR reversed[] = {pages[3], pages[2], pages[1], pages[0]};
|
||||
CHECK(XMemMapPhysicalPages(base + 4 * kPage, 4, reversed) == base + 4 * kPage);
|
||||
CHECK(base[4 * kPage + 9] == 0x43 && base[7 * kPage + 9] == 0x40);
|
||||
base[5 * kPage + 1] = 0x7e;
|
||||
CHECK(base[2 * kPage + 1] == 0x7e);
|
||||
|
||||
linear[7] = 0x41;
|
||||
linear[page_size + 7] = 0x73;
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
scatter[page_size + 30] = 0xf2;
|
||||
CHECK(linear[30] == 0xf2);
|
||||
bx_xmem_region_info_t info{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(base + 4 * kPage + 3), &info));
|
||||
CHECK(info.base_va == reinterpret_cast<uintptr_t>(base + 4 * kPage) && info.physical_tag == pages[3]);
|
||||
CHECK(info.size_bytes == kPage && info.protect_flags == PAGE_READWRITE && info.mem_type_flags == MEM_MAPPED);
|
||||
|
||||
// Duplicate tags are valid when mapping (intra-span ring-buffer/tile aliasing).
|
||||
ULONG_PTR dup_map[] = {pages[0], pages[0]};
|
||||
auto* dup_view = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, dup_map));
|
||||
CHECK(dup_view && reinterpret_cast<uintptr_t>(dup_view) % page_size == 0);
|
||||
dup_view[13] = 0x9b;
|
||||
CHECK(dup_view[page_size + 13] == 0x9b && linear[13] == 0x9b);
|
||||
bx_xmem_region_info_t dup0{};
|
||||
bx_xmem_region_info_t dup1{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view + page_size), &dup1));
|
||||
CHECK(dup0.physical_tag == pages[0] && dup1.physical_tag == pages[0]);
|
||||
CHECK(XMemMapPhysicalPagesScatter(dup_view, count, flags, nullptr) == dup_view);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
// Mapping over mapped pages replaces them.
|
||||
CHECK(XMemMapPhysicalPages(base, 4, reversed) == base);
|
||||
CHECK(base[9] == 0x43 && base[3 * kPage + 9] == 0x40);
|
||||
|
||||
bx_xmem_region_info_t first{};
|
||||
bx_xmem_region_info_t alias{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear + 7), &first));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter + page_size + 7), &alias));
|
||||
CHECK(first.base_va == reinterpret_cast<uintptr_t>(linear));
|
||||
CHECK(alias.base_va == reinterpret_cast<uintptr_t>(scatter + page_size));
|
||||
CHECK(alias.physical_tag == first.physical_tag && first.physical_tag == pages[0]);
|
||||
CHECK(first.size_bytes == page_size && alias.page_size_bytes == page_size);
|
||||
CHECK(first.protect_flags == PAGE_READWRITE && first.mem_type_flags == MEM_MAPPED);
|
||||
// A NULL page array unmaps; the range stays reserved and can be mapped again.
|
||||
CHECK(XMemMapPhysicalPages(base, 4, nullptr) == base);
|
||||
CHECK(state_of(base) == MEM_RESERVE && !bx_xmem_query_region(reinterpret_cast<uintptr_t>(base), &info));
|
||||
CHECK(base[4 * kPage + 9] == 0x43);
|
||||
CHECK(XMemMapPhysicalPages(base, 4, pages) == base);
|
||||
CHECK(base[9] == 0x40);
|
||||
|
||||
// Rejected frees (stale or duplicate tags) must fail without modifying
|
||||
// page_array or disturbing live mappings.
|
||||
// Mapping outside a mappable reservation is refused.
|
||||
void* plain = VirtualAlloc(nullptr, kPage, MEM_RESERVE, PAGE_NOACCESS);
|
||||
CHECK(plain && !XMemMapPhysicalPages(plain, 1, pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
VirtualFree(plain, 0, MEM_RELEASE);
|
||||
|
||||
// Scatter: parallel arrays of slots and tags; a 0 tag unmaps its slot.
|
||||
PVOID slots[] = {base + 7 * kPage, base + 6 * kPage};
|
||||
ULONG_PTR scatter_pages[] = {pages[0], 0};
|
||||
CHECK(XMemMapPhysicalPagesScatter(slots, 2, scatter_pages));
|
||||
CHECK(base[7 * kPage + 9] == 0x40 && state_of(base + 6 * kPage) == MEM_RESERVE);
|
||||
// One bad slot refuses the whole call before anything changes.
|
||||
PVOID bad_slots[] = {base + 6 * kPage, base + 1};
|
||||
ULONG_PTR bad_pages[] = {pages[1], pages[2]};
|
||||
CHECK(!XMemMapPhysicalPagesScatter(bad_slots, 2, bad_pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && state_of(base + 6 * kPage) == MEM_RESERVE);
|
||||
CHECK(!XMemMapPhysicalPagesScatter(nullptr, 1, bad_pages));
|
||||
CHECK(XMemMapPhysicalPagesScatter(slots, 2, nullptr));
|
||||
CHECK(state_of(base + 7 * kPage) == MEM_RESERVE);
|
||||
|
||||
// Frees with stale or duplicate tags fail without changing the array or live mappings.
|
||||
ULONG_PTR stale[] = {pages[0], 0};
|
||||
CHECK(!XMemFreePhysicalPages(&count, stale, flags));
|
||||
CHECK(!XMemFreePhysicalPages(2, stale));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && stale[0] == pages[0] && stale[1] == 0);
|
||||
CHECK(linear[7] == 0x41);
|
||||
ULONG_PTR dup_free[] = {pages[0], pages[0]};
|
||||
CHECK(!XMemFreePhysicalPages(&count, dup_free, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER
|
||||
&& dup_free[0] == pages[0] && dup_free[1] == pages[0]);
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
CHECK(!XMemFreePhysicalPages(2, dup_free));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && base[9] == 0x40);
|
||||
|
||||
CHECK(!XMemMapPhysicalPagesScatter(nullptr, count, flags, stale));
|
||||
// Freeing unmaps every view of the pages and leaves the reservation reserved.
|
||||
CHECK(XMemFreePhysicalPages(4, pages));
|
||||
CHECK(!pages[0] && !pages[3]);
|
||||
CHECK(state_of(base) == MEM_RESERVE && state_of(base + 4 * kPage) == MEM_RESERVE);
|
||||
CHECK(!XMemMapPhysicalPages(base, 4, reversed));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(!XMemMapPhysicalPages(linear, count, flags, pages));
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
// Partial/over-wide unmap must fail cleanly and leave mapped pages intact.
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count + 1, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
|
||||
// Exact unmap succeeds; repeating unmap on the now-empty span must fail.
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr) == scatter);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, reversed) == scatter);
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
CHECK(XMemFreePhysicalPages(&count, pages, flags));
|
||||
CHECK(!pages[0] && !pages[1]);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear), &first));
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, flags, reversed));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
CHECK(VirtualFree(base, 0, MEM_RELEASE));
|
||||
|
||||
// 2 MB-page reservations exist, but mapping into them is not implemented.
|
||||
ULONG_PTR one = 1;
|
||||
ULONG_PTR page[1]{};
|
||||
CHECK(XMemAllocatePhysicalPages(0, &one, page));
|
||||
auto* large = XMemVirtualAlloc(nullptr, 2 * 1024 * 1024, MEM_RESERVE | kMem2MBPages, kXMemMappable,
|
||||
PAGE_READWRITE);
|
||||
CHECK(large && reinterpret_cast<uintptr_t>(large) % (2 * 1024 * 1024) == 0);
|
||||
CHECK(!XMemMapPhysicalPages(large, 1, page));
|
||||
CHECK(GetLastError() == ERROR_NOT_SUPPORTED);
|
||||
VirtualFree(large, 0, MEM_RELEASE);
|
||||
|
||||
// A title can manage the placeholder itself: reserve one below 4 GB, split it with VirtualFree
|
||||
// and MEM_PRESERVE_PLACEHOLDER, turn one part into a mappable range with MEM_REPLACE_PLACEHOLDER
|
||||
// (with GPU protection bits the host ignores) and map pages into it.
|
||||
auto* region = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE | kMemReservePlaceholder,
|
||||
kXMemGraphics32BitAddress, PAGE_NOACCESS));
|
||||
CHECK(region && reinterpret_cast<uintptr_t>(region) + 4 * kPage <= 0x100000000ull);
|
||||
CHECK(VirtualFree(region, 2 * kPage, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER));
|
||||
auto* part = static_cast<BYTE*>(XMemVirtualAlloc(region, 2 * kPage,
|
||||
MEM_RESERVE | kMemReplacePlaceholder | kMem64KPages,
|
||||
kXMemMappable | kXMemGraphics32BitAddress,
|
||||
PAGE_READWRITE | kPageGraphicsReadWrite));
|
||||
CHECK(part == region);
|
||||
ULONG_PTR two = 2;
|
||||
ULONG_PTR part_pages[2]{};
|
||||
CHECK(XMemAllocatePhysicalPages(kXMemGpuOptimalBandwidthRequired, &two, part_pages));
|
||||
CHECK(XMemMapPhysicalPages(part, 2, part_pages) == part);
|
||||
part[kPage + 5] = 0x6c;
|
||||
CHECK(part[kPage + 5] == 0x6c && state_of(part) == MEM_COMMIT);
|
||||
CHECK(state_of(region + 2 * kPage) == MEM_RESERVE);
|
||||
// Replacing a range that is not a placeholder fails.
|
||||
CHECK(!XMemVirtualAlloc(part, kPage, MEM_RESERVE | kMemReplacePlaceholder | kMem64KPages, kXMemMappable,
|
||||
PAGE_READWRITE));
|
||||
CHECK(XMemFreePhysicalPages(2, part_pages));
|
||||
CHECK(state_of(part) == MEM_RESERVE);
|
||||
|
||||
// The public samples' shape: physical pages allocated with MEM_64K_PAGES (MEM_2MB_PAGES |
|
||||
// MEM_PHYSICAL, so it is not XMEM_2MB_CLUSTERS) mapped into a mappable reservation made with
|
||||
// PAGE_READWRITE | PAGE_WRITECOMBINE | PAGE_GRAPHICS_READWRITE (0x2404).
|
||||
auto* sample = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, kPage, MEM_RESERVE | kMem64KPages, kXMemMappable,
|
||||
PAGE_READWRITE | PAGE_WRITECOMBINE | kPageGraphicsReadWrite));
|
||||
CHECK(sample != nullptr);
|
||||
ULONG_PTR one_64k = 1;
|
||||
ULONG_PTR page_64k[1]{};
|
||||
CHECK(XMemAllocatePhysicalPages(kMem64KPages, &one_64k, page_64k) && page_64k[0]);
|
||||
CHECK(sample && XMemMapPhysicalPages(sample, 1, page_64k) == sample);
|
||||
if (sample) {
|
||||
sample[kPage - 1] = 0x5d;
|
||||
CHECK(sample[kPage - 1] == 0x5d && state_of(sample) == MEM_COMMIT);
|
||||
}
|
||||
CHECK(XMemFreePhysicalPages(1, page_64k));
|
||||
|
||||
// BetterXen extension: a NULL address picks a span; unmapping it frees it.
|
||||
auto* picked = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, 1, page));
|
||||
CHECK(picked && reinterpret_cast<uintptr_t>(picked) % kPage == 0);
|
||||
picked[0] = 0x5a;
|
||||
CHECK(XMemMapPhysicalPages(picked, 1, nullptr) == picked);
|
||||
CHECK(state_of(picked) == MEM_FREE);
|
||||
CHECK(XMemFreePhysicalPages(1, page));
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
if (!check_aliases(64 * 1024, 0) || !check_aliases(2 * 1024 * 1024, 2 * 1024 * 1024)) {
|
||||
if (!check_physical_pages()) {
|
||||
return 1;
|
||||
}
|
||||
std::puts("test_xmem_physical: passed");
|
||||
|
||||
Reference in new issue
Block a user