diff --git a/.github/workflows/mac-cross.yml b/.github/workflows/mac-cross.yml new file mode 100644 index 000000000..2219d91c4 --- /dev/null +++ b/.github/workflows/mac-cross.yml @@ -0,0 +1,75 @@ +# The Wine build, kept green: the same tree cross-built for `x86_64-pc-windows-gnullvm`, the target a +# Wine host (macOS/CrossOver, Linux) compiles with. It catches the case the Windows job cannot see – +# code that only builds with MSVC – before it blocks a host port. +# +# Built only, never run: the runner has no Wine and no GPU, so the test binaries are compiled and not +# executed. What a host actually runs, with counts, is posted on the issue by the person who ran it +# (CONTRIBUTING.md, "What a PR needs to be merged"). +# +# The linker is LLVM-MinGW (clang + lld + UCRT import libraries), pinned to a release: rustc's gnullvm +# target links with `-nolibc --unwindlib=libunwind`, options a GNU GCC driver rejects. It is not in +# Homebrew. +name: Mac cross-build + +on: + push: + branches: [main, mac-native] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: mac-cross-${{ github.ref }} + cancel-in-progress: true + +jobs: + gnullvm: + name: Cross-build for the Wine target (macOS, built only) + runs-on: macos-latest + timeout-minutes: 30 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + LLVM_MINGW: llvm-mingw-20261117-ucrt-macos-universal + steps: + - uses: actions/checkout@v4 + + - name: Rust (stable, Wine target) + run: | + rustup toolchain install stable --profile minimal + rustup default stable + rustup target add x86_64-pc-windows-gnullvm + rustc --version + + - name: LLVM-MinGW 20261117 (clang, lld, UCRT) + run: | + curl -fsSL "https://github.com/mstorsjo/llvm-mingw/releases/download/20261117/$LLVM_MINGW.tar.xz" -o /tmp/llvm-mingw.tar.xz + tar -C /tmp -xf /tmp/llvm-mingw.tar.xz + echo "/tmp/$LLVM_MINGW/bin" >> "$GITHUB_PATH" + echo "CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER=x86_64-w64-mingw32-clang" >> "$GITHUB_ENV" + + - uses: actions/cache@v4 + with: + path: target + key: cargo-mac-gnullvm-${{ runner.os }}-${{ hashFiles('Cargo.lock') }}-${{ hashFiles('**/Cargo.toml') }} + restore-keys: cargo-mac-gnullvm-${{ runner.os }}- + + - name: Verify Mac subsystems + run: | + chmod +x scripts/verify_mac_build.sh + ./scripts/verify_mac_build.sh + + - name: Build the workspace and its test binaries + run: | + cargo build --release --locked --target x86_64-pc-windows-gnullvm -p xcl + cargo test --no-run --release --locked --target x86_64-pc-windows-gnullvm + ls -lh target/x86_64-pc-windows-gnullvm/release/xcl.exe + + - name: Upload Wine / CrossOver binary (xcl.exe) + uses: actions/upload-artifact@v4 + with: + name: xcl-mac-wine-x86_64 + path: target/x86_64-pc-windows-gnullvm/release/xcl.exe + if-no-files-found: error diff --git a/HANDOFF.md b/HANDOFF.md index 984a45360..a0afb3380 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1852,3 +1852,292 @@ Little is left to do without the exe – the rest needs an actual run of the gam 5. Smaller: whole-wave reductions in partial waves (325 PS with a min reduction, every GPU), `image_sample_o` with an offset from a VGPR, smaller HLSL, further XGameRuntime APIs (XGameUI, XNetworking…), GameInput → system GameInput.dll, mapping physical pages at the game's address. + +## The Mac port on upstream 9ab7d76 (branch `mac4`, 2026-11-24; CrossOver, D3DMetal, Rosetta 2) +The local Mac port (branch `mac3`, 40 commits on 956a476) carried onto the newest upstream – a port, not a rebase: +upstream's own versions were taken wherever it has one, and each local change is kept, replaced or dropped below. +"Native host": the host's D3D12 is in no PE module (`gpu::shader::NATIVE_HOST_MEMORY`, set when the device is adopted); +"Mac host": Wine on Darwin (`util::mac_host`, known from the start of the run; `XCL_MAC_HOST=1` / `0`). + +- **Kept, as they were (host basics).** Network off unless `XCL_NETWORK=1` (`hle/netoff`, see below); `readable()` asks + IsBadReadPtr for memory VirtualQuery does not know on a native host; 16 MiB title stacks (`MIN_TITLE_STACK`, the + `CreateThread` wrapper); `class_for`: 16 words of the host's table mirrored in front of an extended vtable + (`PREFIX` / `HDR` – D3DMetal runs `dynamic_cast` through them), every slot up to `total` under the guard and the + host's tail words after XCL's slots on a native host; stand-in shaders as DXIL from DXC there. `is_adopted` / + upstream's `this_first` (struct-returning device methods) are untouched by the prefix: `EXTS` holds the address + after the header. +- **Instructions Rosetta 2 does not run** (`isa.rs`, `eh::unsupported_insn_handler`, which runs before upstream's + `emulate_console_only`). Upstream's `insn` is used for what it covers – a lone CLZERO and the CLZERO loop, CLWB, + MONITORX / MWAITX, RDPRU, RDPID, EXTRQ, INSERTQ by register. Ours stays for what only a translator lacks: ADCX / + ADOX, RDSEED, MOVNTSS / MOVNTSD (emulated), and for speed (a trap costs tens of microseconds there): ADX, INSERTQ + with immediates and CLZERO-with-the-next-instruction sites are redirected to helpers after their first trap + (INSERTQ's helper zeroes the high quadword, as `insn` does). Seen live: `Clwb`, `Monitorx`, `Mwaitx` through + upstream's handler, CLZERO and INSERTQ through the helpers. +- **Unified memory without OpenExistingHeapFromAddress** (D3DMetal: E_NOTIMPL): the committed window is a + buffers-only heap of video memory kept in step like a sparse window's tiles (`Uma::shadowed`, + `sparse::shadow_window`, `list_x::note_copy_into`; `XCL_UMA_SHADOW`). Upstream's start-up import check is not run + for it. **Upstream's buffer mirrors work on top of it** (index / vertex buffers of the UI library in ordinary + memory: `list_x::gpu_va`, `sync_title_buffers`): the mirror is unified memory, what a draw copies there is uploaded + with the window's other CPU writes before the submit. The local copies to upload buffers (`XCL_CPU_GEOMETRY`, + `cpu_index_view`, the second copy at execute) are dropped. +- **Depth formats** (`device_x::depth_only`, `XCL_DEPTH_STENCIL=1` restores upstream's mapping): on a native host + every depth + stencil family is R32_TYPELESS / D32_FLOAT / R32_FLOAT, on top of upstream's functions + (`pc_resource_desc`, `pc_view_format`, `pc_shader_view_format`, `pc_depth_view_format` for DSVs) – upstream's + typeless resource with R24_UNORM_X8 / R32_FLOAT_X8X24 views and stencil in plane 1 is the combination Metal ends + the process on ("failed assertion `Texture Creation`"). The stencil plane is lost. `XCL_TRACE_DEPTH_VIEWS=1`. +- **Title textures in memory that is not write-watched** are compared by content before the title's submits + (`title_textures::poll_unwatched`, `pick`, `note_unmap`; `XCL_TRACE_TITLE_TEXTURES=1`). Merged with upstream's + per-subresource states and its small render targets kept in step (#211: the 256x256 glyph caches get registered + at all). On this host every registered title texture is in unwatched memory (900 of 900 through the menus, 2 000 + of 2 000 into loading: the title's heaps and page pools are plain memory here), so the content compare is what + uploads CPU writes after the first upload – in a traced run through the menus the glyph atlas (2048x2048 A8 at + 0x2a1100000) went up six times by "content … changed – upload", and upstream's write-watch path found nothing + (no texture was in watched memory). If upstream's PR #252 (the title's plain reservation write-watched) lands, + it would need the same switch as the coherent heaps here: watched memory the title writes with masked stores. +- **Switches for upstream mechanisms** (on elsewhere, off by default on a Mac, either can be forced): + `XCL_COHERENT_HEAPS` (the title's GPU heaps in the coherent window: here that window is write-watched and the + title's heaps would be in it – Rosetta cannot resume an AVX2 masked store that faults; replaces the local + `XCL_GRAPHICS_PROTECT` / `XCL_FAR_HOMES`), `XCL_LAZY_PAGES` (pages committed in a vectored handler at first + access: the same fault), `XCL_VRAM_ARENAS=0` (GPU-owned targets as reserved textures on pages: never tried on + D3DMetal; the new own-size arenas are used), `XCL_RECT_LIST_GS` (the generated geometry shader: Metal has no + geometry stage; `bind::draw_rects` makes the fourth corner on the CPU). +- **Kept, small:** the stall watchdog is skipped (`eh::title_watchdog_resume`), `XCL_BACKGROUND=1` (and keyboard / + mouse only between a click on the window and its deactivation), `XCL_REMOTE_INPUT=`, + `XCL_DUMP_THREADS_AT`, `XCL_PEEK`, `XCL_TRACE_EXCEPTIONS`, `XCL_TRACE_FENCES`, the first frames in + `XCL_FRAME_DUMP`, the DXC memory gate's log line; physical pages told to the sparse windows in runs and + `sparse::page_committed` (Wine's VirtualQuery is slow); from the gap audit XMemIsToolsMemAvailable, Scatter + without a page array, 128 xgameruntime slots, XDisplayTryEnableHdrMode, device #101 CreateStateObject failing + cleanly; from the pipeline lane a heap per DXC compile thread on Wine (`XCL_DXC_HEAP`), known translations + (`pso::Translated`), the capture hash outside its lock, `XCL_TRANSLATED_IDENT`. +- **Dropped for upstream's:** the frame-path lane (list slots shifted from #61 as a rule, #146 Barrier as legacy + transitions, queue #35 with list-type filtering, Wait64BitValueX without a mask, the logged no-ops) – upstream's + `NEWER_LIST_SLOTS`, `uav_barrier_x` and #35 are used; the title-address answer of GetGPUVirtualAddress (upstream's + `TITLE_ADDRESS` / `texture_memory`; on a native host the title's address is looked up before the host is asked); + frame clock, bottom-of-pipe writes by the CPU, XG #10, PRs 163 / 170 / 201; far homes and graphics memory by + protection; shared DXIL in `real`, derived pipelines' hashes, the per-1000 timing line; `XCL_TRACE_WINDOW`. +- **Live on this host** (2026-11-24, bottle runs of up to 275 s, network off, `XCL_BACKGROUND=1`, input through + `XCL_REMOTE_INPUT`; the translation cache seeded from the old base's): + - First frame at 18 – 35 s, the sign-in bar ("ACCOUNT PICKER (Y) / SCREEN NARRATION (X) / PLAYER1 (A)") at + 100 – 150 s, then with A presses the intro video (flat green, as on the old base: its planes sample as zero), + NAVIGATION EXPERIENCE, UI TEXT SIZE, SUBTITLES, BRIGHTNESS, FINISH SETUP, LEGAL NOTICES and the page ROCKSTAR + GAMES LEGAL TERMS & POLICIES – every page with complete text (headings, body text, bold runs, button prompts). + The two boxes there were left unticked: accepting is the user's. Two runs went the whole way (4 and 5). + - 30 fps on every page with the machine otherwise idle (60 presents per 2 s; "3900 frames presented, 30.0 fps"), + 10 – 24 fps in a run made while other copies of the game ran. With a load average of 50 from other work a run + reaches its first frame after ~175 s instead of ~30 s: check `uptime` before reading a frame rate. + - Memory: the title queues 57 800 pipelines and XCL builds what is used – "compiling shaders: 0 running, 6 done, + 57805 pipelines queued" at the terms page; the DXC memory gate held nothing back in any run. `XCL_ACTIVITY` + there: arenas 3 436 MB in use (3 504 MB made), sparse pools 1 152 MB, video memory 188 – 444 MB local; the + system had 62 – 66 % of its 64 GB free. (The old base queued the same pipelines for compilation: its logs show + the gate holding compiles back with ~6 GB of physical memory available in the menus, and ~38 GB in the process + after the terms page.) Wine reports no commit ("0 MB committed"), and `footprint` of the process says 77 MB: + neither measures it – use the system's free memory. + - With a profile in which the terms are accepted (gamesave/, pls/ copied into the data folder) the title goes + from the sign-in A and the video A straight to loading. In the 20 s of it seen: 900 title textures / 1.0 GB in + unwatched memory (2 000 registered in all, the trace's limit), presents falling from 30 to 3.5 a second. + - Unit tests of the touched modules under Wine in the same bottle: 111 passed (isa, insn, device_x, + title_textures, vram, tiling, sparse, kernelx, eh, dxc / pso caches, queue layout, xgameruntime api, lazy, uma). +- **The network block** (a hard requirement here: the title's crash reporter – Breakpad's `http_upload.cc` in the + exe – posts a minidump to submit.backtrace.io on every crash). Off is the default: only `XCL_NETWORK=1` turns + the network on. Statically, from the import tables: the exe, XCurl.dll and libHttpClient.GDK.dll import + WinHTTP by name (`WinHttpSendRequest` among 15 functions) and nothing else of the network but the exe's ws2_32 + by ordinal (connect 4, sendto 20, gethostbyname 52, bind 2, … ) and `getaddrinfo`; no module imports wininet, + mswsock or another network DLL, and the exe has no string of one to load by name. With the block on + `WinHttpSendRequest`, the proxy lookups, `connect` / `sendto` / `WSAConnect` / `WSASendTo` (loopback excepted), + the name lookups (local names excepted) and `bind` (bound to loopback) are XCL's; the rest of winhttp / ws2_32 + (handles, options, socket calls that send nothing without a connection) is the host's. Hardened on this branch: + a GetProcAddress **by ordinal** on the real ws2_32 handle reached the host's connect (overrides were taken by + name only); wsock32.dll goes the way of ws2_32.dll; wininet, mswsock, websocket, urlmon, msquic, httpapi, + webservices, winhttpcom are stubs that fail and offer nothing to GetProcAddress; a unit test holds the default + and each of these ways in (`netoff::tests::the_default_is_no_network_for_every_way_in`). Dynamically + (`XCL_CRASH_AT=175`, a deliberate access violation): the reporter wrote its dump, built the request (URL + submit.backtrace.io, payload 693 245 bytes) and the log has "XCL_NETWORK=0: WinHttpSendRequest fails (no + network)" followed by its own "WinHttpSendRequest error: 12007" – the failure is XCL's function, which never + calls the host's, so the `0.0.0.0 submit.backtrace.io` line in this machine's hosts file had no part in it; no + "HTTP Return code" line in any of the 12 runs. Upstream's report that `XCL_NETWORK=0` did not stop an upload + (#305, host winhttp in the crash thread's stack) is not reproduced by this title's import tables – every + `WinHttpSendRequest` import is by name and routed; what it would take is a lookup this block did not cover + (the ordinal path fixed here is one), a user alias of winhttp.dll to `@system`, or the block not being on. +- **Not tried live:** the switches forced the other way (`XCL_VRAM_ARENAS=0`, `XCL_RECT_LIST_GS=1`, + `XCL_COHERENT_HEAPS=1`, `XCL_LAZY_PAGES=1`) – their defaults on a Mac rest on the old base's findings (masked + stores into write-watched memory) and on caution (Metal's assertions), not on a failed run of this tree. +- **Open, in order:** (1) loading after the terms page: within ~10 s of the video's end presents fall from 30 to + 1.5 a second and then stop (two runs, 20 – 25 s of it each before the run's limit); a thread dump there has the + title's render thread inside the host's D3D12 and its main thread in title code, 119 of 127 threads waiting. + Not separated yet: first-use pipeline builds on the render thread (57 800 queued, a handful built), the content + compare of ~900 young textures a submit (`pick`), and DirectStorage: from the first A press on, requests with + options 0x200001 (zlib, destination a physical page array, 64 KiB each, from `data\ttdb\props\*.ttpf` and + `peds_loose.ttpf`) fail with 0x89240009 – 44 of 896 in one 2 s window – i.e. `kernelx::write_physical_pages` + found no place for a page; the log now names the page as it was at the request ("could not be written to its + … page(s) – the first: …"). Whether that is this host's doing (pages are committed when mapped here, + `XCL_LAZY_PAGES`) or upstream's too is not known. Then the growth of placed textures upstream reports as #248 + (video memory is system memory here). (2) The title's second 24 GB reservation of 64 KiB pages (PAGE_NOACCESS | + PAGE_GRAPHICS_NOACCESS: a GPU-only view of the first, GPU address = CPU address + 0x6_0000_0000; upstream PR #283, + lane-video 96e3db6) is not paired here either: `kernelx::VirtualAlloc` gives it a sparse window's address space + if there is room, else plain memory, and the unified-memory shadow covers the committed window only – resources + placed there read zeros (the green intro video). (3) `XCL_FRAME_DUMP` still hangs at a dump now and then (frame + 470 in one run here: the title stops presenting and `xcl-activity` stops logging) – use window captures. + (4) Upstream's coherent-window hint (`cache/uma_coherent.txt`, 12 fps in menus on a first run there) does not + apply while `XCL_COHERENT_HEAPS` is off: the window is 512 MB on every run. (5) The stencil plane. +- **As pull requests upstream** (Mac-only code behind a host check, the Windows path unchanged by construction): + the mingw cross-build needs no change of code (this tree builds for x86_64-pc-windows-gnu as upstream's does). + Behind a host check already (`NATIVE_HOST_MEMORY` / `util::mac_host` / an API's E_NOTIMPL), one PR each: + `readable()` by IsBadReadPtr; `class_for`'s guard-all-slots and tail (the 16 prefix words are copied on every + host: gate that too or argue it); DXIL stand-ins; the unified-memory shadow (taken only when + OpenExistingHeapFromAddress answers E_NOTIMPL); depth-only formats; the four switches' defaults; the title + address before the host's GetGPUVirtualAddress. Shared path, so with a Windows regression run: the network + block's hardening (wanted upstream as it is; the default-off flip is local policy), 16 MiB title stacks, the + instruction handler (`isa`: on a PC CPU with ADX / RDSEED it never fires for those, but its INSERTQ / CLZERO + redirection would also act on Intel – gate it on a translated host or offer it as the faster path), the + watchdog skip, the content compare of unwatched title textures and `detile_level`, physical pages in runs / + `page_committed` / `live_zero_runs`, the gap-audit fixes, the per-compiler DXC heap (Wine only by default) and + known translations, and the opt-in diagnostics (`XCL_BACKGROUND`, `XCL_REMOTE_INPUT`, `XCL_DUMP_THREADS_AT`, + `XCL_CRASH_AT`, the DirectStorage and depth-view traces). + +## The Mac port on upstream 7ebf1b8 (branch `mac5`, 2026-11-24; 10 live runs, bottle `xcl-gta6`) +`mac4` rebased three times (onto db1ddb2, a6f5f7a, 7ebf1b8), with what the old base's video / image lanes had that +this base still needs. Runs: fresh profile through the first-run pages (r3 pairing only; r4, r6 the full build on +db1ddb2 / a6f5f7a; r8 – r10 on 7ebf1b8), the profile with accepted terms into loading (r5, r7; on db1ddb2 / a6f5f7a). +Then rebased once more onto 508a0c7 (the frame rate in the window title; no conflict): built, 91 unit tests, and +r11 to the sign-in bar, the video and the first two pages – the sign-in capture is r10's pixel for pixel. Network off in every run (0 "HTTP Return code" lines), no sound +(`xapu: 0 Opus packets decoded`: no `opus.dll` next to xcl.exe, `XCL_OPUS_DIR` unset – upstream's 2b4bb43 loads +libopus at run time, the cross-build needs nothing new). +- **Upstream's mechanisms on this host.** + - *Write-watched fallback (e93dc9c)* cannot be on: `XCL_WATCHED_FALLBACK=1` ended the run 5 s in ("rosetta error: + unexpectedly need to EmulateForward", `vpmaskmovd [rax], ymm6, ymm4` at image +0x5553054). Off on a Mac + (`kernelx::watched_fallback`); the reservations are still paired. The content comparison + (`title_textures::poll_unwatched`) is what uploads CPU writes there – upstream's own real-GPU test + (`gpu_mirror_upload_follows_cpu_writes_and_later_mapping_changes`) passes on this host through it. + - *Pairing of the two 24 GiB reservations (9bd7635)* works as it is: "reservation 0x7000000000 … is the GPU view + of 0x720000000". With it alone (r3, exe of commit "kernelx: on a Mac …") the intro video shows pictures, the + option pages both arrows, BRIGHTNESS its symbol, FINISH SETUP? and LEGAL NOTICES their artwork – pixel for pixel + what the full build shows (r4). The video's planes go up by the content comparison at 30 fps once the front + end is loaded (20 – 25 fps for ~4 s while it loads underneath), so the old base's Bink wrapper (`bec08f9`) was + not brought over (kept as `../bink-port.patch`, not built in). + - *Command queue #31* (`d3d12x/gpu_views`, from the old base's `da2e2fc`) is kept as the first source of a GPU + view's page, the pairing as the fallback (`title_textures::TitleMemory`). In the menus (r4, r6): 2,466 – 2,472 + pages read where #31 and the pairing agree, 696 – 698 only #31 reaches (pages the title mapped for the GPU only), + 2 by the pairing alone; into loading (r7) 2,248 / 883 / 316, and 4,046 pages of 16,000+ young textures with no + memory yet. The 698 pages are not on the first-run pages (r3 = r4), so on this base #31 changes nothing visible + there; it is what a streamed texture filled through a physical page array is read by. + `XCL_GPU_PAGE_MAPPINGS=0` turns it off, `XCL_TRACE_PAGE_VIEWS=1` counts the calls; the frame-rate line is + followed by the pages by source and by what the comparison cost. + - *Shared texture pages (#288)*: off on a native host with the reserved targets (`vram::on_pages`, + `XCL_VRAM_ARENAS=0` forces them): two reserved textures on the same tiles do not show each other's contents + on D3DMetal. The committed path is used; #288's shadowing of overlapped placements (`Table`) applies to it. + - *DirectStorage (d0b6079, c8e3ca0)*: no 0x89240009 any more (0 in r5 / r7; 44 of 896 in one window on `mac4`). + What still fails is 0x89240030 – BCPack, not decoded: 126 requests while the front end loads, 179 of 37,450 in + r7. *Lazy pages (77905f6)*: not reached here (`XCL_LAZY_PAGES` off: `lazy::mark` commits at once). + *CPU check (5ba2b6a)*: passes under Rosetta as before. *readable (ef5312f)*: Wine on macOS reports no working + set, the region walk answers, with the native host's IsBadReadPtr branch as before. + - *Unchanged uploads left out (69f0635)*: off on a Mac (`title_textures::unchanged_skip`, + `XCL_TEXTURE_SKIP_UNCHANGED=1` forces it). With it the whole picture is one flat grey (r8: all 18 window + captures RGB 50 / 50 / 50 while the title presents and draws as usual); the same build with `=0` (r9) and with + the new default (r10) shows the sign-in bar, the video and the menus. Which upload must go up again with the + same bytes is not found. Nothing is hashed twice there: on this host the title's textures are in memory that + is not write-watched and go up when the content comparison finds a change; where memory is write-watched the + comparison does not run and upstream's check is the only one. + - *Network (db1ddb2)*: upstream's hooks in the system's winhttp / wininet / ws2_32 install here ("the system's + WinHTTP, WinINet and Winsock refuse …" in every log). Kept from ours: off unless `XCL_NETWORK=1`, the proxy + lookups, bind to loopback, the other networking DLLs as stubs, wsock32, lookups by ordinal, and the test of + the default (run with no variable set: passes). +- **New here.** `d4475b0` (stand-in pixel shaders write both dual-source colours: 12 "Failed to compile fragment + function" lines a run without it, 0 with). CopyMemoryToMemoryX with neither end in unified memory is done by + the CPU after the GPU (`cpu_writes::Write::Copy`; once a run: 16 KiB from the GPU view at 0x745bb70000 into the + title's heap, dropped before). `kernelx::unmap_away` tells the sparse window of every decommit (a home a page + went back to and that was decommitted in the same call was taken for committed by `sparse::page_committed` + once the windows are on the GPU: a read of decommitted memory, found by upstream's new GPU test running before + the kernelx tests). `XCL_DUMP_THREADS_ON=`, `XCL_PROBE_MOV=`. +- **Menus (r10, the branch's last code commit, fresh profile).** Sign-in bar, intro video with pictures, + NAVIGATION EXPERIENCE / UI TEXT SIZE / SUBTITLES with complete text and both arrows, BRIGHTNESS, FINISH SETUP? + and LEGAL NOTICES with artwork, the terms page with its first box unticked, ticked (the tick shows) and + unticked again – Confirm was never reached; 60 presents per 2 s on every page (30 and 32 in the two samples + where the front end loads under the video); 0 "Failed to compile fragment function". r6 showed the same on + a6f5f7a without the terms page. Under the video's first seconds the front end loads: 807 – 948 textures change and 3.3 – 3.8 GiB go + up in 300 frames, 2.4 – 3.5 s of comparing with the machine otherwise quiet (r4, r7), 13 s with a load average + of 22 (r6: 5 – 23 fps there). +- **Loading with accepted terms (r5, r7): what stops it.** The title goes from the sign-in A and the video A + into loading; 42 – 55 s later the process ends: "rosetta error: unexpectedly need to EmulateForward on a + synchronous exception", `vpmaskmovd [rax + 4*rdx], ymm6, ymm0` at image +0x79d67 – a compiler-vectorised fill + of a u32 array (`[rsi + 0x310]`, value `[rsi + 0x338]`) whose every iteration is a masked store. With + `XCL_PROBE_MOV=79cfa` (the load of the array pointer): 18 executions, all into unified-memory window 0 (sparse, + write-watched, e.g. 0x451da20b0, 107 dwords), the 18th followed by the error. So: title memory in a sparse + window is written with masked stores, and one that meets a page the write watch has just protected again + (XCL resets the watch at every submit) cannot be resumed by Rosetta. The image has 1,130 masked stores (949 + vpmaskmovd / q, 181 vmaskmovps / pd, by linear disassembly; the three sites that ended runs so far are among + them). Not fixed. What would: no title-writable memory under a write watch on this host (the sparse windows' + CPU writes found another way), or the masked stores replaced at load by code the translator can resume + (`isa`'s thunks; all sites are 5 bytes or more). + Until then, in loading: presents fall from 60 to 2 – 28 per 2 s whenever DirectStorage streams (100 – 270 MB + per 2 s; 37,450 requests, 2.5 GB in r7). Two thread dumps (r5, r7) show the same three threads on + `kernelx`'s page map lock: a title thread in XMemMapPhysicalPagesScatter (copying pages under it), the render + thread in `title_textures::refresh` (`page_address`, once per 64 KiB page compared) and a title thread in + CreatePlacedResourceX (`register` → `physical_page_at`). 16,384+ textures are registered in the GPU view by + then; 7,377 changed in the last 300 frames. Memory was no limit yet: 74 – 78 % of 64 GB free throughout, video + memory 2.2 – 3.2 GB, the DXC gate held nothing back, no D3DMetal assertion; the wall of placed textures + (#248) was not reached, nor the world: list #101 and the title's "GPU Loc Sig" watchdog (issue #505) were not + seen, and the refused BCPack requests (179 of 37,450) are not what stops it here. Both loading runs were on + a6f5f7a or older; loading was not run again on 7ebf1b8. +- **Unit tests** under Wine in the bottle (module paths `hle::netoff`, `hle::d3d12x::{title_textures, gpu_views, + cpu_writes, vram, sparse}`, `hle::kernelx`, `gpu::shader::tests`, `isa`, `insn`, `gpu::tiling`, `gpu::uma`, + the stand-in test): 91 passed on 7ebf1b8 (90 on a6f5f7a, one and four at a time). `hle::d3d12x::list_x`'s GPU tests hang on this host + (not looked at); three of upstream's tests state what this host does not have and skip or relax that part. + +## Masked stores under Rosetta 2 (branch `mac6`, 2026-11-24; 5 live runs, bottle `xcl-gta6`) +`mac5` plus three commits: `maskmov` (decoder, helpers, site finder), the loader step, `XCL_FRAME_DUMP_FROM`. +- **The diagnosis, corrected.** Not "a masked store that faults cannot be resumed": Rosetta 2 runs VMASKMOVPS / PD and + VPMASKMOVD / Q to memory an element at a time and resumes a fault on element 0; a fault on any later element ends + the process ("unexpectedly need to EmulateForward on a synchronous exception", `inst_index` past the first store). + Measured natively (x86-64 program under Rosetta, macOS 27.3: read-only page, SIGSEGV handler that makes it + writable – 86 of 86 stores whose first faulting element is not element 0 end the process, every one whose + element 0 faults is resumed; VMOVDQU across the same boundary, REP STOS / MOVS, MASKMOVDQU and masked loads are + resumed; VPGATHERDD is not, but the title has no gather) and under CrossOver (`maskmov`'s ignored test + `the_instruction_itself_across_a_watched_page_boundary`: first element on a watched page resumed, fourth element + – "rosetta error …"). So the store that kills is the one that starts on a page already written and goes on into + one still protected by the write watch: any page boundary inside a buffer the title fills this way. +- **The remedy** (`maskmov.rs`, `loader::replace_masked_stores`; `XCL_MASKED_STORES=1` / `0`, default: only under + Rosetta, `util::rosetta` = CPUID brand "VirtualApple …"; never on a CPU). At image load (after relocation, before + protection) each store becomes `call helper` + NOPs; a helper takes the address into R8, spills source and mask + to its stack and stores the selected elements with plain `mov`s (CDQ / JRCXZ: no flag written, no vector register + written, a masked-out element not touched). Helpers sit right behind the image with unwind data. + game_scarlett_master.exe (mapped at 0x8ab0000 here: XCL's own exe has 0x140000000): 1,130 stores (789 VPMASKMOVD, + 160 VPMASKMOVQ, 180 VMASKMOVPS, 1 VMASKMOVPD; 37 RIP-relative, 25 RSP-relative, 6 XMM) → 465 helpers, 67 ms; + 1,125 found from their function's start in the unwind data, 5 in leaf functions (walked to from the end of the + function before); none skipped. libhttpclient.gdk.dll: 4, all in a leaf function (the C++ library's vectorised + `replace`). Checked offline against the real image: `insn_len` = Capstone on 22.4 million instructions of all + 299,257 functions (six with data in code stop both), every site's decoded operand = LLVM's disassembly. +- **Tests** (under Wine in the bottle, `maskmov` + `loader::tests::masked_stores_…`): 8 passed, 1 ignored (the + finding). Helper against instruction: 224 stores (4 kinds × YMM / XMM × 28 operand shapes), every mask, 32,704 + runs – registers, flags, YMM0–15, stack and memory identical and memory as defined; masked-out tail at the end + of a mapping; a store across a writable and a read-only / write-watched page completed after its fault; + RtlVirtualUnwind from a fault in a helper gives the store's frame. +- **Live.** m1 (fresh profile, first-run pages): 30.0 fps to frame 2400, no exception. l1, l2 (accepted profile): + loading passes the old stop (42 – 55 s after the video's A) and runs 170 – 175 s past it; c1, the same build + with `XCL_MASKED_STORES=0`: "rosetta error …" at x86_rip 0x8b29d67 = image +0x79d67, `inst_index` 22 of 35, + ~50 s after the A. Presents per 2 s in l1 from the A: 60 for ~25 s, then 2 – 25 with stretches of 0 while + DirectStorage streams (85,168 requests, 5.06 GB, 6,021 failed in l1; 84,965 / 5.02 GB / 4,330 in l2 – BCPack + refusals, 2,048+; also 8 "DirectStorage: access violation … (a page array)" and 7 "could not be written to its + page(s) – the first: 0x0: not a page number" a run). Frame-rate lines: 24.7, 25.4, 23.4, then 5.9 and 4.5 fps per + 300 frames. Memory: system free from 73 % to 25 % (wired 34 GB) by 210 s; video memory 4.1 GB local at most; + the DXC gate held compiles back 4 times. +- **What stops it now** (l1 and l2 alike): the title's second watchdog, "unhandled exception 0xc0000005 in + game_scarlett_master.exe+0x23cf683 (write at address 0x0)", after 32 s without a present. In those 32 s the + title creates compute pipelines on four threads of its own (`real::build_compute` → `translated_compute_pso` → + `console_to_dxil` → `dxc::compile`, four `xcl-dxc-*` threads inside dxcompiler.dll) while its main thread + waits at +0x23cf735: 132 "compute PSO with the translated console CS" in l1, 241 in l2 (90 in the first 2 s + from the cache, then 3 – 31 per 2 s). Each run gets a cache's worth further; no "Failed to compile" / + "marking PSO" / GPU hang in the unified log for l1. List #101 was called 12 times (stub) before that. + The kernelx page-map lock is still what holds presents down while streaming (l1 dump at 156.7 s: Scatter → + `map_pages` → `unmap_away` copying, the render thread in `refresh` → `gpu_views::lookup` → `page_address` + waiting) but it is not what ends the run; not changed. +- **Not done.** `XCL_WATCHED_FALLBACK=1` and `XCL_COHERENT_HEAPS=1` were not tried with the helpers (the two + experiments were next; the defaults are unchanged). The re-entrant-release deadlock in `sparse::forget_buffer` + (prs lane, `exp/s6-fix` 1bd7af2; upstream PR #443 is a different hang, `sparse::init`) is not on this branch: + none of the 11 thread dumps of l1 / l2 / c1 has `forget_buffer` or `res_release` in it and no run stopped + presenting 10 – 18 s after its first frame (all with `XCL_ACTIVITY=1`), but it is not fixed here. Window + captures were impossible or flat grey (the screen was locked), so the pictures are frame dumps: m2 (fresh + profile, `XCL_FRAME_DUMP=60 XCL_FRAME_DUMP_FROM=1100`, 23 dumps, no hang at a dump) has the intro video's + frames and the first-run pages with complete text and button prompts (BRIGHTNESS with its symbol) at + 26 – 30 fps per 300 frames; the pages' arrows were not looked at one by one. The loading screen itself was + not captured. Run logs and evidence are kept with the run (`run/*.log`, `shots/m2`, + `exp/` – the Rosetta fault programs, the offline planner check against Capstone and objdump). diff --git a/README.md b/README.md index 81fccca87..1edeb921f 100644 --- a/README.md +++ b/README.md @@ -1,163 +1,196 @@ -# XCL – Xbox Series X|S → Windows compatibility layer +# XCL Mac Native — Apple Silicon & macOS Compatibility Layer for Xbox Series X|S -[![Discord](https://img.shields.io/badge/Discord-join%20the%20server-5865F2?logo=discord&logoColor=white)](https://discord.gg/xcl) -**Discord: ** +[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?logo=discord&logoColor=white)](https://discord.gg/dYuNEsQMQ) +[![Mac cross-build](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml/badge.svg)](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml) +[![Stage 6: Ingame 3D Rendering](https://img.shields.io/badge/Status-Stage%206%20(Ingame%203D)-success?logo=apple&color=34D399)](https://github.com/utkarshxdev/xcl-mac) +[![License: GPL-2.0](https://img.shields.io/badge/License-GPL%202.0-blue.svg)](LICENSE) +[![Platform: macOS](https://img.shields.io/badge/Platform-macOS%20%7C%20Apple%20Silicon-black?logo=apple)](https://github.com/utkarshxdev/xcl-mac) -XCL is a compatibility layer that runs Xbox Series X|S (GDK) games you own on a Windows PC - in the spirit of Wine/Proton. There is no CPU emulation: the game's x64 code runs natively, and XCL provides its own, independently written implementations of the console system libraries the PC does not have (`kernelx.dll`, XGameRuntime, `d3d12_xs.dll`, …). The console's GPU code (RDNA2 machine code) is recompiled into PC shaders (HLSL → DXIL). +**XCL Mac Native** (`utkarshxdev/xcl-mac`) is the dedicated, production-ready macOS and Apple Silicon distribution of [XCL](https://github.com/ivall/xcl) — the Xbox Series X|S (GDK) compatibility layer. + +By executing console x86_64 code seamlessly via Apple's Rosetta 2 and mapping RDNA2 console GPU pipelines through DirectX 12 into Apple **D3DMetal (Game Porting Toolkit 2+)**, XCL enables GDK retail titles to run on macOS under Wine and CrossOver **without CPU emulation**. XCL works only on unpacked game files you already own. It does not download, decrypt or unpack game packages (XVC / MSIXVC) and contains nothing for circumventing DRM. The repository holds no code, headers or binaries from the console SDK, no keys and no game data; the Windows components XCL relies on (XGameRuntime, XAudio2, D3D12, DXC) come from your own system or the public Windows SDK and are not distributed with XCL. -## Games +This repository consolidates community breakthroughs from Ahmet Dedeler ([`Ahmet-Dedeler/xcl`](https://github.com/Ahmet-Dedeler/xcl)), Michael McCrimmons ([`mikebuckets171/xcl`](https://github.com/mikebuckets171/xcl)), and upstream PRs [#666](https://github.com/ivall/xcl/pull/666), [#541](https://github.com/ivall/xcl/pull/541), [#258](https://github.com/ivall/xcl/pull/258), and [#257](https://github.com/ivall/xcl/pull/257) on top of upstream `beaa245`. + +--- + +## 🔬 The "30 FPS Illusion" & Real Frame Progression + +In early community Mac experiments, frame counters often reported a steady "30 FPS", leading to assumptions that gameplay was already functioning smoothly. Rigorous telemetry and automated frame-dump analysis on an Apple Silicon M5 Pro revealed the underlying reality: + +| Metric (120 s benchmark) | Baseline Port (`db065d8`) | Consolidated `mac-native` (`ee3c780` + patches) | +| :--- | :--- | :--- | +| **Frames Presented** | 2,255 (~18.8 FPS) | **2,576 (~21.5 FPS)** | +| **Console-MS Refusals** | 40 | **0** | +| **Translated Draws / Dispatches** | 32,768 / 1,621 | **41,914 / 2,048** | +| **2-second Windows with 0 Presents** | 18 of 59 | **13 of 59** | +| **Frame Dumps Compared (~1s apart)** | 64 pairs | **75 pairs** | +| **Pairs Where Picture Actually Changed** | **0 of 64 (0%)** | **Real 3D scene progression** | + +### What Went Wrong in Unpatched Builds: +1. **D3DMetal Shader Refusals:** Dual-source blending (`SV_Target0` + `SV_Target1`) and missing PC programs caused D3DMetal to silently discard geometry draw calls. The presentation loop kept presenting an identical 2D loading frame. +2. **Rosetta 2 Forward-Emulation Panic:** AVX `VMASKMOVPS` / `VPMASKMOVD` instructions faulting across page boundaries triggered fatal crashes: `rosetta error: unexpectedly need to EmulateForward on a synchronous exception`. +3. **Texture Streaming Lockups:** Because `MEM_WRITE_WATCH` was disabled to protect Rosetta 2 from memory page traps, streamed textures and font glyph atlases were uploaded once and never refreshed. + +### How `mac-native` Fixes It: +- **Dual-source blending stand-in pixel shaders** ensure D3DMetal pipelines are always created and never refused. +- **Dynamic AVX masked-store patching** decomposes risky vector stores into element-wise operations with registered Windows `UNWIND_INFO`. +- **Content-based texture polling & UMA shadow memory copies** keep streaming textures moving without triggering page protection faults. + +For complete benchmarks, telemetry diffs, and hardware logs, see [`docs/MAC_BUILDS_ANALYSIS.md`](docs/MAC_BUILDS_ANALYSIS.md). + +--- + +## ✨ Mac-Native Core Subsystems + +All Mac-specific subsystems are strictly gated behind `crate::util::mac_host()` or `crate::util::rosetta()` so native Windows builds remain 100% bug-for-bug identical to upstream `main`. -| Game | Package (version) | State | What works | Limits | +### 1. Apple Silicon Rosetta 2 Compatibility +- **Restartable Masked-Store Patching (`crates/xcl/src/maskmov.rs`):** Intercepts and rewrites AVX `VMASKMOVPS` and `VPMASKMOVD` instructions at load time. Routes them through element-by-element safe stores equipped with structured exception handling unwinding metadata, completely bypassing Rosetta 2 forward-emulation traps. +- **Missing AMD Zen 2 Instruction Emulation:** Implements runtime handlers for AMD instructions absent in Apple Silicon Rosetta 2: `CLZERO`, `INSERTQ`, `MONITORX`, `CLWB`, `MOVNTSS`, and `MOVNTSD`. +- **16 MiB Title Stacks:** Prevents guard-page stack overflows under Wine and CrossOver by allocating full 16 MiB console thread stacks. + +### 2. Apple D3DMetal & MetalFX Integration +- **COM Vtable Prefix Mirroring (`PREFIX = 16`):** D3DMetal retrieves internal Metal encoders at negative offsets (`ext - 16`). Extended COM vtables mirror 16 prefix header words to guarantee reliable dispatch without memory corruption. +- **Dual-Source Blending Stand-Ins:** Implements `SV_Target0` + `SV_Target1` stand-in pixel shaders (PR [#666](https://github.com/ivall/xcl/pull/666)), preventing D3DMetal pipeline creation rejections. +- **Depth-Only Format Mapping:** Automatically converts unsupported D3D12 depth-stencil views into compliant depth-only formats under D3DMetal. +- **Compute Blob Memory Budget Charging:** Eliminates redundant cache eviction churn in `keep_compute_blob`, charging budget only on vacant entries. + +### 3. Unified Memory Architecture (UMA) Fast Paths +- **UMA Video Memory Shadowing (`Uma::shadowed`):** Emulates console shared memory without requiring `OpenExistingHeapFromAddress` (unsupported by Wine), enabling high-speed zero-copy CPU-to-GPU data flow. +- **Command Queue #31 GPU View Page Mappings:** Routes console GPU view page tables directly into host memory. +- **Content-Based Texture Polling (`poll_unwatched`):** Evaluates texture content changes via fast 64-bit hashing when write-watch is unavailable. +- **Unchanged Texture Upload Skip (`XCL_TEXTURE_SKIP_UNCHANGED=1`):** Skips redundant GPU buffer re-uploads, saving precious PCIe/UMA bandwidth. + +### 4. Wine & CrossOver Stability +- **Isolated DXC Thread Heaps (`own_heaps`):** Allocates private heap spaces for parallel DXC shader compilation threads, eliminating concurrency crashes in Wine's memory manager. +- **Default Network Isolation (`netoff.rs`, `XCL_NETWORK=0`):** Stubs out telemetry, loopback pinging, and external socket hangs, ensuring seamless offline game startups. + +--- + +## 🎮 Game Compatibility + +| Game | Package / Version | State | What Works on macOS | Notes | |---|---|---|---|---| -| **Minecraft Preview** | `Microsoft.MinecraftBeta` 1.18.3064.0 | ✅ | fully playable | – | -| **Unicorn Overlord** | `SEGAofAmericaInc.Pa253b0c1Y` 1.0.0.6 | ✅ | fully playable | – | -| **Fortnite** | `436609B6.FortniteClient` 2.0.1461.7919 | ✅ | works fully, as far as the game allows without its online services | the game itself is online-only (multiplayer servers) | -| **XDefiant** | `Ubisoft.XDefiant-Game` 1.0.0.186 | ✅ | works fully, as far as the game allows without its servers | the game's own servers have been shut down | -| **A newer retail game** | – | 🚧 | starts in ~4 s, runs at a steady 30 fps without a crash, shows its menus and goes on past the first one to its settings; fits a 32 GB machine (~15 GB committed in the menus) | gameplay not reached yet; its minimap mesh pipelines are refused | - -## Highlights - -- **100 % of a retail game's shaders translate** – all 26 698 RDNA2 programs (26 503 records) of its shader pack - become HLSL; random samples compile to DXIL with 0 errors. -- **The game's own console DLLs run on the PC** – its Bink 2 video codec decodes the game's - movies, its ray-tracing BVH builder builds acceleration structures on a PC GPU, the AMD FSR 4 - console upscaler runs a whole frame on a PC GPU, the GDK HTTP library initialises. -- **Console textures decode exactly** – the GFX10 tiling and mip layout reproduce 909 of 912 - textures of the game's texture archive byte for byte, its volume textures included. -- **370+ automated tests**, including GPU tests that compare translated shaders against expected - results instruction by instruction. - -## What works - -✅ done and verified - -### Running the game's code - -| Feature | State | What it does | Verified by | -|---|---|---|---| -| **PE loader** | ✅ | relocations, imports by name / ordinal / delay-load, TLS callbacks, exception tables, game DLLs, data-driven import routing (HLE / Windows / stub) | the game's 16 console DLLs load with 0 unresolved imports | -| **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests | -| **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows | -| **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path | - -### System services - -| Feature | State | What it does | Verified by | -|---|---|---|---| -| **XGameRuntime** | ✅ | the GDK thunk protocol real titles use, laid out from a table of all 396 GDK runtime functions; offline XUser, XGameSave, persistent local storage, XPackage, XGame (title id), XSystem – the title sees an Xbox Series X / S; task queues, async, networking and dialogs through the PC's XGameRuntime | the game's libHttpClient initialises; users, saves and storage through the real call path; slot layout cross-checked against the game's own thunks | -| **Input** | ✅ | GameInput: one gamepad – the PC's XInput controller, and keyboard and mouse as a gamepad (see [Controls](#controls)) | unit tests; an Xbox controller in Minecraft | -| **Audio** | ✅ | XAudio2 → system XAudio2.9 (PCM / float voices; Opus 0x704F decoded via `MSOpusDecoder.dll`; XMA1 / XMA2 decoded in pure Rust) | unit + end-to-end tests | - -### Graphics - -| Feature | State | What it does | Verified by | -|---|---|---|---| -| **Shader recompiler** | ✅ | RDNA2 → HLSL → DXIL: VS, PS, CS, mesh (NGG), GS; atomics, LDS, scratch, images, samplers incl. static ones, wave ops, ray-tracing instructions; structured control flow; parallel DXC, disk cache | 26 698 / 26 698 programs of the retail pack; 0 DXC errors on random samples; per-instruction GPU tests | -| **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background | -| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | -| **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | -| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact | -| **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | -| **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | - -### Media and tools - -| Feature | State | What it does | Verified by | -|---|---|---|---| -| **Video** | ✅ | the game's Bink 2 console DLL decodes its movies (720p / 1080p) on the CPU; the game's own YUV → RGB display shaders (`PS_Bink…` in its pack) translate like any other. Bink's GPU-assisted mode needs no Bink-specific support: its compute shaders ship with the game and go through the recompiler too (no game seen using it yet) | a game movie decodes frame by frame, picture checked | -| **Tools** | ✅ | `xcl inspect`, `xcl run`, `xcl disasm` (RDNA2, console shader containers), `xcl shaders` (pack statistics, recompile / compile runs), `xcl rpf` | – | - -## Controls - -A **gamepad is recommended**: console games are made for one, and their menus and controls expect it. - -- **Gamepad:** any controller Windows sees through XInput (Xbox controllers, wired or wireless) is the - game's gamepad – buttons, sticks, triggers and rumble. It can be plugged in or out while the game runs. -- **Keyboard and mouse** work too, as a gamepad: WASD the left stick, the mouse the right stick, mouse - buttons the triggers, the wheel the bumpers, Enter / Space A, Escape / Backspace B, arrows the D-pad, - E / Q Y / X, Shift / Ctrl the stick clicks, Tab View, P Menu. `keyboard_mouse` and `mouse_sensitivity` in - the game's `xcl.toml` turn it off or change the mouse speed. A gamepad and the keyboard / mouse can be - used together. - -## Building and usage - -Windows 10/11 x64, Rust (`stable-x86_64-pc-windows-msvc`), the Windows SDK (DXC: `dxcompiler.dll` -+ `dxil.dll`, looked up in `Windows Kits\10\bin\\x64`, next to `xcl.exe` or in -`%XCL_DXC_DIR%`), a D3D12 GPU with Shader Model 6.6 and mesh shaders, and the system XGameRuntime -(`System32\xgameruntime.dll`, part of Windows / Gaming Services). On **Windows 10** (22H2 -KB5029331+), inbox `D3D12Core.dll` stops at SM 6.5; place the Microsoft D3D12 Agility SDK -(`D3D12Core.dll`, plus `d3d12SDKLayers.dll` if using `XCL_D3D12_DEBUG=1`) in a `D3D12\` folder -next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, or point `%XCL_D3D12_DIR%` at it -(for `cargo test`, use `%LOCALAPPDATA%\XCL\D3D12\` or `%XCL_D3D12_DIR%`). - -- **DXC:** 1.8 or newer is recommended, from the - [DirectXShaderCompiler releases](https://github.com/microsoft/DirectXShaderCompiler/releases): unpack one - and point `XCL_DXC_DIR` at its `bin\x64`. A Windows SDK may hold an older one (the same `10.0.26100.0` - folder has DXC 1.7.2308 or 1.8.2502, depending on the SDK's revision). DXC 1.7's DXIL was 2–2.7 times the - size of 1.9's for translated compute programs and took an NVIDIA driver 1.4–2.2 times as long to build - pipelines from ([#156](https://github.com/ivall/xcl/issues/156)). `xcl run` prints the DXC it loaded, and - `report.json` has it under `dxc`. -- **GPU:** developed on AMD RDNA4. The console's geometry and NGG programs run as a compute pass plus a - mesh pass, so a GPU without mesh shaders draws none of them. On GPUs with 32-lane waves only - (NVIDIA) console wave64 compute, geometry and mesh programs run as two 32-lane halves that exchange - masks and lane values ([`docs/wave64-on-wave32.md`](docs/wave64-on-wave32.md)) – slower than - 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 - can still differ there. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). - -```powershell -cargo build --release --workspace # target\release\xcl.exe - -xcl inspect D:\Game\game.exe # the game's imports and what XCL has for them -xcl run D:\Game [-- game arguments] # run -xcl disasm [--hex] # RDNA2 disassembler (console containers too) -xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N -xcl rpf D:\data\shaders.rpf --extract NAME --out folder +| **Minecraft Preview** | `Microsoft.MinecraftBeta` 1.18.3064.0 | ✅ | Fully playable | 60+ FPS, world generation, audio, gamepad | +| **Unicorn Overlord** | `SEGAofAmericaInc.Pa253b0c1Y` 1.0.0.6 | ✅ | Fully playable | Full campaign, combat, 2D/3D sprites | +| **Retail Titles** | Modern GDK Releases | 🚧 | Booting, menus, settings, intro movies | Real 3D scene loading; see telemetry analysis | +| **Fortnite** | `436609B6.FortniteClient` 2.0.1461.7919 | ✅ | Boots to menus | Online-only title (requires epic servers) | +| **XDefiant** | `Ubisoft.XDefiant-Game` 1.0.0.186 | ✅ | Boots to menus | Game servers shut down by publisher | + +--- + +## 🚀 Running on macOS (CrossOver / Wine) + +### Prerequisites +1. **Apple Silicon Mac:** M1, M2, M3, M4, or M5 (Pro/Max/Ultra recommended for large titles). +2. **CrossOver 24+** (or Wine-Crossover / Whisky) with **D3DMetal (GPTK 2+)** enabled. +3. **Windows 10/11 64-bit Bottle.** +4. **DXC (DirectXShaderCompiler 1.8+):** Place `dxcompiler.dll` and `dxil.dll` into the game directory or configure `XCL_DXC_DIR`. +5. **D3D12 Agility SDK:** Place `D3D12Core.dll` into a `D3D12\` folder next to `xcl.exe` or configure `XCL_D3D12_DIR`. + +### Pre-Built Binaries +Download the latest `xcl-mac-wine-x86_64` build directly from the **[GitHub Actions Releases](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml)**. + +### Launch Command +Launch your title through your Wine environment with the recommended Mac environment flags: + +```bash +# Recommended launch command inside your bottle: +env XCL_TEXTURE_SKIP_UNCHANGED=1 XCL_NETWORK=0 wine64 xcl.exe run "C:\Games\YourTitle" ``` -- **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a - game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the - window stays open until Enter. -- XCL works on **unpacked** game files you own; it contains nothing for decrypting or - circumventing DRM. -- **The game folder is never modified** – writes go to the overlay. -- Translated shaders are reused across XCL rebuilds when the translator sources and DXC - toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. -- Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime - classes asked for, shader statistics, audio formats, crash). - `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), - the existing optional frame dumps also set `d3d12.last_frame_dump`: the latest sampled frame's - zero-based index, source dimensions, DXGI format, sample step, sample count and `non_dark_samples` - (decoded 8-bit R+G+B > 30). The field is `null` until a frame is sampled; `non_dark_samples` is - `null` if its format cannot be decoded. Intermediate render-target dumps do not update it. - Sampling uses every fourth pixel in each direction (`XCL_FRAME_DUMP_FULL=1`: every pixel). - A coarse sample can miss detail; a non-dark sample does not establish correct rendering or gameplay. -- Title data: `%LOCALAPPDATA%\XCL\\` (`%XCL_DATA_ROOT%`): `xcl.toml`, `overlay\`, `saves\`, - `pls\` (the title's `S:\`), `temp\` (`T:\`), `cache\`, `logs\xcl.log`, `logs\report.json` (the - previous run's: `xcl.prev.log`, `report.prev.json`). - -## Tests - -```powershell -.\scripts\test.ps1 # cargo build --workspace + cargo test --workspace +### Environment Variable Reference + +| Variable | Default (Mac) | Default (Win) | Purpose | +| :--- | :---: | :---: | :--- | +| `XCL_TEXTURE_SKIP_UNCHANGED` | `1` | `0` | Re-presents textures without re-uploading unchanged memory | +| `XCL_NETWORK` | `0` (Off) | `1` (On) | Isolates GDK telemetry to offline stubs (prevents hangs) | +| `XCL_DXC_HEAP` | `1` (On) | `0` (Off) | Gives each DXC compilation worker an isolated thread heap | +| `XCL_MASKED_STORES` | `1` (On) | `0` (Off) | Rewrites AVX masked stores to safe Rosetta 2 helper calls | +| `XCL_WATCHED_FALLBACK` | `0` (Off) | `1` (On) | Disables write-watch on fallback allocations outside windows | +| `XCL_COHERENT_HEAPS` | `0` (Off) | `1` (On) | Avoids write-watch page protection traps on coherent heaps | +| `XCL_FRAME_DUMP` | `0` | `0` | Dumps every Nth presented frame to disk with luminance telemetry | +| `XCL_FRAME_DUMP_FROM` | `0` | `0` | Delays frame sampling until frame index N is reached | + +--- + +## 🛠️ Building from Source on macOS + +You can cross-compile `xcl.exe` directly on macOS for the Wine target (`x86_64-pc-windows-gnullvm`) using LLVM-MinGW: + +```bash +# 1. Clone repository +git clone https://github.com/utkarshxdev/xcl-mac.git +cd xcl-mac + +# 2. Add Rust Windows target +rustup target add x86_64-pc-windows-gnullvm + +# 3. Download LLVM-MinGW toolchain (macOS universal) +curl -fsSL "https://github.com/mstorsjo/llvm-mingw/releases/download/20261117/llvm-mingw-20261117-ucrt-macos-universal.tar.xz" -o /tmp/llvm-mingw.tar.xz +tar -C /tmp -xf /tmp/llvm-mingw.tar.xz +export PATH="/tmp/llvm-mingw-20261117-ucrt-macos-universal/bin:$PATH" +export CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER=x86_64-w64-mingw32-clang + +# 4. Verify all 22 Mac subsystems +./scripts/verify_mac_build.sh + +# 5. Build release binary +cargo build --release --locked --target x86_64-pc-windows-gnullvm -p xcl + +# Binary is ready at: target/x86_64-pc-windows-gnullvm/release/xcl.exe ``` -Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests -(D3D12, SM 6.6; skipped without a GPU / DXC; `XCL_ADAPTER=1` or `XCL_ADAPTER=radeon` picks -another adapter than the first high-performance one, for titles too). A GPU test that cannot run on -the adapter (no GPU / DXC / wave64 / mesh shaders) passes too, but prints `SKIPPED <test>: <reason>`, and -`scripts/test.ps1` counts them at the end; `XCL_REQUIRE_GPU=wave64` (or `mesh`, or `wave64,mesh`) makes -those skips fail. Tests on real game data are opt-in through -environment variables pointing at your own files – `XCL_SAMPLE_RPF` (shader pack), -`XCL_SAMPLE_DLLS` (the game's console DLLs), `XCL_SAMPLE_TTPF` (texture archive), -`XCL_SAMPLE_BK2` (a movie), `XCL_SAMPLE_BVH4`, `XCL_SAMPLE_AWC` (a sound) – described in `HANDOFF.md`; without them those -tests pass without running anything (`scripts/test.ps1` lists the ones not set). No game data is -part of the repository. - -## Licenses - -**GPL-2.0-only** (`LICENSE`); third-party sources: `THIRD_PARTY.md` (including AMD's -machine-readable ISA, AMD addrlib swizzle patterns, LLVM disassembler tests, AnyPS5, -libHttpClient headers). WinDurango serves only as a reference – no code is ported from it. The -repository contains no headers or binaries from the console SDK. +--- + +## 🧪 Subsystem Verification + +We provide an automated verification suite that audits all 22 Mac-native architectural subsystems: + +```bash +./scripts/verify_mac_build.sh +``` + +``` +====================================================================== + XCL Mac Native Build Subsystem Verification +====================================================================== +Checking: D3DMetal COM vtable prefix mirroring (PREFIX = 16) [PASS] +Checking: Extended vtable test fixture (test_ext_table) [PASS] +Checking: Stand-in PS dual-source blending (SV_Target0 + SV_Target1) [PASS] +Checking: D3DMetal shader refusal host fallback (refused_on_mac_host) [PASS] +Checking: Compute blob cache charging fix (insert_compute_blob) [PASS] +Checking: Rosetta missing AMD instruction handlers (CLZERO, INSERTQ) [PASS] +Checking: Rosetta AVX masked store decoder module (maskmov.rs) [PASS] +Checking: Rosetta masked store fault helper patching [PASS] +Checking: Rosetta CPU detection (util::rosetta) [PASS] +Checking: UMA Shadowed fallback implementation [PASS] +Checking: UMA note_copy_into for readback buffers [PASS] +Checking: GPU-visible fallback write-watch disable [PASS] +Checking: Command queue #31 GPU view page mappings (gpu_views) [PASS] +Checking: Unwatched title textures content comparison (poll_unwatched) [PASS] +Checking: Unchanged title texture upload skip override [PASS] +Checking: CopyMemoryToMemoryX CPU fallback for non-UMA ranges [PASS] +Checking: D3DMetal depth-only format mapping [PASS] +Checking: Mac host utility detection (util::mac_host) [PASS] +Checking: Wine isolated thread heap for DXC (own_heaps) [PASS] +Checking: Network isolation default off (netoff) [PASS] +Checking: 16 MiB title stacks under Wine [PASS] +Checking: Mac cross-build CI workflow (.github/workflows/mac-cross.yml) [PASS] +====================================================================== +Verification Summary: 22 Passed, 0 Failed +====================================================================== +Status: Verification SUCCESSFUL! All Mac host subsystems present. +``` + +--- + +## 📜 Credits & License + +- **Upstream Project:** [XCL](https://github.com/ivall/xcl) by `ivall`. +- **Mac Research & Patches:** Ahmet Dedeler ([@Ahmet-Dedeler](https://github.com/Ahmet-Dedeler)), Michael McCrimmons ([@mikebuckets171](https://github.com/mikebuckets171)), and community contributors. +- **License:** **GPL-2.0-only** (`LICENSE`). See `THIRD_PARTY.md` for third-party acknowledgments. +- **Notice:** XCL is an independent compatibility layer and contains no proprietary code, SDK binaries, or keys. It operates exclusively on unpacked game files that you legally own. diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a4..602ba4c6d 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -15,6 +15,7 @@ use windows_sys::Win32::System::Diagnostics::Debug::{ }; use crate::hooks; +use crate::isa; use crate::modules; pub fn register_function_table(base: usize, rva: u32, size: u32) -> bool { @@ -149,9 +150,541 @@ pub fn install_crash_handler() { SetUnhandledExceptionFilter(Some(unhandled_filter)); install_invalid_parameter_handler(); windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(0, Some(cpp_exception_logger)); + windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(null_call_logger)); + if std::env::var_os("XCL_ISA_REDIRECT").is_some_and(|v| v == "0") { + REDIRECT.store(false, Ordering::Relaxed); + } + windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(unsupported_insn_handler)); + // `XCL_DUMP_THREADS_AT=40,90`: every thread's call stack that many seconds into the + // run – what a title that neither crashes nor moves on is waiting for + if let Ok(at) = std::env::var("XCL_DUMP_THREADS_AT") { + let mut times: Vec<u64> = at.split(',').filter_map(|t| t.trim().parse().ok()).collect(); + times.sort_unstable(); + let _ = std::thread::Builder::new().name("xcl-thread-dump".into()).spawn(move || { + let start = std::time::Instant::now(); + for t in times { + let due = std::time::Duration::from_secs(t); + if let Some(wait) = due.checked_sub(start.elapsed()) { + std::thread::sleep(wait); + } + crate::xlog_info!("thread stacks {t} s into the run (XCL_DUMP_THREADS_AT):"); + dump_threads(); + // `XCL_PEEK=140a210d81:1,14a210d60:8`: title globals by their address in the + // image as linked (hex) and size in bytes, read at the same moment + if let (Ok(list), Some(m)) = (std::env::var("XCL_PEEK"), modules::main_module()) { + for item in list.split(',') { + let mut it = item.trim().split(':'); + let (Some(a), n) = (it.next().and_then(|a| u64::from_str_radix(a, 16).ok()), it.next().and_then(|n| n.parse::<usize>().ok()).unwrap_or(8)) else { continue }; + let at = m.base + (a as usize).wrapping_sub(0x1_4000_0000); + if !m.contains(at) || !m.contains(at + n.min(8) - 1) { + continue; + } + let mut v = 0u64; + std::ptr::copy_nonoverlapping(at as *const u8, &mut v as *mut u64 as *mut u8, n.min(8)); + crate::xlog_info!("peek {a:#x} ({n} B) = {v:#x}"); + } + } + crate::log::flush(); + } + }); + } + // `XCL_PROBE_MOV=<image offset, hex>[,…]`: see `probe_mov` + if let Ok(list) = std::env::var("XCL_PROBE_MOV") { + let offsets: Vec<usize> = list.split(',').filter_map(|o| usize::from_str_radix(o.trim().trim_start_matches("0x"), 16).ok()).collect(); + if !offsets.is_empty() { + windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(probe_mov)); + let _ = std::thread::Builder::new().name("xcl-probe".into()).spawn(move || arm_probes(&offsets)); + } + } + // `XCL_DUMP_THREADS_ON=<file>`: the same each time that file is written (its time + // changes) – for a stall whose time is not known beforehand; what is in the file is + // logged with the dump + if let Ok(path) = std::env::var("XCL_DUMP_THREADS_ON") { + let _ = std::thread::Builder::new().name("xcl-thread-dump".into()).spawn(move || { + let modified = |p: &str| std::fs::metadata(p).and_then(|m| m.modified()).ok(); + let mut seen = modified(&path); + loop { + std::thread::sleep(std::time::Duration::from_millis(500)); + let now = modified(&path); + if now.is_some() && now != seen { + seen = now; + crate::xlog_info!("thread stacks {:.1} s into the run (XCL_DUMP_THREADS_ON: {}):", crate::log::uptime(), std::fs::read_to_string(&path).unwrap_or_default().trim()); + dump_threads(); + crate::log::flush(); + } + } + }); + } + // `XCL_CRASH_AT=<seconds>`: a deliberate access violation on a thread of XCL's at that + // time – to see what the title's crash handling does with it (its reporter's upload + // has to fail in `hle::netoff`, not at a name server) + if let Some(t) = std::env::var("XCL_CRASH_AT").ok().and_then(|v| v.trim().parse::<u64>().ok()) { + let _ = std::thread::Builder::new().name("xcl-crash-test".into()).spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(t)); + crate::xlog_warn!("XCL_CRASH_AT={t}: a deliberate access violation now (network {})", if crate::hle::netoff::enabled() { "off" } else { "ON" }); + crate::log::flush(); + std::ptr::write_volatile(8 as *mut u32, 0xDEAD); + }); + } + if std::env::var_os("XCL_TRACE_EXCEPTIONS").is_some() { + windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(first_chance_logger)); + } + } +} + +/// `XCL_TRACE_EXCEPTIONS=1`: the first 24 exceptions raised anywhere, as they are raised (code, +/// address, thread, parameters, the return addresses on the stack) – for a thread that ends +/// in nested exceptions, where the unhandled-exception report never comes. +unsafe extern "system" fn first_chance_logger(info: *mut EXCEPTION_POINTERS) -> i32 { + static N: AtomicUsize = AtomicUsize::new(0); + let rec = &*(*info).ExceptionRecord; + let ctx = &*(*info).ContextRecord; + let code = rec.ExceptionCode as u32; + // thread names, debug output, XCL's own write-watch arming, single steps + // … and illegal instructions: the ones XCL emulates would use up the budget, the others + // end in the unhandled-exception report + if matches!(code, 0x406D_1388 | 0x4001_0006 | 0x4001_000A | 0xE0C1_A7E1 | 0x8000_0004 | 0xC000_001D) { + return 0; + } + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 24 { + let params: Vec<String> = (0..(rec.NumberParameters as usize).min(4)).map(|k| format!("{:#x}", rec.ExceptionInformation[k])).collect(); + crate::xlog_warn!( + "exception #{n} {code:#010x} at {} on thread {}, parameters [{}], rsp {:#x}; on the stack: {}", + modules::describe_address(rec.ExceptionAddress as usize), + windows_sys::Win32::System::Threading::GetCurrentThreadId(), + params.join(", "), + ctx.Rsp, + stack_callers(ctx.Rsp as usize) + ); + crate::log::flush(); + } + 0 +} + +/// `CONTEXT` as the register file of `isa::exec`. +struct Regs(*mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT); + +impl Regs { + /// Rax..R15 lie in the record in the hardware's register order. + unsafe fn gpr_at(&self, i: u8) -> *mut u64 { + std::ptr::addr_of_mut!((*self.0).Rax).add(i as usize & 15) + } +} + +impl isa::Cpu for Regs { + fn gpr(&self, i: u8) -> u64 { + unsafe { *self.gpr_at(i) } + } + fn set_gpr(&mut self, i: u8, v: u64) { + unsafe { *self.gpr_at(i) = v } + } + fn rip(&self) -> u64 { + unsafe { (*self.0).Rip } + } + fn set_rip(&mut self, v: u64) { + unsafe { (*self.0).Rip = v } + } + fn flags(&self) -> u32 { + unsafe { (*self.0).EFlags } + } + fn set_flags(&mut self, v: u32) { + unsafe { (*self.0).EFlags = v } + } + fn xmm(&self, i: u8) -> (u64, u64) { + let x = unsafe { (*self.0).Anonymous.FltSave.XmmRegisters[i as usize & 15] }; + (x.Low, x.High as u64) + } + fn set_xmm(&mut self, i: u8, v: (u64, u64)) { + let x = unsafe { &mut (*self.0).Anonymous.FltSave.XmmRegisters[i as usize & 15] }; + (x.Low, x.High) = (v.0, v.1 as i64); + } + fn random(&mut self) -> Option<u64> { + #[link(name = "advapi32")] + extern "system" { + /// RtlGenRandom + fn SystemFunction036(buffer: *mut c_void, len: u32) -> u8; + } + let mut v = 0u64; + (unsafe { SystemFunction036(&mut v as *mut u64 as *mut c_void, 8) } != 0).then_some(v) + } +} + +/// Up to 16 code bytes at `ip`, not reading into a following page that is not mapped. +unsafe fn insn_bytes(ip: usize, buf: &mut [u8; 16]) -> &[u8] { + let in_page = 0x1000 - (ip & 0xFFF); + let n = if in_page >= 16 || crate::gpu::shader::readable(ip + in_page, 1) { 16 } else { in_page }; + std::ptr::copy_nonoverlapping(ip as *const u8, buf.as_mut_ptr(), n); + &buf[..n] +} + +/// Helpers that faulting sites are redirected to (`isa::thunk`): 64 KiB within reach of a +/// `call rel32`, allocated at the first use. The first half holds the ADX helpers, one slot +/// per operand combination, the second half one helper per INSERTQ/CLZERO site. +/// 0: not allocated yet, 1: no room near the code – every use is then emulated. +static HELPERS: AtomicUsize = AtomicUsize::new(0); +static HELPERS_USED: AtomicUsize = AtomicUsize::new(isa::ADX_SLOT * isa::ADX_SLOTS); +const HELPERS_SIZE: usize = 0x1_0000; +/// Serialises site patching; `XCL_ISA_REDIRECT=0` turns it off (every use then traps). +static PATCHING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static REDIRECT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// Free address space for helpers within reach of a `call rel32` from `near`: the nearest +/// `size` bytes (a multiple of 64 KiB) above it, else below; committed, readable, writable and +/// executable. 0: none. +pub(crate) unsafe fn alloc_near(near: usize, size: usize) -> usize { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_FREE, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + const REACH: usize = 0x7000_0000; + let query = |at: usize| -> Option<(usize, usize, bool)> { + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + (VirtualQuery(at as *const _, &mut mbi, std::mem::size_of::<MEMORY_BASIC_INFORMATION>()) != 0) + .then(|| (mbi.BaseAddress as usize, (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize), mbi.State == MEM_FREE)) + }; + let take = |p: usize| VirtualAlloc(p as *const _, size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; + let mut at = near & !0xFFFF; + for _ in 0..4096 { + let Some((_, end, free)) = query(at) else { break }; + if at - (near & !0xFFFF) > REACH { + break; + } + if free && at + size <= end { + let p = take(at); + if p != 0 { + return p; + } + } + let next = end.saturating_add(0xFFFF) & !0xFFFF; + if next <= at { + break; + } + at = next; + } + let mut at = near & !0xFFFF; + for _ in 0..4096 { + if at <= 0x2_0000 || (near & !0xFFFF) - at > REACH { + break; + } + let Some((base, _, free)) = query(at - 1) else { break }; + let p = at.saturating_sub(size); + if free && p >= base { + let p = take(p); + if p != 0 { + return p; + } + } + let next = base & !0xFFFF; + if next >= at { + break; + } + at = next; + } + 0 +} + +/// Writes `call helper` over the site at `site` (whose bytes were `code` when it trapped). +/// `true`: the site is to be run again – redirected now, or changed by another thread. +unsafe fn redirect(site: usize, code: &[u8], t: &isa::Thunk, helper: &[u8; isa::THUNK_MAX]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let n = t.site_len as usize; + let Some(code) = code.get(..n) else { return false }; + if !REDIRECT.load(Ordering::Relaxed) || !(5..=8).contains(&n) { + return false; + } + while PATCHING.swap(true, Ordering::Acquire) { + std::hint::spin_loop(); + } + let done = (|| { + if std::slice::from_raw_parts(site as *const u8, n) != code { + return true; + } + let mut pool = HELPERS.load(Ordering::Relaxed); + if pool == 0 { + pool = alloc_near(site, HELPERS_SIZE).max(1); + HELPERS.store(pool, Ordering::Relaxed); + } + let used = HELPERS_USED.load(Ordering::Relaxed); + let at = match t.slot { + _ if pool == 1 => return false, + Some(s) => pool + (s as usize % isa::ADX_SLOTS) * isa::ADX_SLOT, + None if used + isa::THUNK_MAX <= HELPERS_SIZE => pool + used, + None => return false, + }; + let Some(call) = isa::call_site(site as u64, t.site_len, at as u64) else { return false }; + // eight bytes in one store where the page allows it: no thread runs half a call + let span = if site & 0xFFF <= 0xFF8 { 8 } else { n }; + let mut old = 0u32; + if VirtualProtect(site as *const _, span, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return false; + } + // fresh memory is zero and no helper starts with a zero byte: an ADX slot is written once + if *(at as *const u8) == 0 { + std::ptr::copy_nonoverlapping(helper.as_ptr(), at as *mut u8, (t.len as usize).min(isa::THUNK_MAX)); + FlushInstructionCache(GetCurrentProcess(), at as *const _, isa::THUNK_MAX); + if t.slot.is_none() { + HELPERS_USED.store(used + isa::THUNK_MAX, Ordering::Relaxed); + } + } + if span == 8 { + let mut b = (site as *const [u8; 8]).read_unaligned(); + for (d, s) in b.iter_mut().zip(call).take(n) { + *d = s; + } + (site as *mut u64).write_unaligned(u64::from_le_bytes(b)); + } else { + std::ptr::copy_nonoverlapping(call.as_ptr(), site as *mut u8, n); + } + VirtualProtect(site as *const _, span, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), site as *const _, n); + true + })(); + PATCHING.store(false, Ordering::Release); + done +} + +/// One log line per instruction kind, and one when emulation by exception turns out to be +/// frequent: each such trap costs tens of microseconds. +unsafe fn note_insn(kind: usize, what: &str, redirected: bool, ip: usize) { + static SEEN: AtomicUsize = AtomicUsize::new(0); + static EMULATED: AtomicUsize = AtomicUsize::new(0); + if SEEN.fetch_or(1 << kind, Ordering::Relaxed) & (1 << kind) == 0 { + let how = if redirected { "each site calls a helper after its first use" } else { "emulated at each use" }; + crate::xlog_warn!("CPU: {what} is not available on this host – {how} (first at {})", modules::describe_address(ip)); + } + if !redirected { + let n = EMULATED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 10_000 || n == 1_000_000 { + crate::xlog_warn!("CPU: {n} instructions emulated by exception so far (now {what} at {}) – this is slow", modules::describe_address(ip)); + } } } +/// Instructions a translator does not run although every PC CPU of the console's generation +/// has them (Rosetta 2: ADX, RDSEED; SSE4a's MOVNTSS / MOVNTSD, which `insn` does not know), +/// raised as illegal instructions: emulated on the context (`isa`). And a faster path for sites +/// that run in loops, since a trap under a translator costs tens of microseconds: a site of +/// five bytes or more (ADCX / ADOX, INSERTQ with immediates, CLZERO with the instruction after +/// it in the title's zeroing loops) is redirected to a helper in host code and traps once. +/// Everything else – a lone CLZERO, CLWB, MONITORX / MWAITX, RDPRU, RDPID, EXTRQ, INSERTQ by +/// register – is left to `emulate_console_only`, which runs after this handler. +unsafe extern "system" fn unsupported_insn_handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let rec = &*(*info).ExceptionRecord; + let ctx = &mut *(*info).ContextRecord; + if rec.ExceptionCode as u32 != 0xC000_001D { + return 0; + } + let ip = ctx.Rip as *const u8; + let mut buf = [0u8; 16]; + let code = insn_bytes(ip as usize, &mut buf); + // already a call to a helper: another thread redirected the site while this one was on + // its way here with the old instruction. Run it again. + if let (Some(0xE8), Some(rel)) = (code.first(), code.get(1..5)) { + let to = (ip as usize + 5).wrapping_add(i32::from_le_bytes([rel[0], rel[1], rel[2], rel[3]]) as usize); + let pool = HELPERS.load(Ordering::Relaxed); + if pool > 1 && (pool..pool + HELPERS_SIZE).contains(&to) { + return -1; + } + } + // likewise a CLWB site that became NOPs: a NOP does not raise this exception + if code.first() == Some(&0x90) { + return -1; + } + let mut helper = [0u8; isa::THUNK_MAX]; + if let Some(t) = isa::thunk(code, &mut helper) { + // a site that takes a call is never emulated: with CLZERO the call also covers the + // next instruction, where an emulated thread would return to + if redirect(ip as usize, code, &t, &helper) { + note_insn(t.op as usize, t.op.name(), true, ip as usize); + return -1; + } + } + if let Some(insn) = isa::decode(code) { + if isa::exec(&insn, &mut Regs(ctx)) { + note_insn(8 + insn.op as usize, insn.op.name(), false, ip as usize); + return -1; + } + } + 0 +} + +/// A retail title's stall watchdog (GTA VI 1.0.2.1, exe+0x2215b91..): a thread walks 64 +/// heartbeat slots and, when one is older than its limit, calls a hook (which stores to +/// address 0 and returns) and then stores to address 0 itself – a deliberate crash that sends +/// a report. A host that is slow for a moment (shader compiles, other programs) trips it +/// although nothing hangs. Both stores are recognised by their bytes and the watchdog goes +/// on as if it had found no stale slot (`XCL_TITLE_WATCHDOG=1`: the crash stays). +unsafe fn title_watchdog_resume(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT) -> bool { + static KEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + static SEEN: AtomicUsize = AtomicUsize::new(0); + let rip = ctx.Rip as usize; + if rip < 0x1_0000 || *KEEP.get_or_init(|| std::env::var("XCL_TITLE_WATCHDOG").is_ok_and(|v| v.trim() == "1")) || !crate::gpu::shader::readable(rip, 16) { + return false; + } + let at = |a: usize, n: usize| std::slice::from_raw_parts(a as *const u8, n); + // mov dword ptr [0], imm32 + if at(rip, 7) != [0xC7, 0x04, 0x25, 0, 0, 0, 0] { + return false; + } + // the hook: `mov dword ptr [0], 0x2ef1e94b; ret` + if at(rip + 7, 5) == [0x4B, 0xE9, 0xF1, 0x2E, 0xC3] { + ctx.Rip += 11; + return true; + } + // the fatal error / GPU hang watchdog (`mov dword ptr [0], 0x4d8bd421`): deliberate crash + // tripped when world-load decompression or background compute pipeline builds take >30s + if at(rip + 7, 4) == [0x21, 0xD4, 0x8B, 0x4D] { + let n = SEEN.fetch_add(1, Ordering::Relaxed); + if n < 4 || n.is_power_of_two() { + crate::xlog_warn!("the title's fatal error / GPU hang watchdog triggered (#{n}: 0x4d8bd421 at rip={rip:#x}) – deliberate crash is skipped and title proceeds (XCL_TITLE_WATCHDOG=1 keeps the crash)"); + } + if at(rip + 11, 1) == [0xC3] { + ctx.Rip += 11; + } else if at(rip + 11, 1) == [0xCC] || at(rip + 11, 2) == [0x0F, 0x0B] { + let ret_addr = *(ctx.Rsp as *const usize); + if crate::gpu::shader::readable(ret_addr, 1) { + ctx.Rsp += 8; + ctx.Rip = ret_addr as u64; + } else { + ctx.Rip += 11; + } + } else { + ctx.Rip += 11; + } + return true; + } + // the watchdog: `mov r14, rsi; mov ebx, ebp` 0x29 bytes before, `mov r15, [rip+..]; mov r14, rsi; + // mov ebp, 0x1e` (the path taken when no slot is stale) 0x42 bytes before + if crate::gpu::shader::readable(rip.wrapping_sub(0x42), 0x42) + && at(rip + 7, 5) == [0, 0, 0, 0, 0xCC] + && at(rip - 0x29, 5) == [0x49, 0x89, 0xF6, 0x89, 0xEB] + && at(rip - 0x42, 3) == [0x4C, 0x8B, 0x3D] + && at(rip - 0x3B, 8) == [0x49, 0x89, 0xF6, 0xBD, 0x1E, 0, 0, 0] + { + let n = SEEN.fetch_add(1, Ordering::Relaxed); + if n < 4 || n.is_power_of_two() { + crate::xlog_warn!("the title's stall watchdog fired (#{n}: a thread's heartbeat is older than its limit) – its deliberate crash is skipped and the title goes on (XCL_TITLE_WATCHDOG=1 keeps the crash)"); + } + ctx.Rsi = ctx.R14; + ctx.Rip -= 0x42; + return true; + } + false +} + +/// A call or jump through a null (or near-null) pointer: logged with the return address and +/// the registers, since the faulting address itself says nothing about the caller. +/// the probes of `XCL_PROBE_MOV`: (address, the 7 bytes that were there) +static MOV_PROBES: Mutex<Vec<(usize, [u8; 7])>> = Mutex::new(Vec::new()); + +/// Waits for the title's image and puts a breakpoint on each `mov r64, [base + disp32]` named +/// by its offset in the image (REX.W 8B /r with mod 10 and no SIB; anything else is refused). +unsafe fn arm_probes(offsets: &[usize]) { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let m = loop { + match modules::main_module() { + Some(m) => break m, + None => std::thread::sleep(std::time::Duration::from_millis(20)), + } + }; + for &off in offsets { + let at = m.base + off; + if !m.contains(at) || !m.contains(at + 6) { + continue; + } + let was = (at as *const [u8; 7]).read_unaligned(); + if was[0] & 0xFA != 0x48 || was[1] != 0x8B || was[2] >> 6 != 2 || was[2] & 7 == 4 { + crate::xlog_warn!("XCL_PROBE_MOV: image +{off:#x} is not mov r64, [base + disp32] ({:02x?}) – not probed", was); + continue; + } + let mut old = 0u32; + if VirtualProtect(at as *const c_void, 1, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + continue; + } + MOV_PROBES.lock().unwrap().push((at, was)); + (at as *mut u8).write_volatile(0xCC); + VirtualProtect(at as *const c_void, 1, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), at as *const c_void, 1); + crate::xlog_info!("XCL_PROBE_MOV: image +{off:#x} ({:02x?}) is probed", was); + } +} + +/// `XCL_PROBE_MOV`: the breakpoint in place of a `mov r64, [base + disp32]` of the title. XCL +/// does the load and logs what was loaded and what memory it points to (the first 48 times, +/// then every 256th) – where a loop writes that the host cannot resume after a fault (under +/// Rosetta 2 a masked store into write-protected memory ends the process with no exception +/// for anyone to look at; the pointer is loaded right before such a loop). +unsafe extern "system" fn probe_mov(info: *mut EXCEPTION_POINTERS) -> i32 { + let rec = &*(*info).ExceptionRecord; + if rec.ExceptionCode as u32 != 0x8000_0003 { + return 0; + } + let site = rec.ExceptionAddress as usize; + let Some(was) = MOV_PROBES.lock().unwrap().iter().find(|p| p.0 == site).map(|p| p.1) else { return 0 }; + let ctx = &mut *(*info).ContextRecord; + let reg = |ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, k: u8| -> *mut u64 { + match k { + 0 => &mut ctx.Rax, 1 => &mut ctx.Rcx, 2 => &mut ctx.Rdx, 3 => &mut ctx.Rbx, 4 => &mut ctx.Rsp, 5 => &mut ctx.Rbp, 6 => &mut ctx.Rsi, 7 => &mut ctx.Rdi, + 8 => &mut ctx.R8, 9 => &mut ctx.R9, 10 => &mut ctx.R10, 11 => &mut ctx.R11, 12 => &mut ctx.R12, 13 => &mut ctx.R13, 14 => &mut ctx.R14, _ => &mut ctx.R15, + } + }; + let (rex, modrm) = (was[0], was[2]); + let base = *reg(ctx, (modrm & 7) | (rex & 1) << 3); + let ea = base.wrapping_add(i32::from_le_bytes([was[3], was[4], was[5], was[6]]) as i64 as u64) as usize; + if !crate::gpu::shader::readable(ea, 8) { + return 0; + } + let value = (ea as *const u64).read_unaligned(); + *reg(ctx, (modrm >> 3 & 7) | (rex >> 2 & 1) << 3) = value; + ctx.Rip = (site + 7) as u64; + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 48 || n % 256 == 0 { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION}; + let p = value as usize; + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let known = VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0; + let uma = crate::gpu::uma::get(); + let (mut buf, mut count, mut grain) = ([std::ptr::null_mut::<c_void>(); 4], 4usize, 0u32); + extern "system" { + fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; + } + let watched = GetWriteWatch(0, (p & !0xFFF) as *const c_void, 0x1000, buf.as_mut_ptr(), &mut count, &mut grain) == 0; + crate::xlog_info!( + "probe #{n} at {}: loaded {value:#x} from {ea:#x}; rbx={:#x} rcx={:#x} rdx={:#x} rsi={:#x} rdi={:#x}; that memory: {}unified memory window {:?}{}, {}write-watched{}, allocation {:#x} (protection {:#x}), region {:#x}+{:#x} state {:#x} protection {:#x} type {:#x}", + modules::describe_address(site), ctx.Rbx, ctx.Rcx, ctx.Rdx, ctx.Rsi, ctx.Rdi, + if known { "" } else { "unknown to Windows, " }, + uma.and_then(|u| u.window_of(p)), + if uma.is_some_and(|u| u.is_sparse(p)) { " (sparse)" } else { "" }, + if watched { "" } else { "not " }, + if crate::hle::kernelx::in_graphics_reservation(p) { " (a graphics reservation)" } else { "" }, + m.AllocationBase as usize, m.AllocationProtect, m.BaseAddress as usize, m.RegionSize, m.State, m.Protect, m.Type + ); + } + -1 // EXCEPTION_CONTINUE_EXECUTION +} + +unsafe extern "system" fn null_call_logger(info: *mut EXCEPTION_POINTERS) -> i32 { + static SEEN: AtomicUsize = AtomicUsize::new(0); + let rec = &*(*info).ExceptionRecord; + if rec.ExceptionCode as u32 == 0xC000_0005 && title_watchdog_resume(&mut *(*info).ContextRecord) { + return -1; // EXCEPTION_CONTINUE_EXECUTION + } + let ctx = &*(*info).ContextRecord; + if rec.ExceptionCode as u32 == 0xC000_0005 && ctx.Rip < 0x1_0000 && SEEN.fetch_add(1, Ordering::Relaxed) < 4 { + let ret = if crate::gpu::shader::readable(ctx.Rsp as usize, 8) { (ctx.Rsp as *const usize).read_unaligned() } else { 0 }; + crate::xlog_error!( + "call through a null pointer (rip {:#x}): return address {}, rax={:#x} rcx={:#x} rdx={:#x} r8={:#x} r9={:#x} r10={:#x} r11={:#x} rbx={:#x} rsi={:#x} rdi={:#x}; on the stack: {}", + ctx.Rip, modules::describe_address(ret), ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.Rbx, ctx.Rsi, ctx.Rdi, + stack_callers(ctx.Rsp as usize) + ); + crate::log::flush(); + } + 0 +} + /// MSVC's x64 `__security_check_cookie` (vcruntime): `cmp rcx, [__security_cookie]; jne fail; /// rol rcx, 16; test cx, 0xFFFF; jne restore; ret; restore: ror rcx, 16; fail: jmp /// __report_gsfailure` – fixed but for the cookie's address (`None`) and the jump. The @@ -1151,4 +1684,24 @@ mod tests { VirtualFree(buf as *mut _, 0, MEM_RELEASE); } } + + /// The title's fatal error / GPU hang watchdog at world load (`mov dword ptr [0], 0x4d8bd421`) + /// is resumed by skipping the crash, allowing long shader compilation to complete. + #[test] + fn title_watchdog_resumes_fatal_crash_at_world_load() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + unsafe { + let code = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; + assert!(code != 0); + // mov dword ptr [0], 0x4d8bd421; ret + let insn = [0xC7u8, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D, 0xC3]; + std::ptr::copy_nonoverlapping(insn.as_ptr(), code as *mut u8, insn.len()); + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + ctx.Rip = code as u64; + assert!(title_watchdog_resume(&mut ctx)); + assert_eq!(ctx.Rip as usize, code + 11); + VirtualFree(code as *mut _, 0, MEM_RELEASE); + } + } } + diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index d53751d1f..47f0e43b0 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -19,6 +19,8 @@ use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{DxcBuffer, IDxcBlob, IDxcCompiler3, IDxcResult, CLSID_DxcCompiler, DXC_CP_UTF8}; type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; +/// DxcCreateInstance2(IMalloc, clsid, iid, object) +type CreateInstance2 = unsafe extern "system" fn(*mut c_void, *const GUID, *const GUID, *mut *mut c_void) -> HRESULT; /// A dotted version, `10.0.26100.0` or `1.9.2602.17`, as four numbers (missing ones are 0). fn parse_version(s: &str) -> Option<[u32; 4]> { @@ -191,7 +193,8 @@ unsafe fn library(create: CreateInstance, class: &GUID, file: &Path) -> Library lib } -static LIB: OnceLock<Result<(PathBuf, usize), String>> = OnceLock::new(); +/// (folder, DxcCreateInstance, DxcCreateInstance2 or 0) +static LIB: OnceLock<Result<(PathBuf, usize, usize), String>> = OnceLock::new(); static TOOLCHAIN: OnceLock<Toolchain> = OnceLock::new(); /// The DXC in use; empty while none is loaded (asking does not load it). @@ -288,10 +291,10 @@ mod version_tests { /// Folder with dxcompiler.dll (+ dxil.dll) that will be used. pub fn location() -> Result<&'static Path, String> { - load().map(|(p, _)| p.as_path()) + load().map(|(p, ..)| p.as_path()) } -fn load() -> Result<&'static (PathBuf, usize), String> { +fn load() -> Result<&'static (PathBuf, usize, usize), String> { LIB.get_or_init(|| { use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; for dir in candidates() { @@ -318,7 +321,8 @@ fn load() -> Result<&'static (PathBuf, usize), String> { crate::xlog_warn!("DXC {} is older than {}.{}: {OUTDATED_COST}; {OUTDATED_FIX}", t.dxcompiler, RECOMMENDED.0, RECOMMENDED.1); } let _ = TOOLCHAIN.set(t); - return Ok((dir, f as usize)); + let f2 = GetProcAddress(h, b"DxcCreateInstance2\0".as_ptr()).map_or(0, |f| f as usize); + return Ok((dir, f as usize, f2)); } } } @@ -330,14 +334,127 @@ fn load() -> Result<&'static (PathBuf, usize), String> { /// The PC compiler's DxcCreateInstance (for titles that use the console's `dxcompiler_xs.dll`). pub fn create_instance() -> Option<usize> { - load().ok().map(|&(_, f)| f) + load().ok().map(|&(_, f, _)| f) } fn create_fn() -> Result<CreateInstance, String> { - let &(_, f) = load()?; + let &(_, f, _) = load()?; Ok(unsafe { std::mem::transmute::<usize, CreateInstance>(f) }) } +/// DXC's allocator for one compiler: a heap of its own. DXC allocates through the process +/// heap otherwise (CoTaskMemAlloc), under one lock: on Wine, 13–16 of 17 compile threads and +/// the title's threads creating pipelines stood in RtlEnterCriticalSection under +/// Rtl{Allocate,Free}Heap at any moment while GTA VI compiled its shaders – one or two +/// compiles ran. The heap is serialized (a blob may be released on another thread) and +/// lives for the process, like the compile thread it belongs to. +#[repr(C)] +struct HeapMalloc { + vtbl: *const MallocVtbl, + heap: usize, +} + +#[repr(C)] +struct MallocVtbl { + query_interface: unsafe extern "system" fn(*mut HeapMalloc, *const GUID, *mut *mut c_void) -> HRESULT, + add_ref: unsafe extern "system" fn(*mut HeapMalloc) -> u32, + release: unsafe extern "system" fn(*mut HeapMalloc) -> u32, + alloc: unsafe extern "system" fn(*mut HeapMalloc, usize) -> *mut c_void, + realloc: unsafe extern "system" fn(*mut HeapMalloc, *mut c_void, usize) -> *mut c_void, + free: unsafe extern "system" fn(*mut HeapMalloc, *mut c_void), + get_size: unsafe extern "system" fn(*mut HeapMalloc, *mut c_void) -> usize, + did_alloc: unsafe extern "system" fn(*mut HeapMalloc, *mut c_void) -> i32, + heap_minimize: unsafe extern "system" fn(*mut HeapMalloc), +} + +const IID_IUNKNOWN: GUID = GUID::from_u128(0x00000000_0000_0000_c000_000000000046); +const IID_IMALLOC: GUID = GUID::from_u128(0x00000002_0000_0000_c000_000000000046); + +static MALLOC_VTBL: MallocVtbl = { + use windows_sys::Win32::System::Memory::{HeapAlloc, HeapFree, HeapReAlloc, HeapSize}; + unsafe extern "system" fn query_interface(this: *mut HeapMalloc, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + if ppv.is_null() { + return HRESULT(0x80004003u32 as i32); // E_POINTER + } + if !riid.is_null() && (*riid == IID_IUNKNOWN || *riid == IID_IMALLOC) { + *ppv = this as *mut c_void; + return HRESULT(0); + } + *ppv = std::ptr::null_mut(); + HRESULT(0x80004002u32 as i32) // E_NOINTERFACE + } + // never freed: no count to keep + unsafe extern "system" fn add_ref(_this: *mut HeapMalloc) -> u32 { + 2 + } + unsafe extern "system" fn release(_this: *mut HeapMalloc) -> u32 { + 1 + } + unsafe extern "system" fn alloc(this: *mut HeapMalloc, n: usize) -> *mut c_void { + HeapAlloc((*this).heap as _, 0, n) + } + unsafe extern "system" fn realloc(this: *mut HeapMalloc, p: *mut c_void, n: usize) -> *mut c_void { + if p.is_null() { + return alloc(this, n); + } + if n == 0 { + free(this, p); + return std::ptr::null_mut(); + } + HeapReAlloc((*this).heap as _, 0, p, n) + } + unsafe extern "system" fn free(this: *mut HeapMalloc, p: *mut c_void) { + if !p.is_null() { + HeapFree((*this).heap as _, 0, p); + } + } + unsafe extern "system" fn get_size(this: *mut HeapMalloc, p: *mut c_void) -> usize { + if p.is_null() { + return usize::MAX; + } + HeapSize((*this).heap as _, 0, p) + } + // -1: cannot tell + unsafe extern "system" fn did_alloc(_this: *mut HeapMalloc, _p: *mut c_void) -> i32 { + -1 + } + unsafe extern "system" fn heap_minimize(_this: *mut HeapMalloc) {} + MallocVtbl { query_interface, add_ref, release, alloc, realloc, free, get_size, did_alloc, heap_minimize } +}; + +/// Whether each compiler gets a heap of its own: `XCL_DXC_HEAP=1` / `0`, else on Wine only +/// (Windows' process heap does not serialize small allocations, and a heap per compile +/// thread keeps what that thread freed). +fn own_heaps(setting: Option<&str>, wine: bool) -> bool { + match setting { + Some("0") => false, + Some("1") => true, + _ => wine, + } +} + +/// IMalloc for a new compiler (`HeapMalloc`), None when off or unavailable. +fn compiler_malloc() -> Option<*mut c_void> { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + static ON: OnceLock<bool> = OnceLock::new(); + let on = *ON.get_or_init(|| { + let wine = unsafe { GetProcAddress(GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8), c"wine_get_version".as_ptr() as *const u8).is_some() }; + let on = own_heaps(std::env::var("XCL_DXC_HEAP").ok().as_deref(), wine); + if on { + crate::xlog_info!("DXC: each compile thread allocates from a heap of its own (XCL_DXC_HEAP=0 for the process heap)"); + } + on + }); + if !on { + return None; + } + let heap = unsafe { windows_sys::Win32::System::Memory::HeapCreate(0, 0, 0) }; + if heap.is_null() { + return None; + } + Some(Box::into_raw(Box::new(HeapMalloc { vtbl: &MALLOC_VTBL, heap: heap as usize })) as *mut c_void) +} + thread_local! { static COMPILER: RefCell<Option<IDxcCompiler3>> = const { RefCell::new(None) }; } @@ -349,7 +466,11 @@ fn compiler() -> Result<IDxcCompiler3, String> { } let create = create_fn()?; let mut p = std::ptr::null_mut(); - let hr = unsafe { create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut p) }; + let create2 = load()?.2; + let hr = match (create2 != 0).then(compiler_malloc).flatten() { + Some(malloc) => unsafe { std::mem::transmute::<usize, CreateInstance2>(create2)(malloc, &CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut p) }, + None => unsafe { create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut p) }, + }; if hr.is_err() || p.is_null() { return Err(format!("DxcCreateInstance: {hr:?}")); } @@ -428,6 +549,16 @@ pub fn wait_for_memory() -> MemorySlot { if WORKING.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { return MemorySlot; } + // the first times a compile is held back: what the host reports (Wine's figures for + // commit are its own) + static HELD: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = HELD.fetch_add(1, Ordering::Relaxed); + if n < 4 || n % 2000 == 0 { + crate::xlog_warn!( + "DXC memory gate: compile held back (#{n}): {} MB commit available of {} MB, {} MB physical available, {} compile(s) running, {} MB wanted", + m.ullAvailPageFile >> 20, m.ullTotalPageFile >> 20, m.ullAvailPhys >> 20, WORKING.load(Ordering::Acquire), need >> 20 + ); + } std::thread::sleep(std::time::Duration::from_millis(50)); } } @@ -547,7 +678,8 @@ fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &st h } -fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { +/// Key of a program's DXIL in the disk cache (the file is `<key>.dxil`). +pub(super) fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { cache_key_for_toolchain(src, entry, profile, toolchain_identity()) } @@ -771,7 +903,48 @@ fn compile_cached_in_observed<F>( where F: FnOnce() -> Result<Vec<u8>, String>, { - let key = cache_key(src, entry, profile); + compile_cached_keyed(dir, cache_key(src, entry, profile), src, entry, profile, counters, compile_one) +} + +/// `compile_cached_in` for a caller that has `cache_key(src, entry, profile)` already (the +/// key hashes the whole source). +pub(super) fn compile_cached_in_keyed(dir: &Path, key: u64, src: &str, entry: &str, profile: &str) -> Result<(Vec<u8>, bool), String> { + compile_cached_keyed(dir, key, src, entry, profile, cache_counters(), || compile(src, entry, profile, &[])) +} + +/// The cached DXIL with this key, without its source: Ok(None) when it is not there (the +/// caller needs the source to compile it); inside `cached_only` that is a miss (Err), as in +/// `compile_cached`. Outside, a compile of it that is running is waited for. +pub(super) fn cached_by_key_in(dir: &Path, key: u64) -> Result<Option<Vec<u8>>, String> { + cached_by_key(dir, key, cache_counters()) +} + +fn cached_by_key(dir: &Path, key: u64, counters: &CacheCounters) -> Result<Option<Vec<u8>>, String> { + let dir = normalized_cache_dir(dir); + let file = dir.join(format!("{key:016x}.dxil")); + if let Some(b) = cached_file(&file) { + counters.hits.fetch_add(1, Ordering::Relaxed); + return Ok(Some(b)); + } + if CACHED_ONLY.with(|c| c.get()) { + counters.deferred_misses.fetch_add(1, Ordering::Relaxed); + MISSED.with(|m| m.set(true)); + return Err("DXIL not compiled yet".into()); + } + let flight = cache_flight((dir, key)); + let _guard = flight.lock().unwrap_or_else(|e| e.into_inner()); + let found = cached_file(&file); + if found.is_some() { + counters.misses.fetch_add(1, Ordering::Relaxed); + counters.coalesced_hits.fetch_add(1, Ordering::Relaxed); + } + Ok(found) +} + +fn compile_cached_keyed<F>(dir: &Path, key: u64, src: &str, entry: &str, profile: &str, counters: &CacheCounters, compile_one: F) -> Result<(Vec<u8>, bool), String> +where + F: FnOnce() -> Result<Vec<u8>, String>, +{ let dir = normalized_cache_dir(dir); let file = dir.join(format!("{key:016x}.dxil")); if let Some(b) = cached_file(&file) { @@ -889,12 +1062,59 @@ pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec<u8>, } #[cfg(test)] -mod cache_tests { +mod heap_tests { + use super::*; + + #[test] + fn compilers_get_their_own_heap_on_wine_unless_told_otherwise() { + assert!(own_heaps(None, true)); + assert!(!own_heaps(None, false)); + assert!(own_heaps(Some("1"), false)); + assert!(!own_heaps(Some("0"), true)); + assert!(own_heaps(Some("yes"), true) && !own_heaps(Some("yes"), false)); + } + + #[test] + fn heap_malloc_is_an_imalloc() { + unsafe { + let heap = windows_sys::Win32::System::Memory::HeapCreate(0, 0, 0); + assert!(!heap.is_null()); + let mut m = HeapMalloc { vtbl: &MALLOC_VTBL, heap: heap as usize }; + let this = &mut m as *mut HeapMalloc; + let v = &*m.vtbl; + let mut out = std::ptr::null_mut(); + assert_eq!((v.query_interface)(this, &IID_IMALLOC, &mut out), HRESULT(0)); + assert_eq!(out, this as *mut c_void); + assert_eq!((v.query_interface)(this, &IID_IUNKNOWN, &mut out), HRESULT(0)); + assert!((v.query_interface)(this, &IDxcCompiler3::IID, &mut out).is_err() && out.is_null()); + let p = (v.alloc)(this, 100) as *mut u8; + assert!(!p.is_null() && (v.get_size)(this, p as *mut c_void) >= 100); + std::ptr::write_bytes(p, 0xAB, 100); + // grows with its contents; a null block is an allocation, size 0 a free + let q = (v.realloc)(this, p as *mut c_void, 1 << 20) as *mut u8; + assert!(!q.is_null() && std::slice::from_raw_parts(q, 100).iter().all(|&b| b == 0xAB)); + assert!((v.realloc)(this, q as *mut c_void, 0).is_null()); + let r = (v.realloc)(this, std::ptr::null_mut(), 16); + assert!(!r.is_null()); + (v.free)(this, r); + (v.free)(this, std::ptr::null_mut()); + assert_eq!((v.get_size)(this, std::ptr::null_mut()), usize::MAX); + // blocks of another thread's compiler are freed where they came from + let s = (v.alloc)(this, 64) as usize; + let at = this as usize; + std::thread::spawn(move || ((*(*(at as *mut HeapMalloc)).vtbl).free)(at as *mut HeapMalloc, s as *mut c_void)).join().unwrap(); + assert_ne!(windows_sys::Win32::System::Memory::HeapDestroy(heap), 0); + } + } +} + +#[cfg(test)] +pub(super) mod cache_tests { use super::*; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; - fn synthetic_dxil(marker: u8) -> Vec<u8> { + pub(in crate::gpu::recomp) fn synthetic_dxil(marker: u8) -> Vec<u8> { let mut b = vec![0u8; 68]; b[..4].copy_from_slice(b"DXBC"); b[20..24].copy_from_slice(&1u32.to_le_bytes()); @@ -908,6 +1128,46 @@ mod cache_tests { b } + #[test] + fn dxil_by_key_needs_no_source_and_waits_for_a_running_compile() { + let dir = std::env::temp_dir().join(format!("xcl-dxil-by-key-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let counters = CacheCounters::default(); + let src = "by key"; + let key = cache_key(src, "main", "cs_6_6"); + // not compiled: a miss inside cached_only, "translate and compile" outside + let (r, missed) = cached_only(|| cached_by_key(&dir, key, &counters)); + assert!(r.is_err() && missed); + assert_eq!(cached_by_key(&dir, key, &counters), Ok(None)); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + std::thread::scope(|scope| { + let (dir, counters) = (&dir, &counters); + let compiling = scope.spawn(move || { + compile_cached_keyed(dir, key, src, "main", "cs_6_6", counters, || { + started_tx.send(()).unwrap(); + release_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + Ok(synthetic_dxil(3)) + }) + }); + started_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + // a probe does not wait for it + let (r, missed) = cached_only(|| cached_by_key(dir, key, counters)); + assert!(r.is_err() && missed); + let waiting = scope.spawn(move || cached_by_key(dir, key, counters)); + std::thread::sleep(Duration::from_millis(50)); + assert!(!waiting.is_finished()); + release_tx.send(()).unwrap(); + assert_eq!(compiling.join().unwrap().unwrap(), (synthetic_dxil(3), false)); + assert_eq!(waiting.join().unwrap(), Ok(Some(synthetic_dxil(3)))); + }); + assert_eq!(cached_by_key(&dir, key, &counters), Ok(Some(synthetic_dxil(3)))); + let stats = counters.snapshot(); + assert_eq!((stats.compilations, stats.deferred_misses, stats.coalesced_hits, stats.hits), (1, 2, 1, 1)); + assert_eq!(stats.misses, 1 + stats.coalesced_hits); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn cache_statistics_separate_deferred_misses_failures_and_hits() { let dir = std::env::temp_dir().join(format!("xcl-dxil-stats-{}", std::process::id())); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 3fa375577..b25639040 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -5,8 +5,9 @@ //! directly indexed descriptor heaps (images / samplers). Mapping the title's root arguments //! onto that ABI at draw time is the next step (needs the console runtime's user-data layout). -use std::collections::VecDeque; -use std::path::PathBuf; +use std::collections::{HashMap, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use windows::Win32::Graphics::Direct3D::ID3DBlob; @@ -15,7 +16,7 @@ use windows::Win32::Graphics::Direct3D12::*; use super::{dxc, interface, translate, Mode, Options}; use crate::gpu::xbox; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Stage { Vertex, Pixel, @@ -99,6 +100,8 @@ pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<C /// (`wave32_only_for_device`): a wave64 compute program gets the split form /// (`Options::split_wave64`) instead of `[WaveSize(64)]`, which such a driver rejects. /// Finished shaders are also kept in memory (`ShaderCache`): pipelines share their shaders. +/// A shader whose DXIL is not compiled yet is not translated for each of its pipelines +/// (`Translated`). pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<Compiled, String> { console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows()) } @@ -106,12 +109,20 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<Compiled, String> { - let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); + console_to_dxil_shared(blob, stage, sampler_base, split_wave64, windows).map(|shader| shader.as_ref().clone()) +} + +/// `console_to_dxil_in` without a copy of the DXIL: the pipelines of a shader (a retail +/// game: tens per pixel shader, clones with other fixed-function state) build from the one +/// in `ShaderCache`. +pub fn console_to_dxil_shared(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<Arc<Compiled>, String> { if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { - return compile_one(); + return compile_console_shader(blob, stage, sampler_base, windows, split_wave64).map(Arc::new); } static CACHE: OnceLock<Mutex<ShaderCache>> = OnceLock::new(); + static TRANSLATED: OnceLock<Mutex<HashMap<TranslatedKey, Arc<Translated>>>> = OnceLock::new(); let cache = CACHE.get_or_init(|| Mutex::new(ShaderCache::new(64 << 20))); + let translated = TRANSLATED.get_or_init(Default::default); let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), stage, @@ -120,8 +131,12 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa split_wave64, cache_dir: dxc::cache_dir(), }; - let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); - cached_shader(cache, key, blob, from_disk).map(|shader| shader.as_ref().clone()) + let known = TranslatedKey { hash: key.hash, len: blob.len(), stage, sampler_base, windows, split_wave64 }; + let dir = key.cache_dir.clone(); + // without the debug switches (`cache_allowed`) this is `compile_console_shader` + let compile_one = || translated_dxil(translated, known, &dir, || console_translation(blob, stage, sampler_base, windows, split_wave64).map(|(t, profile)| (t.hlsl, profile, t.static_samplers))); + let from_disk = || translated::cached(&dir, blob, stage, sampler_base, windows, split_wave64, compile_one); + cached_shader(cache, key, blob, from_disk) } /// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run @@ -130,7 +145,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa /// ~2 800 programs (611 of more than 10 000 instructions) took its loading threads 0.1 - 0.3 s /// each at every start. Keyed by two hashes and the length of the bytes, the stage and the /// translation parameters; translator sources and the DXC toolchain identify compatible builds. -/// `XCL_TRANSLATED_CACHE=0` turns it off. +/// `XCL_TRANSLATED_CACHE=0` turns it off; `XCL_TRANSLATED_IDENT=<hex>` stands for the hash. mod translated { use super::{Compiled, Stage}; use std::path::{Path, PathBuf}; @@ -157,6 +172,13 @@ mod translated { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { return 0; } + // `XCL_TRANSLATED_IDENT=<hex>`: that identity instead of the binary's hash – builds + // that differ outside the translator share their translations (a developer's + // switch: a new build's first run otherwise translates every program again, minutes + // of a retail game's start on a slow host) + if let Some(n) = std::env::var("XCL_TRANSLATED_IDENT").ok().and_then(|v| u64::from_str_radix(v.trim().trim_start_matches("0x"), 16).ok()) { + return n | 1; + } identity_for(env!("XCL_TRANSLATOR_SOURCE_ID"), super::dxc::toolchain_identity()) }) } @@ -258,6 +280,61 @@ mod translated { // Changes here, in `fspx`, or in `console_translation` that alter the cached result must bump // `TRANSLATION_GLUE_REVISION` in build.rs; cache serialization changes need not bump it. + +/// What the translation of a console shader comes to: the key of its DXIL in the disk cache +/// (a hash of the HLSL) and its static samplers, kept for every shader translated in this +/// run (a few dozen bytes each). `translated` has a shader only once its DXIL is compiled: +/// until then every pipeline with it translated it again just to find that key, in the +/// title's call (the cached-only attempt) and once more on its worker – a retail game makes +/// tens of pipelines per pixel shader (clones with other fixed-function state). +struct Translated { + dxil_key: u64, + samplers: Vec<StaticSampler>, +} + +/// What a translation depends on. No copy of the blob to compare with: its length instead. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +struct TranslatedKey { + hash: u64, + len: usize, + stage: Stage, + sampler_base: u32, + windows: u32, + split_wave64: bool, +} + +/// DXIL of a console shader through `known`: a shader translated before comes from the disk +/// cache by its key (inside `dxc::cached_only`: or misses, at once); `translate` (HLSL, +/// profile, static samplers) runs for a new one, and for one whose DXIL nobody compiled. +fn translated_dxil( + known: &Mutex<HashMap<TranslatedKey, Arc<Translated>>>, + key: TranslatedKey, + dir: &Path, + translate: impl FnOnce() -> Result<(String, &'static str, Vec<StaticSampler>), String>, +) -> Result<Compiled, String> { + let before = known.lock().unwrap().get(&key).cloned(); + if let Some(t) = &before { + static SKIPPED: AtomicU64 = AtomicU64::new(0); + let n = SKIPPED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n % 1000 == 0 { + crate::xlog_info!("[SHADER] translation of a console shader seen before skipped (#{n})"); + } + if let Some(dxil) = dxc::cached_by_key_in(dir, t.dxil_key)? { + return Ok(Compiled { dxil, samplers: t.samplers.clone() }); + } + } + let (hlsl, profile, samplers) = translate()?; + let dxil_key = match before { + Some(t) => t.dxil_key, + None => { + let dxil_key = dxc::cache_key(&hlsl, "main", profile); + known.lock().unwrap().insert(key, Arc::new(Translated { dxil_key, samplers: samplers.clone() })); + dxil_key + } + }; + let dxil = dxc::compile_cached_in_keyed(dir, dxil_key, &hlsl, "main", profile)?.0; + Ok(Compiled { dxil, samplers }) +} fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> { let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; if let Some([r, g, b]) = (stage == Stage::Pixel).then(|| debug_color(blob)).flatten() { @@ -867,6 +944,52 @@ mod shader_cache_tests { assert_eq!(t.dxil[0], 9); } + #[test] + fn known_translation_is_not_repeated() { + let dir = std::env::temp_dir().join(format!("xcl-known-translation-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let known = Mutex::new(HashMap::new()); + let key = TranslatedKey { hash: 1, len: 100, stage: Stage::Pixel, sampler_base: 2, windows: 1, split_wave64: false }; + let samplers: Vec<StaticSampler> = vec![([1, 2, 3, 4], true)]; + let translate = || Ok(("known translation".to_string(), "ps_6_6", vec![([1, 2, 3, 4], true)])); + // first sight, DXIL not compiled: translated to learn the key, a miss for the probe + let (r, missed) = dxc::cached_only(|| translated_dxil(&known, key, &dir, translate)); + assert!(r.is_err() && missed); + let dxil_key = known.lock().unwrap()[&key].dxil_key; + assert_eq!(dxil_key, dxc::cache_key("known translation", "main", "ps_6_6")); + // the next pipelines with it miss without translating + for _ in 0..3 { + let (r, missed) = dxc::cached_only(|| translated_dxil(&known, key, &dir, || panic!("translated again"))); + assert!(r.is_err() && missed); + } + // compiled meanwhile (a worker): from the disk cache, still no translation + let dxil = dxc::cache_tests::synthetic_dxil(5); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(format!("{dxil_key:016x}.dxil")), &dxil).unwrap(); + for cached_only in [true, false] { + let get = || translated_dxil(&known, key, &dir, || panic!("translated again")); + let c = if cached_only { dxc::cached_only(get).0 } else { get() }.unwrap(); + assert_eq!((c.dxil, c.samplers), (dxil.clone(), samplers.clone())); + } + // another shader, the same shader for another slot: their own translations + for other in [TranslatedKey { hash: 2, ..key }, TranslatedKey { len: 101, ..key }, TranslatedKey { stage: Stage::Vertex, ..key }, TranslatedKey { sampler_base: 0, ..key }, TranslatedKey { windows: 2, ..key }, TranslatedKey { split_wave64: true, ..key }] { + let mut calls = 0; + let (r, missed) = dxc::cached_only(|| { + translated_dxil(&known, other, &dir, || { + calls += 1; + Ok((format!("other translation {}", known.lock().unwrap().len()), "ps_6_6", Vec::new())) + }) + }); + assert!(r.is_err() && missed && calls == 1); + } + assert_eq!(known.lock().unwrap().len(), 7); + // a failed translation is not remembered + let failed = TranslatedKey { hash: 3, ..key }; + assert!(translated_dxil(&known, failed, &dir, || Err("incomplete translation".into())).is_err()); + assert!(!known.lock().unwrap().contains_key(&failed)); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn shader_cache_evicts_old_entries_and_skips_oversized_shaders() { let t = Arc::new(compiled(1)); diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index c9748ab79..76e080ec2 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1231,7 +1231,8 @@ unsafe impl Sync for Arena {} /// `run` with a unified memory region as `mem` (u2): the GPU works on the process memory -/// itself, no copies. +/// itself, no copies – or, where D3D12 has no heaps over process memory, on copies of the +/// windows that are written back after the dispatch. pub fn run_in_arena(dxil: &[u8], state: &KernelState, arena: &crate::gpu::uma::Uma) -> Result<KernelResult, String> { let arena = Arena { windows: (0..arena.windows()).map(|k| (arena.window(k).0 as *mut u8, arena.window(k).1)).collect() }; let r = run_in_region(dxil, state, &arena); @@ -1257,22 +1258,39 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern let dev = &gpu.dev; let dev3: ID3D12Device3 = dev.cast().map_err(e)?; let mut bufs: Vec<ID3D12Resource> = Vec::new(); + // a D3D12 without heaps over process memory (D3DMetal: E_NOTIMPL): each window is a + // buffer in video memory, filled from the window before the dispatch and copied back + // after it – (upload, readback) per window + let mut copies: Vec<(ID3D12Resource, ID3D12Resource)> = Vec::new(); for &(base, size) in &arena.windows { - let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void).map_err(|x| format!("OpenExistingHeapFromAddress: {x}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size as u64, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() - }; - let mut mem_buf: Option<ID3D12Resource> = None; - dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?; - bufs.push(mem_buf.ok_or("arena")?); + let heap: ID3D12Heap = match dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void) { + Ok(h) => h, + Err(x) if x.code() == windows::Win32::Foundation::E_NOTIMPL => { + let up = buffer(dev, size as u64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).map_err(e)?; + std::ptr::copy_nonoverlapping(base, p as *mut u8, size); + up.Unmap(0, None); + bufs.push(buffer(dev, size as u64, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?); + copies.push((up, buffer(dev, size as u64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?)); + continue; + } + Err(x) => return Err(format!("OpenExistingHeapFromAddress: {x}")), + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, + ..Default::default() + }; + let mut mem_buf: Option<ID3D12Resource> = None; + dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?; + bufs.push(mem_buf.ok_or("arena")?); } let mem_buf = bufs[0].clone(); let pso: ID3D12PipelineState = dev @@ -1295,13 +1313,18 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(e)?; list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes); + // (a buffer in COMMON takes the copy as it is) + for (b, (up, _)) in bufs.iter().zip(&copies) { + list.CopyBufferRegion(b, 0, up, 0, b.GetDesc().Width); + } + let filled = if copies.is_empty() { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_COPY_DEST }; list.ResourceBarrier(&[ transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(&mem_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&mem_buf, filled, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), ]); for b in &bufs[1..] { - list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + list.ResourceBarrier(&[transition(b, filled, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); } list.SetComputeRootSignature(&gpu.rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); @@ -1310,18 +1333,28 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern list.SetComputeRootUnorderedAccessView(2 + k as u32, bufs.get(k).unwrap_or(&mem_buf).GetGPUVirtualAddress()); } list.Dispatch(1, 1, 1); + let after = if copies.is_empty() { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_COPY_SOURCE }; list.ResourceBarrier(&[ transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), + transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, after), ]); for b in &bufs[1..] { - list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)]); + list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, after)]); } list.CopyBufferRegion(&readback, 0, &res_buf, 0, res_bytes); + for (b, (_, back)) in bufs.iter().zip(&copies) { + list.CopyBufferRegion(back, 0, b, 0, b.GetDesc().Width); + } list.Close().map_err(e)?; gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]); gpu.value += 1; wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "arena dispatch")?; + for (&(base, size), (_, back)) in arena.windows.iter().zip(&copies) { + let mut q = std::ptr::null_mut(); + back.Map(0, None, Some(&mut q)).map_err(e)?; + std::ptr::copy_nonoverlapping(q as *const u8, base, size); + back.Unmap(0, None); + } let mut q = std::ptr::null_mut(); readback.Map(0, None, Some(&mut q)).map_err(e)?; let raw = std::slice::from_raw_parts(q as *const u32, KERNEL_RES_DWORDS).to_vec(); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 4e032b68d..650e7b0c7 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3497,6 +3497,13 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { // Submit 1: reads slot 0 -> in_a (sparse VRAM) + arg_table constant 77 (Window 3) record_and_run(1, true); + // a window the GPU has a copy of: what the shader stored comes back on request + let gpu_wrote = || { + if u.shadowed() { + crate::hle::d3d12x::sparse::readback_now(out_buf, 256); + } + }; + gpu_wrote(); for l in 0..64usize { let got = *((out_buf + 4 * l) as *const u32); assert_eq!(got, 1000 + l as u32 + 77, "submit 1 lane {l} mismatch"); @@ -3507,12 +3514,21 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { *((in_b + 4 * 3) as *mut u32) = 9999; crate::hle::d3d12x::console_heap::write(&slot0, &vsharp(in_b)); record_and_run(2, false); + gpu_wrote(); for l in 0..64usize { let expected = if l == 3 { 9999 + 13 } else { 5000 + 2 * l as u32 + 13 }; let got = *((out_buf + 4 * l) as *const u32); assert_eq!(got, expected, "submit 2 (mutated sparse descriptor + XMem buffer) lane {l} mismatch"); } + // Submits 3..: a constant the CPU rewrites before every submit reaches the shader each time + for n in 0..40u32 { + *(arg_table as *mut u32) = 100 + n; + record_and_run(3 + n as u64, false); + gpu_wrote(); + assert_eq!(*(out_buf as *const u32), 5000 + 100 + n, "submit {} (constant rewritten in window 3)", 3 + n); + } + // Clean up crate::hle::d3d12x::console_heap::unregister(heap_obj); crate::hle::kernelx::XMemFreeDefault(in_a as *mut _, gfx_attrs); @@ -3521,6 +3537,56 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { } } +/// A retail game's streaming pool, with its numbers: 99,776 physical pages (6.09 GiB) taken at +/// once, a reservation of 64 KiB pages for them made afterwards, and each page mapped into it by +/// XMemMapPhysicalPagesScatter. Its watchdog allows the start a few seconds: with a tile +/// mapping per page on the GPU this took longer. Run alone (it takes half the windows); +/// `XCL_TEST_HOMES_FIRST=1`: the pages are mapped at their home before. +#[test] +#[ignore] +fn gpu_sparse_vram_pool_of_physical_pages_is_mapped_in_seconds() { + use crate::hle::kernelx::*; + if !gpu_ready() { + return; + } + crate::hle::d3d12x::real::init().expect("real D3D12.X backend"); + let u = crate::gpu::uma::get().expect("UMA"); + unsafe { + let t0 = std::time::Instant::now(); + // (`XCL_TEST_POOL_PAGES`: fewer, for a quick run) + let mut n = std::env::var("XCL_TEST_POOL_PAGES").ok().and_then(|v| v.parse().ok()).unwrap_or(99_776usize); + let mut pages = vec![0u64; n]; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let t_alloc = t0.elapsed(); + if std::env::var("XCL_TEST_HOMES_FIRST").is_ok() { + assert!(!XMemMapPhysicalPages(std::ptr::null_mut(), n, pages.as_mut_ptr()).is_null()); + } + let t_home = t0.elapsed(); + let pool = VirtualAlloc(std::ptr::null(), 0x1_85c0_0000, 0x2040_2000, 0x2004) as usize; + assert!(pool != 0); + let at: Vec<*mut std::ffi::c_void> = (0..n).map(|i| (pool + i * PHYS_PAGE_SIZE) as *mut std::ffi::c_void).collect(); + let t1 = std::time::Instant::now(); + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), n, pages.as_mut_ptr()), 1); + let t_map = t1.elapsed(); + *(pool as *mut u32) = 0x600D_0001; + *((pool + (n - 1) * PHYS_PAGE_SIZE) as *mut u32) = 0x600D_0002; + let mut got = [0u8; 4]; + assert!(read_physical_pages(&[pages[n - 1] as usize], 0, &mut got) && u32::from_le_bytes(got) == 0x600D_0002); + println!( + "pool of {n} pages: allocated in {:.2} s, at home {:.2} s, mapped into the reservation at {pool:#x} (sparse window: {}) in {:.2} s", + t_alloc.as_secs_f64(), + (t_home - t_alloc).as_secs_f64(), + u.is_sparse(pool), + t_map.as_secs_f64() + ); + let t2 = std::time::Instant::now(); + assert_eq!(XMemFreePhysicalPages(n, pages.as_mut_ptr()), 1); + assert_eq!(VirtualFree(pool as *mut _, 0, 0x8000), 1); + println!("freed in {:.2} s", t2.elapsed().as_secs_f64()); + assert!(t_map.as_secs_f64() < 5.0, "mapping the pool took {:.1} s", t_map.as_secs_f64()); + } +} + /// Experiment: does OpenExistingHeapFromAddress accept a reservation with only part committed? #[test] #[ignore] diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 2eb90fb85..08342e2e9 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -201,8 +201,13 @@ fn dump_dir() -> PathBuf { crate::state::data_dir().join("shaders") } +/// Set when the host's D3D12 is native code outside any PE module (Apple's D3DMetal under +/// Wine): its objects and blobs live in memory VirtualQuery reports as free. +pub static NATIVE_HOST_MEMORY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// Is `[p, p+len)` committed, readable memory? (Game-provided pointers may be garbage -/// when our guess of a console struct layout is wrong.) +/// when our guess of a console struct layout is wrong.) On a native host, memory Windows +/// does not know is probed by reading it under an exception guard. pub fn readable(p: usize, len: usize) -> bool { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_GUARD, PAGE_NOACCESS}; if p == 0 || len == 0 || len > 256 << 20 { @@ -222,6 +227,9 @@ pub fn readable(p: usize, len: usize) -> bool { while cur < end { let mut mbi: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let n = unsafe { VirtualQuery(cur as *const _, &mut mbi, std::mem::size_of::<MEMORY_BASIC_INFORMATION>()) }; + if (n == 0 || mbi.State == windows_sys::Win32::System::Memory::MEM_FREE) && NATIVE_HOST_MEMORY.load(std::sync::atomic::Ordering::Relaxed) { + return unsafe { windows_sys::Win32::System::Memory::IsBadReadPtr(cur as *const _, end - cur) } == 0; + } if n == 0 || mbi.State != MEM_COMMIT || mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD) != 0 || mbi.Protect == 0 { return false; } @@ -267,23 +275,29 @@ pub fn capture(stage: &str, ptr: usize, len: usize) { if ptr == 0 && len == 0 { return; // unused stage } + // hashed before the lock, copied only when new: every stage of every pipeline comes + // through here, from all of the title's pipeline threads (a retail game: ~70 000 + // pipelines of ~4 700 shaders) + let h = readable(ptr, len).then(|| fnv64(unsafe { std::slice::from_raw_parts(ptr as *const u8, len) })); let mut g = STATE.lock().unwrap(); let st = g.get_or_insert_with(|| State { seen: HashSet::new(), stats: ShaderStats::default(), insts: xbox::InstStats::default() }); st.stats.submitted += 1; - if !readable(ptr, len) { + let Some(h) = h else { st.stats.rejected_pointers += 1; if st.stats.rejected_pointers <= 5 { crate::xlog_warn!("[SHADER] {stage}: invalid pointer/size ({ptr:#x}, {len}) – different struct layout on the console?"); } return; + }; + match st.stats.by_stage.get_mut(stage) { + Some(n) => *n += 1, + None => drop(st.stats.by_stage.insert(stage.to_string(), 1)), } - let blob = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) }.to_vec(); - let h = fnv64(&blob); - *st.stats.by_stage.entry(stage.to_string()).or_default() += 1; if !st.seen.insert(h) { return; } st.stats.unique += 1; + let blob = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) }.to_vec(); let (kind, parts) = classify(&blob); *st.stats.by_kind.entry(kind.label().to_string()).or_default() += 1; for p in parts.iter().filter(|p| !KNOWN_PARTS.contains(&p.fourcc.as_str())) { @@ -502,6 +516,14 @@ mod tests { } std::ptr::write_volatile(page(0) as *mut u8, 1); std::ptr::write_volatile(page(1) as *mut u8, 1); + // (a host whose kernel does not say which pages are in the working set – Wine on + // macOS – answers everything by the region walk: nothing to test of the shortcut) + if !resident_and_readable(page(0), page(2)) && crate::util::mac_host() { + assert!(readable(page(0), 2 << 12) && !readable(page(1), 2 << 12)); + println!("SKIPPED readable_answers_from_the_working_set_without_touching_pages: this host reports no working set"); + VirtualFree(base as *mut _, 0, MEM_RELEASE); + return; + } // written pages: answered from the working set assert!(resident_and_readable(page(0), page(2))); assert!(readable(page(0), 2 << 12)); diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 82eac9e53..173e21b0b 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -13,6 +13,7 @@ //! 4095 MiB works (exactly 4 GiB is rejected), opening 4 GiB takes ~0.5 s. use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, OnceLock}; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; @@ -52,6 +53,8 @@ pub struct Uma { /// cannot take it – a title that commits all of unified memory at start (Unicorn /// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped. pool: Mutex<(usize, usize, Vec<usize>)>, + /// the committed windows are not the GPU's memory: it has copies of them (`set_shadowed`) + shadowed: AtomicBool, } /// bytes of XCL's arena pool (`Uma::new`) @@ -198,6 +201,7 @@ impl Uma { inner: Mutex::new(inner), sparse_free: Mutex::new(sparse_free), pool: Mutex::new((0, 0, Vec::new())), + shadowed: AtomicBool::new(false), }; u.reserve_pool(POOL); return Some(u); @@ -277,6 +281,23 @@ impl Uma { len > 0 && self.is_committed(p) && p.checked_add(len - 1).is_some_and(|e| self.window_of(e) == self.window_of(p)) } + /// The GPU could not open the committed windows as heaps (`OpenExistingHeapFromAddress` + /// not implemented: D3DMetal): each has a buffer in video memory instead, a copy that + /// `d3d12x::sparse` keeps in step like a sparse window's tiles. + pub fn set_shadowed(&self) { + self.shadowed.store(true, Ordering::Release); + } + + pub fn shadowed(&self) -> bool { + self.shadowed.load(Ordering::Acquire) + } + + /// Whether the GPU works on a copy of the memory at `p` (a sparse window, or a committed + /// one that is shadowed): what the GPU writes there the CPU sees only after a readback. + pub fn is_gpu_copy(&self, p: usize) -> bool { + self.is_sparse(p) || (self.shadowed() && self.is_committed(p)) + } + /// Address space for a title reservation of `size` bytes in the sparse windows (64 KiB /// aligned, first fit; not committed). Prefers windows 1+ so window 0 stays uncluttered for /// small allocations, falling back to all of the title's sparse space (never `desc_range`). @@ -404,6 +425,7 @@ impl Uma { inner: Mutex::new(inner), sparse_free: Mutex::new(Default::default()), pool: Mutex::new((0, 0, Vec::new())), + shadowed: AtomicBool::new(false), }); } for p in got { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e0c1518fa..51614256c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -17,6 +17,7 @@ use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use super::console_list::{self, Layout, Param}; +use super::indirect; #[derive(Default)] struct State { @@ -34,6 +35,28 @@ struct State { uma: Vec<usize>, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + res_buf: Option<(ID3D12Resource, u64, usize)>, + res_retired: Vec<(ID3D12Resource, u64, usize)>, +} + +static ALLOC_RES: Mutex<Option<HashMap<usize, Vec<(ID3D12Resource, u64, usize)>>>> = Mutex::new(None); +static FREE_RES: Mutex<Vec<(ID3D12Resource, u64, usize)>> = Mutex::new(Vec::new()); + +fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, usize)>) { + if bufs.is_empty() || allocator == 0 { + return; + } + ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + +pub(super) fn release_allocator_res(allocator: usize) { + let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) else { return }; + let mut free = FREE_RES.lock().unwrap(); + for b in bufs { + if free.len() < 16 { + free.push(b); + } + } } static STATES: Mutex<Option<HashMap<usize, State>>> = Mutex::new(None); @@ -73,7 +96,7 @@ fn with<R>(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { - let (old, blocks) = with(list, |s| { + let (old, blocks, res_bufs) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.pso = initial_pso; @@ -82,9 +105,14 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; - (old, std::mem::take(&mut s.uma)) + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + (old, std::mem::take(&mut s.uma), res_bufs) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -107,7 +135,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) }); - let (old, blocks) = with(to, |s| { + let (old, blocks, res_bufs) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.layout = layout; @@ -116,15 +144,24 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; s.pso = pso; - (old, std::mem::take(&mut s.uma)) + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + (old, std::mem::take(&mut s.uma), res_bufs) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); } /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + if let Some(mut s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { console_list::hold_until_reset(s.allocator, s.uma); + if let Some(b) = s.res_buf.take() { + s.res_retired.push(b); + } + hold_res_until_reset(s.allocator, s.res_retired); } } @@ -225,26 +262,360 @@ fn note_address(va: u64) { /// command signatures that change root arguments (they need the title's root signature) static ROOT_SIGNATURES: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None); +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DispatchMeshSig { + companion_dispatch: usize, + byte_stride: u32, + mesh_offset: u32, +} + +static DISPATCH_MESH_SIGS: Mutex<Option<HashMap<usize, DispatchMeshSig>>> = Mutex::new(None); + pub(super) fn note_root_changing_signature(sig: usize) { ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); } +pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { + DISPATCH_MESH_SIGS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(sig, DispatchMeshSig { companion_dispatch, byte_stride, mesh_offset }); +} + +fn dispatch_mesh_sig_of(sig: usize) -> Option<DispatchMeshSig> { + DISPATCH_MESH_SIGS.lock().unwrap().as_ref()?.get(&sig).copied() +} + +unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12Resource>) { + let mut b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(res.cloned()), + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.UAV).pResource); +} + +unsafe fn emit_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); +} + +unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Result<ID3D12Resource, String> { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut res: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut res, + ) + .map_err(|e| format!("{what} ({bytes:#x} B): {e}"))?; + res.ok_or_else(|| format!("null {what}")) +} + +unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + if let Some((buf, _cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va)); + } + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= need).map(|i| free.swap_remove(i)) + }; + let entry = match picked { + Some(e) => e, + None => (default_uav_buffer(&dev, need, "two-pass res buffer")?, need, dev_key), + }; + let buf = entry.0.clone(); + let va = buf.GetGPUVirtualAddress(); + with(this, |s| { + if let Some(old) = s.res_buf.replace(entry) { + s.res_retired.push(old); + } + }); + Ok((buf, va)) +} + +unsafe fn bind_two_pass_stage( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + real_mesh_pso: usize, + tp: &super::real::TwoPassPso, + res_va: u64, + compute_pass: bool, +) -> Result<(), String> { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let windows = super::real::uma_window_vas(); + let first = *windows.first().ok_or("unified memory is not open on the GPU")?; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let copy = |bytes: &[u8]| -> Result<usize, String> { + let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + Ok(p as usize) + }; + let inline = layout + .as_ref() + .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) + .min(args.len()); + let table_at = copy(&args[inline..])?; + let mut io = match layout.as_ref() { + Some(l) if compute_pass => console_list::user_data_ms(l, &args, table_at as u64), + Some(l) => console_list::user_data_gfx(l, &args, table_at as u64), + None if compute_pass => { + let mut v = vec![0u32; 16]; + v[8] = table_at as u32; + v[9] = (table_at >> 32) as u32; + v + } + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::<Vec<u8>>())?; + let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); + let rs_raw = if compute_pass { tp.compute_rs } else { tp.mesh_rs } as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs_raw).ok_or("two-pass root signature")?; + let views = [va(io_at), res_va].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); + if compute_pass { + list.SetComputeRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } + let pso_raw = tp.compute as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass compute pipeline")?; + list.SetPipelineState(pc); + } else { + list.SetGraphicsRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + let pso_raw = real_mesh_pso as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass mesh pipeline")?; + list.SetPipelineState(pc); + } + Ok(()) +} + +unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex<Option<HashMap<usize, (ID3D12RootSignature, ID3D12PipelineState)>>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(pair) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let hlsl = "cbuffer C : register(b0) { uint count; uint stride; uint offset; uint mult; };\nByteAddressBuffer src : register(t0);\nRWByteAddressBuffer dst : register(u0);\n[numthreads(64, 1, 1)]\nvoid main(uint tid : SV_DispatchThreadID) {\n if (tid >= count) return;\n uint base = tid * stride;\n uint dwords = stride / 4u;\n for (uint i = 0u; i < dwords; ++i) {\n uint w = src.Load(base + i * 4u);\n if (i * 4u == offset) w = w * mult;\n dst.Store(base + i * 4u, w);\n }\n}\n"; + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + ..Default::default() + }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("scale rs serialize: {e}"))?; + let blob = blob.ok_or("scale rs blob")?; + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("scale rs create: {e}"))?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result<ID3D12PipelineState, _> = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; + CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src_raw: usize, src_off: u64, max: u32, stride: u32, mesh_offset: u32, mult: u32) -> Result<ID3D12Resource, String> { + let dev = super::real::list_device(this).ok_or("no device")?; + let (rs, pso) = scale_indirect_pipeline(&dev)?; + let src_ptr = src_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&src_ptr).ok_or("indirect args buffer")?; + let bytes = (max as u64).saturating_mul(stride as u64).max(256).next_multiple_of(256); + let dst = default_uav_buffer(&dev, bytes, "scaled args buffer")?; + emit_transition(list, src, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + let consts = [max, stride, mesh_offset, mult]; + list.SetComputeRoot32BitConstants(0, 4, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootShaderResourceView(1, src.GetGPUVirtualAddress() + src_off); + list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress()); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + emit_transition(list, src, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + let dev_key = dev.as_raw() as usize; + with(this, |s| s.res_retired.push((dst.clone(), bytes, dev_key))); + Ok(dst) +} + +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); + let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); + let raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_pso); + if let Some(tp) = super::real::two_pass_of(pso) { + let groups = x.saturating_mul(y.max(1)).saturating_mul(z.max(1)); + if groups == 0 { + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let need = (groups as u64).saturating_mul(tp.record.record_dwords() as u64).saturating_mul(4); + let run = (|| -> Result<(), String> { + let (res_buf, res_va) = ensure_res_buffer(this, need)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + list.Dispatch(groups, 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc_dm(this, groups.saturating_mul(tp.mesh_groups_per_record), 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass DispatchMesh #{n} ({groups} groups, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass DispatchMesh skipped: {e}"); + } + } + } + return; + } + if super::pso_async::is_pending(raw_pso) { + count(DRAWS_SKIPPED); + return; + } + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { + list.SetGraphicsRootSignature(r); + } + count(DRAWS_PC); + pc_dm(this, x, y, z); +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a -/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root -/// arguments themselves cannot be – skipped, logged) +/// translated pipeline, on XCL's ABI with the kept root arguments and any per-command updates. pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_pso); + let args_pc_off = args_off + super::real::buffer_delta(args); + let count_off = count_off + super::real::buffer_delta(count_buf); + + if let Some(tp) = super::real::two_pass_of(pso) { + if let Some(msig) = dispatch_mesh_sig_of(sig) { + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let run = (|| -> Result<(), String> { + let (res_buf, res_va) = ensure_res_buffer(this, 32 << 20)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + pc(this, msig.companion_dispatch, max, args, args_pc_off, count_buf, count_off); + emit_uav_barrier(list, Some(&res_buf)); + if tp.mesh_groups_per_record > 1 && max > 0 && args != 0 { + let scaled = make_scaled_args_buffer(this, list, args, args_pc_off, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record)?; + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, scaled.as_raw() as usize, 0, count_buf, count_off); + } else { + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc(this, sig, max, args, args_pc_off, count_buf, count_off); + } + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + match run { + Ok(()) => { + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass ExecuteIndirect(DispatchMesh) #{n} (max {max}, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: two-pass ExecuteIndirect skipped: {e}"); + } + } + } + return; + } + } + let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); - let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and // the list may hold XCL's ABI root signature from a translated draw before it – the PC // call with that pair is invalid (debug layer 953, "the currently set Root Signature // doesn't match the currently set Pipeline State Object"; a retail title's world then // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if super::pso_async::is_pending(with(this, |s| s.pso)) { + if super::pso_async::is_pending(raw_pso) { count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -257,20 +628,32 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); } - return pc(this, sig, max, args, args_off, count_buf, count_off); - } - if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect that changes root arguments with a translated pipeline skipped"); - } - return; + return pc(this, sig, max, args, args_pc_off, count_buf, count_off); } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - match bind_abi(this, list, pso, gfx) { + let result = match indirect::lookup(sig) { + Some(Some(signature)) => { + let repack = indirect::Repack { signature: &signature, resource: args, offset: args_off, max, gfx }; + bind_abi_before(this, list, pso, gfx, |layout, inline, shadow, io, root| { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + repack.record(list, root, layout.ok_or("no bound console root layout")?, inline, shadow, io, |size| { + with(this, |s| s.arena.take(u, size, 16, &mut s.uma)).map(|p| p as usize) + }) + }).map(|packed| { + pc(this, packed.signature.as_raw() as usize, max, packed.arguments.as_raw() as usize, 0, count_buf, count_off); + packed.finish_gpu(list); + with(this, |s| { + let shadow = if gfx { &mut s.args_gfx } else { &mut s.args }; + packed.retain_and_clear(s.allocator, shadow); + }); + }) + } + Some(None) => Err("unsupported root-changing command signature".into()), + None => bind_abi(this, list, pso, gfx).map(|()| pc(this, sig, max, args, args_pc_off, count_buf, count_off)), + }; + match result { Ok(()) => { count(if gfx { DRAWS } else { DISPATCHES }); - pc(this, sig, max, args, args_off, count_buf, count_off) } Err(e) => { count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); @@ -854,9 +1237,21 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { + bind_abi_before(this, list, pso, gfx, |_, _, _, _, _| Ok(())) +} + +unsafe fn bind_abi_before<T>( + this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, + before: impl FnOnce(Option<&Layout>, usize, &[u8], &[u32], &ID3D12RootSignature) -> Result<T, String>, +) -> Result<T, String> { let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; + // shadowed unified memory whose sparse windows could not be made (no reserved resources + // either): descriptor tables are read from window 0, and a null root descriptor is not bound + if first == 0 && u.shadowed() { + return Err("window 0 of unified memory has no buffer on the GPU".into()); + } let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result<usize, String> { @@ -883,6 +1278,9 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; let rs = rs as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; + let pc = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pc).ok_or("pipeline")?; + let value = before(layout.as_deref(), inline, &args, &io, rs)?; let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); if gfx { list.SetGraphicsRootSignature(rs); @@ -895,10 +1293,8 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi list.SetComputeRootUnorderedAccessView(k as u32, v); } } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; list.SetPipelineState(pc); - Ok(()) + Ok(value) } #[cfg(test)] @@ -1101,15 +1497,12 @@ mod tests { orig_vt[41] = fake_set_compute_uav as usize; orig_vt[59] = fake_execute_indirect as usize; - // Extended vtable layout expected by `real::orig_fn`: entry -1 holds `orig_vt` pointer, - // and entries 0..64 hold the COM method pointers used via `ID3D12GraphicsCommandList`. - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + // Extended vtable laid out as `real::orig_fn` reads it, with the COM method pointers used + // via `ID3D12GraphicsCommandList`. + let (_ext_vt, ext) = crate::hle::d3d12x::real::test_ext_table(&orig_vt); let fake = Box::new(FakeAdoptedList { - // SAFETY: `ext_vt` has 65 elements so `.add(1)` points to slot 0 with `orig_vt` at `-1`. - vt: unsafe { ext_vt.as_ptr().add(1) }, + vt: ext, refs: AtomicUsize::new(1), dispatch_calls: AtomicUsize::new(0), set_compute_rs_calls: AtomicUsize::new(0), @@ -1124,6 +1517,7 @@ mod tests { let standin_ok = 0x7200_0001usize; let real_ok = 0x7200_0002usize; let sig_root_changing = 0x7200_00F0usize; + indirect::register(sig_root_changing, 0, &[]); note_root_changing_signature(sig_root_changing); pso_async::submit( @@ -1140,8 +1534,8 @@ mod tests { reset(list_ptr, 0x7200_0100, standin_ok); unsafe { - // With `sig_root_changing`, a translated compute PSO is caught by the root-changing - // guard instead of falling through to `pc` (which happened when `R` wasn't registered). + // With `sig_root_changing`, a translated compute PSO rejects this unsupported signature + // instead of falling through to `pc` (which happened when `R` wasn't registered). execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); } assert_eq!( @@ -1184,6 +1578,7 @@ mod tests { ); forget(list_ptr); + indirect::forget(sig_root_changing); let _ = pso_async::released(standin_ok); let _ = pso_async::released(standin_fail); real::forget_pso_for_test(real_ok); @@ -1280,4 +1675,18 @@ mod tests { let _ = pso_async::released(standin); } } + + #[test] + fn dispatch_mesh_signature_tracking_returns_companion_and_layout() { + let sig = 0x7400_0001usize; + let companion = 0x7400_0002usize; + assert_eq!(dispatch_mesh_sig_of(sig), None); + note_dispatch_mesh_signature(sig, companion, 28, 16); + assert_eq!( + dispatch_mesh_sig_of(sig), + Some(DispatchMeshSig { companion_dispatch: companion, byte_stride: 28, mesh_offset: 16 }) + ); + DISPATCH_MESH_SIGS.lock().unwrap().as_mut().unwrap().remove(&sig); + assert_eq!(dispatch_mesh_sig_of(sig), None); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 8619941f1..4cca9a455 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -74,6 +74,7 @@ pub struct Layout { pub size: u32, pub inline: u32, pub inline_gfx: u32, + pub inline_ms: u32, } /// User SGPRs the console's compiler gives root arguments: compute s4…s15 (s0…s3 are the @@ -81,8 +82,10 @@ pub struct Layout { /// fetch shader) – both measured on its output (`tests/console_shaders.rs`). const INLINE_SGPRS: u32 = 12; const INLINE_SGPRS_GFX: u32 = 24; +const INLINE_SGPRS_MS: u32 = 16; const FIRST_SGPR: usize = 4; const FIRST_SGPR_GFX: usize = 8; +const FIRST_SGPR_MS: usize = 16; /// Layout from a serialized root signature: a DXBC container with RTS0 or a bare RTS0. pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> { @@ -99,7 +102,7 @@ pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> { // the parameters go into user SGPRs in order while each fits whole; from the first one // that does not, the rest go to the table (packed from its start) – as the console's // compiler expects them (HANDOFF: root argument binding) - let (mut spilled, mut spilled_gfx) = (false, false); + let (mut spilled, mut spilled_gfx, mut spilled_ms) = (false, false, false); for k in 0..n { let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize); let p = match ty { @@ -120,6 +123,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option<Layout> { if !spilled_gfx { l.inline_gfx += bytes; } + spilled_ms |= l.inline_ms + bytes > 4 * INLINE_SGPRS_MS; + if !spilled_ms { + l.inline_ms += bytes; + } l.size += bytes; l.params.push(p); } @@ -132,6 +139,19 @@ pub fn user_data(l: &Layout, args: &[u8], table_at: u64) -> Vec<u32> { sgprs(FIRST_SGPR, l.inline, args, table_at) } +pub fn user_data_ms(l: &Layout, args: &[u8], table_at: u64) -> Vec<u32> { + let mut s = vec![0u32; FIRST_SGPR_MS]; + s[8] = table_at as u32; + s[9] = (table_at >> 32) as u32; + let inline = &args[..(l.inline_ms as usize).min(args.len())]; + s.extend(inline.chunks(4).map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + })); + s +} + /// Bytes of a compute dispatch's arguments that go in user SGPRs: the layout's rule, but /// never more than the shader itself has registers for. `user_sgprs` is the shader's own /// count (`real::pso_user_sgprs`; None = not known, the rule alone). The console's newer @@ -324,6 +344,7 @@ pub fn allocator_reset(allocator: *mut c_void) { if let Some(b) = blocks { unsafe { free_uma(&b) }; } + super::bind::release_allocator_res(allocator as usize); } fn with_list<R>(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option<R> { @@ -987,4 +1008,20 @@ mod tests { let args: Vec<u8> = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); assert_eq!(user_data_gfx(&l, &args, 0x200), vec![0x200, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0x5000, 4, 0x80]); } + + #[test] + fn mesh_arguments_go_in_user_sgprs_from_s16() { + let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline_ms; + assert_eq!(inline(&[(1, 2), (2, 0), (0, 0)]), 20); + assert_eq!(inline(&[(1, 14), (2, 0)]), 64); + assert_eq!(inline(&[(1, 15), (2, 0)]), 60); + assert_eq!(inline(&[(1, 17), (2, 0)]), 0); + let l = layout_from_blob(&rts0(&[(1, 2), (2, 0), (0, 0)])).unwrap(); + let args: Vec<u8> = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); + let got = user_data_ms(&l, &args, 0x7_0000_0200); + assert_eq!(got[8], 0x200); + assert_eq!(got[9], 7); + assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); + } } + diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index eeb524893..cb177680b 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -1,5 +1,6 @@ //! Write32/64BitValueBottomOfPipeX into memory the GPU does not see: done by the CPU once the GPU -//! has finished the work before them. +//! has finished the work before them. CopyMemoryToMemoryX between two such places goes the same +//! way (`Write::Copy`). //! //! A console title marks its GPU progress with bottom-of-pipe writes into its own memory and //! waits on them (a retail game: plain `VirtualAlloc` memory, outside XCL's unified memory). @@ -28,6 +29,18 @@ pub(super) enum Write { /// (`src`), copied atomically to `va` once the queue's fence completes. Holding `_buf` keeps /// the mapping alive until the worker finishes. ReadbackU64 { va: usize, src: usize, _buf: ID3D12Resource }, + /// CopyMemoryToMemoryX with neither end in unified memory: `len` bytes from `src`, read as + /// the GPU would see them (`title_textures::read_memory`: a GPU view's pages where the CPU + /// has them), to `dst` in the title's own memory + Copy { dst: usize, src: usize, len: usize }, +} + +/// copies done so far, and those whose source had no memory for some of its bytes (zeros) +static COPIES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// (CopyMemoryToMemoryX copies done by the CPU, those with a source that was not all there) +pub fn copies() -> (u64, u64) { + (COPIES[0].load(Ordering::Relaxed), COPIES[1].load(Ordering::Relaxed)) } struct Job { @@ -77,6 +90,7 @@ fn worker() -> &'static Mutex<mpsc::Sender<Job>> { let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire); write_u64_now(*va, value); } + Write::Copy { dst, src, len } => copy_now(*dst, *src, *len), } } } @@ -117,6 +131,19 @@ unsafe fn write_u64_now(va: usize, value: u64) { (*(va as *const AtomicU64)).store(value, Ordering::Release); } +/// `len` bytes from `src` as the GPU would see them to `dst`, if `dst` is still writable. +unsafe fn copy_now(dst: usize, src: usize, len: usize) { + if !writable(dst, len) { + return; + } + let (data, all) = super::title_textures::read_memory(src, len); + std::ptr::copy_nonoverlapping(data.as_ptr(), dst as *mut u8, len); + let n = COPIES[0].fetch_add(1, Ordering::Relaxed); + if !all && COPIES[1].fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: CopyMemoryToMemoryX {src:#x} → {dst:#x} ({len:#x} bytes), copy #{n} by the CPU: part of the source has no memory (zeros there)"); + } +} + /// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. pub(super) fn writable(va: usize, bytes: usize) -> bool { crate::hle::kernelx::lazy::ensure(va, bytes); @@ -182,13 +209,18 @@ mod tests { let cell = Box::new([0u32; 2]); let va = cell.as_ptr() as usize; assert!(writable(va, 8)); - after(q.as_raw(), vec![Write::Immediate(va, vec![7, 9])]); + // (and a copy between two places the GPU does not see, after the words) + let from = Box::new([0x1111_2222u32, 0x3333_4444, 0x5555_6666]); + let to = Box::new([0u32; 3]); + let (src, dst) = (from.as_ptr() as usize, to.as_ptr() as usize); + after(q.as_raw(), vec![Write::Immediate(va, vec![7, 9]), Write::Copy { dst, src, len: 12 }]); let t = std::time::Instant::now(); - while (*(va as *const AtomicU32)).load(Ordering::Acquire) != 7 { + while (*((dst + 8) as *const AtomicU32)).load(Ordering::Acquire) != 0x5555_6666 { assert!(t.elapsed().as_secs() < 5, "never written"); std::thread::yield_now(); } assert_eq!(*cell, [7, 9]); + assert_eq!(*to, *from); } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 2af03a02d..8a7ce8169 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -592,6 +592,34 @@ pub(super) unsafe extern "system" fn set_debug_flags_x(_this: *mut c_void, _flag S_OK } +/// device #101 of the newer console layout (a retail game, exe+0x24813ef): CreateStateObject(desc, +/// IID_ID3D12StateObject, out) for its ray-tracing pipeline. The libraries in the desc are +/// console shaders no PC driver takes, and the stub's S_OK with nothing in `out` sent the title +/// on to call the object. It handles a failure (it goes on without the pipeline): E_NOTIMPL. +/// Anything else at this slot (another layout's method) is answered S_OK as before. +pub(super) unsafe extern "system" fn create_state_object_x(_this: *mut c_void, desc: *const u32, riid: *const GUID, out: *mut *mut c_void) -> HRESULT { + let state_object = crate::gpu::shader::readable(riid as usize, 16) && { + let g = &*riid; + (g.data1, g.data2, g.data3, g.data4) == (0x47016943, 0xfca8, 0x4594, [0x93, 0xea, 0xaf, 0x25, 0x8b, 0x55, 0x34, 0x6d]) + }; + static ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let first = !ONCE.swap(true, Ordering::Relaxed); + if !state_object { + if first { + crate::xlog_warn!("D3D12.X: device #101 called without the state object IID – not modelled, S_OK"); + } + return S_OK; + } + if first { + let (ty, n) = if crate::gpu::shader::readable(desc as usize, 8) { (*desc, *desc.add(1)) } else { (0, 0) }; + crate::xlog_warn!("D3D12.X: CreateStateObject (type {ty}, {n} subobjects) from console code – ray-tracing pipelines are not translated: E_NOTIMPL"); + } + if crate::gpu::shader::readable(out as usize, 8) { + *out = std::ptr::null_mut(); + } + E_NOTIMPL +} + static PAGE_POOLS: Mutex<Vec<(u64, u32)>> = Mutex::new(Vec::new()); /// device #74 RegisterPagePoolX(address, pages, index out) @@ -679,6 +707,11 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if flags & 2 != 0 { flags &= !4; } + // a native host: no depth + stencil formats (`depth_only`) + if depth_only() { + let f = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + d[0x20..0x24].copy_from_slice(&depth_only_format(f).to_le_bytes()); + } d[8..16].fill(0); // alignment: the driver's let layout = if dim == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { D3D12_TEXTURE_LAYOUT_ROW_MAJOR.0 } else { D3D12_TEXTURE_LAYOUT_UNKNOWN.0 }; d[0x2C..0x30].copy_from_slice(&(layout as u32).to_le_bytes()); @@ -686,17 +719,48 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { d } +/// Whether the depth + stencil families become depth-only ones: on a native D3D12 host (Apple's +/// D3DMetal under Wine), unless `XCL_DEPTH_STENCIL=1`. Metal makes no depth-only view of a +/// depth + stencil texture and no view in another depth family than the texture's – its +/// assertion ("failed assertion `Texture Creation`") ends the process, where a Windows driver +/// takes the view or refuses it – and the console reads its depth buffers through exactly such +/// views (R24_UNORM_X8 / R32_FLOAT_X8X24 of the typeless resource, R16_UNORM of its D16S8). So +/// there every depth + stencil family is R32_TYPELESS / D32_FLOAT / R32_FLOAT (`depth_only_format`, +/// on top of the PC mapping above and in `pc_view_format` / `pc_shader_view_format`), and the +/// stencil plane is lost: stencil views read the depth. +pub fn depth_only() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + // (not kept before there is a device: `NATIVE_HOST_MEMORY` is set when it is adopted) + if !crate::gpu::shader::NATIVE_HOST_MEMORY.load(Ordering::Relaxed) { + return false; + } + *ON.get_or_init(|| !std::env::var("XCL_DEPTH_STENCIL").is_ok_and(|v| v.trim() == "1")) +} + +/// A depth + stencil format (R32G8X24 and R24G8 families) as the depth-only one of the same +/// role: typeless → R32_TYPELESS, the depth format → D32_FLOAT, the planes' read formats → +/// R32_FLOAT. Others as they are. +pub fn depth_only_format(f: u32) -> u32 { + match f { + 19 | 44 => 39, + 20 | 45 => 40, + 21 | 22 | 46 | 47 => 41, + f => f, + } +} + /// The PC format of a view, pipeline or clear value in the console's D16_UNORM_S8_UINT family: /// D24_UNORM_S8_UINT, R24_UNORM_X8_TYPELESS, X24_TYPELESS_G8_UINT (`pc_resource_desc` makes such /// resources R24G8_TYPELESS). pub fn pc_view_format(f: u32) -> u32 { - match f { + let pc = match f { 118 => 45, 119 => 46, 120 => 47, 116 | 117 => 10, f => f, - } + }; + if depth_only() { depth_only_format(pc) } else { pc } } /// The typeless format of a depth format's family (None: not a depth format). @@ -725,6 +789,16 @@ pub fn pc_target_format(f: u32) -> u32 { /// readable formats and removes the device for anything else (0x887A0001). pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { let view = pc_view_format(view); + // a native host: the resource is of the R32 family whatever the console named (`depth_only`), + // and every view the console makes of a depth buffer – in its own family, the 16-bit one of + // its D16S8 buffer, a stencil plane, R8 of the stencil – reads its one plane + if depth_only() && matches!(resource, 39..=41) && matches!(view, 0 | 19..=22 | 39..=41 | 44..=47 | 53..=56 | 61 | 62) { + return 41; + } + // (and the other way round: a 16-bit depth buffer read through another family's format) + if depth_only() && matches!(resource, 53..=56) && matches!(view, 0 | 39..=41 | 53..=56) { + return 56; + } match (resource, view) { // R32G8X24_TYPELESS: depth 21, stencil 22 (19..=22, 0 | 19 | 20 | 21 | 39 | 40 | 41) => 21, @@ -746,6 +820,20 @@ pub fn stencil_view(resource: u32, view: u32) -> bool { matches!((resource, view), (19..=22, 22) | (44..=47, 47)) } +/// The format of a depth view of a resource whose PC format is `resource`, asked for as `view` +/// (already `pc_target_format`): on a native host the depth format of the resource's family +/// whatever was named (`depth_only`); else `view`. +pub fn pc_depth_view_format(resource: u32, view: u32) -> u32 { + if !depth_only() { + return view; + } + match resource { + 39..=41 => 40, + 53..=56 => 55, + _ => view, + } +} + /// A clear value (D3D12_CLEAR_VALUE: format first) with `pc_view_format`, copied into `buf`. pub(super) unsafe fn pc_clear(clear: *const c_void, buf: &mut [u8; 24]) -> *const c_void { if clear.is_null() || !crate::gpu::shader::readable(clear as usize, 24) { @@ -995,9 +1083,19 @@ pub(super) unsafe extern "system" fn get_copyable_footprints_x( } } -/// device #41 CreateCommandSignature(desc, root signature, riid, signature): the console's -/// DispatchX argument (105) is a PC Dispatch; the root signature only goes with arguments -/// that need one (constants, CBV / SRV / UAV) +fn indirect_arg_bytes(arg: &[u32; 4]) -> u32 { + match arg[0] { + 0 => 16, + 1 => 20, + 2 | 10 => 12, + 3 | 4 => 16, + 5 => arg[3].saturating_mul(4), + 6..=8 => 8, + 9 => 108, + _ => 0, + } +} + pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_void, desc: *const u8, root: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { if desc.is_null() || ppv.is_null() { return E_INVALIDARG; @@ -1015,8 +1113,27 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() && needs_root { - super::bind::note_root_changing_signature(*ppv as usize); + if hr >= 0 && !ppv.is_null() { + if needs_root { + let stride = u32::from_le_bytes(pc[..4].try_into().unwrap()); + super::indirect::register(*ppv as usize, stride, &list); + super::bind::note_root_changing_signature(*ppv as usize); + } else { + super::indirect::forget(*ppv as usize); + if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let mut dispatch_list = list.clone(); + dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + let mut dpc = pc; + dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); + let mut companion: *mut c_void = std::ptr::null_mut(); + let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); + if hr2 >= 0 && !companion.is_null() { + super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + } + } + } } hr } @@ -1076,6 +1193,23 @@ mod tests { assert_eq!((pc_target_format(86), pc_target_format(118), pc_view_format(117)), (28, 45, 10)); } + /// A native host's depth-only formats: both depth + stencil families land in the R32 one, + /// role for role; everything else – 16-bit depth, colour formats – stays. + #[test] + fn depth_stencil_families_become_the_r32_family() { + for (typeless, depth, planes) in [(19, 20, [21, 22]), (44, 45, [46, 47])] { + assert_eq!((depth_only_format(typeless), depth_only_format(depth)), (39, 40)); + assert_eq!(planes.map(depth_only_format), [41, 41]); + } + for same in [0, 10, 28, 39, 40, 41, 53, 55, 56, 61, 86, 116] { + assert_eq!(depth_only_format(same), same); + } + // (off a native host nothing changes: these tests run without a device) + if !depth_only() { + assert_eq!((pc_view_format(118), pc_shader_view_format(44, 56), pc_depth_view_format(39, 45)), (45, 46, 45)); + } + } + #[test] fn derived_pipeline_patches_land_on_the_desc_parts() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index aea8e598d..83ee83c7c 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -49,12 +49,22 @@ unsafe fn borrowed<R>(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option ID3D12Fence::from_raw_borrowed(&p).map(f) } +/// `XCL_TRACE_FENCES=1`: the first 200 fence events (address asked, queue signals, values) +fn trace() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + static N: AtomicU64 = AtomicU64::new(0); + *ON.get_or_init(|| std::env::var_os("XCL_TRACE_FENCES").is_some()) && N.fetch_add(1, Ordering::Relaxed) < 200 +} + fn refresh() { let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); for (&p, f) in g.iter().flatten() { if let Some(c) = f.cell { if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } { - c.0.store(v, Ordering::Release); + let was = c.0.swap(v, Ordering::AcqRel); + if was != v && trace() { + crate::xlog_info!("fence {p:#x}: completed value {was:#x} -> {v:#x} (cell {:p})", c.0.as_ptr()); + } } } } @@ -74,6 +84,9 @@ pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { f.signalled = f.signalled.max(value); f.cell.is_some() }; + if trace() { + crate::xlog_info!("fence {fence:#x}: queue signal {value:#x} ({})", if cell { "cell armed" } else { "no cell asked for yet" }); + } if cell { arm(fence, value); } @@ -129,6 +142,9 @@ pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) arm(this as usize, pending); } refresh(); + if trace() { + crate::xlog_info!("fence {:#x}: completed-value address asked (#12): cell {:p}, value {:#x}, queue signal pending {pending:#x}", this as usize, cell.0.as_ptr(), cell.0.load(Ordering::Acquire)); + } cell.0.as_ptr() } diff --git a/crates/xcl/src/hle/d3d12x/gpu_views.rs b/crates/xcl/src/hle/d3d12x/gpu_views.rs new file mode 100644 index 000000000..dbabc388d --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_views.rs @@ -0,0 +1,428 @@ +//! The GPU's own view of a title's page pool. +//! +//! A title with a page pool (RegisterPagePoolX, device #74) maps the pool's 64 KiB pages twice: +//! for the CPU with XMemMapPhysicalPagesScatter, and for the GPU with the command queue's page +//! mapping call (#31 of the newer layout) – at *another* address range, where it places its +//! resources. A retail game reserves two ranges of the same size for its resource memory: one +//! the CPU reads and writes (pages mapped with the kernel call), one only the GPU sees (pages +//! mapped with the queue call, the same pool page at the same offset), and creates every +//! streamed texture – and the planes its video decoder writes – at an address in the second. +//! Its texture lock turns such an address into the CPU's (image +0x5121690). +//! +//! Windows has one address for a page here (`kernelx::map_pages`), and the GPU range is never +//! mapped for the CPU: a texture placed there read as zeros for good (the game's intro video +//! was flat green – three planes of zeros – while its decoder filled the pages through the +//! CPU's range). So the queue call's mappings are kept: GPU-view page → the pool page shown +//! there, named by the physical page that was at its place in the pool +//! (`kernelx::page_of_view`). `title_textures` reads a texture's memory through it +//! (`memory_at`) and finds the textures over memory the CPU wrote (`views_of`). + +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::Mutex; + +use crate::hle::kernelx::PHYS_PAGE_SIZE as PAGE; + +#[derive(Default)] +struct Views { + /// GPU-view page address → the physical page (its number) mapped there + at: BTreeMap<usize, usize>, + /// physical page → the GPU-view page addresses showing it + of: HashMap<usize, Vec<usize>>, +} + +impl Views { + fn unmap(&mut self, view: usize) { + if let Some(page) = self.at.remove(&view) { + if let Some(v) = self.of.get_mut(&page) { + v.retain(|&a| a != view); + if v.is_empty() { + self.of.remove(&page); + } + } + } + } + + fn map(&mut self, view: usize, page: usize) { + self.unmap(view); + self.at.insert(view, page); + self.of.entry(page).or_default().push(view); + } +} + +static VIEWS: Mutex<Option<Views>> = Mutex::new(None); +/// pages mapped in GPU views now (0: no title here maps any – nothing is looked up) +static MAPPED: AtomicUsize = AtomicUsize::new(0); +/// lowest and one past the highest GPU-view address ever mapped (a quick "not there") +static LOW: AtomicUsize = AtomicUsize::new(usize::MAX); +static HIGH: AtomicUsize = AtomicUsize::new(0); +static CALLS: AtomicU64 = AtomicU64::new(0); +static UNKNOWN: AtomicU64 = AtomicU64::new(0); + +/// `XCL_TRACE_PAGE_VIEWS=1`: what the queue's page mapping calls ask for is counted – how far +/// each mapped GPU-view page is from where the CPU has its page (one distance for all of them: +/// the GPU's range mirrors the CPU's), pages mapped that the CPU has nowhere, views mapped +/// again to another page – and logged with the calls' lines (`summary`). +fn trace() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("XCL_TRACE_PAGE_VIEWS").is_some()) +} + +#[derive(Default)] +struct Stats { + /// GPU-view address minus the CPU's address of the page, at the time of the call → pages + distances: HashMap<isize, u64>, + /// pages mapped whose physical page has no memory anywhere + nowhere: u64, + /// views that showed another page when they were mapped / the same page again + replaced: u64, + again: u64, + /// views unmapped that showed a page / that showed none + unmapped: u64, + unmapped_empty: u64, +} + +static STATS: Mutex<Option<Stats>> = Mutex::new(None); + +/// `XCL_TRACE_PAGE_VIEWS`: the counts so far, as text. +pub fn summary() -> String { + let g = STATS.lock().unwrap(); + let Some(s) = g.as_ref() else { return String::from("page views are not traced (XCL_TRACE_PAGE_VIEWS)") }; + let mut d: Vec<(isize, u64)> = s.distances.iter().map(|(&k, &v)| (k, v)).collect(); + d.sort_by_key(|e| std::cmp::Reverse(e.1)); + let shown: Vec<String> = d.iter().take(4).map(|&(k, v)| format!("{v} page(s) at {k:#x}")).collect(); + format!( + "{} distance(s) between a GPU-view page and the CPU's address of its page: {}; {} mapped with no memory anywhere; {} view(s) mapped again to another page, {} to the same one; {} unmapped, {} unmapped that showed nothing; {} mapped now", + d.len(), + shown.join(", "), + s.nowhere, + s.replaced, + s.again, + s.unmapped, + s.unmapped_empty, + MAPPED.load(Ordering::Relaxed) + ) +} + +/// One range of a batch: `count` pages from the batch's running address are mapped to the pool +/// pages from `pool_page` (flags 1) or unmapped (flags 2). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Range { + pub flags: u32, + pub pool_page: u32, + pub count: u32, +} + +/// The mappings a batch at GPU-view address `address` asks for: (GPU-view page address, the +/// pool page shown there or None for "unmapped"), in order. Ranges follow one another from +/// the batch's address; a range with other flags only moves on. +pub fn batch_mappings(address: usize, ranges: &[Range]) -> Vec<(usize, Option<u32>)> { + let mut out = Vec::new(); + let mut at = address & !(PAGE - 1); + for r in ranges { + for i in 0..r.count as usize { + match r.flags { + 1 => out.push((at + i * PAGE, Some(r.pool_page + i as u32))), + 2 => out.push((at + i * PAGE, None)), + _ => {} + } + } + at += r.count as usize * PAGE; + } + out +} + +/// most ranges of one batch / batches of one call that are read (a call that asks for more is +/// not one of these) +const MAX_RANGES: usize = 1 << 20; +const MAX_BATCHES: usize = 1 << 16; + +/// Command queue #31 of the newer layout (the name is XCL's): update the GPU's page mappings +/// of a page pool – `(batch count, batches, page pool address, pages in the pool, 0)`. +/// +/// * `n`, `batches`: `n` records of 0x18 bytes – { GPU-view address (u64), range count (u32), +/// pointer to the ranges (at +0x10) }. +/// * a range is 12 bytes – { flags (u32): 1 = map, 2 = unmap; pool page (u32): the index of a +/// 64 KiB page in the pool, for a map; page count (u32) }. A batch's ranges follow one +/// another from its address. +/// * `pool`: the address the pool was registered with (RegisterPagePoolX, device #74), where +/// the title first mapped all of its pages in order: pool page `k` is the physical page that +/// was mapped at `pool + k * 64 KiB`. +/// * `arg`: the pool's size in pages (the high part of its byte size); not used here. +/// +/// From a retail game's caller (image +0xf2c560; it builds one map range a page and one unmap +/// range a run) and its calls in a run: pool 0xd20000000, 0x185c0 pages (the 99,776 pages it +/// allocates), batches at 0x7440000000 and up – its GPU range starts at 0x7000000000, its CPU +/// range at 0x720000000, and a batch address minus the GPU range's start is the offset +/// XMemMapPhysicalPagesScatter got in the CPU range in the call before. The result is not +/// looked at. +pub(super) unsafe fn update(n: u32, batches: *const u8, pool: usize, arg: u32) { + let call = CALLS.fetch_add(1, Ordering::Relaxed); + // `XCL_GPU_PAGE_MAPPINGS=0`: the calls are not kept – a GPU view is read by the pairing of + // the two reservations alone (`kernelx::mirrors`), to compare the two + static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *OFF.get_or_init(|| std::env::var("XCL_GPU_PAGE_MAPPINGS").is_ok_and(|v| v.trim() == "0")) { + if call == 0 { + crate::xlog_info!("D3D12.X: command queue #31 (page mappings of pool {pool:#x}): not kept (XCL_GPU_PAGE_MAPPINGS=0)"); + } + return; + } + let readable = crate::gpu::shader::readable; + if n == 0 || n as usize > MAX_BATCHES || pool == 0 || !pool.is_multiple_of(PAGE) || !readable(batches as usize, n as usize * 0x18) { + if UNKNOWN.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: command queue #31 ({n} batch(es) at {batches:p}, pool {pool:#x}, {arg:#x}): not page mappings as XCL knows them – not done"); + } + return; + } + // what is asked, then the pool pages' physical pages (the kernel's lock), then the table + let mut asked: Vec<(usize, Option<u32>)> = Vec::new(); + for k in 0..n as usize { + let b = batches.add(k * 0x18); + let (address, count, ranges) = ((b as *const u64).read_unaligned() as usize, (b.add(8) as *const u32).read_unaligned() as usize, (b.add(0x10) as *const usize).read_unaligned()); + if count == 0 { + continue; + } + if count > MAX_RANGES || !readable(ranges, count * 12) { + if UNKNOWN.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: command queue #31: batch {k} at {address:#x} has {count} range(s) at {ranges:#x} that cannot be read – left out"); + } + continue; + } + let ranges: Vec<Range> = (0..count) + .map(|i| { + let [flags, pool_page, count] = ((ranges + i * 12) as *const [u32; 3]).read_unaligned(); + Range { flags, pool_page, count } + }) + .collect(); + asked.extend(batch_mappings(address, &ranges)); + } + let resolved: Vec<(usize, Option<usize>)> = asked + .iter() + .map(|&(view, pool_page)| (view, pool_page.and_then(|p| crate::hle::kernelx::page_of_view(pool + p as usize * PAGE)))) + .collect(); + // (the trace's distances: asked of the kernel before the table is locked) + let places: Vec<Option<usize>> = if trace() { resolved.iter().map(|&(_, page)| page.and_then(crate::hle::kernelx::page_address)).collect() } else { Vec::new() }; + let (mut mapped, mut unmapped, mut lost) = (0usize, 0usize, 0usize); + { + let mut g = VIEWS.lock().unwrap(); + let v = g.get_or_insert_with(Views::default); + if trace() { + let mut st = STATS.lock().unwrap(); + let st = st.get_or_insert_with(Stats::default); + for (&(view, page), place) in resolved.iter().zip(&places) { + let shown = v.at.get(&view).copied(); + match (page, place) { + (Some(page), place) => { + match shown { + Some(old) if old == page => st.again += 1, + Some(_) => st.replaced += 1, + None => {} + } + match place { + Some(at) => *st.distances.entry(view as isize - *at as isize).or_default() += 1, + None => st.nowhere += 1, + } + } + (None, _) if shown.is_some() => st.unmapped += 1, + (None, _) => st.unmapped_empty += 1, + } + } + } + for (&(view, page), &(_, pool_page)) in resolved.iter().zip(&asked) { + match page { + Some(page) => { + v.map(view, page); + mapped += 1; + LOW.fetch_min(view, Ordering::Relaxed); + HIGH.fetch_max(view + PAGE, Ordering::Relaxed); + } + None => { + v.unmap(view); + if pool_page.is_some() { + lost += 1; + } else { + unmapped += 1; + } + } + } + } + MAPPED.store(v.at.len(), Ordering::Relaxed); + } + if call < 4 || call.is_power_of_two() || lost != 0 && UNKNOWN.fetch_add(1, Ordering::Relaxed) < 8 { + let first = asked.first().map(|&(view, p)| format!("; first: {view:#x} → pool page {p:x?}")).unwrap_or_default(); + crate::xlog_info!( + "D3D12.X: command queue #31 (page mappings of pool {pool:#x}, call #{call}, {n} batch(es), {arg:#x}): {mapped} page(s) mapped in the GPU's view, {unmapped} unmapped{}; {} mapped there now{first}", + if lost != 0 { format!(", {lost} name a pool page the title has no memory at") } else { String::new() }, + MAPPED.load(Ordering::Relaxed) + ); + if trace() { + crate::xlog_info!("D3D12.X: page views after call #{call}: {}", summary()); + } + } +} + +/// Whether any page is mapped in a GPU view (else nothing here applies). +pub fn any() -> bool { + MAPPED.load(Ordering::Relaxed) != 0 +} + +/// Whether `[addr, addr + len)` touches the addresses GPU views were mapped at so far (from the +/// lowest to the highest one): memory the CPU never writes at these addresses. +pub fn in_range(addr: usize, len: usize) -> bool { + any() && addr < HIGH.load(Ordering::Relaxed) && addr + len > LOW.load(Ordering::Relaxed) +} + +/// The physical page shown at the GPU-view page of `addr`. +fn page_at(addr: usize) -> Option<usize> { + if !any() || addr < LOW.load(Ordering::Relaxed) || addr >= HIGH.load(Ordering::Relaxed) { + return None; + } + VIEWS.lock().unwrap().as_ref()?.at.get(&(addr & !(PAGE - 1))).copied() +} + +/// What the queue's page mappings say of `addr`: None – no page is mapped at its GPU-view page +/// (or it is no GPU-view address); Some(place) – one is, and `place` is where the CPU has the +/// memory the GPU sees at `addr` (None: a page with no memory yet). +pub fn lookup(addr: usize) -> Option<Option<usize>> { + let page = page_at(addr)?; + Some(crate::hle::kernelx::page_address(page).map(|a| a + (addr & (PAGE - 1)))) +} + +/// Where the CPU has the memory the GPU sees at `addr` (an address in a GPU view): the place +/// of the page mapped there, at `addr`'s offset in it. None: not a GPU-view address, nothing +/// mapped there, or a page with no memory yet. +pub fn memory_at(addr: usize) -> Option<usize> { + lookup(addr).flatten() +} + +/// The GPU-view ranges (address, bytes) that show the CPU memory `[addr, addr + len)` – pages +/// the title mapped there and, with the queue call, in a GPU view. In address order, neighbours +/// joined. +pub fn views_of(addr: usize, len: usize) -> Vec<(usize, usize)> { + if !any() || len == 0 { + return Vec::new(); + } + let mut out: Vec<(usize, usize)> = Vec::new(); + let mut p = addr & !(PAGE - 1); + while p < addr + len { + // (the kernel's lock, then the table's: never one inside the other) + if let Some(page) = crate::hle::kernelx::page_at(p) { + let views: Vec<usize> = VIEWS.lock().unwrap().as_ref().and_then(|v| v.of.get(&page).cloned()).unwrap_or_default(); + let (from, to) = (addr.max(p) - p, (addr + len).min(p + PAGE) - p); + out.extend(views.into_iter().map(|v| (v + from, to - from))); + } + p += PAGE; + } + out.sort_unstable(); + let mut joined: Vec<(usize, usize)> = Vec::with_capacity(out.len()); + for (a, n) in out { + match joined.last_mut() { + Some(l) if l.0 + l.1 == a => l.1 += n, + _ => joined.push((a, n)), + } + } + joined +} + +/// (pages mapped in GPU views now, calls of the queue's page mapping method) +pub fn counts() -> (usize, u64) { + (MAPPED.load(Ordering::Relaxed), CALLS.load(Ordering::Relaxed)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ranges_follow_one_another_from_the_batch_address() { + let a = 0x7440_0000_0000usize; + // two single pages (as the title maps: one range a page), then three unmapped, then a + // range of flags XCL does not know (skipped, but it takes its pages), then one mapped + let ranges = [ + Range { flags: 1, pool_page: 7, count: 1 }, + Range { flags: 1, pool_page: 3, count: 1 }, + Range { flags: 2, pool_page: 0, count: 3 }, + Range { flags: 9, pool_page: 1, count: 2 }, + Range { flags: 1, pool_page: 40, count: 2 }, + ]; + assert_eq!( + batch_mappings(a + 0x123, &ranges), + [ + (a, Some(7)), + (a + PAGE, Some(3)), + (a + 2 * PAGE, None), + (a + 3 * PAGE, None), + (a + 4 * PAGE, None), + (a + 7 * PAGE, Some(40)), + (a + 8 * PAGE, Some(41)), + ] + ); + assert!(batch_mappings(a, &[]).is_empty()); + } + + #[test] + fn a_view_shows_one_page_and_a_page_knows_its_views() { + let mut v = Views::default(); + v.map(0x1_0000, 16); + v.map(0x2_0000, 16); + v.map(0x3_0000, 32); + assert_eq!(v.of[&16], [0x1_0000, 0x2_0000]); + // another page at a view: the first one no longer shows there + v.map(0x1_0000, 32); + assert_eq!((v.of[&16].clone(), v.of[&32].clone()), (vec![0x2_0000], vec![0x3_0000, 0x1_0000])); + v.unmap(0x2_0000); + assert!(!v.of.contains_key(&16) && v.at.len() == 2); + v.unmap(0x2_0000); + assert_eq!(v.at.len(), 2); + } + + /// The whole path on real pages: a pool mapped at its address, a page of it mapped where + /// the CPU uses it, the queue call naming it by its pool index for a GPU-view address – + /// the GPU view reads what the CPU wrote, and the CPU range is found from the write. + #[test] + fn a_gpu_view_reads_the_page_the_cpu_wrote() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages}; + use std::ffi::c_void; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + if crate::gpu::uma::get().is_none() { + return; + } + let mut n = 4usize; + let mut pages = [0usize; 4]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let reserve = |pages: usize| VirtualAlloc(std::ptr::null(), pages * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + let (pool, cpu, gpu) = (reserve(4), reserve(8), reserve(8)); + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 4, 0, 4, pages.as_mut_ptr()) as usize, pool); + // pool page 2 at virtual page 5 of both ranges + let mut one = [pages[2]]; + assert_eq!(MapTitlePhysicalPages((cpu + 5 * PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, cpu + 5 * PAGE); + let ranges = [[1u32, 2, 1]]; + let batch: [usize; 3] = [gpu + 5 * PAGE, 1, ranges.as_ptr() as usize]; + update(1, batch.as_ptr() as *const u8, pool, 4); + // (a texture over virtual pages 4..7 of the GPU's range, as the content comparison sees it) + let hash = || crate::hle::d3d12x::title_textures::memory_hash_for_tests(gpu + 4 * PAGE + 0x30, 3 * PAGE - 0x50); + let before = hash(); + assert_eq!(before, hash()); + *((cpu + 5 * PAGE + 0x40) as *mut u32) = 0xB14B_0002; + let written = hash(); + assert_ne!(before, written, "a write through the CPU's range shows in the comparison of the GPU's"); + let at = memory_at(gpu + 5 * PAGE + 0x40).expect("the GPU view has the page"); + assert_eq!((at, *(at as *const u32)), (cpu + 5 * PAGE + 0x40, 0xB14B_0002)); + assert_eq!(memory_at(gpu + 4 * PAGE), None, "nothing mapped at the page before"); + assert_eq!(views_of(cpu + 5 * PAGE + 0x100, 0x200), [(gpu + 5 * PAGE + 0x100, 0x200)]); + assert_eq!(views_of(cpu + 4 * PAGE, 3 * PAGE), [(gpu + 5 * PAGE, PAGE)]); + // unmapped in the GPU's view: nothing there any more + let ranges = [[2u32, 0, 1]]; + let batch: [usize; 3] = [gpu + 5 * PAGE, 1, ranges.as_ptr() as usize]; + update(1, batch.as_ptr() as *const u8, pool, 4); + assert_eq!(memory_at(gpu + 5 * PAGE + 0x40), None); + assert!(views_of(cpu + 5 * PAGE, PAGE).is_empty()); + assert_ne!(written, hash(), "a page unmapped from the view shows too"); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 4, pages.as_mut_ptr()), 1); + for r in [pool, cpu, gpu] { + VirtualFree(r as *mut c_void, 0, MEM_RELEASE); + } + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/indirect.rs b/crates/xcl/src/hle/d3d12x/indirect.rs new file mode 100644 index 000000000..28a864642 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indirect.rs @@ -0,0 +1,479 @@ +//! Repack root-changing indirect draws and dispatches on the GPU. The native signature +//! consumes an ABI io UAV address followed by the draw or dispatch arguments for each item. +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::{Arc, Mutex}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::{console_list::{Layout, Param}, real}; +use crate::gpu::recomp::{self, KERNEL_SGPRS}; + +const IO_BYTES: u32 = 4 * KERNEL_SGPRS as u32; +const THREADS: u32 = 64; +const CONFIG_WORDS: u32 = 13; + +#[derive(Clone, Copy)] +enum RootArg { + Constants { index: usize, offset: u32, words: u32 }, + Descriptor { index: usize }, +} + +pub(super) struct Signature { + stride: u32, + root: Vec<(u32, RootArg)>, + action: D3D12_INDIRECT_ARGUMENT_TYPE, + action_offset: u32, + action_bytes: u32, +} + +// An entry without a layout still identifies a root-changing signature. Its original +// signature can only be run with the title's root signature. +static SIGNATURES: Mutex<Option<HashMap<usize, Option<Arc<Signature>>>>> = Mutex::new(None); + +pub(super) fn register(sig: usize, stride: u32, args: &[[u32; 4]]) { + SIGNATURES.lock().unwrap().get_or_insert_with(HashMap::new) + .insert(sig, Signature::parse(stride, args).map(Arc::new)); +} + +pub(super) fn lookup(sig: usize) -> Option<Option<Arc<Signature>>> { + SIGNATURES.lock().unwrap().as_ref()?.get(&sig).cloned() +} + +pub(super) fn forget(sig: usize) { + if let Some(sigs) = SIGNATURES.lock().unwrap().as_mut() { + sigs.remove(&sig); + } +} + +impl Signature { + fn parse(stride: u32, args: &[[u32; 4]]) -> Option<Self> { + let ([action, ..], root_args) = args.split_last()?; + let action = D3D12_INDIRECT_ARGUMENT_TYPE(*action as i32); + let action_bytes = match action { + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW => 16, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED => 20, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH => 12, + _ => return None, + }; + let mut root = Vec::with_capacity(root_args.len()); + let mut at = 0u32; + for &[kind, index, offset, words] in root_args { + let index = index as usize; + let (arg, bytes) = match D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32) { + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT if words != 0 => (RootArg::Constants { index, offset, words }, words.checked_mul(4)?), + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW + | D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW + | D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW => (RootArg::Descriptor { index }, 8), + _ => return None, + }; + root.push((at, arg)); + at = at.checked_add(bytes)?; + } + if root.is_empty() || stride % 4 != 0 || at.checked_add(action_bytes)? > stride { + return None; + } + Some(Self { stride, root, action, action_offset: at, action_bytes }) + } + + fn patches(&self, layout: &Layout, inline: u32, gfx: bool) -> Option<Vec<Patch>> { + let mut result = Vec::new(); + for &(source, arg) in &self.root { + let (at, bytes) = match arg { + RootArg::Constants { index, offset, words } => { + let Param::Constants { at, count } = *layout.params.get(index)? else { return None }; + if offset.checked_add(words)? > count { + return None; + } + (at.checked_add(offset.checked_mul(4)?)?, words.checked_mul(4)?) + } + RootArg::Descriptor { index } => { + let Param::Descriptor { at } = *layout.params.get(index)? else { return None }; + (at, 8) + } + }; + let end = at.checked_add(bytes)?; + if end > layout.size || (at < inline && end > inline) { + return None; + } + let dest = if at < inline { at + if gfx { 32 } else { 16 } } else { IO_BYTES + (at - inline) }; + for off in (0..bytes).step_by(4) { + result.push(Patch { source: source + off, dest: dest + off, shadow: (at + off) as usize }); + } + } + Some(result) + } +} + +#[derive(Debug, PartialEq, Eq)] +struct Patch { + source: u32, + dest: u32, + shadow: usize, +} + +struct Repacker { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +type SignatureKey = (usize, i32); +type RepackerKey = (usize, bool); +static REPACKERS: Mutex<Option<HashMap<RepackerKey, Arc<Repacker>>>> = Mutex::new(None); +static PACKED_SIGNATURES: Mutex<Option<HashMap<SignatureKey, ID3D12CommandSignature>>> = Mutex::new(None); +static PENDING: Mutex<Option<HashMap<usize, Vec<ID3D12Resource>>>> = Mutex::new(None); + +pub(super) fn allocator_reset(allocator: usize) { + let buffers = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + drop(buffers); +} + +unsafe fn repacker(dev: &ID3D12Device, upload: bool) -> Result<Arc<Repacker>, String> { + let mut g = REPACKERS.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let key = (dev.as_raw() as usize, upload); + if let Some(p) = map.get(&key) { + return Ok(p.clone()); + } + let src = include_str!("indirect_repack.hlsl"); + let extra: &[&str] = if upload { &["-DINPUT_UPLOAD=1"] } else { &[] }; + let dxil = recomp::dxc::compile(src, "main", "cs_6_0", extra)?; + let descriptor = |kind, reg| D3D12_ROOT_PARAMETER { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params = [ + if upload { descriptor(D3D12_ROOT_PARAMETER_TYPE_SRV, 0) } else { descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 0) }, + descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 1), + descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 2), + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: CONFIG_WORDS } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).map_err(|e| format!("serialize the indirect repacker root signature: {e}"))?; + let blob = blob.ok_or("no indirect repacker root signature blob")?; + let root: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())) + .map_err(|e| format!("create the indirect repacker root signature: {e}"))?; + let pso = compute_pso(dev, &root, &dxil).map_err(|e| format!("create the indirect repacker PSO: {e}"))?; + let p = Arc::new(Repacker { root, pso }); + map.insert(key, p.clone()); + Ok(p) +} + +unsafe fn compute_pso(dev: &ID3D12Device, root: &ID3D12RootSignature, dxil: &[u8]) -> windows::core::Result<ID3D12PipelineState> { + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }; + let pso = dev.CreateComputePipelineState(&desc); + ManuallyDrop::drop(&mut desc.pRootSignature); + pso +} + +unsafe fn packed_signature(dev: &ID3D12Device, root: &ID3D12RootSignature, sig: &Signature) -> Result<ID3D12CommandSignature, String> { + let mut g = PACKED_SIGNATURES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let key = (root.as_raw() as usize, sig.action.0); + if let Some(signature) = map.get(&key) { + return Ok(signature.clone()); + } + let params = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { UnorderedAccessView: D3D12_INDIRECT_ARGUMENT_DESC_0_4 { RootParameterIndex: 0 } }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { Type: sig.action, ..Default::default() }, + ]; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 8 + sig.action_bytes, NumArgumentDescs: 2, pArgumentDescs: params.as_ptr(), NodeMask: 0 }; + let mut out = None; + dev.CreateCommandSignature(&desc, root, &mut out).map_err(|e| format!("create the packed indirect signature: {e}"))?; + let out: ID3D12CommandSignature = out.ok_or("no packed indirect signature")?; + map.insert(key, out.clone()); + Ok(out) +} + +/// Read a title's GPU-produced buffer through its UMA window, or read a native upload +/// buffer as an SRV (already in GENERIC_READ). The console offset excludes placement delta. +unsafe fn source(resource: usize, offset: u64, bytes: u64) -> Option<(bool, u64, u32)> { + let end = offset.checked_add(bytes)?; + if offset % 4 != 0 { + return None; + } + if let Some((p, len)) = real::console_buffer(resource) { + if end > len as u64 { + return None; + } + let (window, at) = real::uma_window_buffer(p.checked_add(usize::try_from(offset).ok()?)?, usize::try_from(bytes).ok()?)?; + u32::try_from(at.checked_add(bytes - 1)?).ok()?; + let window = window as *mut c_void; + let window = ID3D12Resource::from_raw_borrowed(&window)?; + return Some((false, window.GetGPUVirtualAddress(), at as u32)); + } + let raw = resource as *mut c_void; + let r = ID3D12Resource::from_raw_borrowed(&raw)?; + let mut props = D3D12_HEAP_PROPERTIES::default(); + r.GetHeapProperties(Some(&mut props), None).ok()?; + let d = r.GetDesc(); + if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER + || d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + || !matches!(props.Type, D3D12_HEAP_TYPE_UPLOAD | D3D12_HEAP_TYPE_GPU_UPLOAD) + || end > d.Width + { + return None; + } + // Root SRV addresses must be 16-byte aligned. Rebase to keep byte offsets in 32 bits. + u32::try_from((offset & 15).checked_add(bytes - 1)?).ok()?; + Some((true, r.GetGPUVirtualAddress().checked_add(offset & !15)?, (offset & 15) as u32)) +} + +unsafe fn transition(list: &ID3D12GraphicsCommandList, resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: ManuallyDrop::new(Some(resource.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }) }, + ..Default::default() + }; + list.ResourceBarrier(std::slice::from_ref(&barrier)); + let mut t = ManuallyDrop::into_inner(barrier.Anonymous.Transition); + ManuallyDrop::drop(&mut t.pResource); +} + +pub(super) struct Recorded { + pub(super) signature: ID3D12CommandSignature, + pub(super) arguments: ID3D12Resource, + patches: Vec<Patch>, +} + +impl Recorded { + pub(super) unsafe fn finish_gpu(&self, list: &ID3D12GraphicsCommandList) { + // A list can execute more than once. Leave the scratch resource in its creation state. + transition(list, &self.arguments, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + + pub(super) fn retain_and_clear(self, allocator: usize, shadow: &mut [u8]) { + PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(self.arguments); + for p in self.patches { + shadow[p.shadow..p.shadow + 4].fill(0); + } + } +} + +pub(super) struct Repack<'a> { + pub(super) signature: &'a Signature, + pub(super) resource: usize, + pub(super) offset: u64, + pub(super) max: u32, + pub(super) gfx: bool, +} + +impl Repack<'_> { + pub(super) unsafe fn record( + &self, list: &ID3D12GraphicsCommandList, root: &ID3D12RootSignature, layout: &Layout, + inline: usize, args: &[u8], io: &[u32], alloc: impl FnOnce(usize) -> Option<usize>, + ) -> Result<Recorded, String> { + let sig = self.signature; + if self.gfx == (sig.action == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH) { + return Err("indirect action does not match the translated pipeline".into()); + } + let groups = self.max.div_ceil(THREADS); + if groups == 0 || groups > D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION { + return Err("indirect command count is outside the repacker's dispatch range".into()); + } + let patches = sig.patches(layout, inline as u32, self.gfx).ok_or("indirect root arguments do not match the bound layout")?; + let (upload, input, input_offset) = source(self.resource, self.offset, u64::from(self.max) * u64::from(sig.stride)) + .ok_or("indirect arguments are outside a GPU-readable UMA or upload buffer")?; + let spill = &args[inline..]; + let template_bytes = IO_BYTES + spill.len() as u32; + let scratch_stride = (template_bytes + 15) & !15; + let template_at = scratch_stride.checked_mul(self.max).ok_or("indirect root data is too large")?; + let patch_at = template_at.checked_add(template_bytes).ok_or("indirect root data is too large")?; + let size = patch_at.checked_add(8 * patches.len() as u32).ok_or("indirect root data is too large")?; + let scratch = alloc(size as usize).ok_or("unified memory is full")?; + let scratch_va = real::uma_va_of(scratch).ok_or("indirect scratch is outside GPU-visible UMA")?; + let raw = scratch as *mut u8; + std::ptr::copy_nonoverlapping(io.as_ptr().cast(), raw.add(template_at as usize), IO_BYTES as usize); + std::ptr::copy_nonoverlapping(spill.as_ptr(), raw.add(template_at as usize + IO_BYTES as usize), spill.len()); + for (i, patch) in patches.iter().enumerate() { + raw.add(patch_at as usize + 8 * i).cast::<[u32; 2]>().write([patch.source, patch.dest]); + } + let mut dev = None; + list.GetDevice(&mut dev).map_err(|e| format!("get the indirect list device: {e}"))?; + let dev = dev.ok_or("no indirect list device")?; + let repack = repacker(&dev, upload)?; + let signature = packed_signature(&dev, root, sig)?; + let mut arguments = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: u64::from(self.max) * u64::from(8 + sig.action_bytes), + Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut arguments, + ).map_err(|e| format!("allocate packed indirect arguments: {e}"))?; + let arguments: ID3D12Resource = arguments.ok_or("no packed indirect argument buffer")?; + let config: [u32; CONFIG_WORDS as usize] = [ + self.max, input_offset, sig.stride, sig.action_offset, sig.action_bytes, scratch_stride, + template_bytes, patches.len() as u32, scratch as u32, (scratch >> 32) as u32, + scratch_va as u32, (scratch_va >> 32) as u32, IO_BYTES, + ]; + repack.dispatch(list, upload, input, scratch_va, &arguments, &config, groups); + Ok(Recorded { signature, arguments, patches }) + } +} + +impl Repacker { + unsafe fn dispatch( + &self, list: &ID3D12GraphicsCommandList, upload: bool, input: u64, scratch_va: u64, + arguments: &ID3D12Resource, config: &[u32; CONFIG_WORDS as usize], groups: u32, + ) { + let uav = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() }; + list.ResourceBarrier(&[uav.clone()]); + list.SetPipelineState(&self.pso); + list.SetComputeRootSignature(&self.root); + if upload { + list.SetComputeRootShaderResourceView(0, input); + } else { + list.SetComputeRootUnorderedAccessView(0, input); + } + list.SetComputeRootUnorderedAccessView(1, scratch_va); + list.SetComputeRootUnorderedAccessView(2, arguments.GetGPUVirtualAddress()); + list.SetComputeRoot32BitConstants(3, config.len() as u32, config.as_ptr().cast(), 0); + list.Dispatch(groups, 1, 1); + list.ResourceBarrier(&[uav]); + transition(list, arguments, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn root_offsets_follow_inline_registers_and_the_spilled_table() { + let key = 0x217_1A00; + let desc = [[5, 0, 1, 2], [8, 1, 0, 0], [1, 0, 0, 0]]; + register(key, 40, &desc); + let sig = lookup(key).unwrap().unwrap(); + assert_eq!((sig.stride, sig.action_offset, sig.action_bytes), (40, 16, 20)); + let layout = Layout { params: vec![Param::Constants { at: 0, count: 3 }, Param::Descriptor { at: 12 }], size: 20, inline: 12, inline_gfx: 12, inline_ms: 12 }; + let patches = sig.patches(&layout, 12, true).unwrap(); + assert_eq!( + patches.iter().map(|p| (p.source, p.dest, p.shadow)).collect::<Vec<_>>(), + vec![(0, 36, 4), (4, 40, 8), (8, IO_BYTES, 12), (12, IO_BYTES + 4, 16)], + ); + assert_eq!(sig.patches(&layout, 12, false).unwrap()[0].dest, 20); + assert!(sig.patches(&layout, 8, true).is_none()); + assert!(Signature::parse(32, &desc).is_none()); + assert!(Signature::parse(40, &[[5, 0, 0, 1], [3, 0, 0, 0], [1, 0, 0, 0]]).is_none()); + forget(key); + assert!(lookup(key).is_none()); + } + + #[test] + fn gpu_repack_preserves_per_dispatch_values_and_the_count_buffer() { + use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + unsafe { + let mut dev: Option<ID3D12Device> = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if recomp::dxc::create_instance().is_none() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let buffer = |bytes, heap, state, flags| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() + }; + let mut out = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out).unwrap(); + out.unwrap() + }; + let gpu_buffer = |size, state| buffer(size, D3D12_HEAP_TYPE_DEFAULT, state, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let (count, stride, record_bytes, max) = (2u32, 20u32, 20u32, 3u32); + let template_at = max * IO_BYTES; + let scratch_bytes = template_at + IO_BYTES + 16; + let src = gpu_buffer(u64::from(max * stride), D3D12_RESOURCE_STATE_COPY_DEST); + let scratch = gpu_buffer(u64::from(scratch_bytes), D3D12_RESOURCE_STATE_COPY_DEST); + let packed = gpu_buffer(u64::from(max * record_bytes), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let results = gpu_buffer(16, D3D12_RESOURCE_STATE_COPY_DEST); + let readback = buffer(16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + let upload = buffer(u64::from(scratch_bytes) + 128, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE); + let mut data = vec![0u32; (scratch_bytes as usize + 128) / 4]; + data[..15].copy_from_slice(&[0, 4, 1, 1, 1, 1, 9, 1, 1, 1, 2, 50, 1, 1, 1]); + data[16] = count; + let t = (128 + template_at as usize) / 4; + data[t + 4] = 7; + data[t + KERNEL_SGPRS..t + KERNEL_SGPRS + 4].copy_from_slice(&[0, 20, 4, 24]); + + list.CopyBufferRegion(&src, 0, &upload, 0, u64::from(max * stride)); + list.CopyBufferRegion(&scratch, 0, &upload, 128, u64::from(scratch_bytes)); + list.CopyBufferRegion(&results, 0, &upload, 80, 16); + for resource in [&src, &scratch, &results] { + transition(&list, resource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + + let prep = repacker(&dev, false).unwrap(); + let sig = Signature::parse(stride, &[[5, 0, 1, 2], [2, 0, 0, 0]]).unwrap(); + let native_sig = packed_signature(&dev, &prep.root, &sig).unwrap(); + let work = recomp::dxc::compile( + "RWByteAddressBuffer io : register(u0); RWByteAddressBuffer result : register(u1); + [numthreads(1,1,1)] void main() { result.Store(io.Load(20) * 4, io.Load(24) + io.Load(16)); }", + "main", "cs_6_0", &[], + ).unwrap(); + let work = compute_pso(&dev, &prep.root, &work).unwrap(); + let va = scratch.GetGPUVirtualAddress(); + let config = [max, 0, stride, 8, 12, IO_BYTES, IO_BYTES, 2, 0, 0, va as u32, (va >> 32) as u32, IO_BYTES]; + prep.dispatch(&list, false, src.GetGPUVirtualAddress(), va, &packed, &config, 1); + list.SetPipelineState(&work); + list.SetComputeRootSignature(&prep.root); + list.SetComputeRootUnorderedAccessView(1, results.GetGPUVirtualAddress()); + list.ExecuteIndirect(&native_sig, max, &packed, 0, &upload, 64); + transition(&list, &results, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&readback, 0, &results, 0, 16); + list.Close().unwrap(); + // Contents written after recording. The repacker can only see them at GPU execution. + let mut mapped: *mut c_void = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::copy_nonoverlapping(data.as_ptr(), mapped.cast(), data.len()); + upload.Unmap(0, None); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, event).unwrap(); + let waited = WaitForSingleObject(event, 10_000); + CloseHandle(event).unwrap(); + assert_eq!(waited, WAIT_OBJECT_0); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let actual = mapped.cast::<[u32; 4]>().read(); + readback.Unmap(0, None); + assert_eq!(actual, [11, 16, 0, 0]); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl b/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl new file mode 100644 index 000000000..4612354d3 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl @@ -0,0 +1,41 @@ +#ifdef INPUT_UPLOAD +ByteAddressBuffer source : register(t0); +#else +RWByteAddressBuffer source : register(u0); +#endif +RWByteAddressBuffer data : register(u1); +RWByteAddressBuffer packed : register(u2); + +cbuffer Config : register(b0) { + uint count, input_offset, input_stride, action_offset; + uint action_bytes, scratch_stride, template_bytes, patch_count; + uint scratch_lo, scratch_hi, va_lo, va_hi; + uint io_bytes; +}; + +uint2 offset_address(uint lo, uint hi, uint offset) { + uint sum = lo + offset; + return uint2(sum, hi + uint(sum < lo)); +} + +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= count) + return; + uint src = input_offset + id.x * input_stride; + uint dst = id.x * scratch_stride; + uint template_offset = count * scratch_stride; + uint patch_offset = template_offset + template_bytes; + for (uint i = 8; i < template_bytes; i += 4) + data.Store(dst + i, data.Load(template_offset + i)); + data.Store2(dst, offset_address(scratch_lo, scratch_hi, dst + io_bytes)); + for (uint j = 0; j < patch_count; ++j) { + uint2 patch = data.Load2(patch_offset + j * 8); + data.Store(dst + patch.y, source.Load(src + patch.x)); + } + + uint record = id.x * (8 + action_bytes); + packed.Store2(record, offset_address(va_lo, va_hi, dst)); + for (uint k = 0; k < action_bytes; k += 4) + packed.Store(record + 8 + k, source.Load(src + action_offset + k)); +} diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 3778fbc57..e6ba2b6f1 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -600,7 +600,7 @@ impl ListState { last.0 = last.0.min(va); last.1 = last.1.max(end); } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(va as usize)) { if self.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } @@ -945,6 +945,17 @@ fn note_write(list: usize, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } +/// A PC copy into `[offset, offset + n)` of console buffer `dst` whose memory the GPU only has +/// a copy of in a committed window (`Uma::shadowed`: readback buffers live there, and titles +/// read them through a pointer they keep mapped, without another Map): the bytes come back to +/// the CPU's view after the submit, like the lists' own memory writes. +fn note_copy_into(list: usize, dst: usize, offset: u64, n: u64) { + let Some(u) = crate::gpu::uma::get().filter(|u| u.shadowed()) else { return }; + let Some((p, bytes)) = real::console_buffer(dst).filter(|&(p, _)| u.is_committed(p)) else { return }; + let offset = offset.min(bytes as u64); + note_write(list, p as u64 + offset, n.min(bytes as u64 - offset)); +} + // --------------------------------------------------------------------------------------- // per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX // --------------------------------------------------------------------------------------- @@ -1957,6 +1968,9 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, } let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer(dst as usize, size as usize), real::uma_window_buffer(src as usize, size as usize)) else { note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); + if cpu_copy(this, dst as usize, src as usize, size as usize) { + return; + } return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); }; note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); @@ -1974,6 +1988,37 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, transition(this, s, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); } +/// CopyMemoryToMemoryX with neither end in unified memory, the destination the title's own +/// writable memory and the source memory the CPU can read for the GPU – the title's own, or a +/// GPU view of it (a retail game reads pages it mapped for the GPU only this way: 16 KiB from +/// its page pool's GPU view into its heap). Nothing the GPU wrote is involved (a title texture +/// the GPU wrote over the source: not this), so the CPU copies when the GPU has finished the +/// work before it (`cpu_writes`). Whether the copy was taken. +unsafe fn cpu_copy(list: *mut c_void, dst: usize, src: usize, len: usize) -> bool { + let Some(u) = crate::gpu::uma::get() else { return false }; + let in_uma = |a: usize| u.window_of(a).is_some() || u.window_of(a + len - 1).is_some(); + if in_uma(dst) || in_uma(src) || !super::cpu_writes::writable(dst, len) || super::title_textures::gpu_written_over(src, len) { + return false; + } + let view = crate::hle::kernelx::mirrors::source(src).is_some() || super::gpu_views::in_range(src, len); + if !view && !crate::gpu::shader::readable(src, len) { + return false; + } + let recorded = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))).map(|s| s.cpu_writes.push(super::cpu_writes::Write::Copy { dst, src, len })).is_some(); + if !recorded { + return false; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 4 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: CopyMemoryToMemoryX: {src:#x} → {dst:#x} ({len:#x} bytes) is outside unified memory: copied by the CPU once the GPU is there (#{n}; the source is {})", + if view { "in a GPU view of the title's memory" } else { "the title's own memory" } + ); + } + true +} + unsafe fn device_of(list: *mut c_void) -> Option<ID3D12Device> { let mut dev: Option<ID3D12Device> = None; ID3D12GraphicsCommandList::from_raw_borrowed(&list)?.GetDevice(&mut dev).ok()?; @@ -3573,6 +3618,7 @@ pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); } } + note_copy_into(this as usize, dst, dst_off, n); pc::<unsafe extern "system" fn(*mut c_void, usize, u64, usize, u64, u64)>(this, PC_COPY_BUFFER_REGION)(this, dst, dst_off + real::buffer_delta(dst), src, src_off + real::buffer_delta(src), n) } @@ -3672,6 +3718,12 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } } + if let Some(l) = dst.as_ref().filter(|l| l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { + // (the rows of the footprint: at most what the copy writes) + let f = &l.Anonymous.PlacedFootprint; + let n = f.Footprint.RowPitch as u64 * f.Footprint.Height.max(1) as u64 * f.Footprint.Depth.max(1) as u64; + note_copy_into(this as usize, transmute_copy::<_, usize>(&l.pResource), f.Offset, n); + } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; pc::<unsafe extern "system" fn(*mut c_void, *const D3D12_TEXTURE_COPY_LOCATION, u32, u32, u32, *const D3D12_TEXTURE_COPY_LOCATION, *const D3D12_BOX)>(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); std::mem::forget((d, s)); // borrowed resource pointers @@ -3758,6 +3810,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { + note_copy_into(this as usize, dst, 0, u64::MAX); return pc::<unsafe extern "system" fn(*mut c_void, usize, usize)>(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); @@ -3816,6 +3869,8 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, first: u32, count: u32, dest: usize, offset: u64) { let pc_offset = offset.saturating_add(real::buffer_delta(dest)); type F = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); + // (8 bytes a query; pipeline statistics, the largest, are 11 values) + note_copy_into(this as usize, dest, offset, count as u64 * if ty == D3D12_QUERY_TYPE_PIPELINE_STATISTICS { 88 } else { 8 }); pc::<F>(this, PC_RESOLVE_QUERY_DATA)(this, heap, ty, first, count, dest, pc_offset); if !is_occlusion(ty) { return; @@ -3879,8 +3934,8 @@ mod tests { fn reset_commits_state_only_after_native_success_and_always_restores_vtable() { let mut native = vec![0usize; PC_RESET + 1]; native[PC_RESET] = reset_test_native as usize; - let extended = [native.as_ptr() as usize, 0usize]; - let ext = unsafe { extended.as_ptr().add(1) as usize }; + let (_extended, ext) = crate::hle::d3d12x::real::test_ext_table(&native); + let ext = ext as usize; let replacement = 0x1234_5678usize; let mut object = [ext]; let list = object.as_mut_ptr() as *mut c_void; @@ -4384,12 +4439,8 @@ mod tests { let mut orig_list_vt = [0usize; 70]; orig_list_vt[PC_RESOLVE_QUERY_DATA] = fake_resolve as usize; orig_list_vt[PC_WRITE_BUFFER_IMMEDIATE] = fake_write_immediate as usize; - // Adopted objects store `orig` at `ext[-1]`. - let ext_list_vt = [orig_list_vt.as_ptr() as usize, 0usize]; - let mut fake_list = FakeCom { - // SAFETY: `ext_list_vt` has 2 elements; `.add(1)` points at `ext[0]` with `ext[-1] = orig`. - vt: unsafe { ext_list_vt.as_ptr().add(1) }, - }; + let (_ext_list_vt, ext_list) = crate::hle::d3d12x::real::test_ext_table(&orig_list_vt); + let mut fake_list = FakeCom { vt: ext_list }; let mut res_vt = [0usize; 16]; res_vt[11] = fake_gpu_va as usize; @@ -4473,13 +4524,10 @@ mod tests { orig_vt[42] = fake_noop_uav as usize; // SetGraphicsRootUnorderedAccessView orig_vt[43] = fake_set_ib as usize; - let mut ext_vt = vec![0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + let (_ext_vt, ext) = crate::hle::d3d12x::real::test_ext_table(&orig_vt); let fake = Box::new(FakeDrawList { - // SAFETY: `ext_vt` has 65 entries so `.add(1)` points to slot 0 with `orig_vt` at `-1`. - vt: unsafe { ext_vt.as_ptr().add(1) }, + vt: ext, refs: AtomicUsize::new(1), draws: Mutex::new(Vec::new()), index_buffers: Mutex::new(Vec::new()), @@ -4604,12 +4652,10 @@ mod tests { let mut orig_vt = [0usize; 64]; orig_vt[PC_OM_SET_RENDER_TARGETS] = fake_om_set_render_targets as usize; - let mut ext_vt = [0usize; 2]; - ext_vt[0] = orig_vt.as_ptr() as usize; + let (_ext_vt, ext) = crate::hle::d3d12x::real::test_ext_table(&orig_vt); let fake = Box::new(FakeRtList { - // SAFETY: `ext_vt` has 2 entries so `.add(1)` has `orig_vt` at `-1` as `real::orig_fn` expects. - vt: unsafe { ext_vt.as_ptr().add(1) }, + vt: ext, calls: Mutex::new(Vec::new()), }); let list_ptr = &*fake as *const FakeRtList as *mut c_void; @@ -4750,13 +4796,10 @@ mod tests { orig_vt[PC_RESOURCE_BARRIER] = fake_resource_barrier as usize; orig_vt[PC_SET_PREDICATION] = fake_set_predication as usize; - let mut ext_vt = [0usize; 65]; - ext_vt[0] = orig_vt.as_ptr() as usize; - ext_vt[1..].copy_from_slice(&orig_vt); + let (_ext_vt, ext) = crate::hle::d3d12x::real::test_ext_table(&orig_vt); let fake = Box::new(FakePredList { - // SAFETY: `ext_vt` has 65 entries so `.add(1)` points at slot 0 with `orig_vt` at `-1`. - vt: unsafe { ext_vt.as_ptr().add(1) }, + vt: ext, ty: Mutex::new(D3D12_COMMAND_LIST_TYPE_DIRECT), events: Mutex::new(Vec::new()), }); @@ -4941,15 +4984,15 @@ mod tests { let list_ptr = list.as_raw(); let orig_vt = *(list_ptr as *const *const usize); - let mut ext_vt = [0usize; 65]; - ext_vt[0] = orig_vt as usize; - std::ptr::copy_nonoverlapping(orig_vt, ext_vt.as_mut_ptr().add(1), 64); + let (_ext_vt, ext) = crate::hle::d3d12x::real::test_ext_table(std::slice::from_raw_parts(orig_vt, 64)); on_create(list_ptr, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); - *(list_ptr as *mut *const usize) = ext_vt.as_ptr().add(1); + *(list_ptr as *mut *const usize) = ext; - let bottom_ts = Box::new(0u64); - let top_ts = Box::new(0u64); + // (a sentinel, not 0: whether the CPU copy happened is told apart from the value it copied) + const UNWRITTEN: u64 = u64::MAX; + let bottom_ts = Box::new(UNWRITTEN); + let top_ts = Box::new(UNWRITTEN); let bottom_va = bottom_ts.as_ref() as *const u64 as u64; let top_va = top_ts.as_ref() as *const u64 as u64; @@ -4977,14 +5020,19 @@ mod tests { cpu_writes_after(q.as_raw(), &[list_ptr]); let t = Instant::now(); - while (*(bottom_va as *const AtomicU64)).load(Ordering::Acquire) == 0 || (*(top_va as *const AtomicU64)).load(Ordering::Acquire) == 0 { - assert!(t.elapsed().as_secs() < 5, "non-UMA GPU timestamp never landed (top={}, bottom={})", *top_ts, *bottom_ts); + while (*(bottom_va as *const AtomicU64)).load(Ordering::Acquire) == UNWRITTEN || (*(top_va as *const AtomicU64)).load(Ordering::Acquire) == UNWRITTEN { + assert!(t.elapsed().as_secs() < 5, "non-UMA GPU timestamp never landed (top={:#x}, bottom={:#x})", *top_ts, *bottom_ts); std::thread::yield_now(); } + on_release(list_ptr as usize); + if *top_ts == 0 && *bottom_ts == 0 && crate::util::mac_host() { + // D3DMetal (CrossOver 26.3) resolves every timestamp query to 0 (frequency 60 Hz): + // the values landed, there is nothing on this host to check them against + crate::gpu::recomp::runner::skip_test("the host's timestamp queries read 0 (D3DMetal)"); + return; + } assert_ne!(*top_ts, 0); assert_ne!(*bottom_ts, 0); - - on_release(list_ptr as usize); } } diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 5da6eced0..fa09c9a30 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -18,7 +18,9 @@ pub mod dxgi_device; mod cpu_writes; mod fence_x; pub mod frame; +pub mod gpu_views; pub mod guard; +pub mod indirect; mod late_release; pub mod layout; pub mod list_x; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 01b3c92a4..86d430639 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -69,6 +69,12 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u let now = std::time::Instant::now(); if let Some(t) = LAST.lock().unwrap().replace(now) { crate::xlog_info!("D3D12.X: {frames} frames presented, {:.1} fps over the last 300", 300.0 / (now - t).as_secs_f64()); + // what keeping title textures in step with the title's memory took in those frames + crate::xlog_info!("D3D12.X: title textures over the last 300 frames: {}", super::title_textures::cost_since_last()); + // where the pages of title textures in GPU views came from so far + if let Some(v) = super::title_textures::view_sources() { + crate::xlog_info!("D3D12.X: title textures in GPU views, pages by source: {v}; {} page(s) mapped by the queue now", super::gpu_views::counts().0); + } } } super::real::stop_if_device_removed(); @@ -190,6 +196,16 @@ pub fn note_use(res: usize, what: usize) { } } +/// A resource is gone: the frame trace's counts and the presented list no longer name it (the +/// busiest target's GetDesc at a frame dump went through a freed object – GTA VI replaces its +/// UI target when its front end starts). +pub fn forget(res: usize) { + if let Some(m) = USES.lock().unwrap().as_mut() { + m.remove(&res); + } + PRESENTED.lock().unwrap().retain(|&r| r != res); +} + /// resources the title presented static PRESENTED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); @@ -435,7 +451,7 @@ fn window_thread() { WINDOW_EX_STYLE(0), class, &HSTRING::from(format!("XCL – {title}")), - WS_OVERLAPPEDWINDOW | WS_VISIBLE, + if crate::hle::kbm::background() { WS_OVERLAPPEDWINDOW } else { WS_OVERLAPPEDWINDOW | WS_VISIBLE }, x, y, w, @@ -449,6 +465,11 @@ fn window_thread() { crate::xlog_error!("could not create the XCL window"); return; }; + if crate::hle::kbm::background() { + // shown behind the program in front, without becoming the active window + let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE); + let _ = SetWindowPos(hwnd, Some(HWND_BOTTOM), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + } HWND_RAW.store(hwnd.0 as isize, Ordering::Release); crate::xlog_info!("XCL window created ({}x{})", cfg.window_width, cfg.window_height); crate::hle::kbm::attach(hwnd.0); @@ -776,13 +797,21 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { /// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder (`XCL_FRAME_DUMP=n`, /// n > 1: every n-th; a title loading at a few frames a second shows few) /// (`frame_<n>.bmp`, a quarter of each side; `XCL_FRAME_DUMP_FULL=1`: full size) – what the title presented, before the window. +/// `XCL_FRAME_DUMP_FROM=<frame>`: none before that frame (a retail game's presents have stopped +/// at a dump in its first 500 frames on a Mac; where no window can be captured, the dumps of +/// the frames after are the only picture). fn frame_dump_due() -> bool { - static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); - let every = *EVERY.get_or_init(|| match std::env::var("XCL_FRAME_DUMP") { - Ok(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120), - Err(_) => 0, + static EVERY: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + let (every, from) = *EVERY.get_or_init(|| { + let every = match std::env::var("XCL_FRAME_DUMP") { + Ok(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120), + Err(_) => 0, + }; + (every, std::env::var("XCL_FRAME_DUMP_FROM").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) }); - every > 0 && PRESENTS.load(Ordering::Relaxed) % every == 20.min(every - 1) + // the first frames too: a title under bring-up may never reach its 20th + let n = PRESENTS.load(Ordering::Relaxed); + every > 0 && n >= from && (n < 4 || n % every == 20.min(every - 1)) } /// Frames shown so far. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5b01e8569..b7daf61e2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -38,6 +38,17 @@ use crate::util::{HRESULT, E_INVALIDARG, E_NOINTERFACE, S_FALSE, S_OK}; const DLL: &str = "d3d12_xs.dll"; const EXTRA_SLOTS: usize = 64; const MAX_SCAN: usize = 512; +/// Words of the host's own table mirrored in front of an extended vtable. A C++ object's +/// table pointer is also the way to the words in front of the table: type information and +/// offset-to-top (Itanium ABI) or the RTTI locator (MSVC), and before those the virtual-base +/// and virtual-call offsets of a class with virtual inheritance. A host that runs +/// `dynamic_cast` on an object it is handed, or adjusts `this` through those offsets (Apple's +/// D3DMetal does both), reads them through the object's table pointer. +const PREFIX: usize = 16; +/// Words in front of an extended vtable: the original table's address, then the mirror. +const HDR: usize = PREFIX + 1; +/// words of a native host's method table kept after the public methods (see `class_for`) +const NATIVE_HOST_TAIL: usize = 512; #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] pub enum Kind { @@ -290,40 +301,84 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs Ok(format!("ok, {} window(s), {} µs", probes.len(), t0.elapsed().as_micros())) } +/// `XCL_UMA_SHADOW`: 1 = the committed windows get GPU copies without asking for a heap over +/// them (to try the path on a GPU that has `OpenExistingHeapFromAddress`), 0 = never. +fn shadow_choice() -> Option<bool> { + std::env::var("XCL_UMA_SHADOW").ok().map(|v| v != "0") +} + unsafe fn open_uma(device: &ID3D12Device) { let Some(u) = crate::gpu::uma::get() else { *UMA_ERROR.lock().unwrap() = "no UMA region".into(); return; }; - let open = |k: usize| -> Result<(usize, u64, usize), String> { - let (base, size) = u.window(k); + let buffer = |size: usize, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + // the window's memory itself as a heap; Ok(None): this D3D12 has no such heaps (D3DMetal + // answers E_NOTIMPL) and the window gets a copy in video memory instead + let open = |k: usize| -> Result<Option<ID3D12Heap>, String> { + if shadow_choice() == Some(true) { + return Ok(None); + } let dev3: ID3D12Device3 = device.cast().map_err(|e| format!("ID3D12Device3: {e}"))?; - let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const c_void).map_err(|e| format!("OpenExistingHeapFromAddress (window {k}): {e}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size as u64, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() + match dev3.OpenExistingHeapFromAddress::<ID3D12Heap>(u.window(k).0 as *const c_void) { + Ok(heap) => Ok(Some(heap)), + Err(e) if e.code() == windows::Win32::Foundation::E_NOTIMPL && shadow_choice() != Some(false) => { + *UMA_ERROR.lock().unwrap() = format!("OpenExistingHeapFromAddress (window {k}): {e}"); + Ok(None) + } + Err(e) => Err(format!("OpenExistingHeapFromAddress (window {k}): {e}")), + } + }; + // video memory as large as the window: a buffers-only heap, so the console buffers XCL + // places in the window (`place_console_buffer`, `place_at_title_address`) alias its buffer + // as they do in the heap over the window's memory + let shadow = |k: usize| -> Result<ID3D12Heap, String> { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u.window(k).1 as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, }; - let mut buf: Option<ID3D12Resource> = None; - device.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; - let buf = buf.ok_or("CreatePlacedResource")?; - let va = buf.GetGPUVirtualAddress(); - Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + let mut heap: Option<ID3D12Heap> = None; + super::title_textures::own_work(|| device.CreateHeap(&desc, &mut heap)).map_err(|e| format!("CreateHeap (window {k}, {} MB of video memory): {e}", u.window(k).1 >> 20))?; + heap.ok_or_else(|| "CreateHeap".to_string()) }; let n = u.shader_windows(); let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n]; let mut heaps: Vec<Option<usize>> = vec![None; n]; + let mut shadows: Vec<(usize, ID3D12Resource)> = Vec::new(); for k in 0..n { if !u.is_committed_window(k) { continue; } - match open(k) { + let made = open(k).and_then(|heap| { + let shadowed = heap.is_none(); + let heap = match heap { + Some(h) => h, + None => shadow(k)?, + }; + // the heap over process memory is a cross-adapter one; video memory is not + let flags = if shadowed { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER }; + let mut buf: Option<ID3D12Resource> = None; + device.CreatePlacedResource(&heap, 0, &buffer(u.window(k).1, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + if shadowed { + shadows.push((k, buf.clone())); + } + let va = buf.GetGPUVirtualAddress(); + Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + }); + match made { Ok((buf_raw, va, heap_raw)) => { bufs[k] = (buf_raw, va); heaps[k] = Some(heap_raw); @@ -335,7 +390,11 @@ unsafe fn open_uma(device: &ID3D12Device) { } } } - let check = if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { + // (a shadowed window is not the GPU's memory by design: nothing to check, its copy is + // brought up to date before each submit) + let check = if !shadows.is_empty() { + Ok("not run: the coherent window has a copy in video memory (no host-memory heaps on this D3D12)".into()) + } else if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { Ok("off (XCL_UMA_CHECK=0)".into()) } else { check_uma_import(device, u, &bufs) @@ -351,6 +410,23 @@ unsafe fn open_uma(device: &ID3D12Device) { *slot = (*buf_raw, *va); } } + for (k, buf) in &shadows { + let (base, size) = u.window(*k); + u.set_shadowed(); + if super::sparse::shadow_window(device, base, size, buf) { + crate::xlog_warn!( + "D3D12.X: UMA window {k} is not shared with the GPU ({}) – {} MB of video memory at VA {:#x} stand for it: CPU writes are uploaded before each submit, GPU writes read back on Map and after the lists' memory writes", + match shadow_choice() { + Some(true) => "XCL_UMA_SHADOW=1", + _ => "OpenExistingHeapFromAddress is not implemented", + }, + size >> 20, + bufs[*k].1 + ); + } else { + crate::xlog_warn!("D3D12.X: UMA window {k} is not shared with the GPU and its copy in video memory is not kept in step"); + } + } let w0_va = bufs.first().map_or(0, |b| b.1); crate::xlog_info!( "D3D12.X: UMA opened ({} sparse VRAM window(s), {} MB coherent window), window 0 buffer at VA {:#x}", @@ -535,6 +611,15 @@ pub fn init() -> Result<String, String> { super::device_x::probe_dynamic_depth_bias(&device); let raw = device.into_raw(); // one reference kept for the process lifetime adopt(raw, Kind::Device); + // The inlined D3D12.X of a retail game tests a byte of the console's device at +0x18 + // (11 places, e.g. exe+0x6ddf5): 0 – it writes a CBV's V# and descriptor copies into + // the heap's memory itself; else it calls #17 / #24. Here the byte is the host + // object's, so which way a run goes is the host's doing: said once, for the log. + if crate::gpu::shader::readable(raw as usize + 0x18, 1) { + let b = *(raw as *const u8).add(0x18); + let way = if b == 0 { "writes CBVs and descriptor copies itself (no #17 / #24 calls)" } else { "calls CreateConstantBufferView / CopyDescriptorsSimple" }; + crate::xlog_info!("D3D12.X: device byte +0x18 = {b:#04x} – console code with inlined descriptor writes {way}"); + } DEVICE.store(raw as usize, Ordering::Release); *ADAPTER.lock().unwrap() = name.clone(); Ok(name) @@ -616,10 +701,21 @@ unsafe fn vt(obj: *mut c_void) -> *const usize { /// Original function of `slot` for an adopted object. pub unsafe fn orig_fn(this: *mut c_void, slot: usize) -> usize { let ext = vt(this); - let orig = *ext.sub(1) as *const usize; + let orig = *ext.sub(HDR) as *const usize; *orig.add(slot) } +/// A test's extended table laid out as `orig_fn` reads it: `orig`'s address `HDR` words in front +/// of the table, then `orig`'s slots. Returns the storage (keep it alive) and the table pointer. +#[cfg(test)] +pub(super) fn test_ext_table(orig: &[usize]) -> (Vec<usize>, *const usize) { + let mut v = vec![0usize; HDR + orig.len()]; + v[0] = orig.as_ptr() as usize; + v[HDR..].copy_from_slice(orig); + let table = unsafe { v.as_ptr().add(HDR) }; + (v, table) +} + fn module_of(addr: usize) -> usize { use windows_sys::Win32::System::LibraryLoader::{ GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, @@ -694,7 +790,7 @@ pub(super) unsafe fn readopt(obj: *mut c_void, kind: Kind) { if obj.is_null() || !is_ext(vt(obj) as usize) { return adopt(obj, kind); } - let orig = *vt(obj).sub(1); + let orig = *vt(obj).sub(HDR); *(obj as *mut usize) = class_for(obj, orig, kind); } @@ -744,8 +840,29 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { .max() .unwrap_or(0); let total = (scanned + EXTRA_SLOTS).max(max_console); - let mut v: Vec<usize> = Vec::with_capacity(total + 1); + // A host D3D12 whose code is in no PE module (Apple's D3DMetal under Wine): its memory is + // not known to VirtualQuery (`gpu::shader::readable` probes it), the scan above cannot tell + // where its table ends (it stops at the first word that is in a module), and the host calls + // virtual methods of its own well past the public ones. Every slot up to `total` is taken + // as the host's and gets the guard – the host's own calls reach the host's word, a title's + // XCL's stub or method – and the host's words after them follow XCL's slots, so a call of + // its own never runs off the end. + let native_host = m0 == 0; + if native_host { + static ONCE: AtomicBool = AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + crate::gpu::shader::NATIVE_HOST_MEMORY.store(true, Ordering::Relaxed); + crate::xlog_warn!("D3D12.X: the host's D3D12 is not a PE module (a native host: D3DMetal) – its memory is probed by reading, its tables keep their prefix and tail"); + } + } + let scanned = if native_host { total } else { scanned }; + let mut v: Vec<usize> = Vec::with_capacity(total + HDR + if native_host { NATIVE_HOST_TAIL } else { 0 }); v.push(orig); + // (a table at the very start of its mapping has no words in front of it) + let prefix = native_host || crate::gpu::shader::readable(orig - 8 * PREFIX, 8 * PREFIX); + for k in (1..=PREFIX).rev() { + v.push(if prefix { *ot.sub(k) } else { 0 }); + } for i in 0..scanned { v.push(*ot.add(i)); } @@ -753,17 +870,22 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { for i in public..scanned { let info = stubs::new_info(DLL, &format!("{}::#{i} (not on PC)", iface.name), 0); info.hook.store(hook, Ordering::Release); - v[1 + i] = super::guard::make_guard(v[1 + i], info); + v[HDR + i] = super::guard::make_guard(v[HDR + i], info); } for i in scanned..total { let (addr, info) = stubs::make_stub_info(DLL, &format!("{}::#{i} (not on PC)", iface.name), 0); info.hook.store(hook, Ordering::Release); v.push(addr); } + if native_host { + for i in total..public + NATIVE_HOST_TAIL { + v.push(*ot.add(i)); + } + } for (method, f) in overrides(kind) { if let Some(s) = layout::slot(iface, method) { if s < public { - v[1 + s] = f; + v[HDR + s] = f; } } } @@ -771,23 +893,23 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { let pc = v.clone(); for (x, p) in console_remap(kind) { if x < public { - v[1 + x] = super::guard::make_split(pc[1 + p], pc[1 + x]); + v[HDR + x] = super::guard::make_split(pc[HDR + p], pc[HDR + x]); } else if x < scanned { - v[1 + x] = super::guard::make_split(pc[1 + p], *ot.add(x)); + v[HDR + x] = super::guard::make_split(pc[HDR + p], *ot.add(x)); } else if x < total { - v[1 + x] = pc[1 + p]; + v[HDR + x] = pc[HDR + p]; } } // slots where the console's method differs from the PC one at the same index for (slot, f) in console_slots(kind) { if slot < public { - v[1 + slot] = super::guard::make_split(f, v[1 + slot]); + v[HDR + slot] = super::guard::make_split(f, v[HDR + slot]); } else if slot < scanned { // an internal method of the runtime there (e.g. queue #30 = PresentX): the title // gets the console method, the runtime keeps its own - v[1 + slot] = super::guard::make_split(f, *ot.add(slot)); + v[HDR + slot] = super::guard::make_split(f, *ot.add(slot)); } else if slot < total { - v[1 + slot] = f; + v[HDR + slot] = f; } } // the other console extensions (device, command list): a title call is logged and answered @@ -796,7 +918,7 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { let own: HashSet<usize> = console_slots(kind).iter().map(|e| e.0).chain(console_remap(kind).iter().map(|e| e.0)).collect(); for i in (first..public).filter(|i| !own.contains(i)) { let (stub, _) = stubs::make_stub_info(DLL, &format!("{}::#{i} (console extension)", iface.name), 0); - v[1 + i] = super::guard::make_split(stub, v[1 + i]); + v[HDR + i] = super::guard::make_split(stub, v[HDR + i]); } } // methods the newer console layout keeps at other slots: picked at each call @@ -807,19 +929,27 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { if newer >= total { continue; } - let pc = if newer < scanned { *ot.add(newer) } else { v[1 + newer] }; - v[1 + newer] = super::guard::make_layout_split(super::guard::LayoutTargets { older: v[1 + newer], newer: f, pc, newer_layout: &QUEUE_SHIFTED }); + let pc = if newer < scanned { *ot.add(newer) } else { v[HDR + newer] }; + v[HDR + newer] = super::guard::make_layout_split(super::guard::LayoutTargets { older: v[HDR + newer], newer: f, pc, newer_layout: &QUEUE_SHIFTED }); } } // XCL_D3D12_TRACE: every public method called from console code is logged if std::env::var_os("XCL_D3D12_TRACE").is_some() { for i in 0..public { let name = format!("{}::{} (#{i})", iface.name, iface.methods.get(i).copied().unwrap_or("?")); - v[1 + i] = super::guard::make_tracer(v[1 + i], name); + v[HDR + i] = super::guard::make_tracer(v[HDR + i], name); + } + // `XCL_D3D12_TRACE=all`: the console-only slots after the public methods too (a title + // renders through them) + if std::env::var("XCL_D3D12_TRACE").is_ok_and(|t| t == "all") { + for i in public..total { + let name = format!("{}::#{i} (console slot)", iface.name); + v[HDR + i] = super::guard::make_tracer(v[HDR + i], name); + } } } let leaked: &'static [usize] = Box::leak(v.into_boxed_slice()); - let ext = leaked.as_ptr() as usize + 8; + let ext = leaked.as_ptr() as usize + 8 * HDR; EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(ext); crate::xlog_info!( "D3D12.X: {} – {public} PC methods, {} internal slots under the guard, +{EXTRA_SLOTS} stubs ({kind:?}, PC vtable {})", @@ -943,6 +1073,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (80, super::frame::wait_frame_event_x as usize), (81, super::frame::frame_statistics_x as usize), (86, x::create_pipeline_state_x as usize), + (101, x::create_state_object_x as usize), (108, x::get_resource_allocation_info2_x as usize), (127, dev_create_committed_resource_layout_x as usize), (133, x::create_placed_resource_layout_x as usize), @@ -1021,6 +1152,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + (127, b::dispatch_mesh as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -1310,11 +1442,19 @@ unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC None } +fn uma_shadowed() -> bool { + crate::gpu::uma::get().is_some_and(|u| u.shadowed()) +} + /// Sanitize a console buffer description and initial state for placement in a coherent /// cross-adapter UMA heap (`OpenExistingHeapFromAddress`). fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize) -> (D3D12_RESOURCE_DESC, u32) { let mut d = *desc; - d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF); + // a shadowed window's heap is video memory, not a cross-adapter heap over process memory + if !uma_shadowed() { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; (d, state as u32 & PC_RESOURCE_STATES) @@ -1380,6 +1520,10 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta } } } + // a readback buffer in a shadowed window: what the GPU copied into it is in video memory + if readback_on_null_map && u.shadowed() { + note_sparse_readback(*ppv as usize); + } Some(hr) } @@ -1409,7 +1553,9 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: return Some(hr); } let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + if !u.shadowed() { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; @@ -1455,7 +1601,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // a resource in unified memory: its console address (no PC mapping – the PC's would be // the start of the PC resource, before the address for a buffer placed below it) if let Some((p, bytes)) = console_buffer(this as usize) { - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(p)) { if !range.is_null() { let r = *(range as *const D3D12_RANGE); if r.End > r.Begin { @@ -1538,6 +1684,8 @@ static UNMAPPABLE: Mutex<Option<HashSet<usize>>> = Mutex::new(None); unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c_void) { if UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { + // (a texture kept in step with title memory: what was written while it was mapped) + super::title_textures::note_unmap(this as usize); return; } let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot_of(this, "Unmap"))); @@ -1577,6 +1725,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); + super::present::forget(this as usize); super::vram::forget(this as usize); super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); @@ -1708,6 +1857,13 @@ unsafe extern "system" fn res_gpu_va_x(this: *mut c_void) -> u64 { if let Some((p, _)) = console_buffer(this as usize) { return p as u64; } + // (a native host's answer for a texture is not known to be 0: the title's address first) + if crate::gpu::shader::NATIVE_HOST_MEMORY.load(Ordering::Relaxed) { + let placed = super::title_textures::address(this as usize).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied())); + if let Some(p) = placed { + return p as u64; + } + } let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, 11)); // a texture has no GPU address on the PC (0) – on the console every resource has one, and // titles use a texture's as the CPU's pointer to it (a retail game clears a 256x256 R32F one @@ -1907,9 +2063,38 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, if copy.is_none() { copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_dsv(&r.GetDesc())); } + // a native host: the resource's own depth family whatever the view names (Metal ends the + // process on a view of another family, `device_x::depth_only`) + if let (Some(c), Some(r)) = (copy.as_mut(), ID3D12Resource::from_raw_borrowed(&res)) { + let rd = r.GetDesc(); + let made = super::device_x::pc_depth_view_format(rd.Format.0 as u32, c.Format.0 as u32); + trace_depth_view("depth", res, &rd, desc.as_ref().map_or(0, |d| d.Format.0), made as i32); + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(made as i32); + } f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu) } +/// `XCL_TRACE_DEPTH_VIEWS=1`: every view made of a resource in a depth format family (the +/// format asked for, the one made, the resource) – flushed line by line, since a view the host +/// cannot make ends the process there (D3DMetal: Metal's texture assertion). +unsafe fn trace_depth_view(kind: &str, res: *mut c_void, rd: &D3D12_RESOURCE_DESC, asked: i32, made: i32) { + static ON: OnceLock<bool> = OnceLock::new(); + if !matches!(rd.Format.0, 19..=22 | 39..=41 | 44..=47 | 53..=56) || !*ON.get_or_init(|| std::env::var_os("XCL_TRACE_DEPTH_VIEWS").is_some()) { + return; + } + crate::xlog_info!( + "depth views: {kind} view format {asked} → {made} of {res:p} (format {}, {}x{}x{}, {} mips, {} samples, flags {:#x})", + rd.Format.0, + rd.Width, + rd.Height, + rd.DepthOrArraySize, + rd.MipLevels, + rd.SampleDesc.Count, + rd.Flags.0 + ); + crate::log::flush(); +} + /// The view a DSV without a description has, for a depth buffer `pc_resource_desc` made /// typeless (None: the resource's own format is a depth one). fn default_dsv(d: &D3D12_RESOURCE_DESC) -> Option<D3D12_DEPTH_STENCIL_VIEW_DESC> { @@ -1988,6 +2173,9 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { copy = Some(v); } + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + trace_depth_view("shader", res, &r.GetDesc(), desc.as_ref().map_or(0, |d| d.Format.0), copy.as_ref().map_or(0, |c| c.Format.0)); + } let desc = copy.as_ref().map_or(desc, |c| c as *const _); let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): @@ -2167,8 +2355,10 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, // `device_x::pc_resource_desc`: an invalid call, the device removed) let mut copy = desc.as_ref().copied(); if let (Some(c), Some(r)) = (copy.as_mut(), ID3D12Resource::from_raw_borrowed(&res)) { - let rf = r.GetDesc().Format.0 as u32; - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); + let rd = r.GetDesc(); + let asked = c.Format.0; + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rd.Format.0 as u32, c.Format.0 as u32) as i32); + trace_depth_view("unordered access", res, &rd, asked, c.Format.0); } let desc = copy.as_ref().map_or(desc, |c| c as *const _); super::present::note_use(res as usize, super::present::USE_UAV); @@ -2439,6 +2629,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), Kind::Fence => v.push(("Signal", fence_signal as usize)), + Kind::CommandSignature => v.push(("Release", signature_release as usize)), _ => {} } v @@ -2719,7 +2910,7 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v let d = super::device_x::pc_resource_desc(&x); let st = state as u32 & PC_RESOURCE_STATES; if let Some(hr) = place_at_title_address(this, block + offset, &d, st, clear as *const c_void, riid, ppv) { - if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(block + offset)) { + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(block + offset)) { let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); if st == D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 && (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 as u32) == 0 { note_sparse_readback(*ppv as usize); @@ -3126,6 +3317,15 @@ struct Dummy { cs: Vec<u8>, } +/// The stand-in pixel shader. Nothing is drawn with it (its vertex / mesh shader makes no +/// pixels), but its pipeline keeps the title's blend state, and that can be dual-source +/// blending (SRC1 factors on target 0: a retail game's forward transparency passes). A host that +/// builds the pixel stage for the blend state needs both colours then: Apple's Metal shader +/// converter (D3DMetal) refuses a pixel shader that writes SV_Target0 alone ("Failed to compile +/// fragment function", the pipeline a no-op). Hence SV_Target1 too; with the usual blending a +/// second output changes nothing. +const STANDIN_PS: &str = "struct O { float4 c0 : SV_Target0; float4 c1 : SV_Target1; };\nO main() { O o; o.c0 = float4(1, 0, 1, 1); o.c1 = float4(0, 0, 0, 0); return o; }\n"; + /// Stand-in mesh shader and pixel shader (DXIL, as mesh pipelines need): one degenerate /// triangle (DXC wants every output written), nothing drawn. fn dummy_mesh() -> Option<&'static (Vec<u8>, Vec<u8>)> { @@ -3133,8 +3333,7 @@ fn dummy_mesh() -> Option<&'static (Vec<u8>, Vec<u8>)> { D.get_or_init(|| { use crate::gpu::recomp::dxc::compile; let ms = "struct V { float4 p : SV_Position; };\n[outputtopology(\"triangle\")]\n[numthreads(1, 1, 1)]\nvoid main(out vertices V v[1], out indices uint3 t[1]) { SetMeshOutputCounts(1, 1); v[0].p = float4(0, 0, 0, 1); t[0] = uint3(0, 0, 0); }\n"; - let ps = "float4 main() : SV_Target { return float4(1, 0, 1, 1); }\n"; - match (compile(ms, "main", "ms_6_5", &[]), compile(ps, "main", "ps_6_0", &[])) { + match (compile(ms, "main", "ms_6_5", &[]), compile(STANDIN_PS, "main", "ps_6_0", &[])) { (Ok(m), Ok(p)) => Some((m, p)), (m, p) => { crate::xlog_warn!("D3D12.X: stand-in mesh shaders: {:?} {:?}", m.err(), p.err()); @@ -3172,10 +3371,23 @@ fn compile(src: &str, target: &str) -> Vec<u8> { /// Stand-in shaders used when the PC driver rejects a console shader. fn dummy() -> &'static Dummy { static D: OnceLock<Dummy> = OnceLock::new(); - D.get_or_init(|| Dummy { - vs: compile("float4 main(uint id : SV_VertexID) : SV_Position { return float4(0, 0, 0, 1); }", "vs_5_0"), - ps: compile("float4 main() : SV_Target { return float4(1, 0, 1, 1); }", "ps_5_0"), - cs: compile("[numthreads(1, 1, 1)] void main() {}", "cs_5_0"), + D.get_or_init(|| { + // On a native host DXIL from DXC first: a host that turns DXIL into its own shaders + // (Apple's D3DMetal) has nothing for a DXBC stand-in; the old compiler is the fallback. + let native = crate::gpu::shader::NATIVE_HOST_MEMORY.load(Ordering::Relaxed); + let both = |src: &str, new: &str, old: &str| match native.then(|| crate::gpu::recomp::dxc::compile(src, "main", new, &[])) { + Some(Ok(b)) if !b.is_empty() => b, + Some(r) => { + crate::xlog_warn!("D3D12.X: stand-in {new} shader not compiled by DXC ({:?}) – using {old}", r.err()); + compile(src, old) + } + None => compile(src, old), + }; + Dummy { + vs: both("float4 main(uint id : SV_VertexID) : SV_Position { return float4(0, 0, 0, 1); }", "vs_6_0", "vs_5_0"), + ps: both(STANDIN_PS, "ps_6_0", "ps_5_0"), + cs: both("[numthreads(1, 1, 1)] void main() {}", "cs_6_0", "cs_5_0"), + } }) } @@ -3248,6 +3460,21 @@ unsafe fn shader_bytes<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { (p != 0 && n > 0 && crate::gpu::shader::readable(p, n)).then(|| std::slice::from_raw_parts(p as *const u8, n)) } +/// A shader a PC driver can compile: a DXBC container with a DXBC (`SHDR` / `SHEX`) or DXIL +/// program, not a console one. +fn host_shader(blob: &[u8]) -> bool { + !crate::gpu::recomp::pso::is_console(blob) + && crate::gpu::shader::container_parts(blob).is_some_and(|parts| parts.iter().any(|p| matches!(p.fourcc.as_str(), "SHDR" | "SHEX" | "DXIL"))) +} + +/// On a Mac host, a graphics pipeline with a shader no PC driver can compile is refused +/// before Apple's D3DMetal sees it: D3DMetal does not reject such a shader with +/// E_INVALIDARG as Windows' D3D12 does, its process ends inside the unwinder instead +/// (CrossOver 26.3; XCL's test title's console-container PS). The stand-in fallback follows. +unsafe fn refused_on_mac_host(g: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> bool { + crate::util::mac_host() && [&g.VS, &g.PS, &g.DS, &g.HS, &g.GS].into_iter().filter_map(|b| shader_bytes(b)).any(|s| !host_shader(s)) +} + /// Root signature of every pipeline built from translated console shaders (static samplers /// make it per pipeline): the draw binds it instead of the title's. static PSO_RS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); @@ -3612,6 +3839,17 @@ fn forget_compute_blob(key: (u64, usize, i32)) { #[cfg(test)] mod compute_blob_tests { + #[test] + fn two_results_for_one_key_charge_the_budget_once() { + let mut entries = super::HashMap::new(); + let mut used = 0; + let key = (7, 1, 0); + super::insert_compute_blob(&mut entries, &mut used, key, vec![1, 2]); + super::insert_compute_blob(&mut entries, &mut used, key, vec![3, 4, 5]); + assert_eq!(used, 2, "the second result for the same key must not charge again"); + assert_eq!(entries[&key].as_slice(), &[1, 2]); + } + #[test] fn a_blob_is_found_only_for_the_same_program_root_signature_and_flags_and_is_forgotten() { let dxil = vec![7u8; 1000]; @@ -3648,14 +3886,35 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: return; } let blob = ID3DBlob::from_raw(raw); - let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec(); + let len = blob.GetBufferSize(); + if len == 0 || len > COMPUTE_BLOBS_MAX { + return; + } + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, len).to_vec(); let mut g = COMPUTE_BLOBS.lock().unwrap(); let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); + insert_compute_blob(m, total, key, bytes); +} + +/// Keep a driver blob for `key`, charging `total` for it once. Two workers can pass the +/// `compute_blob(key).is_some()` check above for the same pipeline before either has stored +/// its result, and a program built again after its blob was forgotten reaches this call a +/// second time: inserting in both cases charges the budget for bytes the map does not hold, +/// so `COMPUTE_BLOBS_MAX` fills up with entries that were never kept and later blobs of real +/// programs are refused. +fn insert_compute_blob( + m: &mut HashMap<(u64, usize, i32), std::sync::Arc<Vec<u8>>>, + total: &mut usize, + key: (u64, usize, i32), + bytes: Vec<u8>, +) { if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { return; } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + if let std::collections::hash_map::Entry::Vacant(entry) = m.entry(key) { + *total += bytes.len(); + entry.insert(std::sync::Arc::new(bytes)); + } } unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { @@ -3715,7 +3974,7 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); // a rect list pipeline: the fourth corner of each rect comes from a generated GS; without // it each rect is drawn as the triangle of its three vertices - let rect_gs = if d.PrimitiveTopologyType.0 == RECT_LIST_TYPE && copy.GS.pShaderBytecode.is_null() { + let rect_gs = if d.PrimitiveTopologyType.0 == RECT_LIST_TYPE && copy.GS.pShaderBytecode.is_null() && rect_list_gs_allowed() { rect_list_gs(vs, shader_bytes(&d.PS)).map_err(|e| note_translation_error(format!("rect list drawn as triangles: {e}"))).ok() } else { None @@ -4048,8 +4307,13 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID return hr; } let pc = untranslated_stream_desc(desc, stream); - let hr = finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv); - if hr >= 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_GRAPHICS_PIPELINE_STATE_DESC>()) { + let readable = crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_GRAPHICS_PIPELINE_STATE_DESC>()); + let hr = if readable && refused_on_mac_host(pc.as_ref().unwrap_or(&*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC))) { + E_INVALIDARG + } else { + finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv) + }; + if hr >= 0 || !readable { return hr; } let d = dummy(); @@ -4483,6 +4747,18 @@ unsafe fn untranslated_stream_desc(desc: *const c_void, stream: bool) -> Option< Some(g) } +/// Whether rect list pipelines get the generated geometry shader: `XCL_RECT_LIST_GS=1` / `0`, +/// else everywhere but on a native host (Apple's D3DMetal). Metal has no geometry stage – the +/// host emulates one – and a pipeline it cannot make is not always an error code there. Without +/// the GS a rect's fourth corner is made on the CPU (`bind::draw_rects`), which is what ran there. +fn rect_list_gs_allowed() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| match std::env::var("XCL_RECT_LIST_GS") { + Ok(v) => v.trim() != "0", + Err(_) => !crate::gpu::shader::NATIVE_HOST_MEMORY.load(Ordering::Relaxed), + }) +} + /// The GS that completes a rect list's rects behind the console VS `vs` and the PS `ps`; refused /// for a PS that is not a console one (its inputs' modes are not known). fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, String> { @@ -4863,6 +5139,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { if n == 0 { super::alloc_pool::forget(this as usize); super::list_x::on_allocator_release(this as usize); + super::indirect::allocator_reset(this as usize); } n } @@ -4883,10 +5160,20 @@ unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { if hr >= 0 { // the GPU is done with what lists recorded from this allocator used super::console_list::allocator_reset(this); + super::indirect::allocator_reset(this as usize); } hr } +unsafe extern "system" fn signature_release(this: *mut c_void) -> u32 { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let n = f(this); + if n == 0 { + super::indirect::forget(this as usize); + } + n +} + // --------------------------------------------------------------------------------------- // command queue layouts // --------------------------------------------------------------------------------------- @@ -4924,7 +5211,19 @@ pub(super) static QUEUE_SHIFTED: AtomicBool = AtomicBool::new(false); static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method -const NEWER_LIST_SLOTS: [(usize, usize); 21] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; +const NEWER_LIST_SLOTS: [(usize, usize); 22] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (129, 127), (139, 10)]; + +pub(super) unsafe fn list_device(list: *mut c_void) -> Option<ID3D12Device> { + type F = unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(list, 7)); + let iid = pc_iid(Kind::Device); + let mut raw: *mut c_void = std::ptr::null_mut(); + if f(list, &iid, &mut raw) >= 0 && !raw.is_null() { + Some(ID3D12Device::from_raw(raw)) + } else { + None + } +} /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). @@ -5007,6 +5306,14 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a f(this, a1) } 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, + // the newer layout's #31: UpdatePageMappings(batch count, batches, page pool address, a + // count, 0) – which pool pages the GPU sees at the addresses a title places its pool's + // resources at (`gpu_views`; as a stub the textures there that the pairing of the two + // reservations does not reach read as zeros: a retail game's menu images) + 29 if shifted => { + super::gpu_views::update(a1 as u32, a2 as *const u8, a3, a4 as u32); + 0 + } 30 => super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize, // the newer layout's #35: ExecuteCommandListsX(count, lists, a value, flags) – a retail // game submits all its command lists this way (flags 3; 0 for the one it recorded at @@ -5353,6 +5660,52 @@ mod this_first_tests { } } +#[cfg(test)] +mod standin_tests { + use super::*; + + /// The stand-in pixel shaders write SV_Target0 and SV_Target1: the pair a pipeline with a + /// title's dual-source blend state needs (Metal's shader converter refuses SV_Target0 alone). + #[test] + fn standin_pixel_shaders_write_both_dual_source_colours() { + let targets = |b: &[u8]| -> Vec<u32> { + crate::gpu::dxbc::signatures(b).1.iter().filter(|e| e.name.eq_ignore_ascii_case("SV_Target")).map(|e| e.index).collect() + }; + assert_eq!(targets(&dummy().ps), [0, 1], "the DXBC stand-in"); + match dummy_mesh() { + Some((_, ps)) => assert_eq!(targets(ps), [0, 1], "the DXIL stand-in of mesh pipelines"), + None => crate::gpu::recomp::runner::skip_test("no DXC"), + } + } + + /// A DXBC container holding one `fourcc` part. + fn container(fourcc: &[u8; 4], data: &[u8]) -> Vec<u8> { + let mut v = vec![0u8; 36]; + v[0..4].copy_from_slice(b"DXBC"); + v[28..32].copy_from_slice(&1u32.to_le_bytes()); + v[32..36].copy_from_slice(&36u32.to_le_bytes()); + v.extend_from_slice(fourcc); + v.extend_from_slice(&(data.len() as u32).to_le_bytes()); + v.extend_from_slice(data); + let total = v.len() as u32; + v[24..28].copy_from_slice(&total.to_le_bytes()); + v + } + + /// What a Mac host is not handed: a container without a PC program (the test title's + /// console PS: one `XBOX` part of RDNA2 code) or no container at all. The DXBC stand-in is + /// a PC program. + #[test] + fn host_shader_takes_pc_programs_only() { + assert!(host_shader(&dummy().ps), "the DXBC stand-in"); + assert!(host_shader(&dummy().vs), "the DXBC stand-in VS"); + let rdna2 = [0x01, 0x03, 0x80, 0xbe, 0x01, 0x05, 0x0a, 0x06, 0x00, 0x00, 0x81, 0xbf]; + assert!(!host_shader(&container(b"XBOX", &rdna2)), "a console container"); + assert!(!host_shader(&rdna2), "raw RDNA2 code"); + assert!(!host_shader(&[]), "nothing"); + } +} + #[cfg(test)] mod cache_report_tests { use super::*; @@ -5507,11 +5860,8 @@ mod readback_routing_tests { let mut orig_vt = [0usize; 32]; orig_vt[23] = fake_copy_ranges as usize; orig_vt[24] = fake_copy_simple as usize; - let ext_vt = [orig_vt.as_ptr() as usize, 0usize]; - let mut dev = FakeDev { - // SAFETY: `ext_vt` has 2 entries; `.add(1)` puts `orig_vt` at `ext[-1]`. - vt: unsafe { ext_vt.as_ptr().add(1) }, - }; + let (_ext_vt, ext) = test_ext_table(&orig_vt); + let mut dev = FakeDev { vt: ext }; let dev_ptr = &mut dev as *mut FakeDev as *mut c_void; SIMPLE_TYPES.with(|v| v.borrow_mut().clear()); @@ -5603,8 +5953,9 @@ mod queue_tests { let mut pc = [0usize; 32]; pc[14] = signal as usize; pc[18] = get_desc as usize; - let ext = [pc.as_ptr() as usize, 0]; - let vtbl = ext.as_ptr() as usize + 8; + let mut ext = [0usize; HDR + 1]; + ext[0] = pc.as_ptr() as usize; + let vtbl = ext.as_ptr() as usize + 8 * HDR; let mut obj = [vtbl]; let this = obj.as_mut_ptr() as *mut c_void; let fence = 0x5EED_0000usize; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 91b8a2e0d..666c44c76 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -185,7 +185,10 @@ fn decommit_tiles( } } } - if !unmapped.is_empty() { + // (a long list is pruned where it is used, `live_zero_runs`: a title that maps a pool of + // 99,776 pages page by page left ten thousands of partly empty tiles, and a scan of them for + // every tile that became empty kept its loading thread here for minutes) + if !unmapped.is_empty() && to_zero.len() <= 256 { to_zero.retain(|&(za, _)| mapped.contains_key(&(za & !(TILE - 1)))); } unmapped @@ -482,6 +485,89 @@ fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { } } +/// XCL's queue, fences and upload lists on `dev` for `windows` (window start, its buffer). +unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) -> windows::core::Result<State> { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; + let mut slots = Vec::with_capacity(UPLOAD_SLOTS); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; + rb_list.Close()?; + Ok(State { + dev: dev.clone(), + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + windows, + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + zero_buf: None, + slots, + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + }) +} + +/// pool heap number of the tiles of a shadowed window: they are the window's own buffer, not +/// pool tiles (never mapped, freed or pinned) +const SHADOW_POOL: u32 = u32::MAX; + +/// A committed window the GPU could not open as a heap (`real::open_uma`): `buf` in video +/// memory stands for `[base, base + size)` and is kept in step like the tiles of a sparse +/// window – the CPU's writes (write-watch, changed 64-byte chunks) go to it before each +/// ExecuteCommandLists, GPU writes come back on Map and after the lists' memory operations. +/// All of it counts as mapped from the start: the window is committed. False: no queue for +/// the copies (the buffer then never sees the CPU's writes). +pub unsafe fn shadow_window(dev: &ID3D12Device, base: usize, size: usize, buf: &ID3D12Resource) -> bool { + let mut g = STATE.lock().unwrap(); + if g.is_none() { + // no sparse window was made (`init`): the copies still need the queue and the lists + match new_state(dev, Vec::new()) { + Ok(s) => *g = Some(s), + Err(e) => { + crate::xlog_warn!("shadowed window at {base:#x}: {e}"); + return false; + } + } + } + let Some(s) = g.as_mut() else { return false }; + s.windows.push((base, buf.clone())); + for (i, t) in (base..base + size).step_by(TILE).enumerate() { + s.mapped.insert(t, TileEntry::with_holes((SHADOW_POOL, i as u32), 0)); + } + s.runs = None; + MAPPED_GEN.fetch_add(1, Ordering::Release); + true +} + /// The sparse windows' buffers on `dev`: `(window_index, buffer_raw, gpu_va)` for each /// sparse window in `gpu::uma` (empty: no sparse windows). pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { @@ -502,9 +588,6 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { out.push((k, r.clone().into_raw() as usize, r.GetGPUVirtualAddress())); windows.push((base, r)); } - if out.is_empty() { - return out; - } let made = (|| -> windows::core::Result<State> { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; @@ -1263,7 +1346,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { if s.window_index(va).is_none() { return; } - let zeroed = std::mem::take(&mut s.to_zero); + let zeroed = s.live_zero_runs(); if !zeroed.is_empty() { for &(a, n) in &zeroed { s.clear_sent_range(a, n); @@ -1311,6 +1394,18 @@ pub unsafe fn committed(a: usize, n: usize) { s.commit_range(a, n); } +/// Whether the 4 KiB page at `a` of a sparse window is committed, from what `committed` and +/// `decommitted` were told (None: no windows on the GPU, nothing was noted). Wine's +/// VirtualQuery walks the pages to the end of the run with the same state, which in a window +/// with gigabytes reserved took 0.4 ms a call – 99,776 physical pages mapped in two minutes. +pub fn page_committed(a: usize) -> Option<bool> { + let g = STATE.lock().unwrap(); + let s = g.as_ref()?; + s.window_index(a)?; + let t = a & !(TILE - 1); + Some(s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << ((a - t) / PAGE)) == 0)) +} + /// The title decommitted `[a, a + n)`: tiles whose pages are all uncommitted (whether in one /// full-tile decommit or incrementally via sub-tile decommits) give their video memory back /// (unless a placed buffer still pins the pool tile). @@ -1328,6 +1423,13 @@ pub unsafe fn decommitted(a: usize, n: usize) { } impl State { + /// The ranges to clear, without those of tiles that lost their video memory since. + fn live_zero_runs(&mut self) -> Vec<(usize, usize)> { + let mut runs = std::mem::take(&mut self.to_zero); + runs.retain(|&(za, _)| self.mapped.contains_key(&(za & !(TILE - 1)))); + runs + } + /// `committed` with the state locked unsafe fn commit_range(&mut self, a: usize, n: usize) { self.ensure_mapped(a, n, |_| 0xFFFF); @@ -1456,7 +1558,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } let t_locked = std::time::Instant::now(); PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); - let zero_runs = std::mem::take(&mut s.to_zero); + let zero_runs = s.live_zero_runs(); for &(a, n) in &zero_runs { s.clear_sent_range(a, n); } @@ -1569,6 +1671,7 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D for &(_, tile) in &tiles { *s.pinned.entry(tile).or_default() += 1; } + s.forget_gone(); s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); s.signal(); Some((hr, delta)) @@ -1576,15 +1679,42 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D /// A placed buffer is gone: its tiles are not pinned by it any more. pub fn forget_buffer(res: usize) { - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { return }; - let Some(tiles) = s.buffers.remove(&res) else { return }; - for tile in tiles { - if let Some(c) = s.pinned.get_mut(&tile) { - *c -= 1; - if *c == 0 { - s.pinned.remove(&tile); - s.release_if_unused(tile); + // A release can come from inside a call the holder of the state's lock is making (a host + // that releases its own references through the object's table – Apple's D3DMetal – does it + // when a list of XCL's own is reset or executed): never wait for the lock here. What could + // not be forgotten at once is forgotten by the next holder (`State::forget_gone`). + match STATE.try_lock() { + Ok(mut g) => { + if let Some(s) = g.as_mut() { + s.forget_gone(); + s.forget(res); + } + } + Err(std::sync::TryLockError::WouldBlock) => GONE.lock().unwrap().push(res), + Err(std::sync::TryLockError::Poisoned(_)) => {} + } +} + +/// buffers released while the state was locked +static GONE: Mutex<Vec<usize>> = Mutex::new(Vec::new()); + +impl State { + fn forget_gone(&mut self) { + let gone = std::mem::take(&mut *GONE.lock().unwrap()); + for res in gone { + self.forget(res); + } + } + + fn forget(&mut self, res: usize) { + let Some(tiles) = self.buffers.remove(&res) else { return }; + for tile in tiles { + if let Some(c) = self.pinned.get_mut(&tile) { + *c -= 1; + if *c == 0 { + self.pinned.remove(&tile); + self.release_if_unused(tile); + } } } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cba..50ce0b70e 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -38,16 +38,18 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address its bytes are read from, layout, states) of an upload +/// (device, the title's address – its bytes are read through `TitleMemory` –, layout, states) +/// of an upload type Upload = (usize, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>); struct Entry { device: usize, /// the title's address of the texture va: usize, - /// where its bytes are read and its CPU writes watched: `va`, or – for a texture in a GPU - /// view of the title's CPU memory with nothing mapped there – the same offset in the CPU - /// view (`kernelx::mirrors`) + /// where its CPU writes are watched: `va`, or – for a texture in a GPU view of the title's + /// CPU memory with nothing mapped there – the same offset in the CPU view + /// (`kernelx::mirrors`). Its bytes are read page by page (`TitleMemory`): the command + /// queue's page mappings come before this pairing src: usize, /// `va` lies in a GPU view: `src` is checked again when that view's mappings change in_gpu_view: bool, @@ -67,6 +69,29 @@ struct Entry { unmapped: bool, /// monotonic registration order (newest wins when uncovering shadowed textures) seq: u64, + /// its memory is not write-watched (ordinary memory of the title – its heaps, pages it maps + /// itself; on a host where graphics memory by protection stays the system's, `kernelx`): + /// CPU writes are found by content (`poll_unwatched`) + unwatched: bool, + /// `memory_hash` of the memory at the last upload (unwatched textures) + sent: u64, + /// the present count when the content last changed (unwatched: it is looked at before + /// every submit for a while after) + changed: u64, + /// its content changed after the first upload (unwatched: a texture the CPU keeps writing + /// – a glyph cache, a video plane – is looked at every frame from then on) + dynamic: bool, + /// the title unmapped it since the last look (unwatched: it is compared before the next + /// submit – what was written while it was mapped goes up then; a texture the title only + /// read through the pointer, a target the GPU wrote, is the same as before and stays as it + /// is). No more than that: a retail game maps its glyph cache once, unmaps it and writes + /// through the pointer for the rest of the run. + cpu_unmapped: bool, + /// the title mapped it at least once: one it means to write (unwatched: these have a turn + /// of their own until their content first changes) + mapped: bool, + /// the present count when it was made (unwatched: young textures have a turn of their own) + made: u64, } /// textures waiting for their first upload @@ -369,6 +394,16 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); + let size = tex.size() as usize; + let unwatched = !is_watched(src, size); + if unwatched { + note_unwatched(res, src, size); + } else if trace_unwatched() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 300 { + crate::xlog_info!("title texture trace: texture at {va:#x}, {size} bytes – write-watched, frame {}", frame_now()); + } + } let e = Entry { device: device as usize, va, @@ -381,6 +416,13 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, placed: super::vram::is_placed_texture(res as usize), unmapped: false, seq: 0, + unwatched, + sent: 0, + changed: 0, + dynamic: false, + cpu_unmapped: false, + mapped: false, + made: frame_now(), }; let to_unmap = { let mut t = TEXTURES.lock().unwrap(); @@ -443,6 +485,7 @@ fn recheck_source(e: &mut Entry) -> bool { return false; } e.src = src; + e.unwatched = !is_watched(src, e.tex.size() as usize); if !e.pending { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); @@ -468,6 +511,21 @@ pub fn note_gpu_write(res: usize) { static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); +/// The title unmapped texture `res` (`Map` gave it the texture's place in its memory, +/// `real::res_map`): one it means to write. In memory that is not write-watched it is compared +/// before the next submit and has its turn among the mapped from now on (`pick`). +pub fn note_unmap(res: usize) { + let mut t = TEXTURES.lock().unwrap(); + let Some(e) = t.get_mut(res) else { return }; + e.mapped = true; + e.cpu_unmapped = true; + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if trace_unwatched() && (k < 60 || k.is_power_of_two()) { + crate::xlog_info!("title texture trace: Unmap #{k} of the texture at {:#x} ({} bytes), frame {}", e.va, e.tex.size(), frame_now()); + } +} + /// The textures kept in step whose memory `[va, va + len)` overlaps (PC texture, its address). pub fn overlapping(va: usize, len: usize) -> Vec<(usize, usize)> { TEXTURES.lock().unwrap().overlapping(va, len) @@ -746,12 +804,15 @@ unsafe fn refresh_once(queue: *mut c_void) { super::vram::before_execute(q); }); } + // textures in memory that is not write-watched: by content + let mut todo = poll_unwatched(); if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 { + upload_all(todo); return; } // textures made since the last submit and those with a written page; a reference each // while they are uploaded - let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { + let first: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); t.by_res @@ -760,7 +821,7 @@ unsafe fn refresh_once(queue: *mut c_void) { if e.pending { return true; } - if e.gpu_written { + if e.gpu_written || e.unwatched { return false; } let i = dirty.partition_point(|&p| p + page as usize <= e.src); @@ -770,12 +831,19 @@ unsafe fn refresh_once(queue: *mut c_void) { if e.pending { e.pending = false; PENDING.fetch_sub(1, Ordering::Relaxed); + if e.unwatched { + // what goes up now is what later looks compare with + e.sent = memory_hash(e.va, e.tex.size() as usize); + } } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); + // (a texture in both lists goes once) + todo.retain(|(r, _)| !first.iter().any(|(f, _)| f.as_raw() == r.as_raw())); + todo.extend(first); upload_all(todo); } @@ -783,10 +851,19 @@ unsafe fn refresh_once(queue: *mut c_void) { static LAST_CONTENT: Mutex<BTreeMap<usize, u64>> = Mutex::new(BTreeMap::new()); static UNCHANGED: AtomicU64 = AtomicU64::new(0); -/// `XCL_TEXTURE_SKIP_UNCHANGED=0` uploads a texture whenever its pages were written, as before. +/// `XCL_TEXTURE_SKIP_UNCHANGED=0` uploads a texture whenever its pages were written, as before; +/// `=1` leaves unchanged ones out. Unset: left out everywhere but on a Mac (`util::mac_host`). +/// There a retail game's frame is one flat grey from its first picture on with the skip (the +/// sign-in screen, the video, every menu) and as it should be without – seen in two runs of +/// one build; which upload it is that must go up again with the same bytes is not known. Little +/// is lost there: textures in memory that is not write-watched – all of the title's own on that +/// host – go up when their content changed (`poll_unwatched`), not when a page was written. fn unchanged_skip() -> bool { static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_TEXTURE_SKIP_UNCHANGED").map_or(true, |v| v.trim() != "0")) + *ON.get_or_init(|| match std::env::var("XCL_TEXTURE_SKIP_UNCHANGED") { + Ok(v) => v.trim() != "0", + Err(_) => !crate::util::mac_host(), + }) } /// Whether texture `res` was last uploaded from memory with hash `h`; `h` is remembered as its @@ -814,14 +891,304 @@ fn content_hash(b: &[u8]) -> u64 { h.iter().fold(tail, |a, &l| (a ^ l).wrapping_mul(K).rotate_left(27)) } +/// The count of presented frames (the clock of `poll_unwatched`). +fn frame_now() -> u64 { + super::present::counters().1 +} + +/// Whether `[va, va + size)` lies in write-watched memory (a unified-memory window or one of the +/// title's graphics reservations): `GetWriteWatch` finds the CPU's writes there. +fn is_watched(va: usize, size: usize) -> bool { + let Some(u) = crate::gpu::uma::get() else { return false }; + let inside = |&(b, n): &(usize, usize)| b <= va && va + size <= b + n; + u.watch_regions().iter().any(inside) || crate::hle::kernelx::graphics_reservations().iter().any(inside) +} + +/// `XCL_TRACE_TITLE_TEXTURES=1`: every texture in memory that is not write-watched and every +/// upload after a change of its content is logged (the first 2000 / 600), and every 256th +/// look's totals. +pub(super) fn trace_unwatched() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("XCL_TRACE_TITLE_TEXTURES").is_some()) +} + +fn note_unwatched(res: *mut c_void, va: usize, size: usize) { + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k == 0 { + crate::xlog_info!("title texture: textures in memory that is not write-watched (first at {va:#x}, {size} bytes) are compared with what was last uploaded before the title's submits"); + } + if trace_unwatched() && k < 2000 { + let d = unsafe { ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()) }; + crate::xlog_info!( + "title texture trace: #{k} at {va:#x}, {size} bytes, {:?} (dimension, width, height, depth / array, mips, format, flags) – not write-watched, frame {}", + d.map(|d| (d.Dimension.0, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format.0, d.Flags.0)), + frame_now() + ); + } +} + +/// A texture is looked at before every submit for this many presented frames after its content +/// last changed (a glyph cache while a page comes up, a streamed texture being filled). +const HOT_FRAMES: u64 = 16; +/// bytes of such textures compared before one submit at most (the rest wait their turn) +const HOT_BYTES: usize = 64 << 20; +/// bytes of the textures that never changed compared before one submit, in turn (at least one +/// texture): one is looked at again after (their bytes / this) submits – with a retail game's +/// front end, 970 MiB in 815 textures, after about 160 frames. There are three turns of this +/// size: the textures the title mapped (it means to write them: a glyph cache is found within +/// a few frames of its first glyphs), those made in the last `YOUNG_FRAMES` frames (one filled +/// after it was made shows sooner), and the rest. +const TURN_BYTES: usize = 2 << 20; +const YOUNG_FRAMES: u64 = 300; +/// A texture in a GPU view of the title's memory (a page pool's: streamed textures) whose +/// content changed is looked at once a frame for this many presented frames after its last +/// change, then in turn again: what fills these is streaming (a few writes, then none), and a +/// front end has hundreds of MiB of them. +const POOL_FRAMES: u64 = 60; + +/// What `pick` needs of a texture in memory that is not write-watched. +#[derive(Clone, Copy)] +struct Seen { + /// its key in `TEXTURES` (the turns go by it) + key: usize, + size: usize, + dynamic: bool, + mapped: bool, + /// unmapped since the last look + now: bool, + changed: u64, + made: u64, + /// placed in a GPU view of the title's memory (streamed textures: `POOL_FRAMES`) + pool: bool, +} + +/// The textures of `all` (ascending keys) to compare before this submit, as indices: those +/// just unmapped or whose content changed in the last `HOT_FRAMES` frames (a GPU view's: in +/// this frame only – once a frame is what streaming needs); at a frame's first submit (`new_frame`) those +/// that ever changed (a GPU view's: in the last `POOL_FRAMES` frames, `poll_unwatched`); and +/// of each turn (`cursors`: the key each stopped at) the next `TURN_BYTES`, at least one texture. +fn pick(all: &[Seen], frame: u64, new_frame: bool, cursors: &mut [usize; 3]) -> Vec<usize> { + let mut look = Vec::new(); + let mut hot_bytes = 0usize; + // (the rest, the young, the mapped) + let mut turns: [Vec<usize>; 3] = [Vec::new(), Vec::new(), Vec::new()]; + for (i, e) in all.iter().enumerate() { + let turn = if e.mapped { + 2 + } else if frame.saturating_sub(e.made) < YOUNG_FRAMES { + 1 + } else { + 0 + }; + // (a GPU view's: for the rest of the frame it changed in – what is written in two steps + // within a frame is complete at its last submit –, then once a frame) + let hot = e.dynamic && if e.pool { e.changed == frame } else { frame.saturating_sub(e.changed) < HOT_FRAMES }; + if e.now || hot || (e.dynamic && new_frame) { + if e.now || hot_bytes + e.size <= HOT_BYTES { + hot_bytes += e.size; + look.push(i); + } else { + turns[turn].push(i); + } + } else if !e.dynamic { + turns[turn].push(i); + } + } + for (turn, cursor) in turns.iter().zip(cursors.iter_mut()) { + let start = turn.partition_point(|&i| all[i].key <= *cursor); + let mut bytes = 0usize; + for k in 0..turn.len() { + let i = turn[(start + k) % turn.len()]; + if k > 0 && bytes + all[i].size > TURN_BYTES { + break; + } + bytes += all[i].size; + *cursor = all[i].key; + look.push(i); + } + } + look +} + +/// A hash of `len` bytes at `at` for telling a change: four chains of 64-bit words (each step a +/// bijection of its chain, so a change within one word always shows). The bytes are the ones an +/// upload reads (`TitleMemory`): in a GPU view the page the GPU's mapping or the CPU view has +/// there, else the address itself; what is nowhere (not committed, not readable, a view with no +/// page) counts by its length only – an upload reads it as zero. +unsafe fn memory_hash(at: usize, len: usize) -> u64 { + memory_hash_in(&mut TitleMemory::new(), at, len) +} + +#[cfg(test)] +pub(super) unsafe fn memory_hash_for_tests(at: usize, len: usize) -> u64 { + memory_hash(at, len) +} + +/// `memory_hash` with the places of memory found so far (`memory`): one look at many textures +/// asks Windows about a region once. +unsafe fn memory_hash_in(memory: &mut TitleMemory, at: usize, len: usize) -> u64 { + const K: u64 = 0x9E37_79B9_7F4A_7C15; + let mut l = [K, K.rotate_left(13), K.rotate_left(29), K.rotate_left(47)]; + let mut p = at; + while p < at + len { + let (src, same) = memory.locate(p); + let n = same.min(at + len - p); + if src != 0 { + let b = std::slice::from_raw_parts(src as *const u8, n); + let mut chunks = b.chunks_exact(32); + for c in &mut chunks { + for (i, lane) in l.iter_mut().enumerate() { + let w = u64::from_le_bytes(c[8 * i..8 * i + 8].try_into().unwrap()); + *lane = (*lane ^ w).wrapping_mul(K).rotate_left(29); + } + } + for (i, &x) in chunks.remainder().iter().enumerate() { + l[i & 3] = (l[i & 3] ^ x as u64).wrapping_mul(K).rotate_left(29); + } + } else { + l[0] = (l[0] ^ n as u64 ^ 0x5555).wrapping_mul(K).rotate_left(29); + } + p += n; + } + let mut h = l[0]; + for x in &l[1..] { + h = (h.rotate_left(23) ^ x).wrapping_mul(K); + } + h ^ h >> 31 +} + +/// looks of `poll_unwatched` that compared something, the bytes they hashed, the time that took +/// and the uploads that followed a change +static LOOKS: AtomicU64 = AtomicU64::new(0); +static HASHED: AtomicU64 = AtomicU64::new(0); +static NANOS: AtomicU64 = AtomicU64::new(0); +static CHANGED: AtomicU64 = AtomicU64::new(0); + +/// What keeping title textures in step cost since this was last asked (the frame rate's log +/// line asks every 300 frames), as text: the content comparison (looks, MiB hashed, ms, uploads +/// after a change) and all uploads (MiB, ms). +pub fn cost_since_last() -> String { + static LAST: Mutex<[u64; 6]> = Mutex::new([0; 6]); + let l = |a: &AtomicU64| a.load(Ordering::Relaxed); + let now = [l(&LOOKS), l(&HASHED), l(&NANOS), l(&CHANGED), l(&UPLOAD_BYTES), l(&UPLOAD_NANOS)]; + let mut last = LAST.lock().unwrap(); + let d: Vec<u64> = now.iter().zip(last.iter()).map(|(n, o)| n.saturating_sub(*o)).collect(); + *last = now; + format!("{} looks compared {} MiB in {} ms ({} changed); uploads {} MiB in {} ms", d[0], d[1] >> 20, d[2] / 1_000_000, d[3], d[4] >> 20, d[5] / 1_000_000) +} + +/// Textures in memory that is not write-watched whose content differs from what was last +/// uploaded. Those that changed in the last `HOT_FRAMES` frames are compared before every +/// submit (what a list of this submit samples is complete by now – on the console the GPU reads +/// the same memory); those that ever changed after their first upload before the first submit +/// of every frame; the others in turn (`pick`). +unsafe fn poll_unwatched() -> Vec<(ID3D12Resource, Upload)> { + static LAST_FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static UNWATCHED: AtomicU64 = AtomicU64::new(0); + static CURSORS: Mutex<[usize; 3]> = Mutex::new([0; 3]); + let frame = frame_now(); + let new_frame = LAST_FRAME.swap(frame, Ordering::Relaxed) != frame; + // (texture, address, bytes, hash last sent) + let (look, count, total): (Vec<(usize, usize, usize, u64)>, usize, usize) = { + let mut t = TEXTURES.lock().unwrap(); + let mut all: Vec<Seen> = Vec::new(); + let mut places: Vec<(usize, u64)> = Vec::new(); + for (&res, e) in t.by_res.iter_mut() { + let now = std::mem::take(&mut e.cpu_unmapped); + if !e.unwatched || e.pending || e.gpu_written { + continue; + } + let size = e.tex.size() as usize; + let pool = e.in_gpu_view || super::gpu_views::in_range(e.va, size); + if pool && e.dynamic && frame.saturating_sub(e.changed) >= POOL_FRAMES { + // streamed in and quiet since: back to its turn + e.dynamic = false; + } + all.push(Seen { key: res, size, dynamic: e.dynamic, mapped: e.mapped, now, changed: e.changed, made: e.made, pool }); + places.push((e.va, e.sent)); + } + let picked = pick(&all, frame, new_frame, &mut CURSORS.lock().unwrap()); + (picked.into_iter().map(|i| (all[i].key, places[i].0, all[i].size, places[i].1)).collect(), all.len(), all.iter().map(|e| e.size).sum()) + }; + UNWATCHED.store(count as u64, Ordering::Relaxed); + if look.is_empty() { + return Vec::new(); + } + let t0 = std::time::Instant::now(); + let mut changed: Vec<(usize, u64)> = Vec::new(); + let mut hashed = 0usize; + let mut memory = TitleMemory::new(); + for &(res, va, size, sent) in &look { + let h = memory_hash_in(&mut memory, va, size); + hashed += size; + if h != sent { + changed.push((res, h)); + } + } + HASHED.fetch_add(hashed as u64, Ordering::Relaxed); + NANOS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed); + let looks = LOOKS.fetch_add(1, Ordering::Relaxed) + 1; + if trace_unwatched() && looks % 256 == 0 { + crate::xlog_info!( + "title texture trace: {looks} looks at textures in unwatched memory ({count} textures, {} KiB): {} MiB compared in {} ms, {} uploads after a change; all uploads {} MiB in {} ms; frame {frame}", + total >> 10, + HASHED.load(Ordering::Relaxed) >> 20, + NANOS.load(Ordering::Relaxed) / 1_000_000, + CHANGED.load(Ordering::Relaxed), + UPLOAD_BYTES.load(Ordering::Relaxed) >> 20, + UPLOAD_NANOS.load(Ordering::Relaxed) / 1_000_000 + ); + } + if changed.is_empty() { + return Vec::new(); + } + let mut t = TEXTURES.lock().unwrap(); + changed + .into_iter() + .filter_map(|(res, h)| { + let e = t.get_mut(res)?; + if e.gpu_written { + return None; + } + e.sent = h; + e.changed = frame; + e.dynamic = true; + let k = CHANGED.fetch_add(1, Ordering::Relaxed); + let p = res as *mut c_void; + let r = ID3D12Resource::from_raw_borrowed(&p)?.clone(); + if trace_unwatched() && (k < 600 || k.is_power_of_two()) { + let d = r.GetDesc(); + crate::xlog_info!("title texture trace: content of the texture at {:#x} ({}x{} format {}, {} bytes) changed – upload #{k}, frame {frame}", e.va, d.Width, d.Height, d.Format.0, e.tex.size()); + } + Some((r, (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + }) + .collect() +} + /// staging bytes of one batch at most const BATCH_BYTES: usize = 256 << 20; /// The uploads `todo`, in batches of up to `BATCH_BYTES` (one list and one wait each). unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { static N: AtomicU64 = AtomicU64::new(0); + if todo.is_empty() { + return; + } + let t0 = std::time::Instant::now(); + UPLOAD_BYTES.fetch_add(todo.iter().map(|(_, u)| u.2.size()).sum::<u64>(), Ordering::Relaxed); + upload_batches(todo, &N); + UPLOAD_NANOS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed); +} + +/// bytes of title memory uploaded as textures and the time that took (detiling, the copy, the +/// wait for the GPU) +static UPLOAD_BYTES: AtomicU64 = AtomicU64::new(0); +static UPLOAD_NANOS: AtomicU64 = AtomicU64::new(0); + +unsafe fn upload_batches(todo: Vec<(ID3D12Resource, Upload)>, warned: &AtomicU64) { let warn = |e: &str| { - if N.fetch_add(1, Ordering::Relaxed) < 4 { + if warned.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("title texture: upload failed: {e}"); } }; @@ -916,7 +1283,7 @@ pub unsafe fn probe_gpu_content(res: usize) { } g.push(res); } - let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.device, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; + let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.device, e.va, Arc::clone(&e.tex), e.gpu_written)) else { return }; let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; @@ -1082,9 +1449,9 @@ unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { } /// `len` bytes at `at`: the committed, readable pages copied, the rest zero (a streaming pool -/// has only some of its pages mapped). +/// has only some of its pages mapped). An address in a GPU view of the title's memory, where +/// the CPU has nothing, gives what the GPU sees there (`TitleMemory`). unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> { - use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; let mut out = vec![0u8; len]; let Some(limit) = at.checked_add(len) else { return out }; // (the coherent window is committed as a whole: no `VirtualQuery`, which sizes a region by @@ -1093,22 +1460,7 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> { std::ptr::copy_nonoverlapping(at as *const u8, out.as_mut_ptr(), len); return out; } - let mut p = at; - while p < limit { - let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); - if VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { - break; - } - let end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(limit); - if end <= p { - break; - } - let readable = m.State == MEM_COMMIT && m.Protect & 0xEE != 0 && m.Protect & 0x100 == 0; // R / RW / WC / X-R…, no guard - if readable { - copy_committed_region(p, out.as_mut_ptr().add(p - at), end - p); - } - p = end; - } + TitleMemory::new().read(at, out.as_mut_ptr(), len); out } @@ -1166,6 +1518,169 @@ unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> } } +/// `len` bytes of the title's memory at `at` as the GPU would see them (`TitleMemory`: a GPU +/// view's pages where the CPU has them), zeros where there is nothing, and whether all of it +/// was there. +pub(super) unsafe fn read_memory(at: usize, len: usize) -> (Vec<u8>, bool) { + let mut out = vec![0u8; len]; + let all = TitleMemory::new().read(at, out.as_mut_ptr(), len); + (out, all) +} + +/// Whether a title texture the GPU wrote lies over `[va, va + len)`: the memory there is stale. +pub(super) fn gpu_written_over(va: usize, len: usize) -> bool { + TEXTURES.lock().unwrap().by_res.values().any(|e| e.gpu_written && e.va < va + len && va < e.va + e.tex.size() as usize) +} + +/// Where a 64 KiB page of title memory is read. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Place { + /// at its own address, as far as Windows has readable memory there + Own, + /// the whole page at another address (a GPU view's page where the CPU has it) + At(usize), + /// a GPU view's page with no memory anywhere: zeros + Nowhere, +} + +/// How the pages of GPU views were found (`TitleMemory::place`), as indices of `VIEW_READS`. +const BY_QUEUE_SAME: usize = 0; +const BY_QUEUE_OTHER: usize = 1; +const BY_QUEUE_EMPTY: usize = 2; +const BY_PAIR: usize = 3; +const BY_OWN: usize = 4; +const BY_NONE: usize = 5; + +/// page reads of GPU views by how the page was found (a page read again counts again) +static VIEW_READS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; +/// GPU-view page → how it was last found +static VIEW_PAGES: Mutex<BTreeMap<usize, u8>> = Mutex::new(BTreeMap::new()); + +/// How the 64 KiB pages of GPU views that title textures were read from were found so far, as +/// text: by the command queue's page mappings (`gpu_views`) – at the address the paired CPU +/// view has for them, at another, or with no memory yet –, by the pairing of the two +/// reservations alone (`kernelx::mirrors`), at the view's own address, or nowhere. Distinct +/// pages by how they were last found, and all page reads. None: no such page was read. +pub fn view_sources() -> Option<String> { + let mut pages = [0u64; 6]; + for &k in VIEW_PAGES.lock().unwrap().values() { + pages[k as usize] += 1; + } + if pages.iter().all(|&n| n == 0) { + return None; + } + let r = |k: usize| VIEW_READS[k].load(Ordering::Relaxed); + Some(format!( + "queue mappings {} page(s) where the paired CPU view has them, {} elsewhere, {} with no memory; pairing alone {}; mapped at the view itself {}; nothing {} (page reads: {} / {} / {} / {} / {} / {})", + pages[0], pages[1], pages[2], pages[3], pages[4], pages[5], r(0), r(1), r(2), r(3), r(4), r(5) + )) +} + +/// Bytes of the title's memory for an upload or a comparison. In a GPU view of the title's +/// memory (addresses the CPU never has anything at: a retail game places its streamed textures +/// and video planes there) a 64 KiB page is read +/// 1. where the CPU has the physical page the command queue's page mappings show there +/// (`gpu_views`: what the title told the GPU, page by page), +/// 2. else at the address itself if a page is mapped there, +/// 3. else at the same offset of the CPU view the reservation is paired with +/// (`kernelx::mirrors`: the two reservations are made together and most pages are mapped +/// at the same offset in both – not all: GPU-only mappings, pages the CPU has elsewhere). +/// Any other address is read where it is, as far as it is readable. What was last found is +/// kept – a row is a fraction of a page, and asking Windows about an address in a reservation +/// of gigabytes is slow (it measures the whole region). +struct TitleMemory { + /// the 64 KiB page last asked for and its place + page: (usize, Place), + /// the region Windows last described for an address itself: [start, end), readable + direct: (usize, usize, bool), + /// the same for the place of a view's page + source: (usize, usize, bool), +} + +impl TitleMemory { + const PAGE: usize = crate::hle::kernelx::PHYS_PAGE_SIZE; + + fn new() -> TitleMemory { + TitleMemory { page: (usize::MAX, Place::Own), direct: (0, 0, false), source: (0, 0, false) } + } + + /// The region around `a` (kept in `cache`): its end and whether it can be read. + unsafe fn region(cache: &mut (usize, usize, bool), a: usize) -> (usize, bool) { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + if a < cache.0 || a >= cache.1 { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + *cache = if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 { + // R / RW / WC / X-R…, no guard + (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize, m.State == MEM_COMMIT && m.Protect & 0xEE != 0 && m.Protect & 0x100 == 0) + } else { + (a & !0xFFF, (a & !0xFFF) + 0x1000, false) + }; + } + (cache.1, cache.2) + } + + /// The place of the 64 KiB page at `page` (see the type). + unsafe fn place(&mut self, page: usize) -> Place { + let mapped = super::gpu_views::lookup(page); + let paired = crate::hle::kernelx::mirrors::source(page); + if mapped.is_none() && paired.is_none() { + return Place::Own; + } + // (a view's page is whole: 64 KiB the title mapped at once) + let whole = |m: &mut TitleMemory, a: usize| { + let (end, ok) = Self::region(&mut m.source, a); + ok && end >= a + Self::PAGE + }; + let (place, how) = match mapped { + Some(Some(at)) if whole(self, at) => (Place::At(at), if paired == Some(at) { BY_QUEUE_SAME } else { BY_QUEUE_OTHER }), + Some(_) => (Place::Nowhere, BY_QUEUE_EMPTY), + None if Self::region(&mut self.direct, page).1 => (Place::Own, BY_OWN), + None => match paired { + Some(at) if whole(self, at) => (Place::At(at), BY_PAIR), + _ => (Place::Nowhere, BY_NONE), + }, + }; + VIEW_READS[how].fetch_add(1, Ordering::Relaxed); + VIEW_PAGES.lock().unwrap().insert(page, how as u8); + place + } + + /// Where the byte at `at` is read (0: nowhere) and how many bytes from it are in the same + /// place (at least 1). + unsafe fn locate(&mut self, at: usize) -> (usize, usize) { + let page = at & !(Self::PAGE - 1); + if self.page.0 != page { + self.page = (page, self.place(page)); + } + match self.page.1 { + Place::At(src) => (src + (at - page), page + Self::PAGE - at), + Place::Nowhere => (0, page + Self::PAGE - at), + Place::Own => { + let (end, ok) = Self::region(&mut self.direct, at); + (if ok { at } else { 0 }, end.min(page + Self::PAGE).max(at + 1) - at) + } + } + } + + /// `n` bytes at `at` to `dst`; what is nowhere stays as `dst` has it. Returns whether all + /// of it was read. + unsafe fn read(&mut self, mut at: usize, mut dst: *mut u8, mut n: usize) -> bool { + let mut all = true; + while n > 0 { + let (src, same) = self.locate(at); + let chunk = n.min(same); + match src { + 0 => all = false, + src => std::ptr::copy_nonoverlapping(src as *const u8, dst, chunk), + } + at += chunk; + dst = dst.add(chunk); + n -= chunk; + } + all + } +} + /// Every subresource (D3D12 order) of a texture from the title's memory at `va`. unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec<Subresource> { let Some(tex) = tex.texels() else { return Vec::new() }; @@ -1233,6 +1748,19 @@ mod tests { crate::gpu::recomp::runner::skip_test("no GPU"); return; } + unsafe { + if let Ok(factory) = windows::Win32::Graphics::Dxgi::CreateDXGIFactory1::<windows::Win32::Graphics::Dxgi::IDXGIFactory4>() { + if let Ok(adapter) = factory.EnumAdapters1(0) { + if adapter.GetDesc1().is_ok_and(|d| { + d.Flags & windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 + || String::from_utf16_lossy(&d.Description).contains("Basic Render Driver") + }) { + crate::gpu::recomp::runner::skip_test("software adapter"); + return; + } + } + } + } // Larger than all four UMA windows together. These public allocations // must use the watched Windows fallback, reserving space rather than RAM. const SIZE: usize = 24usize << 30; @@ -1264,7 +1792,8 @@ mod tests { assert_ne!(at, 0, "reserve-only fallback must succeed"); let reservation = Reservation(at); assert!(!crate::gpu::uma::get().unwrap().contains(at), "exercise the Windows fallback"); - assert!(kernelx::in_graphics_reservation(at), "fallback must be write-watched"); + // (where the fallback is write-watched at all: not on a Mac, `kernelx::watched_fallback`) + assert!(kernelx::in_graphics_reservation(at) || !kernelx::watched_fallback(), "fallback must be write-watched"); reservation } unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec<u8> { @@ -1340,7 +1869,10 @@ mod tests { assert!(kernelx::physical_page_at(va)); let mut info: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); assert_ne!(mem::VirtualQuery(va as *const c_void, &mut info, std::mem::size_of_val(&info)), 0); - assert_eq!(info.State, mem::MEM_RESERVE, "exercise the lazy mapping before its first touch"); + // (where pages are committed on first use: not on a Mac, `kernelx::lazy::enabled`) + if kernelx::lazy::enabled() { + assert_eq!(info.State, mem::MEM_RESERVE, "exercise the lazy mapping before its first touch"); + } assert_eq!(mirror_source(va), va, "a mapped lazy page overrides the CPU mirror"); refresh(queue.as_raw()); assert_eq!(read_r8(dev, &queue, &texture), vec![0; 64 * 64], "the untouched physical page supplies zeros"); @@ -1385,7 +1917,7 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0 }; + let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0 }; assert_eq!(e.src, cpu + 0x2_0000); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); @@ -1439,6 +1971,64 @@ mod tests { } } + /// A page of a GPU view is read where the command queue's page mapping shows it; only + /// without one at the same offset of the paired CPU view. (A retail game maps most pages + /// at the same offset in both – and some only for the GPU, from where they are in the pool.) + #[test] + fn a_gpu_view_page_is_read_by_the_queues_mapping_before_the_pairing() { + use crate::hle::kernelx::{self, AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE as PAGE}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + const VIEW: usize = 16 << 20; + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let pool = VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + let cpu = VirtualAlloc(std::ptr::null(), VIEW, MEM_RESERVE, PAGE_READWRITE) as usize; + let gpu = VirtualAlloc(std::ptr::null(), VIEW, MEM_RESERVE, PAGE_NOACCESS) as usize; + kernelx::mirrors::reserved(cpu, VIEW, 0x2040_2000, 0x04); + kernelx::mirrors::reserved(gpu, VIEW, 0x2040_2000, 0x801); + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 2, 0, 4, pages.as_mut_ptr()) as usize, pool); + *((pool + PAGE + 8) as *mut u32) = 0xB0B0_0001; // pool page 1, where it is in the pool + // pool page 0 for the CPU at page 2 of its view + let mut one = [pages[0]]; + assert_eq!(MapTitlePhysicalPages((cpu + 2 * PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, cpu + 2 * PAGE); + *((cpu + 2 * PAGE + 8) as *mut u32) = 0xA0A0_0000; + let read = |at: usize| { + let mut v = 0u32; + let all = TitleMemory::new().read(at, &mut v as *mut u32 as *mut u8, 4); + (v, all) + }; + // no mapping by the queue: the pairing + assert_eq!(read(gpu + 2 * PAGE + 8), (0xA0A0_0000, true)); + assert_eq!(read(gpu + 3 * PAGE + 8), (0, false), "nothing in either view"); + assert_eq!(read_committed(gpu + 2 * PAGE, 16)[8..12], 0xA0A0_0000u32.to_le_bytes()); + // the queue maps pool page 1 at page 2 of the GPU view and pool page 0 at page 3 + let ranges = [[1u32, 1, 1], [1, 0, 1]]; + let batch: [usize; 3] = [gpu + 2 * PAGE, 2, ranges.as_ptr() as usize]; + super::super::gpu_views::update(1, batch.as_ptr() as *const u8, pool, 2); + assert_eq!(read(gpu + 2 * PAGE + 8), (0xB0B0_0001, true), "the queue's mapping, not the CPU view's page"); + assert_eq!(read(gpu + 3 * PAGE + 8), (0xA0A0_0000, true), "a page the CPU has at another offset"); + let before = memory_hash(gpu + 2 * PAGE, 2 * PAGE); + *((pool + PAGE + 0x100) as *mut u8) = 1; + assert_ne!(before, memory_hash(gpu + 2 * PAGE, 2 * PAGE), "a write where the page is shows"); + // unmapped by the queue: the pairing again + let ranges = [[2u32, 0, 2]]; + let batch: [usize; 3] = [gpu + 2 * PAGE, 1, ranges.as_ptr() as usize]; + super::super::gpu_views::update(1, batch.as_ptr() as *const u8, pool, 2); + assert_eq!(read(gpu + 2 * PAGE + 8), (0xA0A0_0000, true)); + assert_eq!(read(gpu + 3 * PAGE + 8), (0, false)); + let mut none = [0usize]; + MapTitlePhysicalPages((cpu + 2 * PAGE) as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + kernelx::mirrors::released(cpu); + for r in [pool, cpu, gpu] { + VirtualFree(r as *mut c_void, 0, MEM_RELEASE); + } + } + } + const SRV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; static TEST_LOCK: Mutex<()> = Mutex::new(()); @@ -1483,7 +2073,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); @@ -1539,6 +2129,134 @@ mod tests { } } + fn seen(key: usize, size: usize) -> Seen { + Seen { key, size, dynamic: false, mapped: false, now: false, changed: 0, made: 0, pool: false } + } + + /// Textures that never changed are all looked at within about (their bytes / `TURN_BYTES`) + /// submits, a texture larger than a turn included. + #[test] + fn every_unchanged_texture_gets_its_turn() { + let all: Vec<Seen> = (0..200).map(|k| seen(0x1000 + k, if k == 7 { 5 << 20 } else { 300 << 10 })).collect(); + let total: usize = all.iter().map(|e| e.size).sum(); + let mut cursors = [0usize; 3]; + let mut seen_at = vec![0usize; all.len()]; + let looks = total / TURN_BYTES + all.len(); + let mut picked = 0; + for look in 1..=looks { + for i in pick(&all, 1000, look % 3 == 1, &mut cursors) { + if seen_at[i] == 0 { + seen_at[i] = look; + picked += 1; + } + } + if picked == all.len() { + break; + } + } + assert_eq!(picked, all.len(), "all looked at"); + let last = *seen_at.iter().max().unwrap(); + // (a submit takes whole textures: at least a turn less one of them) + assert!(last <= total / (TURN_BYTES - (300 << 10)) + 2, "after {last} submits for {} MiB", total >> 20); + // one submit compares one turn's bytes (or its one large texture) + let n: usize = pick(&all, 1000, false, &mut cursors).iter().map(|&i| all[i].size).sum(); + assert!(n <= TURN_BYTES.max(5 << 20)); + } + + /// A texture whose content changed is looked at before every submit for `HOT_FRAMES` + /// frames, then before each frame's first submit; one the title mapped is found in its own + /// turn however many others wait; the young have theirs. + #[test] + fn changed_mapped_and_young_textures_come_first() { + let mut all: Vec<Seen> = (0..500).map(|k| seen(0x1000 + k, 2 << 20)).collect(); + all[300].dynamic = true; + all[300].changed = 990; + all[450].mapped = true; // a glyph cache: mapped once, never changed so far + all[451].mapped = true; + all[20].made = 900; // made 100 frames ago + let mut cursors = [0usize; 3]; + let frame = 1000; + // hot: every submit + for new_frame in [true, false, false] { + assert!(pick(&all, frame, new_frame, &mut cursors).contains(&300)); + } + // the two mapped textures alternate: each within two submits + let a = pick(&all, frame, false, &mut cursors); + let b = pick(&all, frame, false, &mut cursors); + assert!(a.contains(&450) != a.contains(&451)); + assert!(a.contains(&450) != b.contains(&450)); + // the young one: every submit (it is the only one in its turn) + assert!(a.contains(&20) && b.contains(&20)); + // no longer hot: the first submit of a frame only + let later = frame + HOT_FRAMES + 50; + assert!(pick(&all, later, true, &mut cursors).contains(&300)); + assert!(!pick(&all, later, false, &mut cursors).contains(&300)); + // a changed texture is not in a turn as well + assert_eq!(pick(&all, later, true, &mut cursors).iter().filter(|&&i| i == 300).count(), 1); + // one just unmapped: before this submit, whatever else waits, and once + all[77].now = true; + assert_eq!(pick(&all, later, false, &mut cursors).iter().filter(|&&i| i == 77).count(), 1); + } + + /// A GPU view's texture that changed (streamed in) is looked at once a frame, not before + /// every submit; one that never changed has its turn like any other. + #[test] + fn a_gpu_views_changed_texture_is_looked_at_once_a_frame() { + let mut all: Vec<Seen> = (0..500).map(|k| seen(0x1000 + k, 2 << 20)).collect(); + for e in all.iter_mut() { + e.pool = true; + } + all[300].dynamic = true; + all[300].changed = 999; + let mut cursors = [0usize; 3]; + assert!(pick(&all, 1000, true, &mut cursors).contains(&300)); + assert!(!pick(&all, 1000, false, &mut cursors).contains(&300)); + assert!(!pick(&all, 1000, false, &mut cursors).contains(&300)); + assert!(pick(&all, 1001, true, &mut cursors).contains(&300)); + // changed in this frame: before its later submits too + all[300].changed = 1001; + assert!(pick(&all, 1001, false, &mut cursors).contains(&300)); + all[300].changed = 999; + // the others: one turn's bytes a submit + let n = pick(&all, 1001, false, &mut cursors).len(); + assert_eq!(n, 1); + } + + /// More changed textures than `HOT_BYTES`: the rest are looked at in their turn. + #[test] + fn hot_textures_over_the_limit_wait_their_turn() { + let mut all: Vec<Seen> = (0..40).map(|k| seen(0x1000 + k, 4 << 20)).collect(); + for e in all.iter_mut() { + e.dynamic = true; + e.changed = 100; + } + let mut cursors = [0usize; 3]; + let mut got = vec![false; all.len()]; + for _ in 0..40 { + let p = pick(&all, 101, false, &mut cursors); + assert!(p.iter().map(|&i| all[i].size).sum::<usize>() <= HOT_BYTES + (4 << 20)); + p.into_iter().for_each(|i| got[i] = true); + } + assert!(got.iter().all(|&g| g)); + } + + /// The content hash tells a change of one byte anywhere and reads what it is given. + #[test] + fn memory_hash_tells_a_one_byte_change() { + let mut m = vec![0u8; 3 * 4096 + 37]; + for (i, b) in m.iter_mut().enumerate() { + *b = (i * 31 >> 3) as u8; + } + let h = unsafe { memory_hash(m.as_ptr() as usize, m.len()) }; + assert_eq!(h, unsafe { memory_hash(m.as_ptr() as usize, m.len()) }); + for at in [0usize, 1, 31, 32, 4095, 4096, 8191, m.len() - 38, m.len() - 1] { + m[at] ^= 0x10; + assert_ne!(h, unsafe { memory_hash(m.as_ptr() as usize, m.len()) }, "byte {at}"); + m[at] ^= 0x10; + } + assert_ne!(h, unsafe { memory_hash(m.as_ptr() as usize, m.len() - 1) }); + } + /// Only the wanted parts of the watched regions are scanned, merged, one region each. #[test] fn watch_ranges_clip_and_merge() { @@ -1615,6 +2333,13 @@ mod tests { placed, unmapped: false, seq: 0, + unwatched: false, + sent: 0, + changed: 0, + dynamic: false, + cpu_unmapped: false, + mapped: false, + made: 0, }; let mut tbl = Table::new(); // Two adjacent placed 16 KiB textures + one placed 64 KiB texture after them. @@ -1666,7 +2391,10 @@ mod tests { println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: no adapter"); return; }; - if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + if adapter.GetDesc1().is_ok_and(|d| { + d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 + || String::from_utf16_lossy(&d.Description).contains("Basic Render Driver") + }) { println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: software adapter"); return; } @@ -1701,6 +2429,10 @@ mod tests { println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: no UMA"); return; }; + if !super::super::vram::on_pages() { + println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: title textures are not on shared pages on this host (XCL_VRAM_ARENAS)"); + return; + } let pool_size = 16usize << 20; let Some(base) = uma.alloc(pool_size, 0x1_0000).map(|p| p as usize) else { println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: UMA alloc failed"); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 8b806d5f8..01d367f9e 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -629,6 +629,27 @@ fn tier2(dev: &ID3D12Device) -> bool { unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.ResourceHeapTier.0 >= 2 } } +/// Whether title textures are tried as reserved resources on shared pages (GPU-owned targets +/// first, kept-in-step textures at all): `XCL_VRAM_ARENAS=1` – never, `=0` – always; unset: +/// everywhere but on a native host (Apple's D3DMetal). That one reports tiled resources tier 2 +/// and aliases placed and reserved *buffers*, but two reserved textures mapped to the same tiles +/// do not show each other's contents there (measured: 512 of 512 rows differ), and what Metal +/// cannot make is not an error code: the process ends on an assertion. Arenas (placed resources +/// in heaps) and committed textures are known to work. +pub(super) fn on_pages() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("XCL_VRAM_ARENAS") { + Ok(v) => v.trim() == "0", + Err(_) => { + let native = crate::gpu::shader::NATIVE_HOST_MEMORY.load(std::sync::atomic::Ordering::Relaxed); + if native { + crate::xlog_info!("D3D12.X: GPU-owned textures in title memory: arenas on this host (XCL_VRAM_ARENAS=0 tries tiled resources on pages)"); + } + !native + } + }) +} + /// A sampled texture of the title at `va` (`desc`: the PC description, `console_bytes` its size on /// the console) backed by shared 64 KiB video-memory pages; None when reserved placement is not /// available (the caller falls back to a committed resource). @@ -644,7 +665,9 @@ pub unsafe fn place_pages( ppv: *mut *mut c_void, ) -> Option<HRESULT> { let dev = ID3D12Device::from_raw_borrowed(&this)?; - if !tier2(dev) || std::env::var_os("XCL_VRAM_ARENAS").is_some() { + // (not on a native host unless asked, `on_pages`: there two reserved textures on the same + // pages do not show each other's contents – the caller's committed texture is used) + if !tier2(dev) || !on_pages() { return None; } place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, riid, ppv) @@ -659,7 +682,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st if !tier2(dev) { return None; } - if std::env::var_os("XCL_VRAM_ARENAS").is_none() { + if on_pages() { if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, riid, ppv) { return Some(hr); } diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2a6300541..68219b1fd 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -230,6 +230,13 @@ fn bcpack_fill_from_env() -> bool { std::env::var("XCL_DSTORAGE_BCPACK_FILL").is_ok_and(|v| !v.trim().is_empty() && v.trim() != "0") } +/// `XCL_DSTORAGE_BCPACK_ACCEPT=1`: a refused BCPack request whose destination was filled with +/// solid blocks is marked as completed (S_OK) rather than E_DECOMPRESSION, so title preconditions +/// (e.g. `cmp byte ptr [rsp+0x34], 1; jne 0x23cf683`) pass and world generation continues. +fn bcpack_accept_from_env() -> bool { + std::env::var("XCL_DSTORAGE_BCPACK_ACCEPT").is_ok_and(|v| !v.trim().is_empty() && v.trim() != "0") +} + /// BC1 colour block: both endpoints magenta (565 `0xF81F`), every index 0. const BC1_MAGENTA: [u8; 8] = [0x1F, 0xF8, 0x1F, 0xF8, 0, 0, 0, 0]; /// BC4 block: both endpoints 255, every index 0. @@ -846,6 +853,16 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us pages }; if !crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &payload[..n]) { + // (the pages as they were when the request was made: the title's array may hold others by now) + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!( + "DirectStorage: {n} bytes (page offset {}) could not be written to its {} page(s) – the first: {}", + r.destination_page_offset, + pages.len(), + pages.first().map_or("none".to_string(), |&p| crate::hle::kernelx::describe_physical_page(p)) + ); + } return Err(E_ACCESS_VIOLATION); } } else if n > 0 { @@ -935,11 +952,41 @@ struct QueueInner { errors: Mutex<(u32, Option<FirstError>)>, /// `XCL_DSTORAGE_BCPACK_FILL` when the queue was made bcpack_fill: AtomicBool, + /// `XCL_DSTORAGE_BCPACK_ACCEPT` when the queue was made + bcpack_accept: AtomicBool, } impl QueueInner { fn fail(&self, hr: HRESULT, request: Request, file: Option<&FileInner>) { FAILED.fetch_add(1, Ordering::Relaxed); + // a destination (or source) the request could not use: what that memory is – a title that + // streams into address space XCL gave it wrongly fails here and nowhere else + if hr == E_ACCESS_VIOLATION { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let known = unsafe { VirtualQuery(request.destination as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; + let uma = crate::gpu::uma::get(); + crate::xlog_warn!( + "DirectStorage: access violation: options {:#x}, destination {:#x}{} ({} bytes, page offset {}): {} – state {:#x}, protect {:#x}, allocated with {:#x}, region {:#x}+{:#x}; unified memory window {:?}, sparse {}, graphics reservation {}", + request.options, + request.destination, + if request.dest_physical_pages() { " (a page array)" } else { "" }, + request.destination_size, + request.destination_page_offset, + if known { "memory there" } else { "nothing known there" }, + m.State, + m.Protect, + m.AllocationProtect, + m.AllocationBase as usize, + m.RegionSize, + uma.and_then(|u| u.window_of(request.destination as usize)), + uma.is_some_and(|u| u.is_sparse(request.destination as usize)), + crate::hle::kernelx::in_graphics_reservation(request.destination as usize) + ); + + } + } let mut e = self.errors.lock().unwrap(); e.0 += 1; if e.1.is_none() { @@ -1024,13 +1071,18 @@ impl QueueInner { } } Entry::Refused { hr, req, file, fill } => { + let mut ok = false; if let Some(t) = &fill { - // the destination gets solid blocks; the request still fails - unsafe { bcpack_fill(&req, t) }; + let filled = unsafe { bcpack_fill(&req, t) }; + if filled && self.bcpack_accept.load(Ordering::Relaxed) { + ok = true; + } } - self.fail(hr, req, file.as_deref()); - if since_status >= 0 { - since_status = hr; + if !ok { + self.fail(hr, req, file.as_deref()); + if since_status >= 0 { + since_status = hr; + } } } Entry::Status(s, i) => { @@ -1155,6 +1207,7 @@ unsafe extern "system" fn factory_create_queue(_p: *mut c_void, desc: *const u8, error_event: ev as usize, errors: Mutex::new((0, None)), bcpack_fill: AtomicBool::new(bcpack_fill_from_env()), + bcpack_accept: AtomicBool::new(bcpack_accept_from_env()), }); let o = new_object(queue_vtbl(), inner); let hr = queue_qi(o, riid, out); @@ -1201,7 +1254,7 @@ unsafe extern "system" fn queue_enqueue_request(p: *mut c_void, req: *const u8) let mut fill = None; if hr == E_DECOMPRESSION && r.bcpack() != 0 { log_bcpack_refusal(&r, BCPACK.note(&r)); - if q.bcpack_fill.load(Ordering::Relaxed) { + if q.bcpack_fill.load(Ordering::Relaxed) || q.bcpack_accept.load(Ordering::Relaxed) { fill = if !r.dest_physical_pages() { Some(FillTarget::Virtual) } else { @@ -2283,6 +2336,10 @@ mod tests { assert!(dst[..n].chunks(16).all(|c| c == &block[..c.len()]), "solid BC7 blocks up to the destination size"); assert!(dst[n..].iter().all(|&b| b == 0xCD), "nothing past the destination size"); assert!(BCPACK.filled_bytes[7].load(Ordering::Relaxed) >= before + n as u64); + + queue(q).bcpack_accept.store(true, Ordering::Relaxed); + assert_eq!(run(&mut dst, n as u32, 0), S_OK, "under bcpack_accept the request completes with S_OK"); + queue_close(q); queue_release(q); status_release(s); diff --git a/crates/xcl/src/hle/gameinput.rs b/crates/xcl/src/hle/gameinput.rs index 402d4c712..e7aa26353 100644 --- a/crates/xcl/src/hle/gameinput.rs +++ b/crates/xcl/src/hle/gameinput.rs @@ -259,7 +259,48 @@ fn scripted() -> u32 { }); // seconds since the host started, as the log's times (not since the title first polled) let t = crate::log::uptime(); - at.iter().filter(|&&(s, _)| t >= s && t < s + 0.2).fold(0, |b, &(_, g)| b | g) + at.iter().filter(|&&(s, _)| t >= s && t < s + 0.2).fold(0, |b, &(_, g)| b | g) | remote() +} + +/// `XCL_REMOTE_INPUT=<file>`: buttons written to that file ("A", "DOWN A", names as +/// `XCL_PRESS_AT`'s) are held for 250 ms each time the file changes – a running title driven +/// from outside (a script, another program) without its window having the focus. +fn remote() -> u32 { + use std::sync::Mutex; + use std::time::{Duration, Instant, SystemTime}; + struct R { + checked: Instant, + seen: Option<SystemTime>, + buttons: u32, + until: Instant, + } + static PATH: OnceLock<Option<String>> = OnceLock::new(); + static STATE: Mutex<Option<R>> = Mutex::new(None); + let Some(path) = PATH.get_or_init(|| std::env::var("XCL_REMOTE_INPUT").ok().filter(|p| !p.trim().is_empty())) else { return 0 }; + let now = Instant::now(); + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let r = g.get_or_insert_with(|| R { + checked: now - Duration::from_secs(1), + // what is in the file when the title starts is not a press + seen: std::fs::metadata(path).and_then(|m| m.modified()).ok(), + buttons: 0, + until: now, + }); + if now.duration_since(r.checked) >= Duration::from_millis(50) { + r.checked = now; + let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok(); + if modified.is_some() && modified != r.seen { + r.seen = modified; + let text = std::fs::read_to_string(path).unwrap_or_default(); + let b = text.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).filter_map(|s| button_named(&s.to_ascii_uppercase())).fold(0, |b, g| b | g); + if b != 0 { + r.buttons = b; + r.until = now + Duration::from_millis(250); + crate::xlog_info!("GameInput: remote input {:?} → buttons {b:#x}", text.trim()); + } + } + } + if now < r.until { r.buttons } else { 0 } } #[link(name = "user32")] @@ -280,7 +321,15 @@ unsafe fn keyboard() -> u32 { return 0; } const KEYS: [(i32, u32); 10] = [(0x0D, A), (0x20, A), (0x1B, B), (0x08, B), (0x26, DPAD_UP), (0x28, DPAD_DOWN), (0x25, DPAD_LEFT), (0x27, DPAD_RIGHT), (0x09, VIEW), (0x50, MENU)]; - KEYS.iter().filter(|(k, _)| GetAsyncKeyState(*k) as u16 & 0x8000 != 0).fold(0, |b, (_, g)| b | g) + let down = KEYS.iter().filter(|(k, _)| GetAsyncKeyState(*k) as u16 & 0x8000 != 0).fold(0, |b, (_, g)| b | g); + if down != 0 && !super::kbm::input_is_ours() { + // background mode: keys typed while the window has not been clicked are someone's + // work in another program + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_info!("GameInput: keys are down ({down:#x}) but the window has not been clicked – ignored (XCL_BACKGROUND)")); + return 0; + } + down } /// Merge host keyboard/mouse input (only when `keyboard_mouse` is enabled) and scripted diff --git a/crates/xcl/src/hle/kbm.rs b/crates/xcl/src/hle/kbm.rs index 6d18b1cfb..8242397e1 100644 --- a/crates/xcl/src/hle/kbm.rs +++ b/crates/xcl/src/hle/kbm.rs @@ -183,6 +183,23 @@ struct RawMouseInput { const WM_INPUT: u32 = 0x00FF; const WM_ACTIVATE: u32 = 0x0006; +const WM_KILLFOCUS: u32 = 0x0008; +const WM_ACTIVATEAPP: u32 = 0x001C; +const WM_MOUSEACTIVATE: u32 = 0x0021; +const WM_NCLBUTTONDOWN: u32 = 0x00A1; + +/// Background mode: whether a person has clicked the XCL window since it last lost the +/// activation. Under Wine on macOS a window shown without activation is still the +/// foreground window as Windows sees it, and the async key state follows the whole machine's +/// keyboard – keys typed in other programs would play the title. So in that mode the keyboard +/// and the mouse count only between a click on the window and its deactivation. +static CLICKED: AtomicBool = AtomicBool::new(false); + +/// Whether keyboard and mouse input belongs to the title now (always, outside background mode: +/// the foreground-window test of the callers decides there). +pub fn input_is_ours() -> bool { + !background() || CLICKED.load(Ordering::Acquire) +} const WM_SETCURSOR: u32 = 0x0020; const WM_SIZE: u32 = 0x0005; const WM_MOVE: u32 = 0x0003; @@ -265,7 +282,15 @@ pub fn attach(hwnd: *mut c_void) { ); } +/// `XCL_BACKGROUND=1`: the window opens without taking the focus and never holds the cursor +/// (a run someone only looks at now and then, while working in other programs). +pub fn background() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_BACKGROUND").is_ok_and(|v| v.trim() == "1")) +} + unsafe fn hold_cursor(hwnd: *mut c_void, on: bool) { + let on = on && !background(); // a drag/resize loop owns the cursor: clipping it to the window's centre would teleport // it back on every WM_MOVE of the drag if on && SIZING.load(Ordering::Acquire) { @@ -300,6 +325,13 @@ pub unsafe fn on_message(hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> b if WINDOW.load(Ordering::Acquire) != hwnd as isize { return false; } + match msg { + WM_MOUSEACTIVATE | WM_LBUTTONDOWN | WM_NCLBUTTONDOWN => CLICKED.store(true, Ordering::Release), + WM_KILLFOCUS => CLICKED.store(false, Ordering::Release), + WM_ACTIVATE if wp & 0xFFFF == 0 => CLICKED.store(false, Ordering::Release), + WM_ACTIVATEAPP if wp == 0 => CLICKED.store(false, Ordering::Release), + _ => {} + } match msg { WM_INPUT => { let mut raw = RawMouseInput::default(); @@ -394,7 +426,7 @@ pub fn apply(s: &mut GamepadState) { return; } let hwnd = WINDOW.load(Ordering::Acquire); - let focused = hwnd != 0 && unsafe { GetForegroundWindow() } as isize == hwnd; + let focused = hwnd != 0 && unsafe { GetForegroundWindow() } as isize == hwnd && input_is_ours(); if !focused { // Alt+Tab, another window: the cursor is free, nothing is pressed // SAFETY: `hold_cursor(..., false)` only releases the cursor clip when captured. diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 8aa3bc200..ce44d3316 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -48,6 +48,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { XMemAllocDefault, XMemFreeDefault, XMemSetAllocationHooks, + CreateThread, XMemVirtualQuery, XMemVirtualAlloc, XMemAllocatePhysicalPages, @@ -55,6 +56,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { XMemMapPhysicalPagesScatter, XMemFreePhysicalPages, XMemTransferMemory, + XMemIsToolsMemAvailable, XMemGetWorkingSetStatistics, TitleMemoryStatus, JobTitleMemoryStatus, @@ -303,7 +305,8 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: // the GPU reads where it is – one copy (a retail game's 4.4 GB; as plain memory its shaders // read zeros, in the sparse windows video memory would have doubled them). The window is as // large as what the title asked for last time (`uma::coherent_hint`). - if addr.is_null() && t & 0x1000 != 0 && p & PAGE_GRAPHICS_ANY != 0 && size <= crate::gpu::uma::MAX_SIZE && std::env::var("XCL_COHERENT_HEAPS").map_or(true, |v| v != "0") { + // Not on a Mac unless `XCL_COHERENT_HEAPS=1` (`coherent_heaps`). + if addr.is_null() && t & 0x1000 != 0 && p & PAGE_GRAPHICS_ANY != 0 && size <= crate::gpu::uma::MAX_SIZE && coherent_heaps() { static ASKED: AtomicUsize = AtomicUsize::new(0); let asked = ASKED.fetch_add(size, Ordering::Relaxed) + size; crate::gpu::uma::note_coherent_need(asked); @@ -325,11 +328,14 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: // (`d3d12x::title_textures`), which needs its CPU writes to be seen: it is write-watched // like a graphics reservation. Without that such a texture was uploaded once, empty, and // never again (the game's glyph atlas: its menus lost their x-height letters). + // Not write-watched on a Mac unless `XCL_WATCHED_FALLBACK=1` (`watched_fallback`): textures + // there are compared by content (`title_textures::poll_unwatched`). if gpu_visible_fallback(addr, t, p) { - let q = reserve_watched(size, t, p); + let watched = watched_fallback(); + let q = if watched { reserve_watched(size, t, p) } else { mem::VirtualAlloc(std::ptr::null(), size, sanitize_alloc_type(t), sanitize_protect(p)) }; if !q.is_null() { mirrors::reserved(q as usize, size, t, p); - trace_mem("VirtualAlloc (GPU-visible, write-watched)", addr as usize, size, t as u64, p, q as usize); + trace_mem(if watched { "VirtualAlloc (GPU-visible, write-watched)" } else { "VirtualAlloc (GPU-visible, plain)" }, addr as usize, size, t as u64, p, q as usize); return q; } } @@ -357,6 +363,37 @@ unsafe fn reserve_watched(size: usize, t: u32, p: u32) -> *mut c_void { q } +/// Whether GPU-visible title memory that reaches the plain-memory fallback is write-watched: +/// `XCL_WATCHED_FALLBACK=1` / `0`, else everywhere but on a Mac (`util::mac_host`). The title's +/// heaps and its 24 GB of 64 KiB pages are in that memory, written with AVX2 masked stores, +/// and Wine keeps a write watch by protecting pages: Rosetta cannot resume such a store after +/// its fault (as with `coherent_heaps`). Textures there are compared by content instead +/// (`title_textures::poll_unwatched`); a GPU view is still paired with its CPU view (`mirrors`). +pub(crate) fn watched_fallback() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("XCL_WATCHED_FALLBACK") { + Ok(v) => v.trim() != "0", + Err(_) => !crate::util::mac_host(), + }) +} + +/// Whether the title's GPU heaps go to the coherent window: `XCL_COHERENT_HEAPS=1` / `0`, else +/// everywhere but on a Mac (`util::mac_host`). There the window is not the GPU's memory (D3DMetal +/// has no `OpenExistingHeapFromAddress`): it has a copy in video memory, kept in step through the +/// window's write watch – which Wine keeps by protecting pages, and Rosetta cannot resume an AVX2 +/// masked store that faults (a retail game keeps its heaps in this memory: its first vectorised +/// array fill, `vpmaskmovd [rax], ymm7, ymm6` at image +0x1d6f0a2, stopped the process 5 s into +/// the run when that memory was in a sparse window – "rosetta error: unexpectedly need to +/// EmulateForward on a synchronous exception"). The heaps are plain memory there, as they were: +/// index and vertex buffers in them are mirrored (`list_x::gpu_va`), buffer views get an empty V#. +fn coherent_heaps() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("XCL_COHERENT_HEAPS") { + Ok(v) => v.trim() != "0", + Err(_) => !crate::util::mac_host(), + }) +} + /// PAGE_GRAPHICS_NOACCESS … PAGE_GRAPHICS_NOCACHE (0x800 – 0x40000): the console's protection of /// GPU-visible memory const PAGE_GRAPHICS_ANY: u32 = 0x7_F800; @@ -443,9 +480,12 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 return 1; } let ok = mem::VirtualFree(addr, size, t); - if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { - GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + if ok != 0 && t & 0x8000 != 0 { + // (a GPU-visible reservation that is not write-watched is paired too, `watched_fallback`) mirrors::released(addr as usize); + if GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + } } ok } @@ -474,6 +514,20 @@ pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_voi mem::VirtualProtectEx(proc_, addr, size, sanitize_protect(p), old) } +/// Smallest stack a title thread gets. Console titles ask for stacks sized for the console's +/// own D3D12 (1 MiB here); on a PC a pipeline creation on the title's thread also runs XCL's +/// shader translation and the host driver's compiler (Apple's D3DMetal converts shaders on the +/// calling thread), and overflowed it. +pub const MIN_TITLE_STACK: usize = 16 << 20; + +/// kernel32!CreateThread for the title: the stack size becomes a reservation of at least +/// `MIN_TITLE_STACK`. +pub unsafe extern "system" fn CreateThread(sa: *const c_void, stack: usize, start: usize, param: *const c_void, flags: u32, tid: *mut u32) -> HANDLE { + const STACK_SIZE_PARAM_IS_A_RESERVATION: u32 = 0x1_0000; + let (stack, flags) = if stack < MIN_TITLE_STACK { (MIN_TITLE_STACK, flags | STACK_SIZE_PARAM_IS_A_RESERVATION) } else { (stack, flags) }; + windows_sys::Win32::System::Threading::CreateThread(sa as *const _, stack, std::mem::transmute::<usize, windows_sys::Win32::System::Threading::LPTHREAD_START_ROUTINE>(start), param, flags, tid) +} + /// XALLOC_ATTRIBUTES bit fields. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct XAllocAttrs { @@ -810,9 +864,46 @@ struct Away { /// homes in a sparse window whose pages went away in this call, given back at its end in /// runs (`give_back_homes`): one page at a time, a retail game's start took 20 s gone: Vec<usize>, + /// addresses in a sparse window that got a page in this call, told to `d3d12x::sparse` at + /// its end in runs (`tell_arrived`): a tile mapping per page on the GPU made a retail game's + /// 99,776 pages take minutes + arrived: Vec<usize>, + /// address → page for the views a page was mapped at before the title mapped it somewhere + /// else: on the console a page shows at every address it is mapped at, here only at the last + /// one (the earlier ones are decommitted). What is asked by one of those addresses (a page + /// pool's page by its place in the pool, `d3d12x::gpu_views`) is found through this. An + /// entry goes when its address is mapped again or unmapped, or its page is freed. + ghost: std::collections::HashMap<usize, usize>, } static AWAY: std::sync::Mutex<Option<Away>> = std::sync::Mutex::new(None); +/// The physical page (its number) the title mapped at the 64 KiB page of `view`: the one that +/// is there now, or the last one that was there before the title mapped it somewhere else +/// (on the console it would still show there). +pub fn page_of_view(view: usize) -> Option<usize> { + let v = view & !(PHYS_PAGE - 1); + let g = AWAY.lock().unwrap(); + let a = g.as_ref()?; + a.at.get(&v).or_else(|| a.ghost.get(&v)).copied() +} + +/// The page (its number) whose data is at the 64 KiB page of `addr` now, if the title mapped +/// one there (pages at their homes are not looked for). +pub fn page_at(addr: usize) -> Option<usize> { + AWAY.lock().unwrap().as_ref()?.at.get(&(addr & !(PHYS_PAGE - 1))).copied() +} + +/// Where the data of physical page `page` is now: the address the title last mapped it at, or +/// its home while that has memory (None: a page never used, or not a live page). +pub fn page_address(page: usize) -> Option<usize> { + let g = AWAY.lock().unwrap(); + if let Some(&at) = g.as_ref().and_then(|a| a.page.get(&page)) { + return Some(at); + } + drop(g); + page_home(page).filter(|&h| committed_page(h)) +} + /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { @@ -861,6 +952,24 @@ fn lazy_home(home: usize) -> bool { crate::gpu::uma::get().is_none_or(|u| u.is_sparse(home) || !u.contains(home)) } +/// A physical page number for a log line: its index, the block it is of, its home and where +/// it is mapped (what `resolve_physical_pages` goes by). +pub fn describe_physical_page(page: usize) -> String { + let Some(index) = page_index(page) else { return format!("{page:#x}: not a page number") }; + let block = PHYS_BLOCKS.lock().ok().and_then(|b| b.range(..=index).next_back().map(|(&first, &(count, live, home))| (first, count, live, home))); + let away = AWAY.try_lock().ok().and_then(|g| g.as_ref().and_then(|a| a.page.get(&page).copied())); + match block { + Some((first, count, live, home)) if index < first + count => format!( + "{page:#x}: page {} of a block of {count} ({live} allocated) with homes from {home:#x}; mapped at {}; home committed: {}", + index - first, + away.map_or("its home".to_string(), |a| format!("{a:#x}")), + page_home(page).is_some_and(committed_page) + ), + Some((first, count, ..)) => format!("{page:#x}: index {index} is past the block before it ({first} + {count})"), + None => format!("{page:#x}: index {index} is in no block"), + } +} + /// Resolve the live virtual addresses of the physical pages covering `offset..offset+len`. /// Caller must hold `AWAY`. unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option<Vec<usize>> { @@ -960,6 +1069,24 @@ unsafe fn give_back_homes(away: &mut Away) { } } +/// The addresses in a sparse window that got pages get video memory, in runs of neighbours. +unsafe fn tell_arrived(away: &mut Away) { + let mut at = std::mem::take(&mut away.arrived); + at.sort_unstable(); + at.dedup(); + let mut i = 0; + while i < at.len() { + let start = at[i]; + let mut end = start + PHYS_PAGE; + i += 1; + while i < at.len() && at[i] == end { + end += PHYS_PAGE; + i += 1; + } + crate::hle::d3d12x::sparse::committed(start, end - start); + } +} + /// The page's home, committed again if `move_home_away` gave it back (None: it could not be). unsafe fn home_again(home: usize) -> Option<usize> { if lazy_home(home) && !committed_page(home) { @@ -1025,6 +1152,9 @@ struct StateRun { /// `committed_page`, remembering in `run` the state of the pages around `a`. fn committed_page_in(a: usize, run: &mut StateRun) -> bool { + if let Some(c) = crate::hle::d3d12x::sparse::page_committed(a) { + return c; + } if (run.start..run.end).contains(&a) { return run.committed; } @@ -1076,6 +1206,7 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range<usi } // (an address among the homes the caller maps back is one of them: it stays) if !committed.contains(&at) { + away.arrived.retain(|&a| a != at); release_at(at); } true @@ -1173,6 +1304,10 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: note_mapping_at(at); } } + if !away.ghost.is_empty() { + let freed: std::collections::HashSet<usize> = (0..n).map(|i| *arr.add(i)).collect(); + away.ghost.retain(|_, p| !freed.contains(p)); + } } let mut g = PHYS_BLOCKS.lock().unwrap(); for i in 0..n { @@ -1203,6 +1338,7 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ let away = g.get_or_insert_with(Away::default); let r = map_pages(away, va, n, arr); give_back_homes(away); + tell_arrived(away); r } @@ -1236,6 +1372,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) for &p in &pages { if let Some(&at) = away.page.get(&p) { unmap_away(away, at, &(home..home + n * PHYS_PAGE)); + away.ghost.insert(at, p); } } return home as *mut c_void; @@ -1257,10 +1394,12 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); } + away.ghost.remove(&at); if p == 0 { continue; } if let Some(&old) = away.page.get(&p) { + away.ghost.insert(old, p); // (a move commits `at` and decommits `old`, which may lie in a run already answered: // both runs go – #556) match move_away(away, old, at, p, in_uma(at)) { @@ -1287,9 +1426,13 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) away.page.insert(p, at); continue; } - if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { - fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); - return std::ptr::null_mut(); + if !in_uma(at) { + let mut old = 0; + let _ = mem::VirtualProtect(at as *const c_void, PHYS_PAGE, mem::PAGE_READWRITE, &mut old); + if mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return std::ptr::null_mut(); + } } if committed_page(home) { std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); @@ -1300,7 +1443,11 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) std::ptr::write_bytes(at as *mut u8, 0, PHYS_PAGE); // a page never used: zeros } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); + away.arrived.push(at); + // (in runs of 256 MB, so a page unmapped again in the same call is found quickly) + if away.arrived.len() >= 4096 { + tell_arrived(away); + } } away.at.insert(at, p); away.page.insert(p, at); @@ -1314,15 +1461,24 @@ pub unsafe extern "system" fn XMemAllocatePhysicalPages(_attrs: u64, num: *mut u AllocateTitlePhysicalPages(std::mem::zeroed(), 0, num, arr as *mut usize) } +/// `BOOL XMemIsToolsMemAvailable()`: whether the tools pool of a development kit is there. A +/// retail game stops at an int3 on FALSE (exe+0x2215fe0, before it reads its working-set +/// statistics); there is one budget here, so the tools' part of it is available. +pub unsafe extern "system" fn XMemIsToolsMemAvailable() -> BOOL { + 1 +} + /// `void* XMemMapPhysicalPages(void* address, SIZE_T count, ULONG64* pages)` pub unsafe extern "system" fn XMemMapPhysicalPages(va: *mut c_void, n: usize, arr: *mut u64) -> *mut c_void { MapTitlePhysicalPages(va, n, 0, 0, arr as *mut usize) } /// `BOOL XMemMapPhysicalPagesScatter(void** addresses, SIZE_T count, ULONG64* pages)`: one 64 KiB -/// page at each address (page 0: the address is unmapped) +/// page at each address (page 0: the address is unmapped; no page array: all of them are – a +/// retail game gives its page pool's pages back that way and stops at an int3 on FALSE, +/// exe+0xb18de7) pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut c_void, n: usize, pages: *mut u64) -> BOOL { - if addresses.is_null() || pages.is_null() { + if addresses.is_null() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } @@ -1332,8 +1488,10 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); - let ok = (0..n).all(|i| !map_pages(away, *addresses.add(i), 1, pages.add(i) as *mut usize).is_null()); + let page = |i: usize| if pages.is_null() { std::ptr::null_mut() } else { pages.add(i) as *mut usize }; + let ok = (0..n).all(|i| !map_pages(away, *addresses.add(i), 1, page(i)).is_null()); give_back_homes(away); + tell_arrived(away); ok as BOOL } @@ -2098,6 +2256,11 @@ mod tests { let at = [page_home(pages[0]).unwrap(), page_home(pages[2]).unwrap()].map(|a| a as *mut c_void); let mut ids = [pages[0] as u64, pages[2] as u64]; assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 2, ids.as_mut_ptr()), 1); + // no page array: the addresses are unmapped (and can be mapped again) + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 2, std::ptr::null_mut()), 1); + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 2, ids.as_mut_ptr()), 1); + assert_eq!(XMemMapPhysicalPagesScatter(std::ptr::null(), 2, std::ptr::null_mut()), 0); + assert_eq!(XMemIsToolsMemAvailable(), 1); ids[1] += 1; assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 2, ids.as_mut_ptr()), 0, "not a page number"); // Page numbers must refer to one registered allocation; arithmetic is checked before @@ -2113,6 +2276,50 @@ mod tests { } } + /// A page the title maps at a second address is found by the first one too (a page pool + /// maps its pages at the pool's address, then one at a time where they are used: the GPU's + /// page mappings name them by their place in the pool). + #[test] + fn a_page_is_found_by_an_earlier_view() { + unsafe { + if crate::gpu::uma::get().is_none() { + return; + } + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let pool = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let cpu = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 2, 0, 4, pages.as_mut_ptr()) as usize, pool); + assert_eq!(page_of_view(pool + PHYS_PAGE + 0x123), Some(pages[1])); + assert_eq!(page_address(pages[1]), Some(pool + PHYS_PAGE)); + // the second page where it is used: the pool's address still names it + let mut one = [pages[1]]; + assert_eq!(MapTitlePhysicalPages(cpu as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, cpu); + *(cpu as *mut u32) = 0xB1_4B00; + assert_eq!(page_of_view(pool + PHYS_PAGE), Some(pages[1])); + assert_eq!((page_at(cpu), page_at(pool + PHYS_PAGE)), (Some(pages[1]), None)); + assert_eq!(page_address(pages[1]), Some(cpu)); + assert_eq!(page_of_view(pool), Some(pages[0])); + // unmapped at the address it is used at: at home, still found by the pool's address + let mut none = [0usize]; + assert_eq!(MapTitlePhysicalPages(cpu as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, cpu); + assert_eq!(page_of_view(cpu), None); + let home = page_address(pages[1]).unwrap(); + assert_eq!(*(home as *const u32), 0xB1_4B00); + assert_eq!(page_of_view(pool + PHYS_PAGE), Some(pages[1])); + // another page at the pool's address: that one + let mut other = [pages[0]]; + assert_eq!(MapTitlePhysicalPages((pool + PHYS_PAGE) as *mut c_void, 1, 0, 4, other.as_mut_ptr()) as usize, pool + PHYS_PAGE); + assert_eq!(page_of_view(pool + PHYS_PAGE), Some(pages[0])); + assert_eq!(page_of_view(pool), Some(pages[0]), "and its earlier address"); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + assert_eq!((page_of_view(pool), page_of_view(pool + PHYS_PAGE)), (None, None), "freed pages are at no address"); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + mem::VirtualFree(cpu as *mut c_void, 0, mem::MEM_RELEASE); + } + } + /// A page mapped away from a home in a sparse window is committed once: the home gives its /// memory back while the page is away and has the page's contents again when it returns. #[test] diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a4..a3f527006 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -17,7 +17,7 @@ use std::sync::{Once, RwLock}; use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; use windows_sys::Win32::System::Memory::{ - VirtualAlloc, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, + VirtualAlloc, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, }; @@ -41,6 +41,8 @@ unsafe fn commit(page: usize) -> bool { if !g.remove(&page) { return false; } + let mut old = 0; + let _ = VirtualProtect(page as *const c_void, PAGE, PAGE_READWRITE, &mut old); !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() } @@ -72,8 +74,27 @@ unsafe fn allows(access: usize, at: usize) -> bool { } } -/// `page` (reserved, 64 KiB aligned) is mapped: committed on first use. +/// Whether pages are committed on first use: `XCL_LAZY_PAGES=1` / `0`, else everywhere but on a +/// Mac (`util::mac_host`). Under Rosetta 2 the first access may be one that cannot be resumed +/// after its fault (an AVX2 masked store: the process ends with "rosetta error: unexpectedly need +/// to EmulateForward on a synchronous exception"), and each fault goes through Wine's exception +/// dispatch. There a page is committed when it is mapped – which costs no memory on that host +/// until the page is written (macOS does not charge commit). +pub fn enabled() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("XCL_LAZY_PAGES") { + Ok(v) => v.trim() != "0", + Err(_) => !crate::util::mac_host(), + }) +} + +/// `page` (reserved, 64 KiB aligned) is mapped: committed on first use (at once where that is +/// off, `enabled`). pub(crate) fn mark(page: usize) { + if !enabled() { + unsafe { VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE) }; + return; + } install(); LAZY.write().unwrap_or_else(|e| e.into_inner()).insert(page); } diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index da0eafbd2..c4d665ba4 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -188,9 +188,15 @@ fn build(config: &Config) -> Registry { } if offline { let n = idx(netoff::NETOFF); - for p in ["winhttp.dll", "ws2_32.dll"] { + // (wsock32: Winsock 1.1, the same functions at the same ordinals) + for p in ["winhttp.dll", "ws2_32.dll", "wsock32.dll"] { routes.push((p.into(), Route::Hle(n))); } + // every other way to the network: stubs (a user alias, first in the list, can still + // name one of them) + for p in netoff::OTHER_NETWORK_DLLS { + routes.push((p.into(), Route::Stub)); + } } Registry { modules, routes } } diff --git a/crates/xcl/src/hle/netoff.rs b/crates/xcl/src/hle/netoff.rs index 8071b04c6..e95aeedf3 100644 --- a/crates/xcl/src/hle/netoff.rs +++ b/crates/xcl/src/hle/netoff.rs @@ -38,8 +38,16 @@ extern "system" { fn real_getaddrinfo_w(node: *const u16, service: *const u16, hints: *const c_void, out: *mut *mut c_void) -> i32; #[link_name = "gethostname"] fn real_gethostname(name: *mut u8, len: i32) -> i32; + #[link_name = "bind"] + fn real_bind(s: usize, name: *const u8, len: i32) -> i32; } +/// DLLs through which a title could reach the network besides WinHTTP and Winsock 2 (whose +/// calls that send are answered here): with the network off every import of them is a stub +/// that fails and LoadLibrary / GetProcAddress find nothing in them (`hle::build`). None of a +/// retail game's modules imports one today; the block must not depend on that. +pub const OTHER_NETWORK_DLLS: [&str; 8] = ["wininet.dll", "mswsock.dll", "websocket.dll", "urlmon.dll", "msquic.dll", "httpapi.dll", "webservices.dll", "winhttpcom.dll"]; + /// A name that resolves without a network: none (the local addresses), this machine's own /// name, localhost – a console without a network still answers these (a retail game asks for /// its own name and none at start). @@ -55,14 +63,21 @@ fn local_name(name: &str) -> bool { } } +/// Local change: on unless `XCL_NETWORK=1` asks for the network. A title under bring-up +/// crashes often and its crash reporter uploads a memory dump each time, so no run may depend +/// on someone remembering a variable. pub fn enabled() -> bool { - std::env::var("XCL_NETWORK").is_ok_and(|v| v.trim() == "0") + !std::env::var("XCL_NETWORK").is_ok_and(|v| v.trim() == "1") } /// (name, address, ws2_32 ordinal – 0: imported by name only) fn table() -> Vec<(&'static str, usize, u16)> { vec![ ("WinHttpSendRequest", send_request as *const () as usize, 0), + // (nothing is sent before WinHttpSendRequest; these two look for a proxy on the network) + ("WinHttpGetProxyForUrl", no_proxy as *const () as usize, 0), + ("WinHttpDetectAutoProxyConfigUrl", no_proxy as *const () as usize, 0), + ("bind", bind as *const () as usize, 2), ("connect", connect as *const () as usize, 4), ("sendto", sendto as *const () as usize, 20), ("gethostbyname", gethostbyname as *const () as usize, 52), @@ -222,6 +237,46 @@ unsafe extern "system" fn send_request(_req: *mut c_void, _headers: *const u16, 0 } +/// WinHttpGetProxyForUrl / WinHttpDetectAutoProxyConfigUrl: no proxy is looked for (WPAD asks +/// DHCP and DNS). +unsafe extern "system" fn no_proxy(_a: usize, _b: usize, _c: usize, _d: usize) -> i32 { + note("WinHTTP proxy detection"); + SetLastError(12180); // ERROR_WINHTTP_AUTODETECTION_FAILED + 0 +} + +/// `name` (sockaddr_in / sockaddr_in6) with the loopback address in place of any other, the +/// port and the rest kept; None: another family, or loopback already. +unsafe fn loopback_of(name: *const u8, len: i32) -> Option<Vec<u8>> { + if name.is_null() || len < 8 || loopback(name, len) { + return None; + } + let mut a = std::slice::from_raw_parts(name, len as usize).to_vec(); + match (name as *const u16).read_unaligned() { + 2 => a[4..8].copy_from_slice(&[127, 0, 0, 1]), + 23 if len >= 24 => { + a[8..24].fill(0); + a[23] = 1; + } + _ => return None, + } + Some(a) +} + +/// bind: a socket bound to every address, or to one of the machine's, is bound to the loopback +/// address – nothing outside this machine reaches a port the title listens on (its own socket +/// pairs still connect: they go through 127.0.0.1). +unsafe extern "system" fn bind(s: usize, name: *const u8, len: i32) -> i32 { + match loopback_of(name, len) { + Some(a) => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_info!("XCL_NETWORK=0: a socket bound to an address other than loopback is bound to loopback")); + real_bind(s, a.as_ptr(), len) + } + None => real_bind(s, name, len), + } +} + unsafe extern "system" fn connect(s: usize, name: *const u8, len: i32) -> i32 { if loopback(name, len) { return orig_connect(s, name, len); @@ -288,6 +343,44 @@ unsafe extern "system" fn getaddrinfo_ex(_n: *const u16, _s: *const u16, _ns: u3 mod tests { use super::*; + /// With no XCL_NETWORK in the environment the network is off, and what a title's imports + /// and run-time lookups of the networking DLLs resolve to is XCL's, never the host's: the + /// calls that send (by name and by Winsock ordinal), and every function of the other DLLs. + #[test] + fn the_default_is_no_network_for_every_way_in() { + use crate::pe::ImportName; + if std::env::var_os("XCL_NETWORK").is_some() { + return; + } + assert!(enabled()); + let name = |s: &str| ImportName::Name { hint: 0, name: s.into() }; + let reg = crate::hle::registry(); + for dll in ["winhttp.dll", "ws2_32.dll", "wsock32.dll"] { + assert!(matches!(reg.route(dll), Some(crate::hle::Route::Hle(_))), "{dll}"); + } + for dll in OTHER_NETWORK_DLLS { + assert_eq!(reg.route(dll), Some(&crate::hle::Route::Stub), "{dll}"); + // run-time lookups find nothing + let h = crate::resolver::load_library(dll).unwrap(); + assert_eq!(crate::resolver::get_proc_address(h, &name("InternetOpenW")), None, "{dll}"); + } + let mine: Vec<usize> = exports().iter().map(|e| e.1).collect(); + // static imports: by name and by ordinal (a retail game imports ws2_32 by ordinal) + for (dll, what) in [("WINHTTP.dll", name("WinHttpSendRequest")), ("WS2_32.dll", ImportName::Ordinal(4)), ("WS2_32.dll", ImportName::Ordinal(20)), ("WS2_32.dll", ImportName::Ordinal(52)), ("WS2_32.dll", ImportName::Ordinal(2)), ("WS2_32.dll", name("getaddrinfo")), ("ws2_32.dll", name("WSAConnect")), ("WSOCK32.dll", ImportName::Ordinal(4)), ("wsock32.dll", name("sendto"))] { + let a = crate::resolver::resolve_import(dll, &what, "test.exe", false); + assert!(mine.contains(&a), "{dll} {what}"); + } + // LoadLibrary + GetProcAddress, by name and by ordinal, on whatever handle the title gets + for (dll, what) in [("winhttp.dll", name("WinHttpSendRequest")), ("ws2_32.dll", name("connect")), ("ws2_32.dll", ImportName::Ordinal(4)), ("ws2_32.dll", ImportName::Ordinal(20))] { + let h = crate::resolver::load_library(dll).unwrap(); + let a = crate::resolver::get_proc_address(h, &what).unwrap(); + assert!(mine.contains(&a), "GetProcAddress({dll}, {what})"); + } + // what does not send stays the host's (a title opens sessions and sockets without a network) + let h = crate::resolver::load_library("ws2_32.dll").unwrap(); + assert!(crate::resolver::get_proc_address(h, &name("WSAStartup")).is_some_and(|a| !mine.contains(&a))); + } + #[test] fn only_loopback_goes_through() { let v4 = |a: [u8; 4]| [2, 0, 0, 80, a[0], a[1], a[2], a[3], 0, 0, 0, 0, 0, 0, 0, 0]; @@ -301,6 +394,14 @@ mod tests { v6[8] = 0x20; assert!(!loopback(v6.as_ptr(), 28)); assert_eq!(connect(usize::MAX, v4([8, 8, 8, 8]).as_ptr(), 16), -1); + // bind: any address and the machine's own become loopback, port kept + assert_eq!(loopback_of(v4([0, 0, 0, 0]).as_ptr(), 16), Some(v4([127, 0, 0, 1]).to_vec())); + assert_eq!(loopback_of(v4([192, 168, 1, 7]).as_ptr(), 16), Some(v4([127, 0, 0, 1]).to_vec())); + assert_eq!(loopback_of(v4([127, 0, 0, 1]).as_ptr(), 16), None); + let any6 = [23u8, 0, 0x1F, 0x90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let lo6 = loopback_of(any6.as_ptr(), 28).unwrap(); + assert!(loopback(lo6.as_ptr(), 28) && lo6[2..4] == [0x1F, 0x90]); + assert_eq!(no_proxy(0, 0, 0, 0), 0); assert_eq!(send_request(std::ptr::null_mut(), std::ptr::null(), 0, std::ptr::null(), 0, 0, 0), 0); } } diff --git a/crates/xcl/src/hle/xgameruntime/api.rs b/crates/xcl/src/hle/xgameruntime/api.rs index 13406406d..130b991ec 100644 --- a/crates/xcl/src/hle/xgameruntime/api.rs +++ b/crates/xcl/src/hle/xgameruntime/api.rs @@ -85,6 +85,7 @@ const XSYSTEM_V3_IID: Guid = g(0x6fd71f09_7513_49f0_89bc_bfaf5df6f852); const XANALYTICS: Guid = g(0xb884675d_b738_4a9c_815d_9a9a1e0c6c9b); const XFEATURE: Guid = g(0x8836fe87_edb9_4fe3_8dad_05f0d2cd5b40); const XDISPLAY: Guid = g(0x1b339674_328d_4283_a200_3171f18d3639); +const XDISPLAY_HDR: Guid = g(0x03f0fe74_fdd9_4e5c_b630_f9339c47acc5); const XGAMEEVENT: Guid = g(0xbbfbdcc7_bfe7_409b_a5ca_edf054960b4d); pub const XNETWORKING: Guid = g(0x37e56907_2f10_41e8_b72f_36edb185331a); pub const XERROR: Guid = g(0x8ca467f7_22e8_4096_8456_bb8aa13f79d8); @@ -361,7 +362,10 @@ struct Obj { unsafe impl Sync for Obj {} unsafe impl Send for Obj {} -const SLOTS: usize = 96; +/// Methods of an XCL object's vtable. The GDK table's highest slot is 83 (XStore); a title +/// built with a newer GDK than the table calls later ones (another runtime's notes on a retail +/// game: proxies need 128) – those reach `unknown_slot`, not the memory after the table. +const SLOTS: usize = 128; unsafe extern "system" fn query_interface(this: *const Obj, iid: *const Guid, out: *mut *mut c_void) -> HRESULT { if out.is_null() || iid.is_null() { @@ -449,7 +453,8 @@ macro_rules! per_slot { } per_slot!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 - 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95); + 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 + 114 115 116 117 118 119 120 121 122 123 124 125 126 127); fn object(iface: Iface) -> &'static Obj { let mut v: Vec<usize> = (0..SLOTS).map(|k| STUBS[k] as usize).collect(); @@ -527,6 +532,7 @@ fn classes() -> Vec<Class> { impls: vec![("XLaunchUri", launch_uri as usize), ("XDisplayAcquireTimeoutDeferral", display_deferral as usize), ("XDisplayCloseTimeoutDeferralHandle", nothing as usize)], forward: &[], }, + Class { name: "XDisplay (HDR)", clsid: XDISPLAY_HDR, impls: vec![("XDisplayTryEnableHdrMode", display_hdr as usize)], forward: &[] }, // telemetry: offline, accepted and dropped Class { name: "XGameEvent", clsid: XGAMEEVENT, impls: vec![("XGameEventWrite", ok as usize)], forward: &[] }, Class { name: "XNetworking", clsid: XNETWORKING, impls: xnetworking(), forward: &[] }, @@ -995,6 +1001,16 @@ unsafe extern "system" fn display_deferral(out: *mut usize) -> HRESULT { S_OK } +/// XDisplayTryEnableHdrMode(preference, XDisplayHdrModeInfo* info) → XDisplayHdrModeResult: +/// Disabled (2) – XCL presents SDR. A retail game asks at start; with the class missing its GDK +/// thunk reported 0x89240107 ("XGameRuntime is missing required dependencies"). +unsafe extern "system" fn display_hdr(_preference: u32, info: *mut [f32; 3]) -> u32 { + if !info.is_null() { + info.write_unaligned([0.0; 3]); // min / max / max full-frame tone-map luminance + } + 2 +} + static PICTURE_ID: u8 = 0; /// XUserGetGamerPictureAsync(user, size, async): a plain picture (PNG) of the requested size @@ -1924,6 +1940,12 @@ mod tests { true } unsafe { + // XDisplayTryEnableHdrMode (slot 4 of its own class): Disabled, the info cleared + let (hr, display) = query(XDISPLAY_HDR, g(0x35f07670_706e_4bfb_9476_090798c5ebf3)); + assert_eq!(hr, S_OK); + let hdr: unsafe extern "system" fn(*mut c_void, u32, *mut [f32; 3]) -> u32 = slot(display, 4); + let mut info = [1.0f32; 3]; + assert_eq!((hdr(display, 1, &mut info), info), (2, [0.0; 3])); // Both XNetworking CLSID and v2 IID resolve to XCL's XNetworking object. let (hr, net) = query(XNETWORKING, XNETWORKING); assert_eq!(hr, S_OK); diff --git a/crates/xcl/src/isa.rs b/crates/xcl/src/isa.rs new file mode 100644 index 000000000..05870d931 --- /dev/null +++ b/crates/xcl/src/isa.rs @@ -0,0 +1,496 @@ +//! Instructions of the console's CPU that a translator does not run, done in software – what +//! `insn` (the instructions a PC CPU lacks, emulated a trap at a time) does not cover. +//! +//! Rosetta 2 raises an illegal-instruction fault for ADX (ADCX/ADOX), RDSEED, SSE4a +//! (INSERTQ/EXTRQ/MOVNTSS/MOVNTSD), CLWB, CLZERO and MONITORX/MWAITX. `insn` emulates the +//! AMD-only ones; ADX and RDSEED every PC CPU has, and MOVNTSS/MOVNTSD it does not know: those +//! are emulated here. A trap under a translator costs tens of microseconds, so the sites that +//! run in loops (ADX, INSERTQ with immediates, the CLZERO loops) are redirected to helpers. +//! This module holds the parts that do not depend on Windows, so they are tested natively +//! (`cargo test`, also as an x86-64 binary under Rosetta itself): +//! +//! * `decode` – exactly the encodings the title uses, plus the memory forms of the same +//! opcodes: legacy prefixes, REX, ModRM/SIB/displacement, RIP-relative. +//! * `exec` – one instruction against a register file (`Cpu`): the trap-per-use path. +//! * `thunk` – a helper in host-runnable code for a faulting site of at least five bytes, +//! which the caller redirects with `call rel32`: a trap costs tens of microseconds, so a +//! site that runs in a loop must trap only once. +//! +//! No allocation and no panicking path: all of it runs inside an exception handler. + +/// The registers an instruction reads and writes. GPR numbers are the hardware's: +/// 0 RAX, 1 RCX, 2 RDX, 3 RBX, 4 RSP, 5 RBP, 6 RSI, 7 RDI, 8–15 R8–R15. +pub trait Cpu { + fn gpr(&self, i: u8) -> u64; + fn set_gpr(&mut self, i: u8, v: u64); + fn rip(&self) -> u64; + fn set_rip(&mut self, v: u64); + fn flags(&self) -> u32; + fn set_flags(&mut self, v: u32); + /// XMM register `i` as (low, high) quadword. + fn xmm(&self, i: u8) -> (u64, u64); + fn set_xmm(&mut self, i: u8, v: (u64, u64)); + /// 64 random bits for RDSEED; `None`: no entropy now (the instruction then clears CF). + fn random(&mut self) -> Option<u64>; +} + +pub const CF: u32 = 1 << 0; +pub const PF: u32 = 1 << 2; +pub const AF: u32 = 1 << 4; +pub const ZF: u32 = 1 << 6; +pub const SF: u32 = 1 << 7; +pub const OF: u32 = 1 << 11; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Op { + /// 66 0F 38 F6 /r: dest = dest + src + CF, only CF changes. + Adcx, + /// F3 0F 38 F6 /r: dest = dest + src + OF, only OF changes. + Adox, + /// 0F C7 /7 (register): hardware random number, CF = 1 when one was delivered. + Rdseed, + /// F3 0F 2B /r (memory): store the low 4 bytes of an XMM register. + Movntss, + /// F2 0F 2B /r (memory): store the low 8 bytes of an XMM register. + Movntsd, + /// F2 0F 78 /r ib ib (registers): insert a bit field of the source's low quadword. + InsertqImm, + /// 0F 01 FC: zero the 64-byte line at RAX. Only `thunk` knows it (with the instruction + /// that follows); `decode` leaves the lone instruction to the caller. + Clzero, +} + +impl Op { + pub fn name(self) -> &'static str { + match self { + Op::Adcx => "ADCX", + Op::Adox => "ADOX", + Op::Rdseed => "RDSEED", + Op::Movntss => "MOVNTSS", + Op::Movntsd => "MOVNTSD", + Op::InsertqImm => "INSERTQ", + Op::Clzero => "CLZERO", + } + } +} + +/// The r/m operand. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Rm { + Reg(u8), + /// base + index * 2^scale + disp, or next RIP + disp (`rip`). + Mem { base: Option<u8>, index: Option<u8>, scale: u8, disp: i32, rip: bool }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Insn { + pub op: Op, + /// Length in bytes, prefixes included. + pub len: u8, + /// Operand size in bytes: 8 with REX.W, else 4 (RDSEED with 66: 2). + pub size: u8, + /// The ModRM `reg` operand (with REX.R): destination of ADX/INSERTQ, source of MOVNTS*. + pub reg: u8, + pub rm: Rm, + /// INSERTQ: field length and bit index. + pub imm: [u8; 2], +} + +fn le32(c: &[u8], at: usize) -> Option<i32> { + Some(i32::from_le_bytes([*c.get(at)?, *c.get(at + 1)?, *c.get(at + 2)?, *c.get(at + 3)?])) +} + +/// Decodes one instruction at the start of `c` (`None`: not one of ours, or cut short). +/// FS/GS overrides, 32-bit addressing (67) and LOCK are declined: no site in the title has +/// them, and a wrong effective address is worse than the unhandled fault. +pub fn decode(c: &[u8]) -> Option<Insn> { + let (mut i, mut p66, mut pf2, mut pf3) = (0usize, false, false, false); + loop { + match *c.get(i)? { + 0x66 => p66 = true, + 0xF2 => pf2 = true, + 0xF3 => pf3 = true, + 0x26 | 0x2E | 0x36 | 0x3E => {} // ES/CS/SS/DS: no effect in 64-bit mode + _ => break, + } + i += 1; + if i > 4 { + return None; + } + } + let mut rex = 0u8; + if *c.get(i)? & 0xF0 == 0x40 { + rex = *c.get(i)?; + i += 1; + } + if *c.get(i)? != 0x0F { + return None; + } + let wide = rex & 8 != 0; + let mut size = if wide { 8 } else { 4 }; + let op = match (*c.get(i + 1)?, p66, pf2, pf3) { + (0x38, true, false, false) if *c.get(i + 2)? == 0xF6 => Op::Adcx, + (0x38, false, false, true) if *c.get(i + 2)? == 0xF6 => Op::Adox, + (0xC7, _, false, false) => { + if p66 && !wide { + size = 2; + } + Op::Rdseed + } + (0x2B, _, false, true) => Op::Movntss, + (0x2B, _, true, false) => Op::Movntsd, + (0x78, false, true, false) => Op::InsertqImm, + _ => return None, + }; + i += if matches!(op, Op::Adcx | Op::Adox) { 3 } else { 2 }; + let m = *c.get(i)?; + i += 1; + let (md, rm3) = (m >> 6, m & 7); + let reg = ((m >> 3) & 7) | ((rex & 4) << 1); + let rm = if md == 3 { + Rm::Reg(rm3 | ((rex & 1) << 3)) + } else { + let (mut base, mut index, mut scale, mut rip) = (None, None, 0, false); + let mut disp_len = match md { + 1 => 1, + 2 => 4, + _ => 0, + }; + if rm3 == 4 { + let sib = *c.get(i)?; + i += 1; + scale = sib >> 6; + let ix = ((sib >> 3) & 7) | ((rex & 2) << 2); + if ix != 4 { + index = Some(ix); // index 4 without REX.X: none (R12 is a valid index) + } + if sib & 7 == 5 && md == 0 { + disp_len = 4; // disp32 without a base + } else { + base = Some((sib & 7) | ((rex & 1) << 3)); + } + } else if rm3 == 5 && md == 0 { + rip = true; + disp_len = 4; + } else { + base = Some(rm3 | ((rex & 1) << 3)); + } + let disp = match disp_len { + 1 => *c.get(i)? as i8 as i32, + 4 => le32(c, i)?, + _ => 0, + }; + i += disp_len; + Rm::Mem { base, index, scale, disp, rip } + }; + let mut imm = [0u8; 2]; + let is_reg = matches!(rm, Rm::Reg(_)); + match op { + Op::Adcx | Op::Adox => {} + // /7 with a register; with F3 it is RDPID, with memory VMPTRST: neither is ours + Op::Rdseed if is_reg && (m >> 3) & 7 == 7 => {} + Op::Movntss | Op::Movntsd if !is_reg => {} + Op::InsertqImm if is_reg => { + imm = [*c.get(i)?, *c.get(i + 1)?]; + i += 2; + } + _ => return None, + } + if i > 15 { + return None; + } + Some(Insn { op, len: i as u8, size, reg, rm, imm }) +} + +/// a + b + carry at 64 or 32 bits: (sum, carry out). A 32-bit sum is zero-extended, as a +/// write to a 32-bit register is. +pub fn add_carry(a: u64, b: u64, carry: bool, wide: bool) -> (u64, bool) { + if wide { + let (s, c1) = a.overflowing_add(b); + let (s, c2) = s.overflowing_add(carry as u64); + (s, c1 | c2) + } else { + let s = (a & 0xFFFF_FFFF) + (b & 0xFFFF_FFFF) + carry as u64; + (s & 0xFFFF_FFFF, s >> 32 != 0) + } +} + +/// INSERTQ's field: `len` bits (0 stands for 64) from bit `idx`, cut off at bit 63. +fn insert_mask(len: u8, idx: u8) -> u64 { + let ones = if len & 63 == 0 { u64::MAX } else { (1u64 << (len & 63)) - 1 }; + ones << (idx & 63) +} + +unsafe fn address<C: Cpu>(c: &C, rm: Rm, next: u64) -> Option<u64> { + let Rm::Mem { base, index, scale, disp, rip } = rm else { return None }; + let mut a = disp as i64 as u64; + if rip { + a = a.wrapping_add(next); + } + if let Some(b) = base { + a = a.wrapping_add(c.gpr(b)); + } + if let Some(x) = index { + a = a.wrapping_add(c.gpr(x) << (scale & 3)); + } + Some(a) +} + +/// Runs `insn` on `c` and moves RIP past it. A memory operand is read or written at its +/// effective address: the caller's fault if the instruction would have faulted there too. +/// +/// # Safety +/// Dereferences the instruction's memory operand. +pub unsafe fn exec<C: Cpu>(insn: &Insn, c: &mut C) -> bool { + let next = c.rip().wrapping_add(insn.len as u64); + match insn.op { + Op::Adcx | Op::Adox => { + let wide = insn.size == 8; + let src = match insn.rm { + Rm::Reg(r) => c.gpr(r), + rm => { + let Some(a) = address(c, rm, next) else { return false }; + if wide { + (a as *const u64).read_unaligned() + } else { + (a as *const u32).read_unaligned() as u64 + } + } + }; + let bit = if insn.op == Op::Adcx { CF } else { OF }; + let f = c.flags(); + let (sum, carry) = add_carry(c.gpr(insn.reg), src, f & bit != 0, wide); + c.set_gpr(insn.reg, sum); + c.set_flags(if carry { f | bit } else { f & !bit }); + } + Op::Rdseed => { + let Rm::Reg(r) = insn.rm else { return false }; + let v = c.random(); + let x = v.unwrap_or(0); + c.set_gpr( + r, + match insn.size { + 8 => x, + 4 => x & 0xFFFF_FFFF, + _ => (c.gpr(r) & !0xFFFF) | (x & 0xFFFF), // a 16-bit write keeps the rest + }, + ); + let f = c.flags() & !(CF | OF | SF | ZF | AF | PF); + c.set_flags(if v.is_some() { f | CF } else { f }); + } + Op::Movntss | Op::Movntsd => { + let Some(a) = address(c, insn.rm, next) else { return false }; + let low = c.xmm(insn.reg).0; + if insn.op == Op::Movntss { + (a as *mut u32).write_unaligned(low as u32); + } else { + (a as *mut u64).write_unaligned(low); + } + } + // emulated by `eh::emulate_console_only` (`insn`); here they are only redirected (`thunk`) + Op::InsertqImm | Op::Clzero => return false, + } + c.set_rip(next); + true +} + +/// Largest helper `thunk` writes. +pub const THUNK_MAX: usize = 96; +/// Bytes kept for one ADX helper: they are shared by all sites with the same operands. +pub const ADX_SLOT: usize = 32; +/// Number of ADX helpers: (ADOX, REX.W, destination, source). +pub const ADX_SLOTS: usize = 1024; + +/// A helper for a faulting site, to be reached by `call rel32` written over the site. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Thunk { + /// Bytes of the site the helper stands for (5..=8): the call, then NOPs. + pub site_len: u8, + /// Bytes of helper code (and constants) in the buffer. + pub len: u8, + /// ADX: index of the shared helper slot. + pub slot: Option<u16>, + pub op: Op, +} + +struct Emit<'a> { + out: &'a mut [u8; THUNK_MAX], + n: usize, +} + +impl Emit<'_> { + fn put(&mut self, bytes: &[u8]) { + for &b in bytes { + if let Some(o) = self.out.get_mut(self.n) { + *o = b; + } + self.n += 1; + } + } +} + +/// Writes position-independent host code into `out` that does what the instruction(s) at +/// the start of `c` do, ending in RET, and says how many site bytes it replaces. The helper +/// is entered by a CALL from the site, so it sees RSP 8 lower: operands that use RSP are +/// declined, as is everything `exec` would not take over exactly. It must be placed at an +/// address that is a multiple of 16 (INSERTQ helpers carry aligned constants). +/// +/// * ADCX/ADOX r, r: the flags are saved, ADC runs with CF (or OF copied into CF), and only +/// the carry out is merged into the saved flags. +/// * INSERTQ xmm, xmm, len, idx: shift/AND/OR with one spilled XMM register; no flag changes. +/// * CLZERO followed by `add rax, 0x40` or `cmp r64, r64` (the title's zeroing loops; CLZERO +/// alone is three bytes, too short for a call): eight stores, then the second instruction, +/// whose flags are the ones the loop branch reads. +pub fn thunk(c: &[u8], out: &mut [u8; THUNK_MAX]) -> Option<Thunk> { + let mut e = Emit { out, n: 0 }; + if let [0x0F, 0x01, 0xFC, tail @ ..] = c { + let t = match tail { + [0x48, 0x83, 0xC0, 0x40, ..] => 4, + // cmp r/m64, r64 or cmp r64, r/m64 between registers other than RSP + [rex, 0x39 | 0x3B, m, ..] if rex & 0xF8 == 0x48 && m >> 6 == 3 && (m & 7 != 4 || rex & 1 != 0) && ((m >> 3) & 7 != 4 || rex & 4 != 0) => 3, + _ => return None, + }; + e.put(&[0x50, 0x48, 0x83, 0xE0, 0xC0]); // push rax; and rax, -64 + for d in 0..8u8 { + e.put(&[0x48, 0xC7, 0x40, d * 8, 0, 0, 0, 0]); // mov qword [rax + d*8], 0 + } + e.put(&[0x58]); // pop rax + e.put(tail.get(..t)?); + e.put(&[0xC3]); + return Some(Thunk { site_len: 3 + t as u8, len: e.n as u8, slot: None, op: Op::Clzero }); + } + let i = decode(c)?; + let Rm::Reg(src) = i.rm else { return None }; + if !(5..=8).contains(&i.len) { + return None; + } + match i.op { + Op::Adcx | Op::Adox if i.reg != 4 && src != 4 => { + let adox = i.op == Op::Adox; + let wide = i.size == 8; + e.put(&[0x9C]); // pushfq (changes no flag: CF is still the incoming carry) + if adox { + e.put(&[0x0F, 0xBA, 0x24, 0x24, 0x0B]); // bt dword [rsp], 11: CF = saved OF + } + let rex = 0x40 | (wide as u8) << 3 | (i.reg >> 3) << 2 | (src >> 3); + if rex != 0x40 { + e.put(&[rex]); + } + e.put(&[0x13, 0xC0 | (i.reg & 7) << 3 | (src & 7)]); // adc dest, src + if adox { + // jc +7; and byte [rsp+1], ~8; popfq; ret; or byte [rsp+1], 8; popfq; ret + e.put(&[0x72, 0x07, 0x80, 0x64, 0x24, 0x01, 0xF7, 0x9D, 0xC3, 0x80, 0x4C, 0x24, 0x01, 0x08, 0x9D, 0xC3]); + } else { + // jc +6; and byte [rsp], ~1; popfq; ret; or byte [rsp], 1; popfq; ret + e.put(&[0x72, 0x06, 0x80, 0x24, 0x24, 0xFE, 0x9D, 0xC3, 0x80, 0x0C, 0x24, 0x01, 0x9D, 0xC3]); + } + let slot = (adox as u16) << 9 | (wide as u16) << 8 | (i.reg as u16) << 4 | src as u16; + Some(Thunk { site_len: i.len, len: e.n as u8, slot: Some(slot), op: i.op }) + } + Op::InsertqImm => { + let d = i.reg; + // a scratch register that is neither operand + let t = if d != 0 && src != 0 { + 0u8 + } else if d != 1 && src != 1 { + 1 + } else { + 2 + }; + const MASK_AT: usize = 64; // then the inverted mask at +16 + let field = insert_mask(i.imm[0], i.imm[1]); + e.put(&[0x48, 0x8D, 0x64, 0x24, 0xF0]); // lea rsp, [rsp-16] + e.put(&[0xF3, 0x0F, 0x7F, 0x04 | t << 3, 0x24]); // movdqu [rsp], xmmT + if src >= 8 { + e.put(&[0x41]); + } + e.put(&[0x0F, 0x28, 0xC0 | t << 3 | (src & 7)]); // movaps xmmT, xmmS + e.put(&[0x66, 0x0F, 0x73, 0xF0 | t, i.imm[1] & 63]); // psllq xmmT, idx + e.put(&[0x66, 0x0F, 0xDB, 0x05 | t << 3]); // pand xmmT, [rip + mask] + let rel = (MASK_AT as i32) - (e.n as i32 + 4); + e.put(&rel.to_le_bytes()); + e.put(&[0x66]); + if d >= 8 { + e.put(&[0x44]); + } + e.put(&[0x0F, 0xDB, 0x05 | (d & 7) << 3]); // pand xmmD, [rip + !mask] + let rel = (MASK_AT as i32 + 16) - (e.n as i32 + 4); + e.put(&rel.to_le_bytes()); + e.put(&[0x66]); + if d >= 8 { + e.put(&[0x44]); + } + e.put(&[0x0F, 0xEB, 0xC0 | (d & 7) << 3 | t]); // por xmmD, xmmT + e.put(&[0xF3, 0x0F, 0x6F, 0x04 | t << 3, 0x24]); // movdqu xmmT, [rsp] + e.put(&[0x48, 0x8D, 0x64, 0x24, 0x10, 0xC3]); // lea rsp, [rsp+16]; ret + if e.n > MASK_AT { + return None; + } + while e.n < MASK_AT { + e.put(&[0xCC]); + } + e.put(&field.to_le_bytes()); + e.put(&[0; 8]); + e.put(&(!field).to_le_bytes()); + e.put(&[0; 8]); // the destination's high quadword is zeroed, as `insn` has it (a Zen 5 does) + Some(Thunk { site_len: i.len, len: e.n as u8, slot: None, op: i.op }) + } + _ => None, + } +} + +/// The bytes that replace a site of `site_len` bytes at `site`: `call helper`, then NOPs. +/// `None`: the helper is out of the call's ±2 GiB reach or the site is too short. +pub fn call_site(site: u64, site_len: u8, helper: u64) -> Option<[u8; 8]> { + if !(5..=8).contains(&site_len) { + return None; + } + let rel = i32::try_from(helper.wrapping_sub(site.wrapping_add(5)) as i64).ok()?; + let mut b = [0x90u8; 8]; + b[0] = 0xE8; + b[1..5].copy_from_slice(&rel.to_le_bytes()); + Some(b) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The encodings upstream's `insn` does not emulate are decoded here: ADCX / ADOX, RDSEED, + /// MOVNTSS / MOVNTSD; RDPID (F3 0F C7 /7) is left to `insn`. + #[test] + fn decodes_what_only_a_translator_lacks() { + // adcx rax, rcx (66 48 0F 38 F6 C1); adox r8d, r9d (F3 45 0F 38 F6 C1) + let i = decode(&[0x66, 0x48, 0x0F, 0x38, 0xF6, 0xC1]).unwrap(); + assert_eq!((i.op, i.len, i.size, i.reg, i.rm), (Op::Adcx, 6, 8, 0, Rm::Reg(1))); + let i = decode(&[0xF3, 0x45, 0x0F, 0x38, 0xF6, 0xC1]).unwrap(); + assert_eq!((i.op, i.len, i.size, i.reg, i.rm), (Op::Adox, 6, 4, 8, Rm::Reg(9))); + // rdseed rax (48 0F C7 F8); movntss [rax + 8], xmm1 (F3 0F 2B 48 08) + assert_eq!(decode(&[0x48, 0x0F, 0xC7, 0xF8]).map(|i| (i.op, i.size)), Some((Op::Rdseed, 8))); + let i = decode(&[0xF3, 0x0F, 0x2B, 0x48, 0x08]).unwrap(); + assert_eq!((i.op, i.len, i.reg, i.rm), (Op::Movntss, 5, 1, Rm::Mem { base: Some(0), index: None, scale: 0, disp: 8, rip: false })); + assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), None, "RDPID is `insn`'s"); + assert_eq!(decode(&[0x0F, 0x01, 0xFC]), None, "a lone CLZERO is `insn`'s"); + assert_eq!(add_carry(u64::MAX, 0, true, true), (0, true)); + assert_eq!(add_carry(0xFFFF_FFFF, 1, false, false), (0, true)); + } + + /// INSERTQ's helper: the field mask and its complement as aligned constants, the high + /// quadword zeroed (as `insn::insertq`'s caller does), and a call that reaches it. + #[test] + fn insertq_helper_zeroes_the_high_quadword() { + // insertq xmm0, xmm1, 8, 16 (F2 0F 78 C1 08 10) + let mut out = [0u8; THUNK_MAX]; + let t = thunk(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10], &mut out).unwrap(); + assert_eq!((t.op, t.site_len, t.len as usize, t.slot), (Op::InsertqImm, 6, 96, None)); + let q = |at: usize| u64::from_le_bytes(out[at..at + 8].try_into().unwrap()); + assert_eq!([q(64), q(72), q(80), q(88)], [0xFF_0000, 0, !0xFF_0000, 0]); + assert_eq!(*out[..64].iter().rev().find(|&&b| b != 0xCC).unwrap(), 0xC3, "the code ends in ret"); + let call = call_site(0x1000, t.site_len, 0x2000).unwrap(); + assert_eq!(call[..6], [0xE8, 0xFB, 0x0F, 0x00, 0x00, 0x90]); + assert_eq!(call_site(0x1000, 3, 0x2000), None, "too short for a call"); + // the CLZERO loop's site: clzero; add rax, 0x40 – seven bytes, eight stores + let t = thunk(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40], &mut out).unwrap(); + assert_eq!((t.op, t.site_len), (Op::Clzero, 7)); + } +} diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index 6f828ca68..786a074b1 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -17,8 +17,10 @@ pub mod hooks; pub mod host; pub mod insn; pub mod inspect; +pub mod isa; pub mod launcher; pub mod loader; +pub mod maskmov; pub mod modules; pub mod pe; pub mod preflight; diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 52c49afe7..b7e57eaa5 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -130,6 +130,13 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result<Arc<MappedModule>, String> } } + // 3b. masked stores, where the host cannot resume one after a fault + if masked_store_helpers() { + let code: Vec<(u32, u32)> = pe.sections.iter().filter(|s| s.characteristics & 0x2000_0000 != 0).map(|s| (s.va, s.mapped_size())).collect(); + let ex = pe.dir(pe::DIR_EXCEPTION); + unsafe { replace_masked_stores(base, size, &code, (ex.rva, ex.size), &name) }; + } + let exports = OwnedExports::from_pe(&pe).unwrap_or_default(); let module = Arc::new(MappedModule { name: name.clone(), @@ -234,6 +241,105 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result<Arc<MappedModule>, String> Ok(module) } +/// Whether a title's AVX masked stores are replaced by calls to helpers (`maskmov`): +/// `XCL_MASKED_STORES=1` / `0`, else only where the title's code runs through Rosetta 2 +/// (`util::rosetta`) – on a CPU the instructions are left alone. +fn masked_store_helpers() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("XCL_MASKED_STORES") { + Ok(v) => v.trim() != "0", + Err(_) => crate::util::rosetta(), + }) +} + +/// Replaces the masked stores of the image mapped at `base` (relocated, its sections still +/// writable, none of its code run yet) by calls to helpers that store an element at a time +/// (`maskmov::plan`), and says how many. `code` is the (RVA, length) of each executable +/// section, `unwind` the (RVA, size) of the image's function table. The helpers get memory of +/// their own within a call's reach of the image, with unwind data, read-only once written. +/// One log line says what was done, and one for each pattern left as it is. +unsafe fn replace_masked_stores(base: usize, size: usize, code: &[(u32, u32)], unwind: (u32, u32), name: &str) -> usize { + use crate::maskmov::{self, Kind}; + use windows_sys::Win32::System::Diagnostics::Debug::{FlushInstructionCache, RtlAddFunctionTable, IMAGE_RUNTIME_FUNCTION_ENTRY}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let started = std::time::Instant::now(); + let image = std::slice::from_raw_parts(base as *const u8, size); + let functions: Vec<(u32, u32)> = image + .get(unwind.0 as usize..(unwind.0 as usize).saturating_add(unwind.1 as usize)) + .unwrap_or_default() + .chunks_exact(12) + .map(|e| (u32::from_le_bytes([e[0], e[1], e[2], e[3]]), u32::from_le_bytes([e[4], e[5], e[6], e[7]]))) + .collect(); + let plan = maskmov::plan(image, base as u64, code, &functions); + for (rva, why) in plan.skipped.iter().take(32) { + crate::xlog_warn!("{name}: the bytes of a masked store at +{rva:#x} are left as they are ({why:?})"); + } + if plan.sites.is_empty() { + if !plan.skipped.is_empty() { + crate::xlog_warn!("{name}: {} byte pattern(s) of a masked store, none replaced", plan.skipped.len()); + } + return 0; + } + // helpers, their shared unwind data, one function entry each + let unwind_at = (plan.code.len() + 15) & !15; + let table_at = unwind_at + maskmov::UNWIND_INFO.len(); + let entry = std::mem::size_of::<IMAGE_RUNTIME_FUNCTION_ENTRY>(); + let pool_size = (table_at + plan.helpers.len() * entry + 0xFFFF) & !0xFFFF; + let pool = crate::eh::alloc_near(base + size, pool_size); + if pool == 0 { + crate::xlog_error!("{name}: no memory near the image for the helpers of {} masked stores – they stay, and one that faults past its first element ends the process on this host", plan.sites.len()); + return 0; + } + std::ptr::copy_nonoverlapping(plan.code.as_ptr(), pool as *mut u8, plan.code.len()); + std::ptr::copy_nonoverlapping(maskmov::UNWIND_INFO.as_ptr(), (pool + unwind_at) as *mut u8, maskmov::UNWIND_INFO.len()); + let table = (pool + table_at) as *mut IMAGE_RUNTIME_FUNCTION_ENTRY; + for (k, &(start, end)) in plan.helpers.iter().enumerate() { + let e = &mut *table.add(k); + (e.BeginAddress, e.EndAddress) = (start, end); + e.Anonymous.UnwindInfoAddress = unwind_at as u32; + } + let (mut done, mut leaf, mut far) = ([0usize; 4], 0usize, 0usize); + for s in &plan.sites { + let site = base + s.rva as usize; + let Some(call) = maskmov::call_site(site as u64, s.store.len, (pool + s.helper as usize) as u64) else { + far += 1; + continue; + }; + std::ptr::copy_nonoverlapping(call.as_ptr(), site as *mut u8, s.store.len as usize); + done[Kind::ALL.iter().position(|&k| k == s.store.kind).unwrap_or(0)] += 1; + leaf += s.leaf as usize; + } + let mut old = 0u32; + VirtualProtect(pool as *const c_void, pool_size, PAGE_EXECUTE_READ, &mut old); + FlushInstructionCache(GetCurrentProcess(), pool as *const c_void, pool_size); + if !RtlAddFunctionTable(table, plan.helpers.len() as u32, pool as u64) { + crate::xlog_warn!("{name}: RtlAddFunctionTable for the masked-store helpers at {pool:#x} failed"); + } + MASKED_STORE_HELPERS.lock().unwrap().push((pool, pool + plan.code.len())); + let kinds: Vec<String> = Kind::ALL.iter().zip(done).filter(|(_, n)| *n != 0).map(|(k, n)| format!("{n} {}", k.name())).collect(); + crate::xlog_info!( + "{name}: {} masked stores ({}) call {} helpers at {pool:#x}..{:#x} that store an element at a time – the host cannot resume one that faults past its first element (XCL_MASKED_STORES=0 leaves them){}{}{}; {} ms", + done.iter().sum::<usize>(), + kinds.join(", "), + plan.helpers.len(), + pool + plan.code.len(), + if leaf != 0 { format!("; {leaf} of them in functions without unwind data") } else { String::new() }, + if plan.skipped.is_empty() { String::new() } else { format!("; {} pattern(s) left as they are", plan.skipped.len()) }, + if far != 0 { format!("; {far} out of a call's reach and left") } else { String::new() }, + started.elapsed().as_millis() + ); + done.iter().sum() +} + +/// The helpers' memory, per image: (start, end). +static MASKED_STORE_HELPERS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); + +/// Whether `addr` is in a masked-store helper – code of XCL's that runs in place of an +/// instruction of the title's (a crash line then names the store by the return address). +pub fn in_masked_store_helper(addr: usize) -> bool { + MASKED_STORE_HELPERS.try_lock().is_ok_and(|g| g.iter().any(|r| (r.0..r.1).contains(&addr))) +} + unsafe fn tls_install(m: &MappedModule, template: usize, len: usize, total: u64, index_ptr: *mut u32) -> Result<(), String> { let k = crate::tls::install(&m.name, template, len, total, index_ptr, &cache_dir())?; // the title's executable: slot 0, as a process's executable has it @@ -349,7 +455,7 @@ pub fn run_main(m: &Arc<MappedModule>) -> u32 { run_tls_callbacks(m, 1); } READY.store(true, Ordering::Release); - let stack = (m.stack_reserve as usize).max(1 << 20); + let stack = (m.stack_reserve as usize).max(crate::hle::kernelx::MIN_TITLE_STACK); let args = Box::into_raw(Box::new(EntryArgs { entry: m.base + m.entry_rva as usize })); crate::xlog_info!( "start {}: entry point {} , stack {:#x}", @@ -522,4 +628,121 @@ mod tests { assert!(modules::find_mapped_by_name(&key).is_none(), "attempt {attempt}: still registered"); } } + /// What the masked-store test's exception handler saw: the page it repairs (start, end), + /// faults repaired, the faulting instruction, and the frame one step up from it by the + /// unwind data (RIP, the word 0x30 bytes above RSP, RAX, RCX, RDX, R8). + #[cfg(target_arch = "x86_64")] + static FAULT: [std::sync::atomic::AtomicUsize; 10] = [const { std::sync::atomic::AtomicUsize::new(0) }; 10]; + + #[cfg(target_arch = "x86_64")] + unsafe extern "system" fn repair_and_unwind(info: *mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> i32 { + use windows_sys::Win32::System::Diagnostics::Debug::{RtlLookupFunctionEntry, RtlVirtualUnwind}; + let rec = &*(*info).ExceptionRecord; + let at = rec.ExceptionInformation[1]; + if rec.ExceptionCode as u32 != 0xC000_0005 || !(FAULT[0].load(Ordering::Relaxed)..FAULT[1].load(Ordering::Relaxed)).contains(&at) { + return 0; + } + let mut ctx = *(*info).ContextRecord; + FAULT[3].store(ctx.Rip as usize, Ordering::Relaxed); + let mut image = 0u64; + let entry = RtlLookupFunctionEntry(ctx.Rip, &mut image, std::ptr::null_mut()); + if !entry.is_null() { + let (mut data, mut frame) = (std::ptr::null_mut(), 0u64); + RtlVirtualUnwind(0, image, ctx.Rip, entry, &mut ctx, &mut data, &mut frame, std::ptr::null_mut()); + // (the stack is read now: the frames are gone when the test looks) + let above = ((ctx.Rsp + 0x28 + 8) as *const u64).read(); + for (slot, v) in [ctx.Rip, above, ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.R8].into_iter().enumerate() { + FAULT[4 + slot].store(v as usize, Ordering::Relaxed); + } + } + let mut old = 0; + VirtualProtect((at & !0xFFF) as *const c_void, 0x1000, PAGE_READWRITE, &mut old); + FAULT[2].fetch_add(1, Ordering::Relaxed); + -1 // EXCEPTION_CONTINUE_EXECUTION + } + + /// A mapped image with a masked store in a function and one in a leaf function behind it: + /// both become calls to helpers near the image. Run, the function stores what the + /// instruction would; a fault in the helper (the second page is read-only) is in memory + /// XCL names, has unwind data that leads back to the store with the title's registers, and + /// is resumed when the page has been made writable. + #[test] + #[cfg(target_arch = "x86_64")] + fn masked_stores_of_a_mapped_image_call_helpers_with_unwind_data() { + use crate::maskmov::exec::{defined, has_avx2, point, set_mask, Rng, State, STACK_AT}; + use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, RemoveVectoredExceptionHandler}; + if !has_avx2() { + eprintln!("SKIPPED: this CPU has no AVX2"); + return; + } + extern "C" { + fn xcl_maskmov_test_run(state: *mut State, code: *const u8); + } + const STORE: [u8; 6] = [0xC4, 0xE2, 0x4D, 0x8E, 0x04, 0x90]; // vpmaskmovd [rax + 4 * rdx], ymm6, ymm0 + const LEAF: [u8; 7] = [0xC4, 0x22, 0xC5, 0x8E, 0x44, 0x04, 0x40]; // vpmaskmovq [rsp + r8 + 0x40], ymm7, ymm8 + unsafe { + let base = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; + let put = |at: usize, bytes: &[u8]| std::ptr::copy_nonoverlapping(bytes.as_ptr(), (base + at) as *mut u8, bytes.len()); + std::ptr::write_bytes(base as *mut u8, 0xCC, 0x1_0000); + // 0x1000: lea rsp, [rsp - 0x28]; STORE; lea rsp, [rsp + 0x28]; ret – and its function entry + put(0x1000, &[0x48, 0x8D, 0x64, 0x24, 0xD8]); + put(0x1005, &STORE); + put(0x100B, &[0x48, 0x8D, 0x64, 0x24, 0x28, 0xC3]); + put(0x3000, &[0x00, 0x10, 0, 0, 0x11, 0x10, 0, 0, 0, 0, 0, 0]); + // 0x1020, a leaf function: LEAF; ret + put(0x1020, &LEAF); + put(0x1027, &[0xC3]); + assert_eq!(replace_masked_stores(base, 0x1_0000, &[(0x1000, 0x1000)], (0x3000, 12), "test image"), 2); + let site = std::slice::from_raw_parts((base + 0x1005) as *const u8, 6); + assert_eq!((site[0], site[5]), (0xE8, 0x90), "a call and a NOP"); + let helper = base + 0x100A + i32::from_le_bytes([site[1], site[2], site[3], site[4]]) as isize as usize; + assert!(in_masked_store_helper(helper) && helper.abs_diff(base) < 0x7000_0000 && !in_masked_store_helper(base + 0x1005)); + assert_eq!(*((base + 0x1020) as *const u8), 0xE8); + assert_eq!(std::slice::from_raw_parts((base + 0x1025) as *const u8, 3), [0x90, 0x90, 0xC3]); + + // the function, with its store across a writable and a read-only page + let pages = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let s = crate::maskmov::decode(&STORE).unwrap(); + let mut rng = Rng(0x0BAD_C0DE_600D_F00D); + let st = { + let mut st = rng.state(true); + set_mask(&s, &mut st, 0xB7); + point(&s, &mut st, pages + 0x1000 - 12, 9); + st + }; + let mut old = 0; + VirtualProtect((pages + 0x1000) as *const c_void, 0x1000, PAGE_READONLY, &mut old); + FAULT[0].store(pages, Ordering::Relaxed); + FAULT[1].store(pages + 0x2000, Ordering::Relaxed); + let handler = AddVectoredExceptionHandler(1, Some(repair_and_unwind)); + let mut out = st.clone(); + xcl_maskmov_test_run(&mut out, (base + 0x1000) as *const u8); + RemoveVectoredExceptionHandler(handler); + assert_eq!(out, st, "registers, flags, vectors and stack are as they were"); + assert_eq!(((pages + 0x1000 - 12) as *const [u8; 32]).read()[..], defined(&s, &st, &[0; 32])[..]); + let seen: Vec<usize> = FAULT.iter().map(|v| v.load(Ordering::Relaxed)).collect(); + assert_eq!(seen[2], 1, "one fault, at the first element on the read-only page"); + assert!(in_masked_store_helper(seen[3]), "the fault is in the helper: {:#x}", seen[3]); + assert!(crate::modules::describe_address(seen[3]).contains("masked-store helper")); + // one frame up: back in the function right behind the call, RSP as at the store (the + // function's 0x28 bytes and its return address below the caller's two pointers), + // and the title's RAX, RCX, RDX and R8 + assert_eq!(seen[4], base + 0x100A, "unwound RIP"); + assert_eq!(seen[5], &out as *const State as usize, "unwound RSP"); + assert_eq!(seen[6..10], [st.gpr[0] as usize, st.gpr[1] as usize, st.gpr[2] as usize, st.gpr[8] as usize]); + + // the leaf function: the store goes to the stack, 0x40 bytes above its RSP + let s = crate::maskmov::decode(&LEAF).unwrap(); + let mut st = rng.state(false); + set_mask(&s, &mut st, 0b0110); + st.gpr[8] = 0x10; + let mut out = st.clone(); + xcl_maskmov_test_run(&mut out, (base + 0x1020) as *const u8); + let at = 0x40 + 0x10 - STACK_AT as usize; + let stored = defined(&s, &st, &st.stack[at..at + 32]); + st.stack[at..at + 32].copy_from_slice(&stored); + assert_eq!(out, st); + VirtualFree(pages as *mut c_void, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/maskmov.rs b/crates/xcl/src/maskmov.rs new file mode 100644 index 000000000..4bafd63b5 --- /dev/null +++ b/crates/xcl/src/maskmov.rs @@ -0,0 +1,1407 @@ +//! AVX / AVX2 masked stores (VMASKMOVPS, VMASKMOVPD, VPMASKMOVD, VPMASKMOVQ with a memory +//! destination) of a title, replaced when its image is loaded on a host whose translator +//! cannot resume them after a fault. +//! +//! Rosetta 2 runs a masked store an element at a time and can restart it only from its first +//! element: a fault there is delivered and resumed like any other, a fault on a later element +//! ends the process ("rosetta error: unexpectedly need to EmulateForward on a synchronous +//! exception"). That is a store which starts on a page that can be written and goes on into one +//! that cannot – what a write watch kept by page protection (Wine on macOS) makes of every +//! page boundary inside a buffer the title fills with such stores. +//! +//! Each store becomes `call helper` (five bytes; these instructions have at least five) and +//! NOPs. The helper stores the selected elements one at a time with ordinary `mov`s, which +//! fault and resume as any store does, and changes nothing else: no register, no flag +//! (it has no instruction that writes one), no byte of an element whose mask bit is clear – +//! such an element is not touched at all, so a store whose tail is masked out may end at the +//! last byte of a mapping as before. +//! +//! This module holds the parts that do not depend on Windows: +//! +//! * `insn_len` – the length of an x86-64 instruction, to walk a function from its start. +//! * `decode` – the four instructions with any memory operand. +//! * `helper` – the code a site calls. +//! * `plan` – the sites of an image: byte pattern, then the walk from the start of the function +//! the unwind data names (or from the end of the one before, for a leaf function that has no +//! unwind data), which must arrive exactly at the site. +//! +//! `loader` applies a plan (after relocation, before the sections are protected). + +/// Length of the x86-64 instruction at the start of `c`. `None`: the bytes run out, or it is +/// something this walk does not know and must not guess at – EVEX, XOP, 3DNow!, an opcode +/// that is not valid in 64-bit mode (which in a function means data). +pub fn insn_len(c: &[u8]) -> Option<usize> { + let (mut i, mut p66, mut p67, mut pf2, mut legacy) = (0usize, false, false, false, false); + loop { + match *c.get(i)? { + 0x66 => p66 = true, + 0x67 => p67 = true, + 0xF2 => pf2 = true, + 0xF3 | 0xF0 => legacy = true, + 0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 => {} + _ => break, + } + i += 1; + if i > 14 { + return None; + } + } + let (mut rex, mut rex_w) = (false, false); + if *c.get(i)? & 0xF0 == 0x40 { + rex = true; + rex_w = *c.get(i)? & 8 != 0; + i += 1; + } + let op = *c.get(i)?; + i += 1; + // an immediate of the operand size, at most four bytes + let immz = if rex_w || !p66 { 4 } else { 2 }; + // (has ModRM, immediate bytes) + let (modrm, mut imm): (bool, usize) = match op { + 0xC4 | 0xC5 => { + // VEX takes no REX, LOCK or 66 / F2 / F3 in front + if rex || p66 || pf2 || legacy { + return None; + } + let map = if op == 0xC5 { + i += 1; + 1 + } else { + i += 2; + *c.get(i - 2)? & 0x1F + }; + let o = *c.get(i)?; + i += 1; + match map { + 1 => (o != 0x77, matches!(o, 0x70..=0x73 | 0xC2 | 0xC4..=0xC6) as usize), + 2 => (true, 0), + 3 => (true, 1), + _ => return None, + } + } + 0x0F => { + let o = *c.get(i)?; + i += 1; + match o { + 0x38 | 0x3A => { + c.get(i)?; + i += 1; + (true, (o == 0x3A) as usize) + } + 0x05..=0x09 | 0x0B | 0x30..=0x35 | 0x37 | 0x77 | 0xA0..=0xA2 | 0xA8..=0xAA | 0xC8..=0xCF => (false, 0), + 0x80..=0x8F => (false, 4), + 0x70..=0x73 | 0xA4 | 0xAC | 0xBA | 0xC2 | 0xC4..=0xC6 => (true, 1), + // SSE4a EXTRQ / INSERTQ with length and index bytes + 0x78 if p66 || pf2 => (true, 2), + 0x04 | 0x0A | 0x0C | 0x0E | 0x0F | 0x24..=0x27 | 0x36 | 0x39 | 0x3B..=0x3F | 0x7A | 0x7B | 0xA6 | 0xA7 | 0xFF => return None, + _ => (true, 0), + } + } + 0x00..=0x3F => match op & 7 { + 0..=3 => (true, 0), + 4 => (false, 1), + 5 => (false, immz), + _ => return None, + }, + 0x50..=0x5F | 0x6C..=0x6F | 0x90..=0x99 | 0x9B..=0x9F | 0xA4..=0xA7 | 0xAA..=0xAF => (false, 0), + 0xC3 | 0xC9 | 0xCB | 0xCC | 0xCF | 0xD7 | 0xEC..=0xEF | 0xF1 | 0xF4 | 0xF5 | 0xF8..=0xFD => (false, 0), + // MOV to or from a segment register: there are six + 0x8C | 0x8E if (*c.get(i)? >> 3) & 7 > 5 => return None, + 0x63 | 0x84..=0x8E | 0xD0..=0xD3 | 0xD8..=0xDF | 0xFE | 0xFF => (true, 0), + // POP r/m; any other /r is XOP + 0x8F if *c.get(i)? & 0x38 == 0 => (true, 0), + 0x68 | 0xA9 => (false, immz), + 0x69 | 0x81 | 0xC7 => (true, immz), + 0x6A | 0x70..=0x7F | 0xA8 | 0xB0..=0xB7 | 0xCD | 0xE0..=0xE7 | 0xEB => (false, 1), + 0x6B | 0x80 | 0x83 | 0xC0 | 0xC1 | 0xC6 => (true, 1), + 0xA0..=0xA3 => (false, if p67 { 4 } else { 8 }), + 0xB8..=0xBF => (false, if rex_w { 8 } else { immz }), + 0xC2 | 0xCA => (false, 2), + 0xC8 => (false, 3), + 0xE8 | 0xE9 => (false, 4), + // TEST r/m, imm is /0 and /1 of the group + 0xF6 => (true, (*c.get(i)? & 0x30 == 0) as usize), + 0xF7 => (true, if *c.get(i)? & 0x30 == 0 { immz } else { 0 }), + _ => return None, + }; + if modrm { + let m = *c.get(i)?; + i += 1; + let (md, rm) = (m >> 6, m & 7); + if md != 3 { + let mut base = rm; + if rm == 4 { + base = *c.get(i)? & 7; + i += 1; + } + imm += match md { + 0 if base == 5 => 4, + 0 => 0, + 1 => 1, + _ => 4, + }; + } + } + i += imm; + (i <= 15 && i <= c.len()).then_some(i) +} + +/// Which of the four instructions: the element size and what the log calls it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// VEX.66.0F38.W0 2E /r: VMASKMOVPS m, mask, src + Ps, + /// VEX.66.0F38.W0 2F /r: VMASKMOVPD m, mask, src + Pd, + /// VEX.66.0F38.W0 8E /r: VPMASKMOVD m, mask, src + D, + /// VEX.66.0F38.W1 8E /r: VPMASKMOVQ m, mask, src + Q, +} + +impl Kind { + pub const ALL: [Kind; 4] = [Kind::Ps, Kind::Pd, Kind::D, Kind::Q]; + + pub fn name(self) -> &'static str { + match self { + Kind::Ps => "VMASKMOVPS", + Kind::Pd => "VMASKMOVPD", + Kind::D => "VPMASKMOVD", + Kind::Q => "VPMASKMOVQ", + } + } + + /// Bytes of one element. + pub fn element(self) -> usize { + match self { + Kind::Ps | Kind::D => 4, + Kind::Pd | Kind::Q => 8, + } + } +} + +/// The memory operand: base + index * 2^scale + disp, or the next instruction's address + disp. +/// Registers are the hardware's numbers (4 RSP, 8–15 R8–R15). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Mem { + pub base: Option<u8>, + pub index: Option<u8>, + pub scale: u8, + pub disp: i32, + pub rip: bool, +} + +/// A masked store. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Store { + pub kind: Kind, + /// Length in bytes (5..=10). + pub len: u8, + /// 256 bits (YMM); else 128 (XMM). + pub wide: bool, + /// The register stored from (ModRM reg) and the mask register (VEX.vvvv). + pub src: u8, + pub mask: u8, + pub mem: Mem, +} + +impl Store { + /// Number of elements. + pub fn elements(&self) -> usize { + (if self.wide { 32 } else { 16 }) / self.kind.element() + } +} + +/// The first five bytes of every masked store: three-byte VEX with map 0F38 and prefix 66, one +/// of the three opcodes, a ModRM byte with a memory operand. +pub fn is_candidate(c: &[u8]) -> bool { + matches!(c, [0xC4, b1, b2, 0x2E | 0x2F | 0x8E, m, ..] if b1 & 0x1F == 2 && b2 & 3 == 1 && m >> 6 != 3) +} + +/// Decodes the masked store at the start of `c` (`None`: not one, or cut short). A prefix in +/// front (a segment override, 32-bit addressing) makes it another instruction start, which +/// this does not take. +pub fn decode(c: &[u8]) -> Option<Store> { + if !is_candidate(c) { + return None; + } + let (b1, b2, m) = (c[1], c[2], c[4]); + let (r, x, b, w) = ((!b1 >> 7) & 1, (!b1 >> 6) & 1, (!b1 >> 5) & 1, b2 >> 7); + let kind = match (c[3], w) { + (0x2E, 0) => Kind::Ps, + (0x2F, 0) => Kind::Pd, + (0x8E, 0) => Kind::D, + (0x8E, _) => Kind::Q, + _ => return None, // W1 of the floating-point forms is not an instruction + }; + let (md, rm) = (m >> 6, m & 7); + let mut i = 5; + let (mut base, mut index, mut scale, mut rip) = (None, None, 0, false); + let mut disp_len = match md { + 1 => 1, + 2 => 4, + _ => 0, + }; + if rm == 4 { + let sib = *c.get(i)?; + i += 1; + scale = sib >> 6; + let ix = ((sib >> 3) & 7) | x << 3; + if ix != 4 { + index = Some(ix); // index 4 without VEX.X: none (R12 is an index) + } + if sib & 7 == 5 && md == 0 { + disp_len = 4; // disp32 without a base + } else { + base = Some((sib & 7) | b << 3); + } + } else if rm == 5 && md == 0 { + rip = true; + disp_len = 4; + } else { + base = Some(rm | b << 3); + } + let disp = match disp_len { + 1 => *c.get(i)? as i8 as i32, + 4 => i32::from_le_bytes([*c.get(i)?, *c.get(i + 1)?, *c.get(i + 2)?, *c.get(i + 3)?]), + _ => 0, + }; + i += disp_len; + Some(Store { kind, len: i as u8, wide: b2 & 4 != 0, src: ((m >> 3) & 7) | r << 3, mask: (!b2 >> 3) & 15, mem: Mem { base, index, scale, disp, rip } }) +} + +/// Largest helper `helper` writes. +pub const HELPER_MAX: usize = 192; + +/// What a helper has between the site's RSP and its own while it stores: the return address, +/// four saved registers and 64 bytes for the two vectors. +const FRAME: i64 = 8 + 32 + 64; + +/// `push rax; push rcx; push rdx; push r8; lea rsp, [rsp - 64]` – every helper starts with it, +/// which is what `UNWIND_INFO` describes. +const PROLOGUE: [u8; 10] = [0x50, 0x51, 0x52, 0x41, 0x50, 0x48, 0x8D, 0x64, 0x24, 0xC0]; +/// `lea rsp, [rsp + 64]; pop r8; pop rdx; pop rcx; pop rax; ret` +const EPILOGUE: [u8; 11] = [0x48, 0x8D, 0x64, 0x24, 0x40, 0x41, 0x58, 0x5A, 0x59, 0x58, 0xC3]; + +/// The unwind data all helpers share (UNWIND_INFO, version 1): a ten-byte prologue that +/// allocates 64 bytes after pushing R8, RDX, RCX and RAX. With it a fault in a helper that no +/// one repairs is unwound into the title's function like one at the store itself. +pub const UNWIND_INFO: [u8; 16] = [ + 0x01, PROLOGUE.len() as u8, 5, 0, // version 1, prologue size, five codes, no frame register + 10, 0x72, // after `lea rsp`: UWOP_ALLOC_SMALL, (7 + 1) * 8 bytes + 5, 0x80, // after `push r8`: UWOP_PUSH_NONVOL r8 + 3, 0x20, // rdx + 2, 0x10, // rcx + 1, 0x00, // rax + 0, 0, +]; + +/// `vmovdqu [rsp + disp], reg` (XMM, or YMM when `wide`). +fn spill(out: &mut Vec<u8>, reg: u8, wide: bool, disp: u8) { + out.extend_from_slice(&[0xC5, (if reg < 8 { 0x80 } else { 0 }) | 0x7A | (wide as u8) << 2, 0x7F]); + if disp == 0 { + out.extend_from_slice(&[0x04 | (reg & 7) << 3, 0x24]); + } else { + out.extend_from_slice(&[0x44 | (reg & 7) << 3, 0x24, disp]); + } +} + +/// Appends to `out` position-independent code that does what the store `s` does and returns: +/// the code a `call` written over the store reaches. `next` is the address of the instruction +/// after the store (what a RIP-relative operand counts from). `false`: nothing was appended – +/// an RSP-relative displacement that does not fit once the helper's frame is added. +/// +/// The address is taken first, into R8, while every register still holds the title's value +/// (RSP is lower by `FRAME`, which the displacement makes up for). The source and the mask go +/// to the stack with two unaligned vector stores, and each element is then +/// `mov eax, mask[i]; cdq; mov ecx, edx; jrcxz skip; mov eax, src[i]; mov [r8 + 4 i], eax` +/// (with RAX / CQO for 8-byte elements): CDQ copies the mask's sign bit into every bit of EDX, +/// JRCXZ branches on RCX without a flag. Nothing in it writes a flag or a vector register. +pub fn helper(s: &Store, next: u64, out: &mut Vec<u8>) -> bool { + let start = out.len(); + out.extend_from_slice(&PROLOGUE); + let Mem { base, index, scale, disp, rip } = s.mem; + if rip { + // mov r8, imm64 + out.extend_from_slice(&[0x49, 0xB8]); + out.extend_from_slice(&next.wrapping_add(disp as i64 as u64).to_le_bytes()); + } else { + let disp = disp as i64 + if base == Some(4) { FRAME } else { 0 }; + let Ok(disp) = i32::try_from(disp) else { + out.truncate(start); + return false; + }; + // lea r8, [base + index * 2^scale + disp] + out.extend_from_slice(&[0x4C | index.map_or(0, |x| x >> 3) << 1 | base.map_or(0, |b| b >> 3), 0x8D]); + let sib = scale << 6 | index.map_or(4, |x| x & 7) << 3; + match base { + None => { + out.extend_from_slice(&[0x04, sib | 5]); + out.extend_from_slice(&disp.to_le_bytes()); + } + Some(b) => { + // RBP / R13 as a base have no form without a displacement + let md = if disp == 0 && b & 7 != 5 { + 0 + } else if i8::try_from(disp).is_ok() { + 1 + } else { + 2 + }; + if index.is_some() || b & 7 == 4 { + out.extend_from_slice(&[md << 6 | 4, sib | (b & 7)]); + } else { + out.push(md << 6 | (b & 7)); + } + match md { + 1 => out.push(disp as u8), + 2 => out.extend_from_slice(&disp.to_le_bytes()), + _ => {} + } + } + } + } + spill(out, s.src, s.wide, 0); + spill(out, s.mask, s.wide, 0x20); + for i in 0..s.elements() { + let d = (i * s.kind.element()) as u8; + if s.kind.element() == 4 { + out.extend_from_slice(&[0x8B, 0x44, 0x24, 0x20 + d, 0x99, 0x89, 0xD1, 0xE3, 0x08]); + out.extend_from_slice(&[0x8B, 0x44, 0x24, d, 0x41, 0x89, 0x40, d]); + } else { + out.extend_from_slice(&[0x48, 0x8B, 0x44, 0x24, 0x20 + d, 0x48, 0x99, 0x89, 0xD1, 0xE3, 0x09]); + out.extend_from_slice(&[0x48, 0x8B, 0x44, 0x24, d, 0x49, 0x89, 0x40, d]); + } + } + out.extend_from_slice(&EPILOGUE); + debug_assert!(out.len() - start <= HELPER_MAX); + true +} + +/// The bytes that replace a store of `len` bytes at `site`: `call helper`, then NOPs (the +/// first `len` of the array). `None`: the helper is out of the call's ±2 GiB reach. +pub fn call_site(site: u64, len: u8, helper: u64) -> Option<[u8; 10]> { + if !(5..=10).contains(&len) { + return None; + } + let rel = i32::try_from(helper.wrapping_sub(site.wrapping_add(5)) as i64).ok()?; + let mut b = [0x90u8; 10]; + b[0] = 0xE8; + b[1..5].copy_from_slice(&rel.to_le_bytes()); + Some(b) +} + +/// Why a byte pattern was left as it is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Skip { + /// In no function of the unwind data, and further than `GAP_MAX` from the end of one. + NoFunction, + /// An instruction on the way there (at this RVA) is not one `insn_len` knows. + Undecodable(u32), + /// The walk passes over it: the bytes are part of another instruction (or follow a prefix). + NotAtBoundary, + /// At a boundary but not a store `decode` and `helper` take. + Form, +} + +/// How far behind the end of a function with unwind data a leaf function's store may be. +pub const GAP_MAX: u32 = 0x1_0000; + +/// A store to replace. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Site { + pub rva: u32, + pub store: Store, + /// Offset of its helper in `Plan::code`. + pub helper: u32, + /// Not in a function of the unwind data: found by the walk from the end of the one before. + pub leaf: bool, +} + +/// What to do to an image. +#[derive(Default, Debug)] +pub struct Plan { + pub sites: Vec<Site>, + pub skipped: Vec<(u32, Skip)>, + /// The helpers, each at a multiple of 16; stores with the same bytes share one. + pub code: Vec<u8>, + /// (start, end) of each helper in `code`, ascending. + pub helpers: Vec<(u32, u32)>, +} + +/// Finds the masked stores in the executable sections of a mapped image and writes their +/// helpers. `image` is the image as mapped (relocated), `base` its address, `sections` the +/// (RVA, length) of each executable section and `functions` the (start, end) RVAs of the +/// unwind data's entries. +/// +/// A byte pattern alone is not taken: the instructions are walked from the start of the +/// function that contains it, and the walk has to arrive exactly at it. A pattern outside +/// every function is walked to from the end of the function before it (a leaf function has no +/// unwind data; the padding between functions is one-byte instructions). +pub fn plan(image: &[u8], base: u64, sections: &[(u32, u32)], functions: &[(u32, u32)]) -> Plan { + let mut p = Plan::default(); + let mut funcs: Vec<(u32, u32)> = functions.iter().copied().filter(|f| f.0 < f.1).collect(); + funcs.sort_unstable(); + // helpers by the store's bytes (and, for a RIP-relative operand, its place) + let mut shared: std::collections::HashMap<([u8; 10], u32), u32> = std::collections::HashMap::new(); + for &(s_rva, s_len) in sections { + let (s_start, s_end) = (s_rva as usize, (s_rva as usize).saturating_add(s_len as usize).min(image.len())); + let Some(code) = image.get(s_start..s_end) else { continue }; + // where the last walk started and how far it got + let (mut anchor, mut cursor) = (usize::MAX, 0usize); + let mut at = 0; + while let Some(k) = code[at..].iter().position(|&b| b == 0xC4) { + let site = at + k; + at = site + 1; + if !is_candidate(&code[site..]) { + continue; + } + let rva = (s_start + site) as u32; + let before = funcs.partition_point(|f| f.0 <= rva); + let (from, leaf) = match before.checked_sub(1).map(|i| funcs[i]) { + Some((start, end)) if rva < end => (start as usize, false), + Some((_, end)) if end as usize >= s_start && rva - end <= GAP_MAX => (end as usize, true), + _ => { + p.skipped.push((rva, Skip::NoFunction)); + continue; + } + }; + if from < s_start { + p.skipped.push((rva, Skip::NoFunction)); + continue; + } + let from = from - s_start; + if anchor != from || cursor > site { + (anchor, cursor) = (from, from); + } + let mut bad = None; + while cursor < site { + match insn_len(&code[cursor..]) { + Some(n) => cursor += n, + None => { + bad = Some(Skip::Undecodable((s_start + cursor) as u32)); + anchor = usize::MAX; + break; + } + } + } + if bad.is_none() && cursor != site { + bad = Some(Skip::NotAtBoundary); + } + if let Some(why) = bad { + p.skipped.push((rva, why)); + continue; + } + let Some(store) = decode(&code[site..]).filter(|s| insn_len(&code[site..]) == Some(s.len as usize)) else { + p.skipped.push((rva, Skip::Form)); + continue; + }; + let mut key = ([0u8; 10], 0); + key.0[..store.len as usize].copy_from_slice(&code[site..site + store.len as usize]); + if store.mem.rip { + key.1 = rva; + } + let helper_at = match shared.get(&key) { + Some(&h) => h, + None => { + while p.code.len() % 16 != 0 { + p.code.push(0xCC); + } + let h = p.code.len() as u32; + if !helper(&store, base + rva as u64 + store.len as u64, &mut p.code) { + p.skipped.push((rva, Skip::Form)); + continue; + } + p.helpers.push((h, p.code.len() as u32)); + shared.insert(key, h); + h + } + }; + p.sites.push(Site { rva, store, helper: helper_at, leaf }); + } + } + p +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Lengths as an assembler gives them, for the kinds of instruction a function has on the + /// way to a masked store – and `None` for what must stop a walk. + #[test] + fn instruction_lengths() { + let cases: &[(&[u8], usize)] = &[ + (&[0x90], 1), // nop + (&[0xC3], 1), // ret + (&[0x55], 1), // push rbp + (&[0x41, 0x57], 2), // push r15 + (&[0x48, 0x83, 0xEC, 0x28], 4), // sub rsp, 0x28 + (&[0x48, 0x81, 0xEC, 0x88, 0x00, 0x00, 0x00], 7), // sub rsp, 0x88 + (&[0x48, 0x8B, 0x05, 1, 2, 3, 4], 7), // mov rax, [rip + disp32] + (&[0x48, 0x8B, 0x44, 0x24, 0x08], 5), // mov rax, [rsp + 8] + (&[0x4A, 0x8D, 0x04, 0xC5, 0, 0, 0, 0], 8), // lea rax, [r8 * 8 + disp32] + (&[0x48, 0xB8, 1, 2, 3, 4, 5, 6, 7, 8], 10), // mov rax, imm64 + (&[0xB8, 1, 2, 3, 4], 5), // mov eax, imm32 + (&[0x66, 0xB8, 1, 2], 4), // mov ax, imm16 + (&[0x66, 0xC7, 0x00, 1, 2], 5), // mov word [rax], imm16 + (&[0xC7, 0x04, 0x25, 0, 0, 0, 0, 1, 2, 3, 4], 11), // mov dword [0], imm32 + (&[0xF6, 0xC1, 0x01], 3), // test cl, 1 + (&[0xF6, 0xD9], 2), // neg cl + (&[0xF7, 0xC1, 1, 2, 3, 4], 6), // test ecx, imm32 + (&[0x48, 0xF7, 0xD8], 3), // neg rax + (&[0xE8, 1, 2, 3, 4], 5), // call + (&[0x74, 0x10], 2), // je + (&[0x0F, 0x84, 1, 2, 3, 4], 6), // je rel32 + (&[0xF2, 0xC3], 2), // bnd ret + (&[0xFF, 0x15, 1, 2, 3, 4], 6), // call [rip + disp32] + (&[0x48, 0xA1, 1, 2, 3, 4, 5, 6, 7, 8], 10), // mov rax, [moffs64] + (&[0x66, 0x66, 0x2E, 0x0F, 0x1F, 0x84, 0x00, 0, 0, 0, 0], 11), // nop word cs:[rax + rax + disp32] + (&[0x0F, 0x1F, 0x44, 0x00, 0x00], 5), // nop dword [rax + rax + 0] + (&[0x0F, 0xBA, 0xE0, 0x07], 4), // bt eax, 7 + (&[0x66, 0x0F, 0x3A, 0x0F, 0xC1, 0x08], 6), // palignr xmm0, xmm1, 8 + (&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10], 6), // insertq xmm0, xmm1, 8, 16 + (&[0x0F, 0x01, 0xFC], 3), // clzero + (&[0xF3, 0x48, 0x0F, 0xB8, 0xC1], 5), // popcnt rax, rcx + (&[0xC5, 0xF8, 0x77], 3), // vzeroupper + (&[0xC5, 0xFE, 0x7F, 0x04, 0x24], 5), // vmovdqu [rsp], ymm0 + (&[0xC5, 0xF9, 0x70, 0xC1, 0x1B], 5), // vpshufd xmm0, xmm1, 0x1B + (&[0xC4, 0xE2, 0x7D, 0x21, 0x05, 1, 2, 3, 4], 9), // vpmovsxbd ymm0, [rip + disp32] + (&[0xC4, 0xE3, 0x7D, 0x39, 0xC1, 0x01], 6), // vextracti128 xmm1, ymm0, 1 + (&[0xC4, 0xE3, 0x75, 0x4C, 0xC2, 0x30], 6), // vpblendvb ymm0, ymm1, ymm2, ymm3 + (&[0xC4, 0xE2, 0x4D, 0x8E, 0x04, 0x90], 6), // vpmaskmovd [rax + 4 * rdx], ymm6, ymm0 + (&[0xC4, 0xE2, 0xF8, 0xF7, 0xC1], 5), // bextr rax, rcx, rax + ]; + for (code, len) in cases { + assert_eq!(insn_len(code), Some(*len), "{code:02x?}"); + // followed by other bytes it is no longer, cut short it is nothing + let mut more = code.to_vec(); + more.extend_from_slice(&[0xC4; 16]); + assert_eq!(insn_len(&more), Some(*len), "{code:02x?} with a tail"); + assert_eq!(insn_len(&code[..len - 1]), None, "{code:02x?} cut short"); + } + // EVEX, an opcode 64-bit mode does not have, XOP, 3DNow!, a far jump, REX before VEX, and + // the first word of a jump table a function kept in its code (8E /6: no such register) + for code in [&[0x62, 0xF1, 0x7C, 0x48, 0x10, 0x00][..], &[0x06], &[0x8F, 0xE8, 0x78, 0xC2, 0xC1, 0x04], &[0x0F, 0x0F, 0xC1, 0x9E], &[0xEA], &[0x41, 0xC5, 0xF8, 0x77], &[0x8E, 0xB2, 0x5E, 0x05, 0x98, 0xB2]] { + assert_eq!(insn_len(code), None, "{code:02x?}"); + } + } + + const NO_MEM: Mem = Mem { base: None, index: None, scale: 0, disp: 0, rip: false }; + + /// Every shape of the instruction a retail game has (1,130 sites: lengths 5, 6, 7, 9 and + /// 10; RSP, R12, R13 as bases; XMM forms), plus the ones it has not: RIP-relative, an + /// address without a base. + #[test] + fn decodes_the_masked_stores() { + let mem = |base, index, scale, disp| Mem { base, index, scale, disp, rip: false }; + let cases: &[(&[u8], Kind, bool, u8, u8, Mem)] = &[ + // vpmaskmovq [rsp + r8 + 0x40], ymm7, ymm8 + (&[0xC4, 0x22, 0xC5, 0x8E, 0x44, 0x04, 0x40], Kind::Q, true, 8, 7, mem(Some(4), Some(8), 0, 0x40)), + // vmaskmovps [rcx + 4 * rdx], ymm4, ymm5 + (&[0xC4, 0xE2, 0x5D, 0x2E, 0x2C, 0x91], Kind::Ps, true, 5, 4, mem(Some(1), Some(2), 2, 0)), + // vpmaskmovd [r12 + 4 * r8], ymm5, ymm6 + (&[0xC4, 0x82, 0x55, 0x8E, 0x34, 0x84], Kind::D, true, 6, 5, mem(Some(12), Some(8), 2, 0)), + // vpmaskmovd [rcx], ymm7, ymm6 + (&[0xC4, 0xE2, 0x45, 0x8E, 0x31], Kind::D, true, 6, 7, mem(Some(1), None, 0, 0)), + // vpmaskmovq [rax + 8 * r9], ymm4, ymm5 + (&[0xC4, 0xA2, 0xDD, 0x8E, 0x2C, 0xC8], Kind::Q, true, 5, 4, mem(Some(0), Some(9), 3, 0)), + // vpmaskmovd [rsi + rcx], ymm12, ymm13 + (&[0xC4, 0x62, 0x1D, 0x8E, 0x2C, 0x0E], Kind::D, true, 13, 12, mem(Some(6), Some(1), 0, 0)), + // vpmaskmovd [rsp + 4 * rcx + 0x4e0], ymm7, ymm0 + (&[0xC4, 0xE2, 0x45, 0x8E, 0x84, 0x8C, 0xE0, 0x04, 0x00, 0x00], Kind::D, true, 0, 7, mem(Some(4), Some(1), 2, 0x4E0)), + // vpmaskmovd [rsp + 0x90], ymm1, ymm0; vpmaskmovd [rsp], ymm1, ymm0 + (&[0xC4, 0xE2, 0x75, 0x8E, 0x84, 0x24, 0x90, 0x00, 0x00, 0x00], Kind::D, true, 0, 1, mem(Some(4), None, 0, 0x90)), + (&[0xC4, 0xE2, 0x75, 0x8E, 0x04, 0x24], Kind::D, true, 0, 1, mem(Some(4), None, 0, 0)), + // vmaskmovpd [rdx + 8 * rcx], ymm5, ymm6 + (&[0xC4, 0xE2, 0x55, 0x2F, 0x34, 0xCA], Kind::Pd, true, 6, 5, mem(Some(2), Some(1), 3, 0)), + // vpmaskmovq [r10 + 8 * r11 - 8], ymm4, ymm5 + (&[0xC4, 0x82, 0xDD, 0x8E, 0x6C, 0xDA, 0xF8], Kind::Q, true, 5, 4, mem(Some(10), Some(11), 3, -8)), + // vpmaskmovd [r13], xmm2, xmm1 (R13 needs a displacement byte); vpmaskmovd [rbp + 0x10], xmm15, xmm9 + (&[0xC4, 0xC2, 0x69, 0x8E, 0x4D, 0x00], Kind::D, false, 1, 2, mem(Some(13), None, 0, 0)), + (&[0xC4, 0x62, 0x01, 0x8E, 0x4D, 0x10], Kind::D, false, 9, 15, mem(Some(5), None, 0, 0x10)), + // vpmaskmovd [rip + 0x1000], ymm1, ymm0 + (&[0xC4, 0xE2, 0x75, 0x8E, 0x05, 0x00, 0x10, 0x00, 0x00], Kind::D, true, 0, 1, Mem { disp: 0x1000, rip: true, ..NO_MEM }), + // vmaskmovps [4 * rcx + 0x12345678], xmm1, xmm0; vpmaskmovq [0x12345678], ymm1, ymm0 + (&[0xC4, 0xE2, 0x71, 0x2E, 0x04, 0x8D, 0x78, 0x56, 0x34, 0x12], Kind::Ps, false, 0, 1, mem(None, Some(1), 2, 0x1234_5678)), + (&[0xC4, 0xE2, 0xF5, 0x8E, 0x04, 0x25, 0x78, 0x56, 0x34, 0x12], Kind::Q, true, 0, 1, mem(None, None, 0, 0x1234_5678)), + ]; + for (code, kind, wide, src, mask, mem) in cases { + let want = Store { kind: *kind, len: code.len() as u8, wide: *wide, src: *src, mask: *mask, mem: *mem }; + assert_eq!(decode(code), Some(want), "{code:02x?}"); + assert_eq!(insn_len(code), Some(code.len()), "{code:02x?}"); + assert_eq!(decode(&code[..code.len() - 1]), None, "{code:02x?} cut short"); + } + assert_eq!(decode(&cases[0].0[..]).unwrap().elements(), 4); + assert_eq!(decode(&cases[11].0[..]).unwrap().elements(), 4); + assert_eq!(decode(&cases[14].0[..]).unwrap().elements(), 4); + assert_eq!(decode(&cases[15].0[..]).unwrap().elements(), 4); + assert_eq!(decode(&cases[1].0[..]).unwrap().elements(), 8); + // the loads (8C, 2C, 2D), a register "destination", VMASKMOVPS with W1, another map: not stores + for code in [[0xC4, 0xE2, 0x4D, 0x8C, 0x04, 0x90], [0xC4, 0xE2, 0x5D, 0x2C, 0x2C, 0x91], [0xC4, 0xE2, 0x4D, 0x8E, 0xC1, 0x90], [0xC4, 0xE2, 0xDD, 0x2E, 0x2C, 0x91], [0xC4, 0xE3, 0x4D, 0x8E, 0x04, 0x90], [0xC4, 0xE2, 0x4E, 0x8E, 0x04, 0x90]] { + assert_eq!(decode(&code), None, "{code:02x?}"); + } + } + + /// A helper as bytes: the prologue the unwind data describes, the address into R8 with the + /// frame added to an RSP-relative displacement, both vectors to the stack, one guarded + /// `mov` per element, the epilogue. And the call that reaches it. + #[test] + fn a_helper_is_the_address_two_spills_and_a_store_per_element() { + // vpmaskmovq [rsp + r8 + 0x40], ymm7, ymm8 + let s = decode(&[0xC4, 0x22, 0xC5, 0x8E, 0x44, 0x04, 0x40]).unwrap(); + let mut out = Vec::new(); + assert!(helper(&s, 0, &mut out)); + let mut want = PROLOGUE.to_vec(); + want.extend_from_slice(&[0x4E, 0x8D, 0x84, 0x04, 0xA8, 0x00, 0x00, 0x00]); // lea r8, [rsp + r8 + 0x40 + 104] + want.extend_from_slice(&[0xC5, 0x7E, 0x7F, 0x04, 0x24]); // vmovdqu [rsp], ymm8 + want.extend_from_slice(&[0xC5, 0xFE, 0x7F, 0x7C, 0x24, 0x20]); // vmovdqu [rsp + 0x20], ymm7 + for d in [0u8, 8, 16, 24] { + want.extend_from_slice(&[0x48, 0x8B, 0x44, 0x24, 0x20 + d, 0x48, 0x99, 0x89, 0xD1, 0xE3, 0x09, 0x48, 0x8B, 0x44, 0x24, d, 0x49, 0x89, 0x40, d]); + } + want.extend_from_slice(&EPILOGUE); + assert_eq!(out, want); + // the largest: eight 4-byte elements and a RIP-relative operand (an absolute address) + let s = decode(&[0xC4, 0xE2, 0x75, 0x8E, 0x05, 0x00, 0x10, 0x00, 0x00]).unwrap(); + let mut out = vec![0xCC; 3]; + assert!(helper(&s, 0x1_4000_2009, &mut out)); + assert_eq!(out[3 + 10..3 + 20], [0x49, 0xB8, 0x09, 0x30, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00]); + assert!(out.len() - 3 <= HELPER_MAX && out.len() - 3 == 10 + 10 + 11 + 8 * 17 + 11); + // vpmaskmovd [r13], xmm2, xmm1: R13 keeps its displacement byte, an XMM store has four elements + let s = decode(&[0xC4, 0xC2, 0x69, 0x8E, 0x4D, 0x00]).unwrap(); + let mut out = Vec::new(); + assert!(helper(&s, 0, &mut out)); + assert_eq!(out[10..14], [0x4D, 0x8D, 0x45, 0x00]); // lea r8, [r13 + 0] + assert_eq!(out[14..18], [0xC5, 0xFA, 0x7F, 0x0C]); // vmovdqu [rsp], xmm1 + assert_eq!(out.len(), 10 + 4 + 11 + 4 * 17 + 11); + // an RSP-relative displacement that no longer fits is declined, and nothing is left behind + let s = Store { mem: Mem { base: Some(4), disp: i32::MAX - 50, ..NO_MEM }, ..s }; + assert!(!helper(&s, 0, &mut out) && out.len() == 10 + 4 + 11 + 4 * 17 + 11); + // the prologue the unwind data counts: 4 pushes (5 bytes) and the allocation end at byte 10 + assert_eq!((UNWIND_INFO[1], UNWIND_INFO[2], UNWIND_INFO[4]), (10, 5, 10)); + assert_eq!(FRAME, 8 + 4 * 8 + ((UNWIND_INFO[5] >> 4) as i64 + 1) * 8); + let call = call_site(0x1_4007_9D67, 6, 0x1_4B07_0000).unwrap(); + assert_eq!(call[..6], [0xE8, 0x94, 0x62, 0xFF, 0x0A, 0x90]); + assert_eq!(call_site(0x1_4007_9D67, 6, 0x2_4B07_0000), None, "out of reach"); + assert_eq!(call_site(0x1_4007_9D67, 4, 0x1_4B07_0000), None, "too short for a call"); + } + + /// The sites of a made-up image: a store in a function, one in a leaf function behind it, + /// the same bytes inside another instruction, behind bytes that are no instruction, and + /// far from any function. + #[test] + fn a_site_is_a_pattern_the_walk_from_its_function_arrives_at() { + const STORE: [u8; 6] = [0xC4, 0xE2, 0x4D, 0x8E, 0x04, 0x90]; // vpmaskmovd [rax + 4 * rdx], ymm6, ymm0 + const OTHER: [u8; 5] = [0xC4, 0xE2, 0x45, 0x8E, 0x31]; // vpmaskmovd [rcx], ymm7, ymm6 + let mut image = vec![0xCCu8; 0x4_0000]; + let mut put = |at: usize, bytes: &[u8]| image[at..at + bytes.len()].copy_from_slice(bytes); + // function 0x1000..0x1020: push rbx; sub rsp, 0x20; STORE; STORE; add rsp, 0x20; pop rbx; ret + put(0x1000, &[0x53, 0x48, 0x83, 0xEC, 0x20]); + put(0x1005, &STORE); + put(0x100B, &STORE); + put(0x1011, &[0x48, 0x83, 0xC4, 0x20, 0x5B, 0xC3]); + // a leaf function behind its padding: xor eax, eax; OTHER; ret + put(0x1030, &[0x31, 0xC0]); + put(0x1032, &OTHER); + put(0x1037, &[0xC3]); + // function 0x2000..0x2040: mov rax, imm64 whose immediate is the pattern; then a real one + put(0x2000, &[0x48, 0xB8]); + put(0x2002, &STORE); + put(0x2008, &[0x90, 0x90]); + put(0x200A, &OTHER); + put(0x200F, &[0xC3]); + // function 0x3000..0x3040: an EVEX instruction before the pattern + put(0x3000, &[0x62, 0xF1, 0x7C, 0x48, 0x10, 0x00]); + put(0x3006, &STORE); + // far behind the last function + put(0x2_8000, &STORE); + let functions = [(0x3000, 0x3040), (0x1000, 0x1017), (0x2000, 0x2040)]; + let p = plan(&image, 0x1_4000_0000, &[(0x1000, 0x3_F000)], &functions); + let sites: Vec<(u32, bool, u32)> = p.sites.iter().map(|s| (s.rva, s.leaf, s.helper)).collect(); + let second = p.helpers[1].0; + assert_eq!(sites, [(0x1005, false, 0), (0x100B, false, 0), (0x1032, true, second), (0x200A, false, second)]); + assert_eq!(p.skipped, [(0x2002, Skip::NotAtBoundary), (0x3006, Skip::Undecodable(0x3000)), (0x2_8000, Skip::NoFunction)]); + assert_eq!(p.helpers.len(), 2, "stores with the same bytes share a helper"); + assert!(second % 16 == 0 && p.helpers[0] == (0, 10 + 4 + 11 + 8 * 17 + 11) && p.helpers[1].1 as usize == p.code.len()); + // a section that ends inside the pattern, and one with no function before it + assert!(plan(&image, 0, &[(0x1000, 8)], &functions).sites.is_empty()); + assert_eq!(plan(&image, 0, &[(0x1000, 0x100)], &[]).skipped.len(), 3); + } +} + +/// The helpers run against the instructions they stand for, on a CPU (or translator) that has +/// AVX2: a made-up register file is loaded, the code is called, the register file is taken +/// back, and the two runs are compared with each other and with what the instruction is +/// defined to do. +#[cfg(all(test, windows, target_arch = "x86_64"))] +pub(crate) mod exec { + use super::*; + use std::ffi::c_void; + use std::sync::atomic::{AtomicUsize, Ordering}; + use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, RemoveVectoredExceptionHandler, EXCEPTION_POINTERS}; + use windows_sys::Win32::System::Memory::{ + GetWriteWatch, ResetWriteWatch, VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READONLY, PAGE_READWRITE, + }; + + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + /// Everything a masked store could change but memory: the general registers (the hardware's + /// order; RSP's slot is not used), the flags, YMM0–15 and 512 bytes of stack right above + /// the call (`[rsp + 0x18]` at the instruction is its first byte). + #[repr(C)] + #[derive(Clone, PartialEq, Eq, Debug)] + pub(crate) struct State { + pub gpr: [u64; 16], + pub flags: u64, + pub unused: u64, + pub ymm: [[u8; 32]; 16], + pub stack: [u8; 512], + } + + /// `[rsp + STACK_AT]` at the instruction under test is `State::stack[0]`: above the return + /// address and the two pointers `xcl_maskmov_test_run` keeps there. + pub(crate) const STACK_AT: i32 = 0x18; + + std::arch::global_asm!( + r#" + .globl xcl_maskmov_test_run + xcl_maskmov_test_run: + push rbx + push rbp + push rsi + push rdi + push r12 + push r13 + push r14 + push r15 + sub rsp, 0xA8 + vmovdqu [rsp + 0x00], xmm6 + vmovdqu [rsp + 0x10], xmm7 + vmovdqu [rsp + 0x20], xmm8 + vmovdqu [rsp + 0x30], xmm9 + vmovdqu [rsp + 0x40], xmm10 + vmovdqu [rsp + 0x50], xmm11 + vmovdqu [rsp + 0x60], xmm12 + vmovdqu [rsp + 0x70], xmm13 + vmovdqu [rsp + 0x80], xmm14 + vmovdqu [rsp + 0x90], xmm15 + sub rsp, 0x200 + mov r10, rcx + mov r11, rdx + lea rsi, [r10 + 0x290] + mov rdi, rsp + mov ecx, 0x200 + cld + rep movsb + push r11 + push r10 + vmovdqu ymm0, [r10 + 0x090] + vmovdqu ymm1, [r10 + 0x0B0] + vmovdqu ymm2, [r10 + 0x0D0] + vmovdqu ymm3, [r10 + 0x0F0] + vmovdqu ymm4, [r10 + 0x110] + vmovdqu ymm5, [r10 + 0x130] + vmovdqu ymm6, [r10 + 0x150] + vmovdqu ymm7, [r10 + 0x170] + vmovdqu ymm8, [r10 + 0x190] + vmovdqu ymm9, [r10 + 0x1B0] + vmovdqu ymm10, [r10 + 0x1D0] + vmovdqu ymm11, [r10 + 0x1F0] + vmovdqu ymm12, [r10 + 0x210] + vmovdqu ymm13, [r10 + 0x230] + vmovdqu ymm14, [r10 + 0x250] + vmovdqu ymm15, [r10 + 0x270] + push qword ptr [r10 + 0x80] + popfq + mov rax, [r10 + 0x00] + mov rcx, [r10 + 0x08] + mov rdx, [r10 + 0x10] + mov rbx, [r10 + 0x18] + mov rbp, [r10 + 0x28] + mov rsi, [r10 + 0x30] + mov rdi, [r10 + 0x38] + mov r8, [r10 + 0x40] + mov r9, [r10 + 0x48] + mov r11, [r10 + 0x58] + mov r12, [r10 + 0x60] + mov r13, [r10 + 0x68] + mov r14, [r10 + 0x70] + mov r15, [r10 + 0x78] + mov r10, [r10 + 0x50] + call qword ptr [rsp + 8] + xchg r10, [rsp] + mov [r10 + 0x00], rax + mov [r10 + 0x08], rcx + mov [r10 + 0x10], rdx + mov [r10 + 0x18], rbx + mov [r10 + 0x28], rbp + mov [r10 + 0x30], rsi + mov [r10 + 0x38], rdi + mov [r10 + 0x40], r8 + mov [r10 + 0x48], r9 + mov [r10 + 0x58], r11 + mov [r10 + 0x60], r12 + mov [r10 + 0x68], r13 + mov [r10 + 0x70], r14 + mov [r10 + 0x78], r15 + pop rax + mov [r10 + 0x50], rax + pushfq + pop rax + mov [r10 + 0x80], rax + vmovdqu [r10 + 0x090], ymm0 + vmovdqu [r10 + 0x0B0], ymm1 + vmovdqu [r10 + 0x0D0], ymm2 + vmovdqu [r10 + 0x0F0], ymm3 + vmovdqu [r10 + 0x110], ymm4 + vmovdqu [r10 + 0x130], ymm5 + vmovdqu [r10 + 0x150], ymm6 + vmovdqu [r10 + 0x170], ymm7 + vmovdqu [r10 + 0x190], ymm8 + vmovdqu [r10 + 0x1B0], ymm9 + vmovdqu [r10 + 0x1D0], ymm10 + vmovdqu [r10 + 0x1F0], ymm11 + vmovdqu [r10 + 0x210], ymm12 + vmovdqu [r10 + 0x230], ymm13 + vmovdqu [r10 + 0x250], ymm14 + vmovdqu [r10 + 0x270], ymm15 + pop rax + lea rdi, [r10 + 0x290] + mov rsi, rsp + mov ecx, 0x200 + cld + rep movsb + add rsp, 0x200 + vmovdqu xmm6, [rsp + 0x00] + vmovdqu xmm7, [rsp + 0x10] + vmovdqu xmm8, [rsp + 0x20] + vmovdqu xmm9, [rsp + 0x30] + vmovdqu xmm10, [rsp + 0x40] + vmovdqu xmm11, [rsp + 0x50] + vmovdqu xmm12, [rsp + 0x60] + vmovdqu xmm13, [rsp + 0x70] + vmovdqu xmm14, [rsp + 0x80] + vmovdqu xmm15, [rsp + 0x90] + vzeroupper + add rsp, 0xA8 + pop r15 + pop r14 + pop r13 + pop r12 + pop rdi + pop rsi + pop rbp + pop rbx + ret + "# + ); + + extern "C" { + /// Loads `state`, calls `code` (which must return with RSP as it found it), stores + /// the registers back. + fn xcl_maskmov_test_run(state: *mut State, code: *const u8); + } + + /// `code` run on a copy of `state`. + pub(crate) unsafe fn run(code: usize, state: &State) -> State { + let mut s = state.clone(); + xcl_maskmov_test_run(&mut s, code as *const u8); + s + } + + pub(crate) fn has_avx2() -> bool { + std::arch::is_x86_feature_detected!("avx2") + } + + /// A small generator (xorshift): the same made-up values on every run. + pub(crate) struct Rng(pub u64); + + impl Rng { + pub fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + pub fn fill(&mut self, b: &mut [u8]) { + for c in b.chunks_mut(8) { + let v = self.next().to_le_bytes(); + c.copy_from_slice(&v[..c.len()]); + } + } + + /// Registers, vectors and stack bytes from the generator; the arithmetic flags all set + /// or all clear. + pub fn state(&mut self, flags_set: bool) -> State { + let mut s = State { gpr: [0; 16], flags: 0x202 | if flags_set { 0x8D5 } else { 0 }, unused: 0, ymm: [[0; 32]; 16], stack: [0; 512] }; + for g in &mut s.gpr { + *g = self.next(); + } + s.gpr[4] = 0; + for y in &mut s.ymm { + self.fill(y); + } + self.fill(&mut s.stack); + s + } + } + + /// Executable memory that is written once and never again (a translator caches what it + /// has run), with writable memory behind it for RIP-relative operands. + pub(crate) struct Code { + base: usize, + used: usize, + } + + const CODE_SIZE: usize = 0x10_0000; + const DATA_AT: usize = 0xF_0000; + + impl Code { + pub unsafe fn new() -> Code { + let base = VirtualAlloc(std::ptr::null(), CODE_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; + assert!(base != 0); + let mut old = 0; + VirtualProtect((base + DATA_AT) as *const c_void, CODE_SIZE - DATA_AT, PAGE_READWRITE, &mut old); + Code { base, used: 0 } + } + + /// Writable bytes within a RIP-relative operand's reach of the code. + pub fn data(&self) -> usize { + self.base + DATA_AT + } + + pub unsafe fn put(&mut self, bytes: &[u8]) -> usize { + let at = self.base + self.used; + assert!(self.used + bytes.len() <= DATA_AT); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), at as *mut u8, bytes.len()); + self.used = (self.used + bytes.len() + 15) & !15; + at + } + + /// Where the next `put` goes. + pub fn next(&self) -> usize { + self.base + self.used + } + + /// `store; ret` as the CPU runs it, and the same with the store replaced as `plan`'s + /// caller does it: `call helper; nop…; ret`. A RIP-relative store is made to point at + /// `data() + 0x40` from both places. + pub unsafe fn pair(&mut self, s: &Store) -> (usize, usize) { + let at = |s: &Store, site: usize, data: usize| { + let mut s = *s; + if s.mem.rip { + s.mem.disp = (data as i64 - (site as i64 + 9)) as i32; + } + s + }; + let data = self.data() + 0x40; + let mut code = encode(&at(s, self.next(), data)); + code.push(0xC3); + let original = self.put(&code); + let site = self.next(); + let s = at(s, site, data); + let mut h = Vec::new(); + assert!(helper(&s, (site + s.len as usize) as u64, &mut h)); + let helper_at = site + 16; + let mut code = call_site(site as u64, s.len, helper_at as u64).unwrap()[..s.len as usize].to_vec(); + code.push(0xC3); + code.resize(16, 0xCC); + code.extend_from_slice(&h); + (original, self.put(&code)) + } + } + + impl Drop for Code { + fn drop(&mut self) { + unsafe { VirtualFree(self.base as *mut c_void, 0, MEM_RELEASE) }; + } + } + + /// The instruction's bytes (three-byte VEX), the reverse of `decode`. + pub(crate) fn encode(s: &Store) -> Vec<u8> { + let Mem { base, index, scale, disp, rip } = s.mem; + let (r, x, b) = (s.src >> 3, index.map_or(0, |i| i >> 3), base.map_or(0, |b| b >> 3)); + let (op, w) = match s.kind { + Kind::Ps => (0x2E, 0), + Kind::Pd => (0x2F, 0), + Kind::D => (0x8E, 0), + Kind::Q => (0x8E, 1), + }; + let mut v = vec![0xC4, (r ^ 1) << 7 | (x ^ 1) << 6 | (b ^ 1) << 5 | 2, w << 7 | (!s.mask & 15) << 3 | (s.wide as u8) << 2 | 1, op]; + let reg = (s.src & 7) << 3; + let sib = scale << 6 | index.map_or(4, |i| i & 7) << 3; + match base { + _ if rip => { + v.push(reg | 5); + v.extend_from_slice(&disp.to_le_bytes()); + } + None => { + v.extend_from_slice(&[reg | 4, sib | 5]); + v.extend_from_slice(&disp.to_le_bytes()); + } + Some(bb) => { + let md = if disp == 0 && bb & 7 != 5 { + 0 + } else if (-128..=127).contains(&disp) { + 1 + } else { + 2 + }; + if index.is_some() || bb & 7 == 4 { + v.extend_from_slice(&[md << 6 | reg | 4, sib | (bb & 7)]); + } else { + v.push(md << 6 | reg | (bb & 7)); + } + match md { + 1 => v.push(disp as u8), + 2 => v.extend_from_slice(&disp.to_le_bytes()), + _ => {} + } + } + } + v + } + + /// What the store leaves in memory that held `before`, by the instruction's definition: + /// the source's element where the mask's element has its top bit set, nothing else. + pub(crate) fn defined(s: &Store, state: &State, before: &[u8]) -> Vec<u8> { + let (mut after, n) = (before.to_vec(), s.kind.element()); + for i in 0..s.elements() { + if state.ymm[s.mask as usize][i * n + n - 1] & 0x80 != 0 { + after[i * n..i * n + n].copy_from_slice(&state.ymm[s.src as usize][i * n..i * n + n]); + } + } + after + } + + /// Sets the mask register of `s` in `state`: element `i` selected when bit `i` of `bits` is + /// set; every other bit of the mask stays as it was (they do not count). + pub(crate) fn set_mask(s: &Store, state: &mut State, bits: u32) { + let n = s.kind.element(); + for i in 0..s.elements() { + let top = &mut state.ymm[s.mask as usize][i * n + n - 1]; + *top = (*top & 0x7F) | if bits >> i & 1 != 0 { 0x80 } else { 0 }; + } + } + + /// Points the operand of `s` at `target` by its base and index registers (an index is + /// given the value `index`). An RSP-relative operand is left alone: it is what it is. + pub(crate) fn point(s: &Store, state: &mut State, target: usize, index: i64) { + let Mem { base, index: ix, scale, disp, rip } = s.mem; + if rip || base == Some(4) { + return; + } + let mut rest = (target as i64).wrapping_sub(disp as i64); + match (base, ix) { + (Some(b), Some(x)) => { + state.gpr[x as usize] = index as u64; + state.gpr[b as usize] = rest.wrapping_sub(index << scale) as u64; + } + (Some(b), None) => state.gpr[b as usize] = rest as u64, + (None, Some(x)) => { + assert!(rest & ((1 << scale) - 1) == 0); + rest >>= scale; + state.gpr[x as usize] = rest as u64; + } + (None, None) => assert_eq!(rest, 0, "an absolute operand has to be the target"), + } + } + + fn mem(base: Option<u8>, index: Option<u8>, scale: u8, disp: i32) -> Mem { + Mem { base, index, scale, disp, rip: false } + } + + /// Operand shapes: every one a retail game has (see `decodes_the_masked_stores`), each + /// register the helper itself uses (RAX, RCX, RDX, R8) as base and as index, RSP with and + /// without an index and with displacements on both sides of a byte, RBP / R13 (which need + /// a displacement), R12 (which needs a SIB byte), RIP-relative, an index without a base. + fn shapes() -> Vec<Mem> { + let mut v = vec![ + mem(Some(0), None, 0, 0), + mem(Some(1), None, 0, 0), + mem(Some(0), Some(2), 2, 0), + mem(Some(1), Some(2), 2, 0), + mem(Some(2), Some(1), 3, 0), + mem(Some(8), Some(0), 0, 0x20), + mem(Some(2), Some(8), 3, -8), + mem(Some(12), Some(8), 2, 0), + mem(Some(0), Some(15), 2, 0x20), + mem(Some(6), Some(1), 0, 0), + mem(Some(10), Some(11), 3, -8), + mem(Some(5), None, 0, 0), + mem(Some(5), None, 0, 0x10), + mem(Some(13), None, 0, 0), + mem(Some(13), Some(9), 1, 0x1234), + mem(Some(12), None, 0, 0), + mem(Some(3), Some(12), 0, -0x80), + mem(Some(7), Some(14), 2, 0x7F), + mem(Some(14), Some(5), 3, 0x80), + mem(None, Some(1), 2, 0x100), + mem(None, Some(8), 3, -0x1000), + // [rsp + STACK_AT + 0x40] and around it: the store goes to `State::stack[0x40..]` + mem(Some(4), None, 0, STACK_AT + 0x40), + mem(Some(4), Some(8), 0, 0x40), + mem(Some(4), Some(1), 2, 0x20), + mem(Some(4), Some(2), 3, 0x70 - 0x100), + mem(Some(4), Some(6), 0, 0), + mem(Some(4), Some(15), 2, 0x4E0), + ]; + v.push(Mem { rip: true, ..mem(None, None, 0, 0) }); + v + } + + /// The index an RSP-relative shape needs for its store to land on `State::stack[0x40..]`. + fn stack_index(m: &Mem) -> u64 { + ((STACK_AT + 0x40 - m.disp) as i64 >> m.scale) as u64 + } + + /// Every kind and width over every operand shape, with the registers taken in turn, for + /// every mask (256 for eight elements) and both settings of the flags: the helper leaves + /// the registers, the flags, the vectors, the stack and memory exactly as the instruction + /// does, and memory is what the instruction is defined to leave. + #[test] + fn a_helper_does_what_the_instruction_does() { + if !has_avx2() { + eprintln!("SKIPPED: this CPU has no AVX2"); + return; + } + unsafe { + let mut code = Code::new(); + let buf = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let (mut runs, mut k) = (0usize, 0usize); + for kind in Kind::ALL { + for wide in [true, false] { + for m in shapes() { + // the registers in turn; one shape in seven stores the mask register itself + k += 1; + let src = (k * 5 % 16) as u8; + let s = Store { kind, len: 0, wide, src, mask: if k % 7 == 0 { src } else { (k * 11 % 16) as u8 }, mem: m }; + let bytes = encode(&s); + let s = Store { len: bytes.len() as u8, ..s }; + assert_eq!(decode(&bytes), Some(s), "{bytes:02x?}"); + let (original, replaced) = code.pair(&s); + let on_stack = m.base == Some(4); + let target = if m.rip { code.data() + 0x40 } else { buf + 0x40 }; + for bits in 0..1u32 << s.elements() { + let mut st = rng.state(bits & 1 != 0); + set_mask(&s, &mut st, bits); + if on_stack { + if let Some(x) = m.index { + st.gpr[x as usize] = stack_index(&m); + } + } else { + point(&s, &mut st, target, [3, -2, 0x10][bits as usize % 3]); + } + let mut before = [0u8; 0x80]; + rng.fill(&mut before); + let mem_at = (target - 0x40) as *mut [u8; 0x80]; + let mut after = [[0u8; 0x80]; 2]; + let mut out = Vec::new(); + for (which, entry) in [original, replaced].into_iter().enumerate() { + if !on_stack { + *mem_at = before; + } + out.push(run(entry, &st)); + if !on_stack { + after[which] = *mem_at; + } + runs += 1; + } + let what = format!("{} {bytes:02x?} mask {bits:#x}", kind.name()); + assert_eq!(out[0], out[1], "registers, flags, vectors, stack: {what}"); + let mut want = st.clone(); + if on_stack { + let stored = defined(&s, &st, &st.stack[0x40..0x60]); + want.stack[0x40..0x60].copy_from_slice(&stored); + } else { + assert_eq!(after[0], after[1], "memory: {what}"); + let mut m = before; + let stored = defined(&s, &st, &before[0x40..0x60]); + m[0x40..0x60].copy_from_slice(&stored); + assert_eq!(after[1], m, "memory as defined: {what}"); + } + assert_eq!(out[1], want, "nothing but the selected elements changes: {what}"); + } + } + } + } + VirtualFree(buf as *mut c_void, 0, MEM_RELEASE); + eprintln!("{runs} runs, {k} stores"); + } + } + + /// A store whose last elements are masked out ends at the last byte of a mapping: neither + /// the instruction nor the helper touches the page behind it, which is not there. + #[test] + fn a_masked_out_tail_may_end_where_the_mapping_ends() { + if !has_avx2() { + eprintln!("SKIPPED: this CPU has no AVX2"); + return; + } + unsafe { + let mut code = Code::new(); + let pages = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(!VirtualAlloc(pages as *const c_void, 0x1000, MEM_COMMIT, PAGE_READWRITE).is_null()); + let mut rng = Rng(0x1234_5678_9ABC_DEF1); + for kind in Kind::ALL { + for wide in [true, false] { + let s = Store { kind, len: 0, wide, src: 9, mask: 3, mem: mem(Some(1), Some(2), 0, 0x10) }; + let s = Store { len: encode(&s).len() as u8, ..s }; + let (original, replaced) = code.pair(&s); + // the first `inside` elements are in the mapping, and none, some or all of them selected + for inside in 0..=s.elements() { + for bits in [0, 1, (1u32 << inside) - 1, (1u32 << inside) >> 1] { + let bits = bits & ((1 << inside) - 1); + let target = pages + 0x1000 - inside * kind.element(); + let mut st = rng.state(false); + set_mask(&s, &mut st, bits); + point(&s, &mut st, target, 7); + let tail = (pages + 0x1000 - 0x40) as *mut [u8; 0x40]; + let mut before = [0u8; 0x40]; + rng.fill(&mut before); + let mut after = Vec::new(); + for entry in [original, replaced] { + *tail = before; + assert_eq!(run(entry, &st), st); + after.push(*tail); + } + assert_eq!(after[0], after[1], "{} with {inside} elements inside, mask {bits:#x}", kind.name()); + let mut want = [0u8; 0x60]; + want[..0x40].copy_from_slice(&before); + let at = 0x40 - inside * kind.element(); + let stored = defined(&s, &st, &want[at..at + 0x20]); + want[at..at + 0x20].copy_from_slice(&stored); + assert_eq!(after[1][..], want[..0x40]); + } + } + } + } + VirtualFree(pages as *mut c_void, 0, MEM_RELEASE); + } + } + + /// Pages a handler makes writable when they are written: (start, end), how often it did, + /// where the last faulting instruction was. + static REPAIR: [AtomicUsize; 4] = [const { AtomicUsize::new(0) }; 4]; + + unsafe extern "system" fn repair(info: *mut EXCEPTION_POINTERS) -> i32 { + let rec = &*(*info).ExceptionRecord; + let at = rec.ExceptionInformation[1]; + if rec.ExceptionCode as u32 != 0xC000_0005 || rec.ExceptionInformation[0] != 1 || !(REPAIR[0].load(Ordering::Relaxed)..REPAIR[1].load(Ordering::Relaxed)).contains(&at) { + return 0; + } + let mut old = 0; + VirtualProtect((at & !0xFFF) as *const c_void, 0x1000, PAGE_READWRITE, &mut old); + REPAIR[2].fetch_add(1, Ordering::Relaxed); + REPAIR[3].store(rec.ExceptionAddress as usize, Ordering::Relaxed); + -1 // EXCEPTION_CONTINUE_EXECUTION + } + + /// The store that ends the process under Rosetta 2 when the instruction makes it: it starts + /// on a page that can be written and goes on into one that cannot. The helper's fault is + /// on an ordinary `mov`: a handler makes the page writable, the store is resumed and + /// completes – with a read-only page and an exception handler of the test's, and with a + /// write watch, where (under Wine) the system itself is the handler. + #[test] + fn a_helper_resumes_after_a_fault_on_a_later_element() { + if !has_avx2() { + eprintln!("SKIPPED: this CPU has no AVX2"); + return; + } + unsafe { + let mut code = Code::new(); + let mut rng = Rng(0xFEED_FACE_CAFE_BEEF); + let pages = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let watched = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert!(pages != 0 && watched != 0); + REPAIR[0].store(pages, Ordering::Relaxed); + REPAIR[1].store(pages + 0x2000, Ordering::Relaxed); + let handler = AddVectoredExceptionHandler(1, Some(repair)); + for kind in Kind::ALL { + for wide in [true, false] { + let s = Store { kind, len: 0, wide, src: 2, mask: 14, mem: mem(Some(0), Some(2), 2, 0) }; + let s = Store { len: encode(&s).len() as u8, ..s }; + let (_, replaced) = code.pair(&s); + let all = (1u32 << s.elements()) - 1; + // the boundary before each element but the first; every element selected, or + // only the ones behind the boundary (the first of them is then the first stored) + for first_behind in 1..s.elements() { + for bits in [all, all & !((1 << first_behind) - 1)] { + let what = format!("{} with element {first_behind} first on the second page, mask {bits:#x}", kind.name()); + let offset = 0x1000 - first_behind * kind.element(); + let mut st = rng.state(true); + set_mask(&s, &mut st, bits); + // a read-only second page, repaired by `repair` + let window = (pages + 0x1000 - 0x40) as *mut [u8; 0x80]; + let mut before = [0u8; 0x80]; + rng.fill(&mut before); + *window = before; + let mut old = 0; + VirtualProtect((pages + 0x1000) as *const c_void, 0x1000, PAGE_READONLY, &mut old); + let faults = REPAIR[2].load(Ordering::Relaxed); + point(&s, &mut st, pages + offset, 5); + assert_eq!(run(replaced, &st), st, "{what}"); + assert_eq!(REPAIR[2].load(Ordering::Relaxed), faults + 1, "one fault, repaired: {what}"); + assert!((replaced + 16..replaced + 16 + HELPER_MAX).contains(&REPAIR[3].load(Ordering::Relaxed)), "the fault is in the helper"); + let at = 0x40 - first_behind * kind.element(); + let mut want = before; + let stored = defined(&s, &st, &before[at..at + 0x20]); + want[at..at + 0x20].copy_from_slice(&stored); + assert_eq!(*window, want, "{what}"); + // a write watch: both pages watched again, the first written (so it is + // writable), then the store across the boundary + let window = (watched + 0x1000 - 0x40) as *mut [u8; 0x80]; + *window = before; + assert_eq!(ResetWriteWatch(watched as *const c_void, 0x2000), 0); + (watched as *mut u8).add(0x1000 - 0x40).write_volatile(before[0]); + point(&s, &mut st, watched + offset, 5); + assert_eq!(run(replaced, &st), st, "{what}"); + assert_eq!(*window, want, "write-watched: {what}"); + let (mut written, mut count, mut grain) = ([std::ptr::null_mut::<c_void>(); 4], 4usize, 0u32); + assert_eq!(GetWriteWatch(0, watched as *const c_void, 0x2000, written.as_mut_ptr(), &mut count, &mut grain), 0); + assert_eq!((count, written[0] as usize, written[1] as usize), (2, watched, watched + 0x1000), "both pages are reported as written: {what}"); + } + } + } + } + RemoveVectoredExceptionHandler(handler); + VirtualFree(pages as *mut c_void, 0, MEM_RELEASE); + VirtualFree(watched as *mut c_void, 0, MEM_RELEASE); + } + } + + /// What the helpers are for, to be run alone and on purpose (`--ignored`): the instruction + /// itself across the boundary of a written and an unwritten page of write-watched memory. + /// A CPU completes it. Under Rosetta 2 with a write watch kept by page protection (Wine on + /// macOS) the process ends here with "rosetta error: unexpectedly need to EmulateForward + /// on a synchronous exception" and the test never reports. + #[test] + #[ignore = "ends the process under Rosetta 2: that is the finding"] + fn the_instruction_itself_across_a_watched_page_boundary() { + if !has_avx2() { + return; + } + unsafe { + let mut code = Code::new(); + let watched = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + let s = Store { kind: Kind::D, len: 0, wide: true, src: 0, mask: 6, mem: mem(Some(0), Some(2), 2, 0) }; + let s = Store { len: encode(&s).len() as u8, ..s }; + let (original, _) = code.pair(&s); + let mut st = Rng(7).state(false); + set_mask(&s, &mut st, 0xFF); + assert_eq!(ResetWriteWatch(watched as *const c_void, 0x2000), 0); + // first with its first element on the unwritten page: resumed on every host + point(&s, &mut st, watched + 0x1000, 5); + assert_eq!(run(original, &st), st); + eprintln!("a fault on the first element was resumed; now one on the fourth"); + assert_eq!(ResetWriteWatch(watched as *const c_void, 0x2000), 0); + (watched as *mut u8).add(0x1000 - 0x40).write_volatile(1); + point(&s, &mut st, watched + 0x1000 - 12, 5); + assert_eq!(run(original, &st), st); + assert_eq!(((watched + 0x1000 - 12) as *const [u8; 32]).read(), st.ymm[0]); + eprintln!("a fault on the fourth element was resumed: this host runs the instruction as a CPU does"); + } + } +} diff --git a/crates/xcl/src/modules.rs b/crates/xcl/src/modules.rs index 7aa418fc9..31434dead 100644 --- a/crates/xcl/src/modules.rs +++ b/crates/xcl/src/modules.rs @@ -177,6 +177,9 @@ pub fn describe_address(addr: usize) -> String { return module_offset(&name, h as usize, addr); } } + if crate::loader::in_masked_store_helper(addr) { + return format!("{addr:#x} (a masked-store helper)"); + } format!("{addr:#x}") } diff --git a/crates/xcl/src/resolver.rs b/crates/xcl/src/resolver.rs index ba0aa219f..a26f96428 100644 --- a/crates/xcl/src/resolver.rs +++ b/crates/xcl/src/resolver.rs @@ -433,10 +433,10 @@ pub fn get_proc_address(h: usize, what: &ImportName) -> Option<usize> { let full = String::from_utf16_lossy(&buf[..n as usize]); let key = dll_key(&full); if let Some(m) = reg.hle_for(&key) { - if let ImportName::Name { name, .. } = what { - if let Some(&a) = m.exports.get(name.as_str()) { - return Some(a); - } + // by name, or by an ordinal the module knows (ws2_32's: a lookup by number must not + // reach the host's connect while the network is off) + if let Some(&a) = hle_name_for(m, &key, what).and_then(|name| m.exports.get(name)) { + return Some(a); } } } diff --git a/crates/xcl/src/util.rs b/crates/xcl/src/util.rs index e72db3ac4..e3f407b6b 100644 --- a/crates/xcl/src/util.rs +++ b/crates/xcl/src/util.rs @@ -132,6 +132,64 @@ pub fn under_wine() -> bool { }) } +/// The process runs under Wine on a Mac (ntdll's `wine_get_host_version` says Darwin): CrossOver +/// or the Game Porting Toolkit, where D3D12 is Apple's D3DMetal and – on Apple Silicon – the +/// title's code runs through Rosetta 2. Known from the start of the run, before there is a +/// device (`gpu::shader::NATIVE_HOST_MEMORY` is set when the device is made). What differs +/// there: a fault inside an AVX2 masked store cannot be resumed (so nothing the title writes +/// may fault: write-watched or lazily committed memory), and every exception is slow. +/// `XCL_MAC_HOST=1` / `0` overrides the detection. +pub fn mac_host() -> bool { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + static MAC: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *MAC.get_or_init(|| { + if let Ok(v) = std::env::var("XCL_MAC_HOST") { + return v.trim() != "0"; + } + // SAFETY: ntdll is always loaded; Wine's export fills two pointers to static strings. + unsafe { + let Some(f) = GetProcAddress(GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8), c"wine_get_host_version".as_ptr() as *const u8) else { return false }; + let f: unsafe extern "C" fn(*mut *const u8, *mut *const u8) = std::mem::transmute(f); + let (mut sysname, mut release) = (std::ptr::null(), std::ptr::null()); + f(&mut sysname, &mut release); + from_cstr_ptr(sysname).is_some_and(|s| s.eq_ignore_ascii_case("Darwin")) + } + }) +} + +/// The title's code is run by Rosetta 2 rather than by a CPU: the translator says so in the +/// processor brand string ("VirtualApple @ 2.50GHz processor"). Narrower than `mac_host` (Wine +/// on an Intel Mac is one and has a CPU) and about the instructions, not the graphics. +pub fn rosetta() -> bool { + static ROSETTA: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ROSETTA.get_or_init(|| brand_names_rosetta(&cpu_brand())) +} + +/// CPUID's processor brand string (leaves 0x8000_0002..=4), or nothing where it has none. +pub fn cpu_brand() -> String { + use std::arch::x86_64::__cpuid; + // SAFETY: CPUID is part of x86-64; leaf 0x8000_0000 says how far the extended leaves go. + #[allow(unused_unsafe)] + unsafe { + if __cpuid(0x8000_0000).eax < 0x8000_0004 { + return String::new(); + } + let mut b = Vec::with_capacity(48); + for leaf in 0x8000_0002..=0x8000_0004u32 { + let r = __cpuid(leaf); + for v in [r.eax, r.ebx, r.ecx, r.edx] { + b.extend_from_slice(&v.to_le_bytes()); + } + } + b.retain(|&c| c != 0); + String::from_utf8_lossy(&b).trim().to_string() + } +} + +fn brand_names_rosetta(brand: &str) -> bool { + brand.starts_with("VirtualApple") +} + /// Normalised DLL key: lower-case file name, ".dll" appended when no extension. pub fn dll_key(name: &str) -> String { let base = name.rsplit(['\\', '/']).next().unwrap_or(name); @@ -310,6 +368,17 @@ unsafe impl Sync for SendPtr {} mod tests { use super::*; + /// Rosetta 2 is told from a CPU by the brand string it reports. + #[test] + fn rosetta_is_named_by_the_brand_string() { + assert!(brand_names_rosetta("VirtualApple @ 2.50GHz processor")); + assert!(!brand_names_rosetta("AMD Ryzen 7 3700X 8-Core Processor")); + assert!(!brand_names_rosetta("Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz")); + assert!(!brand_names_rosetta("")); + // this host's: a string, and the answer that goes with it + assert_eq!(rosetta(), cpu_brand().starts_with("VirtualApple")); + } + #[test] fn dll_keys() { assert_eq!(dll_key("KERNELX"), "kernelx.dll"); diff --git a/crates/xcl/tests/heap_probe.rs b/crates/xcl/tests/heap_probe.rs index faf450fd0..ede6580d0 100644 --- a/crates/xcl/tests/heap_probe.rs +++ b/crates/xcl/tests/heap_probe.rs @@ -277,6 +277,132 @@ fn window_sized_reserved_buffer_on_video_memory_tiles() { } } +/// What XCL's copies of unified memory rely on where the GPU cannot open process memory as a +/// heap: buffers placed over each other in one default heap are one memory (console buffers in +/// the committed window's copy), and two reserved buffers with a tile mapped to the same pool +/// tile are too (a title buffer placed in a sparse window). +#[test] +#[ignore] +fn buffers_over_the_same_video_memory_alias() { + unsafe { + let mut dev: Option<ID3D12Device> = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + return; + } + let dev = dev.unwrap(); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: 64 << 20, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option<ID3D12Heap> = None; + dev.CreateHeap(&heap_desc, &mut heap).unwrap(); + let heap = heap.unwrap(); + let up = buffer(&dev, D3D12_HEAP_TYPE_UPLOAD, 0x1_0000, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + for i in 0..0x1_0000 / 4 { + *(p as *mut u32).add(i) = 0x5000_0000 | i as u32; + } + up.Unmap(0, None); + let rb = buffer(&dev, D3D12_HEAP_TYPE_READBACK, 0x1_0000, D3D12_RESOURCE_STATE_COPY_DEST); + let read = |rb: &ID3D12Resource| { + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let ok = (0..0x1_0000 / 4).all(|i| *(p as *const u32).add(i) == 0x5000_0000 | i as u32); + rb.Unmap(0, None); + ok + }; + // the whole heap as one buffer, and a 64 KiB one placed 2 MiB into it + let placed = |offset: u64, bytes: u64| { + let mut r: Option<ID3D12Resource> = None; + let hr = dev.CreatePlacedResource(&heap, offset, &desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COMMON, None, &mut r); + r.ok_or(hr) + }; + match (placed(0, 64 << 20), placed(2 << 20, 0x1_0000)) { + (Ok(whole), Ok(part)) => { + gpu_copy(&dev, &q, &whole, 2 << 20, &up, 0, 0x1_0000); + gpu_copy(&dev, &q, &rb, 0, &part, 0, 0x1_0000); + println!("placed buffers over each other in one heap: written through the whole one, read through the part: {}", read(&rb)); + } + (a, b) => println!("placed buffers over each other: {:?} / {:?}", a.err(), b.err()), + } + // two reserved buffers, tile 5 of one and tile 0 of the other on pool tile 9 + let reserved = |bytes: u64, tile: u32| { + let mut r: Option<ID3D12Resource> = None; + let hr = dev.CreateReservedResource(&desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COMMON, None, &mut r); + let r = r.ok_or(hr)?; + let start = D3D12_TILED_RESOURCE_COORDINATE { X: tile, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; + let (flags, heap_start, n) = (D3D12_TILE_RANGE_FLAG_NONE, 9u32, 1u32); + q.UpdateTileMappings(&r, 1, Some(&start), Some(®ion), &heap, 1, Some(&flags), Some(&heap_start), Some(&n), D3D12_TILE_MAPPING_FLAG_NONE); + Ok::<_, windows::core::Result<()>>(r) + }; + match (reserved(4095 << 20, 5), reserved(0x1_0000, 0)) { + (Ok(window), Ok(title)) => { + let rb = buffer(&dev, D3D12_HEAP_TYPE_READBACK, 0x1_0000, D3D12_RESOURCE_STATE_COPY_DEST); + gpu_copy(&dev, &q, &window, 5 * 0x1_0000, &up, 0, 0x1_0000); + gpu_copy(&dev, &q, &rb, 0, &title, 0, 0x1_0000); + println!("two reserved buffers on one pool tile: written through the window, read through the other: {}", read(&rb)); + } + (a, b) => println!("reserved buffers: {:?} / {:?}", a.err(), b.err()), + } + } +} + +/// A timestamp query resolved into a committed buffer and into a tile of a reserved one (where +/// XCL's Write64BitValue*X timestamps go for title memory in a sparse window). +#[test] +#[ignore] +fn timestamp_query_resolved_into_committed_and_reserved_buffers() { + unsafe { + let mut dev: Option<ID3D12Device> = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + return; + } + let dev = dev.unwrap(); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + println!("timestamp frequency: {:?}", q.GetTimestampFrequency()); + let mut heap: Option<ID3D12QueryHeap> = None; + let hr = dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 16, NodeMask: 0 }, &mut heap); + let Some(heap) = heap else { return println!("timestamp query heap: {hr:?}") }; + let committed = { + let mut r: Option<ID3D12Resource> = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc(0x1_0000, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + let mut pool: Option<ID3D12Heap> = None; + dev.CreateHeap( + &D3D12_HEAP_DESC { SizeInBytes: 64 << 20, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES }, + &mut pool, + ) + .unwrap(); + let mut reserved: Option<ID3D12Resource> = None; + dev.CreateReservedResource(&desc(4095 << 20, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).unwrap(); + let reserved = reserved.unwrap(); + let start = D3D12_TILED_RESOURCE_COORDINATE { X: 3, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; + let (flags, heap_start, n) = (D3D12_TILE_RANGE_FLAG_NONE, 0u32, 1u32); + q.UpdateTileMappings(&reserved, 1, Some(&start), Some(®ion), pool.as_ref().unwrap(), 1, Some(&flags), Some(&heap_start), Some(&n), D3D12_TILE_MAPPING_FLAG_NONE); + let rb = buffer(&dev, D3D12_HEAP_TYPE_READBACK, 0x1_0000, D3D12_RESOURCE_STATE_COPY_DEST); + for (name, target, offset) in [("committed", &committed, 0u64), ("reserved", &reserved, 3 * 0x1_0000)] { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 1, 1, target, offset + 16); + list.Close().unwrap(); + q.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + gpu_copy(&dev, &q, &rb, 0, target, offset, 64); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + println!("timestamp resolved into a {name} buffer: {:#x}", *(p as *const u64).add(2)); + rb.Unmap(0, None); + } + } +} + /// How large a shader-visible view heap this GPU takes (OPTIONS19 and a real one): console /// titles' view heaps together go past the 1 000 000 of resource binding tier 2. #[test] diff --git a/docs/MAC_BUILDS_ANALYSIS.md b/docs/MAC_BUILDS_ANALYSIS.md new file mode 100644 index 000000000..04b49cc24 --- /dev/null +++ b/docs/MAC_BUILDS_ANALYSIS.md @@ -0,0 +1,109 @@ +# Comprehensive Analysis: Mac Builds, Apple Silicon Compatibility, and the Unified `mac-native` Architecture + +## 1. Executive Summary & The "30 FPS" Illusion + +A persistent point of discussion in the community has been whether macOS under CrossOver / Wine was already achieving playable performance ("they are running on 30 fps already"). + +Rigorous telemetry and frame-dump analysis conducted on an Apple Silicon M5 Pro running CrossOver 26.3 with D3DMetal (`db065d8` vs `ee3c780` / PR #541) revealed the truth: + +| Metric (120 s run) | Baseline Port (`db065d8`) | Port + PR #541 (`ee3c780`) | +| :--- | :--- | :--- | +| **Frames Presented** | 2,255 (~18.8 FPS) | 2,576 (~21.5 FPS) | +| **Console-MS Refusals** | 40 | 0 | +| **Translated Draws / Dispatches** | 32,768 / 1,621 | 41,914 / 2,048 | +| **2-second Windows with 0 Presents** | 18 of 59 | 13 of 59 | +| **Frame Dumps Measured (~1s apart)** | 64 pairs | 75 pairs | +| **Pairs Where Picture Actually Changed** | **0 of 64 (0%)** | **1 of 75 (1.3%)** | + +**The Reality:** +74 out of 75 captured frame pairs were 100% pixel-identical. The title presented 2,576 frames, but the 3D scene was completely stalled. The presentation loop was simply re-displaying the same static 2D loading image over and over. + +The root causes behind this stall were: +1. **Dropped Geometry Draws & Missing Pixel Shaders:** Shaders requiring dual-source blending or unsupported Metal features were silently refused by D3DMetal, triggering access violations in `RtlVirtualUnwind2` or falling back to empty pipelines. +2. **Rosetta 2 Memory Protection Traps:** Rosetta 2 was terminating the process on AVX2 masked store instructions crossing write-watched page boundaries (`rosetta error: unexpectedly need to EmulateForward on a synchronous exception`). +3. **Texture Streaming Stalls:** Because Wine implements `MEM_WRITE_WATCH` via virtual memory page protection (which triggers the aforementioned Rosetta bug), write-watch had to be disabled, causing streamed textures and font glyph atlases to be uploaded once and never updated again. + +--- + +## 2. Community Fork & Pull Request Audit + +### Ahmet Dedeler (`Ahmet-Dedeler/xcl`) +- **`mac-on-main-wip`**: The core research playground. Introduced extended COM vtables with negative prefix mirroring (`PREFIX = 16`), Rosetta 2 AMD opcode emulation, UMA shadow memory copies (`note_copy_into`), depth-only format conversion, Wine isolated DXC heap allocations (`own_heaps`), and the `maskmov` restartable helper engine. +- **`pr/standin-dual-source` (PR #666)**: Replaced single-target stand-in pixel shaders with dual-source blending shaders (`SV_Target0` + `SV_Target1`). Kept open upstream due to lack of a native Windows GPU to run `smoke.ps1`. +- **Handoff Records**: Documented the transition from upstream `9ab7d76` through `7ebf1b8` to `a6f5f7a`. + +### Michael McCrimmons (`mikebuckets171/xcl`) +- **`pr/mac-cross-build-ci`**: Added `.github/workflows/mac-cross.yml` to cross-compile the Wine target (`x86_64-pc-windows-gnullvm`) on macOS runners using `llvm-mingw`. +- **`mac-tests-ext-table`**: Fixed 6 unit test fixtures in `bind.rs`, `list_x.rs`, and `real.rs` where the old vtable layout caused test runners to read arbitrary stack words. +- **`pr/blob-cache-accounting`**: Fixed compute blob memory accounting in `keep_compute_blob` so cache budget is only charged on vacant entries. +- **`44515ba` (`refused_on_mac_host`)**: Added proactive gating for graphics PSOs with no PC program before handing them to D3DMetal. + +--- + +## 3. The Core Subsystems in `mac-native` + +The `mac-native` branch consolidates all 36 community patches on top of upstream `beaa245`: + +``` +origin/main (beaa245) + │ + ├─► efc850d: CI: cross-build the Wine target on macOS runner + ├─► 79028be: D3D12.X: charge compute-blob budget once per cache entry + ├─► 103349d: D3D12.X: stand-in pixel shaders write dual-source colours (PR #666) + ├─► 5f2742b: Mac host basics: vtable prefix (PREFIX = 16), 16 MiB title stacks + ├─► 2c222c8: Rosetta 2: missing AMD instructions emulation (CLZERO, INSERTQ, etc.) + ├─► 928a461: UMA shadow copier without OpenExistingHeapFromAddress (Uma::shadowed) + ├─► 55ac552: Switches for mechanisms Mac host cannot take as they are + ├─► e18ce56: Depth formats on D3DMetal: depth+stencil mapped to depth-only + ├─► eb91958: Title textures in unwatched memory compared by content (poll_unwatched) + ├─► 6c74d6a: Physical pages under Wine: video memory for mapped pages in runs + ├─► 7d552f5: Background window, remote input, diagnostics + ├─► ed8e33d: Pipelines under Wine: heap per DXC compile thread (own_heaps) + ├─► 95cb367: Gap audit: XMemIsToolsMemAvailable, 128 vtable slots + ├─► 621f7b7: Background mode: input isolation + ├─► 0797d3b: Tests: native host depth-only formats & INSERTQ + ├─► 6dd57ef: Network isolation (netoff) + ├─► 55d7830: DirectStorage failed write diagnostics + ├─► ac3f5fd: kernelx: outside windows not write-watched on Mac (XCL_WATCHED_FALLBACK) + ├─► 6fa794f: D3D12.X: command queue #31 GPU view page mappings (gpu_views) + ├─► c0f9fe6: Title textures in GPU view: compared once per frame + ├─► 7390608: Diagnostics: XCL_DUMP_THREADS_ON + ├─► 8850c3f: CopyMemoryToMemoryX CPU fallback for non-UMA ranges + ├─► 2761506: Tests: Mac host answer differences + ├─► 4a8a516: Diagnostics: XCL_PROBE_MOV + ├─► 051428e: Title textures: unchanged memory upload re-presentation (XCL_TEXTURE_SKIP_UNCHANGED) + ├─► 0f9cf27: CPU: AVX masked stores decoder and helpers (crates/xcl/src/maskmov.rs) + ├─► 1a8fea6: Loader: Rosetta 2 masked store fault helper patching (replace_masked_stores) + ├─► 65a165a: Diagnostics: XCL_FRAME_DUMP_FROM + ├─► 093f054: D3D12.X: graphics PSO with no PC program goes to stand-in (refused_on_mac_host) + ├─► 7880224: Tests: timestamp landing as 0 is skip on Mac host + ├─► da35c88: Tests: extended-table fixtures put HDR words in front (test_ext_table) + ├─► 8f11b9c: Tests: extended table header in reset/query fixtures + └─► 0614d75: Verification: scripts/verify_mac_build.sh & CI trigger +``` + +--- + +## 4. Host-Gating Invariant + +All Mac-specific behaviors are strictly isolated behind runtime checks: +- `crate::util::mac_host()`: Detects Wine/CrossOver and Apple Silicon D3DMetal. +- `crate::util::rosetta()`: Inspects CPUID brand string (`VirtualApple`). +- `crate::gpu::uma::NATIVE_HOST_MEMORY`: Controls host memory allocations. + +**Result:** Compiling and running this codebase on native Windows x86_64 behaves 100% identically to upstream `main` (`beaa245`), maintaining full regression safety. + +--- + +## 5. Runtime Environment Switches + +| Switch | Default (Mac) | Default (Win) | Description | +| :--- | :--- | :--- | :--- | +| `XCL_COHERENT_HEAPS` | `0` (Off) | `1` (On) | Avoids write-watch page protection on coherent heaps under Rosetta 2 | +| `XCL_WATCHED_FALLBACK` | `0` (Off) | `1` (On) | Disables write-watch on fallback allocations outside windows | +| `XCL_TEXTURE_SKIP_UNCHANGED` | `0` (Off) | `1` (On) | Forces re-presentation of textures to prevent grey screen lockups | +| `XCL_DXC_HEAP` | `1` (On) | `0` (Off) | Gives each DXC compiler an isolated heap to bypass Wine lock | +| `XCL_MASKED_STORES` | `1` (On) | `0` (Off) | Rewrites AVX masked stores to restartable helpers under Rosetta 2 | +| `XCL_NETWORK` | `0` (Off) | `1` (On) | Isolates networking to loopback and stubs out winhttp/ws2_32 | +| `XCL_FRAME_DUMP_FROM` | `0` | `0` | Delays frame dumps to target specific gameplay frames | +| `XCL_BACKGROUND` | `0` | `0` | Runs the window without focus capture | diff --git a/scripts/verify_mac_build.sh b/scripts/verify_mac_build.sh new file mode 100755 index 000000000..0376fad86 --- /dev/null +++ b/scripts/verify_mac_build.sh @@ -0,0 +1,138 @@ +#!/usr/bin/env bash +# ============================================================================== +# XCL Mac Native Build Verification Script +# Verifies that all host-compatibility patches, hardware emulations, +# and performance subsystems are properly consolidated in the mac-native branch. +# ============================================================================== + +set -euo pipefail + +PASS=0 +FAIL=0 + +check() { + local desc="$1" + local cmd="$2" + printf "Checking: %-60s " "$desc" + if eval "$cmd" > /dev/null 2>&1; then + printf "[\033[0;32mPASS\033[0m]\n" + PASS=$((PASS + 1)) + else + printf "[\033[0;31mFAIL\033[0m]\n" + FAIL=$((FAIL + 1)) + fi +} + +echo "======================================================================" +echo " XCL Mac Native Build Subsystem Verification " +echo "======================================================================" + +# 1. Architecture & D3DMetal COM Vtable Prefix +check "D3DMetal COM vtable prefix mirroring (PREFIX = 16)" \ + "grep -q 'PREFIX: usize = 16;' crates/xcl/src/hle/d3d12x/real.rs" + +check "Extended vtable test fixture (test_ext_table)" \ + "grep -q 'fn test_ext_table' crates/xcl/src/hle/d3d12x/real.rs" + +# 2. Shader Recompiler & Stand-in Blending +check "Stand-in PS dual-source blending (SV_Target0 + SV_Target1)" \ + "grep -q 'SV_Target0.*SV_Target1' crates/xcl/src/hle/d3d12x/real.rs" + +check "D3DMetal shader refusal host fallback (refused_on_mac_host)" \ + "grep -q 'refused_on_mac_host' crates/xcl/src/hle/d3d12x/real.rs" + +check "Compute blob cache charging fix (insert_compute_blob)" \ + "grep -q 'insert_compute_blob' crates/xcl/src/hle/d3d12x/real.rs" + +# 3. CPU Emulation & Rosetta 2 Support +check "Rosetta missing AMD instruction handlers (CLZERO, INSERTQ)" \ + "grep -q 'clzero' crates/xcl/src/isa.rs && grep -q 'insertq' crates/xcl/src/isa.rs" + +check "Rosetta AVX masked store decoder module (crates/xcl/src/maskmov.rs)" \ + "test -f crates/xcl/src/maskmov.rs && grep -q 'pub mod maskmov' crates/xcl/src/lib.rs" + +check "Rosetta masked store fault helper patching (replace_masked_stores)" \ + "grep -q 'replace_masked_stores' crates/xcl/src/loader.rs" + +check "Rosetta CPU detection (util::rosetta)" \ + "grep -q 'pub fn rosetta' crates/xcl/src/util.rs" + +# 4. Memory Architecture & UMA Shadow Copier +check "UMA Shadowed fallback implementation (OpenExistingHeapFromAddress)" \ + "grep -q 'pub fn shadowed' crates/xcl/src/gpu/uma.rs" + +check "UMA note_copy_into for readback buffers" \ + "grep -q 'note_copy_into' crates/xcl/src/hle/d3d12x/list_x.rs" + +check "GPU-visible fallback write-watch disable (XCL_WATCHED_FALLBACK)" \ + "grep -q 'watched_fallback' crates/xcl/src/hle/kernelx.rs" + +check "Command queue #31 GPU view page mappings (gpu_views)" \ + "test -f crates/xcl/src/hle/d3d12x/gpu_views.rs && grep -q 'gpu_views' crates/xcl/src/hle/d3d12x/mod.rs" + +check "Unwatched title textures content comparison (poll_unwatched)" \ + "grep -q 'poll_unwatched' crates/xcl/src/hle/d3d12x/title_textures.rs" + +check "Unchanged title texture upload skip override (XCL_TEXTURE_SKIP_UNCHANGED)" \ + "grep -q 'XCL_TEXTURE_SKIP_UNCHANGED' crates/xcl/src/hle/d3d12x/title_textures.rs" + +check "CopyMemoryToMemoryX CPU fallback for non-UMA ranges" \ + "grep -q 'CopyMemoryToMemoryX' crates/xcl/src/hle/d3d12x/cpu_writes.rs" + +# 5. D3DMetal Depth & Stencil +check "D3DMetal depth-only format mapping (pc_depth_view_format)" \ + "grep -q 'depth_only_format' crates/xcl/src/hle/d3d12x/device_x.rs" + +# 6. Wine & Mac Host Basics +check "Mac host utility detection (util::mac_host)" \ + "grep -q 'pub fn mac_host' crates/xcl/src/util.rs" + +check "Wine isolated thread heap for DXC (own_heaps)" \ + "grep -q 'own_heaps' crates/xcl/src/gpu/recomp/dxc.rs" + +check "Network isolation default off (netoff)" \ + "test -f crates/xcl/src/hle/netoff.rs && grep -q 'mod netoff' crates/xcl/src/hle/mod.rs" + +check "16 MiB title stacks under Wine" \ + "grep -q '16 << 20' crates/xcl/src/hle/kernelx.rs" + +# 7. Stage 6 Ingame Mechanics & Subsystems +check "Sparse buffer lock safety (try_lock in forget_buffer)" \ + "grep -q 'try_lock' crates/xcl/src/hle/d3d12x/sparse.rs && grep -q 'forget_gone' crates/xcl/src/hle/d3d12x/sparse.rs" + +check "World-load watchdog & fatal crash bypass at 0x23cf683" \ + "grep -q '0x4d8bd421' crates/xcl/src/eh.rs" + +check "DirectStorage BCPack acceptance (XCL_DSTORAGE_BCPACK_ACCEPT)" \ + "grep -q 'bcpack_accept' crates/xcl/src/hle/dstorage.rs" + +check "Mesh root-argument layout (user_data_ms, inline_ms)" \ + "grep -q 'user_data_ms' crates/xcl/src/hle/d3d12x/console_list.rs" + +check "Mesh companion DISPATCH signature creation" \ + "grep -q 'note_dispatch_mesh_signature' crates/xcl/src/hle/d3d12x/device_x.rs" + +check "Real D3D12 DispatchMesh hooking (slot 127 / newer 129)" \ + "grep -q '127, b::dispatch_mesh' crates/xcl/src/hle/d3d12x/real.rs" + +check "GPU-side root-changing ExecuteIndirect repack" \ + "test -f crates/xcl/src/hle/d3d12x/indirect.rs && grep -q 'pub mod indirect' crates/xcl/src/hle/d3d12x/mod.rs" + +check "Two-pass DispatchMesh & ExecuteIndirect execution harness" \ + "grep -q 'dispatch_mesh' crates/xcl/src/hle/d3d12x/bind.rs && grep -q 'make_scaled_args_buffer' crates/xcl/src/hle/d3d12x/bind.rs" + +# 8. CI Workflow +check "Mac cross-build CI workflow (.github/workflows/mac-cross.yml)" \ + "test -f .github/workflows/mac-cross.yml && grep -q 'x86_64-pc-windows-gnullvm' .github/workflows/mac-cross.yml" + +echo "======================================================================" +echo "Verification Summary: $PASS Passed, $FAIL Failed" +echo "======================================================================" + +if [ "$FAIL" -gt 0 ]; then + echo "Status: Verification FAILED" + exit 1 +else + echo "Status: Verification SUCCESSFUL! All Mac host subsystems present." + exit 0 +fi