From 34c130c36cebd482f5e40eddb0d3e76ad30607d7 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Sun, 22 Nov 2026 17:26:34 -0500 Subject: docs: slot 67 passes the dispatch state on; what pipeline slot 11 does with 0, measured (RT-99) - d3d12_command_objects.md section 3.5a: slot 67 now passes all four pairs; for slot 11, what the DLL does on failure and with 0 (measured in its code), the object's shape, why no program needs a scratch size (measured over the 29), what is implemented and what stays open. - fspx.md: the slot-67 payload and its checks, and slot 11. - d3d12_vulkan.md and runtime/README.md: the new parts of d3d12_fspx_compute_test; the DLL's own dispatch was not run here (fsr_dispatch_test needs MSVC structured exception handling). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_command_objects.md | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) (limited to 'docs/d3d12_command_objects.md') diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 0c94f58c7..82ead294c 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -466,9 +466,10 @@ vtable pointer of a public object. at `+0x18`, a copy of the kind-6 program at `+0x28` with its exact size at `+0x30`, and kind 7 at `+0x38` ([fspx.md](fspx.md)). The proxy maps the console desc to `D3D12_COMPUTE_PIPELINE_STATE_DESC` and routes it to `CreateComputePipelineState` (PC slot 11). On a PC device that call fails (`E_FAIL`) because the code is not a PC - shader, so the DLL falls back to slot 62; its message for that failure calls the fallback "NewBE". The Vulkan - device takes the bare kind-6 program and finds its translated module by `fspx_code_sha256` ([fspx.md](fspx.md), - "Build and run-time lookup"), for the programs the build translated. + shader, so the DLL falls back to slot 62; its message for that failure calls the fallback "NewBE". With kind 0 in + the description (always, from this DLL) the proxy passes all four pairs on as one `FSPX` payload, checking each pair + before reading it. The Vulkan device then finds the translated module by `fspx_code_sha256` and `fspx_state_sha256` + ([fspx.md](fspx.md), "Build and run-time lookup"), for the programs the build translated. - **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a @@ -482,9 +483,20 @@ vtable pointer of a public object. the largest value (`+0x10f8`). Before a dispatch whose pipeline has a non-zero value (`0x64d3`; zero skips the binding), the DLL creates the scratch buffer once, `largest * 0xd0` bytes rounded up to 64 KiB, through device slot 27 in state `UNORDERED_ACCESS` (`0x65ab`), names it `FFX_XBox_ComputeScratch`, and binds it with list slot - 141 `(2, GPU VA, buffer size, this pipeline's value)` (`0x65f8`). Measured: the calls and the arithmetic. Open: - what the slot-11 object is, the unit of its dword (the factor 1024 suggests KiB), the meaning of `0xd0`, and - of the leading `2`. + 141 `(2, GPU VA, buffer size, this pipeline's value)` (`0x65f8`). Measured: the calls and the arithmetic. + - **Failure and zero (measured, `0x585c` to `0x58b1`).** The value at `+0x44` is set to 0 before the call. A failed + HRESULT or a null `obj` skips to the function's success return with the value still 0, so pipeline creation does + not depend on slot 11. At dispatch a value of 0 skips both the scratch buffer and list slot 141 (`0x64d6`). + - **The object (measured shape, hypothesis about its type).** Slot 3 is called with no arguments and its result is + read as a pointer to the dword; slot 2 releases it. That is the shape of `ID3DBlob::GetBufferPointer` and + `Release`. + - **No per-program size (measured on the 29 programs).** `COMPUTE_PGM_RSRC2.SCRATCH_EN` is clear in all 29, no + program has a `scratch_*` or `flat_scratch` instruction, and kind-0 words 0, 1 and 2 are each one value across + all 29. + - **Implemented.** The Vulkan device's pipeline answers slot 11 with a blob holding 0; console slots 9 and 10 + return `E_NOTIMPL`. A translated module keeps its private data in SPIR-V, not in a console scratch buffer. + - **Open.** What the console returns there for these programs, the unit of the dword (the factor 1024 suggests + KiB), the meaning of `0xd0`, and of the leading `2`. - The DLL's 29 shaders are `DXBC` containers with `SFI0`, `ISG1`, `OSG1`, `PSV0`, `RTS0`, `HASH` and `ACCC` parts and no `DXIL`. The `ACCC` payload starts with the tag `FSPX` in all 29; the game's own native shaders are `FSSM` inside `XBCH` ([design.md](design.md)). `FSPX` is a directory around an uncompressed RDNA2 program and its -- cgit v1.2.3 From cf2a45fc38328435c7459af6ee2712514bb93741 Mon Sep 17 00:00:00 2001 From: Nolan Cotter <186326284+NolanCotter@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:05:38 -0700 Subject: docs: README/d3d12_command_objects reflect the landed console-ABI work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Xbox D3D12 row listed buffer views, root signatures, pipelines, draws, placed resources, 1D textures and a swapchain as missing — all implemented — and predates the console list proxy, the PresentX wiring and the upload arena. The slot-148 note now describes the arena and VA translation that replaced the "must" wording. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 2 +- docs/d3d12_command_objects.md | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) (limited to 'docs/d3d12_command_objects.md') diff --git a/README.md b/README.md index 7ea567ef7..7a085a59c 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ work on booting can start as soon as one is available to a developer. | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Controllers through a GameInput shim on SDL3 (any controller SDL supports, rumble, DualSense trigger effects and lightbar; built when SDL3 is installed or with `-DLEONIDA_SDL3_FETCH=ON`, [notes](docs/gameinput.md)). `--trace-d3d12` logs every D3D12 call and its outcome for the first boot. Untested against the real executable | -| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5; they go into the bindless set), and query heaps. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. No buffer views, root signatures, pipelines, draws, placed resources, 1D textures or swapchain yet ([plan](docs/d3d12_vulkan.md)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md), [console ABI](docs/d3d12_xs_console_abi.md)) | | Ray tracing (BVH) | ⚠️ In progress. `BuildRaytracingAccelerationStructure` builds BLASes and TLASes on the GPU in the console's XDXR BVH4 layout (the default; `LEONIDA_RT_AS=khr` uses Vulkan's own acceleration structures instead), which the translated shaders walk themselves through `image_bvh_intersect_ray` (all four triangle node types, TRI0-TRI3, with the barycentric remap byte); the GPU builder writes TRI0 leaves. Updates refit instead of rebuilding, and clone, compaction and the compacted/current postbuild sizes work; checked against a CPU reference on synthetic scenes. The build descriptions are recovered from the package's `XboxBvhBuilder.dll` ([notes](docs/xdxr.md)). The game's `*_bvh4.rpf` packs are measured: offline-built, dehydrated BLASes that rehydrate through that DLL with their geometry from the drawables in `levels.rpf` (measured on 8 of the 10 sampled BLAS; [notes](docs/bvh.md)). Not done in the builder: TRI1 pairing, BOX16 nodes, serialization. Open: whether the game rehydrates the packs or rebuilds them ([#313](https://github.com/ItsNotRexed/Leonida/issues/313)) | The table above is written by hand. To measure it on your own checkout (unit and runtime tests, which rows of diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 0c94f58c7..588f9675c 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -340,9 +340,10 @@ section 3.5a), and the console list has methods well past the PC tail: 71, 73, 8 FSR DLL. Slot 148 matters beyond the builder: the address it returns is written by the CPU and passed unchanged to the GPU -as a root SRV address, so console upload memory has the same address for the CPU and the GPU. A replacement must -return memory whose CPU pointer is also a valid GPU address (for this layer: inside the arena of -[d3d12_vulkan.md §3.3](d3d12_vulkan.md)). +as a root SRV address, so console upload memory has the same address for the CPU and the GPU. On a PC the two +address spaces differ, so `d3d12_xs_device.cpp` carves a bump arena out of persistently-mapped UPLOAD-heap +buffers: the title writes the mapped memory and the six root descriptor setters and the IA/SO view setters +translate the CPU pointer to the chunk's buffer device address before forwarding. The function at `0xd580` uses the 71/73 pair instead of the slot-146 barrier when the byte at RVA `0xd773c` is set. That byte is one of seven bools at `0xd7738`–`0xd773e` in zero-initialised `.bss`. The only accesses to them in -- cgit v1.2.3 From cf5c0f7fbf43d0428782d4f7f395c758abbfeba8 Mon Sep 17 00:00:00 2001 From: abilliontokens Date: Sun, 22 Nov 2026 16:32:02 -0800 Subject: docs+tools: no shipped module passes an unknown GUID at a call site (D3D-441) The call-site scan tools/d3d12_guid_sites.py enumerates every 16-byte constant a module's code can name (RIP-relative lea targets, absolute data pointers, adjacent movabs immediates, import-slot loads) and classifies it against the SDK's IID set. Over the 16 modules of the 1.0.2.1 package only the ten known IIDs of the two D3D12 clients appear; no unknown GUID exists at any call site, no module imports IID data, and no code-referenced static queue description carries a list type outside the PC enum. The compute/copy console list IIDs and the DMA type's numeric value therefore have no static source in the package (consistent with #3520's export-table negative) and stay reachable only through the running title. --- docs/d3d12_command_objects.md | 41 ++++- tests/test_d3d12_guid_sites.py | 191 ++++++++++++++++++++ tools/d3d12_guid_sites.py | 400 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 630 insertions(+), 2 deletions(-) create mode 100644 tests/test_d3d12_guid_sites.py create mode 100644 tools/d3d12_guid_sites.py (limited to 'docs/d3d12_command_objects.md') diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 0c94f58c7..c185bb7e8 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -270,6 +270,41 @@ shipped modules, not a claim that the game never queries for them. The `GraphicsCommandList` ASCII string occurs 30 times in `XboxBvhBuilder.dll` (type/debug names); `PresentX` does not occur in any of the 16 DLLs. + +### 3.2a No shipped module passes an unknown GUID at a call site + +Section 3.2's byte scan can only recognise *known* IIDs; a console-only GUID (the four list IIDs of +[`d3d12_xs_surface.md §4`](d3d12_xs_surface.md)) would scan as anonymous data. The call-site scan closes +that hole: `tools/d3d12_guid_sites.py` enumerates every 16-byte constant a module's code can name — +RIP-relative `lea` targets in data sections, absolute pointers stored in data, two adjacent +`movabs` immediates that inline a GUID without a constant pool, and `mov reg, [rip+...]` loads +through import slots (a GUID imported as data) — and reports which are GUID-shaped. Over all 16 +modules of the 1.0.2.1 package: + +| Binary | GUID-shaped constants the code references | +|---|---| +| `XboxBvhBuilder.dll` | 2: `IID_ID3D12RootSignature`, `IID_ID3D12PipelineState` (the same pair as §3.2) | +| `amd_fidelityfx_upscaler_xbox.dll` | 8: the §3.2 set, nothing else | +| `amd_fidelityfx_loader_xbox.dll` | 0 | +| the other 13 modules | 0–44 GUIDs each (six have none); where present they are HTTP, WinRT and CRT interfaces — none of these modules imports `d3d12_xs.dll`, so none can call D3D12 at all | + +No module loads a GUID through an import slot, and no `movabs` pair inlines one. As a control, the +upscaler's single `IID_ID3D12Device` reference (rva `0x482f0`) is the IID of a real slot-0 +`QueryInterface` call (`(this, &IID, &out)`, decompiled at rva `0xde66`). So the only +interfaces any shipped module can name at a `QueryInterface` or a creation call are the ten it +already uses; a console compute/copy list IID cannot appear in the package, statically, in any +form. The same scan looks for code-referenced static `D3D12_COMMAND_QUEUE_DESC` windows +`{Type, Priority, Flags, NodeMask}`: 10 windows in 3 modules survive the shape filter, every one with +`Type` 1 — a PC enum value — and all of them offset tables read by stride arithmetic, not queue +descriptions (checked by decompiling the referencing function of the upscaler's six). None has a +value past `VIDEO_DECODE` (4), so the DMA type's numeric value has no static source in the package +either. + +Reproduce: `python -I tools/d3d12_guid_sites.py /*.dll --known +IID_ID3D12ConsDmaCommandList=30bc77b9-8379-4b25-95de-b8588c42275d` (prints GUID values and counts +only). The four list IIDs and the DMA type remain reachable only through the running title, as +[`d3d12_xs_surface.md §4`](d3d12_xs_surface.md) already requires for the IIDs. + ### 3.3 The BVH builder's command-list call sites The exported `BuildRaytracingAccelerationStructure` (ordinal 3, RVA `0x21610`) copies the input @@ -664,7 +699,8 @@ Even taking both projects at face value, the following remain **Open**: - the Xbox queue vtable beyond the public chain (`PresentX`, `SuspendX`, `ResumeX`); - the `PresentX` signature, plane struct, resource/view arrays and swapchain parameters; - the command-list extension slots other than the ones sections 3.3a and 3.5a measured (71, 73, 80, 85, 141, 146, 148); -- the DMA list type's real numeric value and the compute/copy console list IIDs; +- the DMA list type's real numeric value and the compute/copy console list IIDs, which the package + itself cannot supply (§3.2a): they need the running title or a vendor runtime; - any Xbox-specific return convention on these interfaces. ## 5. What a runtime can do without the executable @@ -780,7 +816,8 @@ command object. | `SuspendX` / `ResumeX` | No slot or signature. | | Xbox queue/list/fence/allocator slot deviations | No runtime binary and no game executable; the package has no queue, fence or allocator client, and its only command-list client is the BVH builder. | | Builder's list field `+0x350` | Read once (`0x1d877`) and not explained by the inline buffer of section 3.5a, which covers `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and `+0x544`. | -| DMA list use/value | The IID is prior art; type 6 is derived; no shipped module uses it. | +| DMA list use/value | The IID is prior art; type 6 is derived; no shipped module uses it, and no module can name any GUID at a call site beyond its known ten or holds a static queue description with a non-PC type (§3.2a). | +| Compute/copy console list IIDs | Not exported (see #3520) and not present at any call site (§3.2a); only the running title can supply them. | ### 5.4 GCL8 (resolved in PR #164) diff --git a/tests/test_d3d12_guid_sites.py b/tests/test_d3d12_guid_sites.py new file mode 100644 index 000000000..5e44b5d50 --- /dev/null +++ b/tests/test_d3d12_guid_sites.py @@ -0,0 +1,191 @@ +"""tools/d3d12_guid_sites.py on hand-built PE32+ images (no game files, no SDK needed).""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import uuid + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import d3d12_guid_sites as sites # noqa: E402 + +QUEUE = uuid.UUID("0ec870a6-5d7e-4c22-8cfc-5baae07616ed") +RESOURCE = uuid.UUID("696442be-a72e-4059-bc79-5b5c98040fad") +UNKNOWN = uuid.UUID("12345678-4242-4343-8444-555555555555") +KNOWN = {"ID3D12CommandQueue": QUEUE, "ID3D12Resource": RESOURCE} + + +def build_rdata(rdata: bytes, imports=None): + """The .rdata body, its import directory RVA and its IAT slot RVAs; pe32plus places it at 0x2000. + + imports: {dll_name: [function names, ...]} placed inside the body after `rdata`. + """ + body = bytearray(rdata) + imports = imports or {} + rdata_rva = 0x2000 + iat_slots = [] + + def put(blob, align=8): + while len(body) % align: + body.append(0) + at = len(body) + body.extend(blob) + return rdata_rva + at + + imp = 0 + descriptors = [] + for dll, funcs in imports.items(): + thunks = [put(struct.pack(" [ ...] [--header PATH/d3d12.h] + [--known NAME=GUID ...] [--json OUT] + +Without --header it takes d3d12.h from the newest Windows SDK under "Windows Kits\\10\\Include". +""" +from __future__ import annotations + +import argparse +import glob +import json +import os +import re +import struct +import sys +import uuid + +MIDL = re.compile(r'MIDL_INTERFACE\("([0-9a-fA-F-]{36})"\)\s*\n\s*(ID3D12\w+)') + +# RIP-relative operand: REX.W(le) 0x8D/0x8B, modrm mod=00 rm=101; instruction length 7 (disp32). +_LEA, _MOV = 0x8D, 0x8B +REXES = (0x48, 0x49, 0x4C, 0x4D) # REX.W with optional R/B; mod=00 rm=101 stays RIP-relative + + +def default_header() -> str | None: + root = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), + "Windows Kits", "10", "Include") + found = glob.glob(os.path.join(root, "*", "um", "d3d12.h")) + + def version(path: str) -> tuple[int, ...]: + name = os.path.basename(os.path.dirname(os.path.dirname(path))) + return tuple(int(p) for p in name.split(".") if p.isdigit()) + + return max(found, key=version) if found else None + + +def read_iids(header: str) -> dict[str, uuid.UUID]: + with open(header, encoding="utf-8", errors="replace") as f: + text = f.read() + return {name: uuid.UUID(guid) for guid, name in MIDL.findall(text)} + + +class Image: + """A parsed PE32/PE32+ image: sections, the image base and the import directory.""" + + def __init__(self, data: bytes): + self.data = data + if data[:2] != b"MZ": + raise ValueError("not an MZ image") + pe = struct.unpack_from(" int | None: + for s in self.sections: + if s["va"] <= rva < s["va"] + max(s["vsize"], s["rsize"]): + off = s["raw"] + rva - s["va"] + return off if off < len(self.data) else None + return None + + def read(self, rva: int, size: int) -> bytes | None: + off = self.rva_to_offset(rva) + return self.data[off:off + size] if off is not None else None + + def initialized(self) -> list[dict]: + return [s for s in self.sections if s["rsize"] > 0] + + def section_of(self, rva: int) -> dict | None: + for s in self.initialized(): + if s["va"] <= rva < s["va"] + max(s["vsize"], s["rsize"]): + return s + return None + + def imports(self) -> list[tuple[str, list[str]]]: + """(dll, imported names or "#ordinal") from the import directory.""" + out: list[tuple[str, list[str]]] = [] + imp_rva = self.dirs[1][0] + if not imp_rva: + return out + pos = self.rva_to_offset(imp_rva) + width, flag = (8, 1 << 63) if self.pe32plus else (4, 1 << 31) + while pos is not None and pos + 20 <= len(self.data): + lookup_rva, _, _, name_rva, iat_rva = struct.unpack_from(" dict[int, tuple[str, str]]: + """RVA of every IAT slot -> (dll, import name); targets of `mov reg, [rip+...]` are matched here.""" + slots: dict[int, tuple[str, str]] = {} + imp_rva = self.dirs[1][0] + if not imp_rva: + return slots + pos = self.rva_to_offset(imp_rva) + width = 8 if self.pe32plus else 4 + while pos is not None and pos + 20 <= len(self.data): + lookup_rva, _, _, name_rva, iat_rva = struct.unpack_from(" bool: + """A plausible RFC-4122 GUID: version nibble 1-5, variant 10xx, and not all-zero/constant.""" + if len(blob) < 16 or blob[:4] == b"\0\0\0\0": + return False + if blob[:4] == b"DXBC": # an embedded shader container, whose header hashes parse as GUID-shaped + return False + version = blob[7] >> 4 + variant = blob[8] >> 6 + if version not in (1, 2, 3, 4, 5) or variant != 0b10: + return False + return len(set(blob)) > 6 # random data, not a fill pattern + + +def rip_refs(img: Image) -> list[tuple[int, int, int]]: + """(instruction RVA, target RVA, opcode) for every RIP-relative lea/mov in executable sections.""" + out: list[tuple[int, int, int]] = [] + for s in img.initialized(): + if not s["chars"] & 0x20000000: # IMAGE_SCN_MEM_EXECUTE + continue + blob = img.data[s["raw"]:s["raw"] + s["rsize"]] + for i in range(len(blob) - 6): # a 7-byte RIP-relative instruction must fit entirely + if blob[i] not in REXES or blob[i + 1] not in (_LEA, _MOV): + continue + modrm = blob[i + 2] + if (modrm & 0xC7) != 0x05: # mod=00, rm=101 + continue + disp = struct.unpack_from(" list[tuple[int, bytes]]: + """(first instruction RVA, 16 bytes) of adjacent `movabs reg, imm64` pairs that inline a GUID. + + A compiler that materialises an IID without a constant pool writes its two halves as two 10-byte + `REX.W B8+r imm64` moves; the concatenation is the GUID a lea would otherwise point at. + """ + out: list[tuple[int, bytes]] = [] + for s in img.initialized(): + if not s["chars"] & 0x20000000: + continue + blob = img.data[s["raw"]:s["raw"] + s["rsize"]] + imm: list[tuple[int, bytes]] = [] + for i in range(len(blob) - 10): + if blob[i] == 0x48 and 0xB8 <= blob[i + 1] <= 0xBF: + imm.append((s["va"] + i, blob[i + 2:i + 10])) + for (rva1, first), (rva2, second) in zip(imm, imm[1:]): + if rva2 - rva1 > 32: # the two halves are written together + continue + joined = first + second + if guid_shaped(joined): + out.append((rva1, joined)) + return out + +def absolute_refs(img: Image) -> list[tuple[int, int]]: + """(location RVA, target RVA) for 8-byte aligned absolute pointers into the image's own data.""" + out: list[tuple[int, int]] = [] + if not img.pe32plus: + return out + lo = img.image_base + for s in img.initialized(): + blob = img.data[s["raw"]:s["raw"] + s["rsize"]] + for i in range(0, len(blob) - 8, 8): + value = struct.unpack_from(" bool: + """A plausible `D3D12_COMMAND_QUEUE_DESC` {Type, Priority, Flags, NodeMask}.""" + if blob == b"\0" * 16: # a referenced zero block is padding, not a description + return False + t, p, flags, node = struct.unpack_from(" 15 or node > 1: # console list types stay small; a title queues on one node + return False + if p not in (0, 1, 2, 0xFFFFFFFF, 0x80000000): # NORMAL/HIGH/GLOBAL_REALTIME/"-1"/OR-ed + return False + return flags <= 0x3 # D3D12_COMMAND_QUEUE_FLAG_NONE/ALLOW_GPU_TIMEOUT/DISABLE_GPU_TIMEOUT + + +def scan(path: str, known: dict[str, uuid.UUID]) -> dict: + with open(path, "rb") as f: + data = f.read() + img = Image(data) + by_value = {} + for name, guid in known.items(): + by_value.setdefault(guid.bytes_le, []).append(name) + + def constant_at(rva: int) -> tuple[bytes, str] | None: + """The 16 bytes at `rva` when it sits in an initialized, non-executable section (a constant pool).""" + s = img.section_of(rva) + if s is None or s["chars"] & 0x20000000: + return None + blob = img.read(rva, 16) + return (blob, s["name"]) if blob is not None else None + + candidates: dict[bytes, dict] = {} + leas = 0 + iat_loads: list[tuple[int, str, str]] = [] + slots = img.iat_slots() + for insn_rva, target, opcode in rip_refs(img): + if opcode == _MOV: + if target in slots: + dll, name = slots[target] + iat_loads.append((insn_rva, dll, name)) + continue + leas += 1 + at = constant_at(target) + if at is None or not guid_shaped(at[0]): + continue + entry = candidates.setdefault(at[0], {"refs": [], "known": None, "section": at[1], "rva": target}) + entry["refs"].append(insn_rva) + if at[0] in by_value: + entry["known"] = by_value[at[0]] + for loc_rva, target in absolute_refs(img): + at = constant_at(target) + if at is None or not guid_shaped(at[0]): + continue + entry = candidates.setdefault(at[0], {"refs": [], "known": None, "section": at[1], "rva": target}) + entry["refs"].append(loc_rva) + if at[0] in by_value: + entry["known"] = by_value[at[0]] + for rva, joined in movabs_pairs(img): + entry = candidates.setdefault(joined, {"refs": [], "known": None, "section": "movabs", "rva": rva}) + entry["refs"].append(rva) + if joined in by_value: + entry["known"] = by_value[joined] + lea_targets = {t for _, t, op in rip_refs(img) if op == _LEA} + descs = [] + for s in img.initialized(): + if s["chars"] & 0x20000000: # code sections are not queue descriptions + continue + blob = img.data[s["raw"]:s["raw"] + s["rsize"]] + for i in range(0, len(blob) - 16, 4): + if s["va"] + i in lea_targets and queue_desc_shaped(blob[i:i + 16]): + t, p, flags, node = struct.unpack_from(" int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("images", nargs="+") + ap.add_argument("--header", help="d3d12.h to read the known IIDs from (default: newest Windows SDK)") + ap.add_argument("--known", action="append", default=[], metavar="NAME=GUID", + help="a known GUID the header does not list, e.g. a console IID (repeatable)") + ap.add_argument("--json", help="also write the result here") + args = ap.parse_args(argv) + + known: dict[str, uuid.UUID] = {} + header = args.header + if header is None: + header = default_header() + if header and os.path.isfile(header): + known.update(read_iids(header)) + for pair in args.known: + name, _, value = pair.partition("=") + try: + known[name] = uuid.UUID(value) + except ValueError: + print(f"ERROR: --known expects NAME=GUID, got {pair!r}", file=sys.stderr) + return 2 + print(f"{len(known)} known GUIDs" + (f" from {header}" if header else "")) + + results = [] + for path in args.images: + try: + r = scan(path, known) + except (ValueError, struct.error) as e: + print(f"== {os.path.basename(path)}: skipped ({e})") + continue + results.append(r) + print(f"== {r['image']}: {r['lea_count']} RIP-relative lea, " + f"{len(r['guid_candidates'])} GUID-shaped referenced constants, " + f"{len(r['queue_descs'])} referenced queue-desc-shaped windows") + for c in r["guid_candidates"]: + names = ", ".join(c["known"]) if c["known"] else "UNKNOWN" + print(f" {c['value']} x{c['refs']} at {c['section']} rva 0x{c['rva']:x} {names}") + for w in r["iat_guid_loads"]: + print(f" IAT GUID load at rva 0x{w['rva']:x}: {w['dll']}!{w['name']}") + for d in r["queue_descs"]: + print(f" queue-desc-shaped window at rva 0x{d['rva']:x}: Type={d['type']} " + f"Priority={d['priority']} Flags={d['flags']} NodeMask={d['node']}") + for line in r["imports_of_note"]: + print(f" GUID-named imports: {line}") + if args.json: + with open(args.json, "w", encoding="utf-8", newline="\n") as f: + json.dump({"known": len(known), "images": results}, f, indent=2) + f.write("\n") + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) -- cgit v1.2.3 From a6f9bc4b24a1d839c94f9fb5c598f3b7b85b9f44 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Sun, 22 Nov 2026 19:54:26 -0500 Subject: slot 67: the description pinned from the DLL's code, a test built the DLL's way, every failed call logged A tester on #3951 saw a slot-67 lookup miss with the real FidelityFX DLL where the base build had none, and read it as the proxy taking one program's kind 6 with another program's kind 0. Pinned from the DLL's code and run on all 29 payloads: its FSPX reader (0x1a20) and the same loop inline for a container store kinds 0, 1, 6 and 7 in four pairs from one payload, and the pipeline function copies them to +0x08, +0x18, +0x28 (the kind-6 copy, with kind 6's own size at +0x30) and +0x38 of the description. That is the layout the proxy reads, and code and state of one call always come from the same program. A harness that maps the DLL without running it, calls its reader on each payload and builds the description that way resolves every translated program to its own entry through slot 67 on the Vulkan device (26 of 29 on main aa2988cc; the other 3 are refused), on llvmpipe, the integrated GPU and the RX 7900 XTX. So the proxy does not mix programs. What fits the report: with slot 11 answered, the DLL goes on to its next pipeline, which that translation (20 of 29) does not have; only the first call of a slot is announced, so the miss read as the first call's. - d3d12_xs_device.cpp: every failed slot-67 call is logged with its number and the four sizes. - d3d12_fspx_compute_test: dll_slot67 builds the description from a container's own directory the way the DLL does (reader pair order, pointers into the payload, kind 6 copied into a 256-rounded buffer padded with 0xcc); each program resolves to its own translation with its own state. A proxy that read kind 0 from +0x18 or kind 6 with the rounded size fails the test. - docs/fspx.md, d3d12_command_objects.md, d3d12_vulkan.md: how the layout was pinned, and what happens when a later program is not translated. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_command_objects.md | 6 +++ docs/d3d12_vulkan.md | 3 ++ docs/fspx.md | 24 +++++++++++ runtime/shims/d3d12_xs_device.cpp | 17 +++++++- runtime/test/d3d12_fspx_compute_test.cpp | 74 ++++++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 1 deletion(-) (limited to 'docs/d3d12_command_objects.md') diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 82ead294c..02d62345c 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -470,6 +470,12 @@ vtable pointer of a public object. the description (always, from this DLL) the proxy passes all four pairs on as one `FSPX` payload, checking each pair before reading it. The Vulkan device then finds the translated module by `fspx_code_sha256` and `fspx_state_sha256` ([fspx.md](fspx.md), "Build and run-time lookup"), for the programs the build translated. + - **The layout is pinned from the DLL's code:** its FSPX reader (`0x1a20`), the same loop inline for a container, + and the copy into the description. The kind 0 and kind 6 of one call come from the same payload. With the + reader run on all 29 programs, every translated program resolves to its own entry ([fspx.md](fspx.md), "How + the table was pinned"). + - **A failed call is logged with its number** (`slot 67 call N failed`). The DLL creates its pipelines one after + another, so a miss is not necessarily the first call's. - **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 7778136c3..5cc6568ac 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1110,6 +1110,9 @@ and any validation error fails them. the bare program is refused as ambiguous; - slot 67 with all four pairs picks by kind 0 too (one entry's module is missing on purpose, so the pick shows as `E_FAIL`), and four inconsistent pairs are refused before they are read; + - slot 67 with the description built the way the DLL builds it (`dll_slot67`: the reader's pair order over the + container's own directory, kinds 0, 1 and 7 pointing into the payload, kind 6 copied into a 256-rounded buffer + padded with `0xcc`) resolves each program to its own translation with its own state; - console slot 11 on a slot-67 and a slot-62 pipeline returns an object whose slot 3 points at the dword 0 and whose slot 4 gives 4 bytes; it releases to 0, and the pipeline's reference count is unchanged. - `d3d12_set0_compute_test`: set 0 from the compute bind point, through the proxy and D3D12 alone. The index entry diff --git a/docs/fspx.md b/docs/fspx.md index 8888e540b..88abdd84a 100644 --- a/docs/fspx.md +++ b/docs/fspx.md @@ -55,6 +55,30 @@ The size at `+0x30` is kind 6's own size, not the rounded allocation: the DLL ro `0x56d5`). So the bytes at `+0x28` with that size are exactly kind 6, and their SHA-256 is the key below. +**How the table was pinned** (read from the DLL's code with `objdump`; checked by running the DLL's reader on all 29 +payloads): +- **The reader (`0x1a20`).** It zeroes four (pointer, size) pairs, then stores kind 0 in pair 0, kind 1 in pair 1, + kind 6 in pair 2 and kind 7 in pair 3 (`0x1bcb` to `0x1bfb`). Each pointer points into the payload itself. +- **The container branch (`0x5510` to `0x55ea`).** For a `DXBC` container the pipeline function runs the same loop + inline over the `ACCC` part and fills the same four places. Unlike the reader, it does not zero the kind-1 and + kind-7 places first; all 29 payloads have both kinds. +- **The copy into the description (`0x567d` to `0x56d5`).** Pair 0 goes to `+0x08`, pair 1 to `+0x18`, the kind-6 + copy to `+0x28` with pair 2's size at `+0x30`, and pair 3 to `+0x38`. +- **Code and state come from one payload.** Kind 0 and kind 6 of one call therefore always belong to the same + program, so the run-time lookup by code key and state key (below) has the pairing the build gives it. +- **Run.** A harness mapped the DLL without running it and called its reader on each of the 29 payloads. It built the + description that way and called slot 67 on the Vulkan device with the 26 programs translated on `main` at + `aa2988cc`: + - all 26 resolve to their own entry with their own state, and the other 3 are refused with `E_INVALIDARG`; + - the same on llvmpipe, the Ryzen 9 7950X3D's integrated GPU and the RX 7900 XTX (Mesa 26.3.1, under Wine). + +`d3d12_fspx_compute_test` builds its slot-67 descriptions the same way, from a container's own directory. + +**What happens when a program is not translated.** The DLL creates its pipelines one after another as a dispatch +needs them. When one of them has no translation, slot 67 fails, and so does the slot-62 fallback with the same +container. The DLL then records the null pipeline and faults at `0x65ff`, as on a PC device. The proxy logs every +failed slot-67 call with its number (`slot 67 call N failed`), because only the first call of a slot is announced. + The DLL's own messages name that call `DeserializeComputePipelineStateX` and the path "ACO". When the call fails, the message says it falls back to "NewBE", and the DLL sets the environment variable `FFX_FSR4_XBOX_ACO_ACTIVE` to `0`. Its next pipeline call is slot 62 (measured in #864), so "NewBE" is inferred to be that path, the one a PC diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e69e0899a..79d7860c2 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1102,11 +1102,26 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const pc_desc.CS.pShaderBytecode = payload.data(); pc_desc.CS.BytecodeLength = payload.size(); } + pc_desc.NodeMask = 0; pc_desc.CachedPSO = {nullptr, 0}; pc_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; - return self->real->CreateComputePipelineState(&pc_desc, *riid, out); + // Every failed call is logged with its number: the DLL creates its pipelines one after the other, and only the + // first call of a slot is announced, so a miss on a later program would otherwise read as the first call's. + static std::atomic calls{0}; + const std::uint64_t call = calls.fetch_add(1, std::memory_order_relaxed) + 1; + const HRESULT hr = self->real->CreateComputePipelineState(&pc_desc, *riid, out); + if (FAILED(hr)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 67 call %llu failed with 0x%08lx (kind 0 %llu B, kind 1 %llu B, kind 6 %llu B, " + "kind 7 %llu B)\n", + static_cast(call), static_cast(hr), + static_cast(xbox_desc->kind0_size), + static_cast(xbox_desc->kind1_size), + static_cast(xbox_desc->kind6_size), + static_cast(xbox_desc->kind7_size)); + return hr; } HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp index bf440ce1c..b61659256 100644 --- a/runtime/test/d3d12_fspx_compute_test.cpp +++ b/runtime/test/d3d12_fspx_compute_test.cpp @@ -123,6 +123,58 @@ std::vector container(const std::vector& accc) { return out; } +// The slot-67 description built the way amd_fidelityfx_upscaler_xbox.dll builds it (docs/fspx.md, "How the DLL reads +// it", pinned from its code): +// - its FSPX reader (RVA 0x1a20, and the same loop inline for a container) zeroes four (pointer, size) pairs, walks +// the directory with the reader's bounds rules and stores kind 0 in pair 0, kind 1 in pair 1, kind 6 in pair 2 and +// kind 7 in pair 3, the last entry of a kind winning; the pointers point into the payload itself; +// - it copies kind 6 into an allocation rounded up to 256 bytes (here filled with 0xcc past the program, so a size +// taken from the allocation would show) and passes that copy with kind 6's own size; +// - it copies the pairs into the description in that order: pair 0 at +0x08, pair 1 at +0x18, the copy at +0x28, +// pair 3 at +0x38. +// So the test does not reuse the layout the proxy reads: it follows the DLL's reader over the payload's own directory. +struct DllSlot67 { + XboxNativeDesc desc{}; + std::vector copy; // the kind-6 copy (the DLL's XMemAlloc block) +}; + +DllSlot67 dll_slot67(ID3D12RootSignature* root, const std::vector& container_bytes) { + DllSlot67 out; + out.desc.root_signature = root; + const std::span payload = leonida::dxbc_part(container_bytes, "ACCC"); + const auto u32 = [&](std::size_t at) { + std::uint32_t v; + std::memcpy(&v, payload.data() + at, 4); + return v; + }; + if (payload.size() < 16 || std::memcmp(payload.data(), "FSPX", 4) != 0) return out; + const std::uint64_t total = std::min(u32(12), payload.size()); + const std::uint64_t end_dir = 16 + 16 * std::uint64_t(u32(8)); + if (end_dir > total) return out; + const void* pointer[4] = {}; + std::uint64_t size[4] = {}; + for (std::uint64_t at = 16; at < end_dir; at += 16) { + const std::uint32_t kind = u32(std::size_t(at)), offset = u32(std::size_t(at) + 4), + length = u32(std::size_t(at) + 8); + if (offset < end_dir || std::uint64_t(offset) + length > total) continue; + const int pair = kind == 0 ? 0 : kind == 1 ? 1 : kind == 6 ? 2 : kind == 7 ? 3 : -1; + if (pair < 0) continue; + pointer[pair] = payload.data() + offset; + size[pair] = length; + } + out.copy.assign((size[2] + 255) & ~std::uint64_t(255), 0xcc); + if (size[2]) std::memcpy(out.copy.data(), pointer[2], std::size_t(size[2])); + out.desc.kind0 = pointer[0]; + out.desc.kind0_size = size[0]; + out.desc.kind1 = pointer[1]; + out.desc.kind1_size = size[1]; + out.desc.kind6 = out.copy.data(); + out.desc.kind6_size = size[2]; + out.desc.kind7 = pointer[3]; + out.desc.kind7_size = size[3]; + return out; +} + std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); const auto fn = d3d12 ? reinterpret_cast( @@ -356,6 +408,28 @@ int main() { } } + // Slot 67 with the description built the way the DLL builds it (dll_slot67): each program resolves to its + // own translation with its own state. Program A (state 0x11) and program C with states 0x31 and 0x32 create a + // pipeline; C with 0x33 finds its own entry, whose module is missing (E_FAIL, not E_INVALIDARG); C with 0x11, + // a state nothing was translated for, is refused like any unknown program. + { + const auto slot67 = reinterpret_cast(slot(device.p, 67)); + const auto create = [&](const std::vector& box) { + const DllSlot67 call = dll_slot67(root.p, box); + Ref made; + const HRESULT hr = slot67(device.p, &call.desc, &pso_iid, reinterpret_cast(&made.p)); + if (FAILED(hr) && made.p) return E_UNEXPECTED; // a failure must leave no object + return hr; + }; + EXPECT(dll_slot67(root.p, container_a).desc.kind0_size == 28); // the builder found the entries + EXPECT(dll_slot67(root.p, container_a).copy.size() % 256 == 0); + EXPECT(create(container_a) == S_OK); + EXPECT(create(container(payload(code_c, 128, -1, 0x31))) == S_OK); + EXPECT(create(container(payload(code_c, 128, -1, 0x32))) == S_OK); + EXPECT(create(container(payload(code_c, 128, -1, 0x33))) == E_FAIL); + EXPECT(create(container(payload(code_c, 128, -1, 0x11))) == E_INVALIDARG); + } + // Refused with E_INVALIDARG, and no object: an untranslated program, bare and in a container; directories // whose kind-6 entry is out of bounds or missing; a container without ACCC; bytes without the prologue. { -- cgit v1.2.3 From 57c175391db7b70ac2ec8dc7a7bf04afec52cb88 Mon Sep 17 00:00:00 2001 From: ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:42:53 -0500 Subject: Revert #2490: its console-ABI list proxy breaks run_tiny_frame (please rebase and split) With it, d3d12_xs reads list slot 48 as the console's IASetVertexBuffers, so the PC-shaped fixture list's ClearRenderTargetView never runs and Close fails. The branch also changes runtime/src/pe_loader.cpp and carried committed conflict markers in docs/fssm_crosscheck.md. Its docs rows go with it. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/README.md | 4 - docs/boot.md | 21 +- docs/console_libraries.md | 224 -------- docs/d3d12_command_objects.md | 7 +- docs/d3d12_xs_console_abi.md | 271 ---------- docs/design.md | 4 +- docs/fssm_crosscheck.md | 3 +- docs/hello_pixels.md | 53 -- docs/import_routing.md | 82 --- runtime/CMakeLists.txt | 2 +- runtime/shims/d3d12_xs_device.cpp | 768 +--------------------------- runtime/shims/d3d12_xs_device.h | 38 +- runtime/shims/library_loader.cpp | 87 +--- runtime/shims/registry.cpp | 27 +- runtime/shims/shims.h | 8 - runtime/src/pe_loader.cpp | 82 +-- runtime/src/pe_loader.h | 4 - runtime/test/d3d12_buffer_uav_test.cpp | 2 +- runtime/test/d3d12_compute_test.cpp | 2 +- runtime/test/d3d12_debug_markers_test.cpp | 7 +- runtime/test/d3d12_descriptor_test.cpp | 2 +- runtime/test/d3d12_draw_test.cpp | 2 +- runtime/test/d3d12_f16_halves_test.cpp | 2 +- runtime/test/d3d12_first_light_test.cpp | 2 +- runtime/test/d3d12_fspx_compute_test.cpp | 2 +- runtime/test/d3d12_geometry_test.cpp | 2 +- runtime/test/d3d12_m2_formats_test.cpp | 2 +- runtime/test/d3d12_m2_textured_test.cpp | 2 +- runtime/test/d3d12_m3_frame_test.cpp | 2 +- runtime/test/d3d12_m4_compute_test.cpp | 2 +- runtime/test/d3d12_msaa_draw_test.cpp | 2 +- runtime/test/d3d12_present_test.cpp | 2 +- runtime/test/d3d12_set0_compute_test.cpp | 2 +- runtime/test/d3d12_subgroup_test.cpp | 4 +- runtime/test/d3d12_translated_draw_test.cpp | 2 +- runtime/test/d3d12_vulkan_device_test.cpp | 13 +- runtime/test/loader_test.cpp | 17 - runtime/test/queue_proxy_test.cpp | 30 +- runtime/test/unimplemented_policy_test.cpp | 13 - runtime/test/xbox_present_test.cpp | 2 +- runtime/test/xs_proxy_mock_test.cpp | 241 +-------- tests/semantic/test_alu_int_misc.py | 90 ---- tests/semantic/test_scalar_cmpk_wqm.py | 210 -------- tests/semantic/test_valu_f16_trans.py | 197 ------- tests/semantic/test_valu_f32_unary.py | 212 -------- tests/test_hello_pixels.py | 109 ---- tests/test_import_inventory.py | 435 ---------------- tests/test_make_game_shader_state.py | 412 --------------- tests/test_run_gpu_tests_helpers.py | 236 --------- tests/test_viewer_serve.py | 171 ------- tests/test_wave64_halves_operands.py | 197 ------- tools/hello_pixels.py | 347 ------------- tools/import_inventory.py | 502 ------------------ 54 files changed, 104 insertions(+), 5060 deletions(-) delete mode 100644 docs/console_libraries.md delete mode 100644 docs/d3d12_xs_console_abi.md delete mode 100644 docs/hello_pixels.md delete mode 100644 docs/import_routing.md delete mode 100644 tests/semantic/test_scalar_cmpk_wqm.py delete mode 100644 tests/semantic/test_valu_f16_trans.py delete mode 100644 tests/semantic/test_valu_f32_unary.py delete mode 100644 tests/test_hello_pixels.py delete mode 100644 tests/test_import_inventory.py delete mode 100644 tests/test_make_game_shader_state.py delete mode 100644 tests/test_run_gpu_tests_helpers.py delete mode 100644 tests/test_wave64_halves_operands.py delete mode 100644 tools/hello_pixels.py delete mode 100644 tools/import_inventory.py (limited to 'docs/d3d12_command_objects.md') diff --git a/README.md b/README.md index fab7eb14b..b73800119 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ work on booting can start as soon as one is available to a developer. | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Controllers through a GameInput shim on SDL3 (any controller SDL supports, rumble, DualSense trigger effects and lightbar; built when SDL3 is installed or with `-DLEONIDA_SDL3_FETCH=ON`, [notes](docs/gameinput.md)). `--trace-d3d12` logs every D3D12 call and its outcome for the first boot. Untested against the real executable | -| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md), [console ABI](docs/d3d12_xs_console_abi.md)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md)) | | Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists and bundles, fences, descriptor heaps, committed, placed and reserved resources (1D, 2D, 3D and cube textures), render-target and depth views, texture views and samplers (they go into the bindless set), buffer UAVs (written as address descriptors), root signatures, graphics (vertex, pixel, geometry) and compute pipelines, pipeline libraries, command signatures and query heaps. Draws (MSAA included), dispatches and indirect dispatches, barriers, clears, uploads, copies (BC included), colour and depth resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, as do DXGI swapchains and `PresentX` planes. Tested by contributors on NVIDIA, AMD and Intel GPUs ([#166](https://github.com/ItsNotRexed/Leonida/issues/166)). Not yet: mesh-shader draws, the draw state of indirect draws, stream output, and anything checked against the real executable ([plan](docs/d3d12_vulkan.md)) | | Ray tracing (BVH) | ⚠️ In progress. `BuildRaytracingAccelerationStructure` builds BLASes and TLASes on the GPU in the console's XDXR BVH4 layout (the default; `LEONIDA_RT_AS=khr` uses Vulkan's own acceleration structures instead), which the translated shaders walk themselves through `image_bvh_intersect_ray` (all four triangle node types, TRI0-TRI3, with the barycentric remap byte); the GPU builder writes TRI0 leaves. Updates refit instead of rebuilding, and clone, compaction and the compacted/current postbuild sizes work; checked against a CPU reference on synthetic scenes. The build descriptions are recovered from the package's `XboxBvhBuilder.dll` ([notes](docs/xdxr.md)). The game's `*_bvh4.rpf` packs are measured: offline-built, dehydrated BLASes that rehydrate through that DLL with their geometry from the drawables in `levels.rpf` (measured on 8 of the 10 sampled BLAS; [notes](docs/bvh.md)). Not done in the builder: TRI1 pairing, BOX16 nodes, serialization. Open: whether the game rehydrates the packs or rebuilds them ([#313](https://github.com/ItsNotRexed/Leonida/issues/313)) | | Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists and bundles, fences, descriptor heaps, committed, placed and reserved resources (1D, 2D, 3D and cube textures), render-target and depth views, texture views, buffer UAVs and samplers (they go into the bindless set), root signatures, graphics (vertex, pixel, geometry) and compute pipelines, pipeline libraries, command signatures and query heaps. Draws (MSAA included), dispatches and indirect dispatches, barriers, clears, uploads, copies (BC included), colour and depth resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, as do DXGI swapchains and `PresentX` planes. Tested by contributors on NVIDIA, AMD and Intel GPUs ([#166](https://github.com/ItsNotRexed/Leonida/issues/166)). Not yet: mesh-shader draws, the draw state of indirect draws, stream output, and anything checked against the real executable ([plan](docs/d3d12_vulkan.md)) | diff --git a/docs/README.md b/docs/README.md index f9695b486..1fe20c5bf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -66,11 +66,8 @@ method, scope and caveats. No game data is included. | [d3d12_xs_surface.md](d3d12_xs_surface.md) | The 116-slot `d3d12_xs.dll` export surface; 83/83 standard GUIDs match the PC SDK. | | [xdxr.md](xdxr.md) | `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) from `XboxBvhBuilder.dll`'s reads; stream records' offsets and defaults; offline statistics not in the package. | | [d3d12_command_objects.md](d3d12_command_objects.md) | Measured command queue/list/fence/`PresentX` surface; verified vs prior art vs open. | -| [d3d12_xs_console_abi.md](d3d12_xs_console_abi.md) | The D3D12.X console ABI the `d3d12_xs` shim must reproduce: device/queue/list vtable slots, command-list object fields and record encodings, root-argument SGPR rules, unified memory; sibling-layer measurements marked unverified here. | | [xbox_d3d12_xs.md](xbox_d3d12_xs.md) | The `d3d12_xs` graphics ABI quoted from Microsoft's public GDK reference: root signatures, state objects, DXIL libraries, hit groups, shader cache sessions; which pages are missing or NDA-gated. | | [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. | -| [console_libraries.md](console_libraries.md) | The console-DLL surface a title can import (`d3d12_xs`, `xgameruntime`, `xmem`, `gameinput`, `xaudio2_9`, `dstorage_xs`, `xg_xs`, `AcpHal`, `chad`/`xapu`/`xcrdapi`): which are shimmed, classified or unbound. | -| [import_routing.md](import_routing.md) | The bind order (shim → bundled → host → unimplemented), `owns_dll` and the pseudo-handle path, per-DLL outcome. | | [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. | | [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | | [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | @@ -87,7 +84,6 @@ method, scope and caveats. No game data is included. | [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the one rule still missing. | | [shader_library.md](shader_library.md) | The pipeline library in `shaders.rpf`'s zlib part, which the carve doesn't read: 25,471 graphics and 2,693 compute pipeline records (stage slots: PS, VS, MS) and 21,522 native programs, 21,509 of them pipeline builds of 6,522 carved shaders (named by their `HASH` digest); `tools/shader_library.py`. | | [shader_inputs.md](shader_inputs.md) | Inputs that specific game shaders need to be right, as a first check for a black frame or a device-lost: the studio-shot lighting shader's 512-byte light records, eight-light loop, plane count at +0x4C (#1892 said +0x40), profile table and shadow-strength byte; the ACES LUT bakes' two tone-curve splines (reference order at +0x00, points-first at +0x70 behind the +0x118 switch), the +0x13C luminance mode and the quasi-log addressing (#1896); the sky LUT order and the +0xD0 dword that picks RGB9E5 or float outputs (#1897); the shared atmosphere constant buffer, its table slots (+0x220, +0xC60) and the layout with the two scale-height dwords no pass consumes (#3990). | -| [hello_pixels.md](hello_pixels.md) | The package-free sibling: a synthetic quad drawn through the same `vk_harness` mesh mode, shaders hand-written in SPIR-V assembly; `tools/hello_pixels.py` checks coverage and probe pixels against a closed form. | | [sandbox.md](sandbox.md) | Placed world props through one translated VS/PS pair with a real camera, TTPF albedo and the game's sampler: 442 of 446 draws textured; fly/walk/drive window, `tools/sandbox.py --check`. | | [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. | | [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. | diff --git a/docs/boot.md b/docs/boot.md index 62824b588..b6708fdc3 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -1,23 +1,8 @@ # First boot: the runbook and the two traces -**Status: first run done, on the only executable obtained so far.** A `game_scarlett_master.exe` (2,725,424 bytes) -reached the loader from outside the test corpus and ran end to end: dry-run mapped it at its preferred base with -every import bound (11 shim / 164 host, 0 unimplemented), `--init` ran its three TLS callbacks, and `--run` ran its -entry point to a clean `exit 0`. Its debug output identifies it as a **packaging verification probe, not the -engine** — it scans a payload root and compares file/byte/archive counts against a manifest. With the probe's own -`GetModuleFileNameW` answered for the mapped image (see below), run against the 1.0.2.1 payload it verified -104/104 files, 223,534,748,018 bytes, rpf 22/22, ttpf 57/57, png 5/5, dll 16/16, bad magic 0: **verdict PASS**. -The engine binary itself still is not in the corpus (RT-5), so the D3D12 half of this page is unexercised. Nothing -here quotes game data; a real trace stays on the player's machine. - -The package's own metadata agrees: `MicrosoftGame.Config` declares `Identity Name="GTA6.Probe.PC"` and its -`ExecutableList` names `game_scarlett_master.exe` as the **only** executable, so this payload is a packaging -verification build that carries the real payload's shape (its counts match the probe's manifest exactly) rather -than a retail dump missing its engine. All eleven bundled DLLs also initialise cleanly through `gta6rt --init`. - -One shim gap the probe exposed, now closed: `GetModuleFileName` was host-bound, so a mapped image asking for its -own path got `gta6rt.exe`'s; the bundled-module ops now expose the main image and each module's load path, and -`GetModuleHandle(nullptr)`/`GetModuleFileNameA/W` answer for mapped images first. +**Status: prepared, not yet run against the retail executable.** The package in the repository's test corpus does +not contain `game_scarlett_master.exe` (RT-5), so this page is the procedure and the trace tool for the day it +arrives. Nothing here quotes game data; a real trace stays on the player's machine. ## 1. What the first boot produces diff --git a/docs/console_libraries.md b/docs/console_libraries.md deleted file mode 100644 index cce2facef..000000000 --- a/docs/console_libraries.md +++ /dev/null @@ -1,224 +0,0 @@ -# Console libraries: what the console build can import, and how the loader answers - -Status: catalogue, sourced. This page lists the console-only or console-flavoured DLLs an Xbox -Series title's imports can name, what is measured about each one's export surface, and what -`gta6rt` does with each today. It is the module-level counterpart to -[runtime_imports.md](runtime_imports.md) (what the 16 shipped DLLs import) and to -[d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) (the measured ABI inside -the main one, `d3d12_xs.dll`). - -Basis tags: - -- **This repo** — verifiable in this tree: a `SHIM_TABLE` in `runtime/shims/*.cpp`, the - `classify()` list in `runtime/shims/registry.cpp`, the binding order in - `runtime/src/pe_loader.cpp`, or a measurement recorded in another page here. -- **Sibling-layer measurement** — a fact folded in from `d3d12_vulkan.md` §7, measured elsewhere - by running the console DLLs or a retail title behind a compatibility layer. Paraphrased, not - re-measured here; no external repository is named on this page. - -Scope limit: the game executable is not in the package, so its own import table is unmeasured. -The list below is the surface a console title *can* name — from sibling-layer inventories of the -console DLLs and from one retail title's run — not a claim about what this title does. - -## 1. How an import binds today - -`Loader::resolve` in `runtime/src/pe_loader.cpp` binds each import in a fixed order (**this -repo**): - -1. **Shim registry** — `rt::shims::find(dll, name)`. Ordinal imports look up `"#N"`, so a shim - serves an ordinal import only if its table carries the `"#N"` spelling. -2. **Bundled module** — a DLL of the same name in `--game-dir`, mapped by the same loader (the - `module` count of the dry run; the CRT families are deliberately excluded and always take the - host copy). -3. **Host** — `LoadLibraryEx` on `System32` plus `GetProcAddress`, by name or ordinal. -4. **Unimplemented thunk** — a generated stub whose behaviour `LEONIDA_UNIMPLEMENTED` sets - (`log`/`fail`/`stop`; see - [runtime_imports.md](runtime_imports.md#when-an-unimplemented-import-is-called)). Under `fail`, - `classify()` in `runtime/shims/registry.cpp` decides by DLL and name which imports return - `E_NOTIMPL`. - -A module the registry serves at all and that is not a host DLL is **owned** (`owns_dll`): a -title's `LoadLibrary`/`GetModuleHandle` on it gets a pseudo-handle and its `GetProcAddress` -resolves through the registry by name or `"#N"`, with unknown names returning -`ERROR_PROC_NOT_FOUND` -([runtime_imports.md](runtime_imports.md#run-time-loaded-modules)). Owned today: -`d3d12_xs.dll`, `xgameruntime.dll`, `xmem.dll` and `gameinput.dll` — the modules with a -`SHIM_TABLE` entry. - -The registry also holds tables under `kernel32.dll`, `kernelbase.dll`, the `api-ms-*` sets, -`msvcrt.dll` and `ucrtbase*.dll` (file system, library loader, process entry/exit). Those are -host DLLs a few functions are replaced on, not owned console modules, so they are not in the -list below. - -## 2. The modules - -| Module | What it is | Leonida today | Status | -|---|---|---|---| -| `d3d12_xs.dll` | Console D3D12 runtime front end | 4 names registered | partial shim | -| `xgameruntime.dll` | GDK runtime (task queues, users, store, packaging) | 39 names registered; 2 impl classes | partial shim | -| `xmem.dll` | Console tracked allocator / virtual-memory API | all 4 measured imports implemented | shimmed | -| `gameinput.dll` | GameInput v0, controller input | `GameInputCreate` registered (SDL3 build) | shimmed | -| `xaudio2_9.dll` | Console XAudio2 2.9 | no table; host binds it by ordinal | classified only | -| `dstorage_xs.dll` | Console DirectStorage | no table; `DStorageGetFactory` classified | classified only | -| `xg_xs.dll` | Texture layout helpers | nothing | unhandled | -| `AcpHal.dll` | Audio co-processor HAL | nothing | unhandled | -| `chad`, `xapu`, `xcrdapi`, `*legacy` | DSP, APU and card-API modules; names only | nothing | unhandled | - -### `d3d12_xs.dll` - -The console D3D12 runtime's front end: a thin DLL that loads the user-mode driver, which owns the -device and command objects (**sibling-layer measurement**; -[d3d12_xs_surface.md](d3d12_xs_surface.md) records the reported 116-export surface — 23 functions -plus 93 GUID data exports — and which of the 83 standard GUIDs match the PC SDK). Beyond the -standard `D3D12*` names its exports include `D3D12XboxCreateDevice` — the device entry point, call -shape `(adapter, params, riid, out)` with a 24-word params block that is only logged — -`D3D12XboxCreateSyntheticDevice` and `D3D12XboxSetProcessDebugFlags` (**sibling-layer -measurement**). - -Leonida registers four names (**this repo**, `runtime/shims/d3d12_xs.cpp`): -`D3D12SerializeVersionedRootSignature`, `D3D12SerializeRootSignature` and -`D3D12CreateRootSignatureDeserializer`, each forwarded to the host `d3d12.dll` after the Xbox -high flag byte is cleared on a copy; and `D3D12XboxCreateDevice`, which returns an Xbox-ABI proxy -over the PC `ID3D12Device` — or over the Vulkan-backed device with `LEONIDA_D3D12=vulkan` — with -the measured slot overrides (device slot 62 as compute-PSO creation, slot 76 as texture creation, -descriptor-heap start handles returned in RAX). The other 19 function exports, including -`D3D12XboxCreateSyntheticDevice` and `D3D12XboxSetProcessDebugFlags`, are not registered. -`classify()` marks the `D3D12Create*`/`D3D12Serialize*` families, the two debug entries and both -`D3D12XboxCreate*Device` names as HRESULT; `D3D12XboxSetProcessDebugFlags` is deliberately left -out because its return was not measured (**this repo**, `registry.cpp`). - -The COM surface behind the device — queue, command list, fence, `PresentX` — is vtable work, not -an import problem; it is tracked in [d3d12_vulkan.md](d3d12_vulkan.md), -[d3d12_command_objects.md](d3d12_command_objects.md) and -[d3d12_xs_console_abi.md](d3d12_xs_console_abi.md). The presentation core -(`runtime/shims/xbox_present.h`) is wired to the measured `PresentX` queue slots (30, or 32 on the -newer layout) in `d3d12_xs_device.cpp`; the plane and parameter struct layouts are still provisional. - -### `xgameruntime.dll` - -The GDK runtime. Not in the package; GDK titles reach it either by import or by `LoadLibraryW` + -`GetProcAddress` of `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, -`QueryApiImpl` and `UninitializeApiImpl`, which is how the package's `libHttpClient.GDK.dll` and -`XCurl.dll` do it (**this repo**, -[runtime_imports.md](runtime_imports.md#run-time-loaded-modules)). - -Leonida registers 38 names plus `GameInputCreate` (**this repo**, -`runtime/shims/xgameruntime.cpp`): the five loader entry points, -`XGameRuntimeInitialize`/`Uninitialize`, five `XSystem*` queries, three `XPackage*` queries, the -15-function `XTaskQueue*` set and the 8-function `XAsync*` set, both on the vendored -`third_party/xtaskqueue`. `QueryApiImpl` serves `XThreadingImpl` and `XErrorImpl` and answers -every other class with the documented "not provided" error so the first boot lists what is -missing. `classify()` marks the `XAsync*`/`XTaskQueue*`/`XUser*`/`XStore*`/`XGameSave*`/ -`XPackage*`/`XGameUi*` families as HRESULT except the members the public pages document as -`void`/`bool`/`int` (**this repo**, `registry.cpp`). - -### `xmem.dll` - -The console's tracked allocator. The only console module whose whole measured import surface is -implemented (**this repo**, `runtime/shims/xmem.cpp`): `XMemAlloc`/`XMemFree` on the 64-byte -aligned CRT heap, `XMemVirtualQuery(process, address, out64)` filling the -`MEMORY_BASIC_INFORMATION` prefix and zeroing the rest of the measured 64-byte output, and -`XMemGetWorkingSetStatistics(kind, out)` writing the process working set at +8 of the measured -output. All four names are exactly the set the package's DLLs import -([runtime_imports.md](runtime_imports.md)). - -A sibling layer additionally measured a title's physical-page calls on this module: 64 KiB pages, -with runs of consecutive pages mapping contiguously inside one unified region and scattered or -explicitly addressed mappings refused (**sibling-layer measurement**). Nothing in the package -imports them and no such names are registered; see section 3. - -### `gameinput.dll` - -GameInput v0. The console build's ordinal 1 is `GameInputCreate` (**sibling-layer -measurement**). - -Leonida registers `GameInputCreate` by name under both `gameinput.dll` and `xgameruntime.dll`: -the PC API lives in the former, the GDK links it through the latter, and which the executable -imports is unknown until it exists (**this repo**, `runtime/shims/gameinput.cpp`; the shim's API -surface is [gameinput.md](gameinput.md)). The registration is a name only — no `"#1"` entry — so -an ordinal-1 import would not hit the table (section 3). The shim is optional and built only with -SDL3; without it the import falls through to the host DLL or the unimplemented thunk as before. - -### `xaudio2_9.dll` - -Console XAudio2 2.9. Ordinal 1 is `XAudio2Create` (**sibling-layer measurement**). Voices accept -the console formats — XMA/XMA2 and an Opus format tag `0x704F` — and a `CO_E_NOTINITIALIZED` -from the system XAudio2 is retried after `CoInitializeEx` on the calling thread; forwarding to -the system XAudio2 2.9 works with those two quirks (**sibling-layer measurement**). - -Leonida has no table for it (**this repo**). The package's `Bink2Scarlett.dll` imports -`XAudio2_9.dll` ordinal 1 and the dry run binds it to the host copy by ordinal — 57 host, 0 -unimplemented ([movies.md](movies.md), [runtime_imports.md](runtime_imports.md)) — so creation by -ordinal resolves today, but the console voice formats and the retry quirk are not reproduced: a -voice created with XMA/XMA2 or `0x704F` would reach the host unremapped. `classify()` marks -`xaudio2_9.dll`/`xaudio2_9redist.dll` `XAudio2Create` as HRESULT — by name; the ordinal lookup -classifies as Other (**this repo**, `registry.cpp`). - -### `dstorage_xs.dll` - -Console DirectStorage; named in the sibling export inventory with no export list measured -(**sibling-layer measurement**). Leonida has no table; `DStorageGetFactory` is classified HRESULT -under both `dstorage.dll` and `dstorage_xs.dll` (**this repo**, `registry.cpp`). - -### `xg_xs.dll` - -Texture layout helpers. The sibling export inventory names `XGCreateTexture2DComputer` and -`XGComputeOptimalSwizzleMode` (**sibling-layer measurement**); prior-art text folded into -[d3d12_vulkan.md](d3d12_vulkan.md#35-root-signature-to-user-sgprs) also names -`XGComputeTexture2DLayout` as the module's untiling reference. Leonida has no table and no -classification (`xg_xs.dll!XGCreateTexture2DComputer` is pinned as Other in -`unimplemented_policy_test`; **this repo**). Nothing in the package imports it. - -### `AcpHal.dll` - -The audio co-processor HAL. The sibling export inventory names `ApuAlloc`, `ApuFree`, -`ApuMapVirtualAddress`, `ApuIsVirtualAddressValid`, `AcpHalCreate`, -`AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` (**sibling-layer measurement**). -Leonida has nothing for it (`acphal.dll!AcpHalCreate` is pinned as Other in -`unimplemented_policy_test`; **this repo**). - -### `chad`, `xapu`, `xcrdapi`, `*legacy` variants - -A retail title booted to its menu and lobby through console-library stand-ins, and its -console-only library set added `chad` (`XDsp*` exports), `xapu` (`XApu*` exports), `xcrdapi` and -`*legacy` DLL variants to the modules above (**sibling-layer measurement**). These are names -only: no export list, call shape or argument is measured, and Leonida has nothing for them. - -### Not console modules - -`d3d12.dll`, `dxgi.dll` and the `api-ms-*` sets are ordinary host bindings, not console modules. -The package's own middleware (`Bink2Scarlett.dll`, `XboxBvhBuilder.dll`, the FidelityFX pair, -`libHttpClient.GDK.dll`, `XCurl.dll`, the CRT set) binds as `module`, with the CRT families -deliberately host-bound; their imports are catalogued in -[runtime_imports.md](runtime_imports.md), not here. `xgs12_10.dll`, the user-mode driver a real -`d3d12_xs.dll` loads (recorded in [d3d12_vulkan.md](d3d12_vulkan.md) from prior-art text), is not -an import target a title names; Leonida replaces the whole stack rather than providing it. - -## 3. Gaps - -What a real title is known to call that Leonida does not yet cover (**sibling-layer -measurement** unless noted): - -- **The whole `xg_xs`, `AcpHal`, `dstorage_xs`, `chad`, `xapu`, `xcrdapi` and `*legacy` - surface.** No table, no classification. A retail run reached its menu and lobby with stand-ins - for them; for this title, whether any is imported at all is unknown until the executable exists. -- **The `xaudio2_9` quirks.** Creation by ordinal already binds to the host (**this repo**), but - the XMA/XMA2 and Opus `0x704F` voice formats and the `CoInitializeEx` retry would need a shim - that wraps or remaps — the host sees console format tags it does not know. -- **The unregistered `d3d12_xs` functions.** 4 of the 23 function exports are registered; the - rest — `D3D12XboxCreateSyntheticDevice`, `D3D12XboxSetProcessDebugFlags`, the `DXGIX*` - present/frame-notification functions, `D3D12UploadCustomMicrocodeX`-type console entries — - would hit the unimplemented thunk. Two are at least classified (`D3D12XboxCreate*Device` → - HRESULT under `fail`). -- **`xmem` physical-page calls.** A title's physical-page API uses 64 KiB pages and contiguous - mappings inside one unified region; the shim covers only the four allocator/query names the - package measured. -- **Ordinal-only registrations.** The shim tables serve names; an ordinal import is looked up as - `"#N"`. `gameinput.dll` and `xaudio2_9.dll` ordinal 1 are the measured console entry points, - and neither has a `"#1"` entry — a static ordinal import therefore skips the shim and binds to - the host DLL where one exists (as `xaudio2_9.dll!#1` does today; **this repo**), and a - `GetProcAddress` for ordinal 1 on an owned module returns `ERROR_PROC_NOT_FOUND`. -- **Run-time loading of bundled middleware.** A title that `LoadLibrary`s a package DLL such as - `Bink2Scarlett.dll` gets the host loader, which maps the Xbox build without the registry's - bindings for its own console imports — recorded as an open item in - [runtime_imports.md](runtime_imports.md#run-time-loaded-modules) (**this repo**). diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 00056e2da..5a214e325 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -375,10 +375,9 @@ section 3.5a), and the console list has methods well past the PC tail: 71, 73, 8 FSR DLL. Slot 148 matters beyond the builder: the address it returns is written by the CPU and passed unchanged to the GPU -as a root SRV address, so console upload memory has the same address for the CPU and the GPU. On a PC the two -address spaces differ, so `d3d12_xs_device.cpp` carves a bump arena out of persistently-mapped UPLOAD-heap -buffers: the title writes the mapped memory and the six root descriptor setters and the IA/SO view setters -translate the CPU pointer to the chunk's buffer device address before forwarding. +as a root SRV address, so console upload memory has the same address for the CPU and the GPU. A replacement must +return memory whose CPU pointer is also a valid GPU address (for this layer: inside the arena of +[d3d12_vulkan.md §3.3](d3d12_vulkan.md)). The function at `0xd580` uses the 71/73 pair instead of the slot-146 barrier when the byte at RVA `0xd773c` is set. That byte is one of seven bools at `0xd7738`–`0xd773e` in zero-initialised `.bss`. The only accesses to them in diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md deleted file mode 100644 index 39f570b28..000000000 --- a/docs/d3d12_xs_console_abi.md +++ /dev/null @@ -1,271 +0,0 @@ -# The D3D12.X console ABI: vtable slots, object fields and record encodings - -Status: measured-facts note, sourced. This page collects the Xbox Series (`d3d12_xs`) ABI facts a -replacement runtime must reproduce — vtable slot numbers, object field layouts and the inline -record encodings the console SDK writes into a command-list object — for the layers that are still -missing: command lists, root arguments, descriptor heaps and present. It complements -[d3d12_vulkan.md](d3d12_vulkan.md) (the Vulkan layer plan) and -[d3d12_command_objects.md](d3d12_command_objects.md) (what this package's own DLLs measure). - -Provenance rules for this page, stated once: - -- **Sibling layer** — measured by a sibling open-source layer on retail Series titles and - published as findings. Not independently reproduced here; treat every such claim as unverified - on this package. -- **Package** — measured on this package's shipped DLLs (`XboxBvhBuilder.dll`, - `amd_fidelityfx_upscaler_xbox.dll`); see - [d3d12_command_objects.md](d3d12_command_objects.md) §§3.3–3.5a. -- **SDK** — the public Windows SDK `d3d12.h` order, for contrast. -- **Unconfirmed** — consistent with the surrounding facts but not yet measured anywhere we can - check. - -All slot numbers below are absolute vtable indices including `IUnknown` (0–2) and the -`ID3D12Object`/`ID3D12DeviceChild`/`ID3D12Pageable` base slots, as in -[d3d12_command_objects.md](d3d12_command_objects.md) §2. - -## 1. Device (`ID3D12DeviceX` over the PC `ID3D12Device` layout) - -The console device keeps the PC slot order where measured, with extra console methods placed in -slots the PC chain uses for newer interfaces, plus a tail of console-only methods. Slots marked -**Package** were called by the shipped upscaler or BVH-builder DLLs with the stated shapes; the -rest are **Sibling layer** measurements. - -| Slot | Method | Evidence | -|---:|---|---| -| 8, 48 | `CreateCommandQueue` variants | Sibling layer | -| 9 | `CreateCommandAllocator` | Sibling layer | -| 10, 60 | `CreateGraphicsPipelineState` variants | Sibling layer | -| 12 | `CreateCommandList` | Sibling layer | -| 14 | `CreateDescriptorHeap` | Package + sibling layer | -| 15 | `GetDescriptorHandleIncrementSize` | Package + sibling layer | -| 17, 18, 19 | `CreateConstantBufferView` / `CreateShaderResourceView` / `CreateUnorderedAccessView` | Package + sibling layer | -| 22 | `CreateSampler` | Sibling layer | -| 23, 24 | `CopyDescriptors` / `CopyDescriptorsSimple` | Package + sibling layer | -| 25 | `GetResourceAllocationInfo` | Sibling layer | -| 29, 44 | `CreatePlacedResource` variants | Sibling layer | -| 38 | `GetCopyableFootprints` | Package + sibling layer | -| 41 | `CreateCommandSignature` | Sibling layer | -| 52 | `SetDebugFlags` | Sibling layer | -| 55 | derived pipeline state | Sibling layer | -| 56, 57, 66, 67 | serialize / deserialize pipeline state | Sibling layer; the package's upscaler calls 67 as `DeserializeComputePipelineStateX` (console desc, `IID_ID3D12PipelineState`) — Package | -| 61 | `CreateSamplerX` | Sibling layer | -| 62 | `CreateComputePipelineState` with two extra args: `(desc, NULL, NULL, riid, ppv)`; the PC interface presents `CreateStateObject` at this slot | **Confirmed here**: Package ([d3d12_vulkan.md](d3d12_vulkan.md) §7) + sibling layer | -| 73 | `CreateCommandListX` | Sibling layer | -| 74, 75 | register / unregister page pool | Sibling layer | -| 76 | `CreateCommittedResource`, same signature family as PC slot 27 | **Confirmed here**: Package ([d3d12_vulkan.md](d3d12_vulkan.md) §7) + sibling layer | -| 78–81 | frame pacing: `SetFrameIntervalX`, `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` | Sibling layer | -| 86 | `CreatePipelineStateX` | Sibling layer | - -The slot-76 console resource descriptor is **larger than 52 bytes** (sibling layer); the package's -upscaler DLL writes a 3 at offset +52 (Package). The `Layout` field sits at +44; value `0x101` -denotes a 2D texture ([d3d12_vulkan.md](d3d12_vulkan.md) §7; a sibling layer measured the same on -retail titles). - -### 1.1 Two runtime layouts - -Two console runtime layouts exist: an older game-OS layout and a newer one in which the queue and -list slots shift **+2** (sibling layer). Detection rule (sibling layer): if a fence object is -passed to queue slot 16/17, the layout is newer — on the older layout those slots are -`GetTimestampFrequency`/`GetClockCalibration`. Which layout this package's titles were built -against is **unverified here**. - -## 2. Descriptor heap - -| Slot | Fact | Evidence | -|---:|---|---| -| 9, 10 | `GetCPUDescriptorHandleForHeapStart` / `GetGPUDescriptorHandleForHeapStart` return the 8-byte handle in `rax` on console; the PC convention is a hidden out-pointer | **Confirmed here**: Package + sibling layer | - -Descriptor contents (sibling layer): CBV/SRV/UAV heaps use **32-byte slots** in unified memory — a -T# is 8 dwords, a V# 4 dwords, inside the 32-byte slot; sampler heaps use **16-byte slots**. The -CPU handle, GPU handle and the address in title memory are the same value. - -## 3. Resource - -| Slot | Fact | Evidence | -|---:|---|---| -| 11 | `GetGPUVirtualAddress` returns the title-memory address | Sibling layer; consistent with the package measurement that a CPU pointer from list slot 148 is passed unchanged as a root SRV GPU address ([d3d12_command_objects.md](d3d12_command_objects.md) §3.3a) | - -## 4. Command queue - -Measured queue slots (sibling layer); the queue follows the two-layout rule of §1.1: - -| Method | Older layout | Newer layout | -|---|---:|---:| -| `Signal` | 14 | 16 | -| `Wait` | 15 | 17 | -| `GetTimestampFrequency` | 16 | 18 | -| `GetClockCalibration` | 17 | — (shifted) | -| `GetDesc` | 18 | — (shifted) | -| `SignalX` | 23 | 25 | -| `PresentX` | 30 | 32 | - -Console-only queue methods the layer does not model should return `S_OK` and log the call: -title frame pacing flows through some of them (sibling layer). - -## 5. Command list object - -Measured by a sibling layer with a fake list — a 600-slot vtable of logging thunks — that let the -console SDK's inline writers record into the object (sibling layer; the package's BVH builder and -upscaler independently measured `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and -`+0x544` — Package, [d3d12_command_objects.md](d3d12_command_objects.md) §§3.4–3.5a). - -### 5.1 Object fields - -| Offset | Field | Evidence | -|---:|---|---| -| +0x00 | vtable pointer | Package + sibling layer | -| +0x18 | inline write pointer | Package + sibling layer | -| +0x28 | dispatch-record limit | Package + sibling layer | -| +0x30 | buffer end | Package + sibling layer | -| +0x140 | dirty flag byte, set when record header bits 31:30 are 0 | Package + sibling layer | -| +0x141 | pipeline flag byte, taken from bit 20 of the pipeline's record word at +0x20 | Package + sibling layer | -| +0x143 | flag byte; read by titles, written only by the runtime | Package (read 31+1 sites, never written) + sibling layer | -| +0x344 + 4·i | header word of root parameter *i* | Package + sibling layer | -| +0x544 | current pipeline record, 16 bytes | Package + sibling layer | - -### 5.2 Inline record encodings - -The console SDK's inline writers emit a record only while the write pointer is below the buffer -end; on a full buffer they call the vtable method the record stands for (Package + sibling layer). - -| Record | Encoding | Evidence | -|---|---|---| -| Pipeline | 28 B: `[PSO ptr][D3D12Core ptr][8 B flags][4 B]` | Package + sibling layer | -| Root parameter *i* | header at +0x344+4·i = `0xC0000000 \| i<<10` + const-offset·4 (bits 9:2) + `(count-1)<<16` | Sibling layer; header table itself confirmed Package | -| Root descriptor | header + 64-bit address = 12 B | Package + sibling layer | -| Root constants | one constant = 8 B; *n* constants = 4+4·*n* B | Package + sibling layer | -| Descriptor table | header + one 32-bit word = the 32-bit GPU address of the first descriptor | Sibling layer | -| `Dispatch` | `0x4002C400` (or `(0x1000BA00 \| flag) << 2`) followed by x, y, z = 16 B | Package + sibling layer | -| Indirect dispatch | `0x4003CC00`, 20 B total | Package (five-word form with W `0x8020`/`0x20`) + sibling layer | -| `IASetPrimitiveTopology` | `0xC000B600 \| topology` | Sibling layer | - -### 5.3 Method slots - -| Slot | Method | Evidence | -|---:|---|---| -| 9 | `Close` | Sibling layer | -| 10 | `Reset` | Sibling layer | -| 12 | `DrawInstanced` | Sibling layer | -| 13 | `DrawIndexedInstanced` | Sibling layer | -| 14 | `Dispatch` | Package + sibling layer | -| 15 | `CopyBufferRegion` | Package + sibling layer | -| 16 | `CopyTextureRegion` | Sibling layer | -| 17 | `CopyResource` | Sibling layer | -| 19 | `ResolveSubresource` | Sibling layer | -| 20 | `IASetPrimitiveTopology` | Sibling layer | -| 25 | `SetPipelineState` | Package + sibling layer | -| 26 | `ResourceBarrier` | Package + sibling layer | -| 32 | `SetDescriptorHeaps` | Package + sibling layer | -| 33 | `SetComputeRootSignature` | Package + sibling layer | -| 37, 39 | `Set*RootConstant(s)` | Package + sibling layer | -| 41, 43, 45 | `Set*RootDescriptor*` / table | Package + sibling layer | -| 48 | `IASetVertexBuffers` | Sibling layer | -| 51 | `ClearDepthStencilView` | Sibling layer | -| 80 | `ExecuteIndirect` | Sibling layer (note: the package measured slot 80 as a console-only call, a `Dispatch`-with-extra-word shape; slot assignments past 61 differ between the two sources — unconfirmed) | -| 83 | `CopyTextureRegionX` (older layout) | Sibling layer; the package measured a `CopyTextureRegion`-shaped call at slot 85 — consistent with the newer layout (+2) | -| 108 | `ResolveSubresourceRegion` | Sibling layer | -| 146 | enhanced `Barrier` | **Confirmed here**: Package (console slot 146 takes one `D3D12_BARRIER_GROUP`; PC equivalent is GCL7 slot 80) | -| 148 | `AllocateUploadMemory` `(size, alignment)`; the returned CPU pointer is the GPU address in unified memory | Package + sibling layer | - -Layout shift on the list tail (sibling layer): from `CopyTextureRegionX` on, methods sit two slots -later in the newer layout — newer→older pairs 85→83, 86→84, 87→85, 90→88, 91→89, 92→90, 95→93, -96→94. - -### 5.4 DMA command list - -| Slot | Method | Evidence | -|---:|---|---| -| 9 | `Close` | Sibling layer | -| 10 | `Reset` | Sibling layer | -| 11 | `CopyBufferRegion` | Sibling layer | -| 12 | `CopyTextureRegion` | Sibling layer | -| 13 | `CopyResource` | Sibling layer | - -## 6. Root arguments - -Sibling-layer measurements on retail titles: - -- **Compute.** The root arguments are a packed argument array in title memory; `io[0:1]` of the - dispatch record carries its address. -- **Graphics.** VS and PS receive root arguments in user SGPRs `s8..s31` — `s0..s7` are - driver-reserved; `s[4:5]` of a VS holds the fetch shader — 24 user SGPRs in total. Arguments - past those go through a table whose address is in `s[0:1]`. -- **Descriptor tables** take 4 bytes in the packed array: the record is the parameter header plus - one 32-bit word, the 32-bit GPU address of the first descriptor. -- **Root CBV.** The shader builds its own V#; a measured example sets `DST_SEL xyzw` plus the - format word from `s11`. - -## 7. Resource barriers (list slot 26) - -Sibling layer: console aliasing barriers behave as "any resource" barriers — both resource -pointers are null — where the PC API only allows those between placed or reserved resources. -Console-only state bits must be dropped before forwarding, or `Close` fails `E_INVALIDARG`. - -## 8. Unified memory - -Titles expect graphics memory where the CPU address equals the GPU address (sibling layer; -consistent with the package's slot-148 measurement in §3). - -- The sibling layer backs this with a fully-committed sub-4 GiB region at a 4 GiB-aligned virtual - address, opened via `ID3D12Device3::OpenExistingHeapFromAddress`. Measured limits: a partial - commit is rejected; a full 4 GiB is rejected; 4095 MiB works. -- For reservations above 4 GiB the measured technique is: reserve with `VirtualAlloc2` - `MEM_RESERVE_PLACEHOLDER`, split chunks with `VirtualFree` `MEM_PRESERVE_PLACEHOLDER`, back each - chunk with a `SEC_COMMIT` section mapped via `MapViewOfFile3` `MEM_REPLACE_PLACEHOLDER`. Each - chunk opens as its own heap with GPU/CPU coherence at the title's address. `SEC_RESERVE` - sections are refused even when fully committed. -- Buffers in unified memory are placed resources at 64 KiB alignment. A buffer at a - non-64 KiB-aligned console address is placed from the 64 KiB boundary below it and the copy - paths add the delta. -- `Map` of a unified-memory resource returns its console address. -- GPU-owned textures (resources with RT/DS/UAV flags) go into "arenas" — default heaps standing - for ranges of title addresses — because titles alias several textures at one address. - -## 9. `PresentX` - -Sibling layer: one frame is presented per console queue method call (`PresentX`, §4). The -presented back buffer is detected by tracking render-target binds (RTV creation and -`OMSetRenderTargets`) and `ExecuteCommandLists`. - -## 10. Shader-interface facts - -Measured on real console shaders by a sibling layer; where the claims overlap this repository's -translator docs they are mostly confirmed here. - -- An FSSM stage descriptor at +0x110 looks like `RSRC2`: `USER_SGPR` sits in bits 5:1 (e.g. - `0x18` → 12 SGPRs). A PS header carries an export-variant patch table from about +0x25C. -- User SGPRs (a compute example with 14 per `RSRC2`): `s4` = descriptor table 0, `s5` = table 1, - `s[6:7]` and `s[8:9]` = root CBVs; `s14`/`s15` = thread-group id x/y. -- Mesh-shader interface: `s3[27:24]` = wave index in the group, `v5` = group·128 + thread, - `s16..s24` = user data. -- Console GS runs on-chip: the ES writes vertices to LDS and `s_setpc`s to the GS. The GS writes - vertices to LDS at 64 B per vertex, base = `s2 + ([s8 + 0xB8] << 8)`, and uses `s_sendmsg` - emit/cut/done. No copy shader is present in the pack. -- `IASetPrimitiveTopology` value 17 is rectangle lists, drawn as two triangles on PC. -- Derivatives: console code computes cross-quad derivatives manually (DPP `quad_perm`, - `ds_swizzle`) and reads helper lanes. On PC, reads across quads need quad-aware lane reads: - `WaveReadLaneAt` leaves helper lanes out before SM 6.7, and enabling - `WaveOpsIncludeHelperLanes` caused a device hang in the sibling layer — whole-wave ballots then - never let helper lanes exit. -- A pixel shader doing `v_readfirstlane` after `s_wqm` can read a helper lane's value; the read - must take the value with a quad read inside its own quad plus a wave read from a live lane of - that quad. -- Memory model: a shared "mem" buffer used for flat accesses must be coherent - (`globallycoherent` on D3D12). Bottom-up BVH builds with atomics produce wrong child pointers - otherwise; console code relies on GLC/cache-invalidation semantics. -- ISG1 inputs a VS never reads get no fetch-shader VGPRs. - -## 11. Unverified here - -The sibling-layer measurements above were made on retail Series titles and that project's own -host runtime, not on this package or this layer. Still to be measured on this package: - -- **which runtime layout this title uses** — the older/newer detection rule of §1.1 needs a queue - call trace; -- **draw-record encodings for graphics** — only compute dispatches and copies were measured; the - graphics draw records and their sizes are unknown; -- the `PresentX` signature and plane struct (no signature is recovered anywhere; - [d3d12_command_objects.md](d3d12_command_objects.md) §4); -- queue/fence/allocator slots and the device creation slots 8/9/12/36 for the layout this title - uses ([d3d12_command_objects.md](d3d12_command_objects.md) §5.3); -- the exact newer→older slot pairs on the command-list tail beyond the measured set. diff --git a/docs/design.md b/docs/design.md index d7b62c212..3744aca2f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -1,9 +1,7 @@ # Design notes Groundwork for running the Xbox Series build of GTA VI natively on Windows. The work that does not need the -executable is in place; booting can start as soon as the engine image is available (the -`game_scarlett_master.exe` obtained so far is a packaging verification probe, not the engine — see -docs/boot.md). +executable is in place; booting can start as soon as `game_scarlett_master.exe` is available. ## Ground rules diff --git a/docs/fssm_crosscheck.md b/docs/fssm_crosscheck.md index 072576a6f..9cc5f5a13 100644 --- a/docs/fssm_crosscheck.md +++ b/docs/fssm_crosscheck.md @@ -44,8 +44,7 @@ The short version: ### The duplicate-XBCH exception (the important one) -`tools/fssm_unpack.py` read the entries last-wins, dropping all but the last payload of a -repeated tag: +`tools/fssm_unpack.py` does: ```python ents = {} diff --git a/docs/hello_pixels.md b/docs/hello_pixels.md deleted file mode 100644 index 8df0f4229..000000000 --- a/docs/hello_pixels.md +++ /dev/null @@ -1,53 +0,0 @@ -# Hello pixels: a package-free draw through vk_harness - -**Status: measured** on Mesa llvmpipe (LLVM 20.1.2, Vulkan 1.3.275, Linux). This is a synthetic complement to -[first_light.md](first_light.md): where that page draws a real game model with real translated shaders, this one -draws a quad built entirely in the repository — hand-written SPIR-V assembly, a generated mesh — so anyone with -a Vulkan device can check the pipeline without the game package. - -## What it draws - -`tools/hello_pixels.py --run --check` assembles two tiny shaders (no GLSL compiler needed, `spirv-as` only): - -- **VS** (`vs.asm`): `Location 0` float3 position already in NDC, `Location 1` float2 uv; stores the position - into `gl_Position` and forwards uv to the interpolating varying. This is the same shape as the first_light VS. -- **PS** (`ps.asm`): `rgb = (u, v, (u+v)/2)` dimmed to 20% on every other cell of a 16×16 checker, computed with - core instructions only (`OpFMod` cell coordinate, `OpFOrdLessThan`/`OpSelect` parity). `OriginUpperLeft`. - -The mesh is a generated fullscreen indexed quad (`u32` counts, `5f` vertices, `u32` indices — the -`VKH_DRAW_MESH` format with `VKH_VERTEX_LAYOUT=0:3f,1:2f`), drawn into the RGBA32F attachment, read back, and -written as `image.raw`, `image.ppm` and a zlib-only `image.png`. - -## What --check verifies - -Same style as the first_light oracle, so the image has to be *right*, not just non-clear: - -- the buffer is exactly `w*h*16` bytes of RGBA32F; -- coverage is 100% — a quad that misses the image fails, and so does an all-clear image; -- seven probe pixels match `expected_pixel`, the closed form of the same pattern (u, v, (u+v)/2 with cell - parity) computed at pixel centres, within 0.04. A flipped axis, a swapped u/v or a mirrored checker moves - probe values out of tolerance. - -`tests/test_hello_pixels.py` runs the oracle on synthetic buffers without a GPU or vk_harness: the accepted -image, a truncated buffer, a wrong probe pixel and a coverage loss away from every probe. - -## Why it matters - -first_light needs `shaders.rpf`, `data.rpf` and an OBJ export. This needs nothing but the built harness and -`spirv-as`, so it is the fastest way to tell a fresh machine "your Vulkan path prints pixels": vertex fetch → -interpolation → fragment → readback, exercised end to end. It also serves as the smallest reproducer for -VKH_DRAW_MESH bugs — the file format and layout string are spelled out in one generated mesh. - -## Reproduce it - -```sh -cmake -S runtime -B runtime/build -G Ninja -cmake --build runtime/build --target vk_harness -python -I tools/hello_pixels.py --work --size 512 --run --check -# /image.png: a u/v gradient dimmed on alternating 16x16 cells -``` - -On Windows the same command works against `runtime/build/windows/vk_harness.exe`; on a machine without -`spirv-as`, drop the `vs.spv`/`ps.spv` that `--emit-only` produced on a machine that has one into the `--work` -directory; the tool uses the prebuilt pair when `spirv-as` is absent (fresh assembly always wins when it is -present). diff --git a/docs/import_routing.md b/docs/import_routing.md deleted file mode 100644 index 6be8d31eb..000000000 --- a/docs/import_routing.md +++ /dev/null @@ -1,82 +0,0 @@ -# Import routing: shim, bundled, host or unimplemented - -How `gta6rt` binds an import, per DLL. The code paths are `Loader::resolve` for the import table -(`runtime/src/pe_loader.cpp`), `Loader::resolve_forwarder` for a forwarded export, and the `LoadLibrary*` / -`GetProcAddress` shims for run-time loads (`runtime/shims/library_loader.cpp`). Measured against the 16 shipped -modules in [runtime_imports.md](runtime_imports.md): every import binds, 0 unimplemented. - -## The bind order - -The lookup key is the DLL name normalised the way `LoadLibrary` resolves a file name (`dll_key`, -`pe_loader.cpp`): lower-case, a trailing `.` dropped, and `.dll` added when the name has no extension — -so a descriptor naming `GameInput` or `gameinput.dll.` keys the same as `gameinput.dll`, matching the -host `LoadLibraryExA` it can fall through to. - -`resolve(dll, name)` tries, in order: - -1. **Shim** — `rt::shims::find("dll!name")`, the clean-room tables registered by `SHIM_TABLE` in - `runtime/shims/*.cpp`. The registry is searched first even for host DLLs, which is how `kernel32!CreateFileW` - or `ExitProcess` get redirected without losing the rest of `kernel32`. -2. **Bundled** — `/` mapped by the same loader, unless the name is in `prefer_host_copy` - (the `vcruntime140`/`msvcp140`/`concrt140`/`vccorlib140`/`vcomp140` family: the host CRT is always used, so a - mapped image's `RtlPcToFileHeader` can be redirected, `pe_loader.cpp`). A bundled export that is itself a - forwarder string is followed by `resolve_forwarder` (8 deep, then a loop is declared). -3. **Host** — `LoadLibraryExA(dll, LOAD_LIBRARY_SEARCH_SYSTEM32)` + `GetProcAddress`. System32 only, so the game - folder is never in the search. API-set names (`api-ms-*`, `ext-ms-*`) resolve here through the host's API-set - schema; the measured run binds every api-ms import the package asks for. -4. **Unimplemented** — `shims::make_unimplemented_thunk`: a 32-byte stub per import that calls `rt_unimplemented` - with `"dll!name"` and the argument registers; `LEONIDA_UNIMPLEMENTED` = log (default) / fail / stop picks the - answer (`runtime/shims/registry.cpp`, policy documented in `runtime/README.md` and - [runtime_imports.md](runtime_imports.md#when-an-unimplemented-import-is-called)). - -Step 3 is skipped when `shims::owns_dll(dll)` is true. `xgameruntime.dll` and `gameinput.dll` are real PC names -(Gaming Services installs `xgameruntime.dll` in System32); without the skip, an import the registry doesn't serve -would bind to the live service runtime while a run-time `GetProcAddress` for the same name returns NULL, and the -process would be online-capable. `resolve_forwarder` applies the same order, so a forwarder string naming a -shimmed module resolves to the shim. - -## `owns_dll`: whole-module shims - -`owns_dll` (registry.cpp) is false for `api-ms-*`/`ext-ms-*` prefixes and for the eight host DLLs that the tables -partially override — `kernel32`, `kernelbase`, `msvcrt`, `ucrtbase`, `ucrtbased`, `vulkan-1`, `ntdll`, `user32` — -and otherwise true exactly when the registry holds at least one `dll!` entry. Owned today: `d3d12_xs.dll`, -`xgameruntime.dll`, `gameinput.dll`, `xmem.dll`. - -A title's `LoadLibrary*`/`GetModuleHandle*` for an owned module returns a pseudo-handle -(`library_loader.cpp`); `GetProcAddress` on it resolves through the registry only — an unserved name is NULL with -`ERROR_PROC_NOT_FOUND`, never the host. `FreeLibrary` on a pseudo-handle is a no-op. Every other module goes to -the real `LoadLibrary*`/`GetProcAddress`. - -## Per-DLL outcome - -| DLL | Registry entries | Static import | Run-time load | -|---|---|---|---| -| `d3d12_xs.dll` | 4: `D3D12XboxCreateDevice`, `D3D12Serialize{,Versioned}RootSignature`, `D3D12CreateRootSignatureDeserializer` | those → shim; any other → unimplemented (no host namesake) | owned → pseudo-handle | -| `xgameruntime.dll` | ~40: `*ApiImpl*` entry points, `XGameRuntime*`, `XSystem*`, `XPackage*`, `XTaskQueue*`, `XAsync*`, `GameInputCreate` | registered → shim; unregistered → unimplemented | owned → pseudo-handle (the path `xgameruntime.lib` thunks use) | -| `gameinput.dll` | `GameInputCreate` | registered → shim; unregistered → unimplemented | owned → pseudo-handle | -| `xmem.dll` | `XMemAlloc`, `XMemFree`, `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` | registered → shim; unregistered → unimplemented | owned → pseudo-handle | -| `d3d12.dll`, `dxgi.dll` | none | host (the real PC DLLs; the console surface rides on them through the `d3d12_xs` device proxy and the DXGI COM wrappers) | real host DLL | -| `xaudio2_9.dll`, `xaudio2_9redist.dll` | none | host if installed, else unimplemented | real host DLL | -| `dstorage.dll`, `dstorage_xs.dll` | none | `dstorage.dll` host if the DirectStorage redist is installed, else unimplemented; `dstorage_xs.dll` unimplemented | real host DLL / fails | -| `xg_xs.dll`, `acphal.dll`, `chad*`/`xapu*`/`xcrdapi*` (legacy Xbox names) | none | unimplemented | fails (host can't load them) | -| `kernel32`, `kernelbase` | file (`CreateFile*`, `FindFirstFile*`, `GetFileAttributes*`, `DeleteFile*`), loader (`LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress`, `FreeLibrary`), process (`ExitProcess`, `GetCommandLine*`) | registered → shim; everything else → host | real host DLL (not owned) | -| `msvcrt`, `ucrtbase`, `ucrtbased` | exit/`abort`/argv/command-line overrides | registered → shim; everything else → host | real host DLL | -| `ntdll`, `user32`, `vulkan-1` | none | host | real host DLL | -| `api-ms-*`, `ext-ms-*` | only the sets a GDK title links: `core-file-l1-1-0/l1-2-0/l2-1-0`, `core-libraryloader-l1-1-0/l1-1-1/l1-2-0/l1-2-1/l1-2-2`, `core-processthreads-l1-1-0`, `core-processenvironment-l1-1-0`, `crt-runtime-l1-1-0` | registered names → shim; all other names and sets → host API-set schema (this is what covers every UCRT `api-ms-win-crt-*` variant without a table entry) | real host resolution | -| `vcruntime140*`, `msvcp140*`, `concrt140`, `vccorlib140`, `vcomp140` | none | host, even when a bundled copy exists (`prefer_host_copy`) | real host DLL | -| the package's own DLLs (`Bink2Scarlett.dll`, `XCurl.dll`, …) | none | bundled module, mapped by the loader | host `LoadLibrary` — see the caveat in [runtime_imports.md](runtime_imports.md#run-time-loaded-modules) | -| anything else | none | unimplemented | host or failure | - -## Edge cases - -- **`d3d12.dll`/`dxgi.dll` can never hit the unimplemented thunk** for a name the PC DLL exports: no registry - entries exist for them, and they are real System32 DLLs. A name they don't export ends unimplemented, which is - the wanted answer. -- **Ordinals**: registry keys are `dll!#N` in `Entry.name`, but no shipped table registers an ordinal; an - ordinal-only import from a shimmed or console-only DLL lands unimplemented. Host DLLs bind ordinals through - `GetProcAddress` normally. -- **No console DLL matches the host list.** The `owns_dll` host list holds only names that also exist on the PC - and have partial table overrides. A console-only name (`d3d12_xs`, `xmem`, `xg_xs`, …) can't be owned by - accident and can't be excluded from the tables by accident. -- **Owned ≠ bundled-blocked.** A bundled copy of an owned name would still map through the bundled step before - the unimplemented fallback; nothing in the package ships one. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e47bb9ad9..73326b838 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2499,7 +2499,7 @@ if(TARGET Vulkan::Headers) # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). if(TARGET gta6rt) - target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com user32) # user32: the PresentX window + target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 0286a6876..590f86bd7 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -20,12 +20,6 @@ #include "d3d12_trace.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 -#ifdef LEONIDA_VULKAN_DEVICE -// PresentX wiring: the queue's console slots land on the Xbox presentation core, which needs the Vulkan layer's -// WindowPresenter. Other builds of this file (mock and COM tests) keep the refused-slot behaviour. -#include "xbox_present.h" -#endif - #include #include @@ -34,11 +28,9 @@ #include #include #include -#include #include #include #include -#include namespace rt::d3d12_xs { namespace { @@ -56,19 +48,6 @@ struct DeviceProxy { void** real_vtable; unsigned slot_count; // number of valid entries in real_vtable std::atomic refs; - // The PresentX state (window, presenter, XboxPresentation) the first queue PresentX builds on this device, - // under LEONIDA_VULKAN_DEVICE; always null elsewhere. Opaque: PresentState is defined with the queue proxy. - void* present_state = nullptr; - // The upload-memory arena console list slot 148 (AllocateUploadMemory) carves from; always null until the - // first call. Opaque: UploadArena is defined with the list proxy. Atomic: lists record on several threads - // at once, so the first AllocateUploadMemory installs the arena by compare-exchange. - std::atomic upload_state{nullptr}; - // The console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4): the queue proxy - // writes it on detection and every object shares it — the queue/list slot tails shift +2 under the newer one. - std::atomic console_layout{0}; // 0 unknown, 1 older, 2 newer - // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers - // compiled against the PC headers. - bool console_lists = true; // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. void** dxgi_vtable; DxgiAdapterProvider adapter_provider; @@ -76,10 +55,6 @@ struct DeviceProxy { std::atomic max_frame_latency; }; -// Freed in proxy_release; defined where the states are complete. -void destroy_present_state(void* present_state); -void destroy_upload_state(void* upload_state); - constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles struct HeapProxy { @@ -203,8 +178,6 @@ unsigned long proxy_release(DeviceProxy* self) { note_slot(2); const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { - destroy_present_state(self->present_state); - destroy_upload_state(self->upload_state.load(std::memory_order_relaxed)); ID3D12Device* real = self->real; delete self; if (real) real->Release(); @@ -554,16 +527,10 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII // // Device slots 8 (CreateCommandQueue), 75 (CreateCommandQueue1), 36 (CreateFence) and 32 (OpenSharedHandle, for a // fence) wrap what they create, so a title never holds a PC or Vulkan-layer queue or fence. The proxies forward -// the public chain in PC order, exactly like the device proxy; on a fence a slot past the PC vtable is logged and -// refused with E_NOTIMPL. PresentX, SuspendX and ResumeX are queue methods past the public chain -// (docs/d3d12_command_objects.md §5.3). A sibling layer measured two queue layouts on retail titles -// (docs/d3d12_xs_console_abi.md §4, unverified here): the older has Signal 14, Wait 15, -// GetTimestampFrequency 16, GetClockCalibration 17, GetDesc 18, SignalX 23, PresentX 30; a newer game -// OS inserts two methods before Signal, shifting to Signal 16, Wait 17, frequency 18, SignalX 25, -// PresentX 32 — a fence passed to slot 16 or 17 marks the newer layout, and the detection is shared -// across queues through the device. PresentX is wired to the Vulkan layer's Xbox presentation, -// SignalX forwards as Signal, and the unmodelled console-only slots answer S_OK (the PresentX -// section below); the first run of the executable confirms which layout. +// the public chain in PC order, exactly like the device proxy, and a slot past the PC vtable is logged and refused +// with E_NOTIMPL. PresentX, SuspendX and ResumeX are queue methods past the public chain +// (docs/d3d12_command_objects.md §5.3). Their slots are not known and nothing is guessed: the first run of the +// executable names them in the log. // // Slot numbers are those of the Windows SDK 10.0.26100 d3d12.h: ID3D12CommandQueue has 19, ID3D12Fence 11 and // ID3D12Fence1 12. That the console keeps these public slots, and keeps device slots 8/32/36/75, is an assumption @@ -581,10 +548,11 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII // passed there: queue Signal/Wait (14/15) take a fence; device CreateSharedHandle (31) a device child, // MakeResident/Evict (34/35), SetResidencyPriority (46) and EnqueueMakeResident (50) pageables, and // SetEventOnMultipleFenceCompletion (45) and EnqueueMakeResident fences. The heap proxies of slot 14 are pageables -// and device children too and are unwrapped in the same places. Command lists from device slot 12 come back -// console-shaped (the list proxy below): queue ExecuteCommandLists (10) unwraps the list array, the list's own -// Reset and ExecuteBundle unwrap allocator and bundle proxies, and its SetDescriptorHeaps unwraps heap proxies — -// all through proxy_real_object, so any object kind added later unwraps in every place at once. +// and device children too and are unwrapped in the same places. Command lists are not wrapped yet, so +// ExecuteCommandLists passes them through, and a heap proxy still reaches the real runtime through the list's +// SetDescriptorHeaps. A command-list proxy (docs/d3d12_command_objects.md §3.5a) adds its vtable to +// proxy_real_object, which every unwrap goes through, and a queue slot 10 branch in child_slot that unwraps the list +// array (UnwrappedArray) before forwarding, and unwraps heap proxies in its own SetDescriptorHeaps. // // QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when // the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to @@ -622,14 +590,6 @@ struct ChildProxy { void** real_vtable; unsigned slot_count; // public slots the real object implements; the rest of the table is refused std::atomic refs; - // Queues only: the console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4), - // detected by a fence reaching slot 16/17 or SignalX slot 25. Unused on fences and allocators. A queue is - // used from many threads, so the cache of the device's shared detection is atomic like the shared flag - // itself. - static constexpr unsigned char kQueueLayoutUnknown = 0; - static constexpr unsigned char kQueueLayoutOlder = 1; // PC order; PresentX 30, SignalX 23 - static constexpr unsigned char kQueueLayoutNewer = 2; // +2 shift; PresentX 32, SignalX 25 - std::atomic queue_layout{kQueueLayoutUnknown}; }; template @@ -823,10 +783,6 @@ HRESULT child_get_device(ChildProxy* self, const IID* riid, void** out) { template void** get_child_vtable(); -// The command-list proxy's helpers (defined with the list proxy below): proxy_real_object checks lists through -// list_real_or_null, since the ListProxy type is complete only there. -IUnknown* list_real_or_null(const void* object); - template bool is_child_proxy(const void* object) { return object && *reinterpret_cast(object) == reinterpret_cast(get_child_vtable()); @@ -841,7 +797,6 @@ IUnknown* proxy_real_object(const void* object) { vtable == reinterpret_cast(get_child_vtable()) || vtable == reinterpret_cast(get_child_vtable())) return static_cast(object)->real; - if (IUnknown* real = list_real_or_null(object)) return real; return nullptr; } @@ -922,91 +877,6 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash } -// ---- PresentX on the queue (LEONIDA_VULKAN_DEVICE) --------------------------------------------------------- -// -// The measured console queue slots (docs/d3d12_xs_console_abi.md §4): the older runtime keeps the PC order — -// Signal 14, Wait 15, frequency 16, calibration 17, GetDesc 18 — and presents at slot 30, with SignalX at 23. A -// newer game OS inserts two methods before Signal: Signal 16, Wait 17, frequency 18, calibration 19, GetDesc 20, -// SignalX 25, PresentX 32. The layout is detected once, by a fence object reaching slot 16 or 17 (the older -// layout's frequency and calibration getters take no object argument) or by a fence reaching SignalX slot 25 — -// a title that signals only through SignalX would otherwise stay undetected and lose every signal. -// -// Every other console-only queue method answers S_OK (sibling layer: title frame pacing flows through them, and a -// refusal wedges the present loop), still recorded by note_child_slot. Slot 148's AllocateUploadMemory is a list -// method, not a queue method, so it is not part of this table. - -#ifdef LEONIDA_VULKAN_DEVICE - -struct PresentState { - ~PresentState() { - if (window) DestroyWindow(window); // the presentation and its window die with the device proxy - } - HWND window = nullptr; - std::unique_ptr xbox; - bool tried = false; // creation is attempted once; a null xbox means this device cannot present -}; - -void destroy_present_state(void* present_state) { - delete static_cast(present_state); -} - -LRESULT CALLBACK present_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { - return DefWindowProcW(window, message, wparam, lparam); -} - -// Lazily builds the window, presenter and XboxPresentation a console PresentX needs, once per device. Returns the -// state even when `xbox` stays null (no presentation support): the failure is logged once, not retried. -PresentState* present_state_for(DeviceProxy* device) { - if (auto* state = static_cast(device->present_state)) return state; - auto* state = new (std::nothrow) PresentState; - if (!state) return nullptr; - device->present_state = state; - state->tried = true; - WNDCLASSW window_class{}; - window_class.lpfnWndProc = present_window_proc; - window_class.hInstance = GetModuleHandleW(nullptr); - window_class.lpszClassName = L"LeonidaPresentX"; - if (!RegisterClassW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { - std::fprintf(stderr, "[rt] d3d12_xs: PresentX window class failed (error %lu)\n", GetLastError()); - return state; - } - state->window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, - window_class.hInstance, nullptr); - if (!state->window) { - std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); - return state; - } - auto presenter = rt::d3d12::create_window_presenter(device->real, state->window); - if (!presenter) { - std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX is a no-op\n"); - return state; - } - state->xbox = std::make_unique(std::move(presenter)); - std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(state->window)); - return state; -} - -std::uint64_t queue_present_x(ChildProxy* self, std::uint64_t plane_count, std::uint64_t planes, - std::uint64_t params) { - PresentState* state = self->device ? present_state_for(self->device) : nullptr; - if (!state || !state->xbox) return hr_to_u64(S_OK); // a title still runs with nothing presented - return hr_to_u64(state->xbox->PresentX( - static_cast(plane_count), - reinterpret_cast(planes), - reinterpret_cast(params))); -} - -#else // !LEONIDA_VULKAN_DEVICE: this translation unit stands alone (mock and COM tests) - -void destroy_present_state(void*) {} - -std::uint64_t queue_present_x(ChildProxy*, std::uint64_t, std::uint64_t, std::uint64_t) { - return hr_to_u64(S_OK); -} - -#endif - template std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -1026,100 +896,6 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ reinterpret_cast(a2))); } else { note_child_slot(Slot); - if constexpr (K == ChildKind::queue) { - // Layout detection (the comment at the PresentX section): a fence reaching slot 16 or 17 is the newer - // layout's Signal/Wait; anything else there is the older layout's frequency/calibration getter. A - // fence at slot 14 or 15 is the older Signal/Wait; a non-fence argument there is one of the newer - // layout's two inserted console methods. - // A queue made after another one detected the layout inherits it from the device; undetected queues - // assume the older layout, whose unshifted slots are also the PC chain. A fence reaching SignalX - // slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that - // signals only through SignalX never reaches Signal/Wait at 16/17, and an unanswered SignalX - // returns S_OK having signalled nothing, leaving a waiter on that fence value hanging. - const bool newer = [&] { - const unsigned char own = self->queue_layout.load(std::memory_order_relaxed); - if (own == ChildProxy::kQueueLayoutNewer) return true; - const unsigned char shared = - self->device->console_layout.load(std::memory_order_relaxed); - return own == ChildProxy::kQueueLayoutUnknown && shared == ChildProxy::kQueueLayoutNewer; - }(); - if (Slot == 16 || Slot == 17) { - if (IUnknown* fence = proxy_real_object(reinterpret_cast(a1))) { - self->queue_layout.store(ChildProxy::kQueueLayoutNewer, std::memory_order_relaxed); - self->device->console_layout.store(ChildProxy::kQueueLayoutNewer, - std::memory_order_relaxed); - using Fn = HRESULT(WINAPI*)(IUnknown*, IUnknown*, UINT64); - return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueSignal + (Slot - 16)])( - self->real, fence, a2)); - } - if (newer) return hr_to_u64(S_OK); // proven newer: a non-fence Signal/Wait arg is malformed, - // not evidence of the older layout — do not downgrade the shared detection on it - if (self->queue_layout.load(std::memory_order_relaxed) == - ChildProxy::kQueueLayoutUnknown) { - self->queue_layout.store(ChildProxy::kQueueLayoutOlder, std::memory_order_relaxed); - self->device->console_layout.store(ChildProxy::kQueueLayoutOlder, - std::memory_order_relaxed); - } - } else if ((Slot == 14 || Slot == 15) && !proxy_real_object(reinterpret_cast(a1)) && - newer) { - return hr_to_u64(S_OK); // the newer layout's two inserted console methods, unmeasured - } - if (newer && Slot >= 18 && Slot <= 20) { - // Newer layout: frequency 18, calibration 19, GetDesc 20 are the PC slots 16-18 shifted. - d3d12_trace::record(child_trace_name(Slot)); - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t); - auto fn = reinterpret_cast(self->real_vtable[Slot - 2]); - return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); - } - // Slot 18 while the layout is still unknown is ambiguous: the older GetDesc (a struct-return - // write of a whole desc) or the newer frequency getter (an 8-byte out). Answering it as GetDesc - // writes far past the 8 bytes a frequency caller passes, so the call goes to the frequency - // getter — the only interpretation that cannot overrun its argument, and a title often queries - // the frequency before its first fence call. A proven-older queue keeps the generic GetDesc - // path below; slots 19 and 20 stay no-ops, since their newer interpretations write through - // caller pointers an unmodelled older method might not supply. - if (Slot == 18 && !newer && self->queue_layout == ChildProxy::kQueueLayoutUnknown && - self->device->console_layout.load(std::memory_order_relaxed) != - ChildProxy::kQueueLayoutOlder) { - d3d12_trace::record(child_trace_name(Slot)); - using Fn = HRESULT(WINAPI*)(IUnknown*, UINT64*); - return hr_to_u64(reinterpret_cast(self->real_vtable[16])( - self->real, reinterpret_cast(a1))); - } - if (Slot == (newer ? 25u : 23u) || - (Slot == 25u && self->queue_layout.load(std::memory_order_relaxed) == - ChildProxy::kQueueLayoutUnknown && - self->device->console_layout.load(std::memory_order_relaxed) == - ChildProxy::kQueueLayoutUnknown)) { - // SignalX: console Signal (older 23, newer 25); the extra X word is dropped. The slot-25 - // alternative is the fence itself carrying the layout evidence, per the comment above; a - // proven-older queue still leaves slot 25 to the console-only no-op, since its fence-taking - // methods sit at 14/15/23 there. - if (IUnknown* fence = proxy_real_object(reinterpret_cast(a1))) { - if (Slot == 25u && !newer) { - self->queue_layout.store(ChildProxy::kQueueLayoutNewer, - std::memory_order_relaxed); - self->device->console_layout.store(ChildProxy::kQueueLayoutNewer, - std::memory_order_relaxed); - } - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12_xs: SignalX (queue slot %u) forwarded as Signal\n", Slot); - using Fn = HRESULT(WINAPI*)(IUnknown*, IUnknown*, UINT64); - return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueSignal])(self->real, fence, a2)); - } - return hr_to_u64(S_OK); - } - if (Slot == (newer ? 32u : 30u)) return queue_present_x(self, a1, a2, a3); // PresentX - if (Slot >= self->slot_count || (newer && (Slot == 14 || Slot == 15))) { - d3d12_trace::record(child_trace_name(Slot), "console-only"); - return hr_to_u64(S_OK); // unmodelled console queue methods: frame pacing flows through them - } - } if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, @@ -1137,14 +913,6 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ d3d12_trace::record(child_trace_name(Slot)); // "called": the real object's result is not inspected if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); - // Queue slot 10: ExecuteCommandLists(count, lists). The array is copied with each list proxy replaced by - // its real list; a bundle on the list side unwraps the same way at the console's ExecuteBundle. - UnwrappedArray unwrapped; - if constexpr (K == ChildKind::queue && Slot == 10) { - if (!unwrapped.fill(a2, a1)) return hr_to_u64(E_OUTOFMEMORY); - if (unwrapped.data()) a2 = unwrapped.data(); - } - // The PC vtable entry with the real object as `this`; integer/pointer arguments, the hidden struct-return // pointer and stack arguments keep their positions, as in the device proxy. using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, @@ -1246,498 +1014,6 @@ HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void return S_OK; } -// ---- Command list proxy --------------------------------------------------------------------------------- -// -// Device slot 12 (CreateCommandList) hands the title a console-shaped command list: the console vtable order, a -// 160-slot table, and the object fields the console SDK's inline writers touch (docs/d3d12_xs_console_abi.md -// §5). The write cursor (+0x18) is pinned at both limits (+0x28, +0x30), so a title always finds the record -// buffer full and takes the vtable path for every command — the proxy never has to interpret inline records. -// The flag bytes (+0x140..+0x143), the root-parameter header table (+0x344) and the pipeline record (+0x544) -// stay zeroed: they are only read while writing a record, which never happens at the limit. -// -// The console slot order keeps the PC order through slot 26 (measured: 9, 10, 12-17, 19, 20, 25, 26), places -// four console-only methods at 27-30, then the PC chain resumes shifted +4 — confirmed at console 32->PC 28 -// (SetDescriptorHeaps), 33->29, 41->37, 43->39, 45->41, 48->44, 51->47 and 53->49, and the same shift fills the -// block through console 59 -> PC 55. The console has no PIX markers: console 60 is EndEvent (PC 58) and 61 is -// ExecuteIndirect (PC 59, package-measured). Console 146 is the enhanced Barrier taking one D3D12_BARRIER_GROUP -// (package-confirmed; PC equivalent is GCL7 slot 80). Console-only slots — the 27-30 extras, AllocateUploadMemory -// (148), the disputed tail past 61 and the newer-layout +2 tail — are recorded with their first argument words -// and return 0 without a PC call: a wrong forward is worse than a clean refusal. - -constexpr unsigned kListSlots = 160; -// ---- Upload memory (console list slot 148, AllocateUploadMemory) ---- -// -// On the console the CPU and GPU share one address space: the pointer AllocateUploadMemory(size, alignment) -// returns is written by the CPU and handed to the GPU unchanged — the package measures it going straight into a -// root SRV (docs/d3d12_xs_console_abi.md §5.3, d3d12_command_objects.md §3.3a). A PC has two address spaces, so -// each arena chunk is a persistently-mapped UPLOAD-heap buffer: the title gets the CPU pointer and writes the -// very memory the GPU samples, and the root-descriptor setters translate a chunk address to the buffer's device -// address (the same backing memory) before forwarding. Translation covers the six root VA setters (console -// 41-46); VAs inside view structs (IASetVertexBuffers/IASetIndexBuffer) and ExecuteIndirect arguments are not -// rewritten yet and stay title addresses. - -struct UploadChunk { - UploadChunk* next; - ID3D12Resource* resource; // the mapped buffer; released with the chunk - std::uint8_t* cpu_base; - D3D12_GPU_VIRTUAL_ADDRESS gpu_base; - std::size_t size; - std::size_t used; -}; - -struct UploadArena { - UploadChunk* chunks = nullptr; - std::mutex lock; -}; - -constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads - -UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { - auto* chunk = new (std::nothrow) UploadChunk{}; - if (!chunk) return nullptr; - chunk->size = size; - - D3D12_HEAP_PROPERTIES heap = {}; - heap.Type = D3D12_HEAP_TYPE_UPLOAD; - D3D12_RESOURCE_DESC desc = {}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = size; - desc.Height = 1; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - ID3D12Resource* resource = nullptr; - const HRESULT hr = device->real->CreateCommittedResource( - &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - __uuidof(ID3D12Resource), reinterpret_cast(&resource)); - void* cpu = nullptr; - if (SUCCEEDED(hr) && resource && SUCCEEDED(resource->Map(0, nullptr, &cpu)) && cpu && - resource->GetGPUVirtualAddress() != 0) { - chunk->resource = resource; - chunk->cpu_base = static_cast(cpu); - chunk->gpu_base = resource->GetGPUVirtualAddress(); - return chunk; - } - if (resource) resource->Release(); - // A device that cannot hand out a mapped buffer (a mock, or an older layer without buffer device - // addresses) still gets memory to write; upload_translate leaves its addresses alone. - auto* cpu_fallback = static_cast( - VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); - if (!cpu_fallback) { - delete chunk; - return nullptr; - } - chunk->cpu_base = cpu_fallback; - chunk->gpu_base = reinterpret_cast(cpu_fallback); - return chunk; -} - -std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_t alignment) { - if (!device || !size) return 0; - alignment = alignment < 16 ? 16 : alignment; // every measured call asked for 16 - auto* arena = static_cast(device->upload_state.load(std::memory_order_acquire)); - if (!arena) { - auto* fresh = new (std::nothrow) UploadArena; - if (!fresh) return 0; - void* expected = nullptr; // a concurrent first call loses its arena but keeps the winner's chunks - if (device->upload_state.compare_exchange_strong(expected, fresh, std::memory_order_acq_rel)) - arena = fresh; - else { - delete fresh; - arena = static_cast(expected); - } - } - std::lock_guard lock(arena->lock); - const std::size_t need = static_cast(size); - for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { - const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast(alignment) - 1); - if (aligned + need <= chunk->size) { - chunk->used = aligned + need; - return reinterpret_cast(chunk->cpu_base + aligned); - } - } - const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; - UploadChunk* chunk = upload_chunk_new(device, chunk_size); - if (!chunk) { - std::fprintf(stderr, "[rt] d3d12_xs: AllocateUploadMemory(%llu, %llu) failed\n", - static_cast(size), static_cast(alignment)); - return 0; - } - chunk->next = arena->chunks; - arena->chunks = chunk; - const std::size_t aligned = (alignment - 1) & ~(static_cast(alignment) - 1); // 0-based - chunk->used = aligned + need; - return reinterpret_cast(chunk->cpu_base + aligned); -} - -// An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a -// real resource VA the title already holds — passes through. -std::uint64_t upload_translate(DeviceProxy* device, std::uint64_t va) { - auto* arena = static_cast( - device ? device->upload_state.load(std::memory_order_acquire) : nullptr); - if (!arena) return va; - std::lock_guard lock(arena->lock); - for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { - const std::uint64_t base = reinterpret_cast(chunk->cpu_base); - if (va >= base && va < base + chunk->size) return chunk->gpu_base + (va - base); - } - return va; -} - -void destroy_upload_state(void* upload_state) { - auto* arena = static_cast(upload_state); - if (!arena) return; - for (UploadChunk* chunk = arena->chunks; chunk;) { - UploadChunk* next = chunk->next; - if (chunk->resource) { - chunk->resource->Unmap(0, nullptr); - chunk->resource->Release(); - } else { - VirtualFree(chunk->cpu_base, 0, MEM_RELEASE); - } - delete chunk; - chunk = next; - } - delete arena; -} - -constexpr unsigned kListNotForwarded = ~0u; -constexpr unsigned kConsoleSetDescriptorHeaps = 32; -constexpr unsigned kConsoleExecuteBundle = 31; -constexpr unsigned kConsoleBarrier = 146; -constexpr unsigned kConsoleAllocateUpload = 148; - -constexpr unsigned console_to_pc_list_slot(unsigned slot) { - if (slot <= 26) return slot; // PC order, measured - if (slot <= 30) return kListNotForwarded; // console-only extras - if (slot <= 59) return slot - 4; // PC chain, shifted +4 - if (slot == 60) return 58; // EndEvent (no console SetMarker/BeginEvent) - if (slot == 61) return 59; // ExecuteIndirect (Package) - if (slot == kConsoleBarrier) return 80; // D3D12_BARRIER_GROUP (Package; PC GCL7) - return kListNotForwarded; -} - -struct ListProxy { - void** vtable; // +0x00 - ID3D12GraphicsCommandList* real; // +0x08 - DeviceProxy* device; // +0x10: keeps the Xbox-ABI device alive; GetDevice returns it - // +0x18..: the console object body a title's inline writers read. +0x18 holds the write cursor, +0x28 and - // +0x30 the record limits; the rest is room for the measured flags, header table and pipeline record. - alignas(8) std::uint8_t console_fields[0x600]; - std::atomic refs; // past the console body - unsigned pc_slot_count; // slots the real list implements; mapped slots past it are refused - std::vector vb_scratch; // slot-48 views with their VAs translated - std::vector so_scratch; // slot-49 views, same treatment - - void pin_cursor_at_limit() { - const std::uint64_t at_limit = static_cast( - reinterpret_cast(this) + 0x18 + 0x500); - for (const size_t offset : {0x18, 0x28, 0x30}) - std::memcpy(reinterpret_cast(this) + offset, &at_limit, sizeof(at_limit)); - } -}; -static_assert(offsetof(ListProxy, console_fields) == 0x18, "the console fields start at +0x18"); - -struct ListStats { - static inline std::atomic hits[kListSlots]; - static inline std::atomic first[kListSlots]; -}; - -// The list tail (D3D-445). From CopyTextureRegionX on, the newer console layout sits two slots later than the older -// one (docs/d3d12_xs_console_abi.md 5.3). The table is keyed by the older-layout slot. Only CopyTextureRegionX has a -// measured name; the other measured pairs are named by their older slot, so that both layouts print the same text -// for the same method. -struct ListTailName { - unsigned older_slot; - const char* name; -}; -constexpr ListTailName kListTailNames[] = { - {83, "CopyTextureRegionX"}, {84, "tail method, older slot 84"}, {85, "tail method, older slot 85"}, - {88, "tail method, older slot 88"}, {89, "tail method, older slot 89"}, {90, "tail method, older slot 90"}, - {93, "tail method, older slot 93"}, {94, "tail method, older slot 94"}, -}; -constexpr unsigned kListTailShift = 2; -static_assert(kConsoleLayoutOlder == ChildProxy::kQueueLayoutOlder && - kConsoleLayoutNewer == ChildProxy::kQueueLayoutNewer, - "the list tail names use the queue proxy's layout values"); - -// Null while the layout is unknown, and for a slot that is not a measured tail slot of that layout: a slot number -// never gets the other layout's name. -const char* list_tail_name(unsigned slot, unsigned char console_layout) { - if (console_layout != kConsoleLayoutOlder && console_layout != kConsoleLayoutNewer) return nullptr; - const unsigned shift = console_layout == kConsoleLayoutNewer ? kListTailShift : 0; - if (slot < shift) return nullptr; - for (const ListTailName& entry : kListTailNames) - if (entry.older_slot == slot - shift) return entry.name; - return nullptr; -} - -void note_list_slot(unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, - unsigned char console_layout = 0) { - if (slot >= kListSlots) return; - ListStats::hits[slot].fetch_add(1, std::memory_order_relaxed); - bool expected = false; - if (ListStats::first[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) { - const char* name = list_tail_name(slot, console_layout); - std::fprintf(stderr, "[rt] d3d12_xs: list slot %u%s%s%s first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, - name ? " (" : "", name ? name : "", name ? ")" : "", static_cast(a1), - static_cast(a2), static_cast(a3), - static_cast(a4)); - } -} - -// The interfaces the console list answers: the base chain, ID3D12CommandList and every graphics-command-list -// interface the real list implements — on the console the list is a single object, so any of them returns the -// proxy. -bool is_list_iid(const IID& iid) { - return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || - IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)); -} - -unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } - -void destroy_list(ListProxy* self) { - IUnknown* real = self->real; - DeviceProxy* device = self->device; - delete self; - if (real) real->Release(); - if (device) proxy_release(device); -} - -unsigned long list_release(ListProxy* self) { - const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) destroy_list(self); - return refs; -} - -HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out) { - note_list_slot(0, reinterpret_cast(riid), reinterpret_cast(out), 0, 0); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (!is_list_iid(*riid)) { - if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); - return E_NOINTERFACE; - } - if (!supports_iid(self->real, *riid)) return E_NOINTERFACE; - *out = self; - list_add_ref(self); - return S_OK; -} - -// Highest list interface the real object implements; its cumulative slot count bounds mapped forwards -// (ID3D12GraphicsCommandList8 ends at slot 81, OMSetFrontAndBackStencilRef). -unsigned detect_list_slot_count(IUnknown* real) { - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList8))) return 82; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList7))) return 81; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList6))) return 78; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList5))) return 75; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList4))) return 69; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList3))) return 67; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList2))) return 66; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList1))) return 65; - return 60; -} - -template -std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - return hr_to_u64(list_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return list_add_ref(self); - } else if constexpr (Slot == 2) { - return list_release(self); - } else if constexpr (Slot == 7) { // GetDevice: the Xbox-ABI device, as on the other proxies - note_list_slot(7, a1, a2, 0, 0); - if (a2) *reinterpret_cast(a2) = nullptr; - if (!a1) return hr_to_u64(E_POINTER); - if (!a2) { // no output: the real object's own answer - using Fn = HRESULT(WINAPI*)(IUnknown*, const IID*, void**); - return hr_to_u64(reinterpret_cast((*reinterpret_cast(self->real))[7])( - self->real, reinterpret_cast(a1), nullptr)); - } - return hr_to_u64(proxy_query_interface(self->device, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else { - note_list_slot(Slot, a1, a2, a3, a4, self->device->console_layout.load(std::memory_order_relaxed)); - constexpr unsigned pc = console_to_pc_list_slot(Slot); - if constexpr (pc == kListNotForwarded) { - if constexpr (Slot == kConsoleAllocateUpload) { - return upload_alloc(self->device, a1, a2); // (size, alignment); the comment at UploadChunk - } - return 0; // unmodelled console slot: recorded above, never a PC call - } else { - if (pc >= self->pc_slot_count) { - static std::atomic beyond_warned[kListSlots]; - bool expected = false; - if (beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " - "slots; returning E_NOTIMPL\n", - Slot, pc, self->pc_slot_count); - return hr_to_u64(E_NOTIMPL); - } - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t); - auto** const real_vtable = *reinterpret_cast(self->real); - if constexpr (Slot == 10) { - // Reset(allocator, pso): the title hands its allocator proxy; the real list takes the real one. - a1 = unwrap_object(a1); - } else if constexpr (Slot == kConsoleExecuteBundle) { - a1 = unwrap_object(a1); // the bundle is a list proxy too - } else if constexpr (Slot >= 41 && Slot <= 46) { - // The six root descriptor setters (index, GPU VA): an upload-arena CPU pointer becomes the - // chunk's device address (d3d12_xs_console_abi.md §5.3 measures slots 41/43/45 for the compute - // side; the graphics setters interleave on even slots). - a2 = upload_translate(self->device, a2); - } else if constexpr (Slot == 47) { - // IASetIndexBuffer(pView): the view's BufferLocation is a GPU VA; translate in a copy so the - // title's struct is not written. - if (a1) { - auto view = *reinterpret_cast(a1); - view.BufferLocation = upload_translate(self->device, view.BufferLocation); - return reinterpret_cast(real_vtable[pc])( - self->real, reinterpret_cast(&view), a2, a3, a4, a5, a6, a7, a8, a9, - a10, a11, a12, a13, a14); - } - } else if constexpr (Slot == 48) { - // IASetVertexBuffers(start, count, views): each view's BufferLocation is a GPU VA. The views are - // translated in the proxy's scratch array for the same reason as the index view. - if (a3 && a2) { - const auto* in = reinterpret_cast(a3); - self->vb_scratch.assign(in, in + a2); - for (auto& view : self->vb_scratch) - view.BufferLocation = upload_translate(self->device, view.BufferLocation); - return reinterpret_cast(real_vtable[pc])( - self->real, a1, a2, reinterpret_cast(self->vb_scratch.data()), a4, a5, - a6, a7, a8, a9, a10, a11, a12, a13, a14); - } - } else if constexpr (Slot == 49) { - // SOSetTargets(start, count, views): BufferLocation and BufferFilledSizeLocation are both VAs. - if (a3 && a2) { - const auto* in = reinterpret_cast(a3); - self->so_scratch.assign(in, in + a2); - for (auto& view : self->so_scratch) { - view.BufferLocation = upload_translate(self->device, view.BufferLocation); - view.BufferFilledSizeLocation = - upload_translate(self->device, view.BufferFilledSizeLocation); - } - return reinterpret_cast(real_vtable[pc])( - self->real, a1, a2, reinterpret_cast(self->so_scratch.data()), a4, a5, - a6, a7, a8, a9, a10, a11, a12, a13, a14); - } - } else if constexpr (Slot == kConsoleSetDescriptorHeaps) { - UnwrappedArray heaps; - if (!heaps.fill(a2, a1)) return 0; // void on the PC side; the call simply does not happen - const std::uint64_t real_heaps = heaps.data() ? heaps.data() : a2; - return reinterpret_cast(real_vtable[pc])(self->real, a1, real_heaps, a3, a4, a5, a6, - a7, a8, a9, a10, a11, a12, a13, a14); - } - return reinterpret_cast(real_vtable[pc])(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, - a10, a11, a12, a13, a14); - } - } -} - -template -void fill_list_vtable(void** vtable, std::index_sequence) { - ((vtable[I] = reinterpret_cast(&list_slot(I)>) ), ...); -} - -void** get_list_vtable() { - static void** vtable = [] { - static void* storage[kListSlots]; - fill_list_vtable(storage, std::make_index_sequence{}); - return storage; - }(); - return vtable; -} - -bool is_list_proxy_impl(const void* list) { - return list && *reinterpret_cast(list) == reinterpret_cast(get_list_vtable()); -} - -IUnknown* list_real_or_null(const void* object) { - return is_list_proxy_impl(object) ? static_cast(static_cast(object)->real) - : nullptr; -} - -// Wraps `created` (one reference, owned by the proxy on success, released on failure) and returns `riid` from the -// proxy through `out`. -HRESULT wrap_list(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { - if (!created) return E_FAIL; - ListProxy* proxy = new (std::nothrow) ListProxy(); // (): the console body starts zeroed - if (!proxy) { - created->Release(); - return E_OUTOFMEMORY; - } - proxy->vtable = get_list_vtable(); - proxy->real = static_cast(created); - proxy->device = device; - proxy->refs.store(1, std::memory_order_relaxed); - proxy->pc_slot_count = detect_list_slot_count(created); - proxy->pin_cursor_at_limit(); - proxy_add_ref(device); // the list keeps its Xbox-ABI device alive for GetDevice - - const HRESULT hr = list_query_interface(proxy, riid, out); - if (FAILED(hr)) { - destroy_list(proxy); // no reference escaped - return hr; - } - static std::atomic logged{false}; - if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - std::fprintf(stderr, "[rt] d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", - static_cast(proxy), static_cast(created), proxy->pc_slot_count); - proxy->refs.fetch_sub(1, std::memory_order_relaxed); // drop the creation reference; `out` holds the caller's - return S_OK; -} - -// Device slot 12: CreateCommandList(node_mask, type, allocator, initial_pso, riid, out). The title hands its -// allocator proxy, which the real device unwraps to the real allocator; the created list goes back console-shaped. -HRESULT proxy_create_command_list(DeviceProxy* self, std::uint64_t node_mask, std::uint64_t type, - std::uint64_t allocator, std::uint64_t pso, const IID* riid, void** out) { - note_slot(12); - if (out) *out = nullptr; // as slot 8 - if (!riid) return E_POINTER; - if (!out) return self->real->CreateCommandList(static_cast(node_mask), - static_cast(type), - reinterpret_cast(unwrap_object(allocator)), - reinterpret_cast(pso), *riid, nullptr); - if (!self->console_lists) { - // PC caller (create_device_proxy's console_lists=false): the real list answers every PC slot, and the - // console-only pieces (slot 148, the shifted tail) are simply not there for this caller to reach. - return self->real->CreateCommandList(static_cast(node_mask), - static_cast(type), - reinterpret_cast(unwrap_object(allocator)), - reinterpret_cast(pso), *riid, out); - } - void* created = nullptr; - const HRESULT hr = self->real->CreateCommandList( - static_cast(node_mask), static_cast(type), - reinterpret_cast(unwrap_object(allocator)), - reinterpret_cast(pso), __uuidof(ID3D12GraphicsCommandList), &created); - if (FAILED(hr)) return hr; - if (!created) return E_FAIL; - return wrap_list(static_cast(created), self, riid, out); -} - // Calls the real device's slot `Slot` with these five words in the positions the thunk received them (see "A thunk // declares 14 argument words" at the top: no word may move to another stack position on the way). template @@ -2060,9 +1336,6 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 } else if constexpr (Slot == 9) { return hr_to_u64(proxy_create_command_allocator(self, a1, reinterpret_cast(a2), reinterpret_cast(a3))); - } else if constexpr (Slot == 12) { - return hr_to_u64(proxy_create_command_list(self, a1, a2, a3, a4, reinterpret_cast(a5), - reinterpret_cast(a6))); } else if constexpr (Slot == 36) { return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -2165,7 +1438,7 @@ unsigned detect_slot_count(ID3D12Device* real) { } // namespace -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool console_lists) { +HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { if (!real) return E_POINTER; if (!out) return E_POINTER; *out = nullptr; @@ -2176,7 +1449,6 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool co proxy->real = real; proxy->real_vtable = *reinterpret_cast(real); proxy->slot_count = detect_slot_count(real); - proxy->console_lists = console_lists; proxy->refs.store(1, std::memory_order_relaxed); proxy->dxgi_vtable = get_dxgi_vtable(); proxy->adapter_provider = nullptr; @@ -2243,26 +1515,12 @@ ID3D12Device* device_proxy_real_device(const void* device) { } bool device_slot_overridden(unsigned slot) { - return slot <= 2 || slot == 8 || slot == 9 || slot == 12 || slot == 14 || slot == 31 || slot == 32 || - slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || - slot == 67 || slot == 75 || slot == 76; + return slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || + slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || + slot == 75 || slot == 76; } bool is_queue_proxy(const void* queue) { return is_child_proxy(queue); } - -bool is_list_proxy(const void* list) { return is_list_proxy_impl(list); } - -ID3D12CommandList* list_proxy_real_list(const void* list) { - if (!is_list_proxy_impl(list)) return nullptr; - return static_cast(list)->real; -} - -const char* list_tail_slot_name(unsigned slot, unsigned char console_layout) { - return list_tail_name(slot, console_layout); -} -std::uint64_t list_slot_hits(unsigned slot) { - return slot < kListSlots ? ListStats::hits[slot].load(std::memory_order_relaxed) : 0; -} bool is_fence_proxy(const void* fence) { return is_child_proxy(fence); } bool is_allocator_proxy(const void* allocator) { return is_child_proxy(allocator); } diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 33f38a2c4..8ff508e6f 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -24,23 +24,14 @@ // Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence // proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded // in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its -// first four argument words and answered S_OK on a queue or refused with E_NOTIMPL on a fence or allocator. A slot -// past the table faults on the vtable read inside a +// first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a // reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods -// (PresentX, SuspendX, ResumeX) will show up; the sibling-layer measurement puts PresentX at queue slot 30 or 32 -// and SignalX at 23 or 25 by runtime layout (docs/d3d12_xs_console_abi.md §4, unverified here). The proxy detects -// the layout from a fence reaching slot 16/17, forwards SignalX as PC Signal, routes PresentX to the presentation -// core under LEONIDA_VULKAN_DEVICE and answers the remaining console-only queue methods S_OK (frame pacing flows -// through them) without forwarding, and that -// the console keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are +// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed, and that the console +// keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are // unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device // CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority -// (46) and EnqueueMakeResident (50). Command lists come back from device slot 12 behind a console-shaped list -// proxy: console vtable order (PC order through slot 26, four console-only extras at 27-30, the PC chain shifted -// +4 through console 59, measured tail slots at 60/61/146), the write cursor pinned at the record limits so a -// title's inline writers always take the vtable path, unmodelled slots recorded and refused. Queue -// ExecuteCommandLists unwraps the list array; the list's own Reset, ExecuteBundle and SetDescriptorHeaps unwrap -// allocator, list and heap proxies. QueryInterface answers only the +// (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a +// heap proxy given to a list's SetDescriptorHeaps reaches the real list as it is. QueryInterface answers only the // modelled interfaces; one the real object has but the proxy does not model is logged once and refused. #pragma once @@ -53,10 +44,7 @@ namespace rt::d3d12_xs { // Wraps `real` and returns the requested device interface through `out`. Takes ownership of one reference to // `real` on success; on failure the caller keeps its reference. Returns E_NOINTERFACE if `riid` is not a D3D12 // device interface the PC device implements. -// `console_lists` shapes the command lists CreateCommandList returns: true (the title path) gives the -// console-shaped object the Xbox ABI calls; false hands the real list back for callers compiled against -// the PC headers (the GPU test harnesses), whose vtable indices past slot 26 do not exist in console order. -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool console_lists = true); +HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out); // True when `device` points at a proxy created by create_device_proxy. Used by the tests. bool is_device_proxy(const void* device); @@ -131,20 +119,6 @@ bool command_object_tables_guarded(); inline constexpr GUID kLeonidaCommandAllocatorTag{ 0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}}; bool is_allocator_proxy(const void* allocator); -// Command-list proxies (device slot 12): the console-shaped object. is_list_proxy / list_proxy_real_list give the -// same access as the queue, fence and allocator helpers; list_slot_hits counts calls per console slot. -bool is_list_proxy(const void* list); -ID3D12CommandList* list_proxy_real_list(const void* list); -std::uint64_t list_slot_hits(unsigned slot); -// The diagnostic name of a command-list slot on the list tail, where the newer console layout sits two slots later -// than the older one from CopyTextureRegionX on (docs/d3d12_xs_console_abi.md 5.3: newer->older pairs 85->83, -// 86->84, 87->85, 90->88, 91->89, 92->90, 95->93, 96->94). `console_layout` is the device-wide layout the queue -// proxy detects (kConsoleLayoutOlder or kConsoleLayoutNewer). Null when the layout is not known yet or the slot is -// not a measured tail slot of that layout, so that a slot number is never given the other layout's name. Naming -// only: no slot is forwarded because of it. -inline constexpr unsigned char kConsoleLayoutOlder = 1; -inline constexpr unsigned char kConsoleLayoutNewer = 2; -const char* list_tail_slot_name(unsigned slot, unsigned char console_layout); // The wrapped allocator (no reference added), or null when `allocator` is not an allocator proxy. ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator); unsigned allocator_proxy_slot_count(const void* allocator); diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 9d3810705..2fa04c75f 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -14,9 +14,7 @@ #include #include -#include #include -#include #include #include #include @@ -171,87 +169,26 @@ HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { // GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any // bundled package module already mapped by the native loader. HMODULE WINAPI get_module_handle_a(LPCSTR name) { - if (!name) { - if (void* h = bundled_main_module()) return reinterpret_cast(h); - return GetModuleHandleA(name); + if (name) { + if (HMODULE h = owned_handle(name)) return h; + const std::string dll = module_name(name); + if (!dll.empty()) + if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); } - if (HMODULE h = owned_handle(name)) return h; - const std::string dll = module_name(name); - if (!dll.empty()) - if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); return GetModuleHandleA(name); } HMODULE WINAPI get_module_handle_w(LPCWSTR name) { - if (!name) { - // The process's own image: the mapped exe, not gta6rt. - if (void* h = bundled_main_module()) return reinterpret_cast(h); - return GetModuleHandleW(name); + if (name) { + const std::string path = narrow(name); + if (HMODULE h = owned_handle(path)) return h; + const std::string dll = module_name(path); + if (!dll.empty()) + if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); } - const std::string path = narrow(name); - if (HMODULE h = owned_handle(path)) return h; - const std::string dll = module_name(path); - if (!dll.empty()) - if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); return GetModuleHandleW(name); } -// The Win32 spelling of a stored module path: backslashes throughout, and a unix-absolute path (a leading "/", only -// possible under Wine) becomes Z:\..., the drive Wine maps at the filesystem root. A relative stored path is made -// absolute through the host first, so the result is always drive-qualified. -std::wstring windows_form(const std::filesystem::path& p) { - std::wstring s = p.native(); - for (auto& c : s) - if (c == L'/') c = L'\\'; - if (s.size() >= 2 && s[1] != L':' && s[0] == L'\\' && s[1] != L'\\') s.insert(0, L"Z:"); - if (s.size() < 2 || s[1] != L':') { - std::error_code ec; - s = std::filesystem::absolute(s, ec).native(); - for (auto& c : s) - if (c == L'/') c = L'\\'; - if (s.size() >= 2 && s[1] != L':' && s[0] == L'\\' && s[1] != L'\\') s.insert(0, L"Z:"); - } - return s; -} - -// GetModuleFileName answers for the mapped images: nullptr is the process's own image (the exe the loader mapped, -// not gta6rt.exe) and a bundled module's handle names that module. Host modules fall through. -DWORD WINAPI get_module_file_name_w(HMODULE module, LPWSTR buffer, DWORD size) { - const std::filesystem::path* p = bundled_module_path(module); - if (!p) return GetModuleFileNameW(module, buffer, size); - if (!buffer || !size) { - SetLastError(ERROR_INVALID_PARAMETER); - return 0; - } - const std::wstring s = windows_form(*p); - if (s.size() >= size) { - std::wmemcpy(buffer, s.c_str(), size - 1); - buffer[size - 1] = 0; - SetLastError(ERROR_INSUFFICIENT_BUFFER); - return size; - } - std::wmemcpy(buffer, s.c_str(), s.size() + 1); - return static_cast(s.size()); -} - -DWORD WINAPI get_module_file_name_a(HMODULE module, LPSTR buffer, DWORD size) { - const std::filesystem::path* p = bundled_module_path(module); - if (!p) return GetModuleFileNameA(module, buffer, size); - if (!buffer || !size) { - SetLastError(ERROR_INVALID_PARAMETER); - return 0; - } - const std::string s = narrow(windows_form(*p).c_str()); - if (s.size() >= size) { - std::memcpy(buffer, s.c_str(), size - 1); - buffer[size - 1] = 0; - SetLastError(ERROR_INSUFFICIENT_BUFFER); - return size; - } - std::memcpy(buffer, s.c_str(), s.size() + 1); - return static_cast(s.size()); -} - FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { if (const Pseudo* p = pseudo(module)) { if (!name) { @@ -323,8 +260,6 @@ BOOL WINAPI disable_thread_calls(HMODULE module) { {dll, "LoadLibraryExW", reinterpret_cast(&rt::shims::library_loader::load_library_ex_w)}, \ {dll, "GetModuleHandleA", reinterpret_cast(&rt::shims::library_loader::get_module_handle_a)}, \ {dll, "GetModuleHandleW", reinterpret_cast(&rt::shims::library_loader::get_module_handle_w)}, \ - {dll, "GetModuleFileNameA", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_a)}, \ - {dll, "GetModuleFileNameW", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_w)}, \ {dll, "GetProcAddress", reinterpret_cast(&rt::shims::library_loader::get_proc_address)}, \ {dll, "FreeLibrary", reinterpret_cast(&rt::shims::library_loader::free_library)}, \ {dll, "DisableThreadLibraryCalls", reinterpret_cast(&rt::shims::library_loader::disable_thread_calls)} diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 730c3cbf9..37ff540c5 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -76,11 +76,9 @@ std::vector g_lookups; // left out on purpose. // gameinput.dll GameInputCreate: HRESULT (gaming/gdk/docs/reference/input/gameinput/functions/ // gameinputcreate). The shim implements it (runtime/shims/gameinput.cpp); the class is -// listed anyway for a build or import it misses. "#1" is the same function by ordinal: -// ordinal 1 is GameInputCreate in the console export inventory (docs/d3d12_vulkan.md §7). +// listed anyway for a build or import it misses. // xaudio2_9.dll XAudio2Create: HRESULT (learn.microsoft.com/windows/win32/api/xaudio2/ // xaudio2_9redist.dll nf-xaudio2-xaudio2create). xaudio2_9.dll is the console name (docs/d3d12_vulkan.md §7). -// "#1" is XAudio2Create by ordinal, ordinal 1 verified in the same inventory. // dstorage.dll DStorageGetFactory: HRESULT (learn.microsoft.com/windows/win32/api/dstorage/ // dstorage_xs.dll nf-dstorage-dstoragegetfactory). dstorage_xs.dll is the console name. const char* const kNotHResult[] = { @@ -110,14 +108,9 @@ ReturnClass classify(const std::string& dll, const std::string& name) { name == "DXGIDeclareAdapterRemovalSupport") return ReturnClass::HResult; } else if (dll == "xaudio2_9.dll" || dll == "xaudio2_9redist.dll") { - if (name == "XAudio2Create" || name == "#1") return ReturnClass::HResult; - // Host xaudio2_9.dll ordinals 8-10 are XAudio2CreateV2_9 / XAudio2CreateWithVersionInfo / - // XAudio2CreateWithSharedContexts (measured on the System32 export table); the redist's ordinal - // table is not confirmed, so only the system copy gets them. - if (dll == "xaudio2_9.dll" && (name == "#8" || name == "#9" || name == "#10")) - return ReturnClass::HResult; + if (name == "XAudio2Create") return ReturnClass::HResult; } else if (dll == "gameinput.dll") { - if (name == "GameInputCreate" || name == "#1") return ReturnClass::HResult; + if (name == "GameInputCreate") return ReturnClass::HResult; } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll") { if (name == "DStorageGetFactory") return ReturnClass::HResult; } else if (dll == "xgameruntime.dll") { @@ -461,20 +454,6 @@ bool owns_bundled_module_handle(void* module) { return false; } -void* bundled_main_module() { - for (const auto& entry : snapshot_bundled_loaders()) - if (entry.ops->main_module) - if (void* h = entry.ops->main_module(entry.ctx)) return h; - return nullptr; -} - -const std::filesystem::path* bundled_module_path(void* module) { - for (const auto& entry : snapshot_bundled_loaders()) - if (entry.ops->module_path) - if (const std::filesystem::path* p = entry.ops->module_path(entry.ctx, module)) return p; - return nullptr; -} - Table::Table(const Entry* entries, size_t count) { for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; } diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 56597c9dc..e317ec298 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -2,7 +2,6 @@ // Add a DLL by writing a shims/.cpp with a SHIM_TABLE and listing it in CMakeLists.txt. #pragma once #include -#include #include namespace rt::shims { @@ -66,11 +65,6 @@ struct BundledModuleOps { void* (*load_bundled)(void* ctx, const std::string& dll_lower, uint32_t flags, bool& handled); void* (*get_proc)(void* ctx, void* module, const std::string& sym, bool& owns_handle); bool (*owns_handle)(void* ctx, void* module); - // The handle of the first image the loader mapped (the exe), for GetModuleHandle(nullptr). Null if none. - void* (*main_module)(void* ctx); - // The path a mapped module was loaded from, for GetModuleFileName: `module` nullptr asks for the main image, - // a handle asks for that module; null when the handle is not the loader's (or it has no main image). - const std::filesystem::path* (*module_path)(void* ctx, void* module); }; void add_bundled_loader(void* ctx, const BundledModuleOps* ops); void remove_bundled_loader(void* ctx); @@ -79,8 +73,6 @@ void* find_loaded_bundled_module(const std::string& dll_lower); void* load_bundled_module(const std::string& dll_lower, uint32_t flags, bool& handled); void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); -void* bundled_main_module(); -const std::filesystem::path* bundled_module_path(void* module); // Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return // address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack). diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index f48ecd940..e8c504f0f 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -870,21 +870,11 @@ bool bundled_owns_handle(void* ctx, void* module) { return static_cast(ctx)->owns_module_handle(module); } -void* bundled_main_module(void* ctx) { - return static_cast(ctx)->main_module(); -} - -const std::filesystem::path* bundled_module_path(void* ctx, void* module) { - return static_cast(ctx)->module_path_for(module); -} - const shims::BundledModuleOps kBundledOps{ &bundled_find_loaded, &bundled_load, &bundled_get_proc, &bundled_owns_handle, - &bundled_main_module, - &bundled_module_path, }; } // namespace @@ -1067,19 +1057,6 @@ bool Loader::owns_module_handle(void* module_handle) const { return false; } -void* Loader::main_module() const { - std::lock_guard lock(mutex_); - return order_.empty() ? nullptr : static_cast(order_.front()->base); -} - -const std::filesystem::path* Loader::module_path_for(void* module_handle) const { - std::lock_guard lock(mutex_); - if (!module_handle) return order_.empty() ? nullptr : &order_.front()->path; - for (Module* m : order_) - if (m->base == module_handle) return &m->path; - return nullptr; -} - // x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing // through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps // are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. @@ -1402,19 +1379,6 @@ void Loader::parse_exports(Module& m) { } } -// The file-name rule LoadLibrary applies to a bare module name, the same normalisation library_loader.cpp's -// module_name() uses: lower-case, a trailing '.' dropped, ".dll" added when there is no extension. Without it an -// import naming "GameInput" or "gameinput.dll." misses the shim and owns_dll lookups while LoadLibraryExA still -// binds the real System32 module. -std::string dll_key(std::string name) { - const size_t slash = name.find_last_of("\\/"); - if (slash != std::string::npos) name.erase(0, slash + 1); - name = lower(name); - if (!name.empty() && name.back() == '.') name.pop_back(); - else if (name.find('.') == std::string::npos) name += ".dll"; - return name; -} - // Follows a forwarder string to the module and export it names. Bundled modules are searched first, with or without // the extension, because a forwarder may point at another mapped module; system DLLs go through LoadLibraryEx, whose // own GetProcAddress already follows its forwarders. Errors are "not found": the caller decides what to bind. @@ -1426,7 +1390,8 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d // A forwarder can name a module the loader shims. Shims take precedence over a bundled or host copy, exactly as // they do for a direct import in resolve(); without this, a forwarded xmem or d3d12_xs call becomes a failure thunk. - std::string shim_key = dll_key(module); + std::string shim_key = lower(module); + if (shim_key.size() < 4 || shim_key.compare(shim_key.size() - 4, 4, ".dll") != 0) shim_key += ".dll"; if (void* p = shims::find(shim_key, symbol)) { binding = Binding::Shim; return p; @@ -1458,24 +1423,18 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d return nullptr; // the bundled module exists and does not export it; don't look for a host namesake } - // A module the shims own (xgameruntime.dll, gameinput.dll, d3d12_xs.dll, xmem.dll) never binds to a host - // namesake: xgameruntime.dll and gameinput.dll exist on the PC too, and a call into the real Gaming Services - // runtime would bypass the offline shims the same way a direct host load would (owns_dll, registry.cpp). - if (!shims::owns_dll(shim_key)) { - HMODULE h = LoadLibraryExA(module.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!h) return nullptr; - if (prefer_host_copy(shim_key)) redirect_pc_to_file_header(h); - FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(static_cast(ordinal)) : symbol.c_str()); - if (!p) return nullptr; - if (prefer_host_copy(shim_key)) redirect_pc_to_file_header_at(reinterpret_cast(p)); - binding = Binding::Host; - return reinterpret_cast(p); - } - return nullptr; + HMODULE h = LoadLibraryExA(module.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!h) return nullptr; + if (prefer_host_copy(shim_key)) redirect_pc_to_file_header(h); + FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(static_cast(ordinal)) : symbol.c_str()); + if (!p) return nullptr; + if (prefer_host_copy(shim_key)) redirect_pc_to_file_header_at(reinterpret_cast(p)); + binding = Binding::Host; + return reinterpret_cast(p); } void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { - std::string key = dll_key(dll); + std::string key = lower(dll); std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; if (void* p = shims::find(key, sym)) { @@ -1499,18 +1458,13 @@ void* Loader::resolve(Module& m, const std::string& dll, const std::string& name } } // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search. - // A shim-owned module is skipped: xgameruntime.dll and gameinput.dll have real PC namesakes in System32, and an - // unregistered import must end unimplemented, exactly as GetProcAddress on the pseudo-handle returns NULL - // (library_loader.cpp). Binding it to Gaming Services would also leave the process online-capable. - if (!shims::owns_dll(key)) { - if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { - if (prefer_host_copy(key)) redirect_pc_to_file_header(h); // before any mapped code can throw through it - FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()); - if (p) { - if (prefer_host_copy(key)) redirect_pc_to_file_header_at(reinterpret_cast(p)); - m.imports.push_back({dll, sym, Binding::Host}); - return reinterpret_cast(p); - } + if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { + if (prefer_host_copy(key)) redirect_pc_to_file_header(h); // before any mapped code can throw through it + FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()); + if (p) { + if (prefer_host_copy(key)) redirect_pc_to_file_header_at(reinterpret_cast(p)); + m.imports.push_back({dll, sym, Binding::Host}); + return reinterpret_cast(p); } } m.imports.push_back({dll, sym, Binding::Unimplemented}); diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 57962c9b4..82f05de12 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -118,10 +118,6 @@ public: void* load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled); void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); bool owns_module_handle(void* module_handle) const; - // The first image load() mapped (the exe), for GetModuleHandle(nullptr); the path a mapped module was loaded - // from (nullptr for the main image), for GetModuleFileName. Null when the handle is not this loader's. - void* main_module() const; - const std::filesystem::path* module_path_for(void* module_handle) const; private: void initialise(Module& m); diff --git a/runtime/test/d3d12_buffer_uav_test.cpp b/runtime/test/d3d12_buffer_uav_test.cpp index c2ea4fb37..a2fa90330 100644 --- a/runtime/test/d3d12_buffer_uav_test.cpp +++ b/runtime/test/d3d12_buffer_uav_test.cpp @@ -161,7 +161,7 @@ int run_shaders(vktest::Device& d, const std::filesystem::path& root_dir, unsign EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index 64937f0f3..1c4e3eed3 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -307,7 +307,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-CBV table (s8, its 32-bit VA): diff --git a/runtime/test/d3d12_debug_markers_test.cpp b/runtime/test/d3d12_debug_markers_test.cpp index b5d1a0034..a87fd030f 100644 --- a/runtime/test/d3d12_debug_markers_test.cpp +++ b/runtime/test/d3d12_debug_markers_test.cpp @@ -100,9 +100,7 @@ HRESULT make_device(const vktest::Device& d, bool debug_utils, ID3D12Device** ou ID3D12Device* inner = nullptr; HRESULT hr = rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)); if (FAILED(hr)) return hr; - // PC-shaped lists: this test calls the marker methods the console ABI does not have. - hr = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(out), - /*console_lists=*/false); + hr = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(out)); if (FAILED(hr)) { inner->Release(); return hr; @@ -137,9 +135,6 @@ int run_markers(ID3D12Device* device) { const char ansi[] = "ansi pass and more"; const wchar_t spans[] = L"spans two lists"; const std::uint64_t blob[2] = {0x1234, 0x5678}; - // make_device passes console_lists=false, so first/second are the real PC-shaped lists — the console - // ABI has no SetMarker or BeginEvent, and its one marker slot (EndEvent at console 60) would land here - // on a shifted index. ExecuteCommandLists still unwraps the proxies below. first->SetMarker(0, frame, sizeof(frame)); first->SetMarker(0, nullptr, 0); first->BeginEvent(1, ansi, 9); // "ansi pass" diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp index 301123933..e995d3e00 100644 --- a/runtime/test/d3d12_descriptor_test.cpp +++ b/runtime/test/d3d12_descriptor_test.cpp @@ -344,7 +344,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner` D3D12_FEATURE_DATA_D3D12_OPTIONS8 options8{}; diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index 17902f7bc..36e2f6e37 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -129,7 +129,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint). diff --git a/runtime/test/d3d12_f16_halves_test.cpp b/runtime/test/d3d12_f16_halves_test.cpp index bbd516e5c..c2f194e31 100644 --- a/runtime/test/d3d12_f16_halves_test.cpp +++ b/runtime/test/d3d12_f16_halves_test.cpp @@ -222,7 +222,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; diff --git a/runtime/test/d3d12_first_light_test.cpp b/runtime/test/d3d12_first_light_test.cpp index c5aea7fd5..8dcc2ca9c 100644 --- a/runtime/test/d3d12_first_light_test.cpp +++ b/runtime/test/d3d12_first_light_test.cpp @@ -134,7 +134,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); // No root parameters: the VS applies no matrix and the PS has no bindings (vk_harness pushes zeros too). diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp index fb8c3874d..f07b9eea5 100644 --- a/runtime/test/d3d12_fspx_compute_test.cpp +++ b/runtime/test/d3d12_fspx_compute_test.cpp @@ -281,7 +281,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_fspx_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_geometry_test.cpp b/runtime/test/d3d12_geometry_test.cpp index 1cfe035b7..6d8bb5957 100644 --- a/runtime/test/d3d12_geometry_test.cpp +++ b/runtime/test/d3d12_geometry_test.cpp @@ -91,7 +91,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); D3D12_ROOT_PARAMETER params[2] = {}; diff --git a/runtime/test/d3d12_m2_formats_test.cpp b/runtime/test/d3d12_m2_formats_test.cpp index 36cafd54e..751bca8e8 100644 --- a/runtime/test/d3d12_m2_formats_test.cpp +++ b/runtime/test/d3d12_m2_formats_test.cpp @@ -205,7 +205,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp index cd9448c75..f5734e754 100644 --- a/runtime/test/d3d12_m2_textured_test.cpp +++ b/runtime/test/d3d12_m2_textured_test.cpp @@ -143,7 +143,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_m3_frame_test.cpp b/runtime/test/d3d12_m3_frame_test.cpp index 86479017d..bbf8b5317 100644 --- a/runtime/test/d3d12_m3_frame_test.cpp +++ b/runtime/test/d3d12_m3_frame_test.cpp @@ -176,7 +176,7 @@ int main(int argc, char** argv) { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp index bad8ed98e..c50a63b04 100644 --- a/runtime/test/d3d12_m4_compute_test.cpp +++ b/runtime/test/d3d12_m4_compute_test.cpp @@ -134,7 +134,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp index 3437fe030..5017a01a3 100644 --- a/runtime/test/d3d12_msaa_draw_test.cpp +++ b/runtime/test/d3d12_msaa_draw_test.cpp @@ -88,7 +88,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_msaa_draw_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp index ed7d6659b..3f502fc1a 100644 --- a/runtime/test/d3d12_present_test.cpp +++ b/runtime/test/d3d12_present_test.cpp @@ -341,7 +341,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); auto presenter = rt::d3d12::create_window_presenter(inner, window); EXPECT(presenter); diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp index a37f486d7..c2dfdfc39 100644 --- a/runtime/test/d3d12_set0_compute_test.cpp +++ b/runtime/test/d3d12_set0_compute_test.cpp @@ -98,7 +98,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_set0_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp index 67e5ef5e8..ccc0d2aff 100644 --- a/runtime/test/d3d12_subgroup_test.cpp +++ b/runtime/test/d3d12_subgroup_test.cpp @@ -185,7 +185,7 @@ Result run(vktest::Device& d, const std::filesystem::path& library, const leonid CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] four constants (s4..s7 in the console compute layout, D3D-448), the V# the shaders store @@ -379,7 +379,7 @@ DrawResult draw(vktest::Device& d, const std::filesystem::path& library, const l CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 87bf185fa..62ce7b65c 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -180,7 +180,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); #endif diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index b2d4761d5..a40dc25ec 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -5074,7 +5074,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner` EXPECT(rt::d3d12_xs::is_device_proxy(device.p)); EXPECT(rt::d3d12_xs::device_proxy_slot_count(device.p) == 80); // ID3D12Device11 @@ -5402,7 +5402,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(fallback_info, IID_PPV_ARGS(&fallback_inner)))); Ref fallback_device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(fallback_inner, __uuidof(ID3D12Device), - reinterpret_cast(&fallback_device.p), /*console_lists=*/false))); + reinterpret_cast(&fallback_device.p)))); rt::d3d12::set_device_outer(fallback_inner, fallback_device.p); D3D12_FEATURE_DATA_D3D12_OPTIONS8 options8{TRUE}; EXPECT(fallback_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS8, &options8, @@ -5564,14 +5564,7 @@ int main() { Ref granted_q; EXPECT(SUCCEEDED(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&granted_q.p))) && granted_q.p); if (granted_q.p) { - // PC GetDesc shares console slot 18 with the newer layout's GetTimestampFrequency; the proxy - // serves the frequency getter while the layout is undetected, so the desc is read on the real - // queue instead. - if (auto* real_q = rt::d3d12_xs::queue_proxy_real_queue(granted_q.p)) { - EXPECT(real_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); - } else { - EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); - } + EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); } granted_q.reset(); rt::d3d12::set_global_realtime_privilege_override_for_test(-1); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 7a4e10cfd..3ed83747a 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -470,23 +470,6 @@ void test_imports() { dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR); expect_rejects("an import thunk table that runs past the image", img); } - for (const char* dll : {"TestShim", "testshim.dll."}) { - // LoadLibrary's file-name rule keys these the same as testshim.dll; without that normalisation the - // shim lookup misses while a real host namesake would still bind. - const std::string what = std::string("an import naming ") + dll + " resolves to testshim.dll's shim"; - auto importer = write_image_as(make_import_image(dll, "F"), "importer_key.exe"); - try { - rt::Loader loader(g_dir); - rt::Module& m = loader.load(importer); - if (m.imports.size() != 1 || m.imports[0].binding != rt::Binding::Shim) - return failed(what.c_str(), "the import did not bind as a shim"); - if (*reinterpret_cast(m.base + 0x1180) != reinterpret_cast(&test_shim_function)) - return failed(what.c_str(), "the address table does not hold the shim function"); - pass(what.c_str()); - } catch (const std::exception& e) { - failed(what.c_str(), e.what()); - } - } } void test_import_name_rvas() { diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 75feecf15..142eae84e 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -8,9 +8,8 @@ // - heap, queue and fence proxies are unwrapped where the real runtime receives them (Signal/Wait, // SetEventOnMultipleFenceCompletion, MakeResident/Evict/SetResidencyPriority/EnqueueMakeResident, // CreateSharedHandle), and OpenSharedHandle wraps a shared fence; -// - slots past the public chain answer the console contract — a queue slot returns S_OK having signalled -// nothing (frame pacing flows through those methods), a fence slot is refused with E_NOTIMPL — and a -// slot past either table faults on the vtable read in the guard region and is counted; +// - slots past the public chain are refused (E_NOTIMPL) up to the end of the table, and a slot past the table +// faults on the vtable read in the guard region and is counted; // - calls from eight threads at once, and repeated device, queue and fence creation without leaks; // - the child-process runner of the differential check itself: large output, hangs, crashes, failed starts. // No shaders, game data or Xbox DLLs. LEONIDA_VK_VALIDATION=1 runs the Vulkan device under @@ -385,41 +384,24 @@ int check_slots(const Backend& b) { } } - // The console queue tail answers S_OK instead of refusing: frame pacing flows through those - // methods, the contract xs_proxy_mock checks too. The two methods the proxy models — SignalX at - // 23 and PresentX at 30 on the older layout the 16/17 calls above pinned — are checked below. - // The fence tail below is still refused — nothing console-shaped was measured past its public chain. + // The refused tail: every slot from the end of the public chain to the end of the table. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { - if (slot == 23 || slot == 30) continue; before = qhits(slot); - EXPECT(as_hr(call_slot(queue.p, slot)) == S_OK); + EXPECT(as_hr(call_slot(queue.p, slot)) == E_NOTIMPL); EXPECT(qhits(slot) == before + 1 && xs::queue_slot_first_call_seen(slot)); } - // SignalX forwards to the real queue's Signal with the extra word dropped: the fence reaching 9 - // proves the call was forwarded rather than swallowed by the console-tail answer. - before = qhits(23); - EXPECT(as_hr(raw_call(queue.p, 23, reinterpret_cast(fence.p), 9)) == S_OK); - EXPECT(qhits(23) == before + 1 && xs::queue_slot_first_call_seen(23)); - if (wait_for(label, fence.p, 9)) return 1; - // PresentX is handled by the presentation front end, not refused: its status is the swapchain's - // (a black frame on the test window, or S_OK where it cannot present), so anything but E_NOTIMPL - // shows the modelled path ran. - before = qhits(30); - EXPECT(as_hr(call_slot(queue.p, 30)) != E_NOTIMPL); - EXPECT(qhits(30) == before + 1 && xs::queue_slot_first_call_seen(30)); for (unsigned slot = fence_slots; slot < xs::fence_proxy_table_size(); ++slot) { before = fhits(slot); EXPECT(as_hr(call_slot(fence.p, slot)) == E_NOTIMPL); EXPECT(fhits(slot) == before + 1 && xs::fence_slot_first_call_seen(slot)); } - // The objects still work after the console-only calls. + // The objects still work after refused calls. EXPECT(SUCCEEDED(queue->Signal(fence.p, 10))); if (wait_for(label, fence.p, 10)) return 1; EXPECT(xs::command_object_proxy_ref_count(queue.p) == 1 && xs::command_object_proxy_ref_count(fence.p) == 1); } EXPECT(xs::device_proxy_ref_count(device) == device_refs); // every queue and fence gave its reference back - std::printf("%s: every public queue and fence slot forwarded and counted; queue tail S_OK, fence tail " - "refused\n", label); + std::printf("%s: every public queue and fence slot forwarded and counted; tail refused\n", label); return 0; } diff --git a/runtime/test/unimplemented_policy_test.cpp b/runtime/test/unimplemented_policy_test.cpp index 9e961fa84..77a6e5595 100644 --- a/runtime/test/unimplemented_policy_test.cpp +++ b/runtime/test/unimplemented_policy_test.cpp @@ -229,19 +229,6 @@ void test_classification() { check(cls("xaudio2_9redist.dll", "XAudio2Create") == ReturnClass::HResult, "the redist name gets the same class"); check(cls("gameinput.dll", "GameInputCreate") == ReturnClass::HResult, "GameInputCreate is hresult"); - check(cls("xaudio2_9.dll", "#1") == ReturnClass::HResult, "xaudio2_9 ordinal 1 is XAudio2Create"); - check(cls("xaudio2_9redist.dll", "#1") == ReturnClass::HResult, "the redist ordinal gets the same class"); - check(cls("gameinput.dll", "#1") == ReturnClass::HResult, "gameinput ordinal 1 is GameInputCreate"); - check(cls("xaudio2_9.dll", "#2") == ReturnClass::Other, "another xaudio2_9 ordinal stays other"); - check(cls("gameinput.dll", "#2") == ReturnClass::Other, "another gameinput ordinal stays other"); - check(cls("xaudio2_9.dll", "#8") == ReturnClass::HResult, - "xaudio2_9 ordinal 8 is XAudio2CreateV2_9 on the host copy"); - check(cls("xaudio2_9.dll", "#9") == ReturnClass::HResult, - "xaudio2_9 ordinal 9 is XAudio2CreateWithVersionInfo on the host copy"); - check(cls("xaudio2_9.dll", "#10") == ReturnClass::HResult, - "xaudio2_9 ordinal 10 is XAudio2CreateWithSharedContexts on the host copy"); - check(cls("xaudio2_9redist.dll", "#8") == ReturnClass::Other, - "the redist's ordinal table is unconfirmed, so #8 stays other there"); check(cls("dstorage_xs.dll", "DStorageGetFactory") == ReturnClass::HResult, "the console dstorage name is hresult"); check(cls("xg_xs.dll", "XGCreateTexture2DComputer") == ReturnClass::Other, "unmeasured xg_xs import is other"); diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp index 03f6f3ad4..e15183798 100644 --- a/runtime/test/xbox_present_test.cpp +++ b/runtime/test/xbox_present_test.cpp @@ -327,7 +327,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); auto presenter = rt::d3d12::create_window_presenter(inner, window); EXPECT(presenter); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index e99702c86..f115b6655 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -70,7 +70,7 @@ namespace xs = rt::d3d12_xs; // ---- Mocks ---- -enum class Kind { device, queue, fence, resource, allocator, list }; +enum class Kind { device, queue, fence, resource, allocator }; constexpr unsigned kMockSlots = 128; constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens @@ -130,16 +130,6 @@ bool mock_has(const Mock* m, REFIID iid) { case Kind::allocator: return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) || (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag)); - case Kind::list: { - // The mock answers every graphics-command-list interface so the proxy sees the full 82-slot chain. - const IID lists[] = {__uuidof(ID3D12CommandList), __uuidof(ID3D12GraphicsCommandList), - __uuidof(ID3D12GraphicsCommandList1), __uuidof(ID3D12GraphicsCommandList2), - __uuidof(ID3D12GraphicsCommandList3), __uuidof(ID3D12GraphicsCommandList4), - __uuidof(ID3D12GraphicsCommandList5), __uuidof(ID3D12GraphicsCommandList6), - __uuidof(ID3D12GraphicsCommandList7), __uuidof(ID3D12GraphicsCommandList8)}; - for (const IID& list_iid : lists) if (IsEqualIID(iid, list_iid)) return true; - return false; - } default: return false; } } @@ -172,14 +162,13 @@ void copy_array(Mock* m, unsigned slot, std::uint64_t objects, std::uint64_t cou for (std::uint32_t i = 0; in && i < static_cast(count) && i < 4; ++i) m->array[slot][i] = in[i]; } -// `words` are the call's first six words (a1..a6), copied into the thunk's own frame. +// `words` are the call's first five words (a1..a5), copied into the thunk's own frame. std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { - const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3], a5 = words[4], a6 = words[5]; + const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3]; if (m->kind == Kind::device) { switch (slot) { case 8: return static_cast(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue case 9: return static_cast(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator - case 12: return static_cast(mock_create(m, Kind::list, a5, a6)); // CreateCommandList case 75: return static_cast(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1 case 36: return static_cast(mock_create(m, Kind::fence, a3, a4)); // CreateFence case 32: // OpenSharedHandle @@ -194,20 +183,12 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { return S_OK; } if (m->kind == Kind::fence && slot == 8) return kCompletedValue; // GetCompletedValue - if (m->kind == Kind::queue && slot == 16 && a1) { - // GetTimestampFrequency writes a fixed value — unless a1 is a mock object, which on this slot is a - // newer-layout Signal's fence, not an out pointer. - const auto at = static_cast(a1); - const auto base = reinterpret_cast(g_pool); - const bool is_mock = at >= base && at < base + sizeof(g_pool) && (at - base) % sizeof(Mock) == 0; - if (!is_mock) *reinterpret_cast(a1) = 1000000; - } return S_OK; } template std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, - std::uint64_t a5, std::uint64_t a6) { + std::uint64_t a5) { if constexpr (Slot == 0) { return static_cast(mock_query(self, reinterpret_cast(a1), reinterpret_cast(a2))); @@ -221,8 +202,8 @@ std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, s // forwarding them as stack arguments let MSVC tail-call mock_call and write into the caller's saved // registers (an optimized build corrupted the test's own locals that way). ++self->calls[Slot]; - const std::uint64_t words[] = {a1, a2, a3, a4, a5, a6}; - std::memcpy(self->args[Slot], words, 5 * sizeof(words[0])); + const std::uint64_t words[] = {a1, a2, a3, a4, a5}; + std::memcpy(self->args[Slot], words, sizeof(words)); return mock_call(self, Slot, words); } } @@ -249,10 +230,10 @@ using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std:: std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); std::uint64_t raw(const void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, - std::uint64_t a3 = 0, std::uint64_t a4 = 0, std::uint64_t a5 = 0, std::uint64_t a6 = 0) { + std::uint64_t a3 = 0, std::uint64_t a4 = 0, std::uint64_t a5 = 0) { void* const* vtable = *reinterpret_cast(object); - return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, a6, 0, 0, 0, 0, - 0, 0, 0, 0); + return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, 0, 0, 0, 0, 0, 0, + 0, 0, 0); } HRESULT hr_of(std::uint64_t value) { @@ -667,160 +648,7 @@ int check_allocators() { return 0; } -// ---- 7. Command lists (device slot 12): the console-shaped proxy and AllocateUploadMemory ---- - -int check_lists() { - const IID allocator_iid = __uuidof(ID3D12CommandAllocator); - const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); - Mock* mock = nullptr; - void* device = make_device(mock, 9, true, true); - EXPECT(device); - const unsigned long device_refs = xs::device_proxy_ref_count(device); - void* allocator = nullptr; - EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK); - Mock* const real_allocator = mock->last_child; - // CreateCommandList(node_mask, type, allocator, pso, iid, out): the allocator proxy is unwrapped on the way - // in and the list comes back console-shaped. - void* list = nullptr; - EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid), - word(&list))) == S_OK); - Mock* const real = mock->last_child; - EXPECT(real->kind == Kind::list && mock->args[12][2] == word(real_allocator)); - EXPECT(xs::is_list_proxy(list) && word(xs::list_proxy_real_list(list)) == word(real)); - EXPECT(xs::device_proxy_ref_count(device) == device_refs + 2); // allocator + list - // The console object body sits at +0x18 with the write cursor pinned at the record limits. - const auto* body = reinterpret_cast(word(list) + 0x18); - // Object offsets +0x18/+0x28/+0x30 are body[0]/body[2]/body[3]: the cursor is pinned at both record limits. - EXPECT(body[0] == body[2] && body[0] == body[3]); - // GetDevice answers with the Xbox-ABI device. - void* found = nullptr; - const IID device_iid = __uuidof(ID3D12Device); - EXPECT(hr_of(raw(list, 7, word(&device_iid), word(&found))) == S_OK && found == device); - EXPECT(release(found) >= 1); - // A forwarded console slot: Dispatch is console 14 (PC slot 14 too — order holds through 26). - EXPECT(hr_of(raw(list, 14, 1, 1, 1)) == S_OK && real->calls[14] == 1); - // Console-only extras (27-30) and the unmeasured tail are recorded and return 0, never forwarded. - EXPECT(raw(list, 27, 1, 2, 3, 4) == 0 && real->calls[27] == 0); - EXPECT(raw(list, 148, 0, 16) == 0); // AllocateUploadMemory(0, ...) refuses - // AllocateUploadMemory carves from the upload arena; a later root SRV gets a real address for it. - const std::uint64_t p1 = raw(list, 148, 4096, 64); - const std::uint64_t p2 = raw(list, 148, 16, 16); - EXPECT(p1 && p2 > p1 && (p1 & 63) == 0 && p2 >= p1 + 4096); - // Console 43 -> PC 39 (SetComputeRootShaderResourceView): the arena pointer crosses as a GPU VA (the mock - // device cannot map a real buffer, so the fallback arena translates to the same address). - EXPECT(hr_of(raw(list, 43, 0, p1)) == S_OK && real->calls[39] == 1 && real->args[39][1] == p1); - // The view-struct paths (IASetIndexBuffer console 47 -> PC 43, IASetVertexBuffers console 48 -> PC 44) reach - // the real list; the arena VAs inside the views are rewritten in the proxy's copies. - D3D12_INDEX_BUFFER_VIEW ib_view{}; - ib_view.BufferLocation = p1; - EXPECT(hr_of(raw(list, 47, word(&ib_view))) == S_OK && real->calls[43] == 1); - D3D12_VERTEX_BUFFER_VIEW vb_views[2]{}; - vb_views[0].BufferLocation = p1; - vb_views[1].BufferLocation = 0xDEAD0000; // a VA outside the arena passes through - EXPECT(hr_of(raw(list, 48, 0, 2, word(vb_views))) == S_OK && real->calls[44] == 1); - D3D12_STREAM_OUTPUT_BUFFER_VIEW so_view{}; - so_view.BufferLocation = p1; - so_view.BufferFilledSizeLocation = p2; - EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); - // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. - EXPECT(hr_of(raw(list, 146, word(list), 0)) == S_OK && real->calls[80] == 1); // enhanced Barrier -> GCL7 80 - EXPECT(release(list) == 0 && real->refs == 0); - EXPECT(release(allocator) == 0 && real_allocator->refs == 0); - EXPECT(xs::device_proxy_ref_count(device) == device_refs); - EXPECT(release(device) == 0 && mock->refs == 0); - std::printf("%s: lists come back console-shaped (cursor pinned, GetDevice, Dispatch forwarded, extras " - "recorded); AllocateUploadMemory hands out arena pointers a root SRV receives\n", g_label); - return 0; -} - -// ---- 8. SignalX layout detection ------------------------------------------------------------------------ -// A fence at queue slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that -// signals only through SignalX never reaches Signal/Wait at 16/17, so an unanswered SignalX used to return -// S_OK having signalled nothing — a waiter on that fence value then hangs (shdann's report on #2490: the first -// SignalX gave hr=0 calls=0, the value was lost). - -int check_signalx_detection() { - Mock* mock = nullptr; - void* device = make_device(mock, 9, true); - EXPECT(device); - void* queue = make_queue(device); - void* fence = make_fence(device); - EXPECT(queue && fence); - Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); - const auto real_fence = word(xs::fence_proxy_real_fence(fence)); - // Undetected layout, fence at slot 25: forwarded as Signal and pins the device to the newer layout. - EXPECT(hr_of(raw(queue, 25, word(fence), 7)) == S_OK && queue_mock->calls[14] == 1 && - queue_mock->args[14][0] == real_fence && queue_mock->args[14][1] == 7); - // Now proven newer: Signal at 16 and SignalX at 25 keep forwarding. - EXPECT(hr_of(raw(queue, 16, word(fence), 8)) == S_OK && queue_mock->calls[14] == 2 && - queue_mock->args[14][1] == 8); - EXPECT(hr_of(raw(queue, 25, word(fence), 9)) == S_OK && queue_mock->calls[14] == 3 && - queue_mock->args[14][1] == 9); - // A second queue on the same device inherits the shared detection. - void* queue2 = make_queue(device); - EXPECT(queue2); - Mock* const queue2_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue2)); - EXPECT(hr_of(raw(queue2, 25, word(fence), 11)) == S_OK && queue2_mock->calls[14] == 1 && - queue2_mock->args[14][1] == 11); - EXPECT(release(queue2) == 0); - EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); - - // Proven older stays older: a non-fence at slot 16 pins the older layout (the frequency getter), and a - // fence at 25 afterwards is an unmodelled console method — S_OK with no forward, not a second detection. - Mock* mock2 = nullptr; - void* device2 = make_device(mock2, 9, true); - void* queue3 = make_queue(device2); - void* fence3 = make_fence(device2); - EXPECT(device2 && queue3 && fence3); - Mock* const queue3_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue3)); - EXPECT(hr_of(raw(queue3, 16, 0, 0)) == S_OK && queue3_mock->calls[16] == 1 && - queue3_mock->calls[14] == 0); - EXPECT(hr_of(raw(queue3, 25, word(fence3), 13)) == S_OK && queue3_mock->calls[14] == 0); - // The older SignalX at slot 23 still forwards under the pinned-older layout. - EXPECT(hr_of(raw(queue3, 23, word(fence3), 15)) == S_OK && queue3_mock->calls[14] == 1 && - queue3_mock->args[14][1] == 15); - EXPECT(release(queue3) == 0 && release(fence3) == 0 && release(device2) == 0 && mock2->refs == 0); - - // A fence at the older SignalX slot while undetected forwards but does NOT pin: a newer title could reach - // an unmodelled slot-23 method with a fence argument, and a premature older pin would drop its real - // SignalX at 25. - Mock* mock3 = nullptr; - void* device3 = make_device(mock3, 9, true); - void* queue4 = make_queue(device3); - void* fence4 = make_fence(device3); - EXPECT(device3 && queue4 && fence4); - Mock* const queue4_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue4)); - EXPECT(hr_of(raw(queue4, 23, word(fence4), 17)) == S_OK && queue4_mock->calls[14] == 1 && - queue4_mock->args[14][1] == 17); - EXPECT(hr_of(raw(queue4, 25, word(fence4), 19)) == S_OK && queue4_mock->calls[14] == 2 && - queue4_mock->args[14][1] == 19); - EXPECT(release(queue4) == 0 && release(fence4) == 0 && release(device3) == 0 && mock3->refs == 0); - - // Ambiguous slot 18 on an undetected queue: the older GetDesc or the newer frequency getter. It is - // served as the frequency query — a desc write is far wider than the 8 bytes a frequency caller - // passes (a title often reads the frequency before its first fence call); once a fence proves the - // layout the same call keeps reaching the getter through the shifted path. - Mock* mock4 = nullptr; - void* device4 = make_device(mock4, 9, true); - void* queue5 = make_queue(device4); - void* fence5 = make_fence(device4); - EXPECT(device4 && queue5 && fence5); - Mock* const queue5_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue5)); - UINT64 hz = 0; - EXPECT(hr_of(raw(queue5, 18, word(&hz))) == S_OK && hz == 1000000 && - queue5_mock->calls[16] == 1 && queue5_mock->calls[18] == 0); - hz = 0; - EXPECT(hr_of(raw(queue5, 16, word(fence5), 8)) == S_OK); - EXPECT(hr_of(raw(queue5, 18, word(&hz))) == S_OK && hz == 1000000 && - queue5_mock->calls[16] == 2 && queue5_mock->calls[18] == 0); - EXPECT(release(queue5) == 0 && release(fence5) == 0 && release(device4) == 0 && mock4->refs == 0); - std::printf("xs_proxy_mock: SignalX on an undetected queue's slot 25 forwards as Signal and marks the " - "newer layout; proven-older stays older, a fence at 23 does not pin, and an undetected " - "slot 18 answers the frequency getter\n"); - return 0; -} - -// ---- 9. The console tail and the guard region ---- +// ---- 7. The refused tail and the guard region ---- int check_tail(bool want_guarded) { Mock* mock = nullptr; @@ -834,10 +662,8 @@ int check_tail(bool want_guarded) { // Signal (14) still reaches the real queue, with the real fence. EXPECT(hr_of(raw(queue, 14, word(fence), 5)) == S_OK && queue_mock->calls[14] == 1 && queue_mock->args[14][0] == word(xs::fence_proxy_real_fence(fence)) && queue_mock->args[14][1] == 5); - // Console-only queue methods (the tail past the PC chain, SignalX, PresentX) report S_OK instead of - // refusing: frame pacing flows through them. Nothing is forwarded — the real queue never sees them. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) - EXPECT(hr_of(raw(queue, slot)) == S_OK && queue_mock->calls[slot] == 0); + EXPECT(hr_of(raw(queue, slot)) == E_NOTIMPL && queue_mock->calls[slot] == 0); for (unsigned slot = 12; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); EXPECT(xs::queue_table_overruns() == 0 && xs::fence_table_overruns() == 0); EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); @@ -917,51 +743,13 @@ int run_fault_mode(const char* mode) { g_armed = false; if (failed) return 1; EXPECT(g_injected.load() > 0); // the proxy's own call was the one refused - std::printf("%s: %s refused %d time(s): the tables %s guarded, the proxies forward and answer their " - "console tail as before\n", m.flag, m.function, g_injected.load(), - m.guarded ? "stay" : "are not"); + std::printf("%s: %s refused %d time(s): the tables %s guarded, the proxies forward and refuse their tail as " + "before\n", m.flag, m.function, g_injected.load(), m.guarded ? "stay" : "are not"); return 0; } return 2; } -// ---- 9. List tail slot names (D3D-445) --------------------------------------------------------------------- -// From CopyTextureRegionX on, the newer layout sits two slots later than the older one (d3d12_xs_console_abi.md -// 5.3). A diagnostic name follows the device-wide layout, so slot 85 of the newer layout and slot 83 of the older -// layout are both CopyTextureRegionX, and neither number gets that name under the other layout. - -int check_list_tail_names() { - const unsigned char older = xs::kConsoleLayoutOlder, newer = xs::kConsoleLayoutNewer; - const auto same = [](const char* a, const char* b) { return a && b && std::strcmp(a, b) == 0; }; - EXPECT(same(xs::list_tail_slot_name(83, older), "CopyTextureRegionX")); - EXPECT(same(xs::list_tail_slot_name(85, newer), "CopyTextureRegionX")); - // The same numbers under the other layout are different methods. - EXPECT(!xs::list_tail_slot_name(83, newer)); // not a measured slot of the newer layout - EXPECT(xs::list_tail_slot_name(85, older) && !same(xs::list_tail_slot_name(85, older), "CopyTextureRegionX")); - // Every measured newer->older pair has one name, and the eight names differ. - const unsigned pairs[][2] = {{85, 83}, {86, 84}, {87, 85}, {90, 88}, {91, 89}, {92, 90}, {95, 93}, {96, 94}}; - for (const auto& pair : pairs) { - EXPECT(same(xs::list_tail_slot_name(pair[0], newer), xs::list_tail_slot_name(pair[1], older))); - for (const auto& other : pairs) - EXPECT(pair[1] == other[1] || - !same(xs::list_tail_slot_name(pair[1], older), xs::list_tail_slot_name(other[1], older))); - } - // Slots outside the measured set have no tail name in either layout, and no slot has one before the layout is - // known: the log then prints the slot number only, as before. - for (unsigned slot = 0; slot < 160; ++slot) { - bool older_tail = false, newer_tail = false; - for (const auto& pair : pairs) { - newer_tail = newer_tail || slot == pair[0]; - older_tail = older_tail || slot == pair[1]; - } - EXPECT((xs::list_tail_slot_name(slot, older) != nullptr) == older_tail); - EXPECT((xs::list_tail_slot_name(slot, newer) != nullptr) == newer_tail); - EXPECT(!xs::list_tail_slot_name(slot, 0)); - EXPECT(!xs::list_tail_slot_name(slot, 3)); - } - return 0; -} - } // namespace // A failure ends the process with a message on stderr, never in a dialog a test run would wait on: abort() (an @@ -983,8 +771,7 @@ int main(int argc, char** argv) { if (argc == 2) return run_fault_mode(argv[1]); if (argc != 1) return 2; if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_lists() || check_signalx_detection() || - check_list_tail_names()) + check_alloc_failures() || check_allocators()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; diff --git a/tests/semantic/test_alu_int_misc.py b/tests/semantic/test_alu_int_misc.py index 0fd484946..4342f0235 100644 --- a/tests/semantic/test_alu_int_misc.py +++ b/tests/semantic/test_alu_int_misc.py @@ -6,12 +6,6 @@ v_lshl_or_b32 D = (S0 << (S1 & 31)) | S2 v_mad_i32_i24 D = sext(S0[23:0]) * sext(S1[23:0]) + S2 (mod 2^32) v_mul_lo_u32 D = (S0 * S1) mod 2^32 - v_not_b32 D = ~S0 - v_ashrrev_i32 D.i = S1.i >> (S0.u & 31) (VOP2 reversed order: count is S0, value S1) - v_min_i32 D.i = min(S0.i, S1.i) - v_max_i32 D.i = max(S0.i, S1.i) - v_min_u32 D.u = min(S0.u, S1.u) - v_max_u32 D.u = max(S0.u, S1.u) Each case is a synthetic hand-written pixel-shader listing (operands loaded into VGPRs with v_mov_b32, one instruction, exported to mrt0), translated by tools/rdna2spirv.py and executed by spirv_mini_interp.py. The @@ -38,11 +32,6 @@ def sext24(v): return v - (1 << 24) if v & 0x800000 else v -def sext32(v): - v &= MASK32 - return v - (1 << 32) if v & 0x80000000 else v - - REFERENCE = { "v_bfm_b32": lambda s0, s1: (((1 << (s0 & 31)) - 1) << (s1 & 31)) & MASK32, "v_and_or_b32": lambda s0, s1, s2: ((s0 & s1) | s2) & MASK32, @@ -50,12 +39,6 @@ REFERENCE = { "v_lshl_or_b32": lambda s0, s1, s2: ((s0 << (s1 & 31)) | s2) & MASK32, "v_mad_i32_i24": lambda s0, s1, s2: (sext24(s0) * sext24(s1) + s2) & MASK32, "v_mul_lo_u32": lambda s0, s1: (s0 * s1) & MASK32, - "v_not_b32": lambda s0: (~s0) & MASK32, - "v_ashrrev_i32": lambda s0, s1: (sext32(s1) >> (s0 & 31)) & MASK32, - "v_min_i32": lambda s0, s1: min(sext32(s0), sext32(s1)) & MASK32, - "v_max_i32": lambda s0, s1: max(sext32(s0), sext32(s1)) & MASK32, - "v_min_u32": lambda s0, s1: min(s0 & MASK32, s1 & MASK32), - "v_max_u32": lambda s0, s1: max(s0 & MASK32, s1 & MASK32), } # (sources..., expected) -- expected words computed by hand from the ISA formulas above. @@ -121,61 +104,6 @@ CASES = { (0x00010001, 0x00010001, 0x00020001), # 2^32 + 2^17 + 1 (0x12345678, 0x9ABCDEF0, 0x242D2080), ], - "v_not_b32": [ - (0x00000000, 0xFFFFFFFF), - (0xFFFFFFFF, 0x00000000), - (0xF0F0F0F0, 0x0F0F0F0F), - (0x12345678, 0xEDCBA987), - (0xAAAAAAAA, 0x55555555), - (0x80000000, 0x7FFFFFFF), - ], - "v_ashrrev_i32": [ - # (count, value, expected): the VOP2 form shifts the second source by the first. - (0, 0x80000000, 0x80000000), - (1, 0x80000000, 0xC0000000), # sign bit fills - (4, 0xFFFFFFF0, 0xFFFFFFFF), # -16 >> 4 = -1 - (31, 0x80000000, 0xFFFFFFFF), - (32, 0x80000000, 0x80000000), # 32 & 31 = 0 - (33, 0x80000000, 0xC0000000), # 33 & 31 = 1 - (0xFFFFFFFF, 0x80000001, 0xFFFFFFFF), # count 31: -2147483647 >> 31 = -1 - (1, 0x40000000, 0x20000000), # positive: like a logical shift - (16, 0x7FFF0000, 0x00007FFF), - (8, 0xF0F0F0F0, 0xFFF0F0F0), - ], - "v_min_i32": [ - (0xFFFFFFFF, 0x00000000, 0xFFFFFFFF), # -1 < 0; an unsigned min would pick 0 - (0x80000000, 0x7FFFFFFF, 0x80000000), # INT_MIN < INT_MAX - (0x7FFFFFFF, 0x80000000, 0x80000000), - (0x00000005, 0x00000003, 0x00000003), - (0xFFFFFFFE, 0x00000002, 0xFFFFFFFE), # -2 < 2 - (0x00000000, 0x00000000, 0x00000000), - (0x12345678, 0x12345678, 0x12345678), - ], - "v_max_i32": [ - (0xFFFFFFFF, 0x00000000, 0x00000000), # -1 < 0 - (0x80000000, 0x7FFFFFFF, 0x7FFFFFFF), - (0x7FFFFFFF, 0x80000000, 0x7FFFFFFF), - (0xFFFFFFFE, 0x00000002, 0x00000002), # 2 > -2; unsigned max would pick 0xFFFFFFFE - (0x80000000, 0x00000001, 0x00000001), # 1 > INT_MIN; unsigned max would pick 0x80000000 - (0x00000005, 0x00000003, 0x00000005), - (0xABCDEF01, 0xABCDEF01, 0xABCDEF01), - ], - "v_min_u32": [ - (0xFFFFFFFF, 0x00000000, 0x00000000), # 2^32-1 > 0; a signed min would pick 0xFFFFFFFF - (0x80000000, 0x7FFFFFFF, 0x7FFFFFFF), # signed min would pick 0x80000000 - (0xFFFFFFFE, 0x00000002, 0x00000002), # signed min would pick 0xFFFFFFFE - (0x00000005, 0x00000003, 0x00000003), - (0x00000000, 0xFFFFFFFF, 0x00000000), - (0x12345678, 0x12345678, 0x12345678), - ], - "v_max_u32": [ - (0xFFFFFFFF, 0x00000000, 0xFFFFFFFF), # signed max would pick 0 - (0x80000000, 0x7FFFFFFF, 0x80000000), # signed max would pick 0x7FFFFFFF - (0xFFFFFFFE, 0x00000002, 0xFFFFFFFE), # signed max would pick 2 - (0x00000005, 0x00000003, 0x00000005), - (0x00000001, 0x80000000, 0x80000000), - (0xABCDEF01, 0xABCDEF01, 0xABCDEF01), - ], } _TMP = None @@ -249,24 +177,6 @@ class TranslatedValues(unittest.TestCase): def test_v_mul_lo_u32(self): self.check("v_mul_lo_u32") - def test_v_not_b32(self): - self.check("v_not_b32") - - def test_v_ashrrev_i32(self): - self.check("v_ashrrev_i32") - - def test_v_min_i32(self): - self.check("v_min_i32") - - def test_v_max_i32(self): - self.check("v_max_i32") - - def test_v_min_u32(self): - self.check("v_min_u32") - - def test_v_max_u32(self): - self.check("v_max_u32") - if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_scalar_cmpk_wqm.py b/tests/semantic/test_scalar_cmpk_wqm.py deleted file mode 100644 index c2ebe53c1..000000000 --- a/tests/semantic/test_scalar_cmpk_wqm.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Value tests for two scalar-ALU families the translator handles but no other test reaches: - - s_cmpk__ sX, imm16 SCC = sX K, where K is the 16-bit immediate - zero-extended for _u32 and sign-extended for _i32 - (tools/rdna2spirv.py: `v = a[1]["v"] & 0xFFFF`, - `v -= 0x10000` when the sign bit is set). - s_wqm_b32 sD, sS D = every 4-bit group of S that has any bit set becomes 0xF; - SCC = (D != 0) -- whole-quad mode on plain data - (the lane-mask path is covered by the s_wqm_b64 tests). - -Each case is a synthetic hand-written pixel-shader listing (s_mov_b32 seeds the source SGPR, one -instruction under test, s_cselect_b32 materialises SCC, v_mov_b32 carries results to the export), -translated by tools/rdna2spirv.py and executed by spirv_mini_interp.py. Expected values are -hand-computed constants; a plain-Python ISA reference is checked against them so a typo in either -is caught. Standard library only. -""" -import os -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF - - -def s32(v): - v &= MASK32 - return v - (1 << 32) if v & 0x80000000 else v - - -def ref_cmpk(op, s0, imm): - """RDNA2 ISA: imm16 zero-extended for u32, sign-extended for i32; then the scalar compare.""" - cond, ty = op[len("s_cmpk_"):].rsplit("_", 1) - k = imm & 0xFFFF - if ty == "i32" and k & 0x8000: - k -= 0x10000 - a, b = (s32(s0), k) if ty == "i32" else (s0 & MASK32, k) - return int({"eq": a == b, "ne": a != b, "lg": a != b, "lt": a < b, - "le": a <= b, "gt": a > b, "ge": a >= b}[cond]) - - -def ref_wqm_b32(x): - """Each nibble with any bit set becomes 0xF.""" - out = 0 - for n in range(8): - if (x >> (4 * n)) & 0xF: - out |= 0xF << (4 * n) - return out - - -# (op, s0, imm16, expected SCC). The u32 cases with s0's upper bits set discriminate the -# zero-extended immediate from a low-16-bit compare; the i32 cases discriminate sign- from -# zero-extension and signed from unsigned ordering. -CMPK_CASES = [ - ("s_cmpk_eq_u32", 0x0000BEEF, 0xBEEF, 1), - ("s_cmpk_eq_u32", 0x0001BEEF, 0xBEEF, 0), # not equal: K is 0x0000BEEF, not s0 & 0xFFFF - ("s_cmpk_lg_u32", 0x0000BEEF, 0xBEEF, 0), - ("s_cmpk_lg_u32", 0x00000005, 0x0006, 1), - ("s_cmpk_gt_u32", 0x00010000, 0xFFFF, 1), # 65536 > 65535 - ("s_cmpk_gt_u32", 0x0000FFFF, 0xFFFF, 0), # tie - ("s_cmpk_gt_u32", 0x80000000, 0x7FFF, 1), # unsigned: high bit is magnitude, not sign - ("s_cmpk_lt_u32", 0x00000000, 0x0001, 1), - ("s_cmpk_lt_u32", 0x0000FFFF, 0xFFFE, 0), - ("s_cmpk_lt_u32", 0x0000FFFE, 0xFFFF, 1), - ("s_cmpk_ge_u32", 0x0000FFFF, 0xFFFF, 1), - ("s_cmpk_ge_u32", 0x0000FFFE, 0xFFFF, 0), - ("s_cmpk_le_u32", 0x0000FFFF, 0xFFFF, 1), - ("s_cmpk_le_u32", 0x0000FFFF, 0xFFFE, 0), - # i32: the immediate sign-extends; pairs picked so the wrong extension/order flips the answer. - ("s_cmpk_eq_i32", 0xFFFF8000, 0x8000, 1), # K = -32768 - ("s_cmpk_eq_i32", 0x00008000, 0x8000, 0), # +32768 != -32768 - ("s_cmpk_eq_i32", 0xFFFFFFFF, 0xFFFF, 1), # -1 == -1 - ("s_cmpk_gt_i32", 0x00000001, 0xFFFF, 1), # 1 > -1 (zero-extended K would make this false) - ("s_cmpk_gt_i32", 0xFFFFFFFE, 0xFFFD, 1), # -2 > -3 - ("s_cmpk_lt_i32", 0xFFFFFFFF, 0x0000, 1), # -1 < 0 - ("s_cmpk_lt_i32", 0x00000001, 0xFFFF, 0), # 1 < -1 is false (1 < 65535 would be true) - ("s_cmpk_ge_i32", 0xFFFFFFFE, 0xFFFE, 1), # -2 >= -2 - ("s_cmpk_le_i32", 0xFFFFFFFE, 0xFFFE, 1), # -2 <= -2 - ("s_cmpk_le_i32", 0xFFFFFFFE, 0xFFFD, 0), # -2 <= -3 is false - ("s_cmpk_lg_i32", 0xFFFF8000, 0x8000, 0), - ("s_cmpk_lg_i32", 0xFFFF8000, 0x8001, 1), # -32768 != -32767 - ("s_cmpk_lt_i32", 0x80000000, 0x7FFF, 1), # INT_MIN < 32767 (unsigned order: false) -] - -# (s0, expected D, expected SCC) for `s_wqm_b32 s0, s2`. -WQM_CASES = [ - (0x00000001, 0x0000000F, 1), # lowest nibble only - (0x00000010, 0x000000F0, 1), # second nibble - (0x00040000, 0x000F0000, 1), # nibble 4 - (0x80000000, 0xF0000000, 1), # sign bit: still a bit - (0x00000000, 0x00000000, 0), # nothing set: D = 0, SCC = 0 - (0x12345678, 0xFFFFFFFF, 1), # every nibble nonzero - (0x0000F000, 0x0000F000, 1), # one full nibble - (0x01020304, 0x0F0F0F0F, 1), # low nibble of each byte - (0xF0F0F0F0, 0xF0F0F0F0, 1), # nibbles 1,3,5,7 set - (0x0F0F0F0F, 0x0F0F0F0F, 1), # nibbles 0,2,4,6 set -] - -_TMP = None -_PS_PATH = None - - -def setUpModule(): - global _TMP, _PS_PATH - _TMP = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP.name, "disasm")) - _PS_PATH = os.path.join(_TMP.name, "disasm", "ps_cmpk_wqm.s") - with open(os.path.join(_TMP.name, "ps_cmpk_wqm.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP - if _TMP is not None: - _TMP.cleanup() - _TMP = None - - -def run_ps(lines): - """Translate PS instruction lines; return the four exported words (v0, v1, v2, v3).""" - asm = "; test_scalar_cmpk_wqm\n" + "".join(f"\t{ln}\n" for ln in lines) + \ - "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - words = mrt0_words(spv) - return words[0], words[1], words[2], words[3] - - -class ReferenceMatchesHandConstants(unittest.TestCase): - def test_reference(self): - for op, s0, imm, want in CMPK_CASES: - with self.subTest(op=op, s0=hex(s0), imm=hex(imm)): - self.assertEqual(ref_cmpk(op, s0, imm), want) - for s0, want_d, want_scc in WQM_CASES: - with self.subTest(s0=hex(s0)): - self.assertEqual(ref_wqm_b32(s0), want_d) - self.assertEqual(int(want_d != 0), want_scc) - - -class TestCmpk(unittest.TestCase): - """s_cmpk__u32/i32: SCC observed through s_cselect_b32.""" - - def test_all_cases(self): - for op, s0, imm, want_scc in CMPK_CASES: - with self.subTest(op=op, s0=hex(s0), imm=hex(imm)): - w0, _, _, _ = run_ps([ - f"s_mov_b32 s2, {s0 & MASK32:#x}", - f"{op} s2, {imm:#x}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s1", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(w0, want_scc, - f"{op} s2={s0:#010x} imm={imm:#06x}: SCC {w0}, want {want_scc}") - - -class TestWqmB32(unittest.TestCase): - """s_wqm_b32 on plain data: nibble -> 0xF spread, SCC = (D != 0).""" - - def test_sgpr_source(self): - for s0, want_d, want_scc in WQM_CASES: - with self.subTest(s0=hex(s0)): - w0, w1, _, _ = run_ps([ - f"s_mov_b32 s2, {s0 & MASK32:#x}", - "s_wqm_b32 s0, s2", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (want_d, want_scc), - f"s_wqm_b32 {s0:#010x}: got ({w0:#010x}, {w1}), " - f"want ({want_d:#010x}, {want_scc})") - - def test_immediate_source(self): - # A literal takes the same data path: 0x1234 has all four low nibbles nonzero. - w0, w1, _, _ = run_ps([ - "s_wqm_b32 s0, 0x1234", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (0x0000FFFF, 1)) - w0, w1, _, _ = run_ps([ - "s_wqm_b32 s0, 0", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (0x00000000, 0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f16_trans.py b/tests/semantic/test_valu_f16_trans.py deleted file mode 100644 index 43105c156..000000000 --- a/tests/semantic/test_valu_f16_trans.py +++ /dev/null @@ -1,197 +0,0 @@ -"""Value tests for the f16 transcendental VALU ops no other test reaches: - - v_exp_f16 D.f16 = 2^S0.f16 (GLSL.std.450 Exp2 on the widened operand) - v_log_f16 D.f16 = log2(S0.f16) (Log2; input must be > 0) - v_sqrt_f16 D.f16 = sqrt(S0.f16) (Sqrt) - v_rsq_f16 D.f16 = 1/sqrt(S0.f16) (InverseSqrt; input must be > 0) - -v_rcp_f16 is covered elsewhere; docs/design.md's f16-transcendentals row records these four (with -v_sin/v_cos_f16, covered by test_value_semantics.py) correctly rounded on every non-NaN input, -measured over all 65,536 f16 values on an RX 6700 XT. Like the other f16 VOP1 ops, the default -op_sel reads and writes the low half of each register and keeps the other half; op_sel:[1,1] -reads and writes the high half. MODE rounding is ignored (nearest even always, SHADER-35). - -Each case is a synthetic hand-written pixel-shader listing (source word and destination seed loaded -with v_mov_b32, one instruction, exported to mrt0), translated by tools/rdna2spirv.py and executed -by spirv_mini_interp.py. Only inputs with an exactly representable f16 result are used, and inputs -GLSL.std.450 leaves undefined (log2/rsq of x <= 0, sqrt of a negative) are avoided: the interpreter -raises on them and the translator leaves them to the driver. Expected words are hand-computed f16 -constants; a plain-Python reference is checked against them. Standard library only. -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF - - -def h2f(h): - """f16 bit pattern -> float.""" - return struct.unpack(" f16 bit pattern (round to nearest even, as the ops do).""" - return struct.unpack("> 16))) << 16) - - -# (source word, destination seed, expected word). 4.0 = 0x4400, 2.0 = 0x4000, 1.0 = 0x3C00, -# 0.5 = 0x3800, 0.25 = 0x3400, 8.0 = 0x4800, 3.0 = 0x4200, -2.0 = 0xC000, 16.0 = 0x4C00 in f16. -CASES = { - "v_exp_f16": [ - (0x00004000, 0xAAAA0000, 0xAAAA4400), # 2^2 = 4.0, high half kept - (0x0000C000, 0x12340000, 0x12343400), # 2^-2 = 0.25 - (0x00004200, 0xCAFE0000, 0xCAFE4800), # 2^3 = 8.0 - (0x0000BC00, 0x00000000, 0x00003800), # 2^-1 = 0.5 - (0x00000000, 0xABCD0000, 0xABCD3C00), # 2^0 = 1.0 - ], - "v_log_f16": [ - (0x00004800, 0xAAAA0000, 0xAAAA4200), # log2(8) = 3.0 - (0x00003400, 0x11110000, 0x1111C000), # log2(0.25) = -2.0 - (0x00004000, 0x0000BEEF, 0x00003C00), # log2(2) = 1.0 - (0x00003C00, 0x56780000, 0x56780000), # log2(1) = +0 - (0x00004C00, 0x00000000, 0x00004400), # log2(16) = 4.0 - ], - "v_sqrt_f16": [ - (0x00004400, 0xAAAA0000, 0xAAAA4000), # sqrt(4) = 2.0 - (0x00003400, 0xBBBB1234, 0xBBBB3800), # sqrt(0.25) = 0.5 - (0x00003C00, 0x0000FFFF, 0x00003C00), # sqrt(1) = 1.0 - (0x00004C00, 0xDEAD0000, 0xDEAD4400), # sqrt(16) = 4.0 - ], - "v_rsq_f16": [ - (0x00004400, 0xAAAA0000, 0xAAAA3800), # rsq(4) = 0.5 - (0x00003400, 0x77770000, 0x77774000), # rsq(0.25) = 2.0 - (0x00003C00, 0x0000FFFF, 0x00003C00), # rsq(1) = 1.0 - (0x00004C00, 0x13570000, 0x13573400), # rsq(16) = 0.25 - ], -} - -# op_sel:[1,1]: the source's high half feeds the op, the result lands in the destination's high -# half and the low half is kept. -HI_CASES = { - "v_exp_f16": [ - (0xC0000000, 0x00001234, 0x34001234), # 2^-2 = 0.25 in the high half - (0x40000000, 0x0000BEEF, 0x4400BEEF), # 2^2 = 4.0 - ], - "v_log_f16": [ - (0x48000000, 0x00005678, 0x42005678), # log2(8) = 3.0 - ], - "v_sqrt_f16": [ - (0x44000000, 0x0000BEEF, 0x4000BEEF), # sqrt(4) = 2.0 - ], - "v_rsq_f16": [ - (0x34000000, 0x0000ABCD, 0x4000ABCD), # rsq(0.25) = 2.0 - ], -} - -_TMP = None - - -def setUpModule(): - global _TMP - _TMP = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP.name, "disasm")) - with open(os.path.join(_TMP.name, "ps_f16_trans.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP - if _TMP is not None: - _TMP.cleanup() - _TMP = None - - -def run_case(op, src, seed, opsel=False): - """Translate and run `op v0, v1` (v1 = src word, v0 preloaded with seed); return the mrt0 word.""" - lines = ["; test_f16_trans"] - lines.append(f"\tv_mov_b32 v1, {src & MASK32:#x}") - lines.append(f"\tv_mov_b32 v0, {seed & MASK32:#x}") - lines.append(f"\t{op} v0, v1" + (" op_sel:[1,1]" if opsel else "")) - lines += ["\texp mrt0 v0, v0, v0, v0 done vm", "\ts_endpgm", ""] - path = os.path.join(_TMP.name, "disasm", "ps_f16_trans.s") - with open(path, "w", encoding="utf-8", newline="") as f: - f.write("\n".join(lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - words = mrt0_words(spv) - if len(set(words)) != 1: - raise AssertionError(f"{op}: the four exported words differ: {[hex(w) for w in words]}") - return words[0] - - -class ReferenceMatchesHandConstants(unittest.TestCase): - def test_reference(self): - for op, cases in CASES.items(): - for src, seed, expected in cases: - with self.subTest(op=op, src=hex(src)): - self.assertEqual(ref_lo(op, src, seed), expected) - for op, cases in HI_CASES.items(): - for src, seed, expected in cases: - with self.subTest(op=op, src=hex(src), hi=1): - self.assertEqual(ref_hi(op, src, seed), expected) - - -class TranslatedValues(unittest.TestCase): - def check(self, op): - for src, seed, expected in CASES[op]: - with self.subTest(src=hex(src), seed=hex(seed)): - got = run_case(op, src, seed) - self.assertEqual(got, expected, f"{op} {src:#010x}: got {got:#010x}, " - f"expected {expected:#010x}") - - def check_hi(self, op): - for src, seed, expected in HI_CASES[op]: - with self.subTest(src=hex(src), seed=hex(seed)): - got = run_case(op, src, seed, opsel=True) - self.assertEqual(got, expected, f"{op} op_sel {src:#010x}: got {got:#010x}, " - f"expected {expected:#010x}") - - def test_v_exp_f16(self): - self.check("v_exp_f16") - self.check_hi("v_exp_f16") - - def test_v_log_f16(self): - self.check("v_log_f16") - self.check_hi("v_log_f16") - - def test_v_sqrt_f16(self): - self.check("v_sqrt_f16") - self.check_hi("v_sqrt_f16") - - def test_v_rsq_f16(self): - self.check("v_rsq_f16") - self.check_hi("v_rsq_f16") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f32_unary.py b/tests/semantic/test_valu_f32_unary.py deleted file mode 100644 index 77c8c91f2..000000000 --- a/tests/semantic/test_valu_f32_unary.py +++ /dev/null @@ -1,212 +0,0 @@ -"""Value tests for f32 unary VALU ops (the F1 table) and byte-to-float converts no other test reaches: - - v_exp_f32 D.f = 2^S0.f (GLSL.std.450 Exp2) - v_log_f32 D.f = log2(S0.f) (Log2; input must be > 0) - v_sqrt_f32 D.f = sqrt(S0.f) (Sqrt; sqrt(-0.0) is -0.0) - v_rsq_f32 D.f = 1/sqrt(S0.f) (InverseSqrt; input must be > 0) - v_floor_f32 D.f = floor(S0.f) (Floor) - v_ceil_f32 D.f = ceil(S0.f) (Ceil) - v_trunc_f32 D.f = trunc(S0.f) (Trunc, toward zero) - -v_rcp_f32 and v_fract_f32, the other two F1 entries, are already covered elsewhere -(test_valu_rcp_fdiv.py, test_float_nan_fract.py), as are the v_cvt_f32_ubyte0..3 converts -(test_int_to_float.py). - -Each case is a synthetic hand-written pixel-shader listing (the source word loaded into a VGPR with -v_mov_b32, one instruction, exported to mrt0), translated by tools/rdna2spirv.py and executed by -spirv_mini_interp.py. Only inputs whose result is exactly representable are used: the interpreter -computes Exp2/Log2/Sqrt/InverseSqrt correctly rounded and Floor/Ceil/Trunc exactly (an integral -result keeps the operand's sign, so e.g. trunc(-0.5) is -0.0), and cases that GLSL.std.450 leaves -undefined (log2/rsq of x <= 0, sqrt of a negative) are avoided because it raises on them -- the -translator intentionally leaves those to the driver (docs/design.md, denormal-flush row). The -expected words are hand-computed constants; a plain-Python reference is checked against them so a -typo in either is caught. Standard library only. -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF - - -def u2f(u): - return struct.unpack("right, v rises bottom->top (row 0 is the top of the image). - bottom_left = hp.expected_pixel(0, H - 1, W, H) - bottom_right = hp.expected_pixel(W - 1, H - 1, W, H) - top_right = hp.expected_pixel(W - 1, 0, W, H) - self.assertGreater(bottom_right[0], bottom_left[0]) # red grows to the right - self.assertGreater(top_right[1], bottom_right[1]) # green grows to the top - # b = (u+v)/2 scaled by the grid cell; top-right corner lands on an undimmed cell. - self.assertAlmostEqual(top_right[2], (top_right[0] + top_right[1]) * 0.5) - - -class TestEmitFormats(unittest.TestCase): - def test_mesh_bin_layout(self): - import tempfile - - with tempfile.TemporaryDirectory() as td: - p = os.path.join(td, "mesh.bin") - hp.write_mesh(p) - data = open(p, "rb").read() - nv, ni = struct.unpack(" None: - at = TEXT_RAW + (rva - TEXT_RVA) - buf[at:at + len(blob)] = blob - - def directory(entry: int, rva: int, size: int) -> None: - struct.pack_into(" bytes: - """An image importing xtest.dll!XTestFunc by name and xmem.dll!#7 by ordinal.""" - buf, place, directory = make_pe32plus() - directory(1, 0x1100, 40) - place(0x1100, struct.pack(" str: - path = os.path.join(tmp, name) - with open(path, "wb") as f: - f.write(blob) - return path - - -class ClassifyTest(unittest.TestCase): - def test_families(self): - for dll, name, expected in CLASSIFY_CASES: - with self.subTest(import_=f"{dll}!{name}"): - self.assertEqual(inv.classify(dll, name), expected) - - def test_function_name_is_case_sensitive(self): - # classify() compares the name exactly; only the DLL is lower-cased. - self.assertEqual(inv.classify("d3d12.dll", "d3d12createdevice"), inv.OTHER) - - -class ImportListTest(unittest.TestCase): - def test_parse(self): - imports, bad = inv.parse_import_lines([ - "d3d12_xs.dll!D3D12XboxCreateDevice", - "", - " ", - "# a comment", - " XMem.DLL ! XMemAlloc ", - "xmem.dll!#7", - ]) - self.assertEqual(imports, [("d3d12_xs.dll", "D3D12XboxCreateDevice"), - ("xmem.dll", "XMemAlloc"), ("xmem.dll", "#7")]) - self.assertEqual(bad, 0) - - def test_malformed_lines_are_skipped(self): - imports, bad = inv.parse_import_lines(["no bang here", "!name", "dll!", "ok.dll!Fine"]) - self.assertEqual(imports, [("ok.dll", "Fine")]) - self.assertEqual(bad, 3) - - def test_dll_names_normalise_like_the_loader(self): - # pe_loader.cpp's dll_key: ".dll" is added when there is no extension, one trailing '.' is - # dropped, a directory part is stripped — "GameInput" and "gameinput.dll." key gameinput.dll. - imports, bad = inv.parse_import_lines([ - "GameInput!GameInputCreate", - "gameinput.dll.!GameInputCreate", - "dir\\XMem.DLL!XMemAlloc", - ]) - self.assertEqual(imports, [("gameinput.dll", "GameInputCreate"), - ("gameinput.dll", "GameInputCreate"), - ("xmem.dll", "XMemAlloc")]) - self.assertEqual(bad, 0) - - def test_dll_key_edge_cases(self): - # The same rules the C++ applies, including the odd corners: only one trailing dot is - # dropped, and a name that is all extension keeps it. - self.assertEqual(inv.dll_key("GameInput"), "gameinput.dll") - self.assertEqual(inv.dll_key("gameinput.dll."), "gameinput.dll") - self.assertEqual(inv.dll_key("gameinput.."), "gameinput.") - self.assertEqual(inv.dll_key("api-ms-win-core-file-l2-1-0.dll"), - "api-ms-win-core-file-l2-1-0.dll") - - -class PeParseTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.tmp = tempfile.TemporaryDirectory() - cls.image = os.path.join(cls.tmp.name, "sample.exe") - with open(cls.image, "wb") as f: - f.write(build_pe32plus()) - - @classmethod - def tearDownClass(cls): - cls.tmp.cleanup() - - def test_named_and_ordinal_imports(self): - self.assertEqual(sorted(inv.pe_imports(self.image)), - [("xmem.dll", "#7"), ("xtest.dll", "XTestFunc")]) - - def test_non_pe_input_is_rejected(self): - bad = os.path.join(self.tmp.name, "not_pe.bin") - with open(bad, "wb") as f: - f.write(b"not a PE file") - with self.assertRaises(inv.PeFormatError): - inv.pe_imports(bad) - - def test_delay_imports_are_listed(self): - # Directory 13, IMAGE_DELAYLOAD_DESCRIPTOR: RvaBased attr set, name/IAT/INT as RVAs — the loader - # binds these eagerly, so they are part of the image's import surface. - buf, place, directory = make_pe32plus() - directory(13, 0x1180, 64) - place(0x1180, struct.pack("<8I", 1, 0x1300, 0x1400, 0x1240, 0x1200, 0, 0, 0)) - place(0x11A0, bytes(32)) # terminator - place(0x1200, struct.pack(" {"xgameruntime.dll", #name, ...} - self.assertIn("xgameruntime.dll!XTaskQueueCreate", self.entries) - self.assertIn("xgameruntime.dll!XGameRuntimeInitialize", self.entries) - # FILE_API(dll) -> {dll, "CreateFileA", ...}, ... - self.assertIn("kernel32.dll!CreateFileW", self.entries) - self.assertIn("api-ms-win-core-file-l2-1-0.dll!FindNextFileA", self.entries) - # LOADER(dll) - self.assertIn("kernelbase.dll!GetProcAddress", self.entries) - # UCRT(dll) and COMMAND_LINE(dll) expand to several entries each - self.assertIn("api-ms-win-crt-runtime-l1-1-0.dll!__p___argv", self.entries) - self.assertIn("kernel32.dll!GetCommandLineW", self.entries) - - def test_unregistered_pair_is_absent(self): - self.assertNotIn("xmem.dll!XNope", self.entries) - self.assertNotIn("d3d12.dll!D3D12CreateDevice", self.entries) # host DLL: classed, not shimmed - - -class ReportTest(unittest.TestCase): - IMPORTS = [ - ("d3d12_xs.dll", "D3D12XboxCreateDevice"), # hresult, implemented - ("d3d12_xs.dll", "D3D12XboxSetProcessDebugFlags"), # other, thunk - ("xgameruntime.dll", "XTaskQueueCreate"), # hresult, implemented - ("xgameruntime.dll", "XUserGetId"), # hresult, thunk - ("xmem.dll", "XMemAlloc"), # other, implemented - ("kernel32.dll", "ExitProcess"), # other, implemented - ("kernel32.dll", "NotAFunction"), # other, thunk - ("unknown.dll", "Func"), # other, thunk - ] - - @classmethod - def setUpClass(cls): - cls.implemented = inv.shim_table_entries(SHIMS_DIR) - cls.rows, cls.per_dll = inv.summarize(cls.IMPORTS, cls.implemented) - - def test_rows_classify_and_bind(self): - by_name = {f"{d}!{n}": (c, b) for d, n, c, b in self.rows} - self.assertEqual(by_name["d3d12_xs.dll!D3D12XboxCreateDevice"], (inv.HRESULT, inv.IMPLEMENTED)) - self.assertEqual(by_name["d3d12_xs.dll!D3D12XboxSetProcessDebugFlags"], (inv.OTHER, inv.THUNK)) - self.assertEqual(by_name["xgameruntime.dll!XTaskQueueCreate"], (inv.HRESULT, inv.IMPLEMENTED)) - self.assertEqual(by_name["xgameruntime.dll!XUserGetId"], (inv.HRESULT, inv.THUNK)) - self.assertEqual(by_name["xmem.dll!XMemAlloc"], (inv.OTHER, inv.IMPLEMENTED)) - self.assertEqual(by_name["kernel32.dll!ExitProcess"], (inv.OTHER, inv.IMPLEMENTED)) - self.assertEqual(by_name["kernel32.dll!NotAFunction"], (inv.OTHER, inv.HOST)) - self.assertEqual(by_name["unknown.dll!Func"], (inv.OTHER, inv.HOST)) - - def test_per_dll_counts(self): - # [imports, hresult, other, implemented, host, unimplemented thunk] - self.assertEqual(self.per_dll["d3d12_xs.dll"], [2, 1, 1, 1, 0, 1]) - self.assertEqual(self.per_dll["xgameruntime.dll"], [2, 2, 0, 1, 0, 1]) - self.assertEqual(self.per_dll["xmem.dll"], [1, 0, 1, 1, 0, 0]) - self.assertEqual(self.per_dll["kernel32.dll"], [2, 0, 2, 1, 1, 0]) - self.assertEqual(self.per_dll["unknown.dll"], [1, 0, 1, 0, 1, 0]) - - def test_duplicates_collapse(self): - rows, per_dll = inv.summarize(self.IMPORTS + [self.IMPORTS[0]], self.implemented) - self.assertEqual(len(rows), len(self.rows)) - self.assertEqual(per_dll, self.per_dll) - - def test_unnormalised_names_route_as_their_key(self): - # summarize() must route on the loader's dll_key too: "GameInput" is the registered - # gameinput.dll, not a "gameinput" host module. - rows, per_dll = inv.summarize([("GameInput", "GameInputCreate")], self.implemented) - self.assertEqual(rows, [("gameinput.dll", "GameInputCreate", inv.HRESULT, inv.IMPLEMENTED)]) - self.assertEqual(per_dll["gameinput.dll"], [1, 1, 0, 1, 0, 0]) - - def test_report_text(self): - text = inv.format_report(self.IMPORTS, self.implemented) - self.assertIn("d3d12_xs.dll!D3D12XboxCreateDevice", text) - self.assertIn("hresult", text) - self.assertIn("unimplemented thunk", text) - total = [ln for ln in text.splitlines() if ln.startswith("total")] - self.assertEqual(len(total), 1) - # 8 imports, 3 hresult, 5 other, 4 implemented, 2 host-bound, 2 thunks - self.assertRegex(total[0], r"total\s+8\s+3\s+5\s+4\s+2\s+2$") - - -class CliTest(unittest.TestCase): - def test_main_on_a_list_file(self): - with tempfile.TemporaryDirectory() as d: - path = os.path.join(d, "imports.txt") - with open(path, "w", encoding="utf-8") as f: - f.write("xmem.dll!XMemAlloc\nunknown.dll!Func\n") - stdout = io.StringIO() - with contextlib.redirect_stdout(stdout): - self.assertEqual(inv.main([path]), 0) - text = stdout.getvalue() - self.assertIn("xmem.dll!XMemAlloc", text) - self.assertIn("implemented", text) - self.assertIn("unknown.dll!Func", text) - self.assertIn("host", text) - - def test_main_reports_bad_lines(self): - with tempfile.TemporaryDirectory() as d: - path = os.path.join(d, "imports.txt") - with open(path, "w", encoding="utf-8") as f: - f.write("garbage\nxmem.dll!XMemFree\n") - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - self.assertEqual(inv.main([path]), 0) - self.assertIn("skipped", stderr.getvalue()) - self.assertIn("xmem.dll!XMemFree", stdout.getvalue()) - - def test_main_without_inputs(self): - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr): - self.assertEqual(inv.main([]), 1) - self.assertIn("no inputs", stderr.getvalue()) - - def test_main_on_a_pe_image(self): - with tempfile.TemporaryDirectory() as d: - path = os.path.join(d, "sample.exe") - with open(path, "wb") as f: - f.write(build_pe32plus()) - stdout = io.StringIO() - with contextlib.redirect_stdout(stdout): - self.assertEqual(inv.main(["--pe", path]), 0) - text = stdout.getvalue() - self.assertIn("xtest.dll!XTestFunc", text) - self.assertIn("xmem.dll!#7", text) - - def test_main_on_an_unreadable_pe(self): - with tempfile.TemporaryDirectory() as d: - path = os.path.join(d, "bad.exe") - with open(path, "wb") as f: - f.write(b"no") - stderr = io.StringIO() - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(stderr): - self.assertEqual(inv.main(["--pe", path]), 1) - self.assertIn("not a readable PE32+ image", stderr.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_shader_state.py b/tests/test_make_game_shader_state.py deleted file mode 100644 index 34d70bb3b..000000000 --- a/tests/test_make_game_shader_state.py +++ /dev/null @@ -1,412 +0,0 @@ -"""make_game.py's shader resume state: the settings recorded beside a finished translation, and whether a work -folder can be reused without carving, unpacking or translating again. - -Every input is synthetic and every machine-dependent answer (llvm-mc's version, the translator source digest) is -mocked: no GPU, no LLVM, no Vulkan SDK and no game data are needed. - - python -I tests/test_make_game_shader_state.py -""" -import contextlib -import io -import json -import os -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -import make_game # noqa: E402 - -SIGNATURE = '["llvm-mc", "Ubuntu LLVM version 21.0.0"]' -DIGEST = "a" * 64 -FLAGS = ("--no-float-controls", "--bary-fallback") - - -class TempWorkTest(unittest.TestCase): - """A temporary folder with the shaders stage's layout, and the small file helpers the tests share.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.work = tmp.name - self.dxbc = os.path.join(self.work, "shaders", "dxbc") - self.spirv = os.path.join(self.work, "shaders", "spirv") - self.disasm = os.path.join(self.dxbc, "disasm") - - def write(self, path, text, encoding="utf-8"): - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding=encoding, newline="\n") as f: - f.write(text) - return path - - def touch(self, path): - return self.write(path, "") - - def assert_fails(self, fn, *args, match=None): - err = io.StringIO() - with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as stop: - fn(*args) - self.assertEqual(stop.exception.code, 1) - if match: - self.assertIn(match, err.getvalue()) - return err.getvalue() - - -class ReadShaderSettingTest(TempWorkTest): - """read_shader_setting(): the trimmed contents of a recorded setting, or the default when it can't be read.""" - - def test_missing_file_returns_the_default(self): - self.assertEqual(make_game.read_shader_setting(os.path.join(self.work, "missing.txt")), "") - self.assertEqual(make_game.read_shader_setting(os.path.join(self.work, "missing.txt"), default="off"), - "off") - - def test_surrounding_whitespace_is_trimmed(self): - for text in ("on\n", " on \r\n", "\n\ton\t\n"): - with self.subTest(text=text): - path = self.write(os.path.join(self.work, "setting.txt"), text) - self.assertEqual(make_game.read_shader_setting(path), "on") - - def test_empty_file_is_empty_not_the_default(self): - path = self.touch(os.path.join(self.work, "empty.txt")) - self.assertEqual(make_game.read_shader_setting(path, default="off"), "") - - def test_a_folder_where_the_file_should_be_returns_the_default(self): - # A stopped run can leave a folder where a marker belongs; reading it must not raise. - os.makedirs(os.path.join(self.work, "marker.txt")) - self.assertEqual(make_game.read_shader_setting(os.path.join(self.work, "marker.txt"), default="off"), - "off") - - def test_invalid_utf8_is_replaced_not_raised(self): - path = os.path.join(self.work, "setting.txt") - with open(path, "wb") as f: - f.write(b"\xffon\n") - value = make_game.read_shader_setting(path) - self.assertTrue(value.startswith("\ufffd"), value) - self.assertNotEqual(value, "on") - - -class RequestedShaderModeTest(unittest.TestCase): - """requested_shader_mode(): whether the translation should have wave64 emulation on.""" - - CASES = ( - ("", True, False, "on"), - ("off", True, False, "on"), - ("on", True, False, "on"), - ("on", False, True, "on"), - ("on", False, False, "off"), - ("off", False, True, "off"), - ("off", False, False, "off"), - ("", False, False, "off"), - ("", False, True, "off"), - ("ON", False, True, "off"), - ) - - def test_table(self): - for had, emulate, keep_emulated, want in self.CASES: - with self.subTest(had=had, emulate=emulate, keep_emulated=keep_emulated): - self.assertEqual(make_game.requested_shader_mode(had, emulate, keep_emulated), want) - - def test_explicit_emulation_wins_over_a_native_folder(self): - self.assertEqual(make_game.requested_shader_mode("off", True, False), "on") - - def test_only_auto_keeps_an_emulated_folder_on(self): - self.assertEqual(make_game.requested_shader_mode("on", False, True), "on") - self.assertEqual(make_game.requested_shader_mode("on", False, False), "off") - - -class TranslatorFlagsSettingTest(unittest.TestCase): - """translator_flags_setting(): the exact text recorded in spirv/translator_flags.txt.""" - - def test_no_fallbacks_is_empty(self): - self.assertEqual(make_game.translator_flags_setting(()), "") - - def test_one_flag(self): - self.assertEqual(make_game.translator_flags_setting(("--bary-fallback",)), "--bary-fallback") - - def test_order_is_kept_and_flags_are_space_separated(self): - self.assertEqual(make_game.translator_flags_setting(FLAGS), - "--no-float-controls --bary-fallback") - self.assertEqual(make_game.translator_flags_setting(tuple(reversed(FLAGS))), - "--bary-fallback --no-float-controls") - - -class DisassemblyStatusTest(TempWorkTest): - """disassembly_status(): a disassembly folder counts only with the marker of the llvm-mc that made it, - and only when the listings on disk agree with the unpack inventory.""" - - INACTIVE = (False, False, set()) - - def setUp(self): - super().setUp() - os.makedirs(self.disasm) - self.marker = os.path.join(self.dxbc, "disasm.done") - self.write(os.path.join(self.dxbc, "index.json"), json.dumps([{"file": "s0.dxbc"}])) - self.write(os.path.join(self.dxbc, "fssm_index.json"), json.dumps([{"name": "s0"}])) - self.write(os.path.join(self.disasm, "s0.s"), "synthetic listing\n") - - def status(self): - return make_game.disassembly_status(self.dxbc, SIGNATURE) - - def test_a_matching_done_marker_is_complete(self): - # The pre-inventory marker recorded only the llvm-mc signature: it is complete when every - # unpacked shader has a listing, and it cannot resume. - self.write(self.marker, SIGNATURE + "\n") - self.assertEqual(self.status(), (True, False, set())) - - def test_surrounding_whitespace_in_the_marker_is_ignored(self): - self.write(self.marker, " " + SIGNATURE + " \n\n") - self.assertEqual(self.status(), (True, False, set())) - - def test_a_marker_for_another_llvm_mc_is_not_a_match(self): - self.write(self.marker, SIGNATURE + "\n") - self.assertEqual(make_game.disassembly_status(self.dxbc, '["llvm-mc", "LLVM version 18.0.0"]'), - self.INACTIVE) - - def test_a_missing_marker_is_not_a_match(self): - self.assertEqual(self.status(), self.INACTIVE) - - def test_a_missing_disassembly_folder_is_not_a_match(self): - # The marker alone is not proof: a stopped or failed run can leave it without the .s files. - self.write(self.marker, SIGNATURE + "\n") - os.remove(os.path.join(self.disasm, "s0.s")) - os.rmdir(self.disasm) - self.assertEqual(self.status(), self.INACTIVE) - - def test_a_missing_listing_is_not_complete(self): - self.write(self.marker, SIGNATURE + "\n") - os.remove(os.path.join(self.disasm, "s0.s")) - self.assertEqual(self.status(), self.INACTIVE) - - def test_a_folder_where_the_marker_belongs_is_not_a_match(self): - os.makedirs(self.marker) - self.assertEqual(self.status(), self.INACTIVE) - - def test_an_empty_marker_is_not_a_match(self): - self.touch(self.marker) - self.assertEqual(self.status(), self.INACTIVE) - - def test_a_started_marker_offers_resume(self): - self.write(os.path.join(self.dxbc, "disasm.started"), SIGNATURE + "\n") - self.assertEqual(self.status(), (False, True, set())) - - def test_an_inventory_marker_reports_what_it_expects(self): - recorded = json.dumps({"llvm": SIGNATURE, "listings": ["s0"]}) - self.write(self.marker, recorded + "\n") - self.assertEqual(self.status(), (True, True, {"s0"})) - - def test_an_inventory_started_marker_resumes_against_the_record(self): - recorded = json.dumps({"llvm": SIGNATURE, "listings": ["s0", "s1"]}) - self.write(os.path.join(self.dxbc, "index.json"), - json.dumps([{"file": "s0.dxbc"}, {"file": "s1.dxbc"}])) - self.write(os.path.join(self.dxbc, "fssm_index.json"), - json.dumps([{"name": "s0"}, {"name": "s1"}])) - self.write(self.marker.replace("done", "started"), recorded + "\n") - # s1.s was never written before the stop: resume is offered, complete is not. - self.assertEqual(self.status(), (False, True, {"s0", "s1"})) - - def test_an_inventory_outside_the_unpack_set_is_rejected(self): - recorded = json.dumps({"llvm": SIGNATURE, "listings": ["s0", "removed"]}) - self.write(self.marker, recorded + "\n") - self.assertEqual(self.status(), self.INACTIVE) - - def test_a_symlinked_listing_disqualifies_the_folder(self): - target = self.touch(os.path.join(self.work, "elsewhere.s")) - try: - os.symlink(target, os.path.join(self.disasm, "linked.s")) - except (OSError, NotImplementedError): - self.skipTest("this platform cannot create symbolic links") - self.write(self.marker, SIGNATURE + "\n") - self.assertEqual(self.status(), self.INACTIVE) - - -class PrepareShaderDisassemblyTest(TempWorkTest): - """prepare_shader_disassembly(): drop generated assembly before a fresh run — nothing else, and - nowhere outside the work folder. A resumed run keeps the listings that finished.""" - - def setUp(self): - super().setUp() - os.makedirs(self.disasm) - - def test_removes_only_generated_assembly(self): - kept = [os.path.join(self.disasm, "shader.spv"), os.path.join(self.disasm, "notes.txt")] - for name in ("a.s", "b.s"): - self.touch(os.path.join(self.disasm, name)) - for path in kept: - self.touch(path) - os.makedirs(os.path.join(self.disasm, "nested.s")) # a folder, not a file: left alone - - make_game.prepare_shader_disassembly(self.work, self.disasm, resume=False) - - self.assertEqual(sorted(os.listdir(self.disasm)), - ["nested.s", "notes.txt", "shader.spv"]) - - def test_a_resumed_run_keeps_its_listings(self): - for name in ("a.s", "b.s"): - self.touch(os.path.join(self.disasm, name)) - make_game.prepare_shader_disassembly(self.work, self.disasm, resume=True) - self.assertEqual(sorted(os.listdir(self.disasm)), ["a.s", "b.s"]) - - def test_symlinked_assembly_is_removed_without_following_it(self): - target = self.touch(os.path.join(self.work, "elsewhere.s")) - link = os.path.join(self.disasm, "linked.s") - try: - os.symlink(target, link) - except (OSError, NotImplementedError): - self.skipTest("this platform cannot create symbolic links") - make_game.prepare_shader_disassembly(self.work, self.disasm, resume=False) - self.assertFalse(os.path.lexists(link)) - self.assertTrue(os.path.isfile(target), "the symlink's target must survive") - - def test_a_missing_disassembly_folder_is_fine(self): - os.rmdir(self.disasm) - make_game.prepare_shader_disassembly(self.work, self.disasm, resume=False) - - def test_a_folder_outside_the_work_folder_is_refused(self): - outside = tempfile.TemporaryDirectory() - self.addCleanup(outside.cleanup) - victim = self.touch(os.path.join(outside.name, "a.s")) - self.assert_fails(make_game.prepare_shader_disassembly, self.work, outside.name, False, - match="must be inside the work folder") - self.assertTrue(os.path.isfile(victim), "nothing outside the work folder may be removed") - - def test_a_sibling_with_the_right_name_is_refused(self): - sibling = os.path.join(self.dxbc, "disasm-old") - os.makedirs(sibling) - victim = self.touch(os.path.join(sibling, "a.s")) - self.assert_fails(make_game.prepare_shader_disassembly, self.work, sibling, False, - match="must be inside the work folder") - self.assertTrue(os.path.isfile(victim)) - - def test_another_spelling_of_the_same_folder_is_accepted(self): - victim = self.touch(os.path.join(self.disasm, "a.s")) - roundabout = os.path.join(self.work, "shaders", "dxbc", "..", "dxbc", "disasm") - make_game.prepare_shader_disassembly(self.work, roundabout, resume=False) - self.assertFalse(os.path.exists(victim)) - - def test_a_link_to_a_folder_outside_is_refused(self): - outside = tempfile.TemporaryDirectory() - self.addCleanup(outside.cleanup) - victim = self.touch(os.path.join(outside.name, "a.s")) - os.rmdir(self.disasm) - try: - os.symlink(outside.name, self.disasm) - except (OSError, NotImplementedError): - self.skipTest("this platform cannot create symbolic links") - self.assert_fails(make_game.prepare_shader_disassembly, self.work, self.disasm, False, - match="must be inside the work folder") - self.assertTrue(os.path.isfile(victim)) - - -class ShaderOutputsReusableTest(TempWorkTest): - """shader_outputs_reusable(): a work folder is reusable only when every recorded setting still matches.""" - - def setUp(self): - super().setUp() - os.makedirs(self.disasm) - - def state(self, mode="off", flags="", digest=DIGEST, signature=SIGNATURE, markers=True): - """Write the files a finished shaders stage leaves; markers=False writes none of them.""" - if not markers: - return - for path, text in ((os.path.join(self.dxbc, "index.json"), json.dumps([{"file": "s0.dxbc"}])), - (os.path.join(self.dxbc, "fssm_index.json"), json.dumps([{"name": "s0"}])), - (os.path.join(self.spirv, "index.json"), "{}")): - self.write(path, text) - self.write(os.path.join(self.disasm, "s0.s"), "synthetic listing\n") - self.write(os.path.join(self.spirv, "wave64_emulate.txt"), mode + "\n") - self.write(os.path.join(self.spirv, "translator_flags.txt"), flags + "\n" if flags else "") - self.write(os.path.join(self.spirv, "translation_sources.sha256"), digest + "\n") - self.write(os.path.join(self.dxbc, "disasm.done"), - json.dumps({"llvm": signature, "listings": ["s0"]}) + "\n") - - def reusable(self, emulate=False, keep_emulated=False, fallbacks=()): - with mock.patch.object(make_game, "llvm_mc_signature", return_value=SIGNATURE), \ - mock.patch.object(make_game, "translation_sources_digest", return_value=DIGEST): - return make_game.shader_outputs_reusable(self.work, emulate, keep_emulated, fallbacks) - - def test_a_finished_native_translation_is_reusable(self): - self.state(mode="off", flags="") - self.assertTrue(self.reusable()) - - def test_a_finished_emulated_translation_is_reusable_when_it_is_kept(self): - self.state(mode="on") - self.assertTrue(self.reusable(keep_emulated=True)) - - def test_each_marker_is_required(self): - for rel in (("dxbc", "index.json"), ("dxbc", "fssm_index.json"), ("spirv", "index.json")): - with self.subTest(marker=rel): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.work = tmp.name - self.dxbc = os.path.join(self.work, "shaders", "dxbc") - self.spirv = os.path.join(self.work, "shaders", "spirv") - self.disasm = os.path.join(self.dxbc, "disasm") - os.makedirs(self.disasm) - self.state() - os.remove(os.path.join(self.work, "shaders", *rel)) - self.assertFalse(self.reusable()) - - def test_no_markers_at_all_is_not_reusable(self): - self.state(markers=False) - self.assertFalse(self.reusable()) - - def test_a_missing_disassembly_folder_is_not_reusable(self): - self.state() - os.remove(os.path.join(self.disasm, "s0.s")) - os.rmdir(self.disasm) - self.assertFalse(self.reusable()) - - def test_a_missing_disassembly_marker_is_not_reusable(self): - self.state() - os.remove(os.path.join(self.dxbc, "disasm.done")) - self.assertFalse(self.reusable()) - - def test_another_llvm_mc_is_not_reusable(self): - self.state(signature='["llvm-mc", "LLVM version 18.0.0"]') - self.assertFalse(self.reusable()) - - def test_another_translator_source_is_not_reusable(self): - self.state(digest="b" * 64) - self.assertFalse(self.reusable()) - - def test_a_missing_translator_digest_is_not_reusable(self): - self.state() - os.remove(os.path.join(self.spirv, "translation_sources.sha256")) - self.assertFalse(self.reusable()) - - def test_an_emulated_folder_is_not_reused_when_emulation_is_turned_off(self): - self.state(mode="on") - self.assertFalse(self.reusable(keep_emulated=False)) - - def test_a_native_folder_is_not_reused_when_emulation_is_asked_for(self): - self.state(mode="off") - self.assertFalse(self.reusable(emulate=True)) - - def test_a_folder_from_before_the_mode_file_existed_counts_as_native(self): - self.state(mode="off") - os.remove(os.path.join(self.spirv, "wave64_emulate.txt")) - self.assertTrue(self.reusable()) - - def test_recorded_fallbacks_must_match_exactly(self): - self.state(flags=make_game.translator_flags_setting(FLAGS)) - self.assertTrue(self.reusable(fallbacks=FLAGS)) - self.assertFalse(self.reusable(fallbacks=FLAGS[:1])) - self.assertFalse(self.reusable(fallbacks=tuple(reversed(FLAGS)))) - - def test_a_folder_without_fallbacks_is_reusable_without_them(self): - self.state() - os.remove(os.path.join(self.spirv, "translator_flags.txt")) - self.assertTrue(self.reusable()) - self.assertFalse(self.reusable(fallbacks=("--mesh-compute",))) - - def test_an_unreadable_marker_is_not_reusable(self): - self.state() - os.remove(os.path.join(self.spirv, "translation_sources.sha256")) - os.makedirs(os.path.join(self.spirv, "translation_sources.sha256")) - self.assertFalse(self.reusable()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_gpu_tests_helpers.py b/tests/test_run_gpu_tests_helpers.py deleted file mode 100644 index b822d3935..000000000 --- a/tests/test_run_gpu_tests_helpers.py +++ /dev/null @@ -1,236 +0,0 @@ -"""scripts/run_gpu_tests.py: the synthetic container builders, the pixel/frame helpers and the environment flags. - -The builders are pure byte and string work and the checks read a fixture file, so no assembler, GPU or game data is -needed: the frames here are made by hand. - - python -I tests/test_run_gpu_tests_helpers.py -""" -import math -import os -from pathlib import Path -import struct -import sys -import tempfile -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -import run_gpu_tests as rgt # noqa: E402 - -FLAGS = ("LEONIDA_BARY_FALLBACK", "LEONIDA_F16_INTERP_FALLBACK", "LEONIDA_W64_EMULATE") - - -class FlagEnvironment: - """Run a flag parser with only the flag under test set (the others would leak in from the caller).""" - - def __init__(self, **values): - self.values = values - - def __enter__(self): - self._patch = patch.dict(os.environ, self.values, clear=False) - self._patch.start() - for name in FLAGS: - if name not in self.values: - os.environ.pop(name, None) - return self - - def __exit__(self, *exc): - self._patch.stop() - return False - - -class DxbcBuilder(unittest.TestCase): - def parse(self, data): - magic = data[:4] - version, total, count = struct.unpack_from("viewer", encoding="utf-8") (root / "secret.txt").write_text("secret", encoding="utf-8") @@ -294,10 +281,6 @@ class HandlerTest(unittest.TestCase): status, _, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}") self.assertEqual(status, 403) self.assertNotIn(b"secret", body) - status, _, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}", - method="HEAD") - self.assertEqual(status, 403) - self.assertEqual(body, b"") def test_windows_device_aliases_get_403_without_opening_them(self): targets = ("/world/COM%C2%B9.glb", "/world/sub/lpt%C2%B2.json", "/world/CONIN%24", @@ -394,160 +377,6 @@ class NoWorldHandlerTest(unittest.TestCase): server.server_close() thread.join(5) - def test_the_viewer_root_serves_index_html(self): - # Opening http://127.0.0.1:8765/ is how the viewer is started, and HEAD must agree with GET. - status, head, body = raw_request(self.port, "/", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 200) - self.assertIn("text/html", head.lower()) - self.assertIn(b"viewer", body) - status, head, body = raw_request(self.port, "/", host=f"127.0.0.1:{self.port}", method="HEAD") - self.assertEqual(status, 200) - self.assertEqual(body, b"") - self.assertEqual(int(header_value(head, "content-length")), len(b"viewer")) - - def test_a_missing_world_file_is_404(self): - status, head, body = raw_request(self.port, "/world/missing.glb", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 404) - self.assertIn("cache-control: no-store", head.lower()) - self.assertNotIn(b"world-bytes", body) - status, head_head, head_body = raw_request(self.port, "/world/missing.glb", - host=f"127.0.0.1:{self.port}", method="HEAD") - self.assertEqual(status, 404) - self.assertEqual(head_body, b"") - self.assertEqual(header_value(head, "content-length"), header_value(head_head, "content-length")) - - def test_a_missing_viewer_asset_is_404(self): - status, head, body = raw_request(self.port, "/nope.js", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 404) - self.assertIn("cache-control: no-store", head.lower()) - self.assertNotIn(b"secret", body) - - def test_traversal_outside_the_viewer_folder_is_404(self): - # Paths that do not start with /world/ bypass safe_world_path; SimpleHTTPRequestHandler's own - # translate_path must still drop the parent segments instead of serving the neighbouring secret. - for target in ("/../secret.txt", "/..%2fsecret.txt", "/%2e%2e/secret.txt"): - with self.subTest(target=target): - status, _, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 404) - self.assertNotIn(b"secret", body) - - def test_methods_other_than_get_and_head_are_refused(self): - # SimpleHTTPRequestHandler only implements GET and HEAD, so the answer is 501, not 405. - for method in ("POST", "PUT", "DELETE"): - with self.subTest(method=method): - status, head, body = raw_request(self.port, "/world/ok.bin", method=method, - host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 501) - self.assertIn("cache-control: no-store", head.lower()) - self.assertNotIn(b"world-bytes", body) - - def test_head_matches_get_for_a_world_file(self): - status, head, body = raw_request(self.port, "/world/model.glb", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 200) - status, head_head, head_body = raw_request(self.port, "/world/model.glb", - host=f"127.0.0.1:{self.port}", method="HEAD") - self.assertEqual(status, 200) - self.assertEqual(head_body, b"") - self.assertEqual(header_value(head, "content-length"), header_value(head_head, "content-length")) - self.assertEqual(header_value(head, "content-type"), header_value(head_head, "content-type")) - - def test_world_directories_are_not_listed(self): - for target in ("/world/", "/world/sub", "/world/sub/"): - with self.subTest(target=target): - status, _, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 403) - self.assertNotIn(b"inner.bin", body) - - def test_an_encoded_separator_still_resolves_inside_the_world(self): - status, _, body = raw_request(self.port, "/world/sub%2Finner.bin", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 200) - self.assertEqual(body, b"inner") - - def test_a_range_request_gets_the_whole_file(self): - # The viewer downloads each GLB as one body (fetch + arrayBuffer) and never asks for a slice, so a - # Range header is ignored and the complete file is sent. A 206 here would break the streaming code's - # assumption that arrayBuffer() holds the whole chunk. - for target, expected in (("/world/ok.bin", b"world-bytes"), ("/world/big.bin", self.big)): - with self.subTest(target=target): - status, head, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}", - extra_headers=("Range: bytes=0-4",)) - self.assertEqual(status, 200) - self.assertEqual(body, expected) - self.assertEqual(int(header_value(head, "content-length")), len(expected)) - self.assertIsNone(header_value(head, "content-range")) - - def test_a_large_chunk_is_streamed_whole(self): - status, head, body = raw_request(self.port, "/world/big.bin", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 200) - self.assertEqual(int(header_value(head, "content-length")), len(self.big)) - self.assertEqual(body, self.big) - - def test_parallel_chunk_downloads_do_not_interleave(self): - # The streaming code keeps four downloads in flight; each response must carry its own file. - from concurrent.futures import ThreadPoolExecutor - expected = {"/world/big.bin": self.big, "/world/ok.bin": b"world-bytes", - "/world/model.glb": b"glTF"} - targets = list(expected) * 3 - - def fetch(target): - status, _, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}") - return target, status, body - - with ThreadPoolExecutor(max_workers=len(targets)) as pool: - results = list(pool.map(fetch, targets)) - self.assertEqual(len(results), len(targets)) - for target, status, body in results: - with self.subTest(target=target): - self.assertEqual(status, 200) - self.assertEqual(body, expected[target]) - - -class NoWorldHandlerTest(unittest.TestCase): - """Without --world the viewer serves only its own folder, so /world/ is a plain 404.""" - - @classmethod - def setUpClass(cls): - cls._tmp = tempfile.TemporaryDirectory() - root = Path(cls._tmp.name) - (root / "site").mkdir() - (root / "site" / "index.html").write_text("viewer", encoding="utf-8") - (root / "secret.txt").write_text("secret", encoding="utf-8") - - class QuietHandler(serve.Handler): - world = None - - def log_message(self, *args): - pass - - cls.server = http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), functools.partial(QuietHandler, directory=str(root / "site"))) - cls.port = cls.server.server_address[1] - cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) - cls.thread.start() - - @classmethod - def tearDownClass(cls): - cls.server.shutdown() - cls.server.server_close() - cls.thread.join(5) - cls._tmp.cleanup() - - def test_world_requests_are_404_without_a_world_folder(self): - for target in ("/world/ok.bin", "/world/", "/world/../secret.txt"): - with self.subTest(target=target): - status, _, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 404) - self.assertNotIn(b"secret", body) - - def test_the_viewer_page_is_still_served(self): - status, _, body = raw_request(self.port, "/", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 200) - self.assertIn(b"viewer", body) - - def test_a_foreign_host_is_still_403(self): - status, _, _ = raw_request(self.port, "/world/ok.bin", host="evil.example:8765") - self.assertEqual(status, 403) - class WorldArgumentTest(unittest.TestCase): def test_explicit_world_must_be_a_directory(self): diff --git a/tests/test_wave64_halves_operands.py b/tests/test_wave64_halves_operands.py deleted file mode 100644 index 9130a39b5..000000000 --- a/tests/test_wave64_halves_operands.py +++ /dev/null @@ -1,197 +0,0 @@ -"""wave64_halves' operand helpers: base_op suffix stripping, the register keys an operand names (_regs, _half) -and operands(), which splits an instruction dict into (dests, srcs, implicit defs, implicit uses). All inputs are -hand-written instruction dicts in the shape tools/shader_disasm.py emits; no game data is used. - - python -I tests/test_wave64_halves_operands.py -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import wave64_halves as w64 # noqa: E402 - - -def s(r, n=1): - return {"k": "sgpr", "r": r, "n": n} - - -def v(r, n=1): - return {"k": "vgpr", "r": r, "n": n} - - -def sp(t): - return {"k": "special", "t": t} - - -def imm(x): - return {"k": "imm", "v": x} - - -def ins(op, *args, mods=()): - return {"op": op, "args": list(args), "mods": list(mods)} - - -class BaseOp(unittest.TestCase): - def test_strips_encoding_suffixes(self): - self.assertEqual(w64.base_op("v_mov_b32_e32"), "v_mov_b32") - self.assertEqual(w64.base_op("v_add_co_u32_e64"), "v_add_co_u32") - self.assertEqual(w64.base_op("v_lshlrev_b32_sdwa"), "v_lshlrev_b32") - self.assertEqual(w64.base_op("v_or_b32_dpp"), "v_or_b32") - - def test_leaves_other_names_alone(self): - self.assertEqual(w64.base_op("s_endpgm"), "s_endpgm") - self.assertEqual(w64.base_op("s_movk_i32"), "s_movk_i32") # _i32 is not an encoding suffix - self.assertEqual(w64.base_op(""), "") - - -class Regs(unittest.TestCase): - def test_scalar_registers_expand_by_width(self): - self.assertEqual(w64._regs(s(4, 2)), [("s", 4), ("s", 5)]) - self.assertEqual(w64._regs({"k": "sgpr", "r": 4}), [("s", 4)]) # n defaults to 1 - - def test_vector_registers(self): - self.assertEqual(w64._regs(v(3)), [("v", 3)]) - self.assertEqual(w64._regs(v(3, 2)), [("v", 3), ("v", 4)]) - self.assertEqual(w64._regs({"k": "vlist", "r": [5, 7]}), [("v", 5), ("v", 7)]) - - def test_special_registers(self): - self.assertEqual(w64._regs(sp("vcc")), ["vcc"]) - self.assertEqual(w64._regs(sp("vcc_lo")), ["vcc"]) # either half names the pair - self.assertEqual(w64._regs(sp("exec_hi")), ["exec"]) - self.assertEqual(w64._regs(sp("scc")), ["scc"]) - self.assertEqual(w64._regs(sp("m0")), ["m0"]) - - def test_everything_else_has_no_registers(self): - self.assertEqual(w64._regs(sp("null")), []) - self.assertEqual(w64._regs(sp("tba")), []) - self.assertEqual(w64._regs(imm(5)), []) - self.assertEqual(w64._regs({"k": "fimm", "v": 1.0}), []) - self.assertEqual(w64._regs({}), []) - - -class Half(unittest.TestCase): - def test_named_32_bit_halves(self): - self.assertEqual(w64._half(sp("exec_lo")), "lo") - self.assertEqual(w64._half(sp("vcc_lo")), "lo") - self.assertEqual(w64._half(sp("exec_hi")), "hi") - self.assertEqual(w64._half(sp("vcc_hi")), "hi") - - def test_whole_registers_and_other_operands_are_not_halves(self): - self.assertIsNone(w64._half(sp("exec"))) - self.assertIsNone(w64._half(sp("vcc"))) - self.assertIsNone(w64._half(s(1))) - self.assertIsNone(w64._half(imm(0))) - - -class Operands(unittest.TestCase): - def test_plain_alu_first_operand_is_the_dest(self): - self.assertEqual(w64.operands(ins("v_add_f32_e32", v(0), v(1), v(2))), - ([v(0)], [v(1), v(2)], [], [])) - self.assertEqual(w64.operands(ins("s_mov_b32", s(1), imm(5))), - ([s(1)], [imm(5)], [], [])) - - def test_no_dest_ops_treat_every_operand_as_a_source(self): - self.assertEqual(w64.operands(ins("exp", imm(0), v(0), v(1), v(2), v(3))), - ([], [imm(0), v(0), v(1), v(2), v(3)], [], [])) - self.assertEqual(w64.operands(ins("buffer_store_dword", v(0), v(1), s(0, 4), imm(0))), - ([], [v(0), v(1), s(0, 4), imm(0)], [], [])) - self.assertEqual(w64.operands(ins("s_nop")), ([], [], [], [])) - self.assertEqual(w64.operands(ins("v_nop")), ([], [], [], [])) - self.assertEqual(w64.operands(ins("s_waitcnt", imm(0))), ([], [imm(0)], [], [])) - - def test_scalar_compares_define_scc(self): - self.assertEqual(w64.operands(ins("s_cmp_eq_u32", s(0), imm(1))), - ([], [s(0), imm(1)], ["scc"], [])) - self.assertEqual(w64.operands(ins("s_bitcmp1_b32", s(0), imm(1))), - ([], [s(0), imm(1)], ["scc"], [])) - - def test_vector_compares(self): - # an explicit destination (the _e64 form) is a normal dest; the two-operand form defines VCC implicitly - self.assertEqual(w64.operands(ins("v_cmp_gt_f32_e32", sp("vcc_lo"), imm(0), v(1))), - ([sp("vcc_lo")], [imm(0), v(1)], [], [])) - self.assertEqual(w64.operands(ins("v_cmp_gt_f32_e32", imm(0), v(1))), - ([], [imm(0), v(1)], ["vcc"], [])) - - def test_v_cmpx_reports_its_exec_def(self): - # GFX10 v_cmpx has no destination operand and writes EXEC only; operands() reports that implicit EXEC - # write (it used to report none, which this test pinned until round 44), so the transfer function models - # the narrowing. - self.assertEqual(w64.operands(ins("v_cmpx_eq_u32_e32", s(6), v(1))), - ([], [s(6), v(1)], ["exec"], [])) - - def test_atomics_return_a_value_only_with_glc(self): - args = (v(0), v(1), s(0, 4), imm(0)) - self.assertEqual(w64.operands(ins("buffer_atomic_add", *args)), - ([], list(args), [], [])) - self.assertEqual(w64.operands(ins("buffer_atomic_add", *args, mods=("glc",))), - ([v(0)], list(args), [], [])) # the destination stays in srcs too - self.assertEqual(w64.operands(ins("flat_atomic_add", v(0), v(1), mods=("glc",))), - ([v(0)], [v(0), v(1)], [], [])) - - def test_ds_ops_with_a_return_value(self): - self.assertEqual(w64.operands(ins("ds_read_b32", v(0), v(1))), ([v(0)], [v(1)], [], [])) - self.assertEqual(w64.operands(ins("ds_add_rtn_u32", v(0), v(1), v(2))), - ([v(0)], [v(1), v(2)], [], [])) - self.assertEqual(w64.operands(ins("ds_write_b32", v(0), v(1))), - ([], [v(0), v(1)], [], [])) - self.assertEqual(w64.operands(ins("ds_nop")), ([], [], [], [])) - - def test_dual_dest_vector_ops(self): - self.assertEqual(w64.operands(ins("v_add_co_u32_e64", v(0), s(6, 2), v(1), v(2))), - ([v(0), s(6, 2)], [v(1), v(2)], [], [])) - self.assertEqual(w64.operands(ins("v_add_co_u32", v(0), sp("vcc"), v(1), v(2))), - ([v(0), sp("vcc")], [v(1), v(2)], [], [])) - # a carry-out that is not scalar/special stays a source: single dest - self.assertEqual(w64.operands(ins("v_add_co_u32", v(0), v(1), v(2), v(3))), - ([v(0)], [v(1), v(2), v(3)], [], [])) - self.assertEqual(w64.operands(ins("v_mad_u64_u32", v(0, 2), s(6, 2), v(2), v(3), v(4, 2))), - ([v(0, 2), s(6, 2)], [v(2), v(3), v(4, 2)], [], [])) - - def test_saveexec_defines_exec_and_scc(self): - self.assertEqual(w64.operands(ins("s_and_saveexec_b64", s(6, 2), sp("exec"))), - ([s(6, 2)], [sp("exec")], ["exec", "scc"], [])) - - def test_scalar_ops_define_scc_unless_exempted(self): - self.assertEqual(w64.operands(ins("s_and_b64", s(6, 2), s(2, 2), sp("exec"))), - ([s(6, 2)], [s(2, 2), sp("exec")], ["scc"], [])) - self.assertEqual(w64.operands(ins("s_mov_b32", s(1), imm(5))), - ([s(1)], [imm(5)], [], [])) - # conservative: an s_ op the model does not exempt is assumed to define SCC - self.assertEqual(w64.operands(ins("s_sleep", imm(7))), ([], [imm(7)], ["scc"], [])) - - def test_s_set_is_a_prefix_so_s_setpc_has_no_dest(self): - # "s_set" is in NO_DEST and prefix-matching catches s_setpc_* too (the transfer function calls it - # an unmodelled op regardless). - self.assertEqual(w64.operands(ins("s_setpc_b64", s(4, 2), s(2, 2))), - ([], [s(4, 2), s(2, 2)], [], [])) - - def test_implicit_vcc_use(self): - self.assertEqual(w64.operands(ins("v_cndmask_b32", v(0), v(1), v(2))), - ([v(0)], [v(1), v(2)], [], ["vcc"])) - # an explicit VCC operand is not listed again, and over-long operand lists opt out - self.assertEqual(w64.operands(ins("v_cndmask_b32", v(0), v(1), v(2), sp("vcc"))), - ([v(0)], [v(1), v(2), sp("vcc")], [], [])) - self.assertEqual(w64.operands(ins("v_cndmask_b32", v(0), v(1), v(2), v(3), v(4))), - ([v(0)], [v(1), v(2), v(3), v(4)], [], [])) - - def test_implicit_scc_use(self): - self.assertEqual(w64.operands(ins("s_cselect_b32", s(0), s(1), s(2))), - ([s(0)], [s(1), s(2)], [], ["scc"])) - self.assertEqual(w64.operands(ins("s_cbranch_scc1", imm(12))), - ([], [imm(12)], [], ["scc"])) - - def test_vcc_and_exec_branches(self): - self.assertEqual(w64.operands(ins("s_cbranch_vccz", imm(4))), ([], [imm(4)], [], ["vcc"])) - self.assertEqual(w64.operands(ins("s_branch", imm(4))), ([], [imm(4)], [], [])) - # EXEC branches name their mask implicitly: "exec" is not added to uses - self.assertEqual(w64.operands(ins("s_cbranch_execnz", imm(4))), ([], [imm(4)], [], [])) - - def test_empty_args_give_empty_lists(self): - self.assertEqual(w64.operands(ins("v_mov_b32_e32")), ([], [], [], [])) - self.assertEqual(w64.operands(ins("s_endpgm")), ([], [], [], [])) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/hello_pixels.py b/tools/hello_pixels.py deleted file mode 100644 index 2196c6f01..000000000 --- a/tools/hello_pixels.py +++ /dev/null @@ -1,347 +0,0 @@ -#!/usr/bin/env python3 -"""Draws a synthetic test image through vk_harness: the package-free "does it print pixels" check. - -first_light.py needs the game's own package; this tool needs only vk_harness (built from runtime/) and -spirv-as (Vulkan SDK or spirv-tools). It assembles a tiny hand-written vertex+fragment pair, feeds an -indexed fullscreen quad through VKH_DRAW_MESH/VKH_VERTEX_LAYOUT, reads back the RGBA32F image and writes -image.ppm plus image.png. --check verifies the picture like first_light's oracle: coverage, the corner -clear value and pixel probes against the pattern's own closed form. - - python -I tools/hello_pixels.py --work --run [--check] [--size 256] - -Everything it writes is synthetic and safe to keep; no game data is touched or produced. -""" - -import json -import os -import shutil -import struct -import subprocess -import sys -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - -# Vertex shader: location 0 = float3 position (already NDC), location 1 = float2 uv; -# forwards both to gl_Position and the interpolating varying. -VS_ASM = """\ -; hello_pixels vertex shader: pass position through, forward uv -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %main "main" %in_pos %gl_Position %v_uv %in_uv -OpSource GLSL 450 -OpName %main "main" -OpDecorate %gl_Position BuiltIn Position -OpDecorate %in_pos Location 0 -OpDecorate %in_uv Location 1 -OpDecorate %v_uv Location 0 -%void = OpTypeVoid -%f32 = OpTypeFloat 32 -%v3 = OpTypeVector %f32 3 -%v2 = OpTypeVector %f32 2 -%v4 = OpTypeVector %f32 4 -%fn = OpTypeFunction %void -%pin3 = OpTypePointer Input %v3 -%pin2 = OpTypePointer Input %v2 -%pout4 = OpTypePointer Output %v4 -%pout2 = OpTypePointer Output %v2 -%in_pos = OpVariable %pin3 Input -%gl_Position = OpVariable %pout4 Output -%v_uv = OpVariable %pout2 Output -%in_uv = OpVariable %pin2 Input -%one = OpConstant %f32 1.0 -%main = OpFunction %void None %fn -%entry = OpLabel -%p = OpLoad %v3 %in_pos -%u = OpLoad %v2 %in_uv -%px = OpCompositeExtract %f32 %p 0 -%py = OpCompositeExtract %f32 %p 1 -%pz = OpCompositeExtract %f32 %p 2 -%clip = OpCompositeConstruct %v4 %px %py %pz %one -OpStore %gl_Position %clip -OpStore %v_uv %u -OpReturn -OpFunctionEnd -""" - -# Fragment shader: rgb = gradient(uv) dimmed to 20% on a 16x16 checker grid; alpha = 1. -# r = u, g = v, b = (u+v)/2, dimmed on cells where floor(u*16) parity == floor(v*16) parity. -# Pure core instructions: OpFMod for the cell coordinate, OpFOrdLessThan/OpSelect for parity. -PS_ASM = """\ -; hello_pixels fragment shader: uv gradient with a 16x16 checker grid -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %v_uv %out_color -OpExecutionMode %main OriginUpperLeft -OpSource GLSL 450 -OpName %main "main" -OpDecorate %v_uv Location 0 -OpDecorate %out_color Location 0 -%void = OpTypeVoid -%f32 = OpTypeFloat 32 -%bool = OpTypeBool -%v2 = OpTypeVector %f32 2 -%v4 = OpTypeVector %f32 4 -%fn = OpTypeFunction %void -%pin2 = OpTypePointer Input %v2 -%pout4 = OpTypePointer Output %v4 -%v_uv = OpVariable %pin2 Input -%out_color = OpVariable %pout4 Output -%c16 = OpConstant %f32 16.0 -%c2 = OpConstant %f32 2.0 -%c1 = OpConstant %f32 1.0 -%cdim = OpConstant %f32 0.2 -%half = OpConstant %f32 0.5 -%main = OpFunction %void None %fn -%entry = OpLabel -%uv = OpLoad %v2 %v_uv -%u = OpCompositeExtract %f32 %uv 0 -%v = OpCompositeExtract %f32 %uv 1 -%cu = OpFMul %f32 %u %c16 -%cv = OpFMul %f32 %v %c16 -%mu = OpFMod %f32 %cu %c2 -%mv = OpFMod %f32 %cv %c2 -%lu = OpFOrdLessThan %bool %mu %c1 -%lv = OpFOrdLessThan %bool %mv %c1 -%same = OpLogicalEqual %bool %lu %lv -%grid = OpSelect %f32 %same %c1 %cdim -%sum = OpFAdd %f32 %u %v -%b = OpFMul %f32 %sum %half -%r = OpFMul %f32 %u %grid -%g = OpFMul %f32 %v %grid -%bb = OpFMul %f32 %b %grid -%col = OpCompositeConstruct %v4 %r %g %bb %c1 -OpStore %out_color %col -OpReturn -OpFunctionEnd -""" - -LAYOUT = "0:3f,1:2f" -CLEAR = (0.0, 0.0, 0.0, 0.0) - - -def find_harness(explicit=None): - if explicit: - return explicit - env = os.environ.get("LEONIDA_VK_HARNESS") - if env: - return env - exe = ".exe" if os.name == "nt" else "" - for cand in ( - os.path.join(ROOT, "runtime", "build", "linux", f"vk_harness{exe}"), - os.path.join(ROOT, "runtime", "build", "windows", f"vk_harness{exe}"), - os.path.join(ROOT, "runtime", "build", f"vk_harness{exe}"), - ): - if os.path.isfile(cand): - return cand - raise SystemExit( - "vk_harness not found: build runtime/build/linux or runtime/build/windows " - "(target vk_harness), or pass --harness / set LEONIDA_VK_HARNESS" - ) - - -def find_spirv_as(): - exe = "spirv-as.exe" if os.name == "nt" else "spirv-as" - return shutil.which(exe) or shutil.which("spirv-as") - - -def assemble(text: str, out_spv: str, assembler: str) -> None: - p = subprocess.run( - [assembler, "--target-env", "vulkan1.2", "-o", out_spv, "-"], - input=text.encode(), - capture_output=True, - ) - if p.returncode != 0: - raise SystemExit(f"spirv-as failed for {out_spv}:\n{p.stderr.decode(errors='replace')}") - - -def shaders_into(out_dir: str) -> None: - # The documented no-SDK path: drop prebuilt vs.spv/ps.spv (from --emit-only on a machine that has - # spirv-as) into the work directory and they are used as-is. Assembly still wins when spirv-as is - # on PATH, so a stale pair never shadows fresh sources. - vs_spv = os.path.join(out_dir, "vs.spv") - ps_spv = os.path.join(out_dir, "ps.spv") - assembler = find_spirv_as() - if assembler is None: - # Check the SPIR-V magic so a stray file does not reach the harness. - def spv_ok(path: str) -> bool: - if not os.path.isfile(path): - return False - with open(path, "rb") as f: - return f.read(4) == b"\x03\x02\x23\x07" - - if spv_ok(vs_spv) and spv_ok(ps_spv): - print("spirv-as not found; using the prebuilt vs.spv and ps.spv in the work directory") - return - raise SystemExit( - "spirv-as not found on PATH (install spirv-tools or the Vulkan SDK), and the work directory " - "has no prebuilt vs.spv/ps.spv pair (--emit-only on a machine that has one produces them)" - ) - assemble(VS_ASM, vs_spv, assembler) - assemble(PS_ASM, ps_spv, assembler) - - -def write_mesh(path: str) -> None: - # Fullscreen indexed quad in NDC; (x, y, z, u, v) per vertex, y up. - verts = [(-1.0, -1.0, 0.0, 0.0, 1.0), (1.0, -1.0, 0.0, 1.0, 1.0), - (1.0, 1.0, 0.0, 1.0, 0.0), (-1.0, 1.0, 0.0, 0.0, 0.0)] - idx = [0, 1, 2, 0, 2, 3] - with open(path, "wb") as f: - f.write(struct.pack(" row 0 is top).""" - u = (x + 0.5) / width - v = 1.0 - (y + 0.5) / height - same = (int(u * 16) % 2) == (int(v * 16) % 2) - grid = 1.0 if same else 0.2 - return (u * grid, v * grid, (u + v) * 0.5 * grid, 1.0) - - -def check_image(data: bytes, width: int, height: int): - want = width * height * 16 - if len(data) != want: - raise AssertionError(f"image.raw is {len(data)} bytes, expected {want}") - pixels = struct.unpack(f"<{width * height * 4}f", data) - clear_tol = 1e-3 - probes = [ - (width // 2, height // 2), - (width // 4, height // 4), - (3 * width // 4, height // 4), - (width // 4, 3 * height // 4), - (3 * width // 4, 3 * height // 4), - (width // 8, height // 2), - (7 * width // 8, height // 2), - ] - covered = 0 - for y in range(height): - for x in range(width): - i = (y * width + x) * 4 - if pixels[i + 3] != 0.0: - covered += 1 - if covered != width * height: - raise AssertionError(f"coverage {covered}/{width * height}: the quad did not fill the image") - for x, y in probes: - i = (y * width + x) * 4 - got = pixels[i : i + 4] - want_px = expected_pixel(x, y, width, height) - for c in range(4): - if abs(got[c] - want_px[c]) > 0.04: - raise AssertionError( - f"pixel ({x},{y}) is {[round(g, 4) for g in got]}, " - f"expected {[round(w, 4) for w in want_px]} channel {c}" - ) - return {"covered": covered, "pixels": pixels} - - -def write_ppm(path: str, pixels, width: int, height: int) -> None: - with open(path, "wb") as f: - f.write(f"P6\n{width} {height}\n255\n".encode()) - f.writelines( - bytes(max(0, min(255, round(pixels[i + c] * 255))) for c in range(3)) - for i in range(0, len(pixels), 4) - ) - - -def write_png(path: str, pixels, width: int, height: int) -> None: - def chunk(tag: bytes, payload: bytes) -> bytes: - return ( - struct.pack(">I", len(payload)) - + tag - + payload - + struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF) - ) - - scan = bytearray() - for y in range(height): - scan.append(0) - for x in range(width): - i = (y * width + x) * 4 - scan += bytes(max(0, min(255, round(pixels[i + c] * 255))) for c in range(3)) - png = ( - b"\x89PNG\r\n\x1a\n" - + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) - + chunk(b"IDAT", zlib.compress(bytes(scan), 6)) - + chunk(b"IEND", b"") - ) - with open(path, "wb") as f: - f.write(png) - - -def run_draw(args, out_dir: str) -> dict: - harness = find_harness(args.harness) - raw = os.path.join(out_dir, "image.raw") - if os.path.exists(raw): - os.unlink(raw) - env = dict(os.environ, VKH_DRAW_MESH=os.path.join(out_dir, "mesh.bin"), VKH_VERTEX_LAYOUT=LAYOUT) - cmd = [ - harness, - os.path.join(out_dir, "vs.spv"), - os.path.join(out_dir, "ps.spv"), - raw, - str(args.size), - str(args.size), - ] - subprocess.run(cmd, check=True, env=env) - if not os.path.isfile(raw): - raise SystemExit(f"the harness exited successfully but did not write {raw}") - with open(raw, "rb") as f: - data = f.read() - if args.check: - result = check_image(data, args.size, args.size) - else: - result = {"pixels": struct.unpack(f"<{args.size * args.size * 4}f", data)} - pixels = result["pixels"] - ppm = os.path.join(out_dir, "image.ppm") - png = os.path.join(out_dir, "image.png") - write_ppm(ppm, pixels, args.size, args.size) - write_png(png, pixels, args.size, args.size) - print(f"{args.size}x{args.size} -> {ppm}") - print(f"{args.size}x{args.size} -> {png}") - return result - - -def main(argv=None) -> int: - import argparse - - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--work", default=".", help="output directory (default: cwd)") - ap.add_argument("--size", type=int, default=256, help="image edge in pixels (default 256)") - ap.add_argument("--harness", help="vk_harness binary (default LEONIDA_VK_HARNESS or runtime/build)") - ap.add_argument("--run", action="store_true", help="run the draw and write image.raw/.ppm/.png") - ap.add_argument("--check", action="store_true", help="verify coverage and probe pixels after the draw") - ap.add_argument("--emit-only", action="store_true", help="write shaders and mesh.bin, then stop") - args = ap.parse_args(argv) - - out_dir = os.path.abspath(args.work) - os.makedirs(out_dir, exist_ok=True) - with open(os.path.join(out_dir, "vs.asm"), "w", encoding="utf-8", newline="\n") as f: - f.write(VS_ASM) - with open(os.path.join(out_dir, "ps.asm"), "w", encoding="utf-8", newline="\n") as f: - f.write(PS_ASM) - shaders_into(out_dir) - write_mesh(os.path.join(out_dir, "mesh.bin")) - print(f"emitted vs.spv, ps.spv, mesh.bin in {out_dir}") - if args.emit_only: - return 0 - if not args.run: - print("add --run to draw with vk_harness (VKH_DRAW_MESH mesh path), --check to verify pixels") - return 0 - result = run_draw(args, out_dir) - manifest = { - "size": args.size, - "layout": LAYOUT, - "synthetic": True, - "result": {"covered": result.get("covered"), "ppm": "image.ppm", "png": "image.png"}, - } - with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(manifest, f, indent=1) - return 0 - - -if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") - sys.exit(main()) diff --git a/tools/import_inventory.py b/tools/import_inventory.py deleted file mode 100644 index f700fdb19..000000000 --- a/tools/import_inventory.py +++ /dev/null @@ -1,502 +0,0 @@ -"""Report how a set of PE imports maps onto the runtime's shim layer. - -Usage: - python -I import_inventory.py [ ...] - python -I import_inventory.py --pe [--pe ] - -An imports file lists one ``dll!function`` per line; the DLL part is case-insensitive, blank lines and ``#`` -comments are ignored. ``--pe`` reads the import and delay-import directories of a PE32+ image directly (the -loader binds delay imports eagerly, so both are its import surface); ordinal-only imports report as -``dll!#ordinal``. - -Each import gets the return class runtime/shims/registry.cpp's classify() gives it — the same table that decides -what an unimplemented thunk returns under LEONIDA_UNIMPLEMENTED=fail — and is checked against the SHIM_TABLE -registrations in runtime/shims/*.cpp, mirroring the loader's routing: a registered ``dll!name`` binds to the -shim; an unregistered import on a module the shims own binds to the unimplemented-import thunk; anything else -binds to the host Windows DLL (when the host has it — the tool reports the route, not the host's exports). - -DLL names are reported under the loader's key — pe_loader.cpp's dll_key(), the LoadLibrary file-name rule — -so an import naming ``GameInput`` or ``gameinput.dll.`` groups and routes as ``gameinput.dll``. -""" -from __future__ import annotations - -import argparse -import glob -import os -import re -import struct -import sys - -HRESULT = "hresult" -OTHER = "other" - -# Ported from runtime/shims/registry.cpp: the xgameruntime families classify() treats as HRESULT-returning -# (kXFamilies) and the members the GDK reference shows as void/bool/int (kNotHResult). -NOT_HRESULT = frozenset({ - "XAsyncCancel", "XAsyncComplete", - "XTaskQueueCloseHandle", "XTaskQueueDispatch", "XTaskQueueGetCurrentProcessTaskQueue", - "XTaskQueueSetCurrentProcessTaskQueue", "XTaskQueueUnregisterMonitor", "XTaskQueueUnregisterWaiter", - "XUserCloseHandle", "XUserCloseSignOutDeferralHandle", "XUserCompare", "XUserIsStoreUser", - "XUserUnregisterForChangeEvent", "XUserUnregisterForDefaultAudioEndpointUtf16Changed", - "XUserUnregisterForDeviceAssociationChanged", - "XStoreCloseContextHandle", "XStoreCloseLicenseHandle", "XStoreCloseProductsQueryHandle", - "XStoreIsLicenseValid", "XStoreProductsQueryHasMorePages", "XStoreUnregisterGameLicenseChanged", - "XStoreUnregisterPackageLicenseLost", - "XGameSaveCloseContainer", "XGameSaveCloseProvider", "XGameSaveCloseUpdate", - "XPackageCloseInstallationMonitorHandle", "XPackageCloseMountHandle", "XPackageGetInstallationProgress", - "XPackageIsPackagedProcess", "XPackageUninstallPackage", "XPackageUnregisterInstallationProgressChanged", - "XPackageUnregisterPackageInstalled", "XPackageUpdateInstallationMonitor", -}) -X_FAMILIES = ("XAsync", "XTaskQueue", "XUser", "XStore", "XGameSave", "XPackage", "XGameUi") - - -def classify(dll: str, name: str) -> str: - """"hresult" or "other", the same split registry.cpp's classify() makes. `dll` is case-insensitive; - `name` must match exactly, as the registry's string comparisons do.""" - dll = dll.lower() - if dll in ("d3d12.dll", "d3d12_xs.dll"): - if (name.startswith(("D3D12Create", "D3D12Serialize")) - or name in ("D3D12GetDebugInterface", "D3D12EnableExperimentalFeatures", - "D3D12XboxCreateDevice", "D3D12XboxCreateSyntheticDevice")): - return HRESULT - elif dll == "dxgi.dll": - if name.startswith("CreateDXGIFactory") or name in ("DXGIGetDebugInterface1", - "DXGIDeclareAdapterRemovalSupport"): - return HRESULT - elif dll in ("xaudio2_9.dll", "xaudio2_9redist.dll"): - if name == "XAudio2Create" or name == "#1": - return HRESULT - # Host xaudio2_9.dll ordinals 8-10 are XAudio2CreateV2_9 / XAudio2CreateWithVersionInfo / - # XAudio2CreateWithSharedContexts (measured on the System32 export table); the redist's ordinal - # table is not confirmed, so only the system copy gets them — same split as registry.cpp. - if dll == "xaudio2_9.dll" and name in ("#8", "#9", "#10"): - return HRESULT - elif dll == "gameinput.dll": - if name == "GameInputCreate" or name == "#1": - return HRESULT - elif dll in ("dstorage.dll", "dstorage_xs.dll"): - if name == "DStorageGetFactory": - return HRESULT - elif dll == "xgameruntime.dll": - if name in ("XGameRuntimeInitialize", "XGameEventWrite"): - return HRESULT - if name in NOT_HRESULT: - return OTHER - if name.startswith(X_FAMILIES): - return HRESULT - return OTHER - - -def dll_key(name: str) -> str: - """Port of pe_loader.cpp's dll_key(): the LoadLibrary file-name rule on a module name — basename only, - lower-case, one trailing '.' dropped, '.dll' added when the name has no extension. An import naming - "GameInput" or "gameinput.dll." resolves to gameinput.dll, the module the shims register.""" - name = name[max(name.rfind("\\"), name.rfind("/")) + 1:].lower() - if name.endswith("."): - return name[:-1] - return name if "." in name else name + ".dll" - - -def parse_import_lines(lines) -> tuple[list[tuple[str, str]], int]: - """(dll, name) pairs from `dll!function` lines, and the count of lines skipped as malformed. The DLL part - comes back under the loader's dll_key.""" - imports, bad = [], 0 - for line in lines: - line = line.strip() - if not line or line.startswith("#"): - continue - dll, bang, name = line.partition("!") - if not bang or not dll.strip() or not name.strip(): - bad += 1 - continue - imports.append((dll_key(dll.strip()), name.strip())) - return imports, bad - - -class PeFormatError(ValueError): - """The file is not a PE32+ image this parser can read.""" - - -MAX_ENTRIES = 65536 # a table this long is not a table; stops a malformed image from looping forever -MAX_TOTAL_ENTRIES = 262144 # bounds the table entries parsed and the (dll, name) pairs emitted - - -def _cstring(data: bytes, offset: int, limit: int = 4097) -> str | None: - end = data.find(b"\0", offset, min(len(data), offset + limit)) - if end < 0: - return None - return data[offset:end].decode(errors="replace") - - -def pe_imports(path: str) -> list[tuple[str, str]]: - """(dll, name) pairs from a PE32+ image's import and delay-import directories, matching the tables - pe_loader.cpp's bind_imports walks. Ordinal-only imports come back as '#ordinal'.""" - with open(path, "rb") as f: - data = f.read() - if len(data) < 0x40 or data[:2] != b"MZ": - raise PeFormatError("no MZ header") - nt = struct.unpack_from(" len(data) or data[nt:nt + 4] != b"PE\0\0": - raise PeFormatError("no PE signature") - (_machine, section_count, _ts, _symtab, _syms, opt_size, _chars) = struct.unpack_from( - " len(data) or opt_size < 116: - raise PeFormatError("truncated optional header") - magic = struct.unpack_from(" len(data): - raise PeFormatError("truncated section table") - vsize, rva, rawsize, rawptr = struct.unpack_from(" int | None: - """File offset of an RVA, or None when no file bytes back it.""" - if rva < size_of_headers: - return rva if rva < len(data) else None - for vsize, srva, rawsize, rawptr in sections: - span = vsize or rawsize - if srva <= rva < srva + span: - if rva - srva >= min(rawsize, span): - return None - at = rawptr + rva - srva - return at if at < len(data) else None - return None - - def string_at(rva: int) -> str | None: - at = offset(rva) - return None if at is None else _cstring(data, at) - - out = [] - tables = {} # lookup-table RVA -> symbol names, parsed once per table - total = 0 - - def walk_table(lookup: int) -> list[str]: - """The symbol names one lookup table lists. Descriptors may share a table; the loader still binds - each descriptor's IAT separately, so the names emit per DLL, but the table parses only once.""" - nonlocal total - names = tables.get(lookup) - if names is not None: - return names - names = [] - for j in range(MAX_ENTRIES): - entry = offset(lookup + j * 8) - if entry is None or entry + 8 > len(data): - break - value = struct.unpack_from(" MAX_TOTAL_ENTRIES: - raise PeFormatError(f"more than {MAX_TOTAL_ENTRIES} import entries") - if value & (1 << 63): - names.append(f"#{value & 0xFFFF}") - continue - name = string_at((value & 0x7FFFFFFF) + 2) # skip the 2-byte hint - if name is None: - raise PeFormatError("an import thunk points at an unreadable name") - names.append(name) - tables[lookup] = names - return names - - def walk_thunks(dll: str, lookup: int) -> None: - if not lookup: - return - names = walk_table(lookup) - if len(out) + len(names) > MAX_TOTAL_ENTRIES: - raise PeFormatError(f"more than {MAX_TOTAL_ENTRIES} import entries") - out.extend((dll, name) for name in names) - - # Data directory entry 1. The loader stops the table at the first descriptor with Name == 0 and fails on an - # unreadable name; read_string throws there. - if dir_count > 1 and opt + 120 <= len(data): - imp_rva, _imp_size = struct.unpack_from(" len(data): - break - oft, _stamp, _forwarder, name_rva, iat_rva = struct.unpack_from(" 13 and opt + 112 + 14 * 8 <= len(data): - dd_rva, _dd_size = struct.unpack_from(" len(data): - break - (attrs, name_rva, _module, iat_rva, int_rva, - _bound, _unload, _stamp) = struct.unpack_from("<8I", data, at) - if not name_rva: - break - if not (attrs & 1): - raise PeFormatError("a delay-import descriptor without the RVA attribute") - if not iat_rva or not int_rva: - raise PeFormatError("a delay-import descriptor without an address or name table") - dll = string_at(name_rva) - if dll is None: - raise PeFormatError("a delay-import descriptor points at an unreadable DLL name") - walk_thunks(dll_key(dll), int_rva) - return out - - -# ---- SHIM_TABLE cross-reference ------------------------------------------------------------------------------ - -STRING = re.compile(r'"((?:[^"\\]|\\.)*)"') -ENTRY_GROUP = re.compile(r"\{([^{}]*)\}") -TABLE_RE = re.compile(r"\bSHIM_TABLE\s*\(") -MACRO_CALL = re.compile(r"\b([A-Za-z_]\w*)\s*\(") -# Only function-like macros with one parameter: the shim files build their entry lists from helpers like -# FILE_API(dll) and XGR(name). SHIM_TABLE(id, ...) itself takes two and is matched by TABLE_RE instead. -DEFINE_RE = re.compile( - r"(?m)^\s*#\s*define\s+([A-Za-z_]\w*)\s*\(\s*([A-Za-z_]\w*)\s*\)[ \t]*((?:[^\n]*\\[ \t]*\r?\n)*[^\n]*)") - - -def _table_arguments(text: str) -> list[str]: - """The argument list of each SHIM_TABLE(...) call in a shim source, comments removed.""" - args = [] - pos = 0 - while True: - m = TABLE_RE.search(text, pos) - if not m: - return args - i = m.end() # just past '(' - depth, in_str = 1, False - out = [] - while i < len(text): - c = text[i] - if in_str: - out.append(c) - if c == "\\" and i + 1 < len(text): - out.append(text[i + 1]) - i += 2 - continue - if c == '"': - in_str = False - elif c == '"': - in_str = True - out.append(c) - elif text.startswith("//", i): - end = text.find("\n", i) - i = len(text) if end < 0 else end - continue - elif text.startswith("/*", i): - end = text.find("*/", i + 2) - i = len(text) if end < 0 else end + 2 - continue - elif c == "(": - depth += 1 - out.append(c) - elif c == ")": - depth -= 1 - if depth == 0: - break - out.append(c) - else: - out.append(c) - i += 1 - args.append("".join(out)) - pos = i + 1 - - -def _expand_macros(text: str, macros: dict[str, tuple[str, str]], limit: int = 16) -> str: - """SHIM_TABLE argument text with the file's one-parameter entry macros applied.""" - for _ in range(limit): - found, out, pos = False, [], 0 - for m in MACRO_CALL.finditer(text): - if m.group(1) not in macros: - continue - open_paren = m.end() - 1 - close = _balanced(text, open_paren) - if close < 0: - continue - param, body = macros[m.group(1)] - arg = text[open_paren + 1:close].strip() - expanded = body.replace("#" + param, '"' + arg.strip('"').strip() + '"') - expanded = re.sub(r"\b" + re.escape(param) + r"\b", arg, expanded) - out.append(text[pos:m.start()]) - out.append(expanded) - pos = close + 1 - found = True - if not found: - return text - text = "".join(out) + text[pos:] - return text - - -def _balanced(text: str, start: int) -> int: - """Index of the ')' matching the '(' at `start`, or -1.""" - depth, in_str = 0, False - i = start - while i < len(text): - c = text[i] - if in_str: - if c == "\\": - i += 1 - elif c == '"': - in_str = False - elif c == '"': - in_str = True - elif c == "(": - depth += 1 - elif c == ")": - depth -= 1 - if depth == 0: - return i - i += 1 - return -1 - - -def shim_table_entries(shims_dir: str) -> set[str]: - """The "dll!name" keys the SHIM_TABLE registrations in shims_dir's .cpp files implement.""" - entries = set() - for path in sorted(glob.glob(os.path.join(shims_dir, "*.cpp"))): - with open(path, encoding="utf-8", errors="replace") as f: - text = f.read() - macros = {} - for name, param, body in DEFINE_RE.findall(text): - macros[name] = (param, re.sub(r"\\[ \t]*\r?\n", " ", body)) - for args in _table_arguments(text): - body = args.split(",", 1)[1] if "," in args else "" - for group in ENTRY_GROUP.findall(_expand_macros(body, macros)): - strings = STRING.findall(group) - if len(strings) >= 2: - entries.add(strings[0].lower() + "!" + strings[1]) - return entries - - -IMPLEMENTED = "implemented" -HOST = "host" -THUNK = "unimplemented thunk" - -# Ported from registry.cpp's owns_dll(): the modules that always stay on the host even though the shim -# table registers names for them, and the API-set prefixes it rules out before the table is consulted. -HOST_DLLS = frozenset({ - "kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll", - "vulkan-1.dll", "ntdll.dll", "user32.dll", -}) - - -def owned_dlls(implemented: set[str]) -> frozenset[str]: - """The DLLs registry.cpp's owns_dll() calls shim-owned: any SHIM_TABLE entry exists for them and they - are not the host-bound system modules or API sets it excludes.""" - owned = {key.split("!", 1)[0] for key in implemented} - return frozenset(d for d in owned - if d not in HOST_DLLS and not d.startswith(("api-ms-", "ext-ms-"))) - - -def summarize(imports: list[tuple[str, str]], implemented: set[str]): - """(rows, per_dll): rows are (dll, name, class, binding) sorted and deduplicated on the loader's - dll_key, where binding is IMPLEMENTED, HOST or THUNK, mirroring the loader's routing order; per_dll - maps a dll to [imports, hresult, other, implemented, host, unimplemented thunk].""" - owned = owned_dlls(implemented) - rows = [] - for dll, name in sorted({(dll_key(d), n) for d, n in imports}): - cls = classify(dll, name) - if f"{dll}!{name}" in implemented: - binding = IMPLEMENTED - elif dll in owned: - binding = THUNK - else: - binding = HOST - rows.append((dll, name, cls, binding)) - per_dll: dict[str, list[int]] = {} - for dll, _name, cls, binding in rows: - c = per_dll.setdefault(dll, [0, 0, 0, 0, 0, 0]) - c[0] += 1 - c[1] += cls == HRESULT - c[2] += cls == OTHER - c[3] += binding == IMPLEMENTED - c[4] += binding == HOST - c[5] += binding == THUNK - return rows, per_dll - - -def format_report(imports: list[tuple[str, str]], implemented: set[str]) -> str: - """The per-import and per-DLL report for (dll, name) pairs against the shim table.""" - rows, per_dll = summarize(imports, implemented) - - out = [] - width = max((len(d) + len(n) + 1 for d, n, _c, _b in rows), default=6) - for dll, name, cls, binding in rows: - out.append(f"{dll + '!' + name:<{width}} {cls:<7} {binding}") - out.append("") - - head = ("dll", "imports", "hresult", "other", "implemented", "host", "unimplemented") - dw = max([len(d) for d in per_dll] + [len(head[0]), len("total")]) - out.append(f"{head[0]:<{dw}} {head[1]:>7} {head[2]:>7} {head[3]:>5} {head[4]:>11} " - f"{head[5]:>4} {head[6]:>13}") - totals = [0, 0, 0, 0, 0, 0] - for dll in sorted(per_dll): - n, hresult, other, impl, host, thunk = per_dll[dll] - totals = [a + b for a, b in zip(totals, per_dll[dll])] - out.append(f"{dll:<{dw}} {n:>7} {hresult:>7} {other:>5} {impl:>11} {host:>4} {thunk:>13}") - out.append(f"{'total':<{dw}} {totals[0]:>7} {totals[1]:>7} {totals[2]:>5} " - f"{totals[3]:>11} {totals[4]:>4} {totals[5]:>13}") - return "\n".join(out) + "\n" - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(prog="import_inventory.py", - description="Report how PE imports map onto the runtime's shim layer.") - ap.add_argument("imports", nargs="*", metavar="LIST", - help="text file(s) of dll!function lines") - ap.add_argument("--pe", action="append", default=[], metavar="IMAGE", - help="read imports from a PE32+ image") - ap.add_argument("--shims", metavar="DIR", - default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "runtime", "shims"), - help="directory of shim .cpp files to cross-reference") - a = ap.parse_args(argv) - if not a.imports and not a.pe: - print("no inputs: give an imports file or --pe IMAGE", file=sys.stderr) - return 1 - - imports = [] - rc = 0 - for path in a.imports: - try: - with open(path, encoding="utf-8", errors="replace") as f: - parsed, bad = parse_import_lines(f) - except OSError as e: - print(f"{path}: cannot read ({e.strerror or e})", file=sys.stderr) - rc = 1 - continue - if bad: - print(f"{path}: {bad} line(s) without dll!name skipped", file=sys.stderr) - imports.extend(parsed) - for path in a.pe: - try: - imports.extend(pe_imports(path)) - except (PeFormatError, OSError) as e: - print(f"{path}: not a readable PE32+ image ({e})", file=sys.stderr) - rc = 1 - - implemented = shim_table_entries(a.shims) - print(format_report(imports, implemented), end="") - return rc - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) -- cgit v1.2.3