Compare commits

..
Author SHA1 Message Date
ates d99e35ad42 acphal: IAcpHal slot order and shape contexts
IAcpHal is not COM (authorized GDK documentation): its slots are
Connect, Disconnect, SubmitCommand, PopMessage, GetNumMessages and
Release. AcpHalAllocateShapeContexts and AcpHalReleaseShapeContexts
allocate the documented SHAPE_CONTEXTS arrays from the APU heap, and a
second allocation fails with ACP_E_ALREADY_ALLOCATED; the default APU
heap is 64 MB. A project-authorized target build needs both to start.

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
43 changed files with 470 additions and 7149 deletions

No files matched your search

+5 -42
View File
@@ -14,37 +14,16 @@ remains unsupported.
- `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.
- `AcpHal.dll`:
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
- **The default APU heap** is 64 MB.
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
- `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.
@@ -56,24 +35,8 @@ remains unsupported.
- `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.
-1
View File
@@ -16,7 +16,6 @@
- [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
@@ -1,59 +0,0 @@
# 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.
+104 -23
View File
@@ -1,29 +1,52 @@
#include <windows.h>
#include <unknwn.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <new>
#include "bx_log.h"
namespace {
class AcpHal final : public IUnknown {
LONG refs = 1;
// IAcpHal (authorized GDK documentation; slot order derived from it): not a COM interface. Its
// six methods are Connect(numCommands, numMessages), Disconnect(), SubmitCommand(command,
// commandId, audioFrame, data, notification), PopMessage(ACP_MESSAGE*), GetNumMessages() and
// Release(). BetterXen has no audio control processor: commands are accepted and logged once,
// and no message ever arrives.
class AcpHal {
UINT32 commands_ = 0, messages_ = 0;
bool connected_ = false;
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown) return E_NOINTERFACE;
AddRef();
*out = this;
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
commands_ = num_commands;
messages_ = num_messages;
connected_ = true;
char detail[96];
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
ULONG left = InterlockedDecrement(&refs);
if (!left) delete this;
return left;
virtual HRESULT WINAPI Disconnect() {
connected_ = false;
return S_OK;
}
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
if (!connected_) return E_UNEXPECTED;
static LONG logged = 0;
if (InterlockedIncrement(&logged) == 1) {
char detail[96];
std::snprintf(detail, sizeof(detail), "first command type %u accepted; ACP commands are not processed", command);
bx_log_emit(BX_LOG_WARN, "acphal", "submit_command", detail);
}
return S_OK;
}
virtual bool WINAPI PopMessage(void*) { return false; }
virtual UINT32 WINAPI GetNumMessages() { return 0; }
virtual void WINAPI Release() { delete this; }
virtual ~AcpHal() = default;
};
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
@@ -47,19 +70,77 @@ HRESULT WINAPI AcpHalCreate(void** out) {
return *out ? S_OK : E_OUTOFMEMORY;
}
// 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 E_NOTIMPL;
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment);
HRESULT WINAPI ApuFree(void* va);
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) / AcpHalReleaseShapeContexts() (authorized GDK
// documentation; layout and element sizes derived from it, no header text): the caller fills six
// counts, the call allocates each array from the APU heap and returns its CPU pointer and APU
// address. Allocating twice without a release fails with ACP_E_ALREADY_ALLOCATED.
struct ShapeContexts {
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
void* arrays[6]; // CPU pointers, same order
uint32_t apu[6]; // APU addresses, same order
};
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS is 96 bytes");
static_assert(offsetof(ShapeContexts, arrays) == 24 && offsetof(ShapeContexts, apu) == 72, "SHAPE_CONTEXTS layout");
constexpr uint32_t kShapeElementBytes[6] = {32, 160, 32, 16, 64, 32};
constexpr HRESULT kAcpAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
constexpr uint32_t kDefaultApuHeapBytes = 64u << 20;
void* shape_arrays[6];
bool shape_allocated = false;
HRESULT WINAPI AcpHalAllocateShapeContexts(void* argument) {
auto* contexts = static_cast<ShapeContexts*>(argument);
if (!contexts) return E_INVALIDARG;
if (shape_allocated) return kAcpAlreadyAllocated;
for (int i = 0; i < 6; ++i) {
if (contexts->counts[i] > (0xFFFFFFFFu / kShapeElementBytes[i])) return E_INVALIDARG;
}
{
// The console has a default non-cached APU heap; create one when the title made none.
std::lock_guard guard(heap_lock);
if (!heap_created) {
capacity = kDefaultApuHeapBytes;
used = 0;
heap_created = true;
bx_log_emit(BX_LOG_INFO, "acphal", "apu_default_heap", "no ApuCreateHeap before shape contexts: 64 MB default heap");
}
}
void* arrays[6] = {};
uint32_t apu[6] = {};
for (int i = 0; i < 6; ++i) {
if (!contexts->counts[i]) continue;
const uint32_t bytes = contexts->counts[i] * kShapeElementBytes[i];
const HRESULT hr = ApuAlloc(&arrays[i], &apu[i], bytes, 64);
if (FAILED(hr)) {
for (int j = 0; j < i; ++j) ApuFree(arrays[j]);
return E_OUTOFMEMORY;
}
std::memset(arrays[i], 0, bytes);
}
for (int i = 0; i < 6; ++i) {
contexts->arrays[i] = arrays[i];
contexts->apu[i] = apu[i];
shape_arrays[i] = arrays[i];
}
shape_allocated = true;
char detail[160];
std::snprintf(detail, sizeof(detail), "src=%u eqcomp=%u filtvol=%u dma=%u xma=%u pcm=%u", contexts->counts[0],
contexts->counts[1], contexts->counts[2], contexts->counts[3], contexts->counts[4], contexts->counts[5]);
bx_log_emit(BX_LOG_INFO, "acphal", "shape_contexts_allocated", detail);
return S_OK;
}
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
return E_NOTIMPL;
if (!shape_allocated) return S_OK;
for (void*& array : shape_arrays) {
ApuFree(array);
array = nullptr;
}
shape_allocated = false;
return S_OK;
}
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
+1 -12
View File
@@ -5,16 +5,5 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
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 user32 dxguid)
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
-100
View File
@@ -1,100 +0,0 @@
/*
* 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"
+8 -88
View File
@@ -1,10 +1,7 @@
#include "proxy.h"
#include "vmem.h"
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
/*
@@ -23,38 +20,6 @@ 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, [] {
@@ -68,29 +33,17 @@ void initialize_trace_flag() {
extern "C" {
/*
* 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.
* `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.
*/
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
HRESULT WINAPI D3D12XboxCreateDevice(PVOID 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();
@@ -145,40 +98,12 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID r
}
char detail[256];
std::snprintf(detail, sizeof(detail),
"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);
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
static_cast<void*>(proxy->h_ID3D12Device), highest, params ? "non-null" : "null", g_bx_trace_d3d);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
/*
* 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;
}
@@ -197,12 +122,7 @@ HRESULT WINAPI D3D12SerializeVersionedRootSignature(
auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(
GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")));
if (fn) {
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;
return fn(desc, blob, error_blob);
}
}
BX_STUB_LOG("d3d12_xs.dll", "D3D12SerializeVersionedRootSignature");
-294
View File
@@ -1,294 +0,0 @@
/*
* Descriptor heaps at title-visible addresses (ADR 0009).
*
* On the console a descriptor handle is an address: the runtime allocates a heap's storage as a
* GPU allocation through XMemAlloc (object type Resource, allocator D3D), so a title's allocation
* hooks can place it in the title's own memory, and handles are base + index * descriptor size,
* with the console's sizes (32 bytes CBV/SRV/UAV, 16 sampler, 112 RTV, 128 DSV).
*
* Here each heap has that title-visible storage (allocated the same way, so the title's hooks
* see the same request) and a host D3D12 heap. Title handles are translated to host handles by
* index. The storage is not interpreted: descriptors a title writes there inline (titles built
* with D3DCOMPILE_NO_DEBUG) are not translated, and ID3D12Device's m_OutOfLineFlags keeps the
* other titles' descriptor writes on the out-of-line path, which reaches the host heap.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
namespace {
constexpr ULONGLONG kObjectTypeResource = 4; // D3D12 XMemAlloc object types: GPU "Resource"
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
struct Heap {
uintptr_t base;
UINT count;
UINT xbox_size;
ID3D12DescriptorHeap* host; // not owned: the Xbox object owns the reference
SIZE_T host_cpu;
UINT64 host_gpu;
UINT host_increment;
ULONGLONG attributes;
};
std::mutex g_lock;
Heap* g_heaps = nullptr;
size_t g_count = 0;
size_t g_capacity = 0;
bool add(const Heap& heap) {
std::lock_guard<std::mutex> guard(g_lock);
if (g_count == g_capacity) {
const size_t capacity = g_capacity ? g_capacity * 2 : 32;
auto* grown = new (std::nothrow) Heap[capacity];
if (!grown) return false;
for (size_t i = 0; i < g_count; ++i) grown[i] = g_heaps[i];
delete[] g_heaps;
g_heaps = grown;
g_capacity = capacity;
}
g_heaps[g_count++] = heap;
return true;
}
const Heap* find_locked(uintptr_t address) {
for (size_t i = 0; i < g_count; ++i) {
const Heap& h = g_heaps[i];
if (address >= h.base && address < h.base + static_cast<uintptr_t>(h.count) * h.xbox_size) return &h;
}
return nullptr;
}
void log_untranslated(const char* what, uint64_t value) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) >= 8) return; // the first few are enough to see the pattern
char detail[96];
std::snprintf(detail, sizeof(detail), "%s 0x%llx is in no title descriptor heap", what,
static_cast<unsigned long long>(value));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "descriptor_untranslated", detail);
}
} // namespace
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type) {
switch (type) {
case D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV: return 32;
case D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER: return 16;
case D3D12_DESCRIPTOR_HEAP_TYPE_RTV: return 112;
case D3D12_DESCRIPTOR_HEAP_TYPE_DSV: return 128;
default: return 32;
}
}
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title) {
if (!title.ptr) return title;
std::lock_guard<std::mutex> guard(g_lock);
if (const Heap* h = find_locked(title.ptr)) {
return {h->host_cpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
}
log_untranslated("CPU descriptor handle", title.ptr);
return title;
}
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title) {
if (!title.ptr) return title;
std::lock_guard<std::mutex> guard(g_lock);
if (const Heap* h = find_locked(static_cast<uintptr_t>(title.ptr))) {
if (h->host_gpu) return {h->host_gpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
}
log_untranslated("GPU descriptor handle", title.ptr);
return title;
}
void bx_xbox_descriptor_heap_forget(IUnknown* host) {
Heap gone{};
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (static_cast<IUnknown*>(g_heaps[i].host) == host) {
gone = g_heaps[i];
g_heaps[i] = g_heaps[--g_count];
break;
}
}
}
if (gone.base) XMemFree(reinterpret_cast<void*>(gone.base), gone.attributes);
}
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDescriptorHeap");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device>(self);
ID3D12DescriptorHeap* host = nullptr;
HRESULT hr = device->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&host));
if (FAILED(hr) || !host) return FAILED(hr) ? hr : E_FAIL;
const UINT size = bx_xbox_descriptor_size(desc->Type);
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D;
void* storage = XMemAlloc(static_cast<SIZE_T>(desc->NumDescriptors) * size, attributes);
char detail[200];
std::snprintf(detail, sizeof(detail), "type=%d count=%u xbox_size=%u flags=0x%x title_base=%p",
static_cast<int>(desc->Type), desc->NumDescriptors, size, static_cast<unsigned>(desc->Flags), storage);
bx_log_emit(storage ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "descriptor_heap", detail);
if (!storage) {
host->Release();
return E_OUTOFMEMORY;
}
D3D12_CPU_DESCRIPTOR_HANDLE cpu{};
host->GetCPUDescriptorHandleForHeapStart(&cpu);
D3D12_GPU_DESCRIPTOR_HANDLE gpu{};
if (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) host->GetGPUDescriptorHandleForHeapStart(&gpu);
const Heap heap{reinterpret_cast<uintptr_t>(storage), desc->NumDescriptors, size, host, cpu.ptr, gpu.ptr,
device->GetDescriptorHandleIncrementSize(desc->Type), attributes};
if (!add(heap)) {
XMemFree(storage, attributes);
host->Release();
return E_OUTOFMEMORY;
}
*ppv = host;
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void*, D3D12_DESCRIPTOR_HEAP_TYPE type) {
return bx_xbox_descriptor_size(type);
}
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self) {
auto* host = bx_xbox_host<ID3D12DescriptorHeap>(self);
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_heaps[i].host == host) return {g_heaps[i].base};
}
return {0};
}
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self) {
// On the console the GPU handle of a heap is the same address as its CPU handle.
return {bx_xbox_heap_cpu_start(self).ptr};
}
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateConstantBufferView");
D3D12_CONSTANT_BUFFER_VIEW_DESC host_desc{};
if (desc) {
host_desc = *desc;
host_desc.BufferLocation = bx_xbox_host_gpu_va(desc->BufferLocation);
}
bx_xbox_host<ID3D12Device>(self)->CreateConstantBufferView(desc ? &host_desc : nullptr, bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
const UINT* dest_sizes, UINT src_ranges,
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
D3D12_DESCRIPTOR_HEAP_TYPE type) {
BX_D3D_TRACE("XboxDevice", "CopyDescriptors");
auto* dst = new (std::nothrow) D3D12_CPU_DESCRIPTOR_HANDLE[dest_ranges + src_ranges + 1];
if (!dst) return;
D3D12_CPU_DESCRIPTOR_HANDLE* src = dst + dest_ranges;
for (UINT i = 0; i < dest_ranges; ++i) dst[i] = bx_xbox_host_cpu_handle(dest_starts[i]);
for (UINT i = 0; i < src_ranges; ++i) src[i] = bx_xbox_host_cpu_handle(src_starts[i]);
bx_xbox_host<ID3D12Device>(self)->CopyDescriptors(dest_ranges, dst, dest_sizes, src_ranges, src, src_sizes, type);
delete[] dst;
}
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv) {
BX_D3D_TRACE("XboxGraphicsCommandList", "OMSetRenderTargets");
D3D12_CPU_DESCRIPTOR_HANDLE host_rtvs[8] = {};
const UINT n = count > 8 ? 8 : count;
for (UINT i = 0; rtvs && i < (single_range ? 1u : n); ++i) host_rtvs[i] = bx_xbox_host_cpu_handle(rtvs[i]);
const D3D12_CPU_DESCRIPTOR_HANDLE host_dsv = dsv ? bx_xbox_host_cpu_handle(*dsv) : D3D12_CPU_DESCRIPTOR_HANDLE{};
bx_xbox_host<ID3D12GraphicsCommandList>(self)->OMSetRenderTargets(n, rtvs ? host_rtvs : nullptr, single_range,
dsv ? &host_dsv : nullptr);
}
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
D3D12_VERTEX_BUFFER_VIEW host[32] = {};
const UINT n = count > 32 ? 32 : count;
for (UINT i = 0; views && i < n; ++i) {
host[i] = views[i];
host[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
}
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetIndexBuffer");
D3D12_INDEX_BUFFER_VIEW host{};
if (view) {
host = *view;
host.BufferLocation = bx_xbox_host_gpu_va(view->BufferLocation);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetIndexBuffer(view ? &host : nullptr);
}
} // extern "C"
namespace {
/* The leading fields of D3D12XBOX_SAMPLER_DESC (authorized GDK header; every field is 4 bytes). */
struct XboxSamplerPrefix {
UINT flags;
UINT filter_mag; // D3D12XBOX_TEXTURE_XY_FILTER: 0 point, 1 bilinear, 2 aniso point, 3 aniso bilinear
UINT filter_min;
UINT filter_mip; // D3D12XBOX_TEXTURE_MIP_FILTER: 0 none, 1 point, 2 linear
UINT filter_z;
UINT filter_mode; // D3D12XBOX_TEXTURE_FILTER_MODE: 0 lerp, 1 min, 2 max
D3D12_TEXTURE_ADDRESS_MODE address_u, address_v, address_w;
FLOAT min_lod, max_lod, mip_lod_bias, mip_lod_bias_secondary;
UINT max_anisotropy;
FLOAT anisotropy_bias;
UINT anisotropy_threshold;
D3D12_COMPARISON_FUNC comparison;
FLOAT border_color[4];
};
static_assert(sizeof(XboxSamplerPrefix) == 21 * 4, "D3D12XBOX_SAMPLER_DESC prefix layout");
D3D12_FILTER_TYPE xy_type(UINT filter) { return (filter & 1) ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT; }
} // namespace
extern "C" void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateSamplerX");
if (!xbox_desc) return;
XboxSamplerPrefix x{};
std::memcpy(&x, xbox_desc, sizeof(x));
// A comparison function other than NEVER selects comparison filtering (inference: the console
// description has no separate comparison filter, so the function is the only signal).
const bool compare = x.comparison > D3D12_COMPARISON_FUNC_NEVER;
const D3D12_FILTER_REDUCTION_TYPE reduction = compare ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON
: x.filter_mode == 1 ? D3D12_FILTER_REDUCTION_TYPE_MINIMUM
: x.filter_mode == 2 ? D3D12_FILTER_REDUCTION_TYPE_MAXIMUM
: D3D12_FILTER_REDUCTION_TYPE_STANDARD;
D3D12_SAMPLER_DESC pc{};
const bool aniso = x.filter_mag >= 2 || x.filter_min >= 2;
pc.Filter = aniso ? D3D12_ENCODE_ANISOTROPIC_FILTER(reduction)
: D3D12_ENCODE_BASIC_FILTER(xy_type(x.filter_min), xy_type(x.filter_mag),
x.filter_mip == 2 ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT,
reduction);
pc.AddressU = x.address_u;
pc.AddressV = x.address_v;
pc.AddressW = x.address_w;
pc.MipLODBias = x.mip_lod_bias;
pc.MaxAnisotropy = aniso ? (x.max_anisotropy < 1 ? 1 : x.max_anisotropy > 16 ? 16 : x.max_anisotropy) : 1;
pc.ComparisonFunc = compare ? x.comparison : D3D12_COMPARISON_FUNC_NEVER;
for (int i = 0; i < 4; ++i) pc.BorderColor[i] = x.border_color[i];
pc.MinLOD = x.min_lod;
pc.MaxLOD = x.filter_mip == 0 ? x.min_lod : x.max_lod; // no mip filter: the base level only
bx_xbox_host<ID3D12Device>(self)->CreateSampler(&pc, bx_xbox_host_cpu_handle(dest));
}
-145
View File
@@ -1,145 +0,0 @@
/*
* Fences with a title-visible value (ADR 0009). ID3D12Fence1::GetGpuAddressX returns the GPU
* address of a fence's 64-bit value (authorized GDK documentation); titles read it from the CPU
* and target it with Write*BitValue*X and Wait*BitValueX. Each fence that is asked for its
* address gets an 8-byte slot in memory this layer owns, kept equal to the host fence's value:
* - a CPU Signal stores the value at once;
* - a queue Signal stores it when the host fence completes (a one-shot threadpool wait);
* - a GPU value write to the slot (gpu_writes.cpp) also signals the host fence.
*/
#include "xbox_facade.h"
#include <atomic>
#include <mutex>
#include <vector>
namespace {
struct Slot {
ID3D12Fence* host;
std::atomic<uint64_t>* value;
};
std::mutex g_lock;
std::vector<Slot> g_slots;
std::atomic<uint64_t>* g_page = nullptr;
size_t g_used = 0;
constexpr size_t kSlotsPerPage = 4096 / sizeof(uint64_t);
std::atomic<uint64_t>* allocate_locked() {
if (!g_page || g_used == kSlotsPerPage) {
g_page = static_cast<std::atomic<uint64_t>*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
g_used = 0;
if (!g_page) return nullptr;
}
return &g_page[g_used++];
}
std::atomic<uint64_t>* slot_of(ID3D12Fence* host) {
std::lock_guard<std::mutex> guard(g_lock);
for (const Slot& s : g_slots) {
if (s.host == host) return s.value;
}
return nullptr;
}
void store_max(std::atomic<uint64_t>* slot, uint64_t value) {
uint64_t current = slot->load();
while (current < value && !slot->compare_exchange_weak(current, value)) {
}
}
struct Pending {
std::atomic<uint64_t>* slot;
uint64_t value;
HANDLE event;
HANDLE wait;
};
void CALLBACK on_completed(void* context, BOOLEAN) {
auto* p = static_cast<Pending*>(context);
store_max(p->slot, p->value);
// The wait cannot be unregistered from its own callback with a blocking call; hand it off.
UnregisterWaitEx(p->wait, nullptr);
CloseHandle(p->event);
delete p;
}
} // namespace
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host) {
std::lock_guard<std::mutex> guard(g_lock);
for (const Slot& s : g_slots) {
if (reinterpret_cast<uint64_t>(s.value) == address) {
if (host) *host = s.host;
return true;
}
}
return false;
}
void bx_xbox_fence_forget(IUnknown* host) {
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_slots.size(); ++i) {
if (static_cast<IUnknown*>(g_slots[i].host) == host) { // the slot memory is not reused
g_slots[i] = g_slots.back();
g_slots.pop_back();
return;
}
}
}
extern "C" {
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self) {
BX_D3D_TRACE("XboxFence", "GetGpuAddressX");
auto* host = bx_xbox_host<ID3D12Fence>(self);
if (auto* existing = slot_of(host)) return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(existing);
std::lock_guard<std::mutex> guard(g_lock);
std::atomic<uint64_t>* slot = allocate_locked();
if (!slot) return 0;
slot->store(host->GetCompletedValue());
g_slots.push_back({host, slot});
return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(slot);
}
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value) {
BX_D3D_TRACE("XboxFence", "Signal");
auto* host = bx_xbox_host<ID3D12Fence>(self);
const HRESULT hr = host->Signal(value);
if (SUCCEEDED(hr)) {
if (auto* slot = slot_of(host)) slot->store(value);
}
return hr;
}
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value) {
BX_D3D_TRACE("XboxCommandQueue", "Signal");
ID3D12Fence* host_fence = bx_xbox_unwrap_as(fence);
const HRESULT hr = bx_xbox_host<ID3D12CommandQueue>(self)->Signal(host_fence, value);
std::atomic<uint64_t>* slot = SUCCEEDED(hr) && host_fence ? slot_of(host_fence) : nullptr;
if (!slot) return hr;
if (host_fence->GetCompletedValue() >= value) {
store_max(slot, value);
return hr;
}
auto* p = new (std::nothrow) Pending{slot, value, CreateEventW(nullptr, TRUE, FALSE, nullptr), nullptr};
if (!p || !p->event) {
delete p;
return hr;
}
if (FAILED(host_fence->SetEventOnCompletion(value, p->event)) ||
!RegisterWaitForSingleObject(&p->wait, p->event, on_completed, p, INFINITE, WT_EXECUTEONLYONCE)) {
CloseHandle(p->event);
delete p;
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "fence_slot", "could not arm the completion mirror for a queue Signal");
}
return hr;
}
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value) {
BX_D3D_TRACE("XboxCommandQueue", "Wait");
return bx_xbox_host<ID3D12CommandQueue>(self)->Wait(bx_xbox_unwrap_as(fence), value);
}
} // extern "C"
-173
View File
@@ -1,173 +0,0 @@
/*
* Xbox frame pacing on the host (ADR 0009): ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX
* and WaitFrameEventX, as the authorized GDK documentation describes them.
*
* On the console, display hardware signals the frame events. Here one thread emulates them
* from the recorded frame interval: at the start of each interval it signals the VBLANK and
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
* new frame pipeline token. Each signal also sets the ancillary events given to
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
*/
#include "xbox_facade.h"
#include <cstdio>
#include <mutex>
#include <thread>
namespace {
constexpr UINT kEventTypes = 3; // ORIGIN, DISPLAY_VBLANK, DISPLAY_FLIP
constexpr UINT kOrigin = 0;
constexpr UINT kMaxAncillarySignals = 7;
constexpr UINT kMaxAncillaryWaits = 63;
constexpr UINT kScheduleDisableSignal = 0x1;
constexpr UINT kWaitAll = 0x1;
constexpr UINT kWaitProcessTokenOnTimeout = 0x2;
constexpr UINT kIntervalFlag60FpsPlus = 0x1;
constexpr UINT kSignaledNone = 0xFFFFFFFF;
constexpr UINT kInfinite = 0xFFFFFFFF;
struct Scheduled {
bool active = false;
UINT offset_us = 0;
HANDLE ancillary[kMaxAncillarySignals] = {};
UINT ancillary_count = 0;
};
std::mutex g_lock;
UINT g_interval_us = 0;
UINT g_period = 0;
Scheduled g_events[kEventTypes];
HANDLE g_signal[kEventTypes] = {}; // auto-reset, set at each occurrence
UINT64 g_next_token = 1;
UINT64 g_last_origin_token = 0;
bool g_thread_started = false;
void close_ancillary(Scheduled& e) {
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
e.ancillary_count = 0;
}
void signal(UINT type) {
std::lock_guard<std::mutex> guard(g_lock);
const Scheduled& e = g_events[type];
if (!e.active) return;
if (type == kOrigin) g_last_origin_token = g_next_token++;
SetEvent(g_signal[type]);
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
}
void pacing_thread() {
LARGE_INTEGER frequency, start;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
const auto now_us = [&] {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return static_cast<UINT64>((t.QuadPart - start.QuadPart) * 1000000 / frequency.QuadPart);
};
const auto sleep_until = [&](UINT64 target_us) {
for (UINT64 t = now_us(); t < target_us; t = now_us()) {
const UINT64 ms = (target_us - t) / 1000;
Sleep(ms ? static_cast<DWORD>(ms) : 0);
}
};
UINT64 interval_start = 0;
for (;;) {
UINT interval, origin_offset;
{
std::lock_guard<std::mutex> guard(g_lock);
interval = g_interval_us;
origin_offset = g_events[kOrigin].offset_us;
}
signal(1);
signal(2);
sleep_until(interval_start + (origin_offset < interval ? origin_offset : 0));
signal(kOrigin);
interval_start += interval;
sleep_until(interval_start);
}
}
void log_pacing(const char* event, const char* fmt, UINT a, UINT b, UINT c) {
char detail[160];
std::snprintf(detail, sizeof(detail), fmt, a, b, c);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void*, IDXGIOutput*, UINT length_us, UINT period,
UINT flags) {
BX_D3D_TRACE("XboxDevice", "SetFrameIntervalX");
if (length_us == 0 || period < 1 || period > 4 || (flags & ~kIntervalFlag60FpsPlus) != 0) return E_INVALIDARG;
std::lock_guard<std::mutex> guard(g_lock);
g_interval_us = length_us;
g_period = period;
log_pacing("frame_interval", "length_us=%u period=%u flags=0x%x (host timer, no display sync)", length_us, period, flags);
return S_OK;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void*, UINT type, UINT offset_us,
const BxXboxFrameObjectList* signals, UINT flags) {
BX_D3D_TRACE("XboxDevice", "ScheduleFrameEventX");
if (type >= kEventTypes || (flags & ~kScheduleDisableSignal) != 0) return E_INVALIDARG;
if (signals && (signals->Count > kMaxAncillarySignals || (signals->Count && !signals->pObjects))) return E_INVALIDARG;
std::lock_guard<std::mutex> guard(g_lock);
if (g_interval_us == 0) return E_INVALIDARG; // documented: an interval must be established first
if (offset_us >= g_interval_us) return E_INVALIDARG;
for (UINT i = 0; i < kEventTypes; ++i) {
if (!g_signal[i] && !(g_signal[i] = CreateEventW(nullptr, FALSE, FALSE, nullptr))) return E_OUTOFMEMORY;
}
Scheduled& e = g_events[type];
close_ancillary(e);
e.active = !(flags & kScheduleDisableSignal);
e.offset_us = offset_us;
for (UINT i = 0; signals && i < signals->Count; ++i) {
// The title may close its handle; the scheduled signal keeps its own copy.
if (!DuplicateHandle(GetCurrentProcess(), signals->pObjects[i], GetCurrentProcess(), &e.ancillary[e.ancillary_count],
0, FALSE, DUPLICATE_SAME_ACCESS)) {
close_ancillary(e);
return E_INVALIDARG;
}
++e.ancillary_count;
}
log_pacing("frame_event_scheduled", "type=%u offset_us=%u ancillary=%u", type, offset_us, e.ancillary_count);
if (!g_thread_started) {
std::thread(pacing_thread).detach();
g_thread_started = true;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UINT timeout_ms,
const BxXboxFrameWaitList* waits, UINT flags,
UINT64* token) {
BX_D3D_TRACE("XboxDevice", "WaitFrameEventX");
if (type >= kEventTypes || (flags & ~(kWaitAll | kWaitProcessTokenOnTimeout)) != 0) return E_INVALIDARG;
if (waits && (waits->Count > kMaxAncillaryWaits || (waits->Count && !waits->pObjects))) return E_INVALIDARG;
HANDLE handles[1 + kMaxAncillaryWaits];
{
std::lock_guard<std::mutex> guard(g_lock);
if (!g_events[type].active) return E_INVALIDARG; // documented: the event must be scheduled
handles[0] = g_signal[type];
}
const UINT ancillary = waits ? waits->Count : 0;
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
const DWORD result = WaitForMultipleObjects(1 + ancillary, handles, (flags & kWaitAll) != 0,
timeout_ms == kInfinite ? INFINITE : timeout_ms);
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
if (waits && waits->pSignaledObjectIndex) {
*waits->pSignaledObjectIndex = satisfied && !(flags & kWaitAll) && result > WAIT_OBJECT_0
? result - WAIT_OBJECT_0 - 1 : kSignaledNone;
}
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
std::lock_guard<std::mutex> guard(g_lock);
*token = satisfied ? g_last_origin_token : g_next_token++;
}
return satisfied ? S_OK : S_FALSE;
}
} // extern "C"
-267
View File
@@ -1,267 +0,0 @@
/*
* GPU value writes into title memory (ADR 0009): Write32/64BitValueBottomOfPipeX and
* ...TopOfPipeX record "when the GPU reaches this point, store this value at this address".
* On the console the address is title memory that the CPU polls. The host GPU cannot write
* title memory, so each command list keeps its writes in recording order, and when a queue
* executes lists that carry writes, it waits for the host GPU (an internal fence) and stores the
* values from the CPU, in submission order, before the Execute call returns. Executes with
* writes are therefore synchronous (logged once); executes without writes are not changed.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <mutex>
#include <vector>
namespace {
struct Write {
uint64_t address;
uint64_t value;
bool wide;
bool wait = false; // Wait*BitValueX: value is the reference
D3D12_COMPARISON_FUNC compare = D3D12_COMPARISON_FUNC_GREATER_EQUAL;
uint64_t mask = ~0ull;
};
struct ListWrites {
ID3D12GraphicsCommandList* list;
std::vector<Write> writes;
};
std::mutex g_lock;
std::vector<ListWrites> g_lists;
ListWrites* find_locked(ID3D12GraphicsCommandList* list) {
for (ListWrites& entry : g_lists) {
if (entry.list == list) return &entry;
}
return nullptr;
}
bool writable(uint64_t address, size_t size) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) || region.State != MEM_COMMIT) return false;
constexpr DWORD kWritable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
return (region.Protect & kWritable) && address + size <= reinterpret_cast<uint64_t>(region.BaseAddress) + region.RegionSize;
}
void record(void* self, const Write& op) {
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
std::lock_guard<std::mutex> guard(g_lock);
ListWrites* entry = find_locked(list);
if (!entry) {
g_lists.push_back({list, {}});
entry = &g_lists.back();
}
entry->writes.push_back(op);
}
void record(void* self, uint64_t address, uint64_t value, bool wide) { record(self, Write{address, value, wide}); }
bool satisfied(const Write& w) {
const uint64_t raw = w.wide ? reinterpret_cast<const std::atomic<uint64_t>*>(w.address)->load()
: reinterpret_cast<const std::atomic<uint32_t>*>(w.address)->load();
const uint64_t v = raw & w.mask;
switch (w.compare) {
case D3D12_COMPARISON_FUNC_NEVER: return false;
case D3D12_COMPARISON_FUNC_LESS: return v < w.value;
case D3D12_COMPARISON_FUNC_EQUAL: return v == w.value;
case D3D12_COMPARISON_FUNC_LESS_EQUAL: return v <= w.value;
case D3D12_COMPARISON_FUNC_GREATER: return v > w.value;
case D3D12_COMPARISON_FUNC_NOT_EQUAL: return v != w.value;
case D3D12_COMPARISON_FUNC_GREATER_EQUAL: return v >= w.value;
default: return true;
}
}
// A GPU wait on memory becomes a host queue Wait when the memory is a fence slot and the
// comparison is >=; otherwise the CPU polls the memory before submitting (10 s limit, logged).
void apply_wait(ID3D12CommandQueue* queue, const Write& w) {
ID3D12Fence* fence = nullptr;
if (w.wide && w.compare == D3D12_COMPARISON_FUNC_GREATER_EQUAL && w.mask == ~0ull && bx_xbox_fence_slot(w.address, &fence)) {
queue->Wait(fence, w.value);
return;
}
if (!writable(w.address, w.wide ? 8 : 4)) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", "wait address is not title memory; wait skipped");
return;
}
const ULONGLONG start = GetTickCount64();
while (!satisfied(w)) {
if (GetTickCount64() - start > 10000) {
char detail[128];
std::snprintf(detail, sizeof(detail), "wait on 0x%llx not satisfied after 10 s; submitting anyway",
static_cast<unsigned long long>(w.address));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", detail);
return;
}
SwitchToThread();
}
}
struct QueueFence {
ID3D12CommandQueue* queue;
ID3D12Fence* fence;
uint64_t value;
};
std::vector<QueueFence> g_fences; // guarded by g_lock
HRESULT wait_for_queue(ID3D12CommandQueue* queue) {
ID3D12Fence* fence = nullptr;
uint64_t value = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
for (QueueFence& q : g_fences) {
if (q.queue == queue) {
fence = q.fence;
value = ++q.value;
}
}
if (!fence) {
ID3D12Device* device = nullptr;
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return E_FAIL;
const HRESULT hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
device->Release();
if (FAILED(hr)) return hr;
value = 1;
g_fences.push_back({queue, fence, value});
}
}
HRESULT hr = queue->Signal(fence, value);
if (FAILED(hr)) return hr;
if (fence->GetCompletedValue() >= value) return S_OK;
HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if (!event) return E_OUTOFMEMORY;
hr = fence->SetEventOnCompletion(value, event);
if (SUCCEEDED(hr) && WaitForSingleObject(event, 10000) != WAIT_OBJECT_0) hr = HRESULT_FROM_WIN32(WAIT_TIMEOUT);
CloseHandle(event);
return hr;
}
void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
BxXboxUnwrapArray<ID3D12CommandList> host(lists, count);
if (!host.ok()) return;
std::vector<Write> pending;
{
std::lock_guard<std::mutex> guard(g_lock);
for (UINT i = 0; i < count; ++i) {
if (ListWrites* entry = find_locked(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host.data()[i])))) {
pending.insert(pending.end(), entry->writes.begin(), entry->writes.end());
}
}
}
bx_xbox_sync_mapped_buffers();
for (const Write& w : pending) {
if (w.wait) apply_wait(queue, w);
}
queue->ExecuteCommandLists(count, host.data());
bool any_write = false;
for (const Write& w : pending) any_write = any_write || !w.wait;
if (!any_write) return;
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "gpu_value_writes",
"executes carrying Write*BitValue*X wait for the host GPU, then store the values in title memory");
}
const HRESULT hr = wait_for_queue(queue);
if (FAILED(hr)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "waiting for the host GPU failed hr=0x%08lx; values still written",
static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
}
for (const Write& w : pending) {
if (w.wait) continue;
if (!writable(w.address, w.wide ? 8 : 4)) {
static std::atomic<int> bad{0};
if (bad.fetch_add(1) < 8) {
char detail[96];
std::snprintf(detail, sizeof(detail), "address 0x%llx is not writable title memory; value dropped",
static_cast<unsigned long long>(w.address));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
}
continue;
}
if (w.wide) {
reinterpret_cast<std::atomic<uint64_t>*>(w.address)->store(w.value, std::memory_order_release);
} else {
reinterpret_cast<std::atomic<uint32_t>*>(w.address)->store(static_cast<uint32_t>(w.value), std::memory_order_release);
}
ID3D12Fence* fence = nullptr;
if (w.wide && bx_xbox_fence_slot(w.address, &fence)) fence->Signal(w.value);
}
}
} // namespace
void bx_xbox_gpu_writes_reset(IUnknown* host_list) {
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_lists.size(); ++i) {
if (static_cast<IUnknown*>(g_lists[i].list) == host_list) {
g_lists[i] = std::move(g_lists.back());
g_lists.pop_back();
return;
}
}
}
extern "C" {
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueBottomOfPipeX");
record(self, address, value, false);
}
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueBottomOfPipeX");
record(self, address, value, true);
}
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueTopOfPipeX");
record(self, address, value, false);
}
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueTopOfPipeX");
record(self, address, value, true);
}
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT64 reference, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait64BitValueX");
Write op{address, reference, true};
op.wait = true;
op.compare = compare;
record(self, op);
}
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT reference, UINT mask, UINT) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait32BitValueX");
Write op{address, reference, false};
op.wait = true;
op.compare = compare;
op.mask = mask;
record(self, op);
}
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists) {
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists");
execute(self, count, lists);
}
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
UINT64 token, UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists2X");
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
char detail[128];
std::snprintf(detail, sizeof(detail), "frame token and kickoff flags (first: token=%llu flags=0x%x) not used by the host",
static_cast<unsigned long long>(token), flags);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "execute_command_lists2_x", detail);
}
execute(self, count, lists);
}
} // extern "C"
-193
View File
@@ -1,193 +0,0 @@
// Console GPU page mappings: ID3D12CommandQueue CopyPageMappingsX, ClearPageMappingsX and
// CopyPageMappingsBatchX (authorized GDK documentation; layouts and semantics derived from it).
//
// A page pool is title memory registered with RegisterPagePoolX; these calls make the 64 KiB (or,
// with D3D12XBOX_PAGE_MAPPING_FLAG_2MB_PAGES, 2 MiB) pages at a destination GPU address show pool
// pages. GPU addresses are title addresses in BetterXen and pool pages are xmem physical pages, so
// each destination page is mapped onto the pool page's physical page with
// XMemMapPhysicalPagesScatter; xmem reports the physical page behind a pool address. Range types:
// incrementing pool pages, one constant pool page, null pages (unmapped) and skipped pages (left as
// they are). The remapping happens when the call is made, not in queue order.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <vector>
#include "bx_log.h"
#include "bx_xmem_internal.h"
#include "xbox_facade.h"
namespace {
struct PageMappingRange {
UINT RangeType;
UINT StartPageIndexInPool;
UINT PageCount;
};
struct PageMappingBatch {
D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress;
UINT RangeCount;
const PageMappingRange* pRanges;
};
static_assert(sizeof(PageMappingRange) == 12, "D3D12XBOX_PAGE_MAPPING_RANGE");
static_assert(sizeof(PageMappingBatch) == 24, "D3D12XBOX_PAGE_MAPPING_BATCH");
enum : UINT { kIncrementing = 0, kConstant = 1, kNullPages = 2, kSkip = 3 };
constexpr UINT kFlag2MbPages = 2;
constexpr uint64_t kSmallPage = 64 * 1024;
using ScatterFn = BOOL(WINAPI*)(PVOID*, ULONG_PTR, PULONG_PTR);
using QueryFn = int (*)(uint64_t, bx_xmem_region_info_t*);
struct Xmem {
ScatterFn scatter = nullptr;
QueryFn query = nullptr;
Xmem() {
if (HMODULE m = GetModuleHandleA("xmem.dll")) {
scatter = reinterpret_cast<ScatterFn>(reinterpret_cast<void*>(GetProcAddress(m, "XMemMapPhysicalPagesScatter")));
query = reinterpret_cast<QueryFn>(reinterpret_cast<void*>(GetProcAddress(m, "bx_xmem_query_region")));
}
}
};
const Xmem& xmem() {
static const Xmem api;
return api;
}
void log_mapping(const char* what, const char* detail) {
static LONG logged = 0;
if (InterlockedIncrement(&logged) <= 64) bx_log_emit(BX_LOG_INFO, "d3d12_xs", what, detail);
}
void log_failure(const char* detail) {
static LONG logged = 0;
if (InterlockedIncrement(&logged) <= 32) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "page_mapping_failed", detail);
}
// Collects destination slots and physical pages (0: unmap), then maps them in one scatter call.
class Mapper {
public:
Mapper(uint64_t pool, UINT pool_pages, UINT flags)
: pool_(pool), pool_pages_(pool_pages), page_(flags & kFlag2MbPages ? 32 * kSmallPage : kSmallPage) {}
// One destination page `dst_page` (index from `dst`) showing pool page `pool_page`, or none.
bool add(uint64_t dst, uint64_t dst_page, bool null_page, UINT pool_page) {
for (uint64_t sub = 0; sub < page_ / kSmallPage; ++sub) {
ULONG_PTR tag = 0;
if (!null_page) {
if (pool_page >= pool_pages_) return fail("pool page index past the pool", dst, pool_page);
bx_xmem_region_info_t info{};
const uint64_t src = pool_ + uint64_t(pool_page) * page_ + sub * kSmallPage;
if (!xmem().query || !xmem().query(src, &info) || !info.physical_tag) {
return fail("pool address has no xmem physical page", dst, pool_page);
}
tag = static_cast<ULONG_PTR>(info.physical_tag);
}
slots_.push_back(reinterpret_cast<PVOID>(static_cast<uintptr_t>(dst + dst_page * page_ + sub * kSmallPage)));
tags_.push_back(tag);
}
return true;
}
bool add_range(uint64_t dst, uint64_t& cursor, const PageMappingRange& range) {
switch (range.RangeType) {
case kSkip:
cursor += range.PageCount;
return true;
case kIncrementing:
case kConstant:
case kNullPages:
for (UINT i = 0; i < range.PageCount; ++i) {
const UINT pool_page = range.RangeType == kIncrementing ? range.StartPageIndexInPool + i
: range.StartPageIndexInPool;
if (!add(dst, cursor + i, range.RangeType == kNullPages, pool_page)) return false;
}
cursor += range.PageCount;
return true;
default:
return fail("unknown range type", dst, range.RangeType);
}
}
HRESULT commit() {
if (slots_.empty()) return S_OK;
if (!xmem().scatter) {
log_failure("xmem.dll!XMemMapPhysicalPagesScatter not available");
return E_NOTIMPL;
}
if (!xmem().scatter(slots_.data(), slots_.size(), tags_.data())) {
char detail[160];
std::snprintf(detail, sizeof(detail), "XMemMapPhysicalPagesScatter of %zu pages at %p failed error=%lu",
slots_.size(), slots_.front(), static_cast<unsigned long>(GetLastError()));
log_failure(detail);
return E_INVALIDARG;
}
return S_OK;
}
size_t pages() const { return slots_.size(); }
private:
bool fail(const char* why, uint64_t dst, UINT value) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s (destination 0x%llx, value %u)", why,
static_cast<unsigned long long>(dst), value);
log_failure(detail);
return false;
}
uint64_t pool_;
UINT pool_pages_;
uint64_t page_;
std::vector<PVOID> slots_;
std::vector<ULONG_PTR> tags_;
};
HRESULT map_batches(UINT count, const PageMappingBatch* batches, uint64_t pool, UINT pool_pages, UINT flags,
const char* method) {
if (count && !batches) return E_INVALIDARG;
Mapper mapper(pool, pool_pages, flags);
for (UINT b = 0; b < count; ++b) {
if (batches[b].RangeCount && !batches[b].pRanges) return E_INVALIDARG;
uint64_t cursor = 0;
for (UINT r = 0; r < batches[b].RangeCount; ++r) {
if (!mapper.add_range(batches[b].DestinationAddress, cursor, batches[b].pRanges[r])) return E_INVALIDARG;
}
}
const HRESULT hr = mapper.commit();
char detail[192];
std::snprintf(detail, sizeof(detail), "%s batches=%u first_destination=0x%llx pool=0x%llx pool_pages=%u flags=0x%x pages=%zu hr=0x%08lx",
method, count, count ? static_cast<unsigned long long>(batches[0].DestinationAddress) : 0ull,
static_cast<unsigned long long>(pool), pool_pages, flags, mapper.pages(), static_cast<unsigned long>(hr));
log_mapping("page_mappings", detail);
return hr;
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void*, UINT batch_count, const void* batches,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsBatchX");
return map_batches(batch_count, static_cast<const PageMappingBatch*>(batches), pool, pool_pages, flags,
"CopyPageMappingsBatchX");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT range_count, const void* ranges,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsX");
const PageMappingBatch batch{destination, range_count, static_cast<const PageMappingRange*>(ranges)};
return map_batches(1, &batch, pool, pool_pages, flags, "CopyPageMappingsX");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT page_count, UINT flags) {
BX_D3D_TRACE("XboxCommandQueue", "ClearPageMappingsX");
const PageMappingRange range{kNullPages, 0, page_count};
const PageMappingBatch batch{destination, 1, &range};
return map_batches(1, &batch, 0, 0, flags, "ClearPageMappingsX");
}
-487
View File
@@ -1,487 +0,0 @@
/*
* Pipeline states on the Xbox-layout device (ADR 0009), and the opt-in null-render mode.
*
* Every pipeline creation goes through the M2 shader format gate (shader_gate.h, ADR 0008), so
* each stage writes a `shader_gate` record, and the title's root signature is unwrapped before
* the description reaches the host. The Xbox *X variants take extended descriptions
* (D3D12XBOX_EXTENDED_*_PIPELINE_STATE_DESC) that have no host equivalent; their count is logged
* and the base description is created.
*
* Null-render mode (BX_NULL_RENDER=1, off by default): a pipeline the host refuses, for example
* one whose shaders are console-only, becomes a BetterXen null pipeline instead of a failure.
* Binding it is recorded per command list, and draws and dispatches recorded while it is bound
* are skipped. Everything else still runs, so fences complete and frames present, with the
* skipped work missing from them. Each refusal and each skip is logged: the mode exists to see
* how far a title gets, not to hide what it cannot run.
*/
#include "xbox_facade.h"
#include "proxy.h"
#include "shader_gate.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <vector>
#include <mutex>
namespace {
bool null_render_enabled() {
static const bool enabled = [] {
char value[8] = {};
const DWORD n = GetEnvironmentVariableA("BX_NULL_RENDER", value, sizeof(value));
const bool on = n > 0 && n < sizeof(value) && value[0] == '1';
if (on) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render", "enabled: refused pipelines become null pipelines");
return on;
}();
return enabled;
}
/* A pipeline-state object with no host pipeline behind it. */
class NullPipelineState final : public ID3D12PipelineState {
public:
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12PipelineState)) {
*ppv = static_cast<ID3D12PipelineState*>(this);
AddRef();
return S_OK;
}
*ppv = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
ULONG STDMETHODCALLTYPE Release() override {
const ULONG left = --refs_;
if (!left) {
device_->Release();
delete this;
}
return left;
}
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT* size, void*) override {
if (size) *size = 0;
return DXGI_ERROR_NOT_FOUND;
}
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; }
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; }
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; }
HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override { return device_->QueryInterface(riid, ppv); }
HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override {
if (blob) *blob = nullptr;
return E_NOTIMPL;
}
private:
ID3D12Device* device_;
std::atomic<ULONG> refs_{1};
};
std::mutex g_lock;
NullPipelineState** g_nulls = nullptr; // live null pipelines, so they can be recognised
size_t g_null_count = 0;
size_t g_null_capacity = 0;
ID3D12GraphicsCommandList** g_lists = nullptr; // lists whose bound pipeline is a null pipeline
size_t g_list_count = 0;
size_t g_list_capacity = 0;
template <typename T>
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
if (count == capacity) {
const size_t grown_capacity = capacity ? capacity * 2 : 16;
auto** grown = new (std::nothrow) T*[grown_capacity];
if (!grown) return false;
for (size_t i = 0; i < count; ++i) grown[i] = items[i];
delete[] items;
items = grown;
capacity = grown_capacity;
}
items[count++] = item;
return true;
}
template <typename T>
bool erase(T** items, size_t& count, const T* item) {
for (size_t i = 0; i < count; ++i) {
if (items[i] == item) {
items[i] = items[--count];
return true;
}
}
return false;
}
template <typename T>
bool contains(T* const* items, size_t count, const T* item) {
for (size_t i = 0; i < count; ++i) {
if (items[i] == item) return true;
}
return false;
}
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
std::lock_guard<std::mutex> guard(g_lock);
*is_null = host && contains(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
return *is_null ? nullptr : host;
}
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
std::lock_guard<std::mutex> guard(g_lock);
const bool present = contains(g_lists, g_list_count, list);
if (null_bound && !present) push(g_lists, g_list_count, g_list_capacity, list);
if (!null_bound && present) erase(g_lists, g_list_count, list);
}
bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
{
std::lock_guard<std::mutex> guard(g_lock);
if (!contains(g_lists, g_list_count, list)) return false;
}
static std::atomic<uint64_t> skipped{0};
const uint64_t n = ++skipped;
if ((n & (n - 1)) == 0) { // 1, 2, 4, 8, ...: enough to follow without flooding the log
char detail[96];
std::snprintf(detail, sizeof(detail), "%s with a null pipeline bound; total skipped=%llu", what,
static_cast<unsigned long long>(n));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render_skip", detail);
}
return true;
}
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx%s", kind, static_cast<unsigned long>(hr),
null_render_enabled() ? "; null pipeline returned" : "");
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
if (!null_render_enabled() || !ppv) return hr;
auto* null_pso = new (std::nothrow) NullPipelineState(device);
if (!null_pso) return E_OUTOFMEMORY;
{
std::lock_guard<std::mutex> guard(g_lock);
if (!push(g_nulls, g_null_count, g_null_capacity, null_pso)) {
null_pso->Release();
return E_OUTOFMEMORY;
}
}
*ppv = static_cast<ID3D12PipelineState*>(null_pso);
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
void log_extended(const char* kind, UINT count) {
if (!count) return;
char detail[96];
std::snprintf(detail, sizeof(detail), "%s: %u extended description(s) not applied", kind, count);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_extended_desc", detail);
}
HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device>(self);
BxShaderGate gate;
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
HRESULT hr = gate.admit("compute", "CS", desc->CS, admitted.CS);
if (SUCCEEDED(hr)) hr = device->CreateComputePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device>(self);
BxShaderGate gate;
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
HRESULT hr = gate.admit("graphics", "VS", desc->VS, admitted.VS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "PS", desc->PS, admitted.PS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
auto* device = bx_xbox_host<ID3D12Device2>(self);
std::vector<uint8_t> stream;
std::vector<size_t> offsets;
std::vector<const char*> names;
size_t root_offset = SIZE_MAX;
HRESULT hr = copy_stream(*desc, stream, offsets, names, &root_offset);
if (FAILED(hr)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "stream of %llu bytes not parsed (unknown or console subobject?)",
static_cast<unsigned long long>(desc->SizeInBytes));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pso_stream", detail);
return refused(device, hr, "stream", riid, ppv);
}
if (root_offset != SIZE_MAX) {
ID3D12RootSignature* root = nullptr;
std::memcpy(&root, &stream[root_offset], sizeof(root));
root = bx_xbox_unwrap_as(root);
std::memcpy(&stream[root_offset], &root, sizeof(root));
}
BxShaderGate gate;
for (size_t i = 0; i < offsets.size() && SUCCEEDED(hr); ++i) {
D3D12_SHADER_BYTECODE in{};
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
D3D12_SHADER_BYTECODE out = in;
hr = gate.admit("stream", names[i], in, out);
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
}
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePipelineState");
return create_stream(self, desc, riid, ppv);
}
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title) {
bool is_null = false;
host_pipeline(title, &is_null);
return is_null;
}
void bx_xbox_pipeline_forget(IUnknown* host) {
std::lock_guard<std::mutex> guard(g_lock);
erase(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
}
void bx_xbox_list_forget(IUnknown* host) {
std::lock_guard<std::mutex> guard(g_lock);
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
}
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
return create_compute(self, desc, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineState");
return create_graphics(self, desc, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineStateX");
log_extended("CreateComputePipelineStateX", extended_count);
return create_compute(self, desc, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineStateX");
log_extended("CreateGraphicsPipelineStateX", extended_count);
return create_graphics(self, desc, riid, ppv);
}
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
if (!is_null) list->SetPipelineState(host);
}
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
bx_xbox_gpu_writes_reset(list);
return list->Reset(bx_xbox_unwrap_as(allocator), host);
}
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
}
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
INT base_vertex, UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawIndexedInstanced")) {
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
}
}
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
BX_D3D_TRACE("XboxGraphicsCommandList", "Dispatch");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "Dispatch")) list->Dispatch(x, y, z);
}
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
ID3D12Resource* arguments, UINT64 arguments_offset,
ID3D12Resource* count, UINT64 count_offset) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ExecuteIndirect");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (list_skips(list, "ExecuteIndirect")) return;
list->ExecuteIndirect(bx_xbox_unwrap_as(signature), max_commands, bx_xbox_unwrap_as(arguments), arguments_offset,
bx_xbox_unwrap_as(count), count_offset);
}
} // extern "C"
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
ID3D12RootSignature* root, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommandSignature");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
// D3D12XBOX_INDIRECT_ARGUMENT_TYPE_* values start at 100 and have no PC equivalent, except
// DISPATCH_SINGLE / DISPATCH_L2 (105): a dispatch whose arguments are D3D12_DISPATCH_ARGUMENTS
// and whose D3D12XBOX_DISPATCH_FLAGS are a direct parameter (authorized GDK documentation), so
// the host gets D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. The flags are cache hints and are dropped.
constexpr int kFirstXboxArgument = 100;
constexpr int kXboxDispatchSingle = 105;
constexpr UINT kMaxArguments = 32;
D3D12_INDIRECT_ARGUMENT_DESC host_args[kMaxArguments] = {};
char types[160] = {};
size_t used = 0;
bool console_only = desc->NumArgumentDescs > kMaxArguments;
for (UINT i = 0; i < desc->NumArgumentDescs && i < kMaxArguments && desc->pArgumentDescs; ++i) {
const int type = static_cast<int>(desc->pArgumentDescs[i].Type);
host_args[i] = desc->pArgumentDescs[i];
if (type == kXboxDispatchSingle) {
host_args[i] = {};
host_args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
} else if (type >= kFirstXboxArgument) {
console_only = true;
}
if (used < sizeof(types) - 8) used += std::snprintf(types + used, sizeof(types) - used, "%s%d", i ? "," : "", type);
}
D3D12_COMMAND_SIGNATURE_DESC host_desc = *desc;
host_desc.pArgumentDescs = host_args;
auto* device = bx_xbox_host<ID3D12Device>(self);
HRESULT hr = console_only ? E_NOTIMPL
: device->CreateCommandSignature(&host_desc, bx_xbox_unwrap_as(root), riid, ppv);
char detail[256];
std::snprintf(detail, sizeof(detail), "stride=%u args=[%s] root_signature=%d hr=0x%08lx%s", desc->ByteStride, types,
root ? 1 : 0, static_cast<unsigned long>(hr), console_only ? " (console argument types)" : "");
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "command_signature", detail);
return SUCCEEDED(hr) ? bx_xbox_wrap_result(hr, riid, ppv) : hr;
}
namespace {
void log_once(std::atomic<bool>& flag, const char* event, const char* detail) {
if (!flag.exchange(true)) bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
UINT flags) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ResetX");
static std::atomic<bool> logged{false};
if (flags) log_once(logged, "reset_x_flags", "D3D12XBOX_COMMAND_LIST_RESET_FLAGS have no host meaning; ignored");
return bx_xbox_list_reset(self, allocator, pso);
}
// Console cache synchronisation points. The closest host D3D12 operation is a global UAV
// barrier: all prior UAV work completes before later work starts.
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT, UINT, D3D12_GPU_VIRTUAL_ADDRESS, SIZE_T) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SyncTopOfPipeX/SyncBottomOfPipeX");
static std::atomic<bool> logged{false};
log_once(logged, "sync_x", "SyncTopOfPipeX/SyncBottomOfPipeX recorded as a global UAV barrier");
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(1, &barrier);
}
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, UINT64) {
BX_D3D_TRACE("XboxCommandAllocator", "SetAllocatorCallbackX");
static std::atomic<bool> logged{false};
if (callback) {
log_once(logged, "allocator_callback_x",
"SetAllocatorCallbackX accepted; host command lists do not allocate from title memory, so it is never called");
}
}
} // extern "C"
/*
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
*/
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
}
/*
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
* from a host pipeline needs its creation description, which this layer does not keep yet: that
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
*/
namespace {
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
const bool from_null = bx_xbox_pipeline_is_null(source);
if (!from_null) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_derived",
"deriving from a host pipeline is not implemented (its creation description is not kept)");
}
}
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
return derived(self, source, riid, ppv, "derived graphics");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
return derived(self, source, riid, ppv, "derived compute");
}
-436
View File
@@ -1,436 +0,0 @@
/*
* Resources placed at a title-chosen GPU virtual address (ADR 0009, "translation by copy").
*
* On the console a title maps its own physical pages at an address and places resources there
* with ID3D12Device::CreatePlacedResourceX / CreatePlacedResourceX1; CPU and GPU see the same
* memory. D3DMetal cannot create a resource over existing memory (the existing-memory imports
* measured for #473 return E_NOTIMPL), so each such resource gets a shadow resource on the host:
*
* - a buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's
* memory when it is created;
* - a texture gets a committed texture whose contents are not filled (logged); texture
* contents need the console tiling translation (xg_xs) first.
*
* The title's address and the shadow are recorded, and the resource reports the title's address
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
* title addresses in GPU calls, are not done yet; both are logged when reached.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
namespace {
struct Shadow {
ID3D12Resource* host; // owned by the Xbox object, or (implicit shadows) by this table
uint64_t title_va;
uint64_t size;
bool buffer;
D3D12_RESOURCE_DESC desc;
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
int mapped = 0; // outstanding Map calls on title memory (buffers)
};
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
if (!s.buffer || end <= begin || end > s.size) return false;
void* mapped = nullptr;
const D3D12_RANGE none{0, 0};
if (FAILED(s.host->Map(0, to_host ? &none : nullptr, &mapped)) || !mapped) return false;
auto* host = static_cast<uint8_t*>(mapped) + begin;
auto* title = reinterpret_cast<uint8_t*>(s.title_va) + begin;
if (to_host) std::memcpy(host, title, static_cast<size_t>(end - begin));
else std::memcpy(title, host, static_cast<size_t>(end - begin));
const D3D12_RANGE written{static_cast<SIZE_T>(begin), static_cast<SIZE_T>(end)};
s.host->Unmap(0, to_host ? &written : &none);
return true;
}
std::mutex g_lock;
Shadow* g_shadows = nullptr;
size_t g_count = 0;
size_t g_capacity = 0;
bool remember(const Shadow& shadow) {
std::lock_guard<std::mutex> guard(g_lock);
if (g_count == g_capacity) {
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
auto* grown = new (std::nothrow) Shadow[capacity];
if (!grown) return false;
if (g_count) std::memcpy(grown, g_shadows, g_count * sizeof(Shadow));
delete[] g_shadows;
g_shadows = grown;
g_capacity = capacity;
}
g_shadows[g_count++] = shadow;
return true;
}
bool readable(const void* p, uint64_t size) {
auto cursor = reinterpret_cast<uintptr_t>(p);
const uintptr_t end = cursor + size;
while (cursor < end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(cursor), &region, sizeof(region)) || region.State != MEM_COMMIT
|| (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
return false;
}
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
return true;
}
HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, const char* method,
ID3D12Resource** out) {
*out = nullptr;
const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER;
D3D12_HEAP_PROPERTIES heap{};
if (buffer) {
heap.Type = D3D12_HEAP_TYPE_CUSTOM;
heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
} else {
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
}
D3D12_RESOURCE_DESC host_desc = desc;
// Console tiling layouts and D3D12XBOX_RESOURCE_FLAG_* bits have no PC meaning.
constexpr UINT kPcResourceFlags = 0x1FF;
host_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN;
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc.Flags & kPcResourceFlags);
ID3D12Resource* resource = nullptr;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
char detail[224];
std::snprintf(detail, sizeof(detail), "%s title_va=0x%llx dim=%d width=%llu height=%u format=%d hr=0x%08lx",
method, static_cast<unsigned long long>(title_va), static_cast<int>(desc.Dimension),
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format),
static_cast<unsigned long>(hr));
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", detail);
if (FAILED(hr) || !resource) return FAILED(hr) ? hr : E_FAIL;
const auto* title = reinterpret_cast<const void*>(title_va);
if (buffer) {
void* mapped = nullptr;
if (SUCCEEDED(resource->Map(0, nullptr, &mapped)) && mapped) {
if (readable(title, desc.Width)) {
std::memcpy(mapped, title, static_cast<size_t>(desc.Width));
} else {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "title memory not readable; shadow left zeroed");
}
resource->Unmap(0, nullptr);
}
} else {
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
}
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
resource->Release();
return E_OUTOFMEMORY;
}
*out = resource;
return S_OK;
}
HRESULT create_shadow(void* self, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** ppv,
const char* method) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
ID3D12Resource* resource = nullptr;
const HRESULT hr = make_shadow(bx_xbox_host<ID3D12Device>(self), title_va, desc, method, &resource);
if (FAILED(hr)) return hr;
*ppv = resource;
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
return a.Dimension == b.Dimension && a.Width == b.Width && a.Height == b.Height &&
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
}
// A view of placed memory with no resource object: reuse the shadow made for the same address
// and shape, or make one. These shadows live for the rest of the process (logged).
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
}
}
ID3D12Resource* resource = nullptr;
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
}
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
constexpr size_t kPcViewDescBytes = 40;
static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == kPcViewDescBytes, "PC SRV description size");
static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == kPcViewDescBytes, "PC UAV description size");
uint64_t view_location(const void* xbox_desc) {
uint64_t va = 0;
std::memcpy(&va, static_cast<const char*>(xbox_desc) + kPcViewDescBytes, sizeof(va));
return va;
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX");
if (!desc || !location) return E_INVALIDARG;
return create_shadow(self, location, *desc, riid, ppv, "CreatePlacedResourceX");
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC1* desc1, UINT,
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX1");
if (!desc1 || !location) return E_INVALIDARG;
// D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC followed by SamplerFeedbackMipRegion.
D3D12_RESOURCE_DESC desc{};
std::memcpy(&desc, desc1, sizeof(desc));
return create_shadow(self, location, desc, riid, ppv, "CreatePlacedResourceX1");
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawShaderResourceViewX");
if (!resource_desc || !xbox_desc) return;
auto* device = bx_xbox_host<ID3D12Device>(self);
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
if (!resource) return;
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawUnorderedAccessViewX");
if (!resource_desc || !xbox_desc) return;
auto* device = bx_xbox_host<ID3D12Device>(self);
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
if (!resource) return;
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
device->CreateUnorderedAccessView(resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedShaderResourceViewX");
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr,
bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedUnorderedAccessViewX");
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as(resource), nullptr,
xbox_desc ? &pc : nullptr, bx_xbox_host_cpu_handle(dest));
}
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
if (!title) return title;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const Shadow& s = g_shadows[i];
if (title >= s.title_va && title < s.title_va + s.size) return s.host->GetGPUVirtualAddress() + (title - s.title_va);
}
return title; // not a title address this layer knows: a host address already, or untranslated
}
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes) {
return remember({host, title_va, size, host->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, host->GetDesc(),
attributes});
}
void bx_xbox_placed_forget(IUnknown* host) {
Shadow gone{};
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (static_cast<IUnknown*>(g_shadows[i].host) == host) {
gone = g_shadows[i];
g_shadows[i] = g_shadows[--g_count];
break;
}
}
}
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
}
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self) {
BX_D3D_TRACE("XboxResource", "GetGPUVirtualAddress");
auto* host = bx_xbox_host<ID3D12Resource>(self);
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].host == host) return g_shadows[i].title_va;
}
}
return host->GetGPUVirtualAddress();
}
} // extern "C"
/*
* Page pools (RegisterPagePoolX / UnregisterPagePoolX, authorized GDK documentation): a title
* registers a 64 KB-aligned, fully mapped range of its graphics memory as the source of later
* CopyPageMappingsX calls. Registration is validated and recorded; the handle is the record.
* CopyPageMappingsX itself (a queue method) is not implemented yet and stays a logged stub.
*/
namespace {
struct PagePool {
uint64_t address;
UINT pages;
PagePool* next;
};
PagePool* g_pools = nullptr; // guarded by g_lock
bool fully_mapped(uint64_t address, uint64_t size) {
auto cursor = static_cast<uintptr_t>(address);
const uintptr_t end = cursor + static_cast<uintptr_t>(size);
while (cursor < end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(cursor), &region, sizeof(region)) || region.State != MEM_COMMIT) {
return false;
}
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
return true;
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void*, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
HANDLE* handle) {
BX_D3D_TRACE("XboxDevice", "RegisterPagePoolX");
constexpr uint64_t kPage = 64 * 1024;
const bool valid = handle && pages && address && (address % kPage) == 0 && fully_mapped(address, pages * kPage);
char detail[160];
std::snprintf(detail, sizeof(detail), "address=0x%llx pages=%u %s", static_cast<unsigned long long>(address), pages,
valid ? "registered" : "rejected (unaligned, empty or not fully mapped)");
bx_log_emit(valid ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "page_pool", detail);
if (!valid) return E_INVALIDARG;
auto* pool = new (std::nothrow) PagePool{address, pages, nullptr};
if (!pool) return E_OUTOFMEMORY;
{
std::lock_guard<std::mutex> guard(g_lock);
pool->next = g_pools;
g_pools = pool;
}
*handle = pool;
return S_OK;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void*, HANDLE handle) {
BX_D3D_TRACE("XboxDevice", "UnregisterPagePoolX");
std::lock_guard<std::mutex> guard(g_lock);
for (PagePool** link = &g_pools; *link; link = &(*link)->next) {
if (*link == handle) {
PagePool* gone = *link;
*link = gone->next;
delete gone;
return S_OK;
}
}
return E_INVALIDARG;
}
} // extern "C"
/*
* Map on a resource that has title-visible memory (placed at a title address, or committed with
* XMemAlloc memory) returns that memory, as on the console, where CPU and GPU share it. Other
* resources map their host resource. Writes through the title pointer reach the host resource
* only where this layer copies them (buffers at creation; texture contents are not copied yet,
* logged at creation).
*/
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data) {
BX_D3D_TRACE("XboxResource", "Map");
auto* host = bx_xbox_host<ID3D12Resource>(self);
uint64_t title_va = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
Shadow& s = g_shadows[i];
if (s.host != host) continue;
title_va = s.title_va;
// Make GPU results visible: refresh the read range of title memory from the host.
const uint64_t begin = read ? read->Begin : 0, end = read ? read->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
++s.mapped;
}
}
if (!title_va) {
const HRESULT hr = host->Map(subresource, read, data);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxResource", "Map", hr);
return hr;
}
if (subresource != 0) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_map",
"Map of a non-zero subresource of title memory returns the resource base");
}
}
if (data) *data = reinterpret_cast<void*>(title_va);
return S_OK;
}
extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written) {
BX_D3D_TRACE("XboxResource", "Unmap");
auto* host = bx_xbox_host<ID3D12Resource>(self);
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
Shadow& s = g_shadows[i];
if (s.host != host) continue;
// Hand the CPU's writes to the host resource (a null range means all of it).
const uint64_t begin = written ? written->Begin : 0, end = written ? written->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
if (s.mapped > 0) --s.mapped;
return;
}
}
host->Unmap(subresource, written);
}
/*
* Before a submission, buffers the title keeps mapped (persistent maps) are copied from title
* memory to their host resources, up to 16 MB each; larger ones are logged once and not copied.
*/
void bx_xbox_sync_mapped_buffers() {
constexpr uint64_t kLimit = 16ull << 20;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const Shadow& s = g_shadows[i];
if (!s.mapped || !s.buffer) continue;
if (s.size > kLimit) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 4) {
char detail[128];
std::snprintf(detail, sizeof(detail), "persistently mapped buffer of %llu bytes not copied to the host before submit",
static_cast<unsigned long long>(s.size));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_sync", detail);
}
continue;
}
copy_buffer(s, true, 0, s.size);
}
}
-350
View File
@@ -1,350 +0,0 @@
/*
* 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;
}
+3 -7
View File
@@ -513,13 +513,10 @@ 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 (and, when
* `root_offset` is given, the root-signature payload, or SIZE_MAX without one). An unknown tag,
* touching memory it does not own, and records where each shader payload sits. An unknown tag,
* or a payload that overruns SizeInBytes, is rejected. */
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
size_t* root_offset) {
if (root_offset) *root_offset = SIZE_MAX;
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names) {
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);
@@ -546,7 +543,6 @@ 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, &copy[payload], sizeof(code));
@@ -579,7 +575,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, nullptr);
const HRESULT copied = copy_stream(*desc, stream, offsets, names);
{
char detail[96];
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=%d",
-7
View File
@@ -19,7 +19,6 @@
#include <atomic>
#include <cstdint>
#include <vector>
#include "bx_config.h"
#include "bx_log.h"
@@ -118,9 +117,3 @@ 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);
-7
View File
@@ -296,13 +296,6 @@ 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;
}
+1 -2
View File
@@ -24,8 +24,7 @@ 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, and for a container whose
* DXIL part the bridge cannot classify (a header-only program). Copies live until this
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge. Copies live until this
* object is destroyed.
*/
HRESULT admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
-384
View File
@@ -1,384 +0,0 @@
#!/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()
-316
View File
@@ -1,316 +0,0 @@
#include "xbox_facade.h"
#include <cstdio>
#include <cstring>
#include <mutex>
/*
* ADR 0009: Xbox-layout objects over the PC proxies. See xbox_facade.h for the layout and
* xbox_tables_generated.cpp (tools/gen_xbox_tables.py) for the slot order.
*/
namespace {
constexpr uint8_t kOutOfLineCommon = 0x1; // Xbox OutOfLineFlags_Common
struct Entry {
IUnknown* host;
const BxXboxIface* iface;
BxXboxObject* object;
};
std::mutex g_lock;
Entry* g_entries = nullptr;
size_t g_count = 0;
size_t g_capacity = 0;
bool same_iid(REFIID a, REFIID b) {
return std::memcmp(&a, &b, sizeof(IID)) == 0;
}
bool answers(const BxXboxIface* iface, REFIID riid) {
for (size_t i = 0; i < iface->iid_count; ++i) {
if (same_iid(iface->iids[i], riid)) return true;
}
return false;
}
const BxXboxIface* iface_of_object(const void* p) {
if (!p) return nullptr;
const void* table = *static_cast<const void* const*>(p);
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
if (bx_xbox_ifaces[i]->table == table) return bx_xbox_ifaces[i];
}
return nullptr;
}
void log_iid(const char* event, const char* what, REFIID riid, bx_log_level_t level = BX_LOG_WARN) {
char guid[40];
bx_format_guid(riid, guid, sizeof(guid));
char detail[160];
std::snprintf(detail, sizeof(detail), "%s iid=%s", what, guid);
bx_log_emit(level, "d3d12_xs", event, detail);
}
BxXboxObject* find_locked(IUnknown* host, const BxXboxIface* iface) {
for (size_t i = 0; i < g_count; ++i) {
if (g_entries[i].host == host && g_entries[i].iface == iface) return g_entries[i].object;
}
return nullptr;
}
bool insert_locked(Entry entry) {
if (g_count == g_capacity) {
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
auto* grown = new (std::nothrow) Entry[capacity];
if (!grown) return false;
if (g_count) std::memcpy(grown, g_entries, g_count * sizeof(Entry));
delete[] g_entries;
g_entries = grown;
g_capacity = capacity;
}
g_entries[g_count++] = entry;
return true;
}
void erase_locked(BxXboxObject* object) {
for (size_t i = 0; i < g_count; ++i) {
if (g_entries[i].object == object) {
g_entries[i] = g_entries[--g_count];
return;
}
}
}
} // namespace
const BxXboxIface* bx_xbox_iface_for(REFIID riid) {
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
if (answers(bx_xbox_ifaces[i], riid)) return bx_xbox_ifaces[i];
}
return nullptr;
}
void* bx_xbox_wrap(REFIID riid, void* raw, HRESULT* failure) {
if (failure) *failure = E_OUTOFMEMORY;
if (!raw) return nullptr;
auto* unknown = static_cast<IUnknown*>(raw);
const BxXboxIface* iface = bx_xbox_iface_for(riid);
if (!iface) {
log_iid("xbox_unwrapped", "no Xbox table answers this interface; returning the PC object", riid);
return raw;
}
void* typed = nullptr;
if (FAILED(unknown->QueryInterface(*iface->host_iid, &typed)) || !typed) {
// The Xbox table forwards to an interface this host object lacks. Handing back the PC
// object would let a title call Xbox slot numbers on a PC table, so this fails instead.
log_iid("xbox_wrap_refused", iface->name, *iface->host_iid, BX_LOG_ERROR);
unknown->Release();
if (failure) *failure = E_NOINTERFACE;
return nullptr;
}
unknown->Release();
auto* host = static_cast<IUnknown*>(typed);
std::lock_guard<std::mutex> guard(g_lock);
if (BxXboxObject* existing = find_locked(host, iface)) {
ULONG refs = existing->refs.load();
while (refs != 0 && !existing->refs.compare_exchange_weak(refs, refs + 1)) {
}
if (refs != 0) {
existing->xbox_ref_count = refs + 1;
host->Release();
return existing;
}
}
auto* object = new (std::nothrow) BxXboxObject{};
if (!object) {
host->Release();
return nullptr;
}
object->function_table = iface->table;
object->xbox_ref_count = 1;
if (iface == &bx_xbox_Device) {
object->xbox_fields[kBxXboxDeviceOutOfLineOffset - offsetof(BxXboxObject, xbox_fields)] = kOutOfLineCommon;
}
object->host = host;
object->iface = iface;
object->refs.store(1);
if (!insert_locked({host, iface, object})) {
host->Release();
delete object;
return nullptr;
}
return object;
}
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv) {
if (SUCCEEDED(hr) && ppv && *ppv) {
HRESULT failure = E_OUTOFMEMORY;
void* wrapped = bx_xbox_wrap(riid, *ppv, &failure);
if (!wrapped) {
*ppv = nullptr;
return failure;
}
*ppv = wrapped;
}
return hr;
}
IUnknown* bx_xbox_unwrap(const void* p) {
if (iface_of_object(p)) return static_cast<const BxXboxObject*>(p)->host;
return static_cast<IUnknown*>(const_cast<void*>(p));
}
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s::%s hr=0x%08lx", iface, method, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "host_call_failed", detail);
}
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv) {
auto* object = static_cast<BxXboxObject*>(self);
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (same_iid(riid, IID_BxProxyHost)) {
*ppv = object->host; // by contract, no reference (see bx_unwrap_raw)
return S_OK;
}
if (same_iid(riid, __uuidof(IUnknown)) || answers(object->iface, riid)) {
bx_xbox_add_ref(self);
*ppv = self;
return S_OK;
}
void* raw = nullptr;
HRESULT hr = object->host->QueryInterface(riid, &raw);
if (FAILED(hr) || !raw) return hr;
if (bx_xbox_iface_for(riid)) {
HRESULT failure = E_OUTOFMEMORY;
*ppv = bx_xbox_wrap(riid, raw, &failure);
return *ppv ? S_OK : failure;
}
log_iid("xbox_qi_unwrapped", object->iface->name, riid);
*ppv = raw;
return S_OK;
}
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self) {
auto* object = static_cast<BxXboxObject*>(self);
const ULONG refs = object->refs.fetch_add(1) + 1;
object->xbox_ref_count = refs;
return refs;
}
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self) {
auto* object = static_cast<BxXboxObject*>(self);
std::unique_lock<std::mutex> guard(g_lock);
const ULONG refs = object->refs.fetch_sub(1) - 1;
object->xbox_ref_count = refs;
if (refs != 0) return refs;
erase_locked(object);
guard.unlock();
if (object->iface == &bx_xbox_Resource) bx_xbox_placed_forget(object->host);
if (object->iface == &bx_xbox_DescriptorHeap) bx_xbox_descriptor_heap_forget(object->host);
if (object->iface == &bx_xbox_Fence) bx_xbox_fence_forget(object->host);
if (object->iface == &bx_xbox_PipelineState) bx_xbox_pipeline_forget(object->host);
if (object->iface == &bx_xbox_GraphicsCommandList) {
bx_xbox_list_forget(object->host);
bx_xbox_gpu_writes_reset(object->host);
}
object->host->Release();
delete object;
return 0;
}
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv) {
if (!ppv) return;
*ppv = nullptr;
auto* child = bx_xbox_host<ID3D12DeviceChild>(self);
void* device = nullptr;
if (SUCCEEDED(child->GetDevice(riid, &device)) && device) *ppv = bx_xbox_wrap(riid, device);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommandQueueX");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
D3D12_COMMAND_QUEUE_DESC pc{};
pc.Type = desc->Type;
pc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
pc.Flags = desc->Flags;
char detail[160];
std::snprintf(detail, sizeof(detail), "type=%d flags=0x%x engine_or_pipe=%u queue=%u (indices not used by the host)",
static_cast<int>(desc->Type), static_cast<unsigned>(desc->Flags), desc->EngineOrPipeIndex,
desc->QueueIndex);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandQueueX", detail);
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandQueue(&pc, riid, ppv);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
ID3D12CommandAllocator* allocator,
ID3D12PipelineState* initial_state, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommandListX");
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
char detail[160];
std::snprintf(detail, sizeof(detail), "type=%d xbox_flags=0x%x node_mask=0x%x barrier_batch=%u (flags and batch not used by the host)",
static_cast<int>(desc->Type), desc->Flags, desc->NodeMask, desc->ResourceBarrierBatchSize);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandListX", detail);
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandList(
desc->NodeMask, desc->Type, bx_xbox_unwrap_as(allocator),
bx_xbox_pipeline_is_null(initial_state) ? nullptr : bx_xbox_unwrap_as(initial_state), riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateCommandListX", hr);
return bx_xbox_wrap_result(hr, riid, ppv);
}
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers) {
BX_D3D_TRACE("XboxGraphicsCommandList", "ResourceBarrier");
if (!barriers || count == 0) return 0;
constexpr UINT kInline = 32;
D3D12_RESOURCE_BARRIER inline_copy[kInline];
D3D12_RESOURCE_BARRIER* copy = count <= kInline ? inline_copy : new (std::nothrow) D3D12_RESOURCE_BARRIER[count];
if (!copy) return 0;
for (UINT i = 0; i < count; ++i) {
copy[i] = barriers[i];
switch (copy[i].Type) {
case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION:
copy[i].Transition.pResource = bx_xbox_unwrap_as(copy[i].Transition.pResource);
break;
case D3D12_RESOURCE_BARRIER_TYPE_ALIASING:
copy[i].Aliasing.pResourceBefore = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceBefore);
copy[i].Aliasing.pResourceAfter = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceAfter);
break;
case D3D12_RESOURCE_BARRIER_TYPE_UAV:
copy[i].UAV.pResource = bx_xbox_unwrap_as(copy[i].UAV.pResource);
break;
default:
break;
}
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(count, copy);
if (copy != inline_copy) delete[] copy;
return 0;
}
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box) {
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyTextureRegion");
D3D12_TEXTURE_COPY_LOCATION d{}, s{};
if (dst) {
d = *dst;
d.pResource = bx_xbox_unwrap_as(d.pResource);
}
if (src) {
s = *src;
s.pResource = bx_xbox_unwrap_as(s.pResource);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
}
} // extern "C"
-343
View File
@@ -1,343 +0,0 @@
#ifndef BETTERXEN_D3D12_XS_XBOX_FACADE_H
#define BETTERXEN_D3D12_XS_XBOX_FACADE_H
/*
* Xbox-layout objects in front of the PC proxies (ADR 0009).
*
* A title built against the Xbox Series D3D12 header calls every method through the object's
* function table, whose slot order differs from PC D3D12. A BxXboxObject has the Xbox object
* layout and an Xbox-order table (xbox_tables_generated.cpp); each slot forwards to the PC
* object it hosts, which is usually one of the PC proxies in proxy.h.
*
* Layout (from the Xbox header): the function-table pointer, a 32-bit flags word and the
* reference count make up every object's 16-byte base. ID3D12Device adds a 64-bit null constant
* buffer address at +16 and a 64-byte union at +24 whose first byte, m_OutOfLineFlags, makes
* inline helpers call out through the table when non-zero. The same layout is used for every
* interface family; the fields after the base are ignored by the others. Command lists add a
* put buffer and are not wrapped yet.
*/
#include "proxy.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <new>
struct BxXboxIface {
const char* name; // Xbox leaf interface, for logs
const IID* iids; // Xbox interface IDs this table answers
size_t iid_count;
const IID* host_iid; // PC interface the hosted object provides
const void* const* table; // Xbox-order function table
size_t slots;
};
/*
* Interface-specific Xbox fields follow the 16-byte base. ID3D12Device: null constant-buffer
* address at +16, m_OutOfLineFlags at +24. ID3D12GraphicsCommandList: m_Putter at +16 (five
* put-buffer pointers and 256 reserved bytes), CPU state at +312, the graphics and compute root
* packet-header tables at +316 and +828 and the PSO shadow at +1340; the whole object is 1384
* bytes (an 8-byte field at +1376 follows), which the title's inline code writes. Zero put
* pointers make every inline fast path fail its room check and call through the table. The other
* interfaces define no fields here. The area below is the largest Xbox object (the command list)
* plus a margin, so title writes never reach BetterXen's state after it: with 1360 bytes the
* list's last field was BetterXen's host pointer, and the title overwrote it.
*/
constexpr size_t kBxXboxCommandListBytes = 1384;
constexpr size_t kBxXboxFieldBytes = kBxXboxCommandListBytes - 16 + 64;
struct BxXboxObject {
const void* const* function_table;
uint32_t xbox_flags;
uint32_t xbox_ref_count; // kept equal to `refs` for anything reading the Xbox field
uint8_t xbox_fields[kBxXboxFieldBytes];
// BetterXen state, after every field the Xbox layout defines.
IUnknown* host; // owns one reference; typed as iface->host_iid
const BxXboxIface* iface;
std::atomic<ULONG> refs;
};
static_assert(offsetof(BxXboxObject, xbox_ref_count) == 12, "Xbox m_RefCount offset");
static_assert(offsetof(BxXboxObject, xbox_fields) == 16, "Xbox interface fields start after the base");
static_assert(offsetof(BxXboxObject, host) >= kBxXboxCommandListBytes, "BetterXen state lies past every Xbox field");
static_assert(offsetof(BxXboxObject, host) >= 1372, "BetterXen state follows the Xbox command-list fields");
constexpr size_t kBxXboxDeviceOutOfLineOffset = 24;
/* The Xbox table for `riid`, or nullptr when none of the wrapped families answers it. */
const BxXboxIface* bx_xbox_iface_for(REFIID riid);
/* Wraps `host` (consumes the caller's reference) in the Xbox object for `riid`. One Xbox object
exists per host object and family. When no family answers `riid`, `host` is returned as is
and that is logged. */
void* bx_xbox_wrap(REFIID riid, void* host, HRESULT* failure = nullptr);
/* After a (REFIID, void**) creation call: wraps a successful result. */
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv);
/* The hosted PC object when `p` is one of our Xbox objects, otherwise `p` itself. */
IUnknown* bx_xbox_unwrap(const void* p);
template <typename T>
T* bx_xbox_unwrap_as(T* p) {
return static_cast<T*>(static_cast<void*>(bx_xbox_unwrap(p)));
}
template <typename T>
const T* bx_xbox_unwrap_as(const T* p) {
return static_cast<const T*>(static_cast<void*>(bx_xbox_unwrap(p)));
}
template <typename T>
T* bx_xbox_host(void* self) {
return static_cast<T*>(static_cast<BxXboxObject*>(self)->host);
}
/* Unwraps an array of interface pointers for one forwarded call. */
template <typename T>
class BxXboxUnwrapArray {
public:
BxXboxUnwrapArray(T* const* items, UINT count) : count_(count) {
if (!items || count == 0) {
ok_ = true;
return;
}
data_ = count <= kInline ? inline_ : new (std::nothrow) T*[count];
ok_ = data_ != nullptr;
for (UINT i = 0; ok_ && i < count; ++i) data_[i] = bx_xbox_unwrap_as(items[i]);
}
~BxXboxUnwrapArray() {
if (data_ && data_ != inline_) delete[] data_;
}
BxXboxUnwrapArray(const BxXboxUnwrapArray&) = delete;
BxXboxUnwrapArray& operator=(const BxXboxUnwrapArray&) = delete;
bool ok() const { return ok_; }
T* const* data() const { return data_; }
private:
static constexpr UINT kInline = 16;
T* inline_[kInline] = {};
T** data_ = nullptr;
UINT count_ = 0;
bool ok_ = false;
};
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv);
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self);
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self);
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv);
/* Xbox ID3D12Device::CreateCommandQueueX: the Xbox queue description selects a hardware
engine/pipe and queue index; the PC queue gets the same type and flags at normal priority. */
struct BxXboxCommandQueueDesc {
D3D12_COMMAND_LIST_TYPE Type;
D3D12_COMMAND_QUEUE_FLAGS Flags;
UINT EngineOrPipeIndex;
UINT QueueIndex;
};
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
REFIID riid, void** ppv);
/* Xbox ID3D12Device::CreateCommandListX. ResourceBarrierBatchSize sizes an Xbox-side batch and is
not used by the host. */
struct BxXboxCommandListDesc {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags;
UINT NodeMask;
UINT ResourceBarrierBatchSize;
};
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
ID3D12CommandAllocator* allocator,
ID3D12PipelineState* initial_state, REFIID riid,
void** ppv);
/* Frame pacing (frame_pacing.cpp): Xbox ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX and
WaitFrameEventX, emulated with a host timer. Event types: 0 origin, 1 display vblank, 2 flip. */
struct BxXboxFrameObjectList {
UINT Count;
HANDLE* pObjects;
};
struct BxXboxFrameWaitList {
UINT Count;
HANDLE* pObjects;
UINT* pSignaledObjectIndex;
};
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void* self, IDXGIOutput* output, UINT length_us,
UINT period, UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void* self, UINT type, UINT offset_us,
const BxXboxFrameObjectList* signals, UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void* self, UINT type, UINT timeout_ms,
const BxXboxFrameWaitList* waits, UINT flags,
UINT64* token);
/*
* Title memory and host objects (ADR 0009). Everything that maps title-visible GPU memory to
* host objects goes through these functions, so the backend behind them (D3DMetal today) can be
* replaced on its own: title descriptor handles to host handles (descriptor_heaps.cpp) and title
* GPU addresses to host addresses (placed_x.cpp). Unknown values pass through unchanged.
*/
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title);
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title);
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title);
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
void bx_xbox_descriptor_heap_forget(IUnknown* host);
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes);
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
/* Fences with a title-visible value (fences.cpp). */
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host);
void bx_xbox_fence_forget(IUnknown* host);
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self);
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value);
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT64 reference, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
UINT reference, UINT mask, UINT flags);
/* GPU value writes into title memory (gpu_writes.cpp). */
void bx_xbox_gpu_writes_reset(IUnknown* host_list);
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flush, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flush, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flags);
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists);
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
UINT64 token, UINT flags);
/* Pipelines and the opt-in null-render mode (pipelines.cpp). */
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title);
void bx_xbox_pipeline_forget(IUnknown* host);
void bx_xbox_list_forget(IUnknown* host);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void* extended,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
UINT extended_count, const void* extended,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
ID3D12RootSignature* root, REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void* state, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void* state, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT count, const void* descs, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT count, const void* descs, REFIID riid,
void** ppv);
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso);
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso);
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
UINT flags);
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT sync_flags, UINT control_flags, D3D12_GPU_VIRTUAL_ADDRESS base,
SIZE_T size);
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void* self, void* callback, UINT64 context);
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance);
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
INT base_vertex, UINT first_instance);
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z);
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
ID3D12Resource* arguments, UINT64 arguments_offset,
ID3D12Resource* count, UINT64 count_offset);
/* Map / Unmap: title memory for resources that have it (placed_x.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data);
void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written);
void bx_xbox_sync_mapped_buffers();
HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes, const void* parameters);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void* self, UINT batch_count, const void* batches,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT range_count, const void* ranges,
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages, UINT flags);
HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
UINT page_count, UINT flags);
/* Page pools (placed_x.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
HANDLE* handle);
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void* self, HANDLE handle);
/* Committed resources with title-visible memory (committed.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, UINT32 formats,
DXGI_FORMAT* castable, REFIID riid, void** ppv);
/* Descriptor heaps with title-visible storage (descriptor_heaps.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
REFIID riid, void** ppv);
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void* self, D3D12_DESCRIPTOR_HEAP_TYPE type);
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self);
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self);
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* `xbox_desc` is a D3D12XBOX_SAMPLER_DESC. */
void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
const UINT* dest_sizes, UINT src_ranges,
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
D3D12_DESCRIPTOR_HEAP_TYPE type);
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv);
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views);
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view);
/* Resources at a title-chosen GPU address (placed_x.cpp): host shadow resources. */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
const D3D12_RESOURCE_DESC1* desc, UINT initial_layout,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self);
/* Xbox views of placed memory; `xbox_desc` is a D3D12XBOX_SHADER/UNORDERED_ACCESS_VIEW_DESC. */
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* Drops the shadow record of a destroyed resource. */
void bx_xbox_placed_forget(IUnknown* host);
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers);
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box);
}
#include "xbox_tables_generated.h"
#endif
File diff suppressed because it is too large. Load diff
-24
View File
@@ -1,24 +0,0 @@
// 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
+122 -598
View File
@@ -1,7 +1,6 @@
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <new>
@@ -11,86 +10,35 @@
namespace {
constexpr SIZE_T small_page = 64 * 1024;
constexpr SIZE_T large_page = 2 * 1024 * 1024;
struct PageBlock;
struct Page {
PageBlock* block;
bool allocated;
HANDLE section;
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;
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;
ULONG_PTR next_tag = 1;
struct Lock {
Lock() { AcquireSRWLockExclusive(&memory_lock); }
@@ -101,13 +49,11 @@ 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 {
@@ -115,36 +61,35 @@ struct PlaceholderApi {
}
};
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;
// 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;
}
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) % kFramesPerPage == 0 &&
(tag - block->first_tag) / kFramesPerPage < block->count) {
Page* page = &block->entries[(tag - block->first_tag) / kFramesPerPage];
return page->allocated ? page : nullptr;
if (tag >= block->first_tag && tag - block->first_tag < block->count) {
Page* page = &block->entries[tag - block->first_tag];
return page->section ? page : nullptr;
}
}
return nullptr;
}
ULONG_PTR page_tag(const Page* page) {
return page->block->first_tag + static_cast<ULONG_PTR>(page - page->block->entries) * kFramesPerPage;
return page->block->first_tag + (page - page->block->entries);
}
void delete_block(PageBlock* block) {
if (block->section) CloseHandle(block->section);
for (SIZE_T i = 0; i < block->count; ++i) {
if (block->entries[i].section) CloseHandle(block->entries[i].section);
}
delete[] block->entries;
delete block;
}
@@ -165,11 +110,7 @@ bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
bool remove_view(View** link) {
View* view = *link;
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;
if (!UnmapViewOfFile(view->address)) return false;
*link = view->next;
delete view;
return true;
@@ -188,8 +129,9 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
SIZE_T matched = 0;
for (const View* view = views; view; view = view->next) {
if (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
matched += view->pages;
const auto address = reinterpret_cast<uintptr_t>(view->address);
if (address >= begin && address < end && view->page->block->size == size) {
++matched;
}
}
if (matched != count) {
@@ -199,7 +141,8 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
for (View** link = &views; *link;) {
View* view = *link;
if (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
const auto address = reinterpret_cast<uintptr_t>(view->address);
if (address >= begin && address < end && view->page->block->size == size) {
if (!remove_view(link)) return nullptr;
} else {
link = &view->next;
@@ -208,236 +151,50 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
return base;
}
// Builds one unlinked View per tag, in order, after checking that every tag names a live page.
bool build_views(const ULONG_PTR* tags, SIZE_T count, bool preserve, View** out) {
View* first = nullptr;
View** tail = &first;
for (SIZE_T i = 0; i < count; ++i) {
Page* page = find_page(tags[i]);
if (!page) {
destroy_views(first);
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
auto* view = new (std::nothrow) View{page, 1, nullptr, nullptr, preserve};
if (!view) {
destroy_views(first);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return false;
}
*tail = view;
tail = &view->next;
}
*out = first;
return true;
}
void publish(View* pending) {
while (pending) {
View* next = pending->next;
pending->next = views;
views = pending;
pending = next;
}
}
// Maps the run [first, first + pages) at `address` inside a reservation. The range may cover one
// placeholder or several (left by earlier mappings); each placeholder piece inside it is split out
// where it extends past the range and replaced with one view, so a range inside one placeholder
// becomes one view. Returns the unlinked chain of views (through `next`) and its tail in *tail,
// or nullptr with the error set and nothing mapped.
View* map_run(Page* first, SIZE_T pages, BYTE* address, DWORD protect, View** tail = nullptr) {
const PlaceholderApi& api = placeholder_api();
const uintptr_t begin = reinterpret_cast<uintptr_t>(address);
const uintptr_t end = begin + pages * small_page;
View* head = nullptr;
View** link = &head;
View* last = nullptr;
for (uintptr_t at = begin; at < end;) {
MEMORY_BASIC_INFORMATION region{};
uintptr_t piece_end = end;
if (VirtualQuery(reinterpret_cast<void*>(at), &region, sizeof(region)) && region.State == MEM_RESERVE) {
const uintptr_t region_end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
if (region_end < piece_end) piece_end = region_end;
}
const SIZE_T piece_pages = (piece_end - at) / small_page;
Page* piece_first = first + (at - begin) / small_page;
auto* view = new (std::nothrow) View{piece_first, piece_pages, reinterpret_cast<BYTE*>(at), nullptr, true};
if (!view) SetLastError(ERROR_NOT_ENOUGH_MEMORY);
if (view) VirtualFree(reinterpret_cast<void*>(at), piece_end - at, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
if (!view || !api.replace(first->block->section, GetCurrentProcess(), reinterpret_cast<void*>(at),
page_offset(piece_first), piece_end - at, MEM_REPLACE_PLACEHOLDER, protect,
nullptr, 0)) {
const DWORD error = GetLastError();
delete view;
while (head) {
View* next = head->next;
api.unmap(GetCurrentProcess(), head->address, MEM_PRESERVE_PLACEHOLDER);
delete head;
head = next;
}
SetLastError(error);
return nullptr;
}
*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
// 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 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) {
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) {
Lock lock;
if (!tags) return unmap_span(static_cast<BYTE*>(address), count, size);
static const PlaceholderApi api;
if (!api.reserve || !api.replace) {
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return nullptr;
}
View* pending = nullptr;
for (SIZE_T i = count; i > 0; --i) {
Page* page = find_page(tags[i - 1]);
if (!page || page->block->size != size) {
destroy_views(pending);
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
auto* view = new (std::nothrow) View{page, nullptr, pending};
if (!view) {
destroy_views(pending);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
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;
}
}
pending = view;
}
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 = small_page;
requirements.Alignment = size;
MEM_EXTENDED_PARAMETER alignment{};
alignment.Type = MemExtendedParameterAddressRequirements;
alignment.Pointer = &requirements;
auto* base = static_cast<BYTE*>(api.reserve(nullptr, nullptr, count * small_page,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, &alignment, 1));
auto* base = static_cast<BYTE*>(api.reserve(nullptr, address, count * size,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
address ? nullptr : &alignment, address ? 0 : 1));
if (!base) {
const DWORD error = GetLastError();
destroy_views(pending);
@@ -448,13 +205,13 @@ PVOID map_unreserved(SIZE_T count, const ULONG_PTR* tags) {
BYTE* cursor = base;
SIZE_T remaining = count;
View* view = pending;
for (; view; view = view->next, cursor += small_page, --remaining) {
for (; view; view = view->next, cursor += size, --remaining) {
const bool split = remaining > 1;
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,
if (split && !VirtualFree(cursor, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
if (!api.replace(view->page->section, nullptr, cursor, 0, size,
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
const DWORD error = GetLastError();
if (split) VirtualFree(cursor + small_page, 0, MEM_RELEASE);
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
SetLastError(error);
break;
}
@@ -471,151 +228,31 @@ PVOID map_unreserved(SIZE_T count, const ULONG_PTR* tags) {
SetLastError(error);
return nullptr;
}
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;
while (pending) {
View* next = pending->next;
pending->next = views;
views = pending;
pending = next;
}
return base;
}
} // namespace
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 nullptr;
}
const uintptr_t end = (requested + size + small_page - 1) / small_page * small_page;
MEM_ADDRESS_REQUIREMENTS requirements{};
requirements.Alignment = small_page;
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
MEM_EXTENDED_PARAMETER parameter{};
parameter.Type = MemExtendedParameterAddressRequirements;
parameter.Pointer = &requirements;
return api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr, end - begin,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, begin ? nullptr : &parameter,
begin ? 0 : 1);
}
PVOID reserve_mappable(PVOID address, SIZE_T size, SIZE_T page, DWORD protect, bool adopt, uintptr_t highest) {
const PlaceholderApi& api = placeholder_api();
const auto requested = reinterpret_cast<uintptr_t>(address);
if (!have_placeholder_api()) return nullptr;
if (adopt && (!address || requested % page != 0 || size % page != 0)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
if (!size || size > std::numeric_limits<uintptr_t>::max() - requested - page) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
// A reservation's base rounds down to its page size and its end rounds up.
const uintptr_t begin = requested - requested % page;
const uintptr_t end = (requested + size + page - 1) / page * page;
MEM_ADDRESS_REQUIREMENTS requirements{};
requirements.Alignment = page;
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
MEM_EXTENDED_PARAMETER alignment{};
alignment.Type = MemExtendedParameterAddressRequirements;
alignment.Pointer = &requirements;
auto* reservation = new (std::nothrow) Reservation{};
if (!reservation) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
PVOID base = nullptr;
if (adopt) {
// MEM_REPLACE_PLACEHOLDER: the title split this range out of its own placeholder; it
// stays as it is and becomes mappable.
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(address, &region, sizeof(region)) || region.State != MEM_RESERVE
|| reinterpret_cast<uintptr_t>(region.BaseAddress) != requested || region.RegionSize < size) {
delete reservation;
SetLastError(ERROR_INVALID_ADDRESS);
return nullptr;
}
base = address;
} else {
base = api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr,
end - begin, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
begin ? nullptr : &alignment, begin ? 0 : 1);
}
if (!base) {
delete reservation;
return nullptr;
}
Lock lock;
const auto b = reinterpret_cast<uintptr_t>(base);
// A range the title released with VirtualFree may come back: drop stale records over it.
for (Reservation** link = &reservations; *link;) {
if ((*link)->begin < b + (end - begin) && b < (*link)->end) {
Reservation* stale = *link;
*link = stale->next;
delete stale;
} else {
link = &(*link)->next;
}
}
*reservation = {b, b + (end - begin), page, protect, reservations};
reservations = reservation;
return base;
}
} // namespace bx_xmem
// Diagnostics (off unless BX_XMEM_TRACE=1): one line per map call (address, count, first and last
// tag; Scatter: first and last slot too), up to 4000 calls.
bool xmem_trace_on() {
static const bool on = [] {
char v[4];
const DWORD n = GetEnvironmentVariableA("BX_XMEM_TRACE", v, sizeof(v));
return n > 0 && n < sizeof(v) && v[0] == '1';
}();
return on;
}
void trace_map(const char* kind, const void* first_address, const void* last_address, ULONG_PTR count,
const ULONG_PTR* tags) {
static LONG traced = 0;
if (!xmem_trace_on() || InterlockedIncrement(&traced) > 4000) return;
char detail[200];
std::snprintf(detail, sizeof(detail), "%s va=%p..%p count=%llu tags=%llx..%llx", kind, first_address, last_address,
static_cast<unsigned long long>(count), tags ? static_cast<unsigned long long>(tags[0]) : 0ull,
tags ? static_cast<unsigned long long>(tags[count - 1]) : 0ull);
bx_log_emit(BX_LOG_INFO, "xmem", "map_trace", detail);
}
// Authorized GDK documentation: XMemAllocatePhysicalPages(XMemFlags, NumberOfPages,
// PageArray), in 64 KB pages. XMEM_2MB_CLUSTERS is not implemented.
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR num_pages,
PULONG_PTR page_array) {
if ((flags & mem_64k_pages) == mem_64k_pages) flags &= ~mem_64k_pages; // 64 KB pages: the default
if ((flags & ~(xmem_2mb_clusters | xmem_bandwidth_bits)) != 0 || !num_pages || !page_array
|| !valid_span(nullptr, *num_pages, small_page)) {
// Clean-room synthetic signatures modeled after public Win32 AWE
// AllocateUserPhysicalPages / FreeUserPhysicalPages (memoryapi.h, [in, out]
// page count pointer), pending a public console flags/signature ABI.
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
uint64_t flags) {
const SIZE_T size = page_size(flags);
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
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 > (kTagLimit - next_tag) / kFramesPerPage
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|| count > std::numeric_limits<uint64_t>::max() / size) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
@@ -623,10 +260,6 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR num_
}
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;
}
@@ -637,64 +270,49 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR num_
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
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};
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, 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) entries[i] = {block, true, false};
for (SIZE_T i = 0; i < count; ++i) {
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
0, static_cast<DWORD>(size), nullptr);
if (!section) {
const DWORD error = GetLastError();
delete_block(block);
bx_xmem::release_physical(total_bytes);
SetLastError(error);
return FALSE;
}
entries[i] = {block, section, false};
}
blocks = block;
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i * 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);
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
next_tag += count;
return TRUE;
}
// 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)) {
// Rejects unknown, wrong-size, or duplicate tags in `page_array` with
// ERROR_INVALID_PARAMETER without mutating `page_array` or live views.
extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
uint64_t flags) {
const SIZE_T size = page_size(flags);
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
Lock lock;
const SIZE_T count = *num_pages;
SIZE_T validated = 0;
for (; validated < count; ++validated) {
Page* page = find_page(page_array[validated]);
if (!page || page->releasing) break;
if (!page || page->block->size != size || page->releasing) break;
page->releasing = true;
}
if (validated != count) {
@@ -704,17 +322,22 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_ar
}
for (View** link = &views; *link;) {
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;
if ((*link)->page->releasing) {
if (!remove_view(link)) {
const DWORD error = GetLastError();
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
SetLastError(error);
return FALSE;
}
} else {
link = &(*link)->next;
}
}
for (SIZE_T i = 0; i < count; ++i) {
Page* page = find_page(page_array[i]);
page->allocated = false;
CloseHandle(page->section);
page->section = nullptr;
--page->block->live;
page_array[i] = 0;
}
@@ -727,115 +350,18 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_ar
delete_block(block);
}
}
bx_xmem::release_physical(static_cast<uint64_t>(count) * small_page);
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
return TRUE;
}
// 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 XMemMapPhysicalPages(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" PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID base, SIZE_T count, uint64_t flags,
PULONG_PTR page_array) {
return map_pages(base, count, flags, page_array);
}
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
@@ -843,17 +369,15 @@ 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) {
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;
const auto base = reinterpret_cast<uintptr_t>(view->address);
const SIZE_T size = view->page->block->size;
if (va >= base && va - base < size) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(base), &region, sizeof(region))
if (!VirtualQuery(view->address, &region, sizeof(region))
|| region.AllocationBase != view->address || region.Type != MEM_MAPPED) {
return 0;
}
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page + index)};
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page)};
return 1;
}
}
+16 -97
View File
@@ -2,7 +2,6 @@
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
@@ -115,29 +114,14 @@ bool refresh_virtual_commits() {
return true;
}
// 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);
void report_unsupported_host_hooks() {
static const bool reported = [] {
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
}
return found;
return true;
}();
return hooks;
(void)reported;
}
SIZE_T page_size() {
@@ -188,94 +172,29 @@ VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
}
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
if (const auto alloc = title_hooks().alloc) return alloc(size, attributes);
report_unsupported_host_hooks();
return XMemAllocDefault(size, attributes);
}
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
if (const auto free_routine = title_hooks().free) {
free_routine(address, attributes);
return;
}
report_unsupported_host_hooks();
XMemFreeDefault(address, attributes);
}
/*
* 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;
}
PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect) {
/* 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;
const DWORD win_prot = protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE);
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
DWORD low_prot = protect & 0xFFu;
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
: PAGE_READWRITE;
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
* early here cannot commit pages outside the working-set budget. */
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
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;
return VirtualAlloc(address, size, win_alloc, win_prot);
}
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
-14
View File
@@ -1,8 +1,6 @@
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
#include <windows.h>
#include <cstdint>
namespace bx_xmem {
@@ -12,18 +10,6 @@ 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
+51 -12
View File
@@ -1,6 +1,7 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
@@ -132,11 +133,27 @@ int main() {
}
const uint64_t log_start = log_file_size(dispatcher_log_path);
// IAcpHal is not a COM interface (authorized GDK documentation): slots Connect(numCommands,
// numMessages), Disconnect(), SubmitCommand(command, id, audioFrame, data, notification),
// PopMessage(message), GetNumMessages() and Release(). BetterXen has no ACP: commands are
// accepted and no message arrives.
void* object = nullptr;
CHECK(AcpHalCreate(&object) == S_OK && object);
auto* hal = static_cast<IUnknown*>(object);
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
CHECK(hal->Release() == 1);
void* hal = object;
const void* const* acp = *static_cast<const void* const* const*>(hal);
using ConnectFn = HRESULT(WINAPI*)(void*, uint32_t, uint32_t);
using DisconnectFn = HRESULT(WINAPI*)(void*);
using SubmitFn = HRESULT(WINAPI*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
using PopFn = bool(WINAPI*)(void*, void*);
using CountFn = uint32_t(WINAPI*)(void*);
using ReleaseFn = void(WINAPI*)(void*);
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == E_UNEXPECTED); // before Connect
CHECK(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000) == S_OK);
CHECK(FAILED(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000)));
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == S_OK);
unsigned char message[64]{};
CHECK(!reinterpret_cast<PopFn>(acp[3])(hal, message) && reinterpret_cast<CountFn>(acp[4])(hal) == 0);
CHECK(reinterpret_cast<DisconnectFn>(acp[1])(hal) == S_OK);
void *va = nullptr, *second = nullptr;
uint32_t base = 0, other = 0;
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
@@ -165,20 +182,42 @@ int main() {
CHECK(ApuFree(tail) == E_INVALIDARG);
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
CHECK(ApuFree(second) == S_OK);
reinterpret_cast<ReleaseFn>(acp[5])(hal);
// 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);
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) (authorized GDK documentation): six counts in
// (SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM), six CPU pointers and six APU addresses out, the
// arrays from the APU heap (XMA elements are 64 bytes). A second allocation without a release
// fails with ACP_E_ALREADY_ALLOCATED (0x8AC80001).
struct ShapeContexts {
uint32_t counts[6];
void* arrays[6];
uint32_t apu[6];
};
static_assert(sizeof(ShapeContexts) == 96 && offsetof(ShapeContexts, arrays) == 24 &&
offsetof(ShapeContexts, apu) == 72,
"SHAPE_CONTEXTS layout");
constexpr HRESULT kAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_INVALIDARG);
CHECK(AcpHalReleaseShapeContexts() == S_OK); // nothing allocated
ShapeContexts shape{};
shape.counts[4] = 2; // two XMA contexts: 128 bytes, the whole 64 + 64 heap
CHECK(AcpHalAllocateShapeContexts(&shape) == S_OK);
CHECK(shape.arrays[4] && shape.apu[4] && ApuMapApuAddress(shape.apu[4]) == shape.arrays[4]);
CHECK(!shape.arrays[0] && !shape.arrays[5] && !shape.apu[0]);
CHECK(static_cast<const unsigned char*>(shape.arrays[4])[127] == 0); // zero-filled
ShapeContexts again{};
again.counts[4] = 1;
CHECK(AcpHalAllocateShapeContexts(&again) == kAlreadyAllocated);
CHECK(AcpHalReleaseShapeContexts() == S_OK && !ApuMapApuAddress(shape.apu[4]));
CHECK(AcpHalAllocateShapeContexts(&again) == S_OK && again.arrays[4]);
CHECK(AcpHalReleaseShapeContexts() == S_OK);
char log_path[MAX_PATH];
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
if (log_len > 0 && log_len < sizeof(log_path)) {
CHECK(file_contains(log_path, log_start, "\"event\":\"unimpl_api\"", "AcpHal.dll!AcpHalAllocateShapeContexts"));
CHECK(file_contains(log_path, log_start, "\"event\":\"unimpl_api\"", "AcpHal.dll!AcpHalReleaseShapeContexts"));
CHECK(file_contains(log_path, log_start, "\"event\":\"shape_contexts_allocated\"", "xma=2"));
CHECK(file_contains(log_path, log_start, "\"event\":\"connect\"", "commands=4096"));
} else {
// Unreachable under `bx-cli run --log`. A SKIP that still exits 0 would
// contradict the exit-77 protocol, so a missing log is a failure.
+15 -18
View File
@@ -25,12 +25,12 @@
extern "C" {
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(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 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) BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size);
}
@@ -42,10 +42,6 @@ struct bx_xmem_stats_t {
};
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;
@@ -347,7 +343,7 @@ DWORD WINAPI check_device_startup(LPVOID context) {
return 1;
}
ID3D12Device* device = nullptr;
result.device_hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
result.device_hr = D3D12XboxCreateDevice(nullptr, __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;
@@ -888,9 +884,9 @@ int main() {
SIZE_T page_count = 2;
ULONG_PTR pages[2] = {};
uint8_t* view = nullptr;
bool mapped = XMemAllocatePhysicalPages(0, &page_count, pages) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
bool mapped = XMemAllocatePhysicalPages(&page_count, pages, 0) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
if (mapped) {
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, pages));
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, 0, pages));
mapped = view != nullptr && (reinterpret_cast<uintptr_t>(view) % kAlign) == 0;
if (mapped) {
view[kAlign] = 0x5A;
@@ -904,7 +900,7 @@ int main() {
check_concurrent_device_startup();
}
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
HRESULT hr = D3D12XboxCreateDevice(nullptr, __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;
@@ -1526,7 +1522,7 @@ int main() {
* caller's device reference must leave the proxy alive for GetDevice.
*/
ID3D12Device* side = nullptr;
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&side));
hr = D3D12XboxCreateDevice(nullptr, __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);
@@ -1582,7 +1578,7 @@ int main() {
device = nullptr;
backing->Release();
backing = nullptr;
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
hr = D3D12XboxCreateDevice(nullptr, __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);
@@ -1612,7 +1608,7 @@ int main() {
backing->Release();
backing = replaced;
device = nullptr;
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
hr = D3D12XboxCreateDevice(nullptr, __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
@@ -1647,7 +1643,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, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device_b));
hr = D3D12XboxCreateDevice(nullptr, __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;
@@ -1688,10 +1684,11 @@ int main() {
}
if (view) {
XMemMapPhysicalPages(view, page_count, nullptr);
XMemMapPhysicalPages(view, page_count, 0, nullptr);
}
if (pages[0] || pages[1]) {
XMemFreePhysicalPages(2, pages);
SIZE_T free_count = 2;
XMemFreePhysicalPages(&free_count, pages, 0);
}
if (sync.ready) CloseHandle(sync.ready);
if (sync.done) CloseHandle(sync.done);
@@ -42,10 +42,7 @@
#include "bx_log.h"
#include "presentx.h"
// The documented four parameters: adapter, D3D12XBOX_CREATE_DEVICE_PARAMETERS, riid, device. A zeroed
// block (Version 0) keeps the PC-layout proxy this test is written against (ADR 0009).
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
alignas(8) static const unsigned char kPcLayoutParams[80] = {};
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
namespace {
@@ -654,7 +651,7 @@ int main(int argc, char** argv) {
/* --- Device, queue, window ----------------------------------------------------------------- */
g_stage = kSetup;
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, kPcLayoutParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
REQUIRE(hr == S_OK && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr));
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
ID3D12CommandQueue* queue = nullptr;
+13 -15
View File
@@ -33,16 +33,13 @@
#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 D3D12XboxCreateDevice(void* params, REFIID riid, void** ppv);
__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);
__declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect);
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* page_count, PULONG_PTR pages, uint64_t flags);
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(SIZE_T* page_count, PULONG_PTR pages, uint64_t flags);
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, SIZE_T page_count, uint64_t flags,
PULONG_PTR pages);
}
namespace {
@@ -327,7 +324,7 @@ int main() {
* 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);
PVOID reserved_va = XMemVirtualAlloc(nullptr, 2ull * 1024ull * 1024ull, 0x20402000u, 0x21u);
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");
@@ -340,14 +337,14 @@ int main() {
* survive.
*/
ID3D12Device* device = nullptr;
hr = D3D12XboxCreateDevice(nullptr, kPcLayoutParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
hr = D3D12XboxCreateDevice(nullptr, __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);
const BOOL phys_ok = XMemAllocatePhysicalPages(&page_count, pages, 0);
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;
uint8_t* mapped_region = phys_ok ? static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, 2, 0, pages)) : nullptr;
check(mapped_region != nullptr, "XMemMapPhysicalPages(2) must succeed");
if (device && mapped_region) {
@@ -426,10 +423,11 @@ int main() {
}
if (mapped_region) {
XMemMapPhysicalPages(mapped_region, 2, nullptr);
XMemMapPhysicalPages(mapped_region, 2, 0, nullptr);
}
if (phys_ok) {
XMemFreePhysicalPages(2, pages);
SIZE_T free_count = 2;
XMemFreePhysicalPages(&free_count, pages, 0);
}
if (device) {
device->Release();
@@ -1,3 +0,0 @@
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)
@@ -1,414 +0,0 @@
/*
* 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;
}
+4 -14
View File
@@ -23,11 +23,7 @@
#include "bx_log.h"
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 D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
namespace {
@@ -137,22 +133,16 @@ int main() {
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
/* --- 1. Argument contract ------------------------------------------------------------------ */
check(D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), nullptr) == E_POINTER,
check(D3D12XboxCreateDevice(nullptr, __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, kCreateParams, kUnusedIid, &bogus);
HRESULT hr = D3D12XboxCreateDevice(nullptr, 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, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
hr = D3D12XboxCreateDevice(nullptr, __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,8 +54,7 @@ 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, uint64_t xmem_flags,
DWORD protect);
BX_IMPORT PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect);
BX_IMPORT SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len);
/* xgameruntime.dll */
@@ -100,11 +99,7 @@ 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 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] = {};
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
} // extern "C"
namespace {
@@ -442,7 +437,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, 0x1 /* XMEM_CPU */, PAGE_READWRITE));
auto* vmem = static_cast<uint8_t*>(XMemVirtualAlloc(nullptr, kVirtualBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
bool virtual_ok = false;
if (vmem) {
vmem[0] = 0xA5;
@@ -756,7 +751,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, kCreateParams, __uuidof(ID3D12Device), &device);
HRESULT hr = D3D12XboxCreateDevice(nullptr, __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));
@@ -885,7 +880,8 @@ int main(int argc, char** argv) {
dsp_closed = deact_hr == S_OK && XDspDisconnect(dsp) == S_OK;
}
bool apu_closed = apu_conn ? XApuDisconnect(apu_conn) == S_OK : true;
release_com(acp_hal);
/* IAcpHal is not COM: Release is its sixth slot and returns nothing. */
if (acp_hal) reinterpret_cast<void(WINAPI*)(void*)>((*static_cast<void* const* const*>(acp_hal))[5])(acp_hal);
release_com(dstorage_factory);
if (psm_constrained_reg) UnregisterAppConstrainedChangeNotification(psm_constrained_reg);
if (psm_state_reg) UnregisterAppStateChangeNotification(psm_state_reg);
+9 -12
View File
@@ -25,13 +25,10 @@
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);
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void*, REFIID, void**);
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
}
namespace {
@@ -110,9 +107,9 @@ struct Region {
cleanup(D3D12ConfigureVirtualMemoryX(&config) == S_OK, "clear configured region");
}
if (view)
cleanup(XMemMapPhysicalPages(view, count, nullptr) == view, "unmap physical page");
cleanup(XMemMapPhysicalPages(view, count, 0, nullptr) == view, "unmap physical page");
if (page)
cleanup(XMemFreePhysicalPages(count, &page), "free physical page");
cleanup(XMemFreePhysicalPages(&count, &page, 0), "free physical page");
}
};
// Declared just before ExecuteCommandLists, so on a failure after the submit it is
@@ -164,14 +161,14 @@ void run(bool inject_pixel_mismatch) {
stage = "placed_resource";
Region region;
require(XMemAllocatePhysicalPages(0, &region.count, &region.page) && region.count == 1, "allocate physical page");
region.view = XMemMapPhysicalPages(nullptr, 1, &region.page);
require(XMemAllocatePhysicalPages(&region.count, &region.page, 0) && region.count == 1, "allocate physical page");
region.view = XMemMapPhysicalPages(nullptr, 1, 0, &region.page);
require(region.view, "map physical page");
std::memset(region.view, Region::sentinel, Region::page_bytes);
region.config.base_va = reinterpret_cast<uintptr_t>(region.view);
checked(D3D12ConfigureVirtualMemoryX(&region.config), "configure xmem region");
ComPtr<ID3D12Device> device;
checked(D3D12XboxCreateDevice(nullptr, kPcLayoutParams, IID_PPV_ARGS(&device)), "create Xbox device");
checked(D3D12XboxCreateDevice(nullptr, IID_PPV_ARGS(&device)), "create Xbox device");
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = region.config.size_bytes;
hd.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
+3 -8
View File
@@ -40,12 +40,7 @@
#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 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 D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12SerializeVersionedRootSignature(
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error);
@@ -367,7 +362,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, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "no-bridge: D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
D3D12_ROOT_PARAMETER uav = {};
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
@@ -462,7 +457,7 @@ int main() {
}
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
D3D12_ROOT_PARAMETER uav = {};
+4 -8
View File
@@ -8,11 +8,7 @@
#include <cstring>
#include <limits>
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 D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
using namespace bx::storage;
@@ -274,7 +270,7 @@ int check_batched_buffer_transfers(Factory* factory) {
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
Com<ID3D12Device> device;
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), device.out());
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
if (hr != S_OK || !device.value) {
std::fprintf(stderr, "xcrdapi: D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
@@ -437,7 +433,7 @@ int check_unconfirmed_staged_copy(Factory* factory) {
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
Com<ID3D12Device> device;
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), device.out());
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
if (hr != S_OK || !device.value) {
std::fprintf(stderr, "xcrdapi: unconfirmed D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
@@ -830,7 +826,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, kCreateParams, __uuidof(ID3D12Device), device.out());
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
if (hr != S_OK || !device.value) {
std::fprintf(stderr, "xcrdapi: public D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
+8 -15
View File
@@ -12,16 +12,13 @@ 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, uint64_t, DWORD);
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, 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)) { \
@@ -71,17 +68,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, kXMemCpu, PAGE_READWRITE));
MEM_COMMIT | MEM_RESERVE, 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, kXMemCpu, PAGE_READWRITE));
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, PAGE_READWRITE));
CHECK(reserved && reinterpret_cast<uintptr_t>(reserved) % page == 0);
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, kXMemCpu, PAGE_READWRITE) == reserved);
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, kXMemCpu, PAGE_READWRITE)
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, PAGE_READWRITE) == reserved);
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, PAGE_READWRITE)
== reserved + page);
MEMORY_BASIC_INFORMATION region{};
@@ -103,15 +100,11 @@ int main() {
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == 0 && stats.peak_committed_bytes == page * 3);
// 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.
// Console callers pass multi-bit attributes (e.g. 0x21) in arg 4 and high bits in alloc_type.
auto* console_res = static_cast<unsigned char*>(
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, kXMemCpu, PAGE_READWRITE));
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, 0x21u));
CHECK(console_res != nullptr);
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);
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, 0x21u) == console_res);
console_res[0] = 0x5Au;
CHECK(console_res[0] == 0x5Au);
CHECK(VirtualFree(console_res, 0, MEM_RELEASE));
@@ -9,7 +9,7 @@
#include "bx_xmem_internal.h"
extern "C" {
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
}
@@ -49,7 +49,7 @@ int main() {
// ...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(!XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
// An over-release is refused and leaves the outstanding charge in place.
@@ -62,7 +62,7 @@ int main() {
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);
void* block = XMemVirtualAlloc(nullptr, page, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
CHECK(block != nullptr);
CHECK(VirtualFree(block, 0, MEM_RELEASE));
@@ -1,2 +0,0 @@
add_executable(test_xmem_hooks main.cpp)
target_link_libraries(test_xmem_hooks PRIVATE xmem kernel32)
@@ -1,69 +0,0 @@
/*
* 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;
}
+92 -174
View File
@@ -1,11 +1,3 @@
/*
* 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>
@@ -16,28 +8,13 @@
extern "C" {
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
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 XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID, SIZE_T, uint64_t, PULONG_PTR);
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
}
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)) { \
@@ -47,183 +24,124 @@ constexpr DWORD kPageGraphicsReadWrite = 0x2000;
} \
} while (false)
DWORD state_of(const void* address) {
MEMORY_BASIC_INFORMATION region{};
return VirtualQuery(address, &region, sizeof(region)) ? region.State : 0;
}
bool check_physical_pages() {
bool check_aliases(SIZE_T page_size, uint64_t flags) {
bx_xmem_stats_t stats{};
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
CHECK(stats.allocated_physical_bytes == 0);
// 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]);
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);
// 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));
CHECK(XMemAllocatePhysicalPages(&count, pages, flags));
CHECK(count == 2 && pages[0] && pages[1] && pages[0] != pages[1]);
// Working-set statistics and internal stats must both reflect physical pages.
bx_xmem_get_internal_stats(&stats);
CHECK(stats.allocated_physical_bytes == 4 * kPage);
CHECK(stats.allocated_physical_bytes == count * page_size);
CHECK(stats.peak_committed_bytes >= count * page_size);
bx_xmem_stats_t ws_stats{};
CHECK(XMemGetWorkingSetStatistics(&ws_stats, sizeof(ws_stats)));
CHECK(ws_stats.allocated_physical_bytes == 4 * kPage);
CHECK(ws_stats.allocated_physical_bytes == count * page_size);
ULONG_PTR cap_pages = static_cast<ULONG_PTR>(stats.title_limit_bytes / kPage);
CHECK(!XMemAllocatePhysicalPages(0, &cap_pages, pages));
// Shared title budget cap: existing physical pages must block both full-cap
// physical and full-cap heap allocations without allocating gigabytes.
SIZE_T cap_pages = static_cast<SIZE_T>(stats.title_limit_bytes / page_size);
CHECK(!XMemAllocatePhysicalPages(&cap_pages, pages, flags));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
CHECK(!XMemAllocDefault(static_cast<SIZE_T>(stats.title_limit_bytes), 0));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.allocated_physical_bytes == count * page_size);
// 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(!XMemMapPhysicalPages(nullptr, count, 0x12345, pages));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
// 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);
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);
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);
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);
// Mapping over mapped pages replaces them.
CHECK(XMemMapPhysicalPages(base, 4, reversed) == base);
CHECK(base[9] == 0x43 && base[3 * kPage + 9] == 0x40);
// 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));
// 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);
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);
// 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.
// Rejected frees (stale or duplicate tags) must fail without modifying
// page_array or disturbing live mappings.
ULONG_PTR stale[] = {pages[0], 0};
CHECK(!XMemFreePhysicalPages(2, stale));
CHECK(!XMemFreePhysicalPages(&count, stale, flags));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && stale[0] == pages[0] && stale[1] == 0);
CHECK(linear[7] == 0x41);
ULONG_PTR dup_free[] = {pages[0], pages[0]};
CHECK(!XMemFreePhysicalPages(2, dup_free));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && base[9] == 0x40);
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);
// 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(!XMemMapPhysicalPagesScatter(nullptr, count, flags, stale));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
CHECK(!XMemMapPhysicalPages(linear, count, flags, pages));
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
// Partial/over-wide unmap must fail cleanly and leave mapped pages intact.
CHECK(!XMemMapPhysicalPagesScatter(scatter, count + 1, flags, nullptr));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
// Exact unmap succeeds; repeating unmap on the now-empty span must fail.
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr) == scatter);
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
CHECK(!XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, reversed) == scatter);
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
CHECK(XMemFreePhysicalPages(&count, pages, flags));
CHECK(!pages[0] && !pages[1]);
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear), &first));
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
CHECK(!XMemMapPhysicalPages(nullptr, count, flags, reversed));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.allocated_physical_bytes == 0);
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_physical_pages()) {
if (!check_aliases(64 * 1024, 0) || !check_aliases(2 * 1024 * 1024, 2 * 1024 * 1024)) {
return 1;
}
std::puts("test_xmem_physical: passed");