diff --git a/.github/scripts/pr_gate.py b/.github/scripts/pr_gate.py index 8d531ee0..d4b4445c 100644 --- a/.github/scripts/pr_gate.py +++ b/.github/scripts/pr_gate.py @@ -26,6 +26,8 @@ ".psm1": re.compile(r"^\s*(#|<#|#>)"), } COMMENT_OK = re.compile(r"^\s*#Requires\b") +RVA_CONST = re.compile(r"\bconst\s+[A-Za-z_][A-Za-z0-9_]*\s*:\s*(usize|u64)\s*=\s*0x([0-9a-fA-F_]+)") +RVA_PATH = re.compile(r"^crates/compat/.*\.rs$") def git(*args): @@ -47,12 +49,14 @@ def changed(base, head): def added_lines(base, head, path): out = git("diff", "-U0", "--no-color", "--no-ext-diff", base, head, "--", path).decode("utf-8", "replace") n = 0 + in_hunk = False for line in out.splitlines(): if line.startswith("@@"): m = re.search(r"\+(\d+)", line) n = int(m.group(1)) if m else 0 + in_hunk = True continue - if line.startswith("+++"): + if not in_hunk: continue if line.startswith("+"): yield n, line[1:] @@ -88,6 +92,10 @@ def check_lines(base, head, paths): for rx, why in PRIVATE: if rx.search(text): errors.append(("%s:%d" % (p, n), why)) + if RVA_PATH.search(p): + m = RVA_CONST.search(text) + if m and 6 <= len(m.group(2).replace("_", "").lstrip("0")) <= 8: + errors.append(("%s:%d" % (p, n), "title RVA-style constant (usize/u64 with 6-8 significant hex digits) in a compat crate")) if rule and rule.search(text) and not (n == 1 and text.startswith("#!")) and not COMMENT_OK.search(text): errors.append(("%s:%d" % (p, n), "comment line (the project keeps code free of comment lines)")) return errors diff --git a/.github/scripts/test_pr_gate.py b/.github/scripts/test_pr_gate.py new file mode 100644 index 00000000..30fbe767 --- /dev/null +++ b/.github/scripts/test_pr_gate.py @@ -0,0 +1,77 @@ +import os +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import pr_gate + +TOKEN = "ghp_" + "A" * 36 + + +class AddedLinesTests(unittest.TestCase): + def setUp(self): + self.old = os.getcwd() + self.tmp = tempfile.TemporaryDirectory() + os.chdir(self.tmp.name) + self.run_git("init", "-q") + self.run_git("config", "core.autocrlf", "false") + self.run_git("commit", "-q", "--allow-empty", "-m", "base") + + def tearDown(self): + os.chdir(self.old) + self.tmp.cleanup() + + def run_git(self, *args): + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], check=True, capture_output=True) + + def commit(self, name, text): + with open(name, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + self.run_git("add", name) + self.run_git("commit", "-q", "-m", "change") + + def test_lines_starting_with_two_plus_signs_are_checked(self): + self.commit("notes.md", "a\n++ " + TOKEN + "\nb\n") + lines = list(pr_gate.added_lines("HEAD^1", "HEAD", "notes.md")) + self.assertEqual(lines, [(1, "a"), (2, "++ " + TOKEN), (3, "b")]) + errors = pr_gate.check_lines("HEAD^1", "HEAD", ["notes.md"]) + self.assertEqual(errors, [("notes.md:2", "access token")]) + + def test_file_headers_are_not_added_lines(self): + self.commit("a.rs", "fn a() {}\n") + self.assertEqual(list(pr_gate.added_lines("HEAD^1", "HEAD", "a.rs")), [(1, "fn a() {}")]) + + def test_line_numbers_follow_each_hunk(self): + self.commit("b.md", "".join("%d\n" % i for i in range(1, 11))) + self.commit("b.md", "".join(("+++x\n" if i in (3, 8) else "%d\n" % i) for i in range(1, 11))) + self.assertEqual(list(pr_gate.added_lines("HEAD^1", "HEAD", "b.md")), [(3, "+++x"), (8, "+++x")]) + + def test_rva_constants_in_compat_crates_are_rejected(self): + os.makedirs("crates/compat/x/src") + os.makedirs("crates/other/src") + body = ("const TITLE_RVA: usize = 0x1a2b3c;\n" + "pub const OFF: u64 = 0x0014_5e90;\n" + "const SMALL: usize = 0x1f0;\n" + "const PADDED: u64 = 0x0000_00ff;\n" + "const WORD: u32 = 0x8007_0057;\n" + "const SENTINEL: usize = 0x5842_4F58_4F45_4D11;\n" + "const MASK: u64 = 0xffff_ffff_ff00_0000;\n" + "const NINE: u64 = 0x1_2345_6789;\n" + "const SEVEN: usize = 0x0001_2345_67;\n") + self.commit("crates/compat/x/src/a.rs", body) + self.commit("crates/other/src/a.rs", body) + why = "title RVA-style constant (usize/u64 with 6-8 significant hex digits) in a compat crate" + self.assertEqual(pr_gate.check_lines("HEAD~2", "HEAD", ["crates/compat/x/src/a.rs", "crates/other/src/a.rs"]), + [("crates/compat/x/src/a.rs:1", why), ("crates/compat/x/src/a.rs:2", why), + ("crates/compat/x/src/a.rs:9", why)]) + + def test_added_rust_comment_lines_are_rejected(self): + self.commit("c.rs", "fn c() {}\n// note\n //! doc\nlet u = \"http://x\";\n") + why = "comment line (the project keeps code free of comment lines)" + self.assertEqual(pr_gate.check_lines("HEAD^1", "HEAD", ["c.rs"]), [("c.rs:2", why), ("c.rs:3", why)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 5008b2bf..74d01bbf 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -17,7 +17,7 @@ env: CARGO_INCREMENTAL: "0" jobs: - rust-core: + rust-core-tests: runs-on: windows-latest timeout-minutes: 90 steps: @@ -43,9 +43,63 @@ jobs: - name: cargo check shell: bash run: cargo check --locked -p tombox-pe -p tombox-archive -p tombox-rpf -p tombox-disasm -p tombox-xshader --all-targets - - name: cargo test (no dumps, WARP only) + - name: cargo test (no dumps, WARP only, xshader exec runs in xshader-exec) + shell: bash + run: | + rest=() + for f in crates/tombox-xshader/tests/*.rs crates/tombox-xshader/tests/*/main.rs; do + [ -e "$f" ] || continue + n="$(basename "$f" .rs)" + if [ "$n" = main ]; then n="$(basename "$(dirname "$f")")"; fi + if [ "$n" != exec ]; then rest+=(--test "$n"); fi + done + rc=0 + cargo test --locked -p tombox-pe -p tombox-archive -p tombox-rpf -p tombox-disasm --no-fail-fast || rc=1 + cargo test --locked -p tombox-xshader --no-fail-fast --lib --bins "${rest[@]}" || rc=1 + cargo test --locked -p tombox-xshader --doc || rc=1 + exit "$rc" + + xshader-exec: + runs-on: windows-latest + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3, 4] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - name: Toolchain shell: bash - run: cargo test --locked -p tombox-pe -p tombox-archive -p tombox-rpf -p tombox-disasm -p tombox-xshader --no-fail-fast + run: | + rustup toolchain install stable --profile minimal + rustup default stable + - name: cargo test, xshader exec, shard ${{ matrix.shard }} of ${{ strategy.job-total }} (WARP only) + shell: bash + env: + SHARD_INDEX: ${{ strategy.job-index }} + SHARD_TOTAL: ${{ strategy.job-total }} + run: | + cargo test --locked -p tombox-xshader --test exec -- --list --format terse | tr -d '\r' | sed -n 's/: test$//p' | LC_ALL=C sort > "$RUNNER_TEMP/exec_all.txt" + awk -v k="$SHARD_INDEX" -v n="$SHARD_TOTAL" '(NR - 1) % n == k' "$RUNNER_TEMP/exec_all.txt" > "$RUNNER_TEMP/exec_shard.txt" + echo "shard $((SHARD_INDEX + 1)) of $SHARD_TOTAL: $(wc -l < "$RUNNER_TEMP/exec_shard.txt") of $(wc -l < "$RUNNER_TEMP/exec_all.txt") tests" + test -s "$RUNNER_TEMP/exec_shard.txt" + xargs cargo test --locked -p tombox-xshader --test exec -- --exact < "$RUNNER_TEMP/exec_shard.txt" + + rust-core: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + needs: [rust-core-tests, xshader-exec] + if: always() + steps: + - name: every test job succeeded + shell: bash + env: + RESULTS: ${{ join(needs.*.result, ' ') }} + run: | + echo "rust-core-tests xshader-exec: $RESULTS" + [ "$RESULTS" = "success success" ] rust-workspace-check: runs-on: windows-latest @@ -78,4 +132,4 @@ jobs: restore-keys: rust-ws-${{ runner.os }}- - name: cargo check --workspace shell: bash - run: cargo check --locked --workspace + run: cargo check --locked --workspace --exclude connectedstorageservice_proxystub --exclude gamecorecomproxy --exclude wldp diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f87fb9c7..a65a6ba8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ Contributions are welcome. The most useful thing you can add right now is covera | Path | What it is | |---|---| | `crates/compat//` | One crate per console DLL. It builds a drop-in DLL with the console's exports. | -| `crates/compat//exports.txt` | One line per export: `ordinal Name status \| notes`. Status is `implemented`, `forwarded`, `pc`, `title` or `missing`. | +| `crates/compat//exports.txt` | One line per export: `ordinal Name status \| notes`. Status is `implemented`, `forwarded`, `hooked`, `pc`, `title`, `unsupported` or `missing` (meanings in the [library map](docs/LIBRARY_MAP.md#statuses)). Only `implemented`, `forwarded` and `hooked` rows are routed to the emulator; every other row keeps the PC binding. | | `crates/compat/compat-common/` | Shared runtime: OS hooks, GDK file system and import routing. | | `crates/compat/d3d12_xs/`, `d3d12_x/` | Xbox Direct3D 12.x (Series X\|S and One). | | `crates/tombox-xshader/` | RDNA2 shader translator. | diff --git a/Cargo.lock b/Cargo.lock index 5e814a16..094ca3eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -83,6 +83,7 @@ name = "compat-common" version = "0.1.0" dependencies = [ "iced-x86", + "miniz_oxide", "serde_json", ] @@ -398,6 +399,8 @@ version = "0.1.0" name = "netprofmsvc_c" version = "0.1.0" dependencies = [ + "compat-common", + "console-sandbox", "xone-exports", ] @@ -858,6 +861,7 @@ dependencies = [ name = "xbtp" version = "0.1.0" dependencies = [ + "compat-common", "xone-exports", ] @@ -1075,6 +1079,7 @@ dependencies = [ name = "xtfdiaginfo" version = "0.1.0" dependencies = [ + "compat-common", "xbtp", "xtfbaseservices", "xtfcommon", diff --git a/README.md b/README.md index 276d5f78..aa7409e1 100644 --- a/README.md +++ b/README.md @@ -28,9 +28,9 @@ Uses legally obtained, already-decrypted dumps of games you own. The project doe | Area | State | |---|---| | Imported system functions (Fortnite EXE) | 671 / 671 covered | -| Direct3D 12.x interface methods | 192 / 200 (8 partial: Device 29, 44; CommandList 64, 70, 74, 85, 86, 101) | -| RDNA2 instructions verified | 787 / 794 | -| Xbox console library exports | 2,145 / 2,155 | +| Direct3D 12.x interface methods | 200 / 200 | +| RDNA2 instructions verified | 813 / 820 | +| Xbox console library exports | 2,147 / 2,155 | | Full shader sweep of the tested titles | 105,506 / 105,506 translate | | Shaders without a root signature (GTA VI mesh programs) | **New:** buffers *and* images / samplers translate in memory-descriptor mode; runtime side not wired yet | | Translator checked on real GPUs | **New:** GitHub Actions (Windows, WARP + DXC) and a Steam Deck (RDNA2, Proton / vkd3d-proton / RADV) | @@ -47,10 +47,10 @@ Uses legally obtained, already-decrypted dumps of games you own. The project doe | Title | Build | Result | |---|---|---| | Fortnite (Chapter 2 Season 4) | 2.0.1461.7919 | Boots, logs in to a local backend, reaches the Battle Royale lobby. 2D interface correct; 3D scene lit but materials wrong, bloom artifacts. No audio, no input. Not playable. | -| Trackmania | Xbox One build | Title menu draws at 144 fps. Open: xg_x HTILE / metadata planes, stencil-only MSAA views. | -| Terraria | Xbox One build | Runs 60 s without crashing; no frame yet (textures get GPU VA 0, Unity waits on the upload). | -| XDefiant | Series build | Runs about 140 s at 60 fps, frame black: aliased-VA render targets need shared backing. Parked. | -| Minecraft | GDK build | Imports analysed and GDK slots verified; not brought up. | +| Trackmania | 1.6.2.0 | **Boots and plays on the upstream developers' PC:** menus, login against the in-process backend, the Training - 01 race at about 60 fps, keyboard and controller. Video screens, billboards and streamed textures are black; stencil-tested lighting is dark. **Steam Deck (Proton, through `tombox-launch`):** the runtime, D3D12 device, shader translation and PSOs come up, then a null sub-object crashes it before the first frame (see docs/HANDOFF.md). | +| Terraria | 4.4.14.1081 | **Reaches its world** at 60 fps; keyboard and controller work when played by hand. Automated runs still crash some seconds after the world appears. | +| XDefiant | 1.0.0.186 | Boots to first frames (~26 s) at under 1 fps while shader and pipeline compiles block, then crashes. | +| Minecraft (Beta) | 1.18.3064.0 | Boots past the welcome screen to the menu (~44 s), then crashes in automated runs. | | Grand Theft Auto VI | 1.0.2.1 | **Not run: no executable exists in any dump.** Shader package examined (26,503 shaders). The blocker that stopped two thirds of them, resources bound without a root signature, now has a translator answer (memory-descriptor mode); the rest of the road is in the [roadmap](docs/ROADMAP.md). | ## What changed in the last round @@ -77,7 +77,7 @@ The full plan, with what blocks each step, is in **[docs/ROADMAP.md](docs/ROADMA 1. **Land the open pull requests** and keep CI green. 2. **Finish the GTA VI resource model:** the d3d12_xs runtime fills the user data, maps memory windows and keeps the T# / S# table (memory-descriptor step 3). -3. **Make a second title playable:** Trackmania past the menu, Terraria to its first frame, XDefiant out of the black frame, with audio and input. +3. **More titles playable:** Trackmania already plays on the upstream PC; next are its black video and stencil passes, Terraria past its automated-run crash, XDefiant past its first frames, and Trackmania on the Steam Deck. 4. **Fortnite in game:** correct 3D materials, audio, controller and keyboard. 5. **GTA VI:** everything that can be done without an executable now; boot when one exists. diff --git a/THIRD_PARTY/CREDITS b/THIRD_PARTY/CREDITS index 47a1ef18..653fb020 100644 --- a/THIRD_PARTY/CREDITS +++ b/THIRD_PARTY/CREDITS @@ -1,11 +1,24 @@ bcpack-rs (github.com/Ahmet-Dedeler/bcpack-rs @0a887de, MIT OR Apache-2.0): rANS lane decoder, BC1 block assembly, fitted BC1 window and codebook, synthetic test encoder; crates/compat/xcrdapi/src/bcpack, licence texts alongside silicon-rans (github.com/microsoft/silicon-rans @2f6827d, MIT): MDU rANS model tables from mdu_minirans.v; crates/compat/xcrdapi/src/bcpack/tables.rs, licence text alongside -Mesa (gitlab.freedesktop.org/mesa/mesa, MIT): image_bvh_intersect_ray / image_bvh64_intersect_ray semantics from src/amd/vulkan/radv_rt_common.c and bvh/bvh.h; crates/tombox-xshader/src/hlsl.rs BVH_HELPERS and tests/exec_mem/bvh.rs; GFX103 GDS_GWS_RESOURCE counter width from src/amd/registers/gfx103.json, in crates/tombox-xshader/src/gds_abi.rs (#134); D16 integer image load/store saturation and half-packing semantics from src/amd/common/nir/ac_nir_opt_16bit_tex_image and nir_opt_16bit_tex_image (reference only); crates/tombox-xshader/src/hlsl/mimg_d16.rs and hlsl.rs -LLVM (github.com/llvm/llvm-project, Apache-2.0 WITH LLVM-exception): GFX10 FLAT opcodes from FLATInstructions.td (reference only) and the amdgcn_trig_preop fold from AMDGPUInstCombineIntrinsic.cpp; crates/tombox-xshader/src/hlsl.rs tb_trig_preop64 and tests/exec_vop/mod.rs; the gfx7 dfmt/nfmt to GFX10 unified-format table from DfmtNfmt2UFmtGFX10 in crates/tombox-xshader/src/gcn.rs UFMT_GFX10 +Mesa (gitlab.freedesktop.org/mesa/mesa, MIT): image_bvh_intersect_ray / image_bvh64_intersect_ray semantics from src/amd/vulkan/radv_rt_common.c and bvh/bvh.h; crates/tombox-xshader/src/hlsl.rs BVH_HELPERS and tests/exec_mem/bvh.rs; GFX103 GDS_GWS_RESOURCE counter width from src/amd/registers/gfx103.json, in crates/tombox-xshader/src/gds_abi.rs (#134); D16 integer image load/store saturation and half-packing semantics from src/amd/common/nir/ac_nir_opt_16bit_tex_image and nir_opt_16bit_tex_image (reference only); crates/tombox-xshader/src/hlsl/mimg_d16.rs and hlsl.rs; DI_PT_RECTLIST corner convention (v0 shared corner, implied v3 = v1 + v2 - v0) from the rect-list vertex order radv and radeonsi use for their blit/meta draws (reference only, no code copied; as recalled, not re-checked against the source offline); emulator/crates/compat/d3d12_xs/src/rectlist.rs +LLVM (github.com/llvm/llvm-project, Apache-2.0 WITH LLVM-exception): GFX10 FLAT opcodes from FLATInstructions.td (reference only) and the amdgcn_trig_preop fold from AMDGPUInstCombineIntrinsic.cpp; crates/tombox-xshader/src/hlsl.rs tb_trig_preop64 and tests/exec_vop/mod.rs; the gfx7 dfmt/nfmt to GFX10 unified-format table from DfmtNfmt2UFmtGFX10 in crates/tombox-xshader/src/gcn.rs UFMT_GFX10; gfx1013 and gfx7 opcode names from the MC test vectors (@963ab285f26c) in crates/tombox-xshader/tests/isa_table/gfx1013.txt and gfx7.txt +AMD machine-readable GPU ISA specification (gpuopen.com/machine-readable-isa, MIT): RDNA1 and RDNA2 opcode names; crates/tombox-xshader/tests/isa_table/gfx1013.txt tinygrad (github.com/tinygrad/tinygrad, MIT): RDNA3/RDNA4 ISA pseudocode, reference only, for v_div_scale_f64, v_div_fixup_f64, v_trig_preop_f64, v_permlane16_b32, v_permlanex16_b32, v_mullit_f32; crates/tombox-xshader TheHumanCompiler (github.com/ajmiles/TheHumanCompiler, MIT): hardware-measured v_div_scale_f64 / v_div_fmas_f64 / v_div_fixup_f64 behaviour from src/isa/float64.ts; crates/tombox-xshader/src/hlsl.rs tb_div_*64 and tests/exec_vop/mod.rs -Leonida (github.com/ItsNotRexed/Leonida, GPL-3.0): hardware-checked input/result vectors from runtime/test/shaders/*.asm, facts only, programs rewritten; crates/tombox-xshader/tests/exec_vop/leonida.rs +Leonida (github.com/ItsNotRexed/Leonida, GPL-3.0): hardware-checked input/result vectors from runtime/test/shaders/*.asm, facts only, programs rewritten; crates/tombox-xshader/tests/exec_vop/leonida.rs and the negative-offset and alignment cases of scalar_smem_loads in crates/tombox-xshader/tests/exec.rs TomBox fork by brcly (github.com/brcly/TomBox @6b49c14, no longer reachable; a fork of github.com/drycheetah84/TomBox, which publishes no licence; the ported commit stated MIT OR Apache-2.0): pixel-shader interpolation modifiers matched in the feeding stage, ported in #36; crates/tombox-xshader/src/hlsl.rs and tests/linkage.rs, crates/compat/d3d12_xs shader_xlat.rs, mesh_pso.rs, device_wrap.rs, hot_reload.rs, crates/tools/xreplay; opt-in locale= override from 31d8b03 and size queries from 64e7c2a; crates/compat/compat-common/src/locale.rs and tests/locale_override.rs; WM_CLOSE ends the title from brcly/TomBox PR #12; crates/compat/d3d12_xs/src/present.rs; MIMG UNORM and A16 decoding and MUBUF LDS/TFE refusals from 97db52f and 9d3247a; crates/tombox-xshader/src/hlsl.rs and tests/exec_mem/mimg.rs miniz_oxide (github.com/Frommi/miniz_oxide, MIT OR Zlib OR Apache-2.0): crates.io dependency, zlib deflate/inflate for the XBCH v3 container; crates/compat/xbsc_xs XBSC_CompressBuffer / XBSC_DecompressBuffer xvdtool (github.com/emoose/xvdtool, MIT): reference only, no code copied, public XVD header layout and dynamic-XVD block allocation table placement; crates/compat/xcrdapi/src/xcrd_driver.rs and xcrd_xvdfile.rs TomBox by drycheetah84 (github.com/drycheetah84/TomBox @1d5dbc1, publishes no licence; the ported commit stated MIT OR Apache-2.0): ds_write_b16_d16_hi and buffer_store_format_xy/xyz decoding; crates/tombox-xshader/src/rdna2/mnem.rs and hlsl.rs +rocjitsu (github.com/ROCm/rocm-systems emulation/rocjitsu, MIT): v_log_f32 / v_exp_f32 / v_sin_f32 / v_cos_f32 models from lib/util/include/util/amdgpu_{exp,log,trig}.h, ported in #180; crates/tombox-xshader/src/trans32/amd.rs, licence text alongside +brcly/TuxBox (github.com/brcly/TuxBox, tools/reference/tombox-*.patch only, Apache-2.0 per its docs/REFERENCES.md; the rest of that repository is not used): ported patches credited per commit with brcly as author; licence text in THIRD_PARTY/LICENSE-TuxBox-APACHE-2.0.txt +Leonida 87d7bf7c43 (github.com/ItsNotRexed/Leonida, GPL-3.0): hardware-exact s_buffer_load bounds (dwords past NUM_RECORDS, times stride when stride != 0, return 0; base/soffset/imm each rounded down to 4; no 32-bit wrap of soffset+imm), rules taken from the relayed Leonida review measured on RX 6800, reimplemented because the Leonida source was not available offline; crates/tombox-xshader/src/hlsl/smem_bounds.rs and hlsl.rs Enc::Smem +Leonida e9f3b7e34e (github.com/ItsNotRexed/Leonida, GPL-3.0): the same SMEM bound applied to dynamic soffset reads, replacing the 64 KiB index wrap, on the cbuffer and raw-SRV (tb_cbrN.Load4) paths; rules from the relayed review, reimplemented offline; crates/tombox-xshader/src/hlsl/smem_bounds.rs, hlsl.rs, cbv_raw_hlsl.rs and tests/exec_mem/smem_nr.rs +Leonida 00af470cf5 (github.com/ItsNotRexed/Leonida, GPL-3.0): translate-time SMEM bounds when the V# NUM_RECORDS/stride words are known (constant 0 for dwords proven out of bounds, no check for dwords proven in bounds); rules from the relayed review, reimplemented offline; crates/tombox-xshader/src/hlsl/smem_bounds.rs +Leonida 533d5533a6 (github.com/ItsNotRexed/Leonida, GPL-3.0): v_mad_f32 and v_mad_legacy_f32 flush a subnormal result to signed zero again after the output modifier (FLT_MIN div:2 gives +0), measured on an RX 5600 XT (gfx1010) with tools/mad_denorm_probe.py; operand and result words of its omod cases, test rewritten, no code taken; crates/tombox-xshader/src/hlsl.rs and the mad_denorm cases of crates/tombox-xshader/tests/exec.rs +Leonida 7e7f6ce02c (github.com/ItsNotRexed/Leonida, GPL-3.0): ds_mskor_b32 and ds_mskor_rtn_b32 give M = (M & ~DATA) | DATA2, DATA2 bits outside DATA are ORed in too, the returning form gives the old word; measured on a gfx1100 card, rule only, lowered here as one compare-exchange loop, no code taken; crates/tombox-xshader/src/hlsl.rs and ds_lds_mskor_wrxchg2 in crates/tombox-xshader/tests/exec_mem/ds.rs +Leonida 6da90ef02e (github.com/ItsNotRexed/Leonida, GPL-3.0): ds_wrxchg2_rtn_b32 and ds_wrxchg2st64_rtn_b32 exchange the dwords at vaddr + offset0 * 4 and vaddr + offset1 * 4 (times 64 for st64), both before vdst is written, and two offsets on one dword make the second exchange return data0; measured on a gfx1100 card, rules only, no code taken; crates/tombox-xshader/src/hlsl/ds_ext.rs and ds_lds_mskor_wrxchg2 in crates/tombox-xshader/tests/exec_mem/ds.rs +libHttpClient (github.com/microsoft/libHttpClient @c5007fd9, MIT): behaviour of Tests/UnitTests/Tests/TaskQueueTests.cpp and AsyncBlockTests.cpp ported as test scenarios, and the XAsync return-code and scheduling rules of Source/Task/AsyncLib.cpp followed, rewritten, no code copied; crates/compat/compat-common/tests/support/xtq.rs and src/gdk/rt.rs +Leonida 0906a75f3d (github.com/ItsNotRexed/Leonida, GPL-3.0): an output modifier on an f16 VALU result acts only with IEEE 0 and f16 denormals flushed, a -0 result then becomes +0, and the modifier comes before clamp; measured on gfx1036 (docs/shader_validation.md, SHADER-135), rules only, no code taken; crates/tombox-xshader/src/hlsl.rs, hlsl/mode.rs and f16_omod_follows_mode in crates/tombox-xshader/tests/exec.rs +Leonida c0ac5fd6 (github.com/ItsNotRexed/Leonida, GPL-3.0): image_get_resinfo past the last level gives width, height and depth 0 while the level count stays, measured on a gfx1036 GPU (docs/shader_validation.md SHADER-388), rule only, no code taken; crates/tombox-xshader/src/hlsl.rs and the past-last-level cases of image_mimg_query in crates/tombox-xshader/tests/exec_mem/mimg.rs +Leonida e1b17b3a (github.com/ItsNotRexed/Leonida, GPL-3.0): packed 16-bit integer VOP3P ops take an inline float constant as its 32-bit IEEE word with op_sel choosing the half, and v_pk_mad_u16 / v_pk_mad_i16 clamp saturate to 0xffff and [-32768, 32767], measured on a gfx1036 GPU (docs/shader_validation.md SHADER-302), rules only, no code taken; crates/tombox-xshader/src/hlsl.rs, pk_int16_constants_and_clamp in crates/tombox-xshader/tests/exec.rs diff --git a/THIRD_PARTY/LICENSE-TuxBox-APACHE-2.0.txt b/THIRD_PARTY/LICENSE-TuxBox-APACHE-2.0.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/THIRD_PARTY/LICENSE-TuxBox-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/compat/compat-common/Cargo.toml b/crates/compat/compat-common/Cargo.toml index 55afd9c9..e77c89de 100644 --- a/crates/compat/compat-common/Cargo.toml +++ b/crates/compat/compat-common/Cargo.toml @@ -13,3 +13,4 @@ path = "src/lib.rs" # Relocates displaced prologue instructions when hooking network entry points (net_guard). iced-x86 = { version = "1.21.0", default-features = false, features = ["std", "decoder", "encoder", "block_encoder", "instr_info"] } serde_json = "1.0.154" +miniz_oxide = "0.8" diff --git a/crates/compat/compat-common/src/gameinput_ext.rs b/crates/compat/compat-common/src/gameinput_ext.rs index d75dadc9..5bea9695 100644 --- a/crates/compat/compat-common/src/gameinput_ext.rs +++ b/crates/compat/compat-common/src/gameinput_ext.rs @@ -632,8 +632,13 @@ pub fn store_rumble(device: usize, params: RumbleParams) -> (RumbleParams, bool) pub unsafe extern "system" fn dev_set_rumble_state(this: *mut c_void, params: *const RumbleParams) { let p = if params.is_null() { RumbleParams::default() } else { core::ptr::read_unaligned(params) }; let (p, changed) = store_rumble(this as usize, p); + let sent = if this == crate::gamepad::virtual_device() { crate::pad_host::forward_rumble(p.low_frequency, p.high_frequency) } else { None }; if changed { - log("SetRumbleState", &format!("device {this:p} low={:.2} high={:.2} lt={:.2} rt={:.2} (stored, not sent to a host device)", + let to = match sent { + Some(i) => format!("low/high sent to XInput pad {i}; trigger motors stored, XInput has none"), + None => "stored, not sent to a host device".into(), + }; + log("SetRumbleState", &format!("device {this:p} low={:.2} high={:.2} lt={:.2} rt={:.2} ({to})", p.low_frequency, p.high_frequency, p.left_trigger, p.right_trigger)); } } diff --git a/crates/compat/compat-common/src/gamepad.rs b/crates/compat/compat-common/src/gamepad.rs index 503dadfb..ebb64604 100644 --- a/crates/compat/compat-common/src/gamepad.rs +++ b/crates/compat/compat-common/src/gamepad.rs @@ -16,6 +16,7 @@ extern "system" { } pub const KIND_GAMEPAD: u32 = 0x0004_0000; +const KIND_KEYBOARD: u32 = 0x0000_0010; const STATUS_CONNECTED: u32 = 0x1; const STATUS_INPUT_ENABLED: u32 = 0x2; const S_OK: i32 = 0; @@ -183,6 +184,9 @@ pub fn parse_command(line: &str) -> Result, String> { } static STATE: Mutex = Mutex::new(PadState { buttons: 0, axes: [0.0; 6] }); +static HOST: Mutex = Mutex::new(PadState { buttons: 0, axes: [0.0; 6] }); +static SCRIPT_ACTIVE: AtomicBool = AtomicBool::new(false); +static TITLE_READS_KEYBOARD: AtomicBool = AtomicBool::new(false); static SEQ: AtomicU64 = AtomicU64::new(1); static HIST: Mutex = Mutex::new(history::History::new()); static POLLS: AtomicU64 = AtomicU64::new(0); @@ -191,6 +195,7 @@ static ORIG: [AtomicUsize; 24] = [const { AtomicUsize::new(0) }; 24]; static REAL_VTBL: AtomicUsize = AtomicUsize::new(0); static ORIG_CREATE: AtomicUsize = AtomicUsize::new(0); static LOG_N: AtomicU32 = AtomicU32::new(0); +static HOST_LOG_N: AtomicU32 = AtomicU32::new(0); static CONNECTED: AtomicBool = AtomicBool::new(false); #[derive(Clone, Copy, Debug, PartialEq)] @@ -250,8 +255,85 @@ fn log_limited(func: &str, detail: &str) { } } -fn snapshot() -> PadState { - *STATE.lock().unwrap_or_else(|e| e.into_inner()) +pub fn published() -> PadState { + let script = *STATE.lock().unwrap_or_else(|e| e.into_inner()); + let host = *HOST.lock().unwrap_or_else(|e| e.into_inner()); + crate::pad_host::merge(script, SCRIPT_ACTIVE.load(Ordering::SeqCst), host) +} + +fn published_with(script: &PadState) -> PadState { + let host = *HOST.lock().unwrap_or_else(|e| e.into_inner()); + crate::pad_host::merge(*script, SCRIPT_ACTIVE.load(Ordering::SeqCst), host) +} + +fn record_published() { + let g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let seq = SEQ.fetch_add(1, Ordering::SeqCst) + 1; + let state = published_with(&g).to_bytes(); + HIST.lock().unwrap_or_else(|e| e.into_inner()).push(history::Entry { seq, ts: now_us(), state }); +} + +pub(crate) fn set_host(s: PadState) { + let changed = { + let mut g = HOST.lock().unwrap_or_else(|e| e.into_inner()); + let c = *g != s; + *g = s; + c + }; + if changed { + record_published(); + let n = HOST_LOG_N.fetch_add(1, Ordering::Relaxed); + if n < 20 || n % 5000 == 0 { + log("host", &format!("host -> buttons={:#06x} lt={:.2} rt={:.2} lx={:.2} ly={:.2} rx={:.2} ry={:.2}{} (#{n})", + s.buttons, s.axes[0], s.axes[1], s.axes[2], s.axes[3], s.axes[4], s.axes[5], + if published() == s { "" } else { ", masked by the scripted pad" })); + } + } +} + +pub(crate) fn host_connect(on: bool, why: &str) { + if SCRIPT_ACTIVE.load(Ordering::SeqCst) || CONNECTED.load(Ordering::SeqCst) == on { + return; + } + log("host", &format!("{why} -> virtual pad {}", if on { "plugged in" } else { "unplugged" })); + set_connected(on); +} + +fn set_script_active(on: bool) { + if SCRIPT_ACTIVE.swap(on, Ordering::SeqCst) != on { + record_published(); + } +} + +pub(crate) fn title_reads_keyboard() -> bool { + TITLE_READS_KEYBOARD.load(Ordering::SeqCst) +} + +fn note_reading_kind(api: &str, kind: u32) { + if kind & KIND_KEYBOARD != 0 && !TITLE_READS_KEYBOARD.swap(true, Ordering::SeqCst) { + log(api, &format!("title asks for keyboard readings (kind={kind:#x}); the host keyboard reaches it through GameInput")); + } +} + +pub(crate) fn host_has_gamepad() -> bool { + let (real, f) = (REAL_THIS.load(Ordering::SeqCst), orig(4)); + if real == 0 || f == 0 { + return false; + } + unsafe { + let f: unsafe extern "system" fn(*mut c_void, u32, *mut c_void, *mut *mut c_void) -> i32 = core::mem::transmute(f); + let mut r: *mut c_void = core::ptr::null_mut(); + if f(real as *mut c_void, KIND_GAMEPAD, core::ptr::null_mut(), &mut r) < 0 || r.is_null() { + return false; + } + let release: unsafe extern "system" fn(*mut c_void) -> u32 = core::mem::transmute(*(*(r as *const *const usize)).add(2)); + release(r); + true + } +} + +pub fn virtual_device() -> *mut c_void { + vdev() } fn update(what: &str, f: impl FnOnce(&mut PadState)) { @@ -259,7 +341,7 @@ fn update(what: &str, f: impl FnOnce(&mut PadState)) { let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); f(&mut g); let seq = SEQ.fetch_add(1, Ordering::SeqCst) + 1; - HIST.lock().unwrap_or_else(|e| e.into_inner()).push(history::Entry { seq, ts: now_us(), state: g.to_bytes() }); + HIST.lock().unwrap_or_else(|e| e.into_inner()).push(history::Entry { seq, ts: now_us(), state: published_with(&g).to_bytes() }); *g }; log("state", &format!("{what} -> buttons={:#06x} lt={:.2} rt={:.2} lx={:.2} ly={:.2} rx={:.2} ry={:.2}", @@ -297,6 +379,7 @@ unsafe fn init_device() { b[0x40..0x60].copy_from_slice(&DEVICE_ID); b[0x60..0x64].copy_from_slice(&1u32.to_le_bytes()); b[0x68..0x6C].copy_from_slice(&KIND_GAMEPAD.to_le_bytes()); + b[0x6C..0x70].copy_from_slice(&0x3u32.to_le_bytes()); let vt = &mut *core::ptr::addr_of_mut!(DEVICE_VTBL); for s in vt.iter_mut() { *s = ret_notimpl as usize; @@ -307,9 +390,7 @@ unsafe fn init_device() { vt[3] = dev_info as usize; vt[4] = dev_status as usize; vt[5] = dev_battery as usize; - for i in [7usize, 8, 10, 11, 12, 13] { - vt[i] = ret_zero as usize; - } + crate::gameinput_ext::install_pad_feedback(vt.as_mut_ptr()); (*core::ptr::addr_of_mut!(DEVICE)).vtbl = vt.as_ptr(); } @@ -405,7 +486,7 @@ fn new_reading() -> *mut c_void { let (seq, state) = { let g = STATE.lock().unwrap_or_else(|e| e.into_inner()); let seq = SEQ.load(Ordering::SeqCst); - let state = g.to_bytes(); + let state = published_with(&g).to_bytes(); let mut h = HIST.lock().unwrap_or_else(|e| e.into_inner()); if h.len() == 0 { h.push(history::Entry { seq, ts: now_us(), state }); @@ -529,6 +610,7 @@ type DeviceCb = unsafe extern "system" fn(u64, *mut c_void, *mut c_void, u64, u3 unsafe extern "system" fn gi_current(this: *mut c_void, kind: u32, device: *mut c_void, out: *mut *mut c_void) -> i32 { host::count(4); + note_reading_kind("GetCurrentReading", kind); if out.is_null() { return 0x8000_4003u32 as i32; } @@ -559,6 +641,7 @@ unsafe extern "system" fn gi_current(this: *mut c_void, kind: u32, device: *mut unsafe extern "system" fn gi_next(this: *mut c_void, reference: *mut c_void, kind: u32, device: *mut c_void, out: *mut *mut c_void) -> i32 { host::count(5); + note_reading_kind("GetNextReading", kind); if device == vdev() || is_reading(reference) { return virtual_neighbour(true, reference, kind, out); } @@ -568,6 +651,7 @@ unsafe extern "system" fn gi_next(this: *mut c_void, reference: *mut c_void, kin unsafe extern "system" fn gi_prev(this: *mut c_void, reference: *mut c_void, kind: u32, device: *mut c_void, out: *mut *mut c_void) -> i32 { host::count(6); + note_reading_kind("GetPreviousReading", kind); if device == vdev() || is_reading(reference) { return virtual_neighbour(false, reference, kind, out); } @@ -715,6 +799,7 @@ unsafe extern "system" fn create_hook(out: *mut *mut c_void) -> i32 { if hr >= 0 && !out.is_null() && !(*out).is_null() { patch_object(*out); start_channel(); + crate::pad_host::start(); } else { log("GameInputCreate", &format!("real GameInputCreate failed hr={hr:#x}")); } @@ -932,6 +1017,7 @@ fn channel_loop() { .collect()) .unwrap_or_default(); files.sort(); + set_script_active(!files.is_empty()); for f in files { let text = std::fs::read_to_string(&f).unwrap_or_default(); let fname = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); @@ -951,6 +1037,7 @@ fn channel_loop() { let _ = std::fs::remove_file(&f); log("cmd", &format!("{fname}: done (readings served so far: {})", POLLS.load(Ordering::SeqCst))); } + set_script_active(false); std::thread::sleep(Duration::from_millis(15)); } } @@ -959,6 +1046,28 @@ fn channel_loop() { mod tests { use super::*; + #[test] + fn host_state_reaches_readings_and_their_history() { + let mut s = PadState::default(); + s.buttons = 0x4; + s.axes[2] = 0.5; + let before = SEQ.load(Ordering::SeqCst); + set_host(s); + let r = new_reading() as *mut Reading; + let (seq, state) = unsafe { ((*r).seq, (*r).state) }; + unsafe { drop(Box::from_raw(r)) }; + let step = HIST.lock().unwrap_or_else(|e| e.into_inner()).next(before, now_us()); + set_host(PadState::default()); + assert_eq!(state, s.to_bytes()); + match step { + history::Step::Found(e) => { + assert_eq!(e.state, s.to_bytes()); + assert!(e.seq > before && e.seq <= seq); + } + other => panic!("host change not in the reading history: {other:?}"), + } + } + #[test] fn parses_press_with_default_and_explicit_ms() { assert_eq!(parse_command("press A").unwrap(), Some(Cmd::Press(vec![Input::Button(BTN_A)], DEFAULT_PRESS_MS))); diff --git a/crates/compat/compat-common/src/gdk/capture.rs b/crates/compat/compat-common/src/gdk/capture.rs index 221cc4aa..ddaabed9 100644 --- a/crates/compat/compat-common/src/gdk/capture.rs +++ b/crates/compat/compat-common/src/gdk/capture.rs @@ -53,8 +53,8 @@ unsafe extern "system" fn register_broadcast(_t: This, queue: usize, ctx: *mut c BROADCAST_CHANGED.register(0, queue, ctx, cb, token) } -unsafe extern "system" fn unregister_broadcast(_t: This, token: u64, _wait: bool) -> bool { - BROADCAST_CHANGED.unregister(None, token) +unsafe extern "system" fn unregister_broadcast(_t: This, token: u64, wait: bool) -> bool { + BROADCAST_CHANGED.unregister(None, token, wait) } fn metadata_quota() -> u64 { @@ -162,8 +162,8 @@ unsafe extern "system" fn register_purged(_t: This, queue: usize, ctx: *mut c_vo METADATA_PURGED.register(0, queue, ctx, cb, token) } -unsafe extern "system" fn unregister_purged(_t: This, token: u64, _wait: bool) -> bool { - METADATA_PURGED.unregister(None, token) +unsafe extern "system" fn unregister_purged(_t: This, token: u64, wait: bool) -> bool { + METADATA_PURGED.unregister(None, token, wait) } fn grab() -> Option { diff --git a/crates/compat/compat-common/src/gdk/events.rs b/crates/compat/compat-common/src/gdk/events.rs index 0601a8cb..1053b4db 100644 --- a/crates/compat/compat-common/src/gdk/events.rs +++ b/crates/compat/compat-common/src/gdk/events.rs @@ -1,5 +1,6 @@ use super::{next_token, E_INVALIDARG, S_OK}; -use std::sync::Mutex; +use std::sync::{Condvar, Mutex, MutexGuard}; +use std::thread::ThreadId; #[derive(Clone, Copy)] pub struct Reg { @@ -10,13 +11,40 @@ pub struct Reg { pub cb: usize, } +struct Inner { + regs: Vec, + active: Vec<(u64, ThreadId)>, +} + pub struct Registry { - regs: Mutex>, + inner: Mutex, + idle: Condvar, +} + +struct Running { + reg: &'static Registry, + token: u64, +} + +impl Drop for Running { + fn drop(&mut self) { + let me = std::thread::current().id(); + let mut g = self.reg.lock(); + if let Some(i) = g.active.iter().position(|&(t, th)| t == self.token && th == me) { + g.active.swap_remove(i); + } + drop(g); + self.reg.idle.notify_all(); + } } impl Registry { pub const fn new() -> Registry { - Registry { regs: Mutex::new(Vec::new()) } + Registry { inner: Mutex::new(Inner { regs: Vec::new(), active: Vec::new() }), idle: Condvar::new() } + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(|e| e.into_inner()) } pub unsafe fn register(&self, owner: usize, queue: usize, ctx: *mut core::ffi::c_void, cb: usize, token: *mut u64) -> i32 { @@ -24,24 +52,31 @@ impl Registry { return E_INVALIDARG; } let t = next_token(); - self.regs.lock().unwrap_or_else(|e| e.into_inner()).push(Reg { token: t, owner, queue, ctx: ctx as usize, cb }); + self.lock().regs.push(Reg { token: t, owner, queue, ctx: ctx as usize, cb }); *token = t; S_OK } - pub fn unregister(&self, owner: Option, token: u64) -> bool { - let mut v = self.regs.lock().unwrap_or_else(|e| e.into_inner()); - let before = v.len(); - v.retain(|r| !(r.token == token && owner.map_or(true, |o| o == r.owner))); - v.len() != before + pub fn unregister(&self, owner: Option, token: u64, wait: bool) -> bool { + let me = std::thread::current().id(); + let mut g = self.lock(); + let before = g.regs.len(); + g.regs.retain(|r| !(r.token == token && owner.map_or(true, |o| o == r.owner))); + let removed = g.regs.len() != before; + if removed && wait { + while g.active.iter().any(|&(t, th)| t == token && th != me) { + g = self.idle.wait(g).unwrap_or_else(|e| e.into_inner()); + } + } + removed } pub fn all(&self) -> Vec { - self.regs.lock().unwrap_or_else(|e| e.into_inner()).clone() + self.lock().regs.clone() } pub fn len(&self) -> usize { - self.regs.lock().unwrap_or_else(|e| e.into_inner()).len() + self.lock().regs.len() } pub fn is_empty(&self) -> bool { @@ -49,25 +84,41 @@ impl Registry { } pub fn contains(&self, token: u64) -> bool { - self.regs.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|r| r.token == token) + self.lock().regs.iter().any(|r| r.token == token) + } + + pub fn in_flight(&self, token: u64) -> usize { + self.lock().active.iter().filter(|a| a.0 == token).count() + } + + fn enter(&'static self, token: u64) -> Option { + let mut g = self.lock(); + if !g.regs.iter().any(|r| r.token == token) { + return None; + } + g.active.push((token, std::thread::current().id())); + Some(Running { reg: self, token }) } pub fn fire_token(&'static self, token: u64, f: F) -> i32 where F: FnOnce(&Reg) + Send + 'static, { - let found = self.regs.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|r| r.token == token).copied(); + let found = self.lock().regs.iter().find(|r| r.token == token).copied(); let Some(reg) = found else { return E_INVALIDARG }; unsafe { super::xasync::submit(reg.queue, 1, Box::new(move |canceled| { - if !canceled && self.contains(reg.token) { + if canceled { + return; + } + if let Some(_run) = self.enter(reg.token) { f(®) } })) } } - pub fn fire(&self, owner: Option, f: F) + pub fn fire(&'static self, owner: Option, f: F) where F: Fn(&Reg) + Send + Sync + Clone + 'static, { @@ -77,7 +128,10 @@ impl Registry { let reg = r; unsafe { super::xasync::submit(r.queue, 1, Box::new(move |canceled| { - if !canceled { + if canceled { + return; + } + if let Some(_run) = self.enter(reg.token) { f(®) } })); diff --git a/crates/compat/compat-common/src/gdk/fs.rs b/crates/compat/compat-common/src/gdk/fs.rs index 715089c9..c401e11a 100644 --- a/crates/compat/compat-common/src/gdk/fs.rs +++ b/crates/compat/compat-common/src/gdk/fs.rs @@ -183,13 +183,32 @@ const TABLE: &[Row] = &[ ("_unlink", K::A, &[0], 1), ("remove", K::A, &[0], 1), ("CreateFile2", K::W, &[0], 5), + ("CopyFileExW", K::W, &[0, 1], 6), + ("MoveFileWithProgressW", K::W, &[0, 1], 5), + ("ReplaceFileW", K::W, &[0, 1, 2], 6), + ("CopyFile2", K::W, &[0, 1], 3), + ("CreateFileA", K::A, &[0], 7), + ("DeleteFileA", K::A, &[0], 1), + ("CreateDirectoryA", K::A, &[0], 2), + ("FindFirstFileExA", K::A, &[0], 6), + ("SetFileAttributesA", K::A, &[0], 2), + ("_mkdir", K::A, &[0], 1), + ("_open", K::A, &[0], 3), + ("_access", K::A, &[0], 2), + ("_stat64", K::A, &[0], 2), + ("rename", K::A, &[0, 1], 2), + ("_wopen", K::W, &[0], 3), + ("_wstat64", K::W, &[0], 2), + ("_wfopen_s", K::W, &[1], 3), + ("_wremove", K::W, &[0], 1), + ("_wrename", K::W, &[0, 1], 2), ]; -static ORIG: [AtomicUsize; 25] = [const { AtomicUsize::new(0) }; 25]; +static ORIG: [AtomicUsize; 44] = [const { AtomicUsize::new(0) }; 44]; macro_rules! hooks { ($($i:tt $n:tt),*) => { - fn hook_table() -> [usize; 25] { + fn hook_table() -> [usize; 44] { [$(hook_fn!($i $n)),*] } }; @@ -205,7 +224,7 @@ macro_rules! hook_fn { ($i:tt 7) => {{ unsafe extern "system" fn h(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize) -> usize { run($i, vec![a, b, c, d, e, f, g]) } h as usize }}; } -hooks!(0 7, 1 6, 2 2, 3 1, 4 3, 5 2, 6 2, 7 1, 8 1, 9 4, 10 1, 11 3, 12 2, 13 3, 14 2, 15 3, 16 1, 17 3, 18 1, 19 3, 20 2, 21 3, 22 1, 23 1, 24 5); +hooks!(0 7, 1 6, 2 2, 3 1, 4 3, 5 2, 6 2, 7 1, 8 1, 9 4, 10 1, 11 3, 12 2, 13 3, 14 2, 15 3, 16 1, 17 3, 18 1, 19 3, 20 2, 21 3, 22 1, 23 1, 24 5, 25 6, 26 5, 27 6, 28 3, 29 7, 30 1, 31 2, 32 6, 33 2, 34 1, 35 3, 36 2, 37 2, 38 2, 39 3, 40 2, 41 3, 42 1, 43 2); pub fn targets() -> Vec<(&'static str, usize, &'static AtomicUsize)> { if game_drive().is_none() && !trace_on() && !super::xcrd_paths::enabled() { diff --git a/crates/compat/compat-common/src/gdk/late.rs b/crates/compat/compat-common/src/gdk/late.rs index a695b45c..6db99024 100644 --- a/crates/compat/compat-common/src/gdk/late.rs +++ b/crates/compat/compat-common/src/gdk/late.rs @@ -41,7 +41,7 @@ unsafe extern "system" fn loaded(reason: u32, data: *const u8, _ctx: *mut c_void return; } let path = String::from_utf16_lossy(core::slice::from_raw_parts(buf, len)); - if !is_title_path(&path) { + if !is_title_path(&path) || crate::os_host::foreign::is_host_injected(&path) { return; } let n = super::hook::patch_late(base); @@ -55,6 +55,7 @@ pub fn watch() -> bool { if WATCHING.load(Ordering::Acquire) { return true; } + crate::os_host::foreign::prime(); unsafe { let nt: Vec = "ntdll.dll\0".encode_utf16().collect(); let h = GetModuleHandleW(nt.as_ptr()); diff --git a/crates/compat/compat-common/src/gdk/mod.rs b/crates/compat/compat-common/src/gdk/mod.rs index ab5ed221..6d940f66 100644 --- a/crates/compat/compat-common/src/gdk/mod.rs +++ b/crates/compat/compat-common/src/gdk/mod.rs @@ -450,9 +450,11 @@ extern "system" { #[link_section = ".CRT$XCU"] pub static EARLY_INIT: extern "C" fn() = early_init; +pub static EARLY_INIT_OPT_OUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + extern "C" fn early_init() { let _ = std::panic::catch_unwind(|| { - if setting("gdk_early").as_deref() != Some("0") { + if !EARLY_INIT_OPT_OUT.load(std::sync::atomic::Ordering::SeqCst) && setting("gdk_early").as_deref() != Some("0") { install(); } }); diff --git a/crates/compat/compat-common/src/gdk/net.rs b/crates/compat/compat-common/src/gdk/net.rs index 746c75d0..c67dfea7 100644 --- a/crates/compat/compat-common/src/gdk/net.rs +++ b/crates/compat/compat-common/src/gdk/net.rs @@ -274,8 +274,8 @@ unsafe extern "system" fn register_port(_t: This, queue: usize, ctx: *mut c_void PORT_CHANGED.register(0, queue, ctx, cb, token) } -unsafe extern "system" fn unregister_port(_t: This, token: u64, _wait: bool) -> bool { - PORT_CHANGED.unregister(None, token) +unsafe extern "system" fn unregister_port(_t: This, token: u64, wait: bool) -> bool { + PORT_CHANGED.unregister(None, token, wait) } pub fn notify_connectivity_changed() { @@ -319,8 +319,8 @@ unsafe extern "system" fn register_hint(_t: This, queue: usize, ctx: *mut c_void hr } -unsafe extern "system" fn unregister_hint(_t: This, token: u64, _wait: bool) -> bool { - HINT_CHANGED.unregister(None, token) +unsafe extern "system" fn unregister_hint(_t: This, token: u64, wait: bool) -> bool { + HINT_CHANGED.unregister(None, token, wait) } pub const IID_V2: Guid = Guid::parse("bf2346b2-39af-4658-b5ea-44713c7e83b3"); diff --git a/crates/compat/compat-common/src/gdk/package.rs b/crates/compat/compat-common/src/gdk/package.rs index c808e7e1..eb051297 100644 --- a/crates/compat/compat-common/src/gdk/package.rs +++ b/crates/compat/compat-common/src/gdk/package.rs @@ -436,8 +436,8 @@ unsafe extern "system" fn update_monitor(_t: This, m: usize) { }); } -unsafe extern "system" fn unregister_progress(_t: This, m: usize, token: u64, _wait: bool) -> bool { - PROGRESS.unregister(Some(m), token) +unsafe extern "system" fn unregister_progress(_t: This, m: usize, token: u64, wait: bool) -> bool { + PROGRESS.unregister(Some(m), token, wait) } unsafe extern "system" fn register_progress_v2(_t: This, m: usize, ctx: *mut c_void, cb: usize, token: *mut u64) -> i32 { @@ -451,8 +451,8 @@ unsafe extern "system" fn register_installed(_t: This, queue: usize, ctx: *mut c INSTALLED.register(0, queue, ctx, cb, token) } -unsafe extern "system" fn unregister_installed(_t: This, token: u64, _wait: bool) -> bool { - INSTALLED.unregister(None, token) +unsafe extern "system" fn unregister_installed(_t: This, token: u64, wait: bool) -> bool { + INSTALLED.unregister(None, token, wait) } pub fn user_locale() -> String { diff --git a/crates/compat/compat-common/src/gdk/rt.rs b/crates/compat/compat-common/src/gdk/rt.rs index 0b010897..35f90f7d 100644 --- a/crates/compat/compat-common/src/gdk/rt.rs +++ b/crates/compat/compat-common/src/gdk/rt.rs @@ -1,3 +1,4 @@ +use super::streaming::E_NO_TASK_QUEUE; use super::xasync::{ProviderData, XASYNC}; use super::{log, setting, Iface, This, E_ABORT, E_INVALIDARG, E_NOT_SUFFICIENT_BUFFER, E_PENDING, S_OK}; use core::ffi::c_void; @@ -745,6 +746,7 @@ pub struct Block { } const BMAGIC: u32 = 0x4158_4254; +const E_UNEXPECTED: i32 = 0x8000_FFFFu32 as i32; struct AState { provider: Provider, @@ -755,6 +757,7 @@ struct AState { cleaned: AtomicBool, queue: usize, canceled: AtomicBool, + scheduled: AtomicBool, data: Box>, } @@ -811,6 +814,19 @@ pub unsafe fn begin(block: *mut Block, ctx: *mut c_void, identity: usize, _name: return E_INVALIDARG; } } + let qh = (*block).queue; + let early = if qh == 0 && process_queue() == 0 { + E_NO_TASK_QUEUE + } else if queue(qh).is_some_and(|q| q.ended.load(Ordering::Acquire) || q.work.terminated.load(Ordering::Acquire)) { + E_ABORT + } else { + S_OK + }; + if early < 0 { + states().lock().unwrap_or_else(|e| e.into_inner()).remove(&(block as usize)); + mark(block, early, false); + return early; + } let s = Arc::new(AState { provider, ctx: ctx as usize, @@ -820,32 +836,36 @@ pub unsafe fn begin(block: *mut Block, ctx: *mut c_void, identity: usize, _name: cleaned: AtomicBool::new(false), queue: (*block).queue, canceled: AtomicBool::new(false), + scheduled: AtomicBool::new(false), data: Box::new(core::cell::UnsafeCell::new(ProviderData { block: block as *mut c_void, buffer_size: 0, buffer: core::ptr::null_mut(), context: ctx })), }); states().lock().unwrap_or_else(|e| e.into_inner()).insert(block as usize, s.clone()); mark(block, E_PENDING, true); let hr = call(&s, 0, block, 0, core::ptr::null_mut()); - if hr < 0 { - states().lock().unwrap_or_else(|e| e.into_inner()).remove(&(block as usize)); - mark(block, hr, false); - return hr; + if hr < 0 && hr != E_PENDING { + complete_state(&s, block, hr, 0); } S_OK } pub unsafe fn schedule(block: *mut Block, delay: u32) -> i32 { let Some(s) = state(block as usize) else { return E_INVALIDARG }; + if s.scheduled.swap(true, Ordering::AcqRel) { + return E_UNEXPECTED; + } + let owner = s.clone(); let b = SendPtr(block as usize); let job: Job = Box::new(move |canceled| { + owner.scheduled.store(false, Ordering::Release); let block = b.0 as *mut Block; - let Some(s) = state(block as usize) else { return }; + let Some(s) = state(block as usize).filter(|c| Arc::ptr_eq(c, &owner)) else { return }; if canceled || s.canceled.load(Ordering::Acquire) { complete(block, E_ABORT, 0); return; } let hr = call(&s, 1, block, 0, core::ptr::null_mut()); if hr != E_PENDING { - complete(block, hr, 0); + complete_state(&s, block, if hr >= 0 { E_UNEXPECTED } else { hr }, 0); } }); submit_delayed(s.queue, 0, delay, job) @@ -856,6 +876,13 @@ pub unsafe fn complete(block: *mut Block, hr: i32, size: usize) { return; } let Some(s) = state(block as usize) else { return }; + complete_state(&s, block, hr, size) +} + +unsafe fn complete_state(s: &Arc, block: *mut Block, hr: i32, size: usize) { + if hr == E_PENDING { + return; + } { let mut st = s.status.lock().unwrap_or_else(|e| e.into_inner()); if st.0 != E_PENDING { @@ -920,17 +947,15 @@ pub unsafe fn get_result_size(block: *mut Block, out: *mut usize) -> i32 { Some(s) => { let st = *s.status.lock().unwrap_or_else(|e| e.into_inner()); if st.0 < 0 || st.0 == E_PENDING { + *out = 0; return st.0; } *out = st.1; S_OK } None => { - let hr = marked(block).unwrap_or(E_INVALIDARG); - if hr >= 0 { - *out = 0; - } - hr + *out = 0; + marked(block).unwrap_or(E_INVALIDARG) } } } @@ -953,7 +978,10 @@ pub unsafe fn get_result(block: *mut Block, identity: usize, size: usize, buf: * if hr < 0 || hr == E_PENDING { return hr; } - if size < need || (buf.is_null() && need > 0) { + if buf.is_null() && need > 0 { + return E_INVALIDARG; + } + if size < need { return E_NOT_SUFFICIENT_BUFFER; } let r = if need > 0 { call(&s, 2, block, need, buf) } else { S_OK }; @@ -980,7 +1008,7 @@ pub unsafe fn cancel(block: *mut Block) { unsafe extern "system" fn run_provider(op: u32, d: *const ProviderData) -> i32 { if op == 1 { let w: AsyncWork = core::mem::transmute((*d).context); - return w((*d).block); + complete((*d).block as *mut Block, w((*d).block), 0); } S_OK } diff --git a/crates/compat/compat-common/src/gdk/save.rs b/crates/compat/compat-common/src/gdk/save.rs index 8898c374..ecde4dcb 100644 --- a/crates/compat/compat-common/src/gdk/save.rs +++ b/crates/compat/compat-common/src/gdk/save.rs @@ -5,9 +5,18 @@ use std::collections::HashMap; use std::ffi::{CStr, CString}; use std::io; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::UNIX_EPOCH; +fn first_call(slot: u32, name: &str) { + static SEEN: AtomicU64 = AtomicU64::new(0); + let bit = 1u64 << slot; + if SEEN.fetch_or(bit, Ordering::Relaxed) & bit == 0 { + log(name, &format!("first call (slot {slot})")); + } +} + pub const CLSID: Guid = Guid::parse("704c3f58-e629-4cc2-b197-30511b996fe2"); pub const E_GS_INVALID_CONTAINER_NAME: i32 = 0x8083_0001u32 as i32; @@ -50,6 +59,41 @@ pub fn decode_name(s: &str) -> Option { String::from_utf8(out).ok() } +pub const BLOB_ENC_MAX: usize = 244; +pub const CONTAINER_ENC_MAX: usize = 253; + +fn fnv(s: &str, seed: u64) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64 ^ seed; + for &b in s.as_bytes() { + h ^= b as u64; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h +} + +pub fn file_enc(s: &str, max: usize) -> String { + let e = encode_name(s); + if e.len() <= max { + e + } else { + let f = s.to_lowercase(); + format!("~H{:016x}{:016x}", fnv(&f, 0), fnv(&f, 0x9e37_79b9_7f4a_7c15)) + } +} + +fn is_hashed(enc: &str) -> bool { + enc.starts_with("~H") +} + +fn name_from(enc: &str, sidecar: &Path, max: usize) -> Option { + if is_hashed(enc) { + let n = std::fs::read_to_string(sidecar).ok()?; + file_enc(&n, max).eq_ignore_ascii_case(enc).then_some(n) + } else { + decode_name(enc) + } +} + pub fn valid_name(s: &str, max: usize) -> bool { !s.is_empty() && s.len() <= max && !s.contains('\0') } @@ -120,6 +164,12 @@ impl Store { Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), _ => {} } + if is_hashed(enc) { + match std::fs::remove_file(d.join(format!("n_{enc}"))) { + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => {} + } + } } else if line == "N" { let tmp = d.join(".display.tmp"); if tmp.exists() { @@ -135,16 +185,17 @@ impl Store { } fn cdir(&self, name: &str) -> PathBuf { - self.root.join(format!("c_{}", encode_name(name))) + self.root.join(format!("c_{}", file_enc(name, CONTAINER_ENC_MAX))) } pub fn blobs(&self, container: &str) -> Vec<(String, u64)> { let mut v = Vec::new(); - if let Ok(rd) = std::fs::read_dir(self.cdir(container)) { + let d = self.cdir(container); + if let Ok(rd) = std::fs::read_dir(&d) { for e in rd.flatten() { let f = e.file_name().to_string_lossy().into_owned(); if let Some(enc) = f.strip_prefix("b_").and_then(|x| x.strip_suffix(".blob")) { - if let Some(n) = decode_name(enc) { + if let Some(n) = name_from(enc, &d.join(format!("n_{enc}")), BLOB_ENC_MAX) { v.push((n, e.metadata().map(|m| m.len()).unwrap_or(0))); } } @@ -163,7 +214,7 @@ impl Store { let display = std::fs::read_to_string(d.join(".display")).unwrap_or_default(); let mut modified = mtime(&d); for (b, _) in &blobs { - modified = modified.max(mtime(&d.join(format!("b_{}.blob", encode_name(b))))); + modified = modified.max(mtime(&d.join(format!("b_{}.blob", file_enc(b, BLOB_ENC_MAX))))); } Some(ContainerInfo { name: name.to_string(), @@ -179,7 +230,7 @@ impl Store { if let Ok(rd) = std::fs::read_dir(&self.root) { for e in rd.flatten() { let f = e.file_name().to_string_lossy().into_owned(); - if let Some(n) = f.strip_prefix("c_").and_then(decode_name) { + if let Some(n) = f.strip_prefix("c_").and_then(|enc| name_from(enc, &e.path().join(".name"), CONTAINER_ENC_MAX)) { if e.path().is_dir() { names.push(n); } @@ -191,16 +242,22 @@ impl Store { } pub fn read_blob(&self, container: &str, blob: &str) -> Option> { - std::fs::read(self.cdir(container).join(format!("b_{}.blob", encode_name(blob)))).ok() + std::fs::read(self.cdir(container).join(format!("b_{}.blob", file_enc(blob, BLOB_ENC_MAX)))).ok() } pub fn commit(&self, container: &str, display: Option<&str>, writes: &[(String, Vec)], deletes: &[String]) -> io::Result<()> { let _g = Self::lock(); let d = self.cdir(container); std::fs::create_dir_all(&d)?; + if is_hashed(&file_enc(container, CONTAINER_ENC_MAX)) && std::fs::read_to_string(d.join(".name")).ok().as_deref() != Some(container) { + std::fs::write(d.join(".name"), container)?; + } let mut journal = String::new(); for (name, data) in writes { - let enc = encode_name(name); + let enc = file_enc(name, BLOB_ENC_MAX); + if is_hashed(&enc) { + std::fs::write(d.join(format!("n_{enc}")), name)?; + } let tmp = d.join(format!("b_{enc}.blob.tmp")); let mut f = std::fs::File::create(&tmp)?; io::Write::write_all(&mut f, data)?; @@ -208,7 +265,7 @@ impl Store { journal.push_str(&format!("W {enc}\n")); } for name in deletes { - journal.push_str(&format!("D {}\n", encode_name(name))); + journal.push_str(&format!("D {}\n", file_enc(name, BLOB_ENC_MAX))); } if let Some(disp) = display { std::fs::write(d.join(".display.tmp"), disp)?; @@ -289,6 +346,7 @@ type BlobCb = unsafe extern "system" fn(*const BlobInfoC, *mut c_void) -> bool; static OP_INIT: &[u8] = b"XGameSaveInitializeProviderAsync\0"; unsafe extern "system" fn init_provider_async(_t: This, user: usize, scid: *const u8, sync_on_demand: bool, block: *mut c_void) -> i32 { + first_call(4, "XGameSaveInitializeProviderAsync"); let scid = cstr(scid).unwrap_or_default(); let dir = provider_dir(&super::title().key, super::user::user().xuid, &scid); let payload = match Store::open(dir.clone()) { @@ -303,16 +361,19 @@ unsafe extern "system" fn init_provider_async(_t: This, user: usize, scid: *cons } unsafe extern "system" fn init_provider_result(_t: This, block: *mut c_void, out: *mut usize) -> i32 { + first_call(5, "XGameSaveInitializeProviderResult"); xasync::value(block, OP_INIT, out) } unsafe extern "system" fn close_provider(_t: This, p: *mut Provider) { + first_call(6, "XGameSaveCloseProvider"); if !p.is_null() { drop(Box::from_raw(p)); } } unsafe extern "system" fn delete_container(_t: This, p: *const Provider, name: *const u8) -> i32 { + first_call(10, "XGameSaveDeleteContainer"); let (Some(p), Some(n)) = (p.as_ref(), cstr(name)) else { return E_INVALIDARG }; match p.store.delete_container(&n) { Ok(_) => S_OK, @@ -338,6 +399,7 @@ unsafe fn report_container(info: &ContainerInfo, ctx: *mut c_void, cb: Container } unsafe extern "system" fn get_container_info(_t: This, p: *const Provider, name: *const u8, ctx: *mut c_void, cb: Option) -> i32 { + first_call(13, "XGameSaveGetContainerInfo"); let (Some(p), Some(n), Some(cb)) = (p.as_ref(), cstr(name), cb) else { return E_INVALIDARG }; if let Some(info) = p.store.container_info(&n) { report_container(&info, ctx, cb); @@ -346,6 +408,7 @@ unsafe extern "system" fn get_container_info(_t: This, p: *const Provider, name: } unsafe extern "system" fn enumerate_containers(_t: This, p: *const Provider, ctx: *mut c_void, cb: Option) -> i32 { + first_call(14, "XGameSaveEnumerateContainerInfo"); let (Some(p), Some(cb)) = (p.as_ref(), cb) else { return E_INVALIDARG }; for info in p.store.containers() { if !report_container(&info, ctx, cb) { @@ -356,6 +419,7 @@ unsafe extern "system" fn enumerate_containers(_t: This, p: *const Provider, ctx } unsafe extern "system" fn create_container(_t: This, p: *const Provider, name: *const u8, out: *mut *mut Container) -> i32 { + first_call(16, "XGameSaveCreateContainer"); if p.is_null() || out.is_null() { return E_INVALIDARG; } @@ -365,12 +429,14 @@ unsafe extern "system" fn create_container(_t: This, p: *const Provider, name: * } unsafe extern "system" fn close_container(_t: This, c: *mut Container) { + first_call(17, "XGameSaveCloseContainer"); if !c.is_null() { drop(Box::from_raw(c)); } } unsafe extern "system" fn enumerate_blobs(_t: This, c: *const Container, ctx: *mut c_void, cb: Option) -> i32 { + first_call(18, "XGameSaveEnumerateBlobInfo"); let (Some(c), Some(cb)) = (c.as_ref(), cb) else { return E_INVALIDARG }; for (name, size) in (*c.provider).store.blobs(&c.name) { let n = CString::new(name).unwrap_or_default(); @@ -383,6 +449,7 @@ unsafe extern "system" fn enumerate_blobs(_t: This, c: *const Container, ctx: *m } unsafe extern "system" fn read_blob_data(_t: This, c: *const Container, names: *const *const u8, count: *mut u32, size: usize, out: *mut u8) -> i32 { + first_call(20, "XGameSaveReadBlobData"); let Some(c) = c.as_ref() else { return E_INVALIDARG }; if count.is_null() { return E_INVALIDARG; @@ -423,6 +490,7 @@ unsafe extern "system" fn read_blob_data(_t: This, c: *const Container, names: * } unsafe extern "system" fn create_update(_t: This, c: *const Container, display: *const u8, out: *mut *mut Update) -> i32 { + first_call(23, "XGameSaveCreateUpdate"); if c.is_null() || out.is_null() { return E_INVALIDARG; } @@ -431,12 +499,14 @@ unsafe extern "system" fn create_update(_t: This, c: *const Container, display: } unsafe extern "system" fn close_update(_t: This, u: *mut Update) { + first_call(24, "XGameSaveCloseUpdate"); if !u.is_null() { drop(Box::from_raw(u)); } } unsafe extern "system" fn submit_blob_write(_t: This, u: *mut Update, name: *const u8, data: *const u8, len: usize) -> i32 { + first_call(25, "XGameSaveSubmitBlobWrite"); let Some(u) = u.as_mut() else { return E_INVALIDARG }; let Some(n) = cstr(name).filter(|n| valid_name(n, 256)) else { return E_GS_INVALID_CONTAINER_NAME }; if data.is_null() && len > 0 { @@ -450,6 +520,7 @@ unsafe extern "system" fn submit_blob_write(_t: This, u: *mut Update, name: *con } unsafe extern "system" fn submit_update(_t: This, u: *const Update) -> i32 { + first_call(27, "XGameSaveSubmitUpdate"); let Some(u) = u.as_ref() else { return E_INVALIDARG }; let c = &*u.container; let store = &(*c.provider).store; @@ -505,6 +576,7 @@ unsafe fn open_provider(user: usize, scid: *const u8) -> Result, i } unsafe extern "system" fn init_provider(_t: This, user: usize, scid: *const u8, _sync: bool, out: *mut *mut Provider) -> i32 { + first_call(3, "XGameSaveInitializeProvider"); if out.is_null() { return E_INVALIDARG; } @@ -518,6 +590,7 @@ unsafe extern "system" fn init_provider(_t: This, user: usize, scid: *const u8, } unsafe extern "system" fn get_quota(_t: This, p: *const Provider, out: *mut i64) -> i32 { + first_call(7, "XGameSaveGetRemainingQuota"); let Some(p) = p.as_ref() else { return E_INVALIDARG }; if out.is_null() { return E_INVALIDARG; @@ -532,15 +605,18 @@ static OP_READ: &[u8] = b"XGameSaveReadBlobDataAsync\0"; static OP_SUBMIT: &[u8] = b"XGameSaveSubmitUpdateAsync\0"; unsafe extern "system" fn get_quota_async(_t: This, p: *const Provider, block: *mut c_void) -> i32 { + first_call(8, "XGameSaveGetRemainingQuotaAsync"); let Some(p) = p.as_ref() else { return E_INVALIDARG }; xasync::run(block, OP_QUOTA, xasync::Payload::value(remaining(p))) } unsafe extern "system" fn get_quota_result(_t: This, block: *mut c_void, out: *mut i64) -> i32 { + first_call(9, "XGameSaveGetRemainingQuotaResult"); xasync::value(block, OP_QUOTA, out) } unsafe extern "system" fn delete_container_async(t: This, p: *const Provider, name: *const u8, block: *mut c_void) -> i32 { + first_call(11, "XGameSaveDeleteContainerAsync"); if p.is_null() || cstr(name).is_none() { return E_INVALIDARG; } @@ -549,10 +625,12 @@ unsafe extern "system" fn delete_container_async(t: This, p: *const Provider, na } unsafe extern "system" fn status_result(_t: This, block: *mut c_void) -> i32 { + first_call(12, "XGameSaveDeleteContainerResult or XGameSaveSubmitUpdateResult"); xasync::status(block) } unsafe extern "system" fn enumerate_containers_by_name(_t: This, p: *const Provider, prefix: *const u8, ctx: *mut c_void, cb: Option) -> i32 { + first_call(15, "XGameSaveEnumerateContainerInfoByName"); let (Some(p), Some(cb)) = (p.as_ref(), cb) else { return E_INVALIDARG }; let pre = cstr(prefix).unwrap_or_default(); for info in p.store.containers() { @@ -564,6 +642,7 @@ unsafe extern "system" fn enumerate_containers_by_name(_t: This, p: *const Provi } unsafe extern "system" fn enumerate_blobs_by_name(_t: This, c: *const Container, prefix: *const u8, ctx: *mut c_void, cb: Option) -> i32 { + first_call(19, "XGameSaveEnumerateBlobInfoByName"); let (Some(c), Some(cb)) = (c.as_ref(), cb) else { return E_INVALIDARG }; let pre = cstr(prefix).unwrap_or_default(); for (name, size) in (*c.provider).store.blobs(&c.name) { @@ -588,6 +667,7 @@ unsafe fn wanted_names(c: &Container, names: *const *const u8, count: u32) -> Ve } unsafe extern "system" fn read_blob_data_async(_t: This, c: *const Container, names: *const *const u8, count: u32, block: *mut c_void) -> i32 { + first_call(21, "XGameSaveReadBlobDataAsync"); let Some(c) = c.as_ref() else { return E_INVALIDARG }; let store = &(*c.provider).store; let wanted = wanted_names(c, names, count); @@ -614,6 +694,7 @@ unsafe extern "system" fn read_blob_data_async(_t: This, c: *const Container, na } unsafe extern "system" fn read_blob_data_result(_t: This, block: *mut c_void, size: usize, out: *mut u8, count: *mut u32) -> i32 { + first_call(22, "XGameSaveReadBlobDataResult"); if count.is_null() { return E_INVALIDARG; } @@ -639,6 +720,7 @@ unsafe extern "system" fn read_blob_data_result(_t: This, block: *mut c_void, si } unsafe extern "system" fn submit_blob_delete(_t: This, u: *mut Update, name: *const u8) -> i32 { + first_call(26, "XGameSaveSubmitBlobDelete"); let Some(u) = u.as_mut() else { return E_INVALIDARG }; let Some(n) = cstr(name).filter(|n| valid_name(n, 256)) else { return E_GS_INVALID_CONTAINER_NAME }; u.writes.retain(|w| w.0 != n); @@ -649,6 +731,7 @@ unsafe extern "system" fn submit_blob_delete(_t: This, u: *mut Update, name: *co } unsafe extern "system" fn submit_update_async(t: This, u: *const Update, block: *mut c_void) -> i32 { + first_call(28, "XGameSaveSubmitUpdateAsync"); if u.is_null() { return E_INVALIDARG; } diff --git a/crates/compat/compat-common/src/gdk/social.rs b/crates/compat/compat-common/src/gdk/social.rs index 9fb7e0c3..72c62f58 100644 --- a/crates/compat/compat-common/src/gdk/social.rs +++ b/crates/compat/compat-common/src/gdk/social.rs @@ -214,6 +214,6 @@ pub unsafe extern "system" fn register_invite(_t: super::This, queue: usize, ctx hr } -pub unsafe extern "system" fn unregister_invite(_t: super::This, token: u64, _wait: bool) -> bool { - INVITES.unregister(None, token) +pub unsafe extern "system" fn unregister_invite(_t: super::This, token: u64, wait: bool) -> bool { + INVITES.unregister(None, token, wait) } diff --git a/crates/compat/compat-common/src/gdk/store.rs b/crates/compat/compat-common/src/gdk/store.rs index 7f135bb9..4e00e46f 100644 --- a/crates/compat/compat-common/src/gdk/store.rs +++ b/crates/compat/compat-common/src/gdk/store.rs @@ -741,8 +741,8 @@ unsafe extern "system" fn register_changed(_t: This, owner: usize, queue: usize, LICENSE_CHANGED.register(owner, queue, ctx, cb, token) } -unsafe extern "system" fn unregister_changed(_t: This, owner: usize, token: u64, _wait: bool) -> bool { - LICENSE_CHANGED.unregister(Some(owner), token) +unsafe extern "system" fn unregister_changed(_t: This, owner: usize, token: u64, wait: bool) -> bool { + LICENSE_CHANGED.unregister(Some(owner), token, wait) } unsafe extern "system" fn register_lost(_t: This, license: usize, queue: usize, ctx: *mut c_void, cb: usize, token: *mut u64) -> i32 { @@ -752,8 +752,8 @@ unsafe extern "system" fn register_lost(_t: This, license: usize, queue: usize, LICENSE_LOST.register(license, queue, ctx, cb, token) } -unsafe extern "system" fn unregister_lost(_t: This, license: usize, token: u64, _wait: bool) -> bool { - LICENSE_LOST.unregister(Some(license), token) +unsafe extern "system" fn unregister_lost(_t: This, license: usize, token: u64, wait: bool) -> bool { + LICENSE_LOST.unregister(Some(license), token, wait) } unsafe extern "system" fn is_availability_purchasable(_t: This, a: *const u8) -> bool { diff --git a/crates/compat/compat-common/src/gdk/user.rs b/crates/compat/compat-common/src/gdk/user.rs index eacc0d9b..2387d2e5 100644 --- a/crates/compat/compat-common/src/gdk/user.rs +++ b/crates/compat/compat-common/src/gdk/user.rs @@ -1,6 +1,8 @@ use super::xasync::{self, Payload}; -use super::{log, next_token, put_str, put_wstr, Guid, Iface, This, E_INVALIDARG, S_OK}; +use super::{log, put_str, put_wstr, Guid, Iface, This, E_INVALIDARG, S_OK}; use core::ffi::c_void; +use super::events::Registry; +use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::OnceLock; pub const CLSID: Guid = Guid::parse("01acd177-91f9-4763-a38e-ccbb55ce32e0"); @@ -193,7 +195,7 @@ unsafe extern "system" fn get_state(_t: This, u: usize, out: *mut u32) -> i32 { if u == 0 || out.is_null() { return E_INVALIDARG; } - *out = 0; + *out = STATE.load(Ordering::Acquire); S_OK } @@ -300,18 +302,111 @@ unsafe extern "system" fn resolve_issue_async(_t: This, _u: usize, url: *const u xasync::run(block, OP_RESOLVE_ISSUE, Payload::status(S_OK)) } -pub unsafe extern "system" fn register_event(_t: This, _queue: usize, _ctx: *mut c_void, _cb: *const c_void, token: *mut u64) -> i32 { - if token.is_null() { - return E_INVALIDARG; +pub const STATE_SIGNED_IN: u32 = 0; +pub const STATE_SIGNING_OUT: u32 = 1; +pub const STATE_SIGNED_OUT: u32 = 2; +pub const EVENT_SIGNED_IN_AGAIN: u32 = 0; +pub const EVENT_SIGNING_OUT: u32 = 1; +pub const EVENT_SIGNED_OUT: u32 = 2; +pub const EVENT_GAMERTAG: u32 = 3; +pub const EVENT_GAMER_PICTURE: u32 = 4; +pub const EVENT_PRIVILEGES: u32 = 5; + +static STATE: AtomicU32 = AtomicU32::new(STATE_SIGNED_IN); +pub static CHANGE_EVENTS: Registry = Registry::new(); +pub static DEVICE_ASSOCIATION: Registry = Registry::new(); +pub static AUDIO_ENDPOINT: Registry = Registry::new(); + +pub fn state() -> u32 { + STATE.load(Ordering::Acquire) +} + +pub fn fire_change(event: u32) -> usize { + let n = CHANGE_EVENTS.len(); + CHANGE_EVENTS.fire(None, move |r| unsafe { + let cb: unsafe extern "system" fn(*mut c_void, u64, u32) = core::mem::transmute(r.cb); + cb(r.ctx as *mut c_void, LOCAL_ID, event) + }); + log("XUserChangeEvent", &format!("event {event} queued to {n} registration(s)")); + n +} + +pub fn sign_out() -> bool { + if STATE.compare_exchange(STATE_SIGNED_IN, STATE_SIGNING_OUT, Ordering::AcqRel, Ordering::Acquire).is_err() { + return false; } - *token = next_token(); - S_OK + fire_change(EVENT_SIGNING_OUT); + STATE.store(STATE_SIGNED_OUT, Ordering::Release); + fire_change(EVENT_SIGNED_OUT); + true } -pub unsafe extern "system" fn unregister_event(_t: This, _token: u64, _wait: bool) -> bool { +pub fn sign_in() -> bool { + if STATE.compare_exchange(STATE_SIGNED_OUT, STATE_SIGNED_IN, Ordering::AcqRel, Ordering::Acquire).is_err() { + return false; + } + fire_change(EVENT_SIGNED_IN_AGAIN); true } +pub fn parse_user_command(line: &str) -> Option { + match line.trim().to_ascii_lowercase().as_str() { + "signout" | "sign-out" => Some(false), + "signin" | "sign-in" => Some(true), + _ => None, + } +} + +pub fn fire_device_association(device: [u8; 32], old_user: u64, new_user: u64) -> usize { + let n = DEVICE_ASSOCIATION.len(); + DEVICE_ASSOCIATION.fire(None, move |r| unsafe { + #[repr(C)] + struct Change { + device: [u8; 32], + old_user: u64, + new_user: u64, + } + let c = Change { device, old_user, new_user }; + let cb: unsafe extern "system" fn(*mut c_void, *const Change) = core::mem::transmute(r.cb); + cb(r.ctx as *mut c_void, &c) + }); + n +} + +pub fn fire_audio_endpoint(kind: u32, old_id: &str, new_id: &str) -> usize { + let n = AUDIO_ENDPOINT.len(); + let (old_w, new_w): (Vec, Vec) = (old_id.encode_utf16().chain([0]).collect(), new_id.encode_utf16().chain([0]).collect()); + AUDIO_ENDPOINT.fire(None, move |r| unsafe { + let cb: unsafe extern "system" fn(*mut c_void, u64, u32, *const u16, *const u16) = core::mem::transmute(r.cb); + cb(r.ctx as *mut c_void, LOCAL_ID, kind, old_w.as_ptr(), new_w.as_ptr()) + }); + n +} + +pub unsafe extern "system" fn register_event(_t: This, queue: usize, ctx: *mut c_void, cb: *const c_void, token: *mut u64) -> i32 { + CHANGE_EVENTS.register(0, queue, ctx, cb as usize, token) +} + +pub unsafe extern "system" fn unregister_event(_t: This, token: u64, wait: bool) -> bool { + CHANGE_EVENTS.unregister(None, token, wait) +} + +unsafe extern "system" fn register_device_association(_t: This, queue: usize, ctx: *mut c_void, cb: *const c_void, token: *mut u64) -> i32 { + DEVICE_ASSOCIATION.register(0, queue, ctx, cb as usize, token) +} + +unsafe extern "system" fn unregister_device_association(_t: This, token: u64, wait: bool) -> bool { + DEVICE_ASSOCIATION.unregister(None, token, wait) +} + +unsafe extern "system" fn register_audio_endpoint(_t: This, queue: usize, ctx: *mut c_void, cb: *const c_void, token: *mut u64) -> i32 { + AUDIO_ENDPOINT.register(0, queue, ctx, cb as usize, token) +} + +unsafe extern "system" fn unregister_audio_endpoint(_t: This, token: u64, wait: bool) -> bool { + AUDIO_ENDPOINT.unregister(None, token, wait) +} + unsafe extern "system" fn gamer_picture_async(_t: This, u: usize, size: u32, block: *mut c_void) -> i32 { if u == 0 { return E_INVALIDARG; @@ -485,11 +580,11 @@ pub fn user_layout() -> Vec<(usize, usize)> { pub fn device_layout() -> Vec<(usize, usize)> { vec![ (3, find_for_device as usize), - (4, register_event as usize), - (5, unregister_event as usize), + (4, register_device_association as usize), + (5, unregister_device_association as usize), (6, default_audio_endpoint as usize), - (7, register_event as usize), - (8, unregister_event as usize), + (7, register_audio_endpoint as usize), + (8, unregister_audio_endpoint as usize), (9, find_controller_async as usize), (10, find_controller_result as usize), ] diff --git a/crates/compat/compat-common/src/gdk/xsign.rs b/crates/compat/compat-common/src/gdk/xsign.rs index 060f6cdd..fcf4dc27 100644 --- a/crates/compat/compat-common/src/gdk/xsign.rs +++ b/crates/compat/compat-common/src/gdk/xsign.rs @@ -115,6 +115,7 @@ pub fn sign(method: &str, url: &str, authorization: &str, body: &[u8]) -> Result sign_at(filetime_now(), method, url, authorization, body) } + #[cfg(test)] mod tests { use super::*; diff --git a/crates/compat/compat-common/src/gdk_store.rs b/crates/compat/compat-common/src/gdk_store.rs index a9bc0774..1ceb66b7 100644 --- a/crates/compat/compat-common/src/gdk_store.rs +++ b/crates/compat/compat-common/src/gdk_store.rs @@ -1,17 +1,3 @@ -//! Local, empty Microsoft Store (`XStore*`) for the title's local user. -//! -//! Why: once a local user exists (gdk_user), the title's privilege check runs -//! `FOnlineAsyncTaskGDKGetUserPrivilege::CheckForGDKPackageUpdate`, which calls -//! `XStoreCreateContext(user)`. Microsoft's PC runtime rejects the local user handle -//! ("Handle: does not exist") and the following `XStoreQueryGameAndDlcPackageUpdatesAsync` -//! faults inside the runtime on the null context. -//! -//! Model: a store that knows nothing. No package updates, no associated / entitled / -//! purchasable products, zero consumable balance, and purchase / redeem UI that reports -//! "cancelled". This grants the user **no** entitlements; it only lets the title's store -//! queries complete. Signatures are the public GDK ones (XStore.h). -//! -//! Specific to the same Fortnite build as gdk_user (wrappers located by symbol table). use core::ffi::c_void; use crate::gdk_user::{start_async, write_jump, xasync_complete, xasync_get_status, ProviderData, E_PENDING}; @@ -20,8 +6,8 @@ const S_OK: i32 = 0; const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; const E_ABORT: i32 = 0x8000_4004u32 as i32; -static CONTEXT_ANCHOR: u64 = 0x5853_544F_5245_4354; // store context handle -static QUERY_ANCHOR: u64 = 0x5853_544F_5245_5152; // empty product-query handle +static CONTEXT_ANCHOR: u64 = 0x5853_544F_5245_4354; +static QUERY_ANCHOR: u64 = 0x5853_544F_5245_5152; fn ctx() -> usize { &CONTEXT_ANCHOR as *const u64 as usize } fn query() -> usize { &QUERY_ANCHOR as *const u64 as usize } @@ -88,7 +74,7 @@ unsafe extern "system" fn products_result(block: *mut c_void, out: *mut usize) - hr } unsafe extern "system" fn enumerate(_q: usize, _ctx: *mut c_void, _cb: *const c_void) -> i32 { - S_OK // no products: the callback is never invoked + S_OK } unsafe extern "system" fn has_more_pages(_q: usize) -> bool { false @@ -101,7 +87,7 @@ unsafe extern "system" fn consumable_async(_ctx: usize, _id: *const u8, block: * unsafe extern "system" fn consumable_result(block: *mut c_void, out: *mut u32) -> i32 { let hr = xasync_get_status(block); if hr >= 0 && !out.is_null() { - *out = 0; // XStoreConsumableResult { quantity } + *out = 0; } hr } @@ -118,37 +104,61 @@ unsafe extern "system" fn ui_result(block: *mut c_void) -> i32 { xasync_get_status(block) } -/// Called by gdk_user::install after the build check. -pub(crate) unsafe fn install(base: *mut u8) { - let table: [(&str, usize, usize); 22] = [ - ("XStoreCloseContextHandle", 0x1dca7e4, close_handle as usize), - ("XStoreCloseProductsQueryHandle", 0x1dca83c, close_handle as usize), - ("XStoreCreateContext", 0x1dca898, create_context as usize), - ("XStoreEnumerateProductsQuery", 0x1dca910, enumerate as usize), - ("XStoreProductsQueryHasMorePages", 0x1dca998, has_more_pages as usize), - ("XStoreProductsQueryNextPageAsync", 0x1dca9fc, next_page_async as usize), - ("XStoreProductsQueryNextPageResult", 0x1dcaa70, products_result as usize), - ("XStoreQueryAssociatedProductsAsync", 0x1dcaae4, products_async as usize), - ("XStoreQueryAssociatedProductsResult", 0x1dcab78, products_result as usize), - ("XStoreQueryConsumableBalanceRemainingAsync", 0x1dcabec, consumable_async as usize), - ("XStoreQueryConsumableBalanceRemainingResult", 0x1dcac70, consumable_result as usize), - ("XStoreQueryEntitledProductsAsync", 0x1dcace4, products_async as usize), - ("XStoreQueryEntitledProductsResult", 0x1dcad78, products_result as usize), - ("XStoreQueryGameAndDlcPackageUpdatesAsync", 0x1dcadec, updates_async as usize), - ("XStoreQueryGameAndDlcPackageUpdatesResult", 0x1dcae60, updates_result as usize), - ("XStoreQueryGameAndDlcPackageUpdatesResultCount", 0x1dcaee4, updates_count as usize), - ("XStoreQueryProductsAsync", 0x1dcaf58, products_by_id_async as usize), - ("XStoreQueryProductsResult", 0x1dcb014, products_result as usize), - ("XStoreShowPurchaseUIAsync", 0x1dcb088, purchase_ui_async as usize), - ("XStoreShowPurchaseUIResult", 0x1dcb12c, ui_result as usize), - ("XStoreShowRedeemTokenUIAsync", 0x1dcb190, redeem_ui_async as usize), - ("XStoreShowRedeemTokenUIResult", 0x1dcb240, ui_result as usize), +pub(crate) unsafe fn install(base: *mut u8, rvas: &[usize]) { + let table: [(&str, usize); 22] = [ + ("XStoreCloseContextHandle", close_handle as usize), + ("XStoreCloseProductsQueryHandle", close_handle as usize), + ("XStoreCreateContext", create_context as usize), + ("XStoreEnumerateProductsQuery", enumerate as usize), + ("XStoreProductsQueryHasMorePages", has_more_pages as usize), + ("XStoreProductsQueryNextPageAsync", next_page_async as usize), + ("XStoreProductsQueryNextPageResult", products_result as usize), + ("XStoreQueryAssociatedProductsAsync", products_async as usize), + ("XStoreQueryAssociatedProductsResult", products_result as usize), + ("XStoreQueryConsumableBalanceRemainingAsync", consumable_async as usize), + ("XStoreQueryConsumableBalanceRemainingResult", consumable_result as usize), + ("XStoreQueryEntitledProductsAsync", products_async as usize), + ("XStoreQueryEntitledProductsResult", products_result as usize), + ("XStoreQueryGameAndDlcPackageUpdatesAsync", updates_async as usize), + ("XStoreQueryGameAndDlcPackageUpdatesResult", updates_result as usize), + ("XStoreQueryGameAndDlcPackageUpdatesResultCount", updates_count as usize), + ("XStoreQueryProductsAsync", products_by_id_async as usize), + ("XStoreQueryProductsResult", products_result as usize), + ("XStoreShowPurchaseUIAsync", purchase_ui_async as usize), + ("XStoreShowPurchaseUIResult", ui_result as usize), + ("XStoreShowRedeemTokenUIAsync", redeem_ui_async as usize), + ("XStoreShowRedeemTokenUIResult", ui_result as usize), ]; let mut ok = 0; - for (_, rva, target) in table { - if write_jump(base.add(rva), target) { + for ((_, target), rva) in table.iter().zip(rvas) { + if write_jump(base.add(*rva), *target) { ok += 1; } } crate::record_raw("gdk_store", "install", &format!("local empty store installed ({ok}/22 XStore wrappers redirected)")); } + +pub const XSTORE_NAMES: [&str; 22] = [ + "XStoreCloseContextHandle", + "XStoreCloseProductsQueryHandle", + "XStoreCreateContext", + "XStoreEnumerateProductsQuery", + "XStoreProductsQueryHasMorePages", + "XStoreProductsQueryNextPageAsync", + "XStoreProductsQueryNextPageResult", + "XStoreQueryAssociatedProductsAsync", + "XStoreQueryAssociatedProductsResult", + "XStoreQueryConsumableBalanceRemainingAsync", + "XStoreQueryConsumableBalanceRemainingResult", + "XStoreQueryEntitledProductsAsync", + "XStoreQueryEntitledProductsResult", + "XStoreQueryGameAndDlcPackageUpdatesAsync", + "XStoreQueryGameAndDlcPackageUpdatesResult", + "XStoreQueryGameAndDlcPackageUpdatesResultCount", + "XStoreQueryProductsAsync", + "XStoreQueryProductsResult", + "XStoreShowPurchaseUIAsync", + "XStoreShowPurchaseUIResult", + "XStoreShowRedeemTokenUIAsync", + "XStoreShowRedeemTokenUIResult", +]; diff --git a/crates/compat/compat-common/src/gdk_user.rs b/crates/compat/compat-common/src/gdk_user.rs index 0c3d14bb..d28e770a 100644 --- a/crates/compat/compat-common/src/gdk_user.rs +++ b/crates/compat/compat-common/src/gdk_user.rs @@ -1,25 +1,3 @@ -//! Local Xbox user (`XUser*`) for the title. -//! -//! Finding (2026-11-17): the title boots against Microsoft's *PC* `xgameruntime.dll` from -//! System32. For this unpackaged, unregistered title that runtime has no user, so the -//! title's login state machine aborts at its first step (`ConsolePrivileges`, "User -1 is -//! not valid"). A console always has a signed-in user; this module provides one. -//! -//! Model: exactly one local, offline user. Its identity is configuration, not an Xbox Live -//! account: `gamertag=`, `xuid=` and `xbl_token=` in `tombox.cfg` next to the title (defaults -//! below). Nothing here contacts Microsoft or Epic; the token is a placeholder string that -//! the title forwards to whatever backend the network policy routes it to (see -//! `net_guard`), i.e. the project owner's own server. -//! -//! Mechanism — **specific to this Fortnite build** (2.0.1461.7919, PE timestamp checked): -//! the statically linked GDK wrappers `XUser*` in the EXE (located by the build's symbol -//! table) are redirected to the implementations below. Signatures are the public GDK ones -//! (XUser.h / XAsync.h). Asynchronous calls are completed through the title's own -//! `XAsyncBegin/Schedule/Complete/GetResult` wrappers, which are left untouched. -//! -//! Not modelled: multiple users, guests, sign-out, change-event delivery (registrations are -//! accepted but no event is ever fired), privilege denial (every privilege is granted), -//! real token signing (signature is empty). use core::ffi::c_void; use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; @@ -36,33 +14,24 @@ const S_OK: i32 = 0; pub(crate) const E_PENDING: i32 = 0x8000_000Au32 as i32; const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; const E_NOT_SUFFICIENT_BUFFER: i32 = 0x8007_007Au32 as i32; -const E_NOT_FOUND: i32 = 0x8007_0490u32 as i32; // HRESULT_FROM_WIN32(ERROR_NOT_FOUND); the exact GDK "user not found" code is not verified +const E_NOT_FOUND: i32 = 0x8007_0490u32 as i32; -/// PE TimeDateStamp of FortniteClient-XSX-Shipping.exe 2.0.1461.7919. -const BUILD_TIMESTAMP: u32 = 0x5f9b_76c4; - -// RVAs from the build's symbol table (`*-Symbols.bin`). -const RVA_XASYNC_BEGIN: usize = 0x1dc87c8; -const RVA_XASYNC_COMPLETE: usize = 0x1dc88b4; -const RVA_XASYNC_GET_RESULT: usize = 0x1dc8928; -const RVA_XASYNC_GET_RESULT_SIZE: usize = 0x1dc89c4; -const RVA_XASYNC_GET_STATUS: usize = 0x1dc8a34; -const RVA_XASYNC_SCHEDULE: usize = 0x1dc8aa4; +pub const XASYNC_NAMES: [&str; 6] = ["XAsyncBegin", "XAsyncComplete", "XAsyncGetResult", "XAsyncGetResultSize", "XAsyncGetStatus", "XAsyncSchedule"]; +static XASYNC: [AtomicUsize; 6] = [const { AtomicUsize::new(0) }; 6]; static EXE: AtomicUsize = AtomicUsize::new(0); struct User { gamertag: String, xuid: u64, - token: Vec, // NUL-terminated UTF-8 - token16: Vec, // NUL-terminated UTF-16 + token: Vec, + token16: Vec, } static USER: OnceLock = OnceLock::new(); fn user() -> &'static User { USER.get().expect("gdk_user installed") } -/// The one user handle handed to the title (an address inside this module; never freed). fn handle() -> usize { crate::gdk::user::handle() } @@ -76,7 +45,6 @@ pub(crate) fn log(func: &str, detail: &str) { } } -// ---- XAsync plumbing (title's own wrappers) ------------------------------------------------------- #[repr(C)] pub(crate) struct ProviderData { @@ -89,32 +57,31 @@ type Provider = unsafe extern "system" fn(op: u32, data: *const ProviderData) -> unsafe fn xasync_begin(block: *mut c_void, context: *mut c_void, identity: usize, name: &'static [u8], provider: Provider) -> i32 { let f: unsafe extern "system" fn(*mut c_void, *mut c_void, usize, *const u8, Provider) -> i32 = - core::mem::transmute(EXE.load(Ordering::Relaxed) + RVA_XASYNC_BEGIN); + core::mem::transmute(XASYNC[0].load(Ordering::Relaxed)); f(block, context, identity, name.as_ptr(), provider) } unsafe fn xasync_schedule(block: *mut c_void) -> i32 { - let f: unsafe extern "system" fn(*mut c_void, u32) -> i32 = core::mem::transmute(EXE.load(Ordering::Relaxed) + RVA_XASYNC_SCHEDULE); + let f: unsafe extern "system" fn(*mut c_void, u32) -> i32 = core::mem::transmute(XASYNC[5].load(Ordering::Relaxed)); f(block, 0) } pub(crate) unsafe fn xasync_complete(block: *mut c_void, hr: i32, size: usize) { - let f: unsafe extern "system" fn(*mut c_void, i32, usize) = core::mem::transmute(EXE.load(Ordering::Relaxed) + RVA_XASYNC_COMPLETE); + let f: unsafe extern "system" fn(*mut c_void, i32, usize) = core::mem::transmute(XASYNC[1].load(Ordering::Relaxed)); f(block, hr, size) } unsafe fn xasync_get_result(block: *mut c_void, identity: usize, size: usize, buf: *mut u8, used: *mut usize) -> i32 { let f: unsafe extern "system" fn(*mut c_void, usize, usize, *mut u8, *mut usize) -> i32 = - core::mem::transmute(EXE.load(Ordering::Relaxed) + RVA_XASYNC_GET_RESULT); + core::mem::transmute(XASYNC[2].load(Ordering::Relaxed)); f(block, identity, size, buf, used) } unsafe fn xasync_get_result_size(block: *mut c_void, size: *mut usize) -> i32 { - let f: unsafe extern "system" fn(*mut c_void, *mut usize) -> i32 = core::mem::transmute(EXE.load(Ordering::Relaxed) + RVA_XASYNC_GET_RESULT_SIZE); + let f: unsafe extern "system" fn(*mut c_void, *mut usize) -> i32 = core::mem::transmute(XASYNC[3].load(Ordering::Relaxed)); f(block, size) } pub(crate) unsafe fn xasync_get_status(block: *mut c_void) -> i32 { - let f: unsafe extern "system" fn(*mut c_void, bool) -> i32 = core::mem::transmute(EXE.load(Ordering::Relaxed) + RVA_XASYNC_GET_STATUS); + let f: unsafe extern "system" fn(*mut c_void, bool) -> i32 = core::mem::transmute(XASYNC[4].load(Ordering::Relaxed)); f(block, false) } -/// Start an async operation whose result is produced by `provider` on the block's queue. pub(crate) unsafe fn start_async(block: *mut c_void, identity: usize, name: &'static [u8], provider: Provider) -> i32 { if block.is_null() { return E_INVALIDARG; @@ -126,7 +93,6 @@ pub(crate) unsafe fn start_async(block: *mut c_void, identity: usize, name: &'st xasync_schedule(block) } -// XAsyncOp: 0 Begin, 1 DoWork, 2 GetResult, 3 Cancel, 4 Cleanup. unsafe extern "system" fn add_provider(op: u32, data: *const ProviderData) -> i32 { match op { @@ -153,8 +119,6 @@ unsafe extern "system" fn no_result_provider(op: u32, data: *const ProviderData) S_OK } -/// Result layout: { size_t tokenSize; size_t signatureSize; char* token; char* signature; } -/// followed by the token and an empty signature (both NUL-terminated). fn token_blob_size(wide: bool) -> usize { let u = user(); 32 + if wide { (u.token16.len() + 1) * 2 } else { u.token.len() + 1 } @@ -175,7 +139,7 @@ unsafe fn write_token_blob(buf: *mut u8, wide: bool) { } let sig = tok.add(tok_bytes); core::ptr::write_bytes(sig, 0, if wide { 2 } else { 1 }); - core::ptr::write_unaligned(buf as *mut usize, count); // includes the terminator + core::ptr::write_unaligned(buf as *mut usize, count); core::ptr::write_unaligned(buf.add(8) as *mut usize, 1); core::ptr::write_unaligned(buf.add(16) as *mut usize, tok as usize); core::ptr::write_unaligned(buf.add(24) as *mut usize, sig as usize); @@ -204,7 +168,6 @@ unsafe fn token_provider_impl(op: u32, data: *const ProviderData, wide: bool) -> } } -// ---- XUser implementations (public GDK signatures) ------------------------------------------------ unsafe extern "system" fn x_add_async(options: u32, block: *mut c_void) -> i32 { let hr = start_async(block, x_add_async as usize, b"XUserAddAsync\0", add_provider); @@ -227,7 +190,7 @@ unsafe extern "system" fn x_check_privilege(u: usize, options: u32, privilege: u } *has = true; if !reason.is_null() { - *reason = 0; // XUserPrivilegeDenyReason::None + *reason = 0; } log("XUserCheckPrivilege", &format!("privilege={privilege} options={options:#x} -> granted (local user policy)")); S_OK @@ -251,7 +214,7 @@ unsafe extern "system" fn x_find_for_device(_device: *const u8, out: *mut usize) if out.is_null() { return E_INVALIDARG; } - *out = handle(); // every input device belongs to the one local user + *out = handle(); S_OK } @@ -283,7 +246,6 @@ unsafe extern "system" fn x_get_gamertag(u: usize, component: u32, size: usize, if u == 0 { return E_INVALIDARG; } - // XUserGamertagComponent: 0 Classic, 1 Modern, 2 ModernSuffix, 3 UniqueModern. let s: &str = if component == 2 { "" } else { &user().gamertag }; let need = s.len() + 1; if !used.is_null() { @@ -325,7 +287,7 @@ unsafe extern "system" fn x_get_state(u: usize, out: *mut u32) -> i32 { if u == 0 || out.is_null() { return E_INVALIDARG; } - *out = 0; // XUserState::SignedIn + *out = 0; S_OK } @@ -412,10 +374,9 @@ unsafe extern "system" fn x_resolve_result(block: *mut c_void) -> i32 { xasync_get_status(block) } -// ---- installation ----------------------------------------------------------------------------------- pub(crate) unsafe fn write_jump(p: *mut u8, target: usize) -> bool { - let mut code = [0u8; 12]; // mov rax, imm64 ; jmp rax + let mut code = [0u8; 12]; code[0] = 0x48; code[1] = 0xB8; code[2..10].copy_from_slice(&(target as u64).to_le_bytes()); @@ -432,7 +393,6 @@ pub(crate) unsafe fn write_jump(p: *mut u8, target: usize) -> bool { true } -/// Install the local user if this process is the known Fortnite build. Called once. pub fn install() { crate::gdk::install(); unsafe { @@ -440,13 +400,13 @@ pub fn install() { if base.is_null() { return; } - let pe = core::ptr::read_unaligned(base.add(0x3c) as *const u32) as usize; - let stamp = core::ptr::read_unaligned(base.add(pe + 8) as *const u32); - if stamp != BUILD_TIMESTAMP { - crate::record_raw("gdk_user", "install", &format!( - "host EXE timestamp {stamp:#x} is not the known Fortnite build - local XUser layer NOT installed")); - return; - } + let o = match layout(base) { + Ok(o) => o, + Err(e) => { + crate::record_raw("gdk_user", "install", &format!("{e} - local XUser layer NOT installed")); + return; + } + }; if crate::cfg("local_user").as_deref() == Some("0") { crate::record_raw("gdk_user", "install", "local_user=0 in tombox.cfg - local XUser layer NOT installed"); return; @@ -459,45 +419,147 @@ pub fn install() { let t16: Vec = token.encode_utf16().chain(Some(0)).collect(); let _ = USER.set(User { gamertag: gamertag.clone(), xuid, token: t8, token16: t16 }); EXE.store(base as usize, Ordering::SeqCst); + for (slot, rva) in XASYNC.iter().zip(&o.xasync) { + slot.store(base as usize + rva, Ordering::SeqCst); + } - let table: [(&str, usize, usize); 28] = [ - ("XUserAddAsync", 0x1dcba30, x_add_async as usize), - ("XUserAddResult", 0x1dcbaa0, x_add_result as usize), - ("XUserCheckPrivilege", 0x1dcbb14, x_check_privilege as usize), - ("XUserCloseHandle", 0x1dcbbb8, x_close_handle as usize), - ("XUserCompare", 0x1dcbc10, x_compare as usize), - ("XUserDuplicateHandle", 0x1dcbc84, x_duplicate_handle as usize), - ("XUserFindForDevice", 0x1dcbcf8, x_find_for_device as usize), - ("XUserFindUserById", 0x1dcbd6c, x_find_by_id as usize), - ("XUserFindUserByLocalId", 0x1dcbde4, x_find_by_local_id as usize), - ("XUserGetGamertag", 0x1dcbf00, x_get_gamertag as usize), - ("XUserGetId", 0x1dcbfa0, x_get_id as usize), - ("XUserGetLocalId", 0x1dcc014, x_get_local_id as usize), - ("XUserGetMaxUsers", 0x1dcc088, x_get_max_users as usize), - ("XUserGetState", 0x1dcc0ec, x_get_state as usize), - ("XUserGetTokenAndSignatureAsync", 0x1dcc160, x_token_async as usize), - ("XUserGetTokenAndSignatureResult", 0x1dcc238, x_token_result as usize), - ("XUserGetTokenAndSignatureResultSize", 0x1dcc2dc, x_token_result_size as usize), - ("XUserGetTokenAndSignatureUtf16Async", 0x1dcc350, x_token16_async as usize), - ("XUserGetTokenAndSignatureUtf16Result", 0x1dcc428, x_token16_result as usize), - ("XUserGetTokenAndSignatureUtf16ResultSize", 0x1dcc4cc, x_token_result_size as usize), - ("XUserRegisterForChangeEvent", 0x1dcc540, x_register as usize), - ("XUserRegisterForDeviceAssociationChanged", 0x1dcc5dc, x_register as usize), - ("XUserResolveIssueWithUiAsync", 0x1dcc674, x_resolve_issue_async as usize), - ("XUserResolveIssueWithUiResult", 0x1dcc6f8, x_resolve_result as usize), - ("XUserResolvePrivilegeWithUiAsync", 0x1dcc75c, x_resolve_privilege_async as usize), - ("XUserResolvePrivilegeWithUiResult", 0x1dcc7f4, x_resolve_result as usize), - ("XUserUnregisterForChangeEvent", 0x1dcc858, x_unregister as usize), - ("XUserUnregisterForDeviceAssociationChanged", 0x1dcc8d4, x_unregister as usize), + let table: [(&str, usize); 28] = [ + ("XUserAddAsync", x_add_async as usize), + ("XUserAddResult", x_add_result as usize), + ("XUserCheckPrivilege", x_check_privilege as usize), + ("XUserCloseHandle", x_close_handle as usize), + ("XUserCompare", x_compare as usize), + ("XUserDuplicateHandle", x_duplicate_handle as usize), + ("XUserFindForDevice", x_find_for_device as usize), + ("XUserFindUserById", x_find_by_id as usize), + ("XUserFindUserByLocalId", x_find_by_local_id as usize), + ("XUserGetGamertag", x_get_gamertag as usize), + ("XUserGetId", x_get_id as usize), + ("XUserGetLocalId", x_get_local_id as usize), + ("XUserGetMaxUsers", x_get_max_users as usize), + ("XUserGetState", x_get_state as usize), + ("XUserGetTokenAndSignatureAsync", x_token_async as usize), + ("XUserGetTokenAndSignatureResult", x_token_result as usize), + ("XUserGetTokenAndSignatureResultSize", x_token_result_size as usize), + ("XUserGetTokenAndSignatureUtf16Async", x_token16_async as usize), + ("XUserGetTokenAndSignatureUtf16Result", x_token16_result as usize), + ("XUserGetTokenAndSignatureUtf16ResultSize", x_token_result_size as usize), + ("XUserRegisterForChangeEvent", x_register as usize), + ("XUserRegisterForDeviceAssociationChanged", x_register as usize), + ("XUserResolveIssueWithUiAsync", x_resolve_issue_async as usize), + ("XUserResolveIssueWithUiResult", x_resolve_result as usize), + ("XUserResolvePrivilegeWithUiAsync", x_resolve_privilege_async as usize), + ("XUserResolvePrivilegeWithUiResult", x_resolve_result as usize), + ("XUserUnregisterForChangeEvent", x_unregister as usize), + ("XUserUnregisterForDeviceAssociationChanged", x_unregister as usize), ]; let mut ok = 0; let mut failed = Vec::new(); - for (name, rva, target) in table { - if write_jump(base.add(rva), target) { ok += 1 } else { failed.push(name) } + for ((name, target), rva) in table.iter().zip(&o.xuser) { + if write_jump(base.add(*rva), *target) { ok += 1 } else { failed.push(*name) } } - crate::gdk_store::install(base); + crate::gdk_store::install(base, &o.xstore); crate::record_raw("gdk_user", "install", &format!( - "local offline user installed: gamertag='{gamertag}' xuid={xuid} ({ok}/28 XUser wrappers redirected{})", + "local offline user installed from {}: gamertag='{gamertag}' xuid={xuid} ({ok}/28 XUser wrappers redirected{})", o.source, if failed.is_empty() { String::new() } else { format!("; FAILED: {}", failed.join(", ")) })); } } + +pub const XUSER_NAMES: [&str; 28] = [ + "XUserAddAsync", "XUserAddResult", "XUserCheckPrivilege", "XUserCloseHandle", "XUserCompare", "XUserDuplicateHandle", "XUserFindForDevice", + "XUserFindUserById", "XUserFindUserByLocalId", "XUserGetGamertag", "XUserGetId", "XUserGetLocalId", "XUserGetMaxUsers", "XUserGetState", + "XUserGetTokenAndSignatureAsync", "XUserGetTokenAndSignatureResult", "XUserGetTokenAndSignatureResultSize", "XUserGetTokenAndSignatureUtf16Async", + "XUserGetTokenAndSignatureUtf16Result", "XUserGetTokenAndSignatureUtf16ResultSize", "XUserRegisterForChangeEvent", "XUserRegisterForDeviceAssociationChanged", + "XUserResolveIssueWithUiAsync", "XUserResolveIssueWithUiResult", "XUserResolvePrivilegeWithUiAsync", "XUserResolvePrivilegeWithUiResult", + "XUserUnregisterForChangeEvent", "XUserUnregisterForDeviceAssociationChanged", +]; + +#[derive(Debug, PartialEq)] +pub struct Layout { + pub source: String, + pub xasync: Vec, + pub xuser: Vec, + pub xstore: Vec, +} + +pub fn layout_from(o: &crate::title_offsets::Offsets, stamp: u32) -> Result { + if o.pe_timestamp.is_none() { + return Err(format!("{} has no pe_timestamp", o.source)); + } + if !o.matches_image(stamp) { + return Err(format!("host EXE timestamp {stamp:#x} does not match {}", o.source)); + } + Ok(Layout { source: o.source.clone(), xasync: o.require(&XASYNC_NAMES)?, xuser: o.require(&XUSER_NAMES)?, xstore: o.require(&crate::gdk_store::XSTORE_NAMES)? }) +} + +pub const JUMP_BYTES: usize = 12; + +pub fn layout_from_symbols(t: &crate::title_symbols::Table) -> Result { + let rvas = |names: &[&str], patched: bool| -> Result, String> { + let syms = t.require(names)?; + if patched { + if let Some((n, s)) = names.iter().zip(&syms).find(|(_, s)| s.size < JUMP_BYTES) { + return Err(format!("{n} is only {} bytes, too short for a {JUMP_BYTES}-byte jump", s.size)); + } + } + Ok(syms.iter().map(|s| s.rva).collect()) + }; + Ok(Layout { source: t.source.clone(), xasync: rvas(&XASYNC_NAMES, false)?, xuser: rvas(&XUSER_NAMES, true)?, xstore: rvas(&crate::gdk_store::XSTORE_NAMES, true)? }) +} + +unsafe fn layout(base: *mut u8) -> Result { + let se = match crate::title_symbols::for_this_title().and_then(layout_from_symbols) { + Ok(l) => return Ok(l), + Err(e) => e, + }; + let o = crate::title_offsets::for_this_title().ok_or_else(|| format!("symbols: {se}; offsets file: {}", crate::title_offsets::status_for_this_title()))?; + layout_from(o, crate::title_offsets::image_timestamp(base)).map_err(|je| format!("symbols: {se}; offsets file: {je}")) +} + +#[cfg(test)] +mod layout_tests { + use super::*; + + fn file(stamp: Option<&str>, skip: Option<&str>) -> String { + let names = XASYNC_NAMES.iter().chain(XUSER_NAMES.iter()).chain(crate::gdk_store::XSTORE_NAMES.iter()); + let vals: Vec = names.enumerate().filter(|(_, n)| Some(**n) != skip).map(|(i, n)| format!("\"{n}\":{}", 0x100 + i * 0x10)).collect(); + let ts = stamp.map(|t| format!(",\"pe_timestamp\":\"{t}\"")).unwrap_or_default(); + format!("{{\"exe\":\"T.exe\"{ts},\"values\":{{{}}}}}", vals.join(",")) + } + + #[test] + fn every_patched_function_comes_from_the_offsets_file() { + let o = crate::title_offsets::parse(&file(Some("0x1234"), None), "t").unwrap(); + let l = layout_from(&o, 0x1234).unwrap(); + assert_eq!((l.xasync.len(), l.xuser.len(), l.xstore.len()), (6, 28, 22)); + assert_eq!(l.xasync[0], 0x100); + assert_eq!(l.xuser[0], 0x100 + 6 * 0x10); + assert_eq!(l.xstore[21], 0x100 + 55 * 0x10); + } + + #[test] + fn the_title_symbols_supply_every_address_when_present() { + let names: Vec<&str> = XASYNC_NAMES.iter().chain(XUSER_NAMES.iter()).chain(crate::gdk_store::XSTORE_NAMES.iter()).copied().collect(); + let syms: Vec<(&str, u32, u32)> = names.iter().enumerate().map(|(i, n)| (*n, 0x1000 + i as u32 * 0x80, 0x40)).collect(); + let f = crate::title_symbols::build_for_test("T", &syms); + let t = crate::title_symbols::parse_bytes(&f, &names, "t").unwrap(); + let l = layout_from_symbols(&t).unwrap(); + assert_eq!((l.xasync[0], l.xuser[0], l.xstore[21]), (0x1000, 0x1000 + 6 * 0x80, 0x1000 + 55 * 0x80)); + let mut short = syms.clone(); + short[10].2 = 8; + let t = crate::title_symbols::parse_bytes(&crate::title_symbols::build_for_test("T", &short), &names, "t").unwrap(); + assert!(layout_from_symbols(&t).unwrap_err().contains("too short")); + let t = crate::title_symbols::parse_bytes(&crate::title_symbols::build_for_test("T", &syms[1..]), &names, "t").unwrap(); + assert!(layout_from_symbols(&t).unwrap_err().contains("XAsyncBegin")); + } + + #[test] + fn a_wrong_build_a_missing_stamp_or_a_missing_name_leaves_the_layer_off() { + let o = crate::title_offsets::parse(&file(Some("0x1234"), None), "t").unwrap(); + assert!(layout_from(&o, 0x9999).unwrap_err().contains("does not match")); + let o = crate::title_offsets::parse(&file(None, None), "t").unwrap(); + assert!(layout_from(&o, 0x1234).unwrap_err().contains("pe_timestamp")); + let o = crate::title_offsets::parse(&file(Some("0x1234"), Some("XUserGetId")), "t").unwrap(); + assert!(layout_from(&o, 0x1234).unwrap_err().contains("XUserGetId")); + } +} diff --git a/crates/compat/compat-common/src/lib.rs b/crates/compat/compat-common/src/lib.rs index 4820c47b..8f6eb815 100644 --- a/crates/compat/compat-common/src/lib.rs +++ b/crates/compat/compat-common/src/lib.rs @@ -24,12 +24,15 @@ fn log_path() -> &'static std::path::PathBuf { /// Record a call from `module` (e.g. "xmem") to `func` with a short `detail`. pub mod net_guard; +pub mod netview; pub mod locale; +pub mod physical_pages; pub mod gdk_user; pub mod gdk_store; pub mod gdk; pub mod gamepad; pub mod host_input; +pub mod pad_host; pub mod gameinput_ext; pub mod online; pub mod os_host; @@ -38,8 +41,11 @@ pub mod live; pub mod title_os; pub mod kmd_bridge; pub mod private_heap; +pub mod partition_heap; pub mod headless; pub mod iat; +pub mod title_offsets; +pub mod title_symbols; #[global_allocator] static TB_ALLOC: private_heap::PrivateHeap = private_heap::PrivateHeap; diff --git a/crates/compat/compat-common/src/net_guard.rs b/crates/compat/compat-common/src/net_guard.rs index b3ef710e..26c5fef2 100644 --- a/crates/compat/compat-common/src/net_guard.rs +++ b/crates/compat/compat-common/src/net_guard.rs @@ -32,6 +32,7 @@ use core::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; mod ext; +mod ioctl; extern "system" { fn GetModuleHandleA(name: *const u8) -> *mut c_void; @@ -220,7 +221,14 @@ const H_WINHTTPQUERYAVAIL: usize = 19; const H_WINHTTPREADDATA: usize = 20; const H_WINHTTPQUERYHEADERS: usize = 21; const H_WINHTTPWSUPGRADE: usize = 22; -static ORIG: [AtomicUsize; 23] = [const { AtomicUsize::new(0) }; 23]; +const H_BIND: usize = 23; +const H_LISTEN: usize = 24; +const H_ACCEPT: usize = 25; +const H_WSAACCEPT: usize = 26; +const H_CLOSESOCKET: usize = 27; +const H_WSAIOCTL: usize = 28; +const H_SETSOCKOPT: usize = 29; +static ORIG: [AtomicUsize; 30] = [const { AtomicUsize::new(0) }; 30]; static GAME_CB: Mutex> = Mutex::new(Vec::new()); static PARENT: Mutex> = Mutex::new(Vec::new()); @@ -549,7 +557,239 @@ unsafe extern "system" fn h_connect(s: usize, name: *const u8, len: i32) -> i32 deny_dest("connect", name, len); return -1; } - orig!(H_CONNECT, fn(usize, *const u8, i32) -> i32)(s, name, len) + let r = orig!(H_CONNECT, fn(usize, *const u8, i32) -> i32)(s, name, len); + note_socket(s, r, name, len); + r +} + +unsafe fn note_socket(s: usize, r: i32, remote: *const u8, len: i32) { + let e = GetLastError(); + if r >= 0 { + crate::netview::sockets::report_socket(s, remote, len); + } else if e == WSAEWOULDBLOCK { + crate::netview::sockets::report_event(s, crate::netview::sockets::Event::Connecting, remote, len); + } + SetLastError(e); +} + +unsafe fn note_event(s: usize, event: crate::netview::sockets::Event, remote: *const u8, len: i32) { + let e = GetLastError(); + crate::netview::sockets::report_event(s, event, remote, len); + SetLastError(e); +} + +unsafe extern "system" fn h_bind(s: usize, name: *const u8, len: i32) -> i32 { + let r = orig!(H_BIND, fn(usize, *const u8, i32) -> i32)(s, name, len); + if r == 0 { + note_event(s, crate::netview::sockets::Event::Bound, core::ptr::null(), 0); + } + r +} + +unsafe extern "system" fn h_listen(s: usize, backlog: i32) -> i32 { + let r = orig!(H_LISTEN, fn(usize, i32) -> i32)(s, backlog); + if r == 0 { + note_event(s, crate::netview::sockets::Event::Listening, core::ptr::null(), 0); + } + r +} + +unsafe fn accepted_len(len: *const i32) -> i32 { + if len.is_null() { 0 } else { *len } +} + +unsafe extern "system" fn h_accept(s: usize, addr: *mut u8, len: *mut i32) -> usize { + let r = orig!(H_ACCEPT, fn(usize, *mut u8, *mut i32) -> usize)(s, addr, len); + if r != usize::MAX { + note_event(r, crate::netview::sockets::Event::Accepted, addr, accepted_len(len)); + } + r +} + +unsafe extern "system" fn h_wsaaccept(s: usize, addr: *mut u8, len: *mut i32, cond: *const c_void, data: usize) -> usize { + let r = orig!(H_WSAACCEPT, fn(usize, *mut u8, *mut i32, *const c_void, usize) -> usize)(s, addr, len, cond, data); + if r != usize::MAX { + note_event(r, crate::netview::sockets::Event::Accepted, addr, accepted_len(len)); + } + r +} + +unsafe extern "system" fn h_closesocket(s: usize) -> i32 { + ioctl::socket_closing(s); + crate::netview::sockets::forget(s as u64); + PENDING_ACCEPTS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(_, a)| *a != s); + orig!(H_CLOSESOCKET, fn(usize) -> i32)(s) +} + +const WSAEWOULDBLOCK: u32 = 10035; +const ERROR_IO_PENDING: u32 = 997; +const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006; +const SO_UPDATE_ACCEPT_CONTEXT: i32 = 0x700B; +const SO_UPDATE_CONNECT_CONTEXT: i32 = 0x7010; +const WSAID_ACCEPTEX: [u8; 16] = [0xf1, 0x7d, 0x36, 0xb5, 0xac, 0xcb, 0xcf, 0x11, 0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92]; +const WSAID_GETACCEPTEXSOCKADDRS: [u8; 16] = [0xf2, 0x7d, 0x36, 0xb5, 0xac, 0xcb, 0xcf, 0x11, 0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92]; +const WSAID_CONNECTEX: [u8; 16] = [0xb9, 0x07, 0xa2, 0x25, 0xf3, 0xdd, 0x60, 0x46, 0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e]; + +static REAL_ACCEPTEX: AtomicUsize = AtomicUsize::new(0); +static REAL_GETACCEPTEXSOCKADDRS: AtomicUsize = AtomicUsize::new(0); +static REAL_CONNECTEX: AtomicUsize = AtomicUsize::new(0); +static UNWRAPPED_EXTENSIONS: AtomicUsize = AtomicUsize::new(0); +static PENDING_ACCEPTS: Mutex> = Mutex::new(Vec::new()); + +type AcceptExFn = unsafe extern "system" fn(usize, usize, *mut u8, u32, u32, u32, *mut u32, *mut c_void) -> i32; +type GetAcceptExSockaddrsFn = unsafe extern "system" fn(*mut u8, u32, u32, u32, *mut *mut u8, *mut i32, *mut *mut u8, *mut i32); +type ConnectExFn = unsafe extern "system" fn(usize, *const u8, i32, *const c_void, u32, *mut u32, *mut c_void) -> i32; + +unsafe extern "system" fn w_acceptex(listen: usize, accept: usize, buf: *mut u8, recv: u32, local_len: u32, remote_len: u32, got: *mut u32, ov: *mut c_void) -> i32 { + let f: AcceptExFn = core::mem::transmute(REAL_ACCEPTEX.load(Ordering::SeqCst)); + { + let mut g = PENDING_ACCEPTS.lock().unwrap_or_else(|e| e.into_inner()); + g.retain(|(b, a)| *b != buf as usize && *a != accept); + g.push((buf as usize, accept)); + } + let r = f(listen, accept, buf, recv, local_len, remote_len, got, ov); + let e = GetLastError(); + if r == 0 && e != ERROR_IO_PENDING { + PENDING_ACCEPTS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(b, _)| *b != buf as usize); + } + SetLastError(e); + r +} + +unsafe extern "system" fn w_getacceptexsockaddrs(buf: *mut u8, recv: u32, local_len: u32, remote_len: u32, local: *mut *mut u8, ll: *mut i32, remote: *mut *mut u8, rl: *mut i32) { + let f: GetAcceptExSockaddrsFn = core::mem::transmute(REAL_GETACCEPTEXSOCKADDRS.load(Ordering::SeqCst)); + f(buf, recv, local_len, remote_len, local, ll, remote, rl); + let e = GetLastError(); + let accept = { + let mut g = PENDING_ACCEPTS.lock().unwrap_or_else(|e| e.into_inner()); + let found = g.iter().find(|(b, _)| *b == buf as usize).map(|(_, a)| *a); + g.retain(|(b, _)| *b != buf as usize); + found + }; + if let Some(a) = accept { + if !local.is_null() && !remote.is_null() && !ll.is_null() && !rl.is_null() { + crate::netview::sockets::report_accepted(a, *local, *ll, *remote, *rl); + } + } + SetLastError(e); +} + +unsafe extern "system" fn w_connectex(s: usize, name: *const u8, len: i32, send: *const c_void, send_len: u32, sent: *mut u32, ov: *mut c_void) -> i32 { + if !dest_allowed(name, len) { + deny_dest("ConnectEx", name, len); + return 0; + } + let f: ConnectExFn = core::mem::transmute(REAL_CONNECTEX.load(Ordering::SeqCst)); + let r = f(s, name, len, send, send_len, sent, ov); + let e = GetLastError(); + if r != 0 { + crate::netview::sockets::report_socket(s, name, len); + } else if e == ERROR_IO_PENDING { + crate::netview::sockets::report_event(s, crate::netview::sockets::Event::Connecting, name, len); + } + SetLastError(e); + r +} + +fn wrap_extension(guid: &[u8; 16], real: usize) -> usize { + let (slot, wrapper) = match *guid { + WSAID_ACCEPTEX => (&REAL_ACCEPTEX, w_acceptex as *const () as usize), + WSAID_GETACCEPTEXSOCKADDRS => (&REAL_GETACCEPTEXSOCKADDRS, w_getacceptexsockaddrs as *const () as usize), + WSAID_CONNECTEX => (&REAL_CONNECTEX, w_connectex as *const () as usize), + _ => return real, + }; + if real == 0 || real == wrapper { + return real; + } + match slot.compare_exchange(0, real, Ordering::SeqCst, Ordering::SeqCst) { + Ok(_) => wrapper, + Err(known) if known == real => wrapper, + Err(_) => { + if UNWRAPPED_EXTENSIONS.fetch_add(1, Ordering::SeqCst) == 0 { + note("a second provider returned its own AcceptEx/ConnectEx/GetAcceptExSockaddrs; its sockets are not reported"); + } + real + } + } +} + +unsafe extern "system" fn h_wsaioctl(s: usize, code: u32, input: *const c_void, in_len: u32, out: *mut c_void, out_len: u32, ret: *mut u32, ov: *mut c_void, cr: *mut c_void) -> i32 { + if let Some(r) = ioctl::handle_ioctl(s, code, input, in_len, out, out_len, ret, ov, cr) { + return r; + } + let r = orig!(H_WSAIOCTL, fn(usize, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *mut c_void) -> i32)(s, code, input, in_len, out, out_len, ret, ov, cr); + if r == 0 && code == SIO_GET_EXTENSION_FUNCTION_POINTER && !input.is_null() && in_len as usize >= 16 && !out.is_null() && out_len as usize >= core::mem::size_of::() { + let guid = core::ptr::read_unaligned(input as *const [u8; 16]); + let real = core::ptr::read_unaligned(out as *const usize); + core::ptr::write_unaligned(out as *mut usize, wrap_extension(&guid, real)); + } + if r == 0 { + ext::guard_extension_out(code, input as *const u8, in_len, out as *mut u8, out_len); + } + r +} + +pub(crate) fn wsaioctl_shared() -> bool { + ORIG[H_WSAIOCTL].load(Ordering::SeqCst) != 0 +} + +unsafe extern "system" fn h_setsockopt(s: usize, level: i32, name: i32, val: *const u8, len: i32) -> i32 { + let r = orig!(H_SETSOCKOPT, fn(usize, i32, i32, *const u8, i32) -> i32)(s, level, name, val, len); + if r == 0 && level == 0xffff { + match name { + SO_UPDATE_ACCEPT_CONTEXT => { + PENDING_ACCEPTS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(_, a)| *a != s); + note_event(s, crate::netview::sockets::Event::Accepted, core::ptr::null(), 0); + } + SO_UPDATE_CONNECT_CONTEXT => note_event(s, crate::netview::sockets::Event::Connected, core::ptr::null(), 0), + _ => {} + } + } + r +} + +const SOCKET_TABLE_HOOKS: usize = 7; + +fn install_socket_table_hooks() -> (usize, Vec) { + let ws = b"ws2_32.dll\0"; + let table: [(&[u8], usize, usize); SOCKET_TABLE_HOOKS] = [ + (b"bind\0", H_BIND, h_bind as *const () as usize), + (b"listen\0", H_LISTEN, h_listen as *const () as usize), + (b"accept\0", H_ACCEPT, h_accept as *const () as usize), + (b"WSAAccept\0", H_WSAACCEPT, h_wsaaccept as *const () as usize), + (b"closesocket\0", H_CLOSESOCKET, h_closesocket as *const () as usize), + (b"WSAIoctl\0", H_WSAIOCTL, h_wsaioctl as *const () as usize), + (b"setsockopt\0", H_SETSOCKOPT, h_setsockopt as *const () as usize), + ]; + let (mut hooked, mut missing) = (0, Vec::new()); + for (f, idx, hook) in table { + let name = String::from_utf8_lossy(&f[..f.len() - 1]).into_owned(); + if ORIG[idx].load(Ordering::SeqCst) != 0 { + hooked += 1; + continue; + } + let p = unsafe { resolve_export(ws, f) }; + if p.is_null() { + missing.push(name); + continue; + } + match unsafe { make_trampoline(p) } { + Some(t) => { + ORIG[idx].store(t, Ordering::SeqCst); + if unsafe { write_jump(p, hook) } { hooked += 1 } else { missing.push(name) } + } + None => missing.push(name), + } + } + (hooked, missing) +} + +fn socket_table_note() -> String { + let (mut hooked, mut missing) = install_socket_table_hooks(); + let (ih, im) = ioctl::install(); + hooked += ih; + missing.extend(im); + format!("; socket table: {hooked}/{} hooked{}", SOCKET_TABLE_HOOKS + ioctl::HOOKS, if missing.is_empty() { String::new() } else { format!(" (not patched: {})", missing.join(", ")) }) } unsafe extern "system" fn h_wsaconnect(s: usize, name: *const u8, len: i32, a: *mut c_void, b: *mut c_void, c: *mut c_void, d: *mut c_void) -> i32 { @@ -557,7 +797,9 @@ unsafe extern "system" fn h_wsaconnect(s: usize, name: *const u8, len: i32, a: * deny_dest("WSAConnect", name, len); return -1; } - orig!(H_WSACONNECT, fn(usize, *const u8, i32, *mut c_void, *mut c_void, *mut c_void, *mut c_void) -> i32)(s, name, len, a, b, c, d) + let r = orig!(H_WSACONNECT, fn(usize, *const u8, i32, *mut c_void, *mut c_void, *mut c_void, *mut c_void) -> i32)(s, name, len, a, b, c, d); + note_socket(s, r, name, len); + r } type ByName = unsafe extern "system" fn(usize, *const T, *const T, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32; @@ -589,7 +831,9 @@ unsafe extern "system" fn h_sendto(s: usize, buf: *const u8, len: i32, flags: i3 deny_dest("sendto", to, tolen); return -1; } - orig!(H_SENDTO, fn(usize, *const u8, i32, i32, *const u8, i32) -> i32)(s, buf, len, flags, to, tolen) + let r = orig!(H_SENDTO, fn(usize, *const u8, i32, i32, *const u8, i32) -> i32)(s, buf, len, flags, to, tolen); + note_socket(s, r, to, tolen); + r } unsafe extern "system" fn h_wsasendto( @@ -599,7 +843,9 @@ unsafe extern "system" fn h_wsasendto( deny_dest("WSASendTo", to, tolen); return -1; } - orig!(H_WSASENDTO, fn(usize, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)(s, bufs, count, sent, flags, to, tolen, ov, routine) + let r = orig!(H_WSASENDTO, fn(usize, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)(s, bufs, count, sent, flags, to, tolen, ov, routine); + note_socket(s, r, to, tolen); + r } static LOCAL_PROXY_SESSIONS: Mutex> = Mutex::new(Vec::new()); @@ -944,8 +1190,9 @@ fn install_deny() { missing.push(String::from_utf8_lossy(&f[..f.len() - 1]).into_owned()); } } + let sockets = socket_table_note(); crate::record_raw("net_guard", "installed", &format!( - "{ok}/14 network entry points blocked in-process{}", + "{ok}/14 network entry points blocked in-process{}{sockets}", if missing.is_empty() { String::new() } else { format!(" (not patched: {})", missing.join(", ")) })); ext::install(false); } @@ -998,8 +1245,9 @@ fn install_redirect(host: &str) { } } } + let sockets = socket_table_note(); crate::record_raw("net_guard", "installed", &format!( - "REDIRECT mode: every host -> '{host}'{}; {hooked}/23 entry points hooked{}{}", + "REDIRECT mode: every host -> '{host}'{}; {hooked}/23 entry points hooked{}{}{sockets}", match LOCAL_PORT.load(Ordering::Relaxed) { 0 => String::new(), p => format!(" (local backend: WinHTTP -> port {p}, plain HTTP)") }, if denied.is_empty() { String::new() } else { format!("; fail-closed (no trampoline): {}", denied.join(", ")) }, if missing.is_empty() { String::new() } else { format!("; NOT PATCHED: {}", missing.join(", ")) })); @@ -1131,3 +1379,522 @@ mod callback_owner_tests { assert!(find_cb(ws).is_none()); } } + +#[cfg(test)] +mod socket_table_tests { + use super::*; + use crate::netview::sockets::{self, MIB_TCP_STATE_ESTAB, MIB_TCP_STATE_LISTEN, MIB_TCP_STATE_RESERVED, TCP_TABLE_OWNER_PID_ALL, UDP_TABLE_OWNER_PID}; + use crate::netview::AF_INET; + + #[link(name = "ws2_32")] + extern "system" { + fn socket(af: i32, ty: i32, proto: i32) -> usize; + } + + fn arm() -> std::sync::MutexGuard<'static, ()> { + let g = sockets::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _ = std::net::UdpSocket::bind("127.0.0.1:0"); + for (idx, name) in [(H_BIND, &b"bind\0"[..]), (H_LISTEN, b"listen\0"), (H_ACCEPT, b"accept\0"), (H_WSAACCEPT, b"WSAAccept\0"), (H_CLOSESOCKET, b"closesocket\0"), (H_CONNECT, b"connect\0"), (H_WSAIOCTL, b"WSAIoctl\0"), (H_SETSOCKOPT, b"setsockopt\0")] { + let p = unsafe { resolve_export(b"ws2_32.dll\0", name) }; + assert!(!p.is_null()); + ORIG[idx].store(p as usize, Ordering::SeqCst); + } + g + } + + fn loopback_any() -> [u8; 16] { + let mut a = [0u8; 16]; + a[0] = 2; + a[4..8].copy_from_slice(&[127, 0, 0, 1]); + a + } + + fn mine(s: usize) -> Option { + let pid = std::process::id(); + sockets::snapshot().into_iter().find(|e| e.socket == s as u64 && e.pid == pid) + } + + fn rows(t: &[u8], size: usize) -> Vec<&[u8]> { + let n = u32::from_le_bytes([t[0], t[1], t[2], t[3]]) as usize; + (0..n).map(|i| &t[4 + i * size..4 + (i + 1) * size]).collect() + } + + fn tcp_ports() -> Vec<(u16, u32)> { + let t = sockets::tcp_table(AF_INET, TCP_TABLE_OWNER_PID_ALL, true).unwrap(); + rows(&t, sockets::TCP_ROW_OWNER_PID_SIZE).iter().filter(|r| u32::from_le_bytes([r[0x14], r[0x15], r[0x16], r[0x17]]) == std::process::id()).map(|r| (u16::from_be_bytes([r[8], r[9]]), u32::from_le_bytes([r[0], r[1], r[2], r[3]]))).collect() + } + + #[test] + fn bound_listening_accepted_and_closed_tcp_sockets_track_the_table() { + let _g = arm(); + unsafe { + let s = socket(2, 1, 6); + assert_ne!(s, usize::MAX); + let a = loopback_any(); + assert_eq!(h_bind(s, a.as_ptr(), 16), 0); + let bound = mine(s).expect("bound socket recorded"); + assert_eq!(bound.state, MIB_TCP_STATE_RESERVED); + let port = bound.local.port(); + assert_ne!(port, 0); + assert!(!tcp_ports().iter().any(|(p, _)| *p == port)); + assert_eq!(h_listen(s, 4), 0); + assert_eq!(mine(s).unwrap().state, MIB_TCP_STATE_LISTEN); + assert!(tcp_ports().contains(&(port, MIB_TCP_STATE_LISTEN))); + let client = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut peer = [0u8; 16]; + let mut plen = 16i32; + let c = h_accept(s, peer.as_mut_ptr(), &mut plen); + assert_ne!(c, usize::MAX); + let acc = mine(c).expect("accepted socket recorded"); + assert_eq!(acc.state, MIB_TCP_STATE_ESTAB); + assert_eq!(acc.local.port(), port); + assert_eq!(acc.remote.unwrap().port(), client.local_addr().unwrap().port()); + assert!(tcp_ports().contains(&(port, MIB_TCP_STATE_ESTAB))); + assert_eq!(h_closesocket(c), 0); + assert!(mine(c).is_none()); + assert_eq!(h_closesocket(s), 0); + assert!(mine(s).is_none()); + assert!(!tcp_ports().iter().any(|(p, _)| *p == port)); + } + } + + #[test] + fn bound_udp_sockets_show_in_the_udp_table_until_closed() { + let _g = arm(); + unsafe { + let s = socket(2, 2, 17); + assert_ne!(s, usize::MAX); + let a = loopback_any(); + assert_eq!(h_bind(s, a.as_ptr(), 16), 0); + let port = mine(s).expect("bound udp recorded").local.port(); + let t = sockets::udp_table(AF_INET, UDP_TABLE_OWNER_PID, true).unwrap(); + assert!(rows(&t, sockets::UDP_ROW_OWNER_PID_SIZE).iter().any(|r| u16::from_be_bytes([r[4], r[5]]) == port)); + assert_eq!(h_closesocket(s), 0); + assert!(mine(s).is_none()); + } + } + + #[test] + fn emulator_owned_listeners_are_reported() { + let _g = arm(); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + assert!(sockets::report_std(&l)); + let port = l.local_addr().unwrap().port(); + assert!(tcp_ports().contains(&(port, MIB_TCP_STATE_LISTEN))); + let u = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + assert!(sockets::report_std(&u)); + let up = u.local_addr().unwrap().port(); + let t = sockets::udp_table(AF_INET, UDP_TABLE_OWNER_PID, true).unwrap(); + assert!(rows(&t, sockets::UDP_ROW_OWNER_PID_SIZE).iter().any(|r| u16::from_be_bytes([r[4], r[5]]) == up)); + let raw = std::os::windows::io::AsRawSocket::as_raw_socket(&l); + drop(l); + assert!(!sockets::endpoints().iter().any(|e| e.socket == raw && e.pid == std::process::id())); + } + + #[link(name = "ws2_32")] + extern "system" { + fn ioctlsocket(s: usize, cmd: i32, arg: *mut u32) -> i32; + } + + #[link(name = "kernel32")] + extern "system" { + fn CreateEventW(sa: *mut c_void, manual: i32, initial: i32, name: *const u16) -> *mut c_void; + fn WaitForSingleObject(h: *mut c_void, ms: u32) -> u32; + } + + const FIONBIO: i32 = 0x8004_667Eu32 as i32; + + fn sin(ip: [u8; 4], port: u16) -> [u8; 16] { + let mut a = [0u8; 16]; + a[0] = 2; + a[2..4].copy_from_slice(&port.to_be_bytes()); + a[4..8].copy_from_slice(&ip); + a + } + + fn settled(s: usize) -> Option { + let pid = std::process::id(); + sockets::endpoints().into_iter().find(|e| e.socket == s as u64 && e.pid == pid) + } + + fn wait_for(ms: u64, mut f: impl FnMut() -> bool) -> bool { + let start = std::time::Instant::now(); + while start.elapsed().as_millis() < ms as u128 { + if f() { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + f() + } + + unsafe fn extension(s: usize, guid: &[u8; 16]) -> usize { + let mut p = 0usize; + let mut got = 0u32; + let r = h_wsaioctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, guid.as_ptr() as *const c_void, 16, &mut p as *mut usize as *mut c_void, 8, &mut got, core::ptr::null_mut(), core::ptr::null_mut()); + assert_eq!(r, 0); + p + } + + struct Overlapped { + raw: Box<[usize; 4]>, + } + + impl Overlapped { + unsafe fn new() -> Overlapped { + let ev = CreateEventW(core::ptr::null_mut(), 1, 0, core::ptr::null()); + assert!(!ev.is_null()); + Overlapped { raw: Box::new([0, 0, 0, ev as usize]) } + } + fn ptr(&mut self) -> *mut c_void { + self.raw.as_mut_ptr() as *mut c_void + } + unsafe fn wait(&self) { + assert_eq!(WaitForSingleObject(self.raw[3] as *mut c_void, 5000), 0); + } + } + + #[test] + fn nonblocking_connects_show_syn_sent_then_established_or_vanish_on_failure() { + let _g = arm(); + unsafe { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let s = socket(2, 1, 6); + let mut on = 1u32; + assert_eq!(ioctlsocket(s, FIONBIO, &mut on), 0); + let a = sin([127, 0, 0, 1], port); + assert_eq!(h_connect(s, a.as_ptr(), 16), -1); + assert_eq!(GetLastError(), WSAEWOULDBLOCK); + let row = mine(s).expect("in-progress connect recorded"); + assert_eq!(row.state, sockets::MIB_TCP_STATE_SYN_SENT); + assert_eq!(row.remote.unwrap().port(), port); + assert!(wait_for(5000, || settled(s).map(|e| e.state) == Some(MIB_TCP_STATE_ESTAB))); + let local = settled(s).unwrap().local.port(); + assert!(tcp_ports().contains(&(local, MIB_TCP_STATE_ESTAB))); + assert_eq!(h_closesocket(s), 0); + let dead = { + let t = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + t.local_addr().unwrap().port() + }; + let f = socket(2, 1, 6); + assert_eq!(ioctlsocket(f, FIONBIO, &mut on), 0); + let b = sin([127, 0, 0, 1], dead); + assert_eq!(h_connect(f, b.as_ptr(), 16), -1); + assert_eq!(GetLastError(), WSAEWOULDBLOCK); + assert_eq!(mine(f).unwrap().state, sockets::MIB_TCP_STATE_SYN_SENT); + assert!(wait_for(10000, || settled(f).is_none())); + assert!(mine(f).is_none()); + assert_eq!(h_closesocket(f), 0); + } + } + + #[test] + fn connectex_pointers_are_wrapped_and_report_the_connection() { + let _g = arm(); + unsafe { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let s = socket(2, 1, 6); + assert_eq!(h_bind(s, loopback_any().as_ptr(), 16), 0); + let outer = extension(s, &WSAID_CONNECTEX); + assert_ne!(outer, w_connectex as *const () as usize); + let p = ext::guarded_inner(outer).expect("ConnectEx pointer guarded by ext"); + assert_eq!(p, w_connectex as *const () as usize); + let transmit = [0xf0, 0x7d, 0x36, 0xb5, 0xac, 0xcb, 0xcf, 0x11, 0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92]; + let mut real = 0usize; + let mut got = 0u32; + assert_eq!(orig!(H_WSAIOCTL, fn(usize, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *mut c_void) -> i32)(s, SIO_GET_EXTENSION_FUNCTION_POINTER, transmit.as_ptr() as *const c_void, 16, &mut real as *mut usize as *mut c_void, 8, &mut got, core::ptr::null_mut(), core::ptr::null_mut()), 0); + assert_eq!(extension(s, &transmit), real); + let connect_ex: ConnectExFn = core::mem::transmute(p); + let mut ov = Overlapped::new(); + let a = sin([127, 0, 0, 1], port); + let r = connect_ex(s, a.as_ptr(), 16, core::ptr::null(), 0, core::ptr::null_mut(), ov.ptr()); + if r == 0 { + assert_eq!(GetLastError(), ERROR_IO_PENDING); + } + assert!(mine(s).is_some()); + ov.wait(); + assert!(wait_for(5000, || settled(s).map(|e| e.state) == Some(MIB_TCP_STATE_ESTAB))); + assert_eq!(h_setsockopt(s, 0xffff, SO_UPDATE_CONNECT_CONTEXT, core::ptr::null(), 0), 0); + let row = mine(s).unwrap(); + assert_eq!(row.state, MIB_TCP_STATE_ESTAB); + assert_eq!(row.remote.unwrap().port(), port); + assert_eq!(h_closesocket(s), 0); + let d = socket(2, 1, 6); + assert_eq!(h_bind(d, loopback_any().as_ptr(), 16), 0); + LAST_REFRESH.store(GetTickCount64() as usize, Ordering::Relaxed); + let far = sin([203, 0, 113, 1], 9); + let mut ov2 = Overlapped::new(); + assert_eq!(connect_ex(d, far.as_ptr(), 16, core::ptr::null(), 0, core::ptr::null_mut(), ov2.ptr()), 0); + assert_eq!(GetLastError(), WSAENETUNREACH); + assert_ne!(mine(d).map(|e| e.state), Some(sockets::MIB_TCP_STATE_SYN_SENT)); + assert_eq!(h_closesocket(d), 0); + } + } + + #[test] + fn acceptex_connections_appear_once_their_addresses_are_read() { + let _g = arm(); + unsafe { + let ls = socket(2, 1, 6); + assert_eq!(h_bind(ls, loopback_any().as_ptr(), 16), 0); + assert_eq!(h_listen(ls, 4), 0); + let port = mine(ls).unwrap().local.port(); + let accept_ex: AcceptExFn = core::mem::transmute(extension(ls, &WSAID_ACCEPTEX)); + let p = extension(ls, &WSAID_GETACCEPTEXSOCKADDRS); + assert_eq!(p, w_getacceptexsockaddrs as *const () as usize); + let addrs: GetAcceptExSockaddrsFn = core::mem::transmute(p); + let acc = socket(2, 1, 6); + let mut buf = [0u8; 64]; + let mut got = 0u32; + let mut ov = Overlapped::new(); + let r = accept_ex(ls, acc, buf.as_mut_ptr(), 0, 32, 32, &mut got, ov.ptr()); + if r == 0 { + assert_eq!(GetLastError(), ERROR_IO_PENDING); + } + assert!(mine(acc).is_none()); + let client = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + ov.wait(); + assert!(mine(acc).is_none()); + let (mut lp, mut rp) = (core::ptr::null_mut(), core::ptr::null_mut()); + let (mut ll, mut rl) = (0i32, 0i32); + addrs(buf.as_mut_ptr(), 0, 32, 32, &mut lp, &mut ll, &mut rp, &mut rl); + let row = mine(acc).expect("AcceptEx connection reported"); + assert_eq!(row.state, MIB_TCP_STATE_ESTAB); + assert_eq!(row.local.port(), port); + assert_eq!(row.remote.unwrap().port(), client.local_addr().unwrap().port()); + assert_eq!(h_closesocket(acc), 0); + assert!(mine(acc).is_none()); + let acc2 = socket(2, 1, 6); + let mut buf2 = [0u8; 64]; + let mut ov2 = Overlapped::new(); + let r = accept_ex(ls, acc2, buf2.as_mut_ptr(), 0, 32, 32, &mut got, ov2.ptr()); + if r == 0 { + assert_eq!(GetLastError(), ERROR_IO_PENDING); + } + let client2 = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + ov2.wait(); + assert_eq!(h_setsockopt(acc2, 0xffff, SO_UPDATE_ACCEPT_CONTEXT, &ls as *const usize as *const u8, 8), 0); + let row = mine(acc2).expect("context-updated AcceptEx socket reported"); + assert_eq!(row.state, MIB_TCP_STATE_ESTAB); + assert_eq!(row.remote.unwrap().port(), client2.local_addr().unwrap().port()); + assert!(PENDING_ACCEPTS.lock().unwrap().iter().all(|(_, a)| *a != acc2)); + assert_eq!(h_closesocket(acc2), 0); + assert_eq!(h_closesocket(ls), 0); + } + } + + #[test] + fn address_list_sort_is_answered_from_the_emulated_view() { + let _g = arm(); + let mk = |ip: std::net::Ipv6Addr| { + let mut b = [0u8; 28]; + b[0] = 0x17; + b[8..24].copy_from_slice(&ip.octets()); + b + }; + let root4 = mk(std::net::Ipv4Addr::new(198, 41, 0, 4).to_ipv6_mapped()); + let lo6 = mk(std::net::Ipv6Addr::LOCALHOST); + let mut list = [0u8; 8 + 32]; + list[0] = 2; + list[8..16].copy_from_slice(&(root4.as_ptr() as usize).to_le_bytes()); + list[16] = 28; + list[24..32].copy_from_slice(&(lo6.as_ptr() as usize).to_le_bytes()); + list[32] = 28; + let mut out = [0u8; 40]; + let mut got = 0u32; + unsafe { + let s = socket(23, 2, 0); + assert_ne!(s, usize::MAX); + let r = h_wsaioctl(s, crate::netview::iphlp::SIO_ADDRESS_LIST_SORT, list.as_ptr() as *const c_void, 40, out.as_mut_ptr() as *mut c_void, 40, &mut got, core::ptr::null_mut(), core::ptr::null_mut()); + assert_eq!(r, 0); + assert_eq!(got, 40); + assert_eq!(usize::from_le_bytes(out[8..16].try_into().unwrap()), lo6.as_ptr() as usize); + assert_eq!(usize::from_le_bytes(out[24..32].try_into().unwrap()), root4.as_ptr() as usize); + let r = h_wsaioctl(s, crate::netview::iphlp::SIO_ADDRESS_LIST_SORT, list.as_ptr() as *const c_void, 40, out.as_mut_ptr() as *mut c_void, 20, &mut got, core::ptr::null_mut(), core::ptr::null_mut()); + assert_eq!(r, -1); + assert_eq!(GetLastError(), ioctl::WSAEFAULT); + let ev = CreateEventW(core::ptr::null_mut(), 1, 0, core::ptr::null()); + let mut ov = [0usize; 4]; + ov[3] = ev as usize; + let r = h_wsaioctl(s, crate::netview::iphlp::SIO_ADDRESS_LIST_SORT, list.as_ptr() as *const c_void, 40, list.as_mut_ptr() as *mut c_void, 40, &mut got, ov.as_mut_ptr() as *mut c_void, core::ptr::null_mut()); + assert_eq!(r, 0); + assert_eq!(ov[1], 40); + assert_eq!(WaitForSingleObject(ev, 0), 0); + assert_eq!(usize::from_le_bytes(list[8..16].try_into().unwrap()), lo6.as_ptr() as usize); + assert_eq!(h_closesocket(s), 0); + } + } + + #[link(name = "kernel32")] + extern "system" { + fn GetQueuedCompletionStatus(port: usize, bytes: *mut u32, key: *mut usize, ov: *mut *mut c_void, ms: u32) -> i32; + fn SleepEx(ms: u32, alertable: i32) -> u32; + fn CloseHandle(h: *mut c_void) -> i32; + } + + fn arm_all() -> std::sync::MutexGuard<'static, ()> { + let g = arm(); + ioctl::arm_for_tests(); + g + } + + unsafe fn ioctl_call(s: usize, code: u32, input: &[u8], out: &mut [u8], ov: *mut c_void) -> (i32, u32, u32) { + let mut got = 0u32; + let r = h_wsaioctl(s, code, if input.is_empty() { core::ptr::null() } else { input.as_ptr() as *const c_void }, input.len() as u32, if out.is_empty() { core::ptr::null_mut() } else { out.as_mut_ptr() as *mut c_void }, out.len() as u32, &mut got, ov, core::ptr::null_mut()); + (r, got, if r == 0 { 0 } else { GetLastError() }) + } + + #[test] + fn address_and_routing_queries_come_from_the_view() { + use crate::netview::iphlp::{SIO_ADDRESS_LIST_QUERY, SIO_ROUTING_INTERFACE_QUERY}; + let _g = arm_all(); + unsafe { + let s4 = socket(2, 2, 0); + let (r, need, e) = ioctl_call(s4, SIO_ADDRESS_LIST_QUERY, &[], &mut [0u8; 4], core::ptr::null_mut()); + assert_eq!((r, e), (-1, ioctl::WSAEFAULT)); + assert_eq!(need, 8 + 16 + 16); + let mut out = vec![0u8; need as usize]; + let (r, got, _) = ioctl_call(s4, SIO_ADDRESS_LIST_QUERY, &[], &mut out, core::ptr::null_mut()); + assert_eq!((r, got), (0, need)); + assert_eq!(i32::from_le_bytes(out[0..4].try_into().unwrap()), 1); + let p = usize::from_le_bytes(out[8..16].try_into().unwrap()); + assert_eq!(p, out.as_ptr() as usize + 24); + assert_eq!(&out[24 + 4..24 + 8], &[169, 254, 66, 1]); + let s6 = socket(23, 2, 0); + let mut out6 = vec![0u8; 256]; + let (r, got, _) = ioctl_call(s6, SIO_ADDRESS_LIST_QUERY, &[], &mut out6, core::ptr::null_mut()); + assert_eq!((r, got), (0, 8 + 16 + 28)); + assert_eq!(&out6[24 + 8..24 + 24], &crate::netview::NIC_IPV6.octets()); + assert_eq!(u32::from_le_bytes(out6[24 + 24..24 + 28].try_into().unwrap()), crate::netview::NIC_IF_INDEX); + let mut o = [0u8; 16]; + let (r, got, _) = ioctl_call(s4, SIO_ROUTING_INTERFACE_QUERY, &sin([169, 254, 9, 9], 80), &mut o, core::ptr::null_mut()); + assert_eq!((r, got), (0, 16)); + assert_eq!(&o[4..8], &[169, 254, 66, 1]); + let (r, got, _) = ioctl_call(s4, SIO_ROUTING_INTERFACE_QUERY, &sin([127, 0, 0, 1], 80), &mut o, core::ptr::null_mut()); + assert_eq!((r, got), (0, 16)); + assert_eq!(&o[4..8], &[127, 0, 0, 1]); + let (r, _, e) = ioctl_call(s4, SIO_ROUTING_INTERFACE_QUERY, &sin([8, 8, 8, 8], 53), &mut o, core::ptr::null_mut()); + assert_eq!((r, e), (-1, ioctl::WSAENETUNREACH)); + let (r, need, e) = ioctl_call(s4, SIO_ROUTING_INTERFACE_QUERY, &sin([127, 0, 0, 1], 80), &mut [0u8; 8], core::ptr::null_mut()); + assert_eq!((r, need, e), (-1, 16, ioctl::WSAEFAULT)); + assert_eq!(h_closesocket(s4), 0); + assert_eq!(h_closesocket(s6), 0); + } + } + + #[test] + fn change_notifications_pend_until_close_and_complete_cancelled() { + use crate::netview::iphlp::{SIO_ADDRESS_LIST_CHANGE, SIO_ROUTING_INTERFACE_CHANGE}; + let _g = arm_all(); + unsafe { + let s = socket(2, 2, 0); + let ev = CreateEventW(core::ptr::null_mut(), 1, 0, core::ptr::null()); + let mut ov = [0usize; 4]; + ov[3] = ev as usize; + let (r, _, e) = ioctl_call(s, SIO_ADDRESS_LIST_CHANGE, &[], &mut [], ov.as_mut_ptr() as *mut c_void); + assert_eq!((r, e), (-1, ioctl::WSA_IO_PENDING)); + assert_eq!(ov[0], ioctl::STATUS_PENDING); + assert_eq!(WaitForSingleObject(ev, 50), 0x102); + assert_eq!(ioctl::pending_count(s), 1); + let mut nb = 1u32; + assert_eq!(ioctl::test_ioctlsocket(s, ioctl::FIONBIO, &mut nb), 0); + let (r, _, e) = ioctl_call(s, SIO_ROUTING_INTERFACE_CHANGE, &[], &mut [], core::ptr::null_mut()); + assert_eq!((r, e), (-1, ioctl::WSAEWOULDBLOCK)); + assert_eq!(h_closesocket(s), 0); + assert_eq!(WaitForSingleObject(ev, 0), 0); + assert_eq!(ov[0], ioctl::STATUS_CANCELLED); + assert_eq!(ioctl::pending_count(s), 0); + let b = socket(2, 2, 0); + let t = std::thread::spawn(move || { + let r = h_wsaioctl(b, SIO_ADDRESS_LIST_CHANGE, core::ptr::null(), 0, core::ptr::null_mut(), 0, &mut 0u32, core::ptr::null_mut(), core::ptr::null_mut()); + (r, GetLastError()) + }); + let mut spins = 0; + while ioctl::pending_count(b) == 0 && spins < 500 { + std::thread::sleep(std::time::Duration::from_millis(2)); + spins += 1; + } + assert_eq!(ioctl::pending_count(b), 1); + assert_eq!(h_closesocket(b), 0); + assert_eq!(t.join().unwrap(), (-1, ioctl::WSAEINTR)); + } + } + + static APC_SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + + unsafe extern "system" fn record_apc(err: u32, bytes: u32, _ov: *mut c_void, _flags: u32) { + APC_SEEN.lock().unwrap().push((err, bytes)); + } + + #[test] + fn overlapped_queries_post_to_bound_completion_ports_and_routines() { + use crate::netview::iphlp::{SIO_ADDRESS_LIST_CHANGE, SIO_ADDRESS_LIST_SORT}; + let _g = arm_all(); + unsafe { + let s = socket(23, 2, 0); + let port = ioctl::test_create_iocp(s, 0, 0x77, 0); + assert_ne!(port, 0); + let lo6 = { + let mut b = [0u8; 28]; + b[0] = 0x17; + b[8 + 15] = 1; + b + }; + let mut list = [0u8; 24]; + list[0] = 1; + list[8..16].copy_from_slice(&(lo6.as_ptr() as usize).to_le_bytes()); + list[16] = 28; + let mut out = [0u8; 24]; + let mut ov = [0usize; 4]; + let mut got = 0u32; + assert_eq!(h_wsaioctl(s, SIO_ADDRESS_LIST_SORT, list.as_ptr() as *const c_void, 24, out.as_mut_ptr() as *mut c_void, 24, &mut got, ov.as_mut_ptr() as *mut c_void, core::ptr::null_mut()), 0); + let (mut bytes, mut key, mut po) = (0u32, 0usize, core::ptr::null_mut()); + assert_ne!(GetQueuedCompletionStatus(port, &mut bytes, &mut key, &mut po, 0), 0); + assert_eq!((bytes, key, po as usize), (24, 0x77, ov.as_ptr() as usize)); + assert_eq!(ioctl::test_set_fcnm(s, ioctl::FILE_SKIP_COMPLETION_PORT_ON_SUCCESS), 1); + assert_eq!(h_wsaioctl(s, SIO_ADDRESS_LIST_SORT, list.as_ptr() as *const c_void, 24, out.as_mut_ptr() as *mut c_void, 24, &mut got, ov.as_mut_ptr() as *mut c_void, core::ptr::null_mut()), 0); + assert_eq!(GetQueuedCompletionStatus(port, &mut bytes, &mut key, &mut po, 0), 0); + let mut ov2 = [0usize; 4]; + assert_eq!(h_wsaioctl(s, SIO_ADDRESS_LIST_CHANGE, core::ptr::null(), 0, core::ptr::null_mut(), 0, &mut got, ov2.as_mut_ptr() as *mut c_void, core::ptr::null_mut()), -1); + assert_eq!(GetQueuedCompletionStatus(port, &mut bytes, &mut key, &mut po, 0), 0); + assert_eq!(h_closesocket(s), 0); + assert_eq!(GetQueuedCompletionStatus(port, &mut bytes, &mut key, &mut po, 0), 0); + assert_eq!(GetLastError(), ioctl::WSA_OPERATION_ABORTED); + assert_eq!(po as usize, ov2.as_ptr() as usize); + let s2 = socket(23, 2, 0); + let mut ov3 = [0usize; 4]; + APC_SEEN.lock().unwrap().clear(); + assert_eq!(h_wsaioctl(s2, SIO_ADDRESS_LIST_SORT, list.as_ptr() as *const c_void, 24, out.as_mut_ptr() as *mut c_void, 24, &mut got, ov3.as_mut_ptr() as *mut c_void, record_apc as *mut c_void), 0); + assert_eq!(h_wsaioctl(s2, SIO_ADDRESS_LIST_CHANGE, core::ptr::null(), 0, core::ptr::null_mut(), 0, &mut got, ov3.as_mut_ptr() as *mut c_void, record_apc as *mut c_void), -1); + assert_eq!(h_closesocket(s2), 0); + SleepEx(0, 1); + assert_eq!(*APC_SEEN.lock().unwrap(), vec![(0, 24), (ioctl::WSA_OPERATION_ABORTED, 0)]); + CloseHandle(port as *mut c_void); + } + } + + #[test] + fn completion_port_bindings_are_recorded_for_sockets_only() { + use std::os::windows::io::AsRawHandle; + let _g = arm_all(); + let path = std::env::temp_dir().join(format!("tombox_iocp_{}.bin", std::process::id())); + let f = { use std::os::windows::fs::OpenOptionsExt; std::fs::OpenOptions::new().write(true).create(true).truncate(true).custom_flags(0x4000_0000).open(&path).unwrap() }; + let h = f.as_raw_handle() as usize; + unsafe { + let port = ioctl::test_create_iocp(h, 0, 0x55, 0); + assert_ne!(port, 0); + assert!(!ioctl::is_bound(h)); + let s = socket(2, 2, 0); + assert!(!ioctl::is_bound(s)); + assert_eq!(ioctl::test_create_iocp(s, port, 0x66, 0), port); + assert!(ioctl::is_bound(s)); + assert_eq!(h_closesocket(s), 0); + assert!(!ioctl::is_bound(s)); + CloseHandle(port as *mut c_void); + } + drop(f); + let _ = std::fs::remove_file(&path); + } +} diff --git a/crates/compat/compat-common/src/net_guard/ext.rs b/crates/compat/compat-common/src/net_guard/ext.rs index bf48031f..7b50e8f9 100644 --- a/crates/compat/compat-common/src/net_guard/ext.rs +++ b/crates/compat/compat-common/src/net_guard/ext.rs @@ -150,18 +150,38 @@ fn sm_wrapper(i: usize) -> usize { [sm0 as *const () as usize, sm1 as *const () as usize, sm2 as *const () as usize, sm3 as *const () as usize][i] } +#[cfg(test)] +pub(crate) fn guarded_inner(p: usize) -> Option { + (0..4).find_map(|i| { + if cx_wrapper(i) == p { + Some(CX_REAL[i].load(Ordering::Acquire)) + } else if sm_wrapper(i) == p { + Some(SM_REAL[i].load(Ordering::Acquire)) + } else { + None + } + }) +} + pub unsafe extern "system" fn h_wsaioctl( s: usize, code: u32, inb: *const u8, inlen: u32, outb: *mut u8, outlen: u32, ret: *mut u32, ov: *mut c_void, routine: *const c_void, ) -> i32 { let rc = xorig!(X_WSAIOCTL, fn(usize, u32, *const u8, u32, *mut u8, u32, *mut u32, *mut c_void, *const c_void) -> i32)(s, code, inb, inlen, outb, outlen, ret, ov, routine); - if rc != 0 || code != SIO_GET_EXTENSION_FUNCTION_POINTER || inb.is_null() || inlen < 16 || outb.is_null() || outlen < 8 { - return rc; + if rc == 0 { + guard_extension_out(code, inb, inlen, outb, outlen); + } + rc +} + +pub unsafe fn guard_extension_out(code: u32, inb: *const u8, inlen: u32, outb: *mut u8, outlen: u32) { + if code != SIO_GET_EXTENSION_FUNCTION_POINTER || inb.is_null() || inlen < 16 || outb.is_null() || outlen < 8 { + return; } let mut guid = [0u8; 16]; core::ptr::copy_nonoverlapping(inb, guid.as_mut_ptr(), 16); let real = core::ptr::read_unaligned(outb as *const usize); if real == 0 { - return rc; + return; } let wrapped = if guid == WSAID_CONNECTEX { Some(register(&CX_REAL, real).map_or(cx_deny as *const () as usize, cx_wrapper)) @@ -173,7 +193,6 @@ pub unsafe extern "system" fn h_wsaioctl( if let Some(w) = wrapped { core::ptr::write_unaligned(outb as *mut usize, w); } - rc } pub unsafe extern "system" fn h_wsasendmsg(s: usize, msg: *const u8, flags: u32, sent: *mut u32, ov: *mut c_void, routine: *const c_void) -> i32 { @@ -349,6 +368,10 @@ pub fn install(redirect: bool) { let (mut hooked, mut denied, mut missing) = (0, Vec::new(), Vec::new()); for (m, f, idx, hook, deny) in table { let name = String::from_utf8_lossy(&f[..f.len() - 1]).into_owned(); + if idx == X_WSAIOCTL && super::wsaioctl_shared() { + hooked += 1; + continue; + } let p = unsafe { resolve_export(m, f) }; if p.is_null() { missing.push(name); diff --git a/crates/compat/compat-common/src/net_guard/ioctl.rs b/crates/compat/compat-common/src/net_guard/ioctl.rs new file mode 100644 index 00000000..7ac8d221 --- /dev/null +++ b/crates/compat/compat-common/src/net_guard/ioctl.rs @@ -0,0 +1,425 @@ +use core::ffi::c_void; +use core::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use super::{make_trampoline, resolve_export, write_jump}; +use crate::netview::iphlp; + +pub const WSAEINTR: u32 = 10004; +pub const WSAEFAULT: u32 = 10014; +pub const WSAEINVAL: u32 = 10022; +pub const WSAEWOULDBLOCK: u32 = 10035; +pub const WSAENOTSOCK: u32 = 10038; +pub const WSAENETUNREACH: u32 = 10051; +pub const WSA_IO_PENDING: u32 = 997; +pub const WSA_OPERATION_ABORTED: u32 = 995; +pub const STATUS_PENDING: usize = 0x103; +pub const STATUS_CANCELLED: usize = 0xC000_0120; +pub const FIONBIO: i32 = 0x8004_667Eu32 as i32; +pub const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS: u8 = 1; +const SO_PROTOCOL_INFOW: i32 = 0x2005; +const PROTOCOL_INFO_SIZE: usize = 628; + +#[link(name = "kernel32")] +extern "system" { + fn SetLastError(code: u32); + fn SetEvent(h: *mut c_void) -> i32; + fn CreateEventW(sa: *mut c_void, manual: i32, initial: i32, name: *const u16) -> *mut c_void; + fn WaitForSingleObject(h: *mut c_void, ms: u32) -> u32; + fn QueueUserAPC(f: unsafe extern "system" fn(usize), thread: *mut c_void, data: usize) -> u32; + fn GetCurrentThread() -> *mut c_void; + fn GetCurrentProcess() -> *mut c_void; + fn DuplicateHandle(sp: *mut c_void, s: *mut c_void, tp: *mut c_void, t: *mut *mut c_void, access: u32, inherit: i32, options: u32) -> u32; + fn CloseHandle(h: *mut c_void) -> i32; +} + +#[link(name = "ntdll")] +extern "system" { + fn NtSetIoCompletion(port: *mut c_void, key: usize, apc: usize, status: i32, info: usize) -> i32; +} + +const I_IOCTLSOCKET: usize = 0; +const I_EVENTSELECT: usize = 1; +const I_ASYNCSELECT: usize = 2; +const I_CREATEIOCP: usize = 3; +const I_SETFCNM: usize = 4; +static REAL: [AtomicUsize; 5] = [const { AtomicUsize::new(0) }; 5]; + +static NONBLOCKING: Mutex> = Mutex::new(Vec::new()); +static PORTS: Mutex> = Mutex::new(Vec::new()); +static PENDING: Mutex> = Mutex::new(Vec::new()); + +#[derive(Clone, Copy)] +struct Binding { + handle: usize, + port: usize, + key: usize, + skip_on_success: bool, +} + +struct Pending { + s: usize, + ov: usize, + cr: usize, + thread: usize, + event: usize, +} + +unsafe impl Send for Pending {} + +type WsaCompletion = unsafe extern "system" fn(u32, u32, *mut c_void, u32); + +struct Apc { + cr: usize, + error: u32, + bytes: u32, + ov: usize, + thread: usize, +} + +unsafe extern "system" fn run_apc(data: usize) { + let a = Box::from_raw(data as *mut Apc); + let f: WsaCompletion = core::mem::transmute(a.cr); + f(a.error, a.bytes, a.ov as *mut c_void, 0); + CloseHandle(a.thread as *mut c_void); +} + +unsafe fn current_thread() -> usize { + let mut t: *mut c_void = core::ptr::null_mut(); + DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &mut t, 0, 0, 2); + t as usize +} + +unsafe fn queue_apc(thread: usize, cr: usize, error: u32, bytes: u32, ov: usize) { + let a = Box::into_raw(Box::new(Apc { cr, error, bytes, ov, thread })); + if QueueUserAPC(run_apc, thread as *mut c_void, a as usize) == 0 { + drop(Box::from_raw(a)); + CloseHandle(thread as *mut c_void); + } +} + +fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub fn is_nonblocking(s: usize) -> bool { + lock(&NONBLOCKING).contains(&s) +} + +fn binding(s: usize) -> Option { + lock(&PORTS).iter().find(|b| b.handle == s).copied() +} + +unsafe fn finish(s: usize, ov: usize, cr: usize, thread: usize, status: usize, error: u32, bytes: u32, synchronous: bool) { + if ov != 0 { + let o = ov as *mut usize; + *o = status; + *o.add(1) = bytes as usize; + } + if cr != 0 { + let t = if thread != 0 { thread } else { current_thread() }; + queue_apc(t, cr, error, bytes, ov); + return; + } + if thread != 0 { + CloseHandle(thread as *mut c_void); + } + if ov == 0 { + return; + } + let ev = *(ov as *const usize).add(3); + if ev & !1 != 0 { + SetEvent((ev & !1) as *mut c_void); + } + if ev & 1 == 0 { + if let Some(b) = binding(s) { + if !(synchronous && status == 0 && b.skip_on_success) { + NtSetIoCompletion(b.port as *mut c_void, b.key, ov, status as u32 as i32, bytes as usize); + } + } + } +} + +unsafe fn fail(code: u32) -> i32 { + SetLastError(code); + -1 +} + +unsafe fn done(s: usize, ret: *mut u32, bytes: u32, ov: *mut c_void, cr: *mut c_void) -> i32 { + if !ret.is_null() { + *ret = bytes; + } + finish(s, ov as usize, cr as usize, 0, 0, 0, bytes, true); + SetLastError(0); + 0 +} + +pub unsafe fn address_list_sort(s: usize, input: *const c_void, in_len: u32, out: *mut c_void, out_len: u32, ret: *mut u32, ov: *mut c_void, cr: *mut c_void) -> i32 { + if input.is_null() || out.is_null() || (in_len as usize) < 4 { + return fail(WSAEINVAL); + } + let n = core::ptr::read_unaligned(input as *const i32); + let need = if n < 0 { usize::MAX } else { 8 + 16 * n as usize }; + if (in_len as usize) < need { + return fail(WSAEINVAL); + } + if (out_len as usize) < need { + return fail(WSAEFAULT); + } + if input as usize != out as usize { + core::ptr::copy(input as *const u8, out as *mut u8, need); + } + match iphlp::address_list_sort(out as *mut u8, out_len) { + Ok(b) => done(s, ret, b, ov, cr), + Err(_) => fail(WSAEINVAL), + } +} + +unsafe fn is_socket(h: usize) -> bool { + let p = resolve_export(b"ws2_32.dll\0", b"getsockopt\0"); + if p.is_null() { + return false; + } + let f: unsafe extern "system" fn(usize, i32, i32, *mut u8, *mut i32) -> i32 = core::mem::transmute(p); + let e = super::GetLastError(); + let mut ty = 0i32; + let mut len = 4i32; + let ok = f(h, 0xffff, 0x1008, &mut ty as *mut i32 as *mut u8, &mut len) == 0; + SetLastError(e); + ok +} + +unsafe fn socket_family(s: usize) -> Option { + let p = resolve_export(b"ws2_32.dll\0", b"getsockopt\0"); + if p.is_null() { + return None; + } + let f: unsafe extern "system" fn(usize, i32, i32, *mut u8, *mut i32) -> i32 = core::mem::transmute(p); + let mut info = [0u8; PROTOCOL_INFO_SIZE]; + let mut len = PROTOCOL_INFO_SIZE as i32; + if f(s, 0xffff, SO_PROTOCOL_INFOW, info.as_mut_ptr(), &mut len) != 0 { + return None; + } + Some(u32::from_le_bytes(info[0x4c..0x50].try_into().unwrap())) +} + +pub unsafe fn address_list_query(s: usize, out: *mut c_void, out_len: u32, ret: *mut u32, ov: *mut c_void, cr: *mut c_void) -> i32 { + let Some(family) = socket_family(s) else { + return fail(WSAENOTSOCK); + }; + match iphlp::write_address_list(family, out as *mut u8, out_len as usize) { + Ok(n) => done(s, ret, n as u32, ov, cr), + Err(need) => { + if !ret.is_null() { + *ret = need as u32; + } + fail(WSAEFAULT) + } + } +} + +pub unsafe fn routing_interface_query(s: usize, input: *const c_void, in_len: u32, out: *mut c_void, out_len: u32, ret: *mut u32, ov: *mut c_void, cr: *mut c_void) -> i32 { + if input.is_null() || in_len < 16 { + return fail(WSAEFAULT); + } + let fam = core::ptr::read_unaligned(input as *const u16) as u32; + if (fam == crate::netview::AF_INET6 && in_len < 0x1c) || !matches!(fam, crate::netview::AF_INET | crate::netview::AF_INET6) { + return fail(WSAEINVAL); + } + let Some(ip) = iphlp::sockaddr_to_ip(input as *const u8) else { + return fail(WSAEINVAL); + }; + let Some(b) = iphlp::routing_interface(&ip) else { + return fail(WSAENETUNREACH); + }; + if out.is_null() || (out_len as usize) < b.len() { + if !ret.is_null() { + *ret = b.len() as u32; + } + return fail(WSAEFAULT); + } + core::ptr::copy_nonoverlapping(b.as_ptr(), out as *mut u8, b.len()); + done(s, ret, b.len() as u32, ov, cr) +} + +pub unsafe fn change_notification(s: usize, ov: *mut c_void, cr: *mut c_void) -> i32 { + if ov.is_null() && cr.is_null() { + if is_nonblocking(s) { + return fail(WSAEWOULDBLOCK); + } + let ev = CreateEventW(core::ptr::null_mut(), 1, 0, core::ptr::null()); + if ev.is_null() { + return fail(WSAEINVAL); + } + lock(&PENDING).push(Pending { s, ov: 0, cr: 0, thread: 0, event: ev as usize }); + WaitForSingleObject(ev, 0xffff_ffff); + CloseHandle(ev); + return fail(WSAEINTR); + } + if ov.is_null() { + return fail(WSAEINVAL); + } + *(ov as *mut usize) = STATUS_PENDING; + *(ov as *mut usize).add(1) = 0; + let thread = if cr.is_null() { 0 } else { current_thread() }; + lock(&PENDING).push(Pending { s, ov: ov as usize, cr: cr as usize, thread, event: 0 }); + fail(WSA_IO_PENDING) +} + +pub fn pending_count(s: usize) -> usize { + lock(&PENDING).iter().filter(|p| p.s == s).count() +} + +pub unsafe fn socket_closing(s: usize) { + let mine: Vec = { + let mut all = lock(&PENDING); + let (m, rest): (Vec, Vec) = all.drain(..).partition(|p| p.s == s); + *all = rest; + m + }; + for p in mine { + if p.event != 0 { + SetEvent(p.event as *mut c_void); + } else { + finish(s, p.ov, p.cr, p.thread, STATUS_CANCELLED, WSA_OPERATION_ABORTED, 0, false); + } + } + lock(&NONBLOCKING).retain(|x| *x != s); + lock(&PORTS).retain(|b| b.handle != s); +} + +pub unsafe fn handle_ioctl(s: usize, code: u32, input: *const c_void, in_len: u32, out: *mut c_void, out_len: u32, ret: *mut u32, ov: *mut c_void, cr: *mut c_void) -> Option { + match code { + iphlp::SIO_ADDRESS_LIST_SORT => Some(address_list_sort(s, input, in_len, out, out_len, ret, ov, cr)), + iphlp::SIO_ADDRESS_LIST_QUERY => Some(address_list_query(s, out, out_len, ret, ov, cr)), + iphlp::SIO_ROUTING_INTERFACE_QUERY => Some(routing_interface_query(s, input, in_len, out, out_len, ret, ov, cr)), + iphlp::SIO_ADDRESS_LIST_CHANGE | iphlp::SIO_ROUTING_INTERFACE_CHANGE => Some(change_notification(s, ov, cr)), + _ => None, + } +} + +unsafe fn real(i: usize) -> usize { + REAL[i].load(Ordering::Relaxed) +} + +unsafe extern "system" fn h_ioctlsocket(s: usize, cmd: i32, arg: *mut u32) -> i32 { + let f: unsafe extern "system" fn(usize, i32, *mut u32) -> i32 = core::mem::transmute(real(I_IOCTLSOCKET)); + let r = f(s, cmd, arg); + if r == 0 && cmd == FIONBIO && !arg.is_null() { + let mut nb = lock(&NONBLOCKING); + nb.retain(|x| *x != s); + if *arg != 0 { + nb.push(s); + } + } + r +} + +fn mark_nonblocking(s: usize) { + let mut nb = lock(&NONBLOCKING); + if !nb.contains(&s) { + nb.push(s); + } +} + +unsafe extern "system" fn h_wsaeventselect(s: usize, ev: *mut c_void, mask: i32) -> i32 { + let f: unsafe extern "system" fn(usize, *mut c_void, i32) -> i32 = core::mem::transmute(real(I_EVENTSELECT)); + let r = f(s, ev, mask); + if r == 0 && mask != 0 { + mark_nonblocking(s); + } + r +} + +unsafe extern "system" fn h_wsaasyncselect(s: usize, hwnd: *mut c_void, msg: u32, mask: i32) -> i32 { + let f: unsafe extern "system" fn(usize, *mut c_void, u32, i32) -> i32 = core::mem::transmute(real(I_ASYNCSELECT)); + let r = f(s, hwnd, msg, mask); + if r == 0 && mask != 0 { + mark_nonblocking(s); + } + r +} + +unsafe extern "system" fn h_create_iocp(file: usize, existing: usize, key: usize, threads: u32) -> usize { + let f: unsafe extern "system" fn(usize, usize, usize, u32) -> usize = core::mem::transmute(real(I_CREATEIOCP)); + let r = f(file, existing, key, threads); + if r != 0 && file != usize::MAX && file != 0 && is_socket(file) { + let mut p = lock(&PORTS); + p.retain(|b| b.handle != file); + p.push(Binding { handle: file, port: r, key, skip_on_success: false }); + } + r +} + +unsafe extern "system" fn h_set_fcnm(handle: usize, flags: u8) -> i32 { + let f: unsafe extern "system" fn(usize, u8) -> i32 = core::mem::transmute(real(I_SETFCNM)); + let r = f(handle, flags); + if r != 0 { + if let Some(b) = lock(&PORTS).iter_mut().find(|b| b.handle == handle) { + b.skip_on_success = flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS != 0; + } + } + r +} + +pub const HOOKS: usize = 5; + +pub fn install() -> (usize, Vec) { + let table: [(&[u8], &[u8], usize, usize); HOOKS] = [ + (b"ws2_32.dll\0", b"ioctlsocket\0", I_IOCTLSOCKET, h_ioctlsocket as *const () as usize), + (b"ws2_32.dll\0", b"WSAEventSelect\0", I_EVENTSELECT, h_wsaeventselect as *const () as usize), + (b"ws2_32.dll\0", b"WSAAsyncSelect\0", I_ASYNCSELECT, h_wsaasyncselect as *const () as usize), + (b"kernelbase.dll\0", b"CreateIoCompletionPort\0", I_CREATEIOCP, h_create_iocp as *const () as usize), + (b"kernel32.dll\0", b"SetFileCompletionNotificationModes\0", I_SETFCNM, h_set_fcnm as *const () as usize), + ]; + let (mut hooked, mut missing) = (0, Vec::new()); + for (dll, f, idx, hook) in table { + let name = String::from_utf8_lossy(&f[..f.len() - 1]).into_owned(); + if REAL[idx].load(Ordering::SeqCst) != 0 { + hooked += 1; + continue; + } + let p = unsafe { resolve_export(dll, f) }; + if p.is_null() { + missing.push(name); + continue; + } + match unsafe { make_trampoline(p) } { + Some(t) => { + REAL[idx].store(t, Ordering::SeqCst); + if unsafe { write_jump(p, hook) } { hooked += 1 } else { missing.push(name) } + } + None => missing.push(name), + } + } + (hooked, missing) +} + +#[cfg(test)] +pub fn arm_for_tests() { + for (dll, f, idx) in [(&b"ws2_32.dll\0"[..], &b"ioctlsocket\0"[..], I_IOCTLSOCKET), (b"ws2_32.dll\0", b"WSAEventSelect\0", I_EVENTSELECT), (b"ws2_32.dll\0", b"WSAAsyncSelect\0", I_ASYNCSELECT), (b"kernelbase.dll\0", b"CreateIoCompletionPort\0", I_CREATEIOCP), (b"kernel32.dll\0", b"SetFileCompletionNotificationModes\0", I_SETFCNM)] { + let p = unsafe { resolve_export(dll, f) }; + assert!(!p.is_null()); + REAL[idx].store(p as usize, Ordering::SeqCst); + } +} + +#[cfg(test)] +pub unsafe fn test_ioctlsocket(s: usize, cmd: i32, arg: *mut u32) -> i32 { + h_ioctlsocket(s, cmd, arg) +} + +#[cfg(test)] +pub unsafe fn test_create_iocp(file: usize, existing: usize, key: usize, threads: u32) -> usize { + h_create_iocp(file, existing, key, threads) +} + +#[cfg(test)] +pub unsafe fn test_set_fcnm(handle: usize, flags: u8) -> i32 { + h_set_fcnm(handle, flags) +} + +#[cfg(test)] +pub fn is_bound(h: usize) -> bool { + binding(h).is_some() +} diff --git a/crates/compat/compat-common/src/netview/iphlp.rs b/crates/compat/compat-common/src/netview/iphlp.rs new file mode 100644 index 00000000..b8390f9c --- /dev/null +++ b/crates/compat/compat-common/src/netview/iphlp.rs @@ -0,0 +1,571 @@ +use super::*; +use core::ffi::c_void; +use std::sync::Mutex; + +pub const IF_ROW2_SIZE: usize = 0x548; +pub const IF_ROW_SIZE: usize = 0x360; +pub const IF_TABLE2_HEADER: usize = 8; +pub const ERROR_FILE_NOT_FOUND: u32 = 2; +pub const ERROR_INVALID_HANDLE: u32 = 6; +pub const ERROR_NOT_ENOUGH_MEMORY: u32 = 8; +pub const ERROR_NETWORK_UNREACHABLE: u32 = 1231; +pub const MIB_IF_ENTRY_NORMAL: u32 = 0; +pub const MIB_IF_ENTRY_NORMAL_WITHOUT_STATISTICS: u32 = 2; +pub const MIB_IF_OPER_STATUS_OPERATIONAL: u32 = 5; +pub const SIO_ADDRESS_LIST_SORT: u32 = 0xC800_0019; +pub const NPI_MS_IPV4_MODULEID: [u8; 24] = [0x18, 0, 0, 0, 1, 0, 0, 0, 0x00, 0x4a, 0x00, 0xeb, 0x1a, 0x9b, 0xd4, 0x11, 0x91, 0x23, 0x00, 0x50, 0x04, 0x77, 0x59, 0xbc]; +pub const NPI_MS_IPV6_MODULEID: [u8; 24] = [0x18, 0, 0, 0, 1, 0, 0, 0, 0x01, 0x4a, 0x00, 0xeb, 0x1a, 0x9b, 0xd4, 0x11, 0x91, 0x23, 0x00, 0x50, 0x04, 0x77, 0x59, 0xbc]; +pub const NSI_STORE_ACTIVE: u32 = 1; +pub const NSI_SET_DEFAULT: u32 = 0; +pub const NL_INTERFACE_OBJECT: u32 = 7; +pub const NL_INTERFACE_RW_SIZE: usize = 0xf0; + +#[link(name = "kernel32")] +extern "system" { + fn GetProcessHeap() -> *mut c_void; + fn HeapAlloc(heap: *mut c_void, flags: u32, size: usize) -> *mut c_void; + fn HeapFree(heap: *mut c_void, flags: u32, mem: *mut c_void) -> i32; +} + +fn hex_nibble(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } +} + +pub fn parse_guid(text: &str) -> Option<[u8; 16]> { + let t = text.trim().trim_start_matches('{').trim_end_matches('}'); + let parts: Vec<&str> = t.split('-').collect(); + if parts.len() != 5 || parts.iter().map(|p| p.len()).collect::>() != [8, 4, 4, 4, 12] { + return None; + } + let hex: Vec = parts.concat().bytes().collect(); + let mut raw = [0u8; 16]; + for (i, r) in raw.iter_mut().enumerate() { + *r = (hex_nibble(hex[2 * i])? << 4) | hex_nibble(hex[2 * i + 1])?; + } + let mut g = raw; + g[0..4].copy_from_slice(&[raw[3], raw[2], raw[1], raw[0]]); + g[4..6].copy_from_slice(&[raw[5], raw[4]]); + g[6..8].copy_from_slice(&[raw[7], raw[6]]); + Some(g) +} + +pub fn interface_guid(a: &Adapter) -> [u8; 16] { + parse_guid(a.name).unwrap_or([0; 16]) +} + +pub fn find_adapter(luid: u64, if_index: u32) -> Option { + adapters().into_iter().find(|a| if luid != 0 { a.luid == luid } else { a.if_index == if_index }) +} + +fn put_wide(dst: &mut [u8], s: &str) { + for (i, c) in s.encode_utf16().take(dst.len() / 2 - 1).enumerate() { + dst[2 * i..2 * i + 2].copy_from_slice(&c.to_le_bytes()); + } +} + +fn put32(b: &mut [u8], o: usize, v: u32) { + b[o..o + 4].copy_from_slice(&v.to_le_bytes()); +} + +fn put64(b: &mut [u8], o: usize, v: u64) { + b[o..o + 8].copy_from_slice(&v.to_le_bytes()); +} + +pub struct IfMedia { + pub media_type: u32, + pub physical_medium: u32, + pub access_type: u32, + pub status_flags: u8, +} + +pub fn if_media(a: &Adapter) -> IfMedia { + if a.if_type == IF_TYPE_SOFTWARE_LOOPBACK { + IfMedia { media_type: 0, physical_medium: 0, access_type: 1, status_flags: 0 } + } else { + IfMedia { media_type: 0, physical_medium: 14, access_type: 2, status_flags: 0x1 | 0x4 } + } +} + +pub fn if_row2(a: &Adapter) -> Vec { + let mut r = vec![0u8; IF_ROW2_SIZE]; + let m = if_media(a); + put64(&mut r, 0, a.luid); + put32(&mut r, 8, a.if_index); + r[0xc..0x1c].copy_from_slice(&interface_guid(a)); + put_wide(&mut r[0x1c..0x21e], a.friendly_name); + put_wide(&mut r[0x21e..0x420], a.description); + put32(&mut r, 0x420, a.mac.len() as u32); + r[0x424..0x424 + a.mac.len()].copy_from_slice(a.mac); + r[0x444..0x444 + a.mac.len()].copy_from_slice(a.mac); + put32(&mut r, 0x464, a.mtu); + put32(&mut r, 0x468, a.if_type); + put32(&mut r, 0x46c, 0); + put32(&mut r, 0x470, m.media_type); + put32(&mut r, 0x474, m.physical_medium); + put32(&mut r, 0x478, m.access_type); + put32(&mut r, 0x47c, 0); + r[0x480] = m.status_flags; + put32(&mut r, 0x484, a.oper_status); + put32(&mut r, 0x488, 1); + put32(&mut r, 0x48c, 1); + r[0x490..0x4a0].copy_from_slice(&a.network_guid); + put32(&mut r, 0x4a0, a.connection_type); + put64(&mut r, 0x4a8, a.speed); + put64(&mut r, 0x4b0, a.speed); + r +} + +pub fn if_table2() -> Vec { + let rows = adapters(); + let mut t = vec![0u8; IF_TABLE2_HEADER + rows.len() * IF_ROW2_SIZE]; + put32(&mut t, 0, rows.len() as u32); + for (i, a) in rows.iter().enumerate() { + let o = IF_TABLE2_HEADER + i * IF_ROW2_SIZE; + t[o..o + IF_ROW2_SIZE].copy_from_slice(&if_row2(a)); + } + t +} + +pub fn if_row(a: &Adapter) -> Vec { + let mut r = vec![0u8; IF_ROW_SIZE]; + let g = interface_guid(a); + let name = format!("\\DEVICE\\TCPIP_{{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{}}}", u32::from_le_bytes([g[0], g[1], g[2], g[3]]), u16::from_le_bytes([g[4], g[5]]), u16::from_le_bytes([g[6], g[7]]), g[8], g[9], g[10..16].iter().map(|b| format!("{:02X}", b)).collect::()); + put_wide(&mut r[0..0x200], &name); + put32(&mut r, 0x200, a.if_index); + put32(&mut r, 0x204, a.if_type); + put32(&mut r, 0x208, a.mtu); + put32(&mut r, 0x20c, a.speed.min(u32::MAX as u64) as u32); + let n = a.mac.len().min(8); + put32(&mut r, 0x210, n as u32); + r[0x214..0x214 + n].copy_from_slice(&a.mac[..n]); + put32(&mut r, 0x21c, 1); + put32(&mut r, 0x220, if a.oper_status == IF_OPER_STATUS_UP { MIB_IF_OPER_STATUS_OPERATIONAL } else { 0 }); + let d = a.description.as_bytes(); + let dn = d.len().min(255); + put32(&mut r, 0x258, dn as u32 + 1); + r[0x25c..0x25c + dn].copy_from_slice(&d[..dn]); + r +} + +pub unsafe fn get_if_entry2_ex(level: u32, row: *mut u8) -> u32 { + if row.is_null() || !matches!(level, MIB_IF_ENTRY_NORMAL | MIB_IF_ENTRY_NORMAL_WITHOUT_STATISTICS) { + return ERROR_INVALID_PARAMETER; + } + let luid = core::ptr::read_unaligned(row as *const u64); + let index = core::ptr::read_unaligned(row.add(8) as *const u32); + if luid == 0 && index == 0 { + return ERROR_INVALID_PARAMETER; + } + match find_adapter(luid, index) { + Some(a) => { + let r = if_row2(&a); + core::ptr::copy_nonoverlapping(r.as_ptr(), row, IF_ROW2_SIZE); + ERROR_SUCCESS + } + None => ERROR_FILE_NOT_FOUND, + } +} + +pub unsafe fn get_if_entry2(row: *mut u8) -> u32 { + get_if_entry2_ex(MIB_IF_ENTRY_NORMAL, row) +} + +pub unsafe fn get_if_entry(row: *mut u8) -> u32 { + if row.is_null() { + return ERROR_INVALID_PARAMETER; + } + let index = core::ptr::read_unaligned(row.add(0x200) as *const u32); + match adapters().into_iter().find(|a| a.if_index == index) { + Some(a) => { + let r = if_row(&a); + core::ptr::copy_nonoverlapping(r.as_ptr(), row, IF_ROW_SIZE); + ERROR_SUCCESS + } + None => ERROR_INVALID_PARAMETER, + } +} + +pub unsafe fn get_if_table2(table: *mut *mut u8) -> u32 { + if table.is_null() { + return ERROR_INVALID_PARAMETER; + } + let t = if_table2(); + let p = HeapAlloc(GetProcessHeap(), 0, t.len()) as *mut u8; + if p.is_null() { + *table = core::ptr::null_mut(); + return ERROR_NOT_ENOUGH_MEMORY; + } + core::ptr::copy_nonoverlapping(t.as_ptr(), p, t.len()); + *table = p; + ERROR_SUCCESS +} + +pub unsafe fn free_mib_table(table: *mut c_void) { + if !table.is_null() { + HeapFree(GetProcessHeap(), 0, table); + } +} + +pub unsafe fn convert_interface_guid_to_luid(guid: *const [u8; 16], luid: *mut u64) -> u32 { + if guid.is_null() || luid.is_null() { + return ERROR_INVALID_PARAMETER; + } + let g = core::ptr::read_unaligned(guid); + match adapters().into_iter().find(|a| interface_guid(a) == g) { + Some(a) => { + core::ptr::write_unaligned(luid, a.luid); + ERROR_SUCCESS + } + None => ERROR_NOT_FOUND, + } +} + +pub unsafe fn convert_interface_luid_to_index(luid: *const u64, index: *mut u32) -> u32 { + if luid.is_null() || index.is_null() { + return ERROR_INVALID_PARAMETER; + } + let l = core::ptr::read_unaligned(luid); + match adapters().into_iter().find(|a| a.luid == l) { + Some(a) => { + core::ptr::write_unaligned(index, a.if_index); + ERROR_SUCCESS + } + None => ERROR_NOT_FOUND, + } +} + +fn interface_metric(r: &Route) -> u32 { + adapters().into_iter().find(|a| a.luid == r.luid).map(|a| if r.dest.is_ipv4() { a.ipv4_metric } else { a.ipv6_metric }).unwrap_or(0) +} + +pub fn best_route(ip: &IpAddr) -> Option { + let ip = match ip { + IpAddr::V6(v) => v.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(*ip), + _ => *ip, + }; + routes().into_iter().filter(|r| prefix_matches(&r.dest, r.prefix_len, &ip)).min_by_key(|r| (core::cmp::Reverse(r.prefix_len), r.metric + interface_metric(r))) +} + +pub unsafe fn sockaddr_to_ip(addr: *const u8) -> Option { + if addr.is_null() { + return None; + } + match core::ptr::read_unaligned(addr as *const u16) as u32 { + AF_INET => { + let b = core::ptr::read_unaligned(addr.add(4) as *const [u8; 4]); + Some(IpAddr::V4(Ipv4Addr::from(b))) + } + AF_INET6 => Some(IpAddr::V6(Ipv6Addr::from(core::ptr::read_unaligned(addr.add(8) as *const [u8; 16])))), + _ => None, + } +} + +pub unsafe fn get_best_interface_ex(dest: *const u8, index: *mut u32) -> u32 { + if index.is_null() { + return ERROR_INVALID_PARAMETER; + } + let Some(ip) = sockaddr_to_ip(dest) else { + return ERROR_INVALID_PARAMETER; + }; + match best_route(&ip) { + Some(r) => { + *index = r.if_index; + ERROR_SUCCESS + } + None => ERROR_NETWORK_UNREACHABLE, + } +} + +pub type PhysicalInterfaceCallback = unsafe extern "system" fn(*mut c_void, *const [u8; 16], u32); + +pub unsafe fn physical_interface_for_destination(dest: *const u8, out: *mut [u8; 16], handle: *mut usize) -> u32 { + if out.is_null() { + return ERROR_INVALID_PARAMETER; + } + if !handle.is_null() { + *handle = 0; + } + let Some(ip) = sockaddr_to_ip(dest) else { + return ERROR_INVALID_PARAMETER; + }; + let Some(r) = best_route(&ip) else { + return ERROR_NETWORK_UNREACHABLE; + }; + match adapters().into_iter().find(|a| a.luid == r.luid) { + Some(a) => { + core::ptr::write_unaligned(out, interface_guid(&a)); + ERROR_SUCCESS + } + None => ERROR_NETWORK_UNREACHABLE, + } +} + +pub unsafe fn close_physical_interface_for_destination(handle: *mut usize) -> u32 { + if handle.is_null() || *handle == 0 { + return ERROR_SUCCESS; + } + ERROR_INVALID_HANDLE +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct Policy { + pub precedence: u32, + pub label: u32, +} + +const POLICY: [([u8; 16], u8, u32, u32); 9] = [ + ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 128, 50, 0), + ([0; 16], 0, 40, 1), + ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0], 96, 35, 4), + ([0x20, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 30, 2), + ([0x20, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 32, 5, 5), + ([0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 7, 3, 13), + ([0; 16], 96, 1, 3), + ([0xfe, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 10, 1, 11), + ([0x3f, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 1, 12), +]; + +fn as_v6(ip: &IpAddr) -> Ipv6Addr { + match ip { + IpAddr::V4(v) => v.to_ipv6_mapped(), + IpAddr::V6(v) => *v, + } +} + +pub fn policy(ip: &IpAddr) -> Policy { + let v = IpAddr::V6(as_v6(ip)); + POLICY.iter().filter(|(p, len, _, _)| prefix_matches(&IpAddr::V6(Ipv6Addr::from(*p)), *len, &v)).max_by_key(|(_, len, _, _)| *len).map(|(_, _, precedence, label)| Policy { precedence: *precedence, label: *label }).unwrap_or(Policy { precedence: 40, label: 1 }) +} + +pub fn scope(ip: &IpAddr) -> u32 { + let v = as_v6(ip); + if let Some(m) = v.to_ipv4_mapped() { + let o = m.octets(); + return if o[0] == 127 || (o[0] == 169 && o[1] == 254) { 2 } else { 14 }; + } + let s = v.segments(); + if s[0] >> 8 == 0xff { + return (s[0] & 0xf) as u32; + } + if v.is_loopback() || (s[0] & 0xffc0) == 0xfe80 { + return 2; + } + if (s[0] & 0xffc0) == 0xfec0 { + return 5; + } + 14 +} + +pub fn source_for(dest: &IpAddr) -> Option { + let r = best_route(dest)?; + let a = adapters().into_iter().find(|a| a.luid == r.luid)?; + let want_v4 = match dest { + IpAddr::V4(_) => true, + IpAddr::V6(v) => v.to_ipv4_mapped().is_some(), + }; + let ds = scope(dest); + let mut c: Vec = a.unicast.iter().map(|u| u.addr).filter(|x| x.is_ipv4() == want_v4).collect(); + c.sort_by_key(|x| (scope(x) != ds, scope(x) < ds)); + c.first().map(|x| if want_v4 && dest.is_ipv6() { IpAddr::V6(as_v6(x)) } else { *x }) +} + +fn common_prefix(a: &Ipv6Addr, b: &Ipv6Addr) -> u32 { + let (x, y) = (u128::from_be_bytes(a.octets()), u128::from_be_bytes(b.octets())); + (x ^ y).leading_zeros().min(64) +} + +pub fn destination_order(a: &IpAddr, b: &IpAddr) -> core::cmp::Ordering { + use core::cmp::Ordering::*; + let (sa, sb) = (source_for(a), source_for(b)); + match (sa.is_some(), sb.is_some()) { + (true, false) => return Less, + (false, true) => return Greater, + (false, false) => return Equal, + _ => {} + } + let (sa, sb) = (sa.unwrap(), sb.unwrap()); + let m = |d: &IpAddr, s: &IpAddr| scope(d) == scope(s); + if m(a, &sa) != m(b, &sb) { + return if m(a, &sa) { Less } else { Greater }; + } + let l = |d: &IpAddr, s: &IpAddr| policy(d).label == policy(s).label; + if l(a, &sa) != l(b, &sb) { + return if l(a, &sa) { Less } else { Greater }; + } + let (pa, pb) = (policy(a).precedence, policy(b).precedence); + if pa != pb { + return pb.cmp(&pa); + } + let (ca, cb) = (scope(a), scope(b)); + if ca != cb { + return ca.cmp(&cb); + } + let native = |d: &IpAddr| as_v6(d).to_ipv4_mapped().is_none(); + if native(a) && native(b) && native(&sa) && native(&sb) { + let (la, lb) = (common_prefix(&as_v6(a), &as_v6(&sa)), common_prefix(&as_v6(b), &as_v6(&sb))); + if la != lb { + return lb.cmp(&la); + } + } + Equal +} + +pub unsafe fn address_list_sort(list: *mut u8, len: u32) -> Result { + if list.is_null() || (len as usize) < 4 { + return Err(ERROR_INVALID_PARAMETER); + } + let n = core::ptr::read_unaligned(list as *const i32); + if n < 0 { + return Err(ERROR_INVALID_PARAMETER); + } + let need = 8 + 16 * n as usize; + if (len as usize) < need { + return Err(ERROR_INVALID_PARAMETER); + } + let mut entries: Vec<[u8; 16]> = (0..n as usize).map(|i| core::ptr::read_unaligned(list.add(8 + 16 * i) as *const [u8; 16])).collect(); + let mut keyed: Vec<([u8; 16], Option)> = Vec::with_capacity(entries.len()); + for e in &entries { + let p = usize::from_le_bytes(e[0..8].try_into().unwrap()) as *const u8; + let l = i32::from_le_bytes(e[8..12].try_into().unwrap()); + if p.is_null() || l < 0x1c || core::ptr::read_unaligned(p as *const u16) as u32 != AF_INET6 { + return Err(ERROR_INVALID_PARAMETER); + } + keyed.push((*e, sockaddr_to_ip(p))); + } + keyed.sort_by(|x, y| destination_order(x.1.as_ref().unwrap(), y.1.as_ref().unwrap())); + for (i, (e, _)) in keyed.iter().enumerate() { + entries[i] = *e; + core::ptr::write_unaligned(list.add(8 + 16 * i) as *mut [u8; 16], *e); + } + Ok(need as u32) +} + +struct NsiRow { + module: [u8; 24], + object: u32, + key: Vec, + rw: Vec, +} + +static NSI_ROWS: Mutex> = Mutex::new(Vec::new()); + +fn ip_module(m: &[u8]) -> bool { + m == NPI_MS_IPV4_MODULEID || m == NPI_MS_IPV6_MODULEID +} + +#[allow(clippy::too_many_arguments)] +pub unsafe fn nsi_set_all_parameters(store: u32, action: u32, module: *const u8, object: u32, key: *const u8, key_len: u32, rw: *const u8, rw_len: u32) -> u32 { + if module.is_null() || key.is_null() || rw.is_null() { + return ERROR_INVALID_PARAMETER; + } + let m: [u8; 24] = core::ptr::read_unaligned(module as *const [u8; 24]); + if !ip_module(&m) || object != NL_INTERFACE_OBJECT { + return ERROR_NOT_FOUND; + } + if store != NSI_STORE_ACTIVE || action != NSI_SET_DEFAULT || key_len != 8 || rw_len as usize != NL_INTERFACE_RW_SIZE { + return ERROR_INVALID_PARAMETER; + } + let luid = core::ptr::read_unaligned(key as *const u64); + if !adapters().iter().any(|a| a.luid == luid) { + return ERROR_NOT_FOUND; + } + let new = core::slice::from_raw_parts(rw, NL_INTERFACE_RW_SIZE); + let k = luid.to_le_bytes().to_vec(); + let mut rows = NSI_ROWS.lock().unwrap_or_else(|e| e.into_inner()); + let idx = match rows.iter().position(|r| r.module == m && r.object == object && r.key == k) { + Some(i) => i, + None => { + rows.push(NsiRow { module: m, object, key: k, rw: vec![0xff; NL_INTERFACE_RW_SIZE] }); + rows.len() - 1 + } + }; + let cur = &mut rows[idx].rw; + for g in (0..NL_INTERFACE_RW_SIZE).step_by(4) { + if new[g..g + 4] != [0xff; 4] { + cur[g..g + 4].copy_from_slice(&new[g..g + 4]); + } + } + ERROR_SUCCESS +} + +pub fn nsi_interface_rw(module: &[u8; 24], luid: u64) -> Option> { + let k = luid.to_le_bytes().to_vec(); + NSI_ROWS.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|r| &r.module == module && r.object == NL_INTERFACE_OBJECT && r.key == k).map(|r| r.rw.clone()) +} + +pub fn nsi_reset() { + NSI_ROWS.lock().unwrap_or_else(|e| e.into_inner()).clear(); +} + +pub const SIO_ADDRESS_LIST_QUERY: u32 = 0x4800_0016; +pub const SIO_ADDRESS_LIST_CHANGE: u32 = 0x2800_0017; +pub const SIO_ROUTING_INTERFACE_QUERY: u32 = 0xC800_0014; +pub const SIO_ROUTING_INTERFACE_CHANGE: u32 = 0x8800_0015; + +pub fn local_addresses(family: u32) -> Vec<(IpAddr, u32)> { + adapters().into_iter().filter(|a| a.if_type != IF_TYPE_SOFTWARE_LOOPBACK).flat_map(|a| a.unicast.into_iter().map(move |u| (u.addr, scope_of(&u.addr, a.if_index)))).filter(|(ip, _)| family_matches(family, ip)).collect() +} + +pub fn address_list_size(family: u32) -> usize { + let a = local_addresses(family); + 8 + 16 * a.len() + a.iter().map(|(ip, _)| if ip.is_ipv4() { 16 } else { 28 }).sum::() +} + +pub unsafe fn write_address_list(family: u32, out: *mut u8, out_len: usize) -> Result { + let need = address_list_size(family); + if out.is_null() || out_len < need { + return Err(need); + } + let a = local_addresses(family); + core::ptr::write_bytes(out, 0, need); + core::ptr::write_unaligned(out as *mut i32, a.len() as i32); + let mut tail = 8 + 16 * a.len(); + for (i, (ip, sc)) in a.iter().enumerate() { + let b = sockaddr_bytes(ip, 0, *sc); + core::ptr::copy_nonoverlapping(b.as_ptr(), out.add(tail), b.len()); + core::ptr::write_unaligned(out.add(8 + 16 * i) as *mut usize, out.add(tail) as usize); + core::ptr::write_unaligned(out.add(16 + 16 * i) as *mut i32, b.len() as i32); + tail += b.len(); + } + Ok(need) +} + +pub fn routing_interface(dest: &IpAddr) -> Option> { + let src = source_for(dest)?; + let r = best_route(dest)?; + Some(sockaddr_bytes(&src, 0, scope_of(&src, r.if_index))) +} + +pub const ERROR_NOT_SUPPORTED: u32 = 50; + +#[allow(clippy::too_many_arguments)] +pub unsafe fn nsi_get_interface_rw(module: &[u8], object: u32, key: *const u8, key_len: u32, rw: *mut u8, rw_len: u32, rod: *mut u8, rod_len: u32, ros: *mut u8, ros_len: u32) -> u32 { + if object != NL_INTERFACE_OBJECT { + return ERROR_NOT_FOUND; + } + if key.is_null() || key_len != 8 || (rw.is_null() && rw_len != 0) || (!rw.is_null() && rw_len as usize != NL_INTERFACE_RW_SIZE) { + return ERROR_INVALID_PARAMETER; + } + if !rod.is_null() || rod_len != 0 || !ros.is_null() || ros_len != 0 { + return ERROR_NOT_SUPPORTED; + } + let m: [u8; 24] = module.try_into().unwrap_or([0; 24]); + let luid = core::ptr::read_unaligned(key as *const u64); + if !adapters().iter().any(|a| a.luid == luid) { + return ERROR_NOT_FOUND; + } + match nsi_interface_rw(&m, luid) { + Some(row) => { + if !rw.is_null() { + core::ptr::copy_nonoverlapping(row.as_ptr(), rw, NL_INTERFACE_RW_SIZE); + } + ERROR_SUCCESS + } + None => ERROR_NOT_FOUND, + } +} diff --git a/crates/compat/compat-common/src/netview/mod.rs b/crates/compat/compat-common/src/netview/mod.rs new file mode 100644 index 00000000..9289812a --- /dev/null +++ b/crates/compat/compat-common/src/netview/mod.rs @@ -0,0 +1,512 @@ +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +pub mod iphlp; +pub mod sockets; +pub mod wfp; +pub(crate) mod wfp_codec; +pub mod wfp_names; + +#[cfg(test)] +mod tests; + +pub const AF_UNSPEC: u32 = 0; +pub const AF_INET: u32 = 2; +pub const AF_INET6: u32 = 23; + +pub const ERROR_SUCCESS: u32 = 0; +pub const ERROR_NOT_READY: u32 = 0x15; +pub const ERROR_INVALID_PARAMETER: u32 = 87; +pub const ERROR_BUFFER_OVERFLOW: u32 = 111; +pub const ERROR_INSUFFICIENT_BUFFER: u32 = 122; +pub const ERROR_NOT_FOUND: u32 = 1168; + +pub const GAA_FLAG_SKIP_UNICAST: u32 = 0x1; +pub const GAA_FLAG_SKIP_ANYCAST: u32 = 0x2; +pub const GAA_FLAG_SKIP_MULTICAST: u32 = 0x4; +pub const GAA_FLAG_SKIP_DNS_SERVER: u32 = 0x8; +pub const GAA_FLAG_INCLUDE_PREFIX: u32 = 0x10; +pub const GAA_FLAG_SKIP_FRIENDLY_NAME: u32 = 0x20; + +pub const IF_TYPE_ETHERNET_CSMACD: u32 = 6; +pub const IF_TYPE_SOFTWARE_LOOPBACK: u32 = 24; +pub const IF_OPER_STATUS_UP: u32 = 1; + +pub const ADAPTER_SIZE: usize = 0x1c0; +pub const UNICAST_SIZE: usize = 0x40; +pub const MULTICAST_SIZE: usize = 0x20; +pub const PREFIX_SIZE: usize = 0x28; +pub const ROUTE_ROW_SIZE: usize = 0x68; + +pub const NIC_IF_INDEX: u32 = 2; +pub const LOOPBACK_IF_INDEX: u32 = 1; +pub const NIC_MAC: [u8; 6] = [0x02, 0x54, 0x42, 0x00, 0x00, 0x01]; +pub const NIC_IPV4: Ipv4Addr = Ipv4Addr::new(169, 254, 66, 1); +pub const NIC_IPV6: Ipv6Addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0x0054, 0x42ff, 0xfe00, 0x0001); + +pub const TEREDO_STATE_OFFLINE: u32 = 0; +pub const TEREDO_STATE_QUALIFIED: u32 = 5; +pub const NSI_TEREDO_OBJECT_STATE: u32 = 1; +pub const NSI_TEREDO_OBJECT_PORT: u32 = 3; +pub const NPI_MS_TEREDO_MODULEID: [u8; 24] = [0x18, 0, 0, 0, 1, 0, 0, 0, 0x1c, 0x4a, 0x00, 0xeb, 0x1a, 0x9b, 0xd4, 0x11, 0x91, 0x23, 0x00, 0x50, 0x04, 0x77, 0x59, 0xbc]; + +#[derive(Clone, Debug, PartialEq)] +pub struct Unicast { + pub addr: IpAddr, + pub prefix_len: u8, + pub prefix_origin: u32, + pub suffix_origin: u32, + pub dad_state: u32, + pub flags: u32, + pub valid: u32, + pub preferred: u32, + pub lease: u32, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Adapter { + pub if_index: u32, + pub ipv6_if_index: u32, + pub luid: u64, + pub name: &'static str, + pub network_guid: [u8; 16], + pub friendly_name: &'static str, + pub description: &'static str, + pub if_type: u32, + pub oper_status: u32, + pub mtu: u32, + pub mac: &'static [u8], + pub flags: u32, + pub speed: u64, + pub ipv4_metric: u32, + pub ipv6_metric: u32, + pub connection_type: u32, + pub unicast: Vec, + pub multicast: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Route { + pub luid: u64, + pub if_index: u32, + pub dest: IpAddr, + pub prefix_len: u8, + pub next_hop: IpAddr, + pub metric: u32, + pub loopback: bool, +} + +pub const ROUTE_PROTOCOL_LOCAL: u32 = 2; +pub const ROUTE_ORIGIN_WELL_KNOWN: u32 = 2; +pub const INFINITE_LIFETIME: u32 = 0xffff_ffff; + +const fn luid(if_type: u32, index: u32) -> u64 { + ((if_type as u64) << 48) | ((index as u64) << 24) +} + +pub const NIC_LUID: u64 = luid(IF_TYPE_ETHERNET_CSMACD, 1); +pub const LOOPBACK_LUID: u64 = luid(IF_TYPE_SOFTWARE_LOOPBACK, 0); + +fn unicast(addr: IpAddr, prefix_len: u8, prefix_origin: u32, suffix_origin: u32) -> Unicast { + Unicast { addr, prefix_len, prefix_origin, suffix_origin, dad_state: 4, flags: 0, valid: INFINITE_LIFETIME, preferred: INFINITE_LIFETIME, lease: INFINITE_LIFETIME } +} + +pub fn adapters() -> Vec { + vec![ + Adapter { + if_index: NIC_IF_INDEX, + ipv6_if_index: NIC_IF_INDEX, + luid: NIC_LUID, + name: "{5A6F8E2C-1B3D-4E59-9C70-546F6D426F78}", + network_guid: [0x2c, 0x8e, 0x6f, 0x5a, 0x3d, 0x1b, 0x59, 0x4e, 0x9c, 0x70, 0x54, 0x6f, 0x6d, 0x42, 0x6f, 0x78], + friendly_name: "Ethernet", + description: "TomBox Emulated Console Network Adapter", + if_type: IF_TYPE_ETHERNET_CSMACD, + oper_status: IF_OPER_STATUS_UP, + mtu: 1500, + mac: &NIC_MAC, + flags: 0x1 | 0x2 | 0x4 | 0x80 | 0x100, + speed: 1_000_000_000, + ipv4_metric: 25, + ipv6_metric: 25, + connection_type: 1, + unicast: vec![unicast(IpAddr::V6(NIC_IPV6), 64, 2, 4), unicast(IpAddr::V4(NIC_IPV4), 16, 2, 4)], + multicast: vec![IpAddr::V6(Ipv6Addr::new(0xff01, 0, 0, 0, 0, 0, 0, 1)), IpAddr::V6(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1)), IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1))], + }, + Adapter { + if_index: LOOPBACK_IF_INDEX, + ipv6_if_index: LOOPBACK_IF_INDEX, + luid: LOOPBACK_LUID, + name: "{6C6F6F70-6261-636B-2054-6F6D426F7801}", + network_guid: [0; 16], + friendly_name: "Loopback Pseudo-Interface 1", + description: "Software Loopback Interface 1", + if_type: IF_TYPE_SOFTWARE_LOOPBACK, + oper_status: IF_OPER_STATUS_UP, + mtu: 0xffff_ffff, + mac: &[], + flags: 0x80 | 0x100, + speed: 1_073_741_824, + ipv4_metric: 75, + ipv6_metric: 75, + connection_type: 1, + unicast: vec![unicast(IpAddr::V6(Ipv6Addr::LOCALHOST), 128, 2, 2), unicast(IpAddr::V4(Ipv4Addr::LOCALHOST), 8, 2, 2)], + multicast: vec![IpAddr::V6(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 0xc)), IpAddr::V4(Ipv4Addr::new(239, 255, 255, 250))], + }, + ] +} + +fn route(luid: u64, if_index: u32, dest: IpAddr, prefix_len: u8, metric: u32, loopback: bool) -> Route { + let next_hop = match dest { + IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::UNSPECIFIED), + IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::UNSPECIFIED), + }; + Route { luid, if_index, dest, prefix_len, next_hop, metric, loopback } +} + +pub fn routes() -> Vec { + let v4 = |a, b, c, d| IpAddr::V4(Ipv4Addr::new(a, b, c, d)); + let (n, ni, l, li) = (NIC_LUID, NIC_IF_INDEX, LOOPBACK_LUID, LOOPBACK_IF_INDEX); + vec![ + route(l, li, v4(127, 0, 0, 0), 8, 256, true), + route(l, li, v4(127, 0, 0, 1), 32, 256, true), + route(l, li, v4(127, 255, 255, 255), 32, 256, true), + route(n, ni, v4(169, 254, 0, 0), 16, 256, false), + route(n, ni, IpAddr::V4(NIC_IPV4), 32, 256, true), + route(n, ni, v4(169, 254, 255, 255), 32, 256, false), + route(l, li, v4(224, 0, 0, 0), 4, 256, true), + route(n, ni, v4(224, 0, 0, 0), 4, 256, false), + route(l, li, v4(255, 255, 255, 255), 32, 256, true), + route(n, ni, v4(255, 255, 255, 255), 32, 256, false), + route(l, li, IpAddr::V6(Ipv6Addr::LOCALHOST), 128, 256, true), + route(n, ni, IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0)), 64, 256, false), + route(n, ni, IpAddr::V6(NIC_IPV6), 128, 256, true), + route(l, li, IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)), 8, 256, true), + route(n, ni, IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)), 8, 256, false), + ] +} + +pub fn has_route_to(ip: &IpAddr) -> bool { + routes().iter().any(|r| prefix_matches(&r.dest, r.prefix_len, ip)) +} + +fn prefix_matches(net: &IpAddr, len: u8, ip: &IpAddr) -> bool { + let (a, b, bits): (Vec, Vec, usize) = match (net, ip) { + (IpAddr::V4(n), IpAddr::V4(i)) => (n.octets().to_vec(), i.octets().to_vec(), 32), + (IpAddr::V6(n), IpAddr::V6(i)) => (n.octets().to_vec(), i.octets().to_vec(), 128), + _ => return false, + }; + let len = (len as usize).min(bits); + (0..len).all(|k| (a[k / 8] >> (7 - k % 8)) & 1 == (b[k / 8] >> (7 - k % 8)) & 1) +} + +fn family_matches(family: u32, ip: &IpAddr) -> bool { + match family { + AF_INET => ip.is_ipv4(), + AF_INET6 => ip.is_ipv6(), + _ => true, + } +} + +pub fn sockaddr_bytes(ip: &IpAddr, port: u16, scope: u32) -> Vec { + match ip { + IpAddr::V4(a) => { + let mut b = vec![0u8; 16]; + b[0..2].copy_from_slice(&(AF_INET as u16).to_le_bytes()); + b[2..4].copy_from_slice(&port.to_be_bytes()); + b[4..8].copy_from_slice(&a.octets()); + b + } + IpAddr::V6(a) => { + let mut b = vec![0u8; 28]; + b[0..2].copy_from_slice(&(AF_INET6 as u16).to_le_bytes()); + b[2..4].copy_from_slice(&port.to_be_bytes()); + b[8..24].copy_from_slice(&a.octets()); + b[24..28].copy_from_slice(&scope.to_le_bytes()); + b + } + } +} + +pub fn scope_of(ip: &IpAddr, if_index: u32) -> u32 { + match ip { + IpAddr::V6(a) if (a.segments()[0] & 0xffc0) == 0xfe80 || (a.segments()[0] & 0xff0f) == 0xff02 => if_index, + _ => 0, + } +} + +fn wide(s: &str) -> Vec { + let mut v: Vec = s.encode_utf16().flat_map(|c| c.to_le_bytes()).collect(); + v.extend_from_slice(&[0, 0]); + v +} + +fn align8(n: usize) -> usize { + (n + 7) & !7 +} + +struct Writer { + base: usize, + buf: Vec, +} + +impl Writer { + fn alloc(&mut self, n: usize) -> usize { + let o = align8(self.buf.len()); + self.buf.resize(o + n, 0); + o + } + fn put(&mut self, o: usize, b: &[u8]) { + self.buf[o..o + b.len()].copy_from_slice(b); + } + fn u32(&mut self, o: usize, v: u32) { + self.put(o, &v.to_le_bytes()); + } + fn u64(&mut self, o: usize, v: u64) { + self.put(o, &v.to_le_bytes()); + } + fn ptr(&mut self, o: usize, target: usize) { + let v = (self.base + target) as u64; + self.u64(o, v); + } + fn blob(&mut self, b: &[u8]) -> usize { + let o = self.alloc(b.len()); + self.put(o, b); + o + } + fn socket_address(&mut self, at: usize, ip: &IpAddr, scope: u32) { + let sa = sockaddr_bytes(ip, 0, scope); + let o = self.blob(&sa); + self.ptr(at, o); + self.u32(at + 8, sa.len() as u32); + } +} + +fn build_adapters(base: usize, family: u32, flags: u32) -> Vec { + let list = adapters(); + let mut w = Writer { base, buf: Vec::new() }; + let heads: Vec = list.iter().map(|_| w.alloc(ADAPTER_SIZE)).collect(); + for (i, a) in list.iter().enumerate() { + let h = heads[i]; + w.u32(h, ADAPTER_SIZE as u32); + w.u32(h + 4, a.if_index); + if i + 1 < heads.len() { + w.ptr(h + 8, heads[i + 1]); + } + let mut name = a.name.as_bytes().to_vec(); + name.push(0); + let o = w.blob(&name); + w.ptr(h + 0x10, o); + if flags & GAA_FLAG_SKIP_UNICAST == 0 { + let us: Vec<&Unicast> = a.unicast.iter().filter(|u| family_matches(family, &u.addr)).collect(); + let entries: Vec = us.iter().map(|_| w.alloc(UNICAST_SIZE)).collect(); + for (k, u) in us.iter().enumerate() { + let e = entries[k]; + w.u32(e, UNICAST_SIZE as u32); + w.u32(e + 4, u.flags); + if k + 1 < entries.len() { + w.ptr(e + 8, entries[k + 1]); + } + w.socket_address(e + 0x10, &u.addr, scope_of(&u.addr, a.if_index)); + w.u32(e + 0x20, u.prefix_origin); + w.u32(e + 0x24, u.suffix_origin); + w.u32(e + 0x28, u.dad_state); + w.u32(e + 0x2c, u.valid); + w.u32(e + 0x30, u.preferred); + w.u32(e + 0x34, u.lease); + w.buf[e + 0x38] = u.prefix_len; + } + if let Some(f) = entries.first() { + w.ptr(h + 0x18, *f); + } + } + if flags & GAA_FLAG_SKIP_MULTICAST == 0 { + let ms: Vec<&IpAddr> = a.multicast.iter().filter(|m| family_matches(family, m)).collect(); + let entries: Vec = ms.iter().map(|_| w.alloc(MULTICAST_SIZE)).collect(); + for (k, m) in ms.iter().enumerate() { + let e = entries[k]; + w.u32(e, MULTICAST_SIZE as u32); + if k + 1 < entries.len() { + w.ptr(e + 8, entries[k + 1]); + } + w.socket_address(e + 0x10, m, scope_of(m, a.if_index)); + } + if let Some(f) = entries.first() { + w.ptr(h + 0x28, *f); + } + } + let o = w.blob(&wide("")); + w.ptr(h + 0x38, o); + let o = w.blob(&wide(a.description)); + w.ptr(h + 0x40, o); + let o = w.blob(&wide(if flags & GAA_FLAG_SKIP_FRIENDLY_NAME == 0 { a.friendly_name } else { "" })); + w.ptr(h + 0x48, o); + w.put(h + 0x50, a.mac); + w.u32(h + 0x58, a.mac.len() as u32); + w.u32(h + 0x5c, a.flags); + w.u32(h + 0x60, a.mtu); + w.u32(h + 0x64, a.if_type); + w.u32(h + 0x68, a.oper_status); + w.u32(h + 0x6c, a.ipv6_if_index); + for z in 0..16usize { + let v = match z { + 1..=3 => a.if_index, + 4..=13 => 1, + _ => 0, + }; + w.u32(h + 0x70 + z * 4, v); + } + if flags & GAA_FLAG_INCLUDE_PREFIX != 0 { + let ps: Vec<(IpAddr, u8)> = a.unicast.iter().filter(|u| family_matches(family, &u.addr)).map(|u| (network_of(&u.addr, u.prefix_len), u.prefix_len)).collect(); + let entries: Vec = ps.iter().map(|_| w.alloc(PREFIX_SIZE)).collect(); + for (k, (p, len)) in ps.iter().enumerate() { + let e = entries[k]; + w.u32(e, PREFIX_SIZE as u32); + if k + 1 < entries.len() { + w.ptr(e + 8, entries[k + 1]); + } + w.socket_address(e + 0x10, p, 0); + w.u32(e + 0x20, *len as u32); + } + if let Some(f) = entries.first() { + w.ptr(h + 0xb0, *f); + } + } + w.u64(h + 0xb8, a.speed); + w.u64(h + 0xc0, a.speed); + w.u32(h + 0xd8, a.ipv4_metric); + w.u32(h + 0xdc, a.ipv6_metric); + w.u64(h + 0xe0, a.luid); + w.u32(h + 0xf8, 1); + w.put(h + 0xfc, &a.network_guid); + w.u32(h + 0x10c, a.connection_type); + } + w.buf +} + +fn network_of(ip: &IpAddr, len: u8) -> IpAddr { + let mask = |b: &mut [u8], len: usize| { + for (k, x) in b.iter_mut().enumerate() { + let keep = len.saturating_sub(k * 8).min(8); + *x &= if keep == 0 { 0 } else { 0xffu8 << (8 - keep) }; + } + }; + match ip { + IpAddr::V4(a) => { + let mut o = a.octets(); + mask(&mut o, len as usize); + IpAddr::V4(Ipv4Addr::from(o)) + } + IpAddr::V6(a) => { + let mut o = a.octets(); + mask(&mut o, len as usize); + IpAddr::V6(Ipv6Addr::from(o)) + } + } +} + +pub fn adapters_addresses_size(family: u32, flags: u32) -> usize { + build_adapters(0, family, flags).len() +} + +pub unsafe fn get_adapters_addresses(family: u32, flags: u32, buf: *mut u8, size: *mut u32) -> u32 { + if size.is_null() || !matches!(family, AF_UNSPEC | AF_INET | AF_INET6) { + return ERROR_INVALID_PARAMETER; + } + let need = adapters_addresses_size(family, flags); + if buf.is_null() || (*size as usize) < need { + *size = need as u32; + return ERROR_BUFFER_OVERFLOW; + } + let bytes = build_adapters(buf as usize, family, flags); + core::ptr::copy_nonoverlapping(bytes.as_ptr(), buf, bytes.len()); + ERROR_SUCCESS +} + +fn sockaddr_inet(ip: &IpAddr, scope: u32) -> [u8; 28] { + let mut out = [0u8; 28]; + let b = sockaddr_bytes(ip, 0, scope); + out[..b.len()].copy_from_slice(&b); + out +} + +pub fn ip_forward_table2(family: u32) -> Result, u32> { + if !matches!(family, AF_UNSPEC | AF_INET | AF_INET6) { + return Err(ERROR_INVALID_PARAMETER); + } + let rows: Vec = routes().into_iter().filter(|r| family_matches(family, &r.dest)).collect(); + let mut t = vec![0u8; 8 + rows.len() * ROUTE_ROW_SIZE]; + t[0..4].copy_from_slice(&(rows.len() as u32).to_le_bytes()); + for (i, r) in rows.iter().enumerate() { + let o = 8 + i * ROUTE_ROW_SIZE; + let row = &mut t[o..o + ROUTE_ROW_SIZE]; + row[0..8].copy_from_slice(&r.luid.to_le_bytes()); + row[8..0xc].copy_from_slice(&r.if_index.to_le_bytes()); + row[0xc..0x28].copy_from_slice(&sockaddr_inet(&r.dest, scope_of(&r.dest, r.if_index))); + row[0x28] = r.prefix_len; + row[0x2c..0x48].copy_from_slice(&sockaddr_inet(&r.next_hop, 0)); + row[0x4c..0x50].copy_from_slice(&INFINITE_LIFETIME.to_le_bytes()); + row[0x50..0x54].copy_from_slice(&INFINITE_LIFETIME.to_le_bytes()); + row[0x54..0x58].copy_from_slice(&r.metric.to_le_bytes()); + row[0x58..0x5c].copy_from_slice(&ROUTE_PROTOCOL_LOCAL.to_le_bytes()); + row[0x5c] = r.loopback as u8; + row[0x5d] = 1; + row[0x5e] = 0; + row[0x5f] = 1; + row[0x64..0x68].copy_from_slice(&ROUTE_ORIGIN_WELL_KNOWN.to_le_bytes()); + } + Ok(t) +} + +pub fn teredo_state() -> u32 { + TEREDO_STATE_OFFLINE +} + +pub fn teredo_rw_parameters() -> [u8; 12] { + let mut b = [0u8; 12]; + b[0..4].copy_from_slice(&teredo_state().to_le_bytes()); + b +} + +pub fn teredo_port() -> Option { + None +} + +#[allow(clippy::too_many_arguments)] +pub unsafe fn nsi_get_all_parameters(_store: u32, module: *const u8, object: u32, key: *const u8, key_len: u32, rw: *mut u8, rw_len: u32, rod: *mut u8, rod_len: u32, ros: *mut u8, ros_len: u32) -> u32 { + if module.is_null() { + return ERROR_INVALID_PARAMETER; + } + let id = core::slice::from_raw_parts(module, NPI_MS_TEREDO_MODULEID.len()); + if id == iphlp::NPI_MS_IPV4_MODULEID || id == iphlp::NPI_MS_IPV6_MODULEID { + return iphlp::nsi_get_interface_rw(id, object, key, key_len, rw, rw_len, rod, rod_len, ros, ros_len); + } + if id != NPI_MS_TEREDO_MODULEID { + return ERROR_NOT_FOUND; + } + if !key.is_null() || key_len != 0 || !rod.is_null() || rod_len != 0 || !ros.is_null() || ros_len != 0 { + return ERROR_INVALID_PARAMETER; + } + match object { + NSI_TEREDO_OBJECT_STATE => { + if rw.is_null() || rw_len != 12 { + return ERROR_INVALID_PARAMETER; + } + let p = teredo_rw_parameters(); + core::ptr::copy_nonoverlapping(p.as_ptr(), rw, p.len()); + ERROR_SUCCESS + } + NSI_TEREDO_OBJECT_PORT => { + if rw.is_null() || rw_len != 2 { + return ERROR_INVALID_PARAMETER; + } + match teredo_port() { + Some(p) => { + core::ptr::copy_nonoverlapping(p.to_le_bytes().as_ptr(), rw, 2); + ERROR_SUCCESS + } + None => ERROR_NOT_READY, + } + } + _ => ERROR_NOT_FOUND, + } +} diff --git a/crates/compat/compat-common/src/netview/sockets.rs b/crates/compat/compat-common/src/netview/sockets.rs new file mode 100644 index 00000000..bce794a8 --- /dev/null +++ b/crates/compat/compat-common/src/netview/sockets.rs @@ -0,0 +1,665 @@ +use core::ffi::c_void; +use core::sync::atomic::{AtomicU32, Ordering}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; +use std::sync::OnceLock; + +use super::{AF_INET, AF_INET6, AF_UNSPEC, ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PARAMETER, ERROR_SUCCESS, NIC_IPV4, NIC_IPV6, NIC_IF_INDEX}; + +extern "system" { + fn CreateFileMappingW(file: *mut c_void, sa: *mut c_void, protect: u32, high: u32, low: u32, name: *const u16) -> *mut c_void; + fn MapViewOfFile(h: *mut c_void, access: u32, high: u32, low: u32, n: usize) -> *mut c_void; + fn GetCurrentProcessId() -> u32; + fn GetSystemTimeAsFileTime(t: *mut u64); + fn GetModuleHandleA(name: *const u8) -> *mut c_void; + fn GetProcAddress(h: *mut c_void, name: *const u8) -> *mut c_void; +} + +pub const MIB_TCP_STATE_LISTEN: u32 = 2; +pub const MIB_TCP_STATE_SYN_SENT: u32 = 3; +pub const MIB_TCP_STATE_ESTAB: u32 = 5; +pub const MIB_TCP_STATE_RESERVED: u32 = 100; +pub const SIO_TCP_INFO: u32 = 0xD800_0027; +pub const SO_CONNECT_TIME: i32 = 0x700C; +pub const SO_ERROR: i32 = 0x1007; +pub const TCPSTATE_CLOSED: u32 = 0; +pub const TCPSTATE_SYN_SENT: u32 = 2; +pub const TCPSTATE_SYN_RCVD: u32 = 3; + +pub const TCP_TABLE_OWNER_PID_LISTENER: u32 = 3; +pub const TCP_TABLE_OWNER_PID_CONNECTIONS: u32 = 4; +pub const TCP_TABLE_OWNER_PID_ALL: u32 = 5; +pub const TCP_TABLE_OWNER_MODULE_LISTENER: u32 = 6; +pub const TCP_TABLE_OWNER_MODULE_CONNECTIONS: u32 = 7; +pub const TCP_TABLE_OWNER_MODULE_ALL: u32 = 8; +pub const UDP_TABLE_OWNER_PID: u32 = 1; +pub const UDP_TABLE_OWNER_MODULE: u32 = 2; + +pub const TCP_ROW_OWNER_MODULE_SIZE: usize = 0xa0; +pub const TCP6_ROW_OWNER_MODULE_SIZE: usize = 0xc0; +pub const UDP_ROW_OWNER_MODULE_SIZE: usize = 0xa0; +pub const UDP6_ROW_OWNER_MODULE_SIZE: usize = 0xb0; +pub const TCP_ROW_OWNER_PID_SIZE: usize = 24; +pub const TCP6_ROW_OWNER_PID_SIZE: usize = 56; +pub const UDP_ROW_OWNER_PID_SIZE: usize = 12; +pub const UDP6_ROW_OWNER_PID_SIZE: usize = 28; + +const SOCK_STREAM: i32 = 1; +const SOCK_DGRAM: i32 = 2; +const SOL_SOCKET: i32 = 0xffff; +const SO_TYPE: i32 = 0x1008; +const SO_ACCEPTCONN: i32 = 0x0002; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Proto { + Tcp, + Udp, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Endpoint { + pub socket: u64, + pub pid: u32, + pub proto: Proto, + pub local: SocketAddr, + pub remote: Option, + pub state: u32, + pub created: u64, +} + +const CAPACITY: usize = 256; + +#[cfg(test)] +pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[repr(C)] +#[derive(Clone, Copy)] +struct Slot { + socket: u64, + created: u64, + pid: u32, + proto: u8, + family: u8, + used: u8, + has_remote: u8, + state: u32, + local: [u8; 16], + local_scope: u32, + local_port: u16, + remote_port: u16, + remote: [u8; 16], + remote_scope: u32, +} + +#[repr(C)] +struct Shared { + lock: AtomicU32, + slots: [Slot; CAPACITY], +} + +fn shared() -> Option<&'static Shared> { + static P: OnceLock = OnceLock::new(); + let p = *P.get_or_init(|| unsafe { + let name: Vec = format!("Local\\TomBox.NetView.Sockets.{}", GetCurrentProcessId()).encode_utf16().chain(Some(0)).collect(); + let size = core::mem::size_of::() as u32; + let h = CreateFileMappingW(-1isize as *mut c_void, core::ptr::null_mut(), 0x04, 0, size, name.as_ptr()); + if h.is_null() { + return 0; + } + MapViewOfFile(h, 0x0006, 0, 0, size as usize) as usize + }); + if p == 0 { + None + } else { + Some(unsafe { &*(p as *const Shared) }) + } +} + +fn with_slots(f: impl FnOnce(&mut [Slot; CAPACITY]) -> R) -> Option { + let s = shared()?; + while s.lock.compare_exchange(0, 1, Ordering::Acquire, Ordering::Relaxed).is_err() { + std::thread::yield_now(); + } + let slots = unsafe { &mut *(core::ptr::addr_of!(s.slots) as *mut [Slot; CAPACITY]) }; + let r = f(slots); + s.lock.store(0, Ordering::Release); + Some(r) +} + +fn split(a: &SocketAddr) -> (u8, [u8; 16], u32, u16) { + match a { + SocketAddr::V4(v) => { + let mut b = [0u8; 16]; + b[..4].copy_from_slice(&v.ip().octets()); + (AF_INET as u8, b, 0, v.port()) + } + SocketAddr::V6(v) => (AF_INET6 as u8, v.ip().octets(), v.scope_id(), v.port()), + } +} + +fn join(family: u8, b: [u8; 16], scope: u32, port: u16) -> SocketAddr { + if family as u32 == AF_INET { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(b[0], b[1], b[2], b[3]), port)) + } else { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from(b), port, 0, scope)) + } +} + +fn to_slot(e: &Endpoint) -> Slot { + let (family, local, local_scope, local_port) = split(&e.local); + let (has_remote, remote, remote_scope, remote_port) = match &e.remote { + Some(r) => { + let (_, b, s, p) = split(r); + (1, b, s, p) + } + None => (0, [0u8; 16], 0, 0), + }; + Slot { socket: e.socket, created: e.created, pid: e.pid, proto: (e.proto == Proto::Udp) as u8, family, used: 1, has_remote, state: e.state, local, local_scope, local_port, remote_port, remote, remote_scope } +} + +fn from_slot(s: &Slot) -> Endpoint { + Endpoint { + socket: s.socket, + pid: s.pid, + proto: if s.proto == 1 { Proto::Udp } else { Proto::Tcp }, + local: join(s.family, s.local, s.local_scope, s.local_port), + remote: if s.has_remote == 1 { Some(join(s.family, s.remote, s.remote_scope, s.remote_port)) } else { None }, + state: s.state, + created: s.created, + } +} + +pub fn now_filetime() -> u64 { + let mut t = 0u64; + unsafe { GetSystemTimeAsFileTime(&mut t) }; + t +} + +pub fn console_local(a: SocketAddr) -> SocketAddr { + match a { + SocketAddr::V4(v) if !v.ip().is_loopback() && !v.ip().is_unspecified() => SocketAddr::V4(SocketAddrV4::new(NIC_IPV4, v.port())), + SocketAddr::V6(v) if !v.ip().is_loopback() && !v.ip().is_unspecified() && v.ip().to_ipv4_mapped().map(|m| !m.is_loopback()).unwrap_or(true) => SocketAddr::V6(SocketAddrV6::new(NIC_IPV6, v.port(), 0, NIC_IF_INDEX)), + other => other, + } +} + +pub fn report(e: Endpoint) -> bool { + let slot = to_slot(&e); + with_slots(|slots| { + if let Some(s) = slots.iter_mut().find(|s| s.used == 1 && s.socket == e.socket && s.pid == e.pid) { + *s = slot; + return true; + } + match slots.iter_mut().find(|s| s.used == 0) { + Some(s) => { + *s = slot; + true + } + None => false, + } + }) + .unwrap_or(false) +} + +pub fn forget(socket: u64) { + let pid = unsafe { GetCurrentProcessId() }; + with_slots(|slots| { + for s in slots.iter_mut().filter(|s| s.used == 1 && s.socket == socket && s.pid == pid) { + s.used = 0; + } + }); +} + +pub fn snapshot() -> Vec { + with_slots(|slots| slots.iter().filter(|s| s.used == 1).map(from_slot).collect()).unwrap_or_default() +} + +type GetSockOpt = unsafe extern "system" fn(usize, i32, i32, *mut u8, *mut i32) -> i32; +type GetSockName = unsafe extern "system" fn(usize, *mut u8, *mut i32) -> i32; + +fn ws_fn(name: &[u8]) -> usize { + unsafe { + let m = GetModuleHandleA(b"ws2_32.dll\0".as_ptr()); + if m.is_null() { + return 0; + } + GetProcAddress(m, name.as_ptr()) as usize + } +} + +unsafe fn socket_type(s: usize) -> Option { + let f = ws_fn(b"getsockopt\0"); + if f == 0 { + return None; + } + let f: GetSockOpt = core::mem::transmute(f); + let mut t = 0i32; + let mut n = 4i32; + if f(s, SOL_SOCKET, SO_TYPE, &mut t as *mut i32 as *mut u8, &mut n) != 0 { + return None; + } + Some(t) +} + +unsafe fn accepting(s: usize) -> bool { + let f = ws_fn(b"getsockopt\0"); + if f == 0 { + return false; + } + let f: GetSockOpt = core::mem::transmute(f); + let mut v = 0i32; + let mut n = 4i32; + f(s, SOL_SOCKET, SO_ACCEPTCONN, &mut v as *mut i32 as *mut u8, &mut n) == 0 && v != 0 +} + +pub unsafe fn parse_sockaddr(p: *const u8, len: i32) -> Option { + if p.is_null() || len < 16 { + return None; + } + let b = core::slice::from_raw_parts(p, len as usize); + let family = u16::from_le_bytes([b[0], b[1]]) as u32; + let port = u16::from_be_bytes([b[2], b[3]]); + if family == AF_INET { + Some(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(b[4], b[5], b[6], b[7]), port))) + } else if family == AF_INET6 && len >= 28 { + let mut a = [0u8; 16]; + a.copy_from_slice(&b[8..24]); + Some(SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::from(a), port, 0, u32::from_le_bytes([b[24], b[25], b[26], b[27]])))) + } else { + None + } +} + +unsafe fn local_name(s: usize) -> Option { + let f = ws_fn(b"getsockname\0"); + if f == 0 { + return None; + } + let f: GetSockName = core::mem::transmute(f); + let mut b = [0u8; 128]; + let mut n = b.len() as i32; + if f(s, b.as_mut_ptr(), &mut n) != 0 { + return None; + } + parse_sockaddr(b.as_ptr(), n) +} + +unsafe fn peer_name(s: usize) -> Option { + let f = ws_fn(b"getpeername\0"); + if f == 0 { + return None; + } + let f: GetSockName = core::mem::transmute(f); + let mut b = [0u8; 128]; + let mut n = b.len() as i32; + if f(s, b.as_mut_ptr(), &mut n) != 0 { + return None; + } + parse_sockaddr(b.as_ptr(), n) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Event { + Bound, + Listening, + Connected, + Accepted, + Sent, + Connecting, +} + +pub unsafe fn report_event(s: usize, event: Event, remote: *const u8, remote_len: i32) -> bool { + let proto = match socket_type(s) { + Some(SOCK_STREAM) => Proto::Tcp, + Some(SOCK_DGRAM) => Proto::Udp, + _ => return false, + }; + let Some(local) = local_name(s) else { + return false; + }; + let pid = GetCurrentProcessId(); + let prior = snapshot().into_iter().find(|e| e.socket == s as u64 && e.pid == pid && e.proto == proto); + let (remote, state) = match proto { + Proto::Udp => (None, 0), + Proto::Tcp => match event { + Event::Listening => (None, MIB_TCP_STATE_LISTEN), + Event::Bound => match prior { + Some(p) => (p.remote, p.state), + None => (None, if accepting(s) { MIB_TCP_STATE_LISTEN } else { MIB_TCP_STATE_RESERVED }), + }, + Event::Accepted => match peer_name(s).or_else(|| parse_sockaddr(remote, remote_len)) { + Some(r) => (Some(r), MIB_TCP_STATE_ESTAB), + None => return false, + }, + Event::Connecting => match parse_sockaddr(remote, remote_len) { + Some(r) => (Some(r), MIB_TCP_STATE_SYN_SENT), + None => return false, + }, + Event::Connected | Event::Sent => match parse_sockaddr(remote, remote_len).or_else(|| peer_name(s)) { + Some(r) => (Some(r), MIB_TCP_STATE_ESTAB), + None if accepting(s) => (None, MIB_TCP_STATE_LISTEN), + None => match prior { + Some(p) => (p.remote, p.state), + None => (None, MIB_TCP_STATE_RESERVED), + }, + }, + }, + }; + let created = prior.map(|e| e.created).unwrap_or_else(now_filetime); + report(Endpoint { socket: s as u64, pid, proto, local: console_local(local), remote, state, created }) +} + +pub unsafe fn report_accepted(s: usize, local: *const u8, local_len: i32, remote: *const u8, remote_len: i32) -> bool { + if socket_type(s) != Some(SOCK_STREAM) { + return false; + } + let (Some(l), Some(r)) = (parse_sockaddr(local, local_len), parse_sockaddr(remote, remote_len)) else { + return false; + }; + let pid = GetCurrentProcessId(); + let created = snapshot().into_iter().find(|e| e.socket == s as u64 && e.pid == pid).map(|e| e.created).unwrap_or_else(now_filetime); + report(Endpoint { socket: s as u64, pid, proto: Proto::Tcp, local: console_local(l), remote: Some(r), state: MIB_TCP_STATE_ESTAB, created }) +} + +type WsaIoctl = unsafe extern "system" fn(usize, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *mut c_void) -> i32; + +pub unsafe fn tcp_state(s: usize) -> Option { + let f = ws_fn(b"WSAIoctl\0"); + if f == 0 { + return None; + } + let f: WsaIoctl = core::mem::transmute(f); + let version = 0u32; + let mut info = [0u8; 256]; + let mut got = 0u32; + if f(s, SIO_TCP_INFO, &version as *const u32 as *const c_void, 4, info.as_mut_ptr() as *mut c_void, info.len() as u32, &mut got, core::ptr::null_mut(), core::ptr::null_mut()) != 0 || got < 4 { + return None; + } + Some(u32::from_le_bytes([info[0], info[1], info[2], info[3]])) +} + +unsafe fn sock_opt_u32(s: usize, name: i32) -> Option { + let f = ws_fn(b"getsockopt\0"); + if f == 0 { + return None; + } + let f: GetSockOpt = core::mem::transmute(f); + let mut v = 0u32; + let mut n = 4i32; + if f(s, SOL_SOCKET, name, &mut v as *mut u32 as *mut u8, &mut n) != 0 { + return None; + } + Some(v) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Pending { + Still, + Established, + Failed, +} + +pub unsafe fn connect_progress(s: usize) -> Pending { + match tcp_state(s) { + Some(TCPSTATE_CLOSED) => Pending::Failed, + Some(TCPSTATE_SYN_SENT | TCPSTATE_SYN_RCVD) => Pending::Still, + Some(_) => Pending::Established, + None => match (sock_opt_u32(s, SO_CONNECT_TIME), sock_opt_u32(s, SO_ERROR)) { + (Some(t), _) if t != u32::MAX => Pending::Established, + (_, Some(e)) if e != 0 => Pending::Failed, + _ => Pending::Still, + }, + } +} + +fn settle(e: Endpoint) -> Option { + if e.proto != Proto::Tcp || e.state != MIB_TCP_STATE_SYN_SENT { + return Some(e); + } + match unsafe { connect_progress(e.socket as usize) } { + Pending::Still => Some(e), + Pending::Failed => { + forget(e.socket); + None + } + Pending::Established => { + let up = Endpoint { state: MIB_TCP_STATE_ESTAB, ..e }; + report(up); + Some(up) + } + } +} + +pub unsafe fn report_socket(s: usize, remote: *const u8, remote_len: i32) -> bool { + report_event(s, Event::Connected, remote, remote_len) +} + +pub fn report_std(s: &S) -> bool { + report_owned(s.as_raw_socket()) +} + +pub fn report_owned(s: u64) -> bool { + unsafe { + let event = match socket_type(s as usize) { + Some(SOCK_STREAM) if accepting(s as usize) => Event::Listening, + Some(_) => Event::Connected, + None => return false, + }; + report_event(s as usize, event, core::ptr::null(), 0) + } +} + +pub fn endpoints() -> Vec { + let pid = unsafe { GetCurrentProcessId() }; + let mut out = Vec::new(); + for e in snapshot() { + if e.pid == pid { + let want = if e.proto == Proto::Tcp { SOCK_STREAM } else { SOCK_DGRAM }; + if unsafe { socket_type(e.socket as usize) } != Some(want) { + forget(e.socket); + continue; + } + match settle(e) { + Some(e) => out.push(e), + None => continue, + } + continue; + } + out.push(e); + } + out +} + +fn family_of(a: &SocketAddr) -> u32 { + if a.is_ipv4() { + AF_INET + } else { + AF_INET6 + } +} + +fn key(e: &Endpoint) -> (Vec, u16, Vec, u16) { + let ip = |a: &SocketAddr| match a.ip() { + IpAddr::V4(v) => v.octets().to_vec(), + IpAddr::V6(v) => v.octets().to_vec(), + }; + let (r, rp) = e.remote.map(|r| (ip(&r), r.port())).unwrap_or_default(); + (ip(&e.local), e.local.port(), r, rp) +} + +fn port_dword(p: u16) -> [u8; 4] { + let b = p.to_be_bytes(); + [b[0], b[1], 0, 0] +} + +fn v4(a: &SocketAddr) -> [u8; 4] { + match a.ip() { + IpAddr::V4(v) => v.octets(), + IpAddr::V6(_) => [0; 4], + } +} + +fn v6(a: &SocketAddr) -> ([u8; 16], u32) { + match a { + SocketAddr::V6(v) => (v.ip().octets(), v.scope_id()), + SocketAddr::V4(_) => ([0; 16], 0), + } +} + +fn unspecified(family: u32) -> SocketAddr { + if family == AF_INET { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) + } else { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)) + } +} + +fn select(proto: Proto, family: u32, order: bool, keep: impl Fn(&Endpoint) -> bool) -> Vec { + let mut v: Vec = endpoints().into_iter().filter(|e| e.proto == proto && family_of(&e.local) == family && keep(e)).collect(); + if order { + v.sort_by_key(key); + } + v +} + +fn tcp_row(e: &Endpoint, family: u32, module: bool) -> Vec { + let r = e.remote.unwrap_or_else(|| unspecified(family)); + if family == AF_INET { + let mut b = vec![0u8; if module { TCP_ROW_OWNER_MODULE_SIZE } else { TCP_ROW_OWNER_PID_SIZE }]; + b[0..4].copy_from_slice(&e.state.to_le_bytes()); + b[4..8].copy_from_slice(&v4(&e.local)); + b[8..0xc].copy_from_slice(&port_dword(e.local.port())); + b[0xc..0x10].copy_from_slice(&v4(&r)); + b[0x10..0x14].copy_from_slice(&port_dword(r.port())); + b[0x14..0x18].copy_from_slice(&e.pid.to_le_bytes()); + if module { + b[0x18..0x20].copy_from_slice(&e.created.to_le_bytes()); + } + b + } else { + let mut b = vec![0u8; if module { TCP6_ROW_OWNER_MODULE_SIZE } else { TCP6_ROW_OWNER_PID_SIZE }]; + let (la, ls) = v6(&e.local); + let (ra, rs) = v6(&r); + b[0..0x10].copy_from_slice(&la); + b[0x10..0x14].copy_from_slice(&ls.to_le_bytes()); + b[0x14..0x18].copy_from_slice(&port_dword(e.local.port())); + b[0x18..0x28].copy_from_slice(&ra); + b[0x28..0x2c].copy_from_slice(&rs.to_le_bytes()); + b[0x2c..0x30].copy_from_slice(&port_dword(r.port())); + b[0x30..0x34].copy_from_slice(&e.state.to_le_bytes()); + b[0x34..0x38].copy_from_slice(&e.pid.to_le_bytes()); + if module { + b[0x38..0x40].copy_from_slice(&e.created.to_le_bytes()); + } + b + } +} + +fn udp_row(e: &Endpoint, family: u32, module: bool) -> Vec { + if family == AF_INET { + let mut b = vec![0u8; if module { UDP_ROW_OWNER_MODULE_SIZE } else { UDP_ROW_OWNER_PID_SIZE }]; + b[0..4].copy_from_slice(&v4(&e.local)); + b[4..8].copy_from_slice(&port_dword(e.local.port())); + b[8..0xc].copy_from_slice(&e.pid.to_le_bytes()); + if module { + b[0x10..0x18].copy_from_slice(&e.created.to_le_bytes()); + } + b + } else { + let mut b = vec![0u8; if module { UDP6_ROW_OWNER_MODULE_SIZE } else { UDP6_ROW_OWNER_PID_SIZE }]; + let (la, ls) = v6(&e.local); + b[0..0x10].copy_from_slice(&la); + b[0x10..0x14].copy_from_slice(&ls.to_le_bytes()); + b[0x14..0x18].copy_from_slice(&port_dword(e.local.port())); + b[0x18..0x1c].copy_from_slice(&e.pid.to_le_bytes()); + if module { + b[0x20..0x28].copy_from_slice(&e.created.to_le_bytes()); + } + b + } +} + +fn table(rows: Vec>, header: usize, empty_row: usize) -> Vec { + let mut t = vec![0u8; header]; + t[0..4].copy_from_slice(&(rows.len() as u32).to_le_bytes()); + for r in &rows { + t.extend_from_slice(r); + } + if rows.is_empty() { + t.resize(header + empty_row, 0); + } + t +} + +pub fn tcp_table(family: u32, class: u32, order: bool) -> Result, u32> { + if !matches!(family, AF_INET | AF_INET6) { + return Err(ERROR_INVALID_PARAMETER); + } + let (module, listen, conn) = match class { + TCP_TABLE_OWNER_PID_LISTENER => (false, true, false), + TCP_TABLE_OWNER_PID_CONNECTIONS => (false, false, true), + TCP_TABLE_OWNER_PID_ALL => (false, true, true), + TCP_TABLE_OWNER_MODULE_LISTENER => (true, true, false), + TCP_TABLE_OWNER_MODULE_CONNECTIONS => (true, false, true), + TCP_TABLE_OWNER_MODULE_ALL => (true, true, true), + _ => return Err(ERROR_INVALID_PARAMETER), + }; + let rows: Vec> = select(Proto::Tcp, family, order, |e| match e.state { + MIB_TCP_STATE_RESERVED => false, + MIB_TCP_STATE_LISTEN => listen, + _ => conn, + }).iter().map(|e| tcp_row(e, family, module)).collect(); + let row = match (family, module) { + (AF_INET, true) => TCP_ROW_OWNER_MODULE_SIZE, + (AF_INET, false) => TCP_ROW_OWNER_PID_SIZE, + (_, true) => TCP6_ROW_OWNER_MODULE_SIZE, + _ => TCP6_ROW_OWNER_PID_SIZE, + }; + Ok(table(rows, if module { 8 } else { 4 }, row)) +} + +pub fn udp_table(family: u32, class: u32, order: bool) -> Result, u32> { + if !matches!(family, AF_INET | AF_INET6) { + return Err(ERROR_INVALID_PARAMETER); + } + let module = match class { + UDP_TABLE_OWNER_PID => false, + UDP_TABLE_OWNER_MODULE => true, + _ => return Err(ERROR_INVALID_PARAMETER), + }; + let rows: Vec> = select(Proto::Udp, family, order, |_| true).iter().map(|e| udp_row(e, family, module)).collect(); + let row = match (family, module) { + (AF_INET, true) => UDP_ROW_OWNER_MODULE_SIZE, + (AF_INET, false) => UDP_ROW_OWNER_PID_SIZE, + (_, true) => UDP6_ROW_OWNER_MODULE_SIZE, + _ => UDP6_ROW_OWNER_PID_SIZE, + }; + Ok(table(rows, if module { 8 } else { 4 }, row)) +} + +unsafe fn copy_out(t: Result, u32>, buf: *mut u8, size: *mut u32) -> u32 { + let t = match t { + Ok(t) => t, + Err(e) => return e, + }; + if buf.is_null() || (*size as usize) < t.len() { + *size = t.len() as u32; + return ERROR_INSUFFICIENT_BUFFER; + } + core::ptr::copy_nonoverlapping(t.as_ptr(), buf, t.len()); + *size = t.len() as u32; + ERROR_SUCCESS +} + +pub unsafe fn get_extended_tcp_table(buf: *mut u8, size: *mut u32, order: bool, family: u32, class: u32, reserved: u32) -> u32 { + if size.is_null() || reserved != 0 || family == AF_UNSPEC { + return ERROR_INVALID_PARAMETER; + } + copy_out(tcp_table(family, class, order), buf, size) +} + +pub unsafe fn get_extended_udp_table(buf: *mut u8, size: *mut u32, order: bool, family: u32, class: u32, reserved: u32) -> u32 { + if size.is_null() || reserved != 0 || family == AF_UNSPEC { + return ERROR_INVALID_PARAMETER; + } + copy_out(udp_table(family, class, order), buf, size) +} diff --git a/crates/compat/compat-common/src/netview/tests.rs b/crates/compat/compat-common/src/netview/tests.rs new file mode 100644 index 00000000..5e24fa33 --- /dev/null +++ b/crates/compat/compat-common/src/netview/tests.rs @@ -0,0 +1,583 @@ +use super::sockets::*; +use super::wfp; +use super::*; +use std::os::windows::io::AsRawSocket; + +fn rd32(b: &[u8], o: usize) -> u32 { + u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) +} + +fn rd64(b: &[u8], o: usize) -> u64 { + u64::from_le_bytes(b[o..o + 8].try_into().unwrap()) +} + +unsafe fn gaa(family: u32, flags: u32) -> Vec { + let mut size = 0u32; + assert_eq!(get_adapters_addresses(family, flags, core::ptr::null_mut(), &mut size), ERROR_BUFFER_OVERFLOW); + let mut small = size - 1; + let mut buf = vec![0u8; size as usize]; + assert_eq!(get_adapters_addresses(family, flags, buf.as_mut_ptr(), &mut small), ERROR_BUFFER_OVERFLOW); + assert_eq!(small, size); + assert_eq!(get_adapters_addresses(family, flags, buf.as_mut_ptr(), &mut size), ERROR_SUCCESS); + buf +} + +unsafe fn sockaddr_at(p: u64, len: u32) -> std::net::SocketAddr { + parse_sockaddr(p as *const u8, len as i32).unwrap() +} + +#[test] +fn adapters_addresses_use_the_lh_layout_with_one_nic_and_loopback() { + unsafe { + let buf = gaa(AF_UNSPEC, 6); + let base = buf.as_ptr() as u64; + let a = &buf[..]; + assert_eq!(rd32(a, 0), 0x1c0); + assert_eq!(rd32(a, 4), NIC_IF_INDEX); + let next = rd64(a, 8); + assert_eq!(next - base, 0x1c0); + let name = std::ffi::CStr::from_ptr(rd64(a, 0x10) as *const i8).to_str().unwrap().to_string(); + assert!(name.starts_with('{') && name.len() == 38); + assert_eq!(&a[0x50..0x56], &NIC_MAC); + assert_eq!(rd32(a, 0x58), 6); + assert_eq!(rd32(a, 0x64), IF_TYPE_ETHERNET_CSMACD); + assert_eq!(rd32(a, 0x68), IF_OPER_STATUS_UP); + assert_eq!(rd64(a, 0xe0), NIC_LUID); + assert_eq!(rd64(a, 0x28), 0); + assert_eq!(rd64(a, 0x30), 0); + assert_eq!(rd64(a, 0xb0), 0); + let mut u = rd64(a, 0x18); + let mut seen = Vec::new(); + while u != 0 { + let e = core::slice::from_raw_parts(u as *const u8, UNICAST_SIZE); + assert_eq!(rd32(e, 0), UNICAST_SIZE as u32); + seen.push((sockaddr_at(rd64(e, 0x10), rd32(e, 0x18)).ip(), e[0x38], rd32(e, 0x20), rd32(e, 0x24), rd32(e, 0x28))); + u = rd64(e, 8); + } + assert_eq!(seen, vec![(IpAddr::V6(NIC_IPV6), 64, 2, 4, 4), (IpAddr::V4(NIC_IPV4), 16, 2, 4, 4)]); + let lo = core::slice::from_raw_parts(next as *const u8, 0x1c0); + assert_eq!(rd32(lo, 4), LOOPBACK_IF_INDEX); + assert_eq!(rd64(lo, 8), 0); + assert_eq!(rd32(lo, 0x64), IF_TYPE_SOFTWARE_LOOPBACK); + assert_eq!(rd32(lo, 0x58), 0); + let fname: Vec = (0..).map(|i| *(rd64(lo, 0x48) as *const u16).add(i)).take_while(|c| *c != 0).collect(); + assert_eq!(String::from_utf16(&fname).unwrap(), "Loopback Pseudo-Interface 1"); + } +} + +#[test] +fn adapter_family_and_list_flags_filter_entries() { + unsafe { + let buf = gaa(AF_INET, GAA_FLAG_INCLUDE_PREFIX); + let a = &buf[..]; + let u = core::slice::from_raw_parts(rd64(a, 0x18) as *const u8, UNICAST_SIZE); + assert_eq!(sockaddr_at(rd64(u, 0x10), rd32(u, 0x18)).ip(), IpAddr::V4(NIC_IPV4)); + assert_eq!(rd64(u, 8), 0); + let m = core::slice::from_raw_parts(rd64(a, 0x28) as *const u8, MULTICAST_SIZE); + assert_eq!(sockaddr_at(rd64(m, 0x10), rd32(m, 0x18)).ip(), IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1))); + let p = core::slice::from_raw_parts(rd64(a, 0xb0) as *const u8, PREFIX_SIZE); + assert_eq!(sockaddr_at(rd64(p, 0x10), rd32(p, 0x18)).ip(), IpAddr::V4(Ipv4Addr::new(169, 254, 0, 0))); + assert_eq!(rd32(p, 0x20), 16); + let mut size = 0u32; + assert_eq!(get_adapters_addresses(5, 0, core::ptr::null_mut(), &mut size), ERROR_INVALID_PARAMETER); + assert_eq!(get_adapters_addresses(AF_INET, 0, core::ptr::null_mut(), core::ptr::null_mut()), ERROR_INVALID_PARAMETER); + } +} + +#[test] +fn forward_table_has_on_link_routes_and_no_default_route() { + let t = ip_forward_table2(AF_UNSPEC).unwrap(); + let n = rd32(&t, 0) as usize; + assert_eq!(t.len(), 8 + n * ROUTE_ROW_SIZE); + assert_eq!(n, routes().len()); + let row = &t[8..8 + ROUTE_ROW_SIZE]; + assert_eq!(rd64(row, 0), LOOPBACK_LUID); + assert_eq!(rd32(row, 8), LOOPBACK_IF_INDEX); + assert_eq!(&row[0xc..0x14], &[2, 0, 0, 0, 127, 0, 0, 0]); + assert_eq!(row[0x28], 8); + assert_eq!(rd32(row, 0x54), 256); + assert_eq!(rd32(row, 0x58), ROUTE_PROTOCOL_LOCAL); + assert_eq!(row[0x5c], 1); + assert_eq!(rd32(row, 0x64), ROUTE_ORIGIN_WELL_KNOWN); + assert!(routes().iter().all(|r| r.prefix_len != 0)); + assert!(has_route_to(&"127.5.5.5".parse().unwrap())); + assert!(has_route_to(&IpAddr::V4(NIC_IPV4))); + assert!(!has_route_to(&"8.8.8.8".parse().unwrap())); + assert!(!has_route_to(&"2001:db8::1".parse().unwrap())); + let v6 = ip_forward_table2(AF_INET6).unwrap(); + assert_eq!(rd32(&v6, 0) as usize, routes().iter().filter(|r| r.dest.is_ipv6()).count()); + assert_eq!(ip_forward_table2(7), Err(ERROR_INVALID_PARAMETER)); +} + +#[test] +fn teredo_reports_offline_state_and_no_port() { + unsafe { + let mut rw = [0xffu8; 12]; + let m = NPI_MS_TEREDO_MODULEID; + let n = core::ptr::null_mut(); + assert_eq!(nsi_get_all_parameters(1, m.as_ptr(), 1, core::ptr::null(), 0, rw.as_mut_ptr(), 12, n, 0, n, 0), 0); + assert_eq!(rd32(&rw, 0), TEREDO_STATE_OFFLINE); + assert_ne!(rd32(&rw, 0), TEREDO_STATE_QUALIFIED); + assert_eq!(&rw[4..], &[0; 8]); + let mut port = [0u8; 2]; + assert_eq!(nsi_get_all_parameters(1, m.as_ptr(), 3, core::ptr::null(), 0, port.as_mut_ptr(), 2, n, 0, n, 0), ERROR_NOT_READY); + assert_eq!(nsi_get_all_parameters(1, m.as_ptr(), 1, core::ptr::null(), 0, rw.as_mut_ptr(), 8, n, 0, n, 0), ERROR_INVALID_PARAMETER); + let mut other = m; + other[8] = 0; + assert_eq!(nsi_get_all_parameters(1, other.as_ptr(), 1, core::ptr::null(), 0, rw.as_mut_ptr(), 12, n, 0, n, 0), ERROR_NOT_FOUND); + } +} + +#[test] +fn socket_registry_reports_live_title_sockets_in_owner_module_tables() { + let _g = super::sockets::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let c = std::net::TcpStream::connect(l.local_addr().unwrap()).unwrap(); + let u = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let peer = l.local_addr().unwrap(); + let sa = sockaddr_bytes(&peer.ip(), peer.port(), 0); + unsafe { + assert!(report_socket(l.as_raw_socket() as usize, core::ptr::null(), 0)); + assert!(report_socket(c.as_raw_socket() as usize, sa.as_ptr(), sa.len() as i32)); + assert!(report_socket(u.as_raw_socket() as usize, core::ptr::null(), 0)); + assert!(!report_socket(0xdead_beef, core::ptr::null(), 0)); + let mut size = 0u32; + assert_eq!(get_extended_tcp_table(core::ptr::null_mut(), &mut size, true, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0), ERROR_INSUFFICIENT_BUFFER); + let mut buf = vec![0u8; size as usize]; + assert_eq!(get_extended_tcp_table(buf.as_mut_ptr(), &mut size, true, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0), ERROR_SUCCESS); + let n = rd32(&buf, 0) as usize; + let rows: Vec<&[u8]> = (0..n).map(|i| &buf[8 + i * TCP_ROW_OWNER_MODULE_SIZE..8 + (i + 1) * TCP_ROW_OWNER_MODULE_SIZE]).collect(); + let pid = std::process::id(); + let listen = rows.iter().find(|r| rd32(r, 0) == MIB_TCP_STATE_LISTEN && u16::from_be_bytes([r[8], r[9]]) == peer.port()).expect("listener row"); + assert_eq!(&listen[4..8], &[127, 0, 0, 1]); + assert_eq!(rd32(listen, 0x14), pid); + assert_ne!(rd64(listen, 0x18), 0); + let est = rows.iter().find(|r| rd32(r, 0) == MIB_TCP_STATE_ESTAB && u16::from_be_bytes([r[0x10], r[0x11]]) == peer.port()).expect("connected row"); + assert_eq!(u16::from_be_bytes([est[8], est[9]]), c.local_addr().unwrap().port()); + let t = udp_table(AF_INET, UDP_TABLE_OWNER_MODULE, true).unwrap(); + let un = rd32(&t, 0) as usize; + assert!((0..un).any(|i| { + let r = &t[8 + i * UDP_ROW_OWNER_MODULE_SIZE..]; + u16::from_be_bytes([r[4], r[5]]) == u.local_addr().unwrap().port() && rd32(r, 8) == pid + })); + let pidt = tcp_table(AF_INET, TCP_TABLE_OWNER_PID_LISTENER, false).unwrap(); + assert_eq!((pidt.len() - 4) % TCP_ROW_OWNER_PID_SIZE, 0); + assert!(tcp_table(AF_INET, 2, true).is_err()); + let ls = l.as_raw_socket() as u64; + drop(l); + assert!(!endpoints().iter().any(|e| e.socket == ls)); + assert!(!snapshot().iter().any(|e| e.socket == ls)); + } +} + +#[test] +fn console_view_maps_host_lan_addresses_to_the_emulated_nic() { + let _g = super::sockets::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let a: std::net::SocketAddr = "192.168.1.20:5000".parse().unwrap(); + assert_eq!(console_local(a), std::net::SocketAddr::new(IpAddr::V4(NIC_IPV4), 5000)); + let l: std::net::SocketAddr = "127.0.0.1:7".parse().unwrap(); + assert_eq!(console_local(l), l); + let z: std::net::SocketAddr = "0.0.0.0:9".parse().unwrap(); + assert_eq!(console_local(z), z); +} + +#[test] +fn wfp_store_is_empty_and_keeps_dynamic_providers_per_session() { + let _g = wfp::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let e = wfp::engine_open(wfp::FWPM_SESSION_FLAG_DYNAMIC).unwrap(); + for kind in [wfp::Kind::ProviderContext, wfp::Kind::SubLayer, wfp::Kind::Callout, wfp::Kind::Filter, wfp::Kind::IpsecSaContext, wfp::Kind::IpsecSa, wfp::Kind::IkeSa, wfp::Kind::AleEndpoint] { + let h = wfp::create_enum_handle(e, kind).unwrap(); + assert!(wfp::enum_next(e, h, 0x40).unwrap().is_empty()); + assert_eq!(wfp::destroy_enum_handle(e, h), 0); + assert_eq!(wfp::destroy_enum_handle(e, h), wfp::ERROR_INVALID_HANDLE); + } + let key = [7u8; 16]; + assert_eq!(wfp::provider_get_by_key(e, &key), Err(wfp::FWP_E_PROVIDER_NOT_FOUND)); + let p = wfp::Provider { key, name: Some("p".encode_utf16().collect()), description: None, flags: 0, data: Vec::new(), service_name: None }; + assert_eq!(wfp::provider_add(e, wfp::Provider { flags: wfp::FWPM_PROVIDER_FLAG_PERSISTENT, ..p.clone() }), wfp::FWP_E_DYNAMIC_SESSION_IN_PROGRESS); + assert_eq!(wfp::provider_add(e, p.clone()), 0); + assert_eq!(wfp::provider_add(e, p.clone()), wfp::FWP_E_ALREADY_EXISTS); + assert_eq!(wfp::provider_get_by_key(e, &key), Ok(p.clone())); + let h = wfp::create_enum_handle(e, wfp::Kind::Provider).unwrap(); + let first = wfp::enum_next(e, h, 0x40).unwrap(); + assert!(first.contains(&wfp::Object::Provider(p.clone()))); + assert!(wfp::enum_next(e, h, 0x40).unwrap().is_empty()); + assert_eq!(wfp::destroy_enum_handle(e, h), 0); + assert_eq!(wfp::transaction_abort(e), wfp::FWP_E_NO_TXN_IN_PROGRESS); + assert_eq!(wfp::transaction_begin(e), 0); + assert_eq!(wfp::transaction_begin(e), wfp::FWP_E_TXN_IN_PROGRESS); + assert_eq!(wfp::transaction_abort(e), 0); + assert_eq!(wfp::engine_close(e), 0); + assert_eq!(wfp::engine_close(e), wfp::ERROR_INVALID_HANDLE); + let e2 = wfp::engine_open(0).unwrap(); + assert_eq!(wfp::provider_get_by_key(e2, &key), Err(wfp::FWP_E_PROVIDER_NOT_FOUND)); + assert_eq!(wfp::provider_delete_by_key(e2, &key), wfp::FWP_E_PROVIDER_NOT_FOUND); + assert_eq!(wfp::engine_close(e2), 0); + assert_eq!(wfp::create_enum_handle(e2, wfp::Kind::Provider), Err(wfp::ERROR_INVALID_HANDLE)); +} + +#[test] +fn wfp_store_lives_in_the_process_wide_mapping() { + let _g = wfp::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + extern "system" { + fn OpenFileMappingW(access: u32, inherit: i32, name: *const u16) -> *mut core::ffi::c_void; + fn MapViewOfFile(h: *mut core::ffi::c_void, access: u32, high: u32, low: u32, n: usize) -> *mut core::ffi::c_void; + fn UnmapViewOfFile(p: *const core::ffi::c_void) -> i32; + fn CloseHandle(h: *mut core::ffi::c_void) -> i32; + } + let e = wfp::engine_open(wfp::FWPM_SESSION_FLAG_DYNAMIC).unwrap(); + let e2 = wfp::engine_open(0).unwrap(); + assert!(e2 > e && e >= wfp::FIRST_HANDLE); + let name: Vec = "shared-store-probe".encode_utf16().collect(); + let key = [0x5a; 16]; + let p = wfp::Provider { key, name: Some(name.clone()), description: None, flags: 0, data: vec![1, 2, 3], service_name: None }; + assert_eq!(wfp::provider_add(e, p.clone()), 0); + let n: Vec = wfp::shared_mapping_name().encode_utf16().chain(Some(0)).collect(); + unsafe { + let h = OpenFileMappingW(0x0004, 0, n.as_ptr()); + assert!(!h.is_null()); + let v = MapViewOfFile(h, 0x0004, 0, 0, 0) as *const u8; + assert!(!v.is_null()); + let len = u32::from_le_bytes(core::slice::from_raw_parts(v.add(4), 4).try_into().unwrap()) as usize; + let next = u64::from_le_bytes(core::slice::from_raw_parts(v.add(8), 8).try_into().unwrap()); + assert!(next >= e2); + let arena = core::slice::from_raw_parts(v.add(16), len); + let wide: Vec = name.iter().flat_map(|c| c.to_le_bytes()).collect(); + assert!(arena.windows(16).any(|w| w == key)); + assert!(arena.windows(wide.len()).any(|w| w == wide.as_slice())); + UnmapViewOfFile(v as *const _); + CloseHandle(h); + } + assert_eq!(wfp::provider_get_by_key(e2, &key), Ok(p)); + assert_eq!(wfp::engine_close(e), 0); + assert_eq!(wfp::provider_get_by_key(e2, &key), Err(wfp::FWP_E_PROVIDER_NOT_FOUND)); + assert_eq!(wfp::engine_close(e2), 0); +} + +fn named(n: &str) -> [u8; 16] { + super::wfp_names::NAMES.iter().find(|(_, x)| *x == n).map(|(k, _)| *k).unwrap() +} + +fn wide(s: &str) -> Option> { + Some(s.encode_utf16().collect()) +} + +fn test_filter(key: u8, layer: [u8; 16], sublayer: [u8; 16], weight: wfp::Value) -> wfp::Filter { + wfp::Filter { + key: [key; 16], + name: wide("f"), + description: None, + flags: 0, + provider_key: None, + data: Vec::new(), + layer, + sublayer, + weight, + conditions: vec![wfp::Condition { field: named("FWPM_CONDITION_IP_REMOTE_ADDRESS"), match_type: 0, value: wfp::Value::U32(0x0a00_0001) }], + action_type: 0x1001, + action_key: [0; 16], + context: [0; 16], + reserved: None, + id: 0, + effective_weight: wfp::Value::Empty, + } +} + +#[test] +fn wfp_store_adds_sublayers_callouts_contexts_and_filters_with_console_checks() { + let _g = wfp::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let e = wfp::engine_open(wfp::FWPM_SESSION_FLAG_DYNAMIC).unwrap(); + let connect = named("FWPM_LAYER_ALE_AUTH_CONNECT_V4"); + let transport = named("FWPM_LAYER_INBOUND_TRANSPORT_V4"); + let pkey = [0x71u8; 16]; + let sl = wfp::SubLayer { key: [0x72; 16], name: wide("s"), description: None, flags: 0, provider_key: Some(pkey), data: vec![1, 2, 3], weight: 0x10 }; + assert_eq!(wfp::sublayer_add(e, sl.clone()), wfp::FWP_E_PROVIDER_NOT_FOUND); + assert_eq!(wfp::provider_add(e, wfp::Provider { key: pkey, name: wide("p"), description: None, flags: 0, data: Vec::new(), service_name: None }), 0); + assert_eq!(wfp::sublayer_add(e, wfp::SubLayer { name: None, ..sl.clone() }), wfp::ERROR_INVALID_PARAMETER); + assert_eq!(wfp::sublayer_add(e, wfp::SubLayer { key: named("FWPM_SUBLAYER_UNIVERSAL"), ..sl.clone() }), wfp::FWP_E_ALREADY_EXISTS); + assert_eq!(wfp::sublayer_add(e, wfp::SubLayer { flags: wfp::FWPM_SUBLAYER_FLAG_PERSISTENT, ..sl.clone() }), wfp::FWP_E_DYNAMIC_SESSION_IN_PROGRESS); + assert_eq!(wfp::sublayer_add(e, sl.clone()), 0); + assert_eq!(wfp::sublayer_get_by_key(e, &sl.key), Ok(sl.clone())); + let co = wfp::Callout { key: [0x73; 16], name: wide("c"), description: None, flags: 0, provider_key: None, data: Vec::new(), layer: [0x99; 16], id: 0 }; + assert_eq!(wfp::callout_add(e, co.clone()), Err(wfp::FWP_E_LAYER_NOT_FOUND)); + let id1 = wfp::callout_add(e, wfp::Callout { layer: connect, ..co.clone() }).unwrap(); + assert_eq!(wfp::callout_get_by_key(e, &co.key).unwrap().id, id1); + let ctx = wfp::ProviderContext { key: [0x74; 16], name: wide("x"), description: None, flags: 0, provider_key: None, data: Vec::new(), kind: wfp::FWPM_GENERAL_CONTEXT, body: wfp::ContextBody::General(vec![9]), id: 0 }; + assert_eq!(wfp::provider_context_add(e, wfp::ProviderContext { body: wfp::ContextBody::Null, ..ctx.clone() }), Err(wfp::ERROR_INVALID_PARAMETER)); + assert_eq!(wfp::provider_context_add(e, wfp::ProviderContext { kind: 13, ..ctx.clone() }), Err(wfp::ERROR_INVALID_PARAMETER)); + let cid = wfp::provider_context_add(e, ctx.clone()).unwrap(); + assert_eq!(wfp::provider_context_get_by_key(e, &ctx.key).unwrap().id, cid); + assert_eq!(wfp::filter_add(e, test_filter(1, [0x99; 16], [0; 16], wfp::Value::Empty)), Err(wfp::FWP_E_LAYER_NOT_FOUND)); + assert_eq!(wfp::filter_add(e, test_filter(1, connect, [0x98; 16], wfp::Value::Empty)), Err(wfp::FWP_E_SUBLAYER_NOT_FOUND)); + assert_eq!(wfp::filter_add(e, test_filter(1, connect, [0; 16], wfp::Value::U32(1))), Err(wfp::ERROR_INVALID_PARAMETER)); + assert_eq!(wfp::filter_add(e, wfp::Filter { action_type: 0x5003, action_key: [0x97; 16], ..test_filter(1, connect, [0; 16], wfp::Value::Empty) }), Err(wfp::FWP_E_CALLOUT_NOT_FOUND)); + assert_eq!(wfp::filter_add(e, wfp::Filter { flags: wfp::FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT, context: [0x96; 16], ..test_filter(1, connect, [0; 16], wfp::Value::Empty) }), Err(wfp::FWP_E_PROVIDER_CONTEXT_NOT_FOUND)); + let a = wfp::filter_add(e, wfp::Filter { action_type: 0x5003, action_key: co.key, ..test_filter(1, connect, sl.key, wfp::Value::U64(7)) }).unwrap(); + let b = wfp::filter_add(e, wfp::Filter { flags: wfp::FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT, context: ctx.key, ..test_filter(2, transport, named("FWPM_SUBLAYER_UNIVERSAL"), wfp::Value::U8(3)) }).unwrap(); + let c = wfp::filter_add(e, test_filter(3, transport, [0; 16], wfp::Value::Empty)).unwrap(); + assert_eq!((b, c), (a + 1, a + 2)); + assert_eq!(wfp::filter_get_by_key(e, &[1; 16]).unwrap().effective_weight, wfp::Value::U64(7)); + match wfp::filter_get_by_key(e, &[2; 16]).unwrap().effective_weight { + wfp::Value::U64(w) => assert_eq!(w >> 60, 3), + other => panic!("{:?}", other), + } + assert!(matches!(wfp::filter_get_by_key(e, &[3; 16]).unwrap().effective_weight, wfp::Value::U64(_))); + assert_eq!(wfp::filter_add(e, test_filter(3, transport, [0; 16], wfp::Value::Empty)), Err(wfp::FWP_E_ALREADY_EXISTS)); + let by_layer = |l: Option<[u8; 16]>| { + let h = wfp::create_filter_enum_handle(e, l).unwrap(); + let v: Vec = wfp::enum_next(e, h, 0x40).unwrap().iter().map(|o| match o { wfp::Object::Filter(f) => f.id, _ => panic!() }).collect(); + assert_eq!(wfp::destroy_enum_handle(e, h), 0); + v + }; + assert_eq!(by_layer(Some(connect)), vec![a]); + assert_eq!(by_layer(Some(transport)), vec![b, c]); + assert_eq!(by_layer(None), vec![a, b, c]); + assert_eq!(wfp::create_filter_enum_handle(e, Some([0x99; 16])), Err(wfp::FWP_E_LAYER_NOT_FOUND)); + assert_eq!(wfp::sublayer_delete_by_key(e, &sl.key), wfp::FWP_E_IN_USE); + assert_eq!(wfp::callout_delete_by_key(e, &co.key), wfp::FWP_E_IN_USE); + assert_eq!(wfp::provider_context_delete_by_key(e, &ctx.key), wfp::FWP_E_IN_USE); + assert_eq!(wfp::provider_delete_by_key(e, &pkey), wfp::FWP_E_IN_USE); + assert_eq!(wfp::filter_delete_by_key(e, &[1; 16]), 0); + assert_eq!(wfp::filter_delete_by_id(e, b), 0); + assert_eq!(wfp::filter_delete_by_id(e, b), wfp::FWP_E_FILTER_NOT_FOUND); + assert_eq!(wfp::sublayer_delete_by_key(e, &sl.key), 0); + assert_eq!(wfp::callout_delete_by_key(e, &co.key), 0); + assert_eq!(wfp::provider_context_delete_by_key(e, &ctx.key), 0); + assert_eq!(wfp::object_count(wfp::Kind::Filter), 1); + assert_eq!(wfp::engine_close(e), 0); + for k in [wfp::Kind::Provider, wfp::Kind::SubLayer, wfp::Kind::Callout, wfp::Kind::Filter, wfp::Kind::ProviderContext] { + assert_eq!(wfp::object_count(k), 0); + } +} + +mod iphlp_model { + use super::super::iphlp::*; + use super::super::*; + use super::{rd32, rd64}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + + fn nic() -> Adapter { + adapters().into_iter().find(|a| a.if_index == NIC_IF_INDEX).unwrap() + } + + fn v6sock(ip: Ipv6Addr) -> [u8; 28] { + let mut b = [0u8; 28]; + b[0] = 0x17; + b[8..24].copy_from_slice(&ip.octets()); + b + } + + #[test] + fn if_table2_rows_follow_mib_if_row2_layout() { + let t = if_table2(); + assert_eq!(rd32(&t, 0), 2); + assert_eq!(t.len(), 8 + 2 * IF_ROW2_SIZE); + let r = &t[8..8 + IF_ROW2_SIZE]; + let a = nic(); + assert_eq!(rd64(r, 0), NIC_LUID); + assert_eq!(rd32(r, 8), NIC_IF_INDEX); + assert_eq!(&r[0xc..0x1c], &interface_guid(&a)); + assert_eq!(interface_guid(&a), parse_guid("{5A6F8E2C-1B3D-4E59-9C70-546F6D426F78}").unwrap()); + assert_eq!(&r[0xc..0x10], &[0x2c, 0x8e, 0x6f, 0x5a]); + let alias: Vec = r[0x1c..0x1c + 16].chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + assert_eq!(String::from_utf16_lossy(&alias), "Ethernet"); + assert_eq!(rd32(r, 0x420), 6); + assert_eq!(&r[0x424..0x42a], &NIC_MAC); + assert_eq!(&r[0x444..0x44a], &NIC_MAC); + assert_eq!(rd32(r, 0x464), 1500); + assert_eq!(rd32(r, 0x468), IF_TYPE_ETHERNET_CSMACD); + assert_eq!(rd32(r, 0x474), 14); + assert_eq!(rd32(r, 0x478), 2); + assert_eq!(r[0x480], 5); + assert_eq!(rd32(r, 0x484), 1); + assert_eq!(rd32(r, 0x488), 1); + assert_eq!(rd32(r, 0x48c), 1); + assert_eq!(&r[0x490..0x4a0], &a.network_guid); + assert_eq!(rd64(r, 0x4a8), 1_000_000_000); + assert!(r[0x4b8..].iter().all(|b| *b == 0)); + let l = &t[8 + IF_ROW2_SIZE..]; + assert_eq!(rd64(l, 0), LOOPBACK_LUID); + assert_eq!(rd32(l, 0x478), 1); + assert_eq!(rd32(l, 0x420), 0); + } + + #[test] + fn if_entry_lookups_use_luid_then_index_and_report_missing_rows() { + unsafe { + let mut row = vec![0u8; IF_ROW2_SIZE]; + assert_eq!(get_if_entry2(row.as_mut_ptr()), ERROR_INVALID_PARAMETER); + row[8..12].copy_from_slice(&LOOPBACK_IF_INDEX.to_le_bytes()); + assert_eq!(get_if_entry2(row.as_mut_ptr()), ERROR_SUCCESS); + assert_eq!(rd64(&row, 0), LOOPBACK_LUID); + let mut row = vec![0u8; IF_ROW2_SIZE]; + row[0..8].copy_from_slice(&NIC_LUID.to_le_bytes()); + row[8..12].copy_from_slice(&LOOPBACK_IF_INDEX.to_le_bytes()); + assert_eq!(get_if_entry2_ex(MIB_IF_ENTRY_NORMAL_WITHOUT_STATISTICS, row.as_mut_ptr()), ERROR_SUCCESS); + assert_eq!(rd32(&row, 8), NIC_IF_INDEX); + assert_eq!(get_if_entry2_ex(1, row.as_mut_ptr()), ERROR_INVALID_PARAMETER); + row[0..8].copy_from_slice(&0x1234u64.to_le_bytes()); + assert_eq!(get_if_entry2(row.as_mut_ptr()), ERROR_FILE_NOT_FOUND); + let mut old = vec![0u8; IF_ROW_SIZE]; + old[0x200..0x204].copy_from_slice(&NIC_IF_INDEX.to_le_bytes()); + assert_eq!(get_if_entry(old.as_mut_ptr()), ERROR_SUCCESS); + let name: Vec = old[0..0x200].chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|c| *c != 0).collect(); + assert_eq!(String::from_utf16_lossy(&name), "\\DEVICE\\TCPIP_{5A6F8E2C-1B3D-4E59-9C70-546F6D426F78}"); + assert_eq!(rd32(&old, 0x210), 6); + assert_eq!(rd32(&old, 0x220), MIB_IF_OPER_STATUS_OPERATIONAL); + assert_eq!(&old[0x25c..0x25c + 6], b"TomBox"); + old[0x200..0x204].copy_from_slice(&99u32.to_le_bytes()); + assert_eq!(get_if_entry(old.as_mut_ptr()), ERROR_INVALID_PARAMETER); + let mut tp: *mut u8 = core::ptr::null_mut(); + assert_eq!(get_if_table2(&mut tp), ERROR_SUCCESS); + let t = core::slice::from_raw_parts(tp, 8 + 2 * IF_ROW2_SIZE); + assert_eq!(t, &if_table2()[..]); + free_mib_table(tp as *mut core::ffi::c_void); + free_mib_table(core::ptr::null_mut()); + } + } + + #[test] + fn guid_luid_index_conversions_and_best_interface() { + unsafe { + let g = interface_guid(&nic()); + let mut luid = 0u64; + assert_eq!(convert_interface_guid_to_luid(&g, &mut luid), ERROR_SUCCESS); + assert_eq!(luid, NIC_LUID); + assert_eq!(convert_interface_guid_to_luid(&[9u8; 16], &mut luid), ERROR_NOT_FOUND); + let mut idx = 0u32; + assert_eq!(convert_interface_luid_to_index(&LOOPBACK_LUID, &mut idx), ERROR_SUCCESS); + assert_eq!(idx, LOOPBACK_IF_INDEX); + assert_eq!(convert_interface_luid_to_index(&7u64, &mut idx), ERROR_NOT_FOUND); + assert_eq!(convert_interface_luid_to_index(core::ptr::null(), &mut idx), ERROR_INVALID_PARAMETER); + let s = sockaddr_bytes(&IpAddr::V4(Ipv4Addr::new(169, 254, 3, 4)), 0, 0); + assert_eq!(get_best_interface_ex(s.as_ptr(), &mut idx), ERROR_SUCCESS); + assert_eq!(idx, NIC_IF_INDEX); + let s = sockaddr_bytes(&IpAddr::V4(Ipv4Addr::LOCALHOST), 0, 0); + assert_eq!(get_best_interface_ex(s.as_ptr(), &mut idx), ERROR_SUCCESS); + assert_eq!(idx, LOOPBACK_IF_INDEX); + let s = sockaddr_bytes(&IpAddr::V4(Ipv4Addr::new(198, 41, 0, 4)), 0, 0); + assert_eq!(get_best_interface_ex(s.as_ptr(), &mut idx), ERROR_NETWORK_UNREACHABLE); + let s = v6sock(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 9)); + assert_eq!(get_best_interface_ex(s.as_ptr(), &mut idx), ERROR_SUCCESS); + assert_eq!(idx, NIC_IF_INDEX); + let s = v6sock(Ipv4Addr::new(169, 254, 66, 1).to_ipv6_mapped()); + assert_eq!(get_best_interface_ex(s.as_ptr(), &mut idx), ERROR_SUCCESS); + assert_eq!(idx, NIC_IF_INDEX); + } + } + + #[test] + fn physical_interface_for_destination_is_unreachable_offline_and_names_on_link_interfaces() { + unsafe { + let mut out = [0u8; 16]; + let mut h = 5usize; + let root4 = v6sock(Ipv4Addr::new(198, 41, 0, 4).to_ipv6_mapped()); + assert_eq!(physical_interface_for_destination(root4.as_ptr(), &mut out, &mut h), ERROR_NETWORK_UNREACHABLE); + assert_eq!(h, 0); + let root6 = v6sock(Ipv6Addr::new(0x2001, 0x503, 0xba3e, 0, 0, 0, 2, 0x30)); + assert_eq!(physical_interface_for_destination(root6.as_ptr(), &mut out, &mut h), ERROR_NETWORK_UNREACHABLE); + let link = sockaddr_bytes(&IpAddr::V4(Ipv4Addr::new(169, 254, 9, 9)), 0, 0); + assert_eq!(physical_interface_for_destination(link.as_ptr(), &mut out, &mut h), ERROR_SUCCESS); + assert_eq!(out, interface_guid(&nic())); + assert_eq!(close_physical_interface_for_destination(&mut h), ERROR_SUCCESS); + let mut bogus = 0x44usize; + assert_eq!(close_physical_interface_for_destination(&mut bogus), ERROR_INVALID_HANDLE); + } + } + + fn sort_list(addrs: &[&[u8]]) -> Vec { + let mut list = vec![0u8; 8 + 16 * addrs.len()]; + list[0..4].copy_from_slice(&(addrs.len() as i32).to_le_bytes()); + for (i, a) in addrs.iter().enumerate() { + list[8 + 16 * i..16 + 16 * i].copy_from_slice(&(a.as_ptr() as usize).to_le_bytes()); + list[16 + 16 * i..20 + 16 * i].copy_from_slice(&(a.len() as i32).to_le_bytes()); + } + list + } + + fn order(list: &[u8]) -> Vec { + let n = rd32(list, 0) as usize; + (0..n).map(|i| usize::from_le_bytes(list[8 + 16 * i..16 + 16 * i].try_into().unwrap())).collect() + } + + #[test] + fn address_list_sort_follows_rfc6724_against_the_emulated_view() { + let root4 = v6sock(Ipv4Addr::new(198, 41, 0, 4).to_ipv6_mapped()); + let link4 = v6sock(Ipv4Addr::new(169, 254, 7, 7).to_ipv6_mapped()); + let ll6 = v6sock(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 7)); + let lo6 = v6sock(Ipv6Addr::LOCALHOST); + let mut list = sort_list(&[&root4, &link4, &ll6, &lo6]); + let len = list.len() as u32; + assert_eq!(unsafe { address_list_sort(list.as_mut_ptr(), len) }, Ok(len)); + assert_eq!(order(&list), vec![lo6.as_ptr() as usize, ll6.as_ptr() as usize, link4.as_ptr() as usize, root4.as_ptr() as usize]); + let root6 = v6sock(Ipv6Addr::new(0x2001, 0x503, 0xba3e, 0, 0, 0, 2, 0x30)); + let mut both = sort_list(&[&root4, &root6]); + assert_eq!(unsafe { address_list_sort(both.as_mut_ptr(), both.len() as u32) }, Ok(both.len() as u32)); + assert_eq!(order(&both), vec![root4.as_ptr() as usize, root6.as_ptr() as usize]); + assert_eq!(policy(&IpAddr::V6(Ipv6Addr::LOCALHOST)), Policy { precedence: 50, label: 0 }); + assert_eq!(policy(&IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4))), Policy { precedence: 35, label: 4 }); + assert_eq!(scope(&IpAddr::V4(Ipv4Addr::new(169, 254, 1, 1))), 2); + assert_eq!(scope(&IpAddr::V6(Ipv6Addr::new(0xff05, 0, 0, 0, 0, 0, 0, 1))), 5); + let v4 = sockaddr_bytes(&IpAddr::V4(Ipv4Addr::LOCALHOST), 0, 0); + list[8..16].copy_from_slice(&(v4.as_ptr() as usize).to_le_bytes()); + assert_eq!(unsafe { address_list_sort(list.as_mut_ptr(), len) }, Err(ERROR_INVALID_PARAMETER)); + assert_eq!(unsafe { address_list_sort(list.as_mut_ptr(), 20) }, Err(ERROR_INVALID_PARAMETER)); + } + + #[test] + fn nsi_interface_rw_writes_merge_unchanged_groups() { + let _g = super::super::sockets::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + nsi_reset(); + let mut rw = vec![0xffu8; NL_INTERFACE_RW_SIZE]; + rw[0x10..0x14].copy_from_slice(&1u32.to_le_bytes()); + rw[0xc0..0xd0].copy_from_slice(&[7u8; 16]); + let key = NIC_LUID.to_le_bytes(); + let n = NL_INTERFACE_RW_SIZE as u32; + unsafe { + assert_eq!(nsi_set_all_parameters(NSI_STORE_ACTIVE, NSI_SET_DEFAULT, NPI_MS_IPV4_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, rw.as_ptr(), n), ERROR_SUCCESS); + let mut rw2 = vec![0xffu8; NL_INTERFACE_RW_SIZE]; + rw2[0x10..0x14].copy_from_slice(&2u32.to_le_bytes()); + assert_eq!(nsi_set_all_parameters(NSI_STORE_ACTIVE, NSI_SET_DEFAULT, NPI_MS_IPV4_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, rw2.as_ptr(), n), ERROR_SUCCESS); + let bad = 5u64.to_le_bytes(); + assert_eq!(nsi_set_all_parameters(NSI_STORE_ACTIVE, NSI_SET_DEFAULT, NPI_MS_IPV4_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, bad.as_ptr(), 8, rw.as_ptr(), n), ERROR_NOT_FOUND); + assert_eq!(nsi_set_all_parameters(NSI_STORE_ACTIVE, NSI_SET_DEFAULT, NPI_MS_TEREDO_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, rw.as_ptr(), n), ERROR_NOT_FOUND); + assert_eq!(nsi_set_all_parameters(NSI_STORE_ACTIVE, NSI_SET_DEFAULT, NPI_MS_IPV4_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, rw.as_ptr(), 0x10), ERROR_INVALID_PARAMETER); + } + let got = nsi_interface_rw(&NPI_MS_IPV4_MODULEID, NIC_LUID).unwrap(); + assert_eq!(rd32(&got, 0x10), 2); + assert_eq!(&got[0xc0..0xd0], &[7u8; 16]); + assert!(got[0x20..0x30].iter().all(|b| *b == 0xff)); + assert!(nsi_interface_rw(&NPI_MS_IPV6_MODULEID, NIC_LUID).is_none()); + nsi_reset(); + } +} + +mod nsi_read { + use super::super::iphlp::*; + use super::super::*; + use super::rd32; + + #[test] + fn nsi_get_all_parameters_returns_written_interface_rows() { + let _g = super::super::sockets::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + nsi_reset(); + let key = NIC_LUID.to_le_bytes(); + let mut out = vec![0u8; NL_INTERFACE_RW_SIZE]; + let n = NL_INTERFACE_RW_SIZE as u32; + let null = core::ptr::null_mut(); + unsafe { + assert_eq!(nsi_get_all_parameters(1, NPI_MS_IPV6_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, out.as_mut_ptr(), n, null, 0, null, 0), ERROR_NOT_FOUND); + let mut rw = vec![0xffu8; NL_INTERFACE_RW_SIZE]; + rw[0xbc..0xc0].copy_from_slice(&9u32.to_le_bytes()); + assert_eq!(nsi_set_all_parameters(NSI_STORE_ACTIVE, NSI_SET_DEFAULT, NPI_MS_IPV6_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, rw.as_ptr(), n), ERROR_SUCCESS); + assert_eq!(nsi_get_all_parameters(1, NPI_MS_IPV6_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, out.as_mut_ptr(), n, null, 0, null, 0), ERROR_SUCCESS); + assert_eq!(rd32(&out, 0xbc), 9); + assert_eq!(nsi_get_all_parameters(1, NPI_MS_IPV4_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, out.as_mut_ptr(), n, null, 0, null, 0), ERROR_NOT_FOUND); + assert_eq!(nsi_get_all_parameters(1, NPI_MS_IPV6_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, out.as_mut_ptr(), 4, null, 0, null, 0), ERROR_INVALID_PARAMETER); + let mut rod = [0u8; 16]; + assert_eq!(nsi_get_all_parameters(1, NPI_MS_IPV6_MODULEID.as_ptr(), NL_INTERFACE_OBJECT, key.as_ptr(), 8, out.as_mut_ptr(), n, rod.as_mut_ptr(), 16, null, 0), ERROR_NOT_SUPPORTED); + assert_eq!(nsi_get_all_parameters(1, NPI_MS_TEREDO_MODULEID.as_ptr(), NSI_TEREDO_OBJECT_STATE, core::ptr::null(), 0, out.as_mut_ptr(), 12, null, 0, null, 0), ERROR_SUCCESS); + } + nsi_reset(); + } +} diff --git a/crates/compat/compat-common/src/netview/wfp.rs b/crates/compat/compat-common/src/netview/wfp.rs new file mode 100644 index 00000000..980ae71c --- /dev/null +++ b/crates/compat/compat-common/src/netview/wfp.rs @@ -0,0 +1,1232 @@ +use core::ffi::c_void; +use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::OnceLock; + +use super::wfp_codec::{struct_codec, Codec, R, W}; +use super::wfp_names; + +extern "system" { + fn CreateFileMappingW(file: *mut c_void, sa: *mut c_void, protect: u32, high: u32, low: u32, name: *const u16) -> *mut c_void; + fn MapViewOfFile(h: *mut c_void, access: u32, high: u32, low: u32, n: usize) -> *mut c_void; + fn GetCurrentProcessId() -> u32; +} + +pub const ERROR_INVALID_HANDLE: u32 = 6; +pub const ERROR_NOT_ENOUGH_MEMORY: u32 = 8; +pub const ERROR_INVALID_PARAMETER: u32 = 87; +pub const FWP_E_CALLOUT_NOT_FOUND: u32 = 0x8032_0001; +pub const FWP_E_FILTER_NOT_FOUND: u32 = 0x8032_0003; +pub const FWP_E_LAYER_NOT_FOUND: u32 = 0x8032_0004; +pub const FWP_E_PROVIDER_NOT_FOUND: u32 = 0x8032_0005; +pub const FWP_E_PROVIDER_CONTEXT_NOT_FOUND: u32 = 0x8032_0006; +pub const FWP_E_SUBLAYER_NOT_FOUND: u32 = 0x8032_0007; +pub const FWP_E_ALREADY_EXISTS: u32 = 0x8032_0009; +pub const FWP_E_IN_USE: u32 = 0x8032_000A; +pub const FWP_E_DYNAMIC_SESSION_IN_PROGRESS: u32 = 0x8032_000B; +pub const FWP_E_NO_TXN_IN_PROGRESS: u32 = 0x8032_000D; +pub const FWP_E_TXN_IN_PROGRESS: u32 = 0x8032_000E; + +pub const FWPM_SESSION_FLAG_DYNAMIC: u32 = 0x1; +pub const FWPM_PROVIDER_FLAG_PERSISTENT: u32 = 0x1; +pub const FWPM_SUBLAYER_FLAG_PERSISTENT: u32 = 0x1; +pub const FWPM_CALLOUT_FLAG_PERSISTENT: u32 = 0x1_0000; +pub const FWPM_FILTER_FLAG_PERSISTENT: u32 = 0x1; +pub const FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT: u32 = 0x4; +pub const FWPM_PROVIDER_CONTEXT_FLAG_PERSISTENT: u32 = 0x1; +pub const FWP_ACTION_FLAG_CALLOUT: u32 = 0x4000; + +pub const FWPM_IPSEC_KEYING_CONTEXT: u32 = 0; +pub const FWPM_CLASSIFY_OPTIONS_CONTEXT: u32 = 7; +pub const FWPM_GENERAL_CONTEXT: u32 = 8; +pub const FWPM_PROVIDER_CONTEXT_TYPE_MAX: u32 = 13; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Provider, + ProviderContext, + SubLayer, + Callout, + Filter, + IpsecSaContext, + IpsecSa, + IkeSa, + AleEndpoint, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Provider { + pub key: [u8; 16], + pub name: Option>, + pub description: Option>, + pub flags: u32, + pub data: Vec, + pub service_name: Option>, +} +struct_codec!(Provider { key, name, description, flags, data, service_name }); + +#[derive(Clone, Debug, PartialEq)] +pub struct SubLayer { + pub key: [u8; 16], + pub name: Option>, + pub description: Option>, + pub flags: u32, + pub provider_key: Option<[u8; 16]>, + pub data: Vec, + pub weight: u16, +} +struct_codec!(SubLayer { key, name, description, flags, provider_key, data, weight }); + +#[derive(Clone, Debug, PartialEq)] +pub struct Callout { + pub key: [u8; 16], + pub name: Option>, + pub description: Option>, + pub flags: u32, + pub provider_key: Option<[u8; 16]>, + pub data: Vec, + pub layer: [u8; 16], + pub id: u32, +} +struct_codec!(Callout { key, name, description, flags, provider_key, data, layer, id }); + +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + Empty, + U8(u8), + U16(u16), + U32(u32), + U64(u64), + I8(i8), + I16(i16), + I32(i32), + I64(i64), + F32(f32), + F64(f64), + Bytes16([u8; 16]), + Blob(Vec), + Sid(Vec), + SecurityDescriptor(Vec), + TokenInformation(bool), + TokenAccessInformation(bool), + Unicode(Option>), + Bytes6([u8; 6]), + V4AddrMask(u32, u32), + V6AddrMask([u8; 16], u8), + Range(Box, Box), + Other(u32), +} + +impl Value { + pub fn data_type(&self) -> u32 { + match self { + Value::Empty => 0, + Value::U8(_) => 1, + Value::U16(_) => 2, + Value::U32(_) => 3, + Value::U64(_) => 4, + Value::I8(_) => 5, + Value::I16(_) => 6, + Value::I32(_) => 7, + Value::I64(_) => 8, + Value::F32(_) => 9, + Value::F64(_) => 10, + Value::Bytes16(_) => 11, + Value::Blob(_) => 12, + Value::Sid(_) => 13, + Value::SecurityDescriptor(_) => 14, + Value::TokenInformation(_) => 15, + Value::TokenAccessInformation(_) => 16, + Value::Unicode(_) => 17, + Value::Bytes6(_) => 18, + Value::V4AddrMask(..) => 0x100, + Value::V6AddrMask(..) => 0x101, + Value::Range(..) => 0x102, + Value::Other(t) => *t, + } + } +} + +impl Codec for Value { + fn put(&self, w: &mut W) { + self.data_type().put(w); + match self { + Value::Empty => {} + Value::U8(v) => v.put(w), + Value::U16(v) => v.put(w), + Value::U32(v) => v.put(w), + Value::U64(v) => v.put(w), + Value::I8(v) => v.put(w), + Value::I16(v) => v.put(w), + Value::I32(v) => v.put(w), + Value::I64(v) => v.put(w), + Value::F32(v) => v.put(w), + Value::F64(v) => v.put(w), + Value::Bytes16(v) => v.put(w), + Value::Blob(v) | Value::Sid(v) | Value::SecurityDescriptor(v) => v.put(w), + Value::TokenInformation(v) | Value::TokenAccessInformation(v) => v.put(w), + Value::Unicode(v) => v.put(w), + Value::Bytes6(v) => v.put(w), + Value::V4AddrMask(a, m) => { + a.put(w); + m.put(w); + } + Value::V6AddrMask(a, p) => { + a.put(w); + p.put(w); + } + Value::Range(l, h) => { + l.put(w); + h.put(w); + } + Value::Other(_) => {} + } + } + fn get(r: &mut R) -> Option { + Some(match u32::get(r)? { + 0 => Value::Empty, + 1 => Value::U8(Codec::get(r)?), + 2 => Value::U16(Codec::get(r)?), + 3 => Value::U32(Codec::get(r)?), + 4 => Value::U64(Codec::get(r)?), + 5 => Value::I8(Codec::get(r)?), + 6 => Value::I16(Codec::get(r)?), + 7 => Value::I32(Codec::get(r)?), + 8 => Value::I64(Codec::get(r)?), + 9 => Value::F32(Codec::get(r)?), + 10 => Value::F64(Codec::get(r)?), + 11 => Value::Bytes16(Codec::get(r)?), + 12 => Value::Blob(Codec::get(r)?), + 13 => Value::Sid(Codec::get(r)?), + 14 => Value::SecurityDescriptor(Codec::get(r)?), + 15 => Value::TokenInformation(Codec::get(r)?), + 16 => Value::TokenAccessInformation(Codec::get(r)?), + 17 => Value::Unicode(Codec::get(r)?), + 18 => Value::Bytes6(Codec::get(r)?), + 0x100 => Value::V4AddrMask(Codec::get(r)?, Codec::get(r)?), + 0x101 => Value::V6AddrMask(Codec::get(r)?, Codec::get(r)?), + 0x102 => Value::Range(Codec::get(r)?, Codec::get(r)?), + t => Value::Other(t), + }) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Condition { + pub field: [u8; 16], + pub match_type: u32, + pub value: Value, +} +struct_codec!(Condition { field, match_type, value }); + +#[derive(Clone, Debug, PartialEq)] +pub struct Filter { + pub key: [u8; 16], + pub name: Option>, + pub description: Option>, + pub flags: u32, + pub provider_key: Option<[u8; 16]>, + pub data: Vec, + pub layer: [u8; 16], + pub sublayer: [u8; 16], + pub weight: Value, + pub conditions: Vec, + pub action_type: u32, + pub action_key: [u8; 16], + pub context: [u8; 16], + pub reserved: Option<[u8; 16]>, + pub id: u64, + pub effective_weight: Value, +} +struct_codec!(Filter { key, name, description, flags, provider_key, data, layer, sublayer, weight, conditions, action_type, action_key, context, reserved, id, effective_weight }); + +#[derive(Clone, Debug, PartialEq)] +pub struct AuthTransform { + pub auth_type: u32, + pub auth_config: u8, + pub crypto_module: Option<[u8; 16]>, +} +struct_codec!(AuthTransform { auth_type, auth_config, crypto_module }); + +#[derive(Clone, Debug, PartialEq)] +pub struct CipherTransform { + pub cipher_type: u32, + pub cipher_config: u8, + pub crypto_module: Option<[u8; 16]>, +} +struct_codec!(CipherTransform { cipher_type, cipher_config, crypto_module }); + +#[derive(Clone, Debug, PartialEq)] +pub struct SaTransform { + pub kind: u32, + pub auth: AuthTransform, + pub cipher: CipherTransform, +} +struct_codec!(SaTransform { kind, auth, cipher }); + +#[derive(Clone, Debug, PartialEq)] +pub struct IpsecProposal { + pub lifetime: [u32; 3], + pub transforms: Vec, + pub pfs_group: u32, +} +struct_codec!(IpsecProposal { lifetime, transforms, pfs_group }); + +#[derive(Clone, Debug, PartialEq)] +pub struct CertName { + pub kind: u32, + pub name: Option>, +} +struct_codec!(CertName { kind, name }); + +#[derive(Clone, Debug, PartialEq)] +pub struct CertCriteria { + pub data: Vec, + pub hash: Vec, + pub eku: Option>>>, + pub name: Option, + pub flags: u32, +} +struct_codec!(CertCriteria { data, hash, eku, name, flags }); + +#[derive(Clone, Debug, PartialEq)] +pub struct CertAuth { + pub inbound_type: u32, + pub inbound: Vec, + pub outbound_type: u32, + pub outbound: Vec, + pub flags: u32, + pub url: Vec, +} +struct_codec!(CertAuth { inbound_type, inbound, outbound_type, outbound, flags, url }); + +#[derive(Clone, Debug, PartialEq)] +pub struct AuthMethod { + pub kind: u32, + pub psk: Vec, + pub psk_flags: u32, + pub cert: CertAuth, +} +struct_codec!(AuthMethod { kind, psk, psk_flags, cert }); + +#[derive(Clone, Debug, PartialEq)] +pub struct EmPolicy { + pub methods: Vec, + pub impersonation: u32, +} +struct_codec!(EmPolicy { methods, impersonation }); + +#[derive(Clone, Debug, PartialEq)] +pub struct TransportPolicy { + pub proposals: Vec, + pub flags: u32, + pub nd_allow_clear_timeout: u32, + pub idle_timeout: u32, + pub idle_timeout_failover: u32, + pub em_policy: Option, +} +struct_codec!(TransportPolicy { proposals, flags, nd_allow_clear_timeout, idle_timeout, idle_timeout_failover, em_policy }); + +#[derive(Clone, Debug, PartialEq)] +pub struct IkeProposal { + pub cipher: u32, + pub key_len: u32, + pub rounds: u32, + pub integrity: u32, + pub max_lifetime: u32, + pub dh_group: u32, + pub qm_limit: u32, +} +struct_codec!(IkeProposal { cipher, key_len, rounds, integrity, max_lifetime, dh_group, qm_limit }); + +#[derive(Clone, Debug, PartialEq)] +pub struct IkePolicy { + pub soft_expiration: u32, + pub methods: Vec, + pub impersonation: u32, + pub proposals: Vec, + pub flags: u32, + pub max_dynamic_filters: u32, + pub retransmit_secs: u32, +} +struct_codec!(IkePolicy { soft_expiration, methods, impersonation, proposals, flags, max_dynamic_filters, retransmit_secs }); + +#[derive(Clone, Debug, PartialEq)] +pub struct ClassifyOption { + pub kind: u32, + pub value: Value, +} +struct_codec!(ClassifyOption { kind, value }); + +#[derive(Clone, Debug, PartialEq)] +pub enum ContextBody { + Null, + Keying { key_mods: Vec<[u8; 16]>, flags: u32 }, + Transport(TransportPolicy), + MainMode(IkePolicy), + ClassifyOptions(Vec), + General(Vec), + Opaque, +} + +impl Codec for ContextBody { + fn put(&self, w: &mut W) { + match self { + ContextBody::Null => 0u8.put(w), + ContextBody::Keying { key_mods, flags } => { + 1u8.put(w); + key_mods.put(w); + flags.put(w); + } + ContextBody::Transport(t) => { + 2u8.put(w); + t.put(w); + } + ContextBody::MainMode(m) => { + 3u8.put(w); + m.put(w); + } + ContextBody::ClassifyOptions(o) => { + 4u8.put(w); + o.put(w); + } + ContextBody::General(g) => { + 5u8.put(w); + g.put(w); + } + ContextBody::Opaque => 6u8.put(w), + } + } + fn get(r: &mut R) -> Option { + Some(match u8::get(r)? { + 0 => ContextBody::Null, + 1 => ContextBody::Keying { key_mods: Codec::get(r)?, flags: Codec::get(r)? }, + 2 => ContextBody::Transport(Codec::get(r)?), + 3 => ContextBody::MainMode(Codec::get(r)?), + 4 => ContextBody::ClassifyOptions(Codec::get(r)?), + 5 => ContextBody::General(Codec::get(r)?), + 6 => ContextBody::Opaque, + _ => return None, + }) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ProviderContext { + pub key: [u8; 16], + pub name: Option>, + pub description: Option>, + pub flags: u32, + pub provider_key: Option<[u8; 16]>, + pub data: Vec, + pub kind: u32, + pub body: ContextBody, + pub id: u64, +} +struct_codec!(ProviderContext { key, name, description, flags, provider_key, data, kind, body, id }); + +#[derive(Clone, Debug, PartialEq)] +pub struct AleEndpoint { + pub id: u64, + pub ip_version: u32, + pub local: [u8; 16], + pub remote: [u8; 16], + pub protocol: u8, + pub local_port: u16, + pub remote_port: u16, + pub token_id: u64, + pub mm_sa: u64, + pub qm_sa: u64, + pub ipsec_status: u32, + pub flags: u32, + pub app_id: Vec, +} +struct_codec!(AleEndpoint { id, ip_version, local, remote, protocol, local_port, remote_port, token_id, mm_sa, qm_sa, ipsec_status, flags, app_id }); + +#[derive(Clone, Debug, PartialEq)] +pub struct Traffic { + pub ip_version: u32, + pub local: [u8; 16], + pub remote: [u8; 16], + pub traffic_type: u32, + pub filter_or_policy_id: u64, + pub remote_port: u16, + pub local_port: u16, + pub protocol: u8, + pub local_if_luid: u64, + pub real_if_profile_id: u32, +} +struct_codec!(Traffic { ip_version, local, remote, traffic_type, filter_or_policy_id, remote_port, local_port, protocol, local_if_luid, real_if_profile_id }); + +#[derive(Clone, Debug, PartialEq)] +pub struct IpsecToken { + pub kind: u32, + pub principal: u32, + pub mode: u32, + pub token: u64, +} +struct_codec!(IpsecToken { kind, principal, mode, token }); + +#[derive(Clone, Debug, PartialEq)] +pub struct IpsecId { + pub mm_target: Option>, + pub em_target: Option>, + pub tokens: Vec, + pub explicit_credentials: u64, + pub logon_id: u64, +} +struct_codec!(IpsecId { mm_target, em_target, tokens, explicit_credentials, logon_id }); + +#[derive(Clone, Debug, PartialEq)] +pub struct Sa { + pub spi: u32, + pub transform: u32, + pub auth: AuthTransform, + pub auth_key: Vec, + pub cipher: CipherTransform, + pub cipher_key: Vec, +} +struct_codec!(Sa { spi, transform, auth, auth_key, cipher, cipher_key }); + +#[derive(Clone, Debug, PartialEq)] +pub struct KeyModuleState { + pub key: [u8; 16], + pub state: Vec, +} +struct_codec!(KeyModuleState { key, state }); + +#[derive(Clone, Debug, PartialEq)] +pub struct SaBundle { + pub flags: u32, + pub lifetime: [u32; 3], + pub idle_timeout: u32, + pub nd_allow_clear_timeout: u32, + pub ipsec_id: Option, + pub nap_context: u32, + pub qm_sa_id: u32, + pub sas: Vec, + pub key_module: Option, + pub ip_version: u32, + pub peer_v4_private: u32, + pub mm_sa_id: u64, + pub pfs_group: u32, + pub sa_lookup_context: [u8; 16], + pub qm_filter_id: u64, +} +struct_codec!(SaBundle { flags, lifetime, idle_timeout, nd_allow_clear_timeout, ipsec_id, nap_context, qm_sa_id, sas, key_module, ip_version, peer_v4_private, mm_sa_id, pfs_group, sa_lookup_context, qm_filter_id }); + +#[derive(Clone, Debug, PartialEq)] +pub struct SaDetails { + pub ip_version: u32, + pub direction: u32, + pub traffic: Traffic, + pub bundle: SaBundle, + pub udp_encap: Option<(u16, u16)>, + pub transport_filter: Option>, +} +struct_codec!(SaDetails { ip_version, direction, traffic, bundle, udp_encap, transport_filter }); + +#[derive(Clone, Debug, PartialEq)] +pub struct SaContext { + pub id: u64, + pub inbound: SaDetails, + pub outbound: SaDetails, +} +struct_codec!(SaContext { id, inbound, outbound }); + +#[derive(Clone, Debug, PartialEq)] +pub enum CredentialBody { + None, + PresharedKey { key: Vec, flags: u32 }, + Certificate { subject: Vec, hash: Vec, flags: u32, certificate: Vec }, + Name(Option>), +} + +impl Codec for CredentialBody { + fn put(&self, w: &mut W) { + match self { + CredentialBody::None => 0u8.put(w), + CredentialBody::PresharedKey { key, flags } => { + 1u8.put(w); + key.put(w); + flags.put(w); + } + CredentialBody::Certificate { subject, hash, flags, certificate } => { + 2u8.put(w); + subject.put(w); + hash.put(w); + flags.put(w); + certificate.put(w); + } + CredentialBody::Name(n) => { + 3u8.put(w); + n.put(w); + } + } + } + fn get(r: &mut R) -> Option { + Some(match u8::get(r)? { + 0 => CredentialBody::None, + 1 => CredentialBody::PresharedKey { key: Codec::get(r)?, flags: Codec::get(r)? }, + 2 => CredentialBody::Certificate { subject: Codec::get(r)?, hash: Codec::get(r)?, flags: Codec::get(r)?, certificate: Codec::get(r)? }, + 3 => CredentialBody::Name(Codec::get(r)?), + _ => return None, + }) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Credential { + pub kind: u32, + pub impersonation: u32, + pub body: CredentialBody, +} +struct_codec!(Credential { kind, impersonation, body }); + +#[derive(Clone, Debug, PartialEq)] +pub struct IkeSa { + pub id: u64, + pub key_module: u32, + pub ip_version: u32, + pub udp_encap: Option<(u16, u16)>, + pub traffic_ip_version: u32, + pub local: [u8; 16], + pub remote: [u8; 16], + pub auth_ip_filter_id: u64, + pub proposal: IkeProposal, + pub cookie_initiator: u64, + pub cookie_responder: u64, + pub credentials: Vec<(Credential, Credential)>, + pub policy_key: [u8; 16], + pub virtual_if_tunnel_id: u64, + pub correlation_key: Vec, +} +struct_codec!(IkeSa { id, key_module, ip_version, udp_encap, traffic_ip_version, local, remote, auth_ip_filter_id, proposal, cookie_initiator, cookie_responder, credentials, policy_key, virtual_if_tunnel_id, correlation_key }); + +#[derive(Clone, Debug, PartialEq)] +pub enum Object { + Provider(Provider), + SubLayer(SubLayer), + Callout(Callout), + Filter(Filter), + ProviderContext(ProviderContext), + AleEndpoint(AleEndpoint), + SaContext(SaContext), + IpsecSa(SaDetails), + IkeSa(IkeSa), +} + +impl Codec for Object { + fn put(&self, w: &mut W) { + match self { + Object::Provider(v) => { + 0u8.put(w); + v.put(w); + } + Object::SubLayer(v) => { + 1u8.put(w); + v.put(w); + } + Object::Callout(v) => { + 2u8.put(w); + v.put(w); + } + Object::Filter(v) => { + 3u8.put(w); + v.put(w); + } + Object::ProviderContext(v) => { + 4u8.put(w); + v.put(w); + } + Object::AleEndpoint(v) => { + 5u8.put(w); + v.put(w); + } + Object::SaContext(v) => { + 6u8.put(w); + v.put(w); + } + Object::IpsecSa(v) => { + 7u8.put(w); + v.put(w); + } + Object::IkeSa(v) => { + 8u8.put(w); + v.put(w); + } + } + } + fn get(r: &mut R) -> Option { + Some(match u8::get(r)? { + 0 => Object::Provider(Codec::get(r)?), + 1 => Object::SubLayer(Codec::get(r)?), + 2 => Object::Callout(Codec::get(r)?), + 3 => Object::Filter(Codec::get(r)?), + 4 => Object::ProviderContext(Codec::get(r)?), + 5 => Object::AleEndpoint(Codec::get(r)?), + 6 => Object::SaContext(Codec::get(r)?), + 7 => Object::IpsecSa(Codec::get(r)?), + 8 => Object::IkeSa(Codec::get(r)?), + _ => return None, + }) + } +} + +impl Object { + fn key(&self) -> Option<[u8; 16]> { + match self { + Object::Provider(v) => Some(v.key), + Object::SubLayer(v) => Some(v.key), + Object::Callout(v) => Some(v.key), + Object::Filter(v) => Some(v.key), + Object::ProviderContext(v) => Some(v.key), + _ => None, + } + } + fn kind(&self) -> Kind { + match self { + Object::Provider(_) => Kind::Provider, + Object::SubLayer(_) => Kind::SubLayer, + Object::Callout(_) => Kind::Callout, + Object::Filter(_) => Kind::Filter, + Object::ProviderContext(_) => Kind::ProviderContext, + Object::AleEndpoint(_) => Kind::AleEndpoint, + Object::SaContext(_) => Kind::IpsecSaContext, + Object::IpsecSa(_) => Kind::IpsecSa, + Object::IkeSa(_) => Kind::IkeSa, + } + } + fn provider_key(&self) -> Option<[u8; 16]> { + match self { + Object::SubLayer(v) => v.provider_key, + Object::Callout(v) => v.provider_key, + Object::Filter(v) => v.provider_key, + Object::ProviderContext(v) => v.provider_key, + _ => None, + } + } +} + +struct Stored { + object: Object, + owner: Option, +} +struct_codec!(Stored { object, owner }); + +struct EnumState { + engine: u64, + items: Vec, + pos: u32, +} +struct_codec!(EnumState { engine, items, pos }); + +struct Session { + handle: u64, + flags: u32, + txn: bool, +} +struct_codec!(Session { handle, flags, txn }); + +struct Store { + next: u64, + sessions: Vec, + objects: Vec, + enums: Vec<(u64, EnumState)>, + next_filter_id: u64, + next_callout_id: u32, + next_context_id: u64, + auto_weight: u64, +} + +pub const SHARED_ARENA: usize = 1 << 20; +pub const FIRST_HANDLE: u64 = 0x5746_5000; + +#[repr(C)] +struct Header { + lock: AtomicU32, + len: AtomicU32, + next: AtomicU64, +} + +pub fn shared_mapping_name() -> String { + format!("Local\\TomBox.NetView.Wfp.{}", unsafe { GetCurrentProcessId() }) +} + +fn shared() -> Option { + static P: OnceLock = OnceLock::new(); + let p = *P.get_or_init(|| unsafe { + let name: Vec = shared_mapping_name().encode_utf16().chain(Some(0)).collect(); + let size = (core::mem::size_of::
() + SHARED_ARENA) as u32; + let h = CreateFileMappingW(-1isize as *mut c_void, core::ptr::null_mut(), 0x04, 0, size, name.as_ptr()); + if h.is_null() { + return 0; + } + MapViewOfFile(h, 0x0006, 0, 0, size as usize) as usize + }); + (p != 0).then_some(p) +} + +pub const AUTO_WEIGHT_TOP: u64 = (1u64 << 60) - 1; + +impl Store { + fn encode(&self) -> Vec { + let mut w = W(Vec::new()); + self.sessions.put(&mut w); + self.objects.put(&mut w); + self.enums.put(&mut w); + self.next_filter_id.put(&mut w); + self.next_callout_id.put(&mut w); + self.next_context_id.put(&mut w); + self.auto_weight.put(&mut w); + w.0 + } + fn decode(next: u64, b: &[u8]) -> Option { + if b.is_empty() { + return Some(Store { next, sessions: Vec::new(), objects: Vec::new(), enums: Vec::new(), next_filter_id: 1, next_callout_id: 1, next_context_id: 1, auto_weight: AUTO_WEIGHT_TOP }); + } + let mut r = R(b, 0); + Some(Store { + next, + sessions: Codec::get(&mut r)?, + objects: Codec::get(&mut r)?, + enums: Codec::get(&mut r)?, + next_filter_id: Codec::get(&mut r)?, + next_callout_id: Codec::get(&mut r)?, + next_context_id: Codec::get(&mut r)?, + auto_weight: Codec::get(&mut r)?, + }) + } + fn alloc(&mut self) -> u64 { + self.next += 4; + self.next + } + fn session(&mut self, h: u64) -> Option<&mut Session> { + self.sessions.iter_mut().find(|s| s.handle == h) + } + fn find(&self, kind: Kind, key: &[u8; 16]) -> Option<&Object> { + self.objects.iter().map(|o| &o.object).find(|o| o.kind() == kind && o.key().as_ref() == Some(key)) + } + fn has(&self, kind: Kind, key: &[u8; 16]) -> bool { + self.find(kind, key).is_some() + } + fn add(&mut self, engine: u64, persistent: bool, o: Object) -> Result<(), u32> { + let Some(sess) = self.session(engine) else { + return Err(ERROR_INVALID_HANDLE); + }; + let dynamic = sess.flags & FWPM_SESSION_FLAG_DYNAMIC != 0; + if dynamic && persistent { + return Err(FWP_E_DYNAMIC_SESSION_IN_PROGRESS); + } + if let Some(k) = o.key() { + if self.has(o.kind(), &k) { + return Err(FWP_E_ALREADY_EXISTS); + } + } + if let Some(p) = o.provider_key() { + if !self.has(Kind::Provider, &p) { + return Err(FWP_E_PROVIDER_NOT_FOUND); + } + } + self.objects.push(Stored { object: o, owner: if dynamic { Some(engine) } else { None } }); + Ok(()) + } + fn referenced(&self, kind: Kind, key: &[u8; 16]) -> bool { + self.objects.iter().any(|s| match (&s.object, kind) { + (o, Kind::Provider) => o.provider_key().as_ref() == Some(key), + (Object::Filter(f), Kind::SubLayer) => &f.sublayer == key, + (Object::Filter(f), Kind::Callout) => f.action_type & FWP_ACTION_FLAG_CALLOUT != 0 && &f.action_key == key, + (Object::Filter(f), Kind::ProviderContext) => f.flags & FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT != 0 && &f.context == key, + _ => false, + }) + } + fn delete(&mut self, engine: u64, kind: Kind, key: &[u8; 16], missing: u32) -> u32 { + if self.session(engine).is_none() { + return ERROR_INVALID_HANDLE; + } + let Some(i) = self.objects.iter().position(|s| s.object.kind() == kind && s.object.key().as_ref() == Some(key)) else { + return missing; + }; + if self.referenced(kind, key) { + return FWP_E_IN_USE; + } + self.objects.remove(i); + 0 + } + fn get(&mut self, engine: u64, kind: Kind, key: &[u8; 16], missing: u32) -> Result { + if self.session(engine).is_none() { + return Err(ERROR_INVALID_HANDLE); + } + self.find(kind, key).cloned().ok_or(missing) + } +} + +fn with_store(f: impl FnOnce(&mut Store) -> Result) -> Result { + let base = shared().ok_or(ERROR_NOT_ENOUGH_MEMORY)?; + let hdr = unsafe { &*(base as *const Header) }; + while hdr.lock.compare_exchange(0, 1, Ordering::Acquire, Ordering::Relaxed).is_err() { + std::thread::yield_now(); + } + let arena = unsafe { core::slice::from_raw_parts_mut((base + core::mem::size_of::
()) as *mut u8, SHARED_ARENA) }; + let len = (hdr.len.load(Ordering::Relaxed) as usize).min(SHARED_ARENA); + let next = match hdr.next.load(Ordering::Relaxed) { + 0 => FIRST_HANDLE, + n => n, + }; + let out = match Store::decode(next, &arena[..len]) { + None => Err(ERROR_NOT_ENOUGH_MEMORY), + Some(mut st) => match f(&mut st) { + Err(e) => Err(e), + Ok(v) => { + let bytes = st.encode(); + if bytes.len() > SHARED_ARENA { + Err(ERROR_NOT_ENOUGH_MEMORY) + } else { + arena[..bytes.len()].copy_from_slice(&bytes); + hdr.len.store(bytes.len() as u32, Ordering::Relaxed); + hdr.next.store(st.next, Ordering::Relaxed); + Ok(v) + } + } + }, + }; + hdr.lock.store(0, Ordering::Release); + out +} + +fn status(r: Result) -> u32 { + match r { + Ok(v) | Err(v) => v, + } +} + +fn code(r: Result<(), u32>) -> u32 { + match r { + Ok(()) => 0, + Err(e) => e, + } +} + +pub fn is_builtin(prefix: &str, key: &[u8; 16]) -> bool { + wfp_names::NAMES.iter().any(|(k, n)| k == key && n.starts_with(prefix)) +} + +pub fn engine_open(session_flags: u32) -> Result { + with_store(|s| { + let h = s.alloc(); + s.sessions.push(Session { handle: h, flags: session_flags, txn: false }); + Ok(h) + }) +} + +pub fn engine_close(engine: u64) -> u32 { + status(with_store(|s| { + let Some(i) = s.sessions.iter().position(|x| x.handle == engine) else { + return Ok(ERROR_INVALID_HANDLE); + }; + let sess = s.sessions.remove(i); + if sess.flags & FWPM_SESSION_FLAG_DYNAMIC != 0 { + s.objects.retain(|p| p.owner != Some(engine)); + } + s.enums.retain(|(_, e)| e.engine != engine); + Ok(0) + })) +} + +pub fn transaction_begin(engine: u64) -> u32 { + status(with_store(|s| { + Ok(match s.session(engine) { + None => ERROR_INVALID_HANDLE, + Some(x) if x.txn => FWP_E_TXN_IN_PROGRESS, + Some(x) => { + x.txn = true; + 0 + } + }) + })) +} + +pub fn transaction_commit(engine: u64) -> u32 { + status(with_store(|s| { + Ok(match s.session(engine) { + None => ERROR_INVALID_HANDLE, + Some(x) if !x.txn => FWP_E_NO_TXN_IN_PROGRESS, + Some(x) => { + x.txn = false; + 0 + } + }) + })) +} + +pub fn transaction_abort(engine: u64) -> u32 { + transaction_commit(engine) +} + +pub fn provider_add(engine: u64, p: Provider) -> u32 { + status(with_store(|s| { + if s.session(engine).is_none() { + return Ok(ERROR_INVALID_HANDLE); + } + if p.name.is_none() { + return Ok(ERROR_INVALID_PARAMETER); + } + let persistent = p.flags & FWPM_PROVIDER_FLAG_PERSISTENT != 0; + Ok(code(s.add(engine, persistent, Object::Provider(p)))) + })) +} + +pub fn provider_get_by_key(engine: u64, key: &[u8; 16]) -> Result { + match with_store(|s| s.get(engine, Kind::Provider, key, FWP_E_PROVIDER_NOT_FOUND))? { + Object::Provider(p) => Ok(p), + _ => Err(FWP_E_PROVIDER_NOT_FOUND), + } +} + +pub fn provider_delete_by_key(engine: u64, key: &[u8; 16]) -> u32 { + status(with_store(|s| Ok(s.delete(engine, Kind::Provider, key, FWP_E_PROVIDER_NOT_FOUND)))) +} + +pub fn sublayer_add(engine: u64, l: SubLayer) -> u32 { + status(with_store(|s| { + if s.session(engine).is_none() { + return Ok(ERROR_INVALID_HANDLE); + } + if l.name.is_none() { + return Ok(ERROR_INVALID_PARAMETER); + } + if is_builtin("FWPM_SUBLAYER_", &l.key) { + return Ok(FWP_E_ALREADY_EXISTS); + } + let persistent = l.flags & FWPM_SUBLAYER_FLAG_PERSISTENT != 0; + Ok(code(s.add(engine, persistent, Object::SubLayer(l)))) + })) +} + +pub fn sublayer_get_by_key(engine: u64, key: &[u8; 16]) -> Result { + match with_store(|s| s.get(engine, Kind::SubLayer, key, FWP_E_SUBLAYER_NOT_FOUND))? { + Object::SubLayer(v) => Ok(v), + _ => Err(FWP_E_SUBLAYER_NOT_FOUND), + } +} + +pub fn sublayer_delete_by_key(engine: u64, key: &[u8; 16]) -> u32 { + status(with_store(|s| Ok(s.delete(engine, Kind::SubLayer, key, FWP_E_SUBLAYER_NOT_FOUND)))) +} + +pub fn callout_add(engine: u64, mut c: Callout) -> Result { + with_store(|s| { + if s.session(engine).is_none() { + return Err(ERROR_INVALID_HANDLE); + } + if c.name.is_none() { + return Err(ERROR_INVALID_PARAMETER); + } + if !is_builtin("FWPM_LAYER_", &c.layer) { + return Err(FWP_E_LAYER_NOT_FOUND); + } + if is_builtin("FWPM_CALLOUT_", &c.key) { + return Err(FWP_E_ALREADY_EXISTS); + } + let id = s.next_callout_id; + c.id = id; + let persistent = c.flags & FWPM_CALLOUT_FLAG_PERSISTENT != 0; + s.add(engine, persistent, Object::Callout(c))?; + s.next_callout_id += 1; + Ok(id) + }) +} + +pub fn callout_get_by_key(engine: u64, key: &[u8; 16]) -> Result { + match with_store(|s| s.get(engine, Kind::Callout, key, FWP_E_CALLOUT_NOT_FOUND))? { + Object::Callout(v) => Ok(v), + _ => Err(FWP_E_CALLOUT_NOT_FOUND), + } +} + +pub fn callout_delete_by_key(engine: u64, key: &[u8; 16]) -> u32 { + status(with_store(|s| Ok(s.delete(engine, Kind::Callout, key, FWP_E_CALLOUT_NOT_FOUND)))) +} + +fn effective_weight(w: &Value, auto: &mut u64) -> Result { + match w { + Value::U64(v) => Ok(Value::U64(*v)), + Value::U8(v) if *v <= 15 => Ok(Value::U64((*v as u64) << 60 | (*auto & AUTO_WEIGHT_TOP))), + Value::Empty => Ok(Value::U64(*auto)), + _ => Err(ERROR_INVALID_PARAMETER), + } +} + +pub fn filter_add(engine: u64, mut f: Filter) -> Result { + with_store(|s| { + if s.session(engine).is_none() { + return Err(ERROR_INVALID_HANDLE); + } + if f.name.is_none() { + return Err(ERROR_INVALID_PARAMETER); + } + if !is_builtin("FWPM_LAYER_", &f.layer) { + return Err(FWP_E_LAYER_NOT_FOUND); + } + if f.sublayer != [0u8; 16] && !s.has(Kind::SubLayer, &f.sublayer) && !is_builtin("FWPM_SUBLAYER_", &f.sublayer) { + return Err(FWP_E_SUBLAYER_NOT_FOUND); + } + if f.action_type & FWP_ACTION_FLAG_CALLOUT != 0 && !s.has(Kind::Callout, &f.action_key) && !is_builtin("FWPM_CALLOUT_", &f.action_key) { + return Err(FWP_E_CALLOUT_NOT_FOUND); + } + if f.flags & FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT != 0 && !s.has(Kind::ProviderContext, &f.context) { + return Err(FWP_E_PROVIDER_CONTEXT_NOT_FOUND); + } + let mut auto = s.auto_weight; + f.effective_weight = effective_weight(&f.weight, &mut auto)?; + let id = s.next_filter_id; + f.id = id; + let persistent = f.flags & FWPM_FILTER_FLAG_PERSISTENT != 0; + s.add(engine, persistent, Object::Filter(f))?; + s.next_filter_id += 1; + s.auto_weight = s.auto_weight.saturating_sub(1); + Ok(id) + }) +} + +pub fn filter_get_by_key(engine: u64, key: &[u8; 16]) -> Result { + match with_store(|s| s.get(engine, Kind::Filter, key, FWP_E_FILTER_NOT_FOUND))? { + Object::Filter(v) => Ok(v), + _ => Err(FWP_E_FILTER_NOT_FOUND), + } +} + +pub fn filter_delete_by_key(engine: u64, key: &[u8; 16]) -> u32 { + status(with_store(|s| Ok(s.delete(engine, Kind::Filter, key, FWP_E_FILTER_NOT_FOUND)))) +} + +pub fn filter_delete_by_id(engine: u64, id: u64) -> u32 { + status(with_store(|s| { + if s.session(engine).is_none() { + return Ok(ERROR_INVALID_HANDLE); + } + Ok(match s.objects.iter().position(|o| matches!(&o.object, Object::Filter(f) if f.id == id)) { + Some(i) => { + s.objects.remove(i); + 0 + } + None => FWP_E_FILTER_NOT_FOUND, + }) + })) +} + +fn body_fits(kind: u32, body: &ContextBody) -> bool { + match (kind, body) { + (FWPM_IPSEC_KEYING_CONTEXT, ContextBody::Keying { .. }) => true, + (FWPM_IPSEC_KEYING_CONTEXT, _) => false, + (1 | 3 | 12, ContextBody::Transport(_)) => true, + (5 | 6 | 10, ContextBody::MainMode(_)) => true, + (FWPM_CLASSIFY_OPTIONS_CONTEXT, ContextBody::ClassifyOptions(_)) => true, + (FWPM_GENERAL_CONTEXT, ContextBody::General(_)) => true, + (2 | 4 | 9 | 11, ContextBody::Opaque) => true, + _ => false, + } +} + +pub fn provider_context_add(engine: u64, mut c: ProviderContext) -> Result { + with_store(|s| { + if s.session(engine).is_none() { + return Err(ERROR_INVALID_HANDLE); + } + if c.name.is_none() || c.kind >= FWPM_PROVIDER_CONTEXT_TYPE_MAX || !body_fits(c.kind, &c.body) { + return Err(ERROR_INVALID_PARAMETER); + } + let id = s.next_context_id; + c.id = id; + let persistent = c.flags & FWPM_PROVIDER_CONTEXT_FLAG_PERSISTENT != 0; + s.add(engine, persistent, Object::ProviderContext(c))?; + s.next_context_id += 1; + Ok(id) + }) +} + +pub fn provider_context_get_by_key(engine: u64, key: &[u8; 16]) -> Result { + match with_store(|s| s.get(engine, Kind::ProviderContext, key, FWP_E_PROVIDER_CONTEXT_NOT_FOUND))? { + Object::ProviderContext(v) => Ok(v), + _ => Err(FWP_E_PROVIDER_CONTEXT_NOT_FOUND), + } +} + +pub fn provider_context_delete_by_key(engine: u64, key: &[u8; 16]) -> u32 { + status(with_store(|s| Ok(s.delete(engine, Kind::ProviderContext, key, FWP_E_PROVIDER_CONTEXT_NOT_FOUND)))) +} + +fn open_enum(s: &mut Store, engine: u64, items: Vec) -> u64 { + let h = s.alloc(); + s.enums.push((h, EnumState { engine, items, pos: 0 })); + h +} + +pub fn create_enum_handle(engine: u64, kind: Kind) -> Result { + with_store(|s| { + if s.session(engine).is_none() { + return Err(ERROR_INVALID_HANDLE); + } + let items = s.objects.iter().map(|o| o.object.clone()).filter(|o| o.kind() == kind).collect(); + Ok(open_enum(s, engine, items)) + }) +} + +pub fn create_filter_enum_handle(engine: u64, layer: Option<[u8; 16]>) -> Result { + with_store(|s| { + if s.session(engine).is_none() { + return Err(ERROR_INVALID_HANDLE); + } + if let Some(l) = layer { + if !is_builtin("FWPM_LAYER_", &l) { + return Err(FWP_E_LAYER_NOT_FOUND); + } + } + let items = s.objects.iter().filter_map(|o| match &o.object { + Object::Filter(f) if layer.map(|l| l == f.layer).unwrap_or(true) => Some(o.object.clone()), + _ => None, + }).collect(); + Ok(open_enum(s, engine, items)) + }) +} + +pub fn enum_next(engine: u64, handle: u64, requested: u32) -> Result, u32> { + with_store(|s| { + if s.session(engine).is_none() { + return Err(ERROR_INVALID_HANDLE); + } + let Some((_, e)) = s.enums.iter_mut().find(|(h, e)| *h == handle && e.engine == engine) else { + return Err(ERROR_INVALID_HANDLE); + }; + let pos = e.pos as usize; + let end = (pos + requested as usize).min(e.items.len()); + let out = e.items[pos..end].to_vec(); + e.pos = end as u32; + Ok(out) + }) +} + +pub fn destroy_enum_handle(engine: u64, handle: u64) -> u32 { + status(with_store(|s| { + if s.session(engine).is_none() { + return Ok(ERROR_INVALID_HANDLE); + } + Ok(match s.enums.iter().position(|(h, e)| *h == handle && e.engine == engine) { + Some(i) => { + s.enums.remove(i); + 0 + } + None => ERROR_INVALID_HANDLE, + }) + })) +} + +pub fn provider_count() -> usize { + with_store(|s| Ok(s.objects.iter().filter(|o| o.object.kind() == Kind::Provider).count())).unwrap_or(0) +} + +pub fn object_count(kind: Kind) -> usize { + with_store(|s| Ok(s.objects.iter().filter(|o| o.object.kind() == kind).count())).unwrap_or(0) +} + +#[cfg(test)] +pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); diff --git a/crates/compat/compat-common/src/netview/wfp_codec.rs b/crates/compat/compat-common/src/netview/wfp_codec.rs new file mode 100644 index 00000000..ba6b7543 --- /dev/null +++ b/crates/compat/compat-common/src/netview/wfp_codec.rs @@ -0,0 +1,132 @@ +pub(crate) struct W(pub Vec); + +pub(crate) struct R<'a>(pub &'a [u8], pub usize); + +impl<'a> R<'a> { + pub fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let b = self.0.get(self.1..self.1.checked_add(n)?)?; + self.1 += n; + Some(b) + } +} + +pub(crate) trait Codec: Sized { + fn put(&self, w: &mut W); + fn get(r: &mut R) -> Option; +} + +macro_rules! num_codec { + ($($t:ty),*) => {$( + impl Codec for $t { + fn put(&self, w: &mut W) { + w.0.extend_from_slice(&self.to_le_bytes()); + } + fn get(r: &mut R) -> Option { + Some(<$t>::from_le_bytes(r.take(core::mem::size_of::<$t>())?.try_into().ok()?)) + } + } + )*}; +} + +num_codec!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64); + +impl Codec for bool { + fn put(&self, w: &mut W) { + w.0.push(*self as u8); + } + fn get(r: &mut R) -> Option { + Some(r.take(1)?[0] != 0) + } +} + +impl Codec for [u8; N] { + fn put(&self, w: &mut W) { + w.0.extend_from_slice(self); + } + fn get(r: &mut R) -> Option { + r.take(N)?.try_into().ok() + } +} + +impl Codec for [u32; 3] { + fn put(&self, w: &mut W) { + for v in self { + v.put(w); + } + } + fn get(r: &mut R) -> Option { + Some([u32::get(r)?, u32::get(r)?, u32::get(r)?]) + } +} + +impl Codec for Vec { + fn put(&self, w: &mut W) { + (self.len() as u32).put(w); + for v in self { + v.put(w); + } + } + fn get(r: &mut R) -> Option { + let n = u32::get(r)? as usize; + if n > r.0.len() { + return None; + } + let mut v = Vec::with_capacity(n); + for _ in 0..n { + v.push(T::get(r)?); + } + Some(v) + } +} + +impl Codec for Option { + fn put(&self, w: &mut W) { + match self { + None => w.0.push(0), + Some(v) => { + w.0.push(1); + v.put(w); + } + } + } + fn get(r: &mut R) -> Option { + match r.take(1)?[0] { + 0 => Some(None), + _ => Some(Some(T::get(r)?)), + } + } +} + +impl Codec for Box { + fn put(&self, w: &mut W) { + (**self).put(w); + } + fn get(r: &mut R) -> Option { + Some(Box::new(T::get(r)?)) + } +} + +impl Codec for (A, B) { + fn put(&self, w: &mut W) { + self.0.put(w); + self.1.put(w); + } + fn get(r: &mut R) -> Option { + Some((A::get(r)?, B::get(r)?)) + } +} + +macro_rules! struct_codec { + ($name:ident { $($f:ident),* $(,)? }) => { + impl $crate::netview::wfp_codec::Codec for $name { + fn put(&self, w: &mut $crate::netview::wfp_codec::W) { + $( $crate::netview::wfp_codec::Codec::put(&self.$f, w); )* + } + fn get(r: &mut $crate::netview::wfp_codec::R) -> Option { + Some($name { $( $f: $crate::netview::wfp_codec::Codec::get(r)?, )* }) + } + } + }; +} + +pub(crate) use struct_codec; diff --git a/crates/compat/compat-common/src/netview/wfp_names.rs b/crates/compat/compat-common/src/netview/wfp_names.rs new file mode 100644 index 00000000..d65eec38 --- /dev/null +++ b/crates/compat/compat-common/src/netview/wfp_names.rs @@ -0,0 +1,326 @@ +pub const NAMES: [([u8; 16], &str); 324] = [ + ([0xde, 0x44, 0x84, 0x74, 0x5a, 0xa4, 0x18, 0x4f, 0xb8, 0x86, 0x67, 0x48, 0x29, 0x57, 0xae, 0x09], "DurangoTemporaryOverrideProviderGuid"), + ([0x37, 0xbe, 0x1b, 0x55, 0x9e, 0xe2, 0xe6, 0x48, 0xb6, 0x55, 0xd6, 0x95, 0x00, 0xa6, 0xa9, 0x25], "XboxOnePersistentProviderGuid"), + ([0xca, 0x16, 0xcc, 0xde, 0x33, 0x3f, 0x46, 0x43, 0xbe, 0x1e, 0x8f, 0xb4, 0xae, 0x0f, 0x3d, 0x62], "MpssvcProviderGuid"), + ([0x41, 0xd4, 0xcd, 0xb3, 0x90, 0xaf, 0xba, 0x41, 0xa7, 0x45, 0x7c, 0x60, 0x08, 0xff, 0x23, 0x00], "MpssvcWindowsServiceHardeningSublayerGuid"), + ([0x41, 0xd4, 0xcd, 0xb3, 0x90, 0xaf, 0xba, 0x41, 0xa7, 0x45, 0x7c, 0x60, 0x08, 0xff, 0x23, 0x01], "MpssvcWindowsFirewallSublayerGuid"), + ([0x41, 0xd4, 0xcd, 0xb3, 0x90, 0xaf, 0xba, 0x41, 0xa7, 0x45, 0x7c, 0x60, 0x08, 0xff, 0x23, 0x02], "MpssvcQuarantineSublayerGuid"), + ([0xc3, 0x21, 0xe2, 0xff, 0xa8, 0x92, 0x64, 0x45, 0xa5, 0x9f, 0xda, 0xfb, 0x70, 0x75, 0x60, 0x20], "MpssvcAppIsolationSublayerGuid"), + ([0x69, 0xc9, 0xeb, 0x1b, 0xa5, 0x61, 0x32, 0x47, 0xa1, 0x77, 0x84, 0x7a, 0x08, 0x17, 0x86, 0x2a], "MipsProviderGuid"), + ([0x13, 0x00, 0xa3, 0x9b, 0x4e, 0xc8, 0xe5, 0x47, 0xac, 0x6e, 0x1e, 0x1a, 0xed, 0x72, 0xfa, 0x69], "MipsMmRuleSublayerGuid"), + ([0x22, 0x4f, 0x3a, 0x89, 0xba, 0x9b, 0xb7, 0x49, 0x8c, 0x66, 0x3d, 0x40, 0x92, 0x9c, 0x8f, 0xd5], "TeredoProviderGuid"), + ([0xf6, 0x11, 0x6b, 0x7b, 0xb5, 0xcb, 0x3c, 0x43, 0xae, 0x06, 0x6a, 0x4f, 0x00, 0x76, 0xe4, 0x9e], "TeredoEdgeTraversalAuthorizationSublayerGuid"), + ([0x62, 0x66, 0xf2, 0x7b, 0x86, 0x18, 0x58, 0x4d, 0x85, 0xc4, 0x50, 0x7c, 0xce, 0x2a, 0x53, 0xc5], "TeredoWfpSublayerGuid"), + ([0xbf, 0xd1, 0x6f, 0xc8, 0xcd, 0x21, 0x7e, 0x49, 0xa0, 0xbb, 0x17, 0x42, 0x5c, 0x88, 0x5c, 0x58], "FWPM_LAYER_INBOUND_IPPACKET_V4"), + ([0xd0, 0x30, 0xa2, 0xb5, 0xc0, 0xa8, 0xf2, 0x44, 0x91, 0x6e, 0x99, 0x1b, 0x53, 0xde, 0xd1, 0xf7], "FWPM_LAYER_INBOUND_IPPACKET_V4_DISCARD"), + ([0xcb, 0x32, 0x20, 0xf5, 0x1c, 0x99, 0xe7, 0x46, 0x97, 0x1d, 0x26, 0x01, 0x45, 0x9a, 0x91, 0xca], "FWPM_LAYER_INBOUND_IPPACKET_V6"), + ([0x79, 0xc2, 0x24, 0xbb, 0xb4, 0x93, 0xa2, 0x47, 0x83, 0xad, 0xae, 0x16, 0x98, 0xb5, 0x08, 0x85], "FWPM_LAYER_INBOUND_IPPACKET_V6_DISCARD"), + ([0xae, 0x9f, 0x5c, 0x1e, 0x84, 0x8a, 0x35, 0x41, 0xa3, 0x31, 0x95, 0x0b, 0x54, 0x22, 0x9e, 0xcd], "FWPM_LAYER_OUTBOUND_IPPACKET_V4"), + ([0xb5, 0xbc, 0xe4, 0x08, 0x47, 0xb6, 0xf3, 0x48, 0x95, 0x3c, 0xe5, 0xdd, 0xbd, 0x03, 0x93, 0x7e], "FWPM_LAYER_OUTBOUND_IPPACKET_V4_DISCARD"), + ([0x6b, 0xab, 0xb3, 0xa3, 0x64, 0x35, 0x8c, 0x48, 0x91, 0x17, 0xf3, 0x4e, 0x82, 0x14, 0x27, 0x63], "FWPM_LAYER_OUTBOUND_IPPACKET_V6"), + ([0xc4, 0xd7, 0x13, 0x95, 0x34, 0xa9, 0xdc, 0x49, 0x91, 0xa7, 0x6c, 0xcb, 0x80, 0xcc, 0x02, 0xe3], "FWPM_LAYER_OUTBOUND_IPPACKET_V6_DISCARD"), + ([0x24, 0xcc, 0x2a, 0xa8, 0xe1, 0x4e, 0xe1, 0x4e, 0xb4, 0x65, 0xfd, 0x1d, 0x25, 0xcb, 0x10, 0xa4], "FWPM_LAYER_IPFORWARD_V4"), + ([0x73, 0xa7, 0x9e, 0x9e, 0xae, 0x2f, 0x10, 0x42, 0x8f, 0x17, 0x34, 0x12, 0x9e, 0xf3, 0x69, 0xeb], "FWPM_LAYER_IPFORWARD_V4_DISCARD"), + ([0x18, 0x48, 0x96, 0x7b, 0xc7, 0x19, 0x3a, 0x49, 0xb7, 0x1f, 0x83, 0x2c, 0x36, 0x84, 0xd2, 0x8c], "FWPM_LAYER_IPFORWARD_V6"), + ([0x5d, 0x4a, 0x52, 0x31, 0xfe, 0x1d, 0x2f, 0x47, 0xbb, 0x93, 0x51, 0x8e, 0xe9, 0x45, 0xd8, 0xa2], "FWPM_LAYER_IPFORWARD_V6_DISCARD"), + ([0xc8, 0xdf, 0x26, 0x59, 0xcf, 0xe3, 0x26, 0x44, 0xa2, 0x83, 0xdc, 0x39, 0x3f, 0x5d, 0x0f, 0x9d], "FWPM_LAYER_INBOUND_TRANSPORT_V4"), + ([0x33, 0x98, 0x4a, 0xac, 0x9d, 0xf6, 0x48, 0x46, 0xb2, 0x61, 0x6d, 0xc8, 0x48, 0x35, 0xef, 0x39], "FWPM_LAYER_INBOUND_TRANSPORT_V4_DISCARD"), + ([0x9f, 0x86, 0x4a, 0x63, 0x23, 0xfc, 0x90, 0x4b, 0xb0, 0xc1, 0xbf, 0x62, 0x0a, 0x36, 0xae, 0x6f], "FWPM_LAYER_INBOUND_TRANSPORT_V6"), + ([0x55, 0xf9, 0x6f, 0x2a, 0x2b, 0x3b, 0xd2, 0x49, 0x98, 0x48, 0xad, 0x9d, 0x72, 0xdc, 0xaa, 0xb7], "FWPM_LAYER_INBOUND_TRANSPORT_V6_DISCARD"), + ([0xea, 0x1a, 0xe6, 0x09, 0x14, 0xd2, 0xe2, 0x46, 0x9b, 0x21, 0xb2, 0x6b, 0x0b, 0x2f, 0x28, 0xc8], "FWPM_LAYER_OUTBOUND_TRANSPORT_V4"), + ([0x51, 0x05, 0xf1, 0xc5, 0xb0, 0xbd, 0xd7, 0x43, 0xa3, 0x13, 0x50, 0xe2, 0x11, 0xf4, 0xd6, 0x8a], "FWPM_LAYER_OUTBOUND_TRANSPORT_V4_DISCARD"), + ([0xde, 0x5b, 0x73, 0xe1, 0x3f, 0x01, 0x55, 0x46, 0xb3, 0x51, 0xa4, 0x9e, 0x15, 0x76, 0x2d, 0xf0], "FWPM_LAYER_OUTBOUND_TRANSPORT_V6"), + ([0x69, 0xdf, 0x33, 0xf4, 0xbd, 0xcc, 0x2e, 0x48, 0xb9, 0xb2, 0x57, 0x16, 0x56, 0x58, 0xc3, 0xb3], "FWPM_LAYER_OUTBOUND_TRANSPORT_V6_DISCARD"), + ([0x3c, 0x65, 0x89, 0x3b, 0x70, 0xc1, 0xe4, 0x49, 0xb1, 0xcd, 0xe0, 0xee, 0xee, 0xe1, 0x9a, 0x3e], "FWPM_LAYER_STREAM_V4"), + ([0xc2, 0xc2, 0xc4, 0x25, 0xff, 0x25, 0x52, 0x43, 0x82, 0xf9, 0xc5, 0x4a, 0x4a, 0x47, 0x26, 0xdc], "FWPM_LAYER_STREAM_V4_DISCARD"), + ([0x7a, 0x13, 0xc9, 0x47, 0xc4, 0x7e, 0xb3, 0x46, 0xb6, 0xe4, 0x48, 0xe9, 0x26, 0xb1, 0xed, 0xa4], "FWPM_LAYER_STREAM_V6"), + ([0xc7, 0x9f, 0xa5, 0x10, 0x28, 0xb6, 0x41, 0x4c, 0x9e, 0xb8, 0xcf, 0x37, 0xd5, 0x51, 0x03, 0xcf], "FWPM_LAYER_STREAM_V6_DISCARD"), + ([0x4e, 0xbf, 0x08, 0x3d, 0xf6, 0x45, 0x30, 0x49, 0xa9, 0x22, 0x41, 0x70, 0x98, 0xe2, 0x00, 0x27], "FWPM_LAYER_DATAGRAM_DATA_V4"), + ([0xc6, 0x30, 0xe3, 0x18, 0x48, 0x72, 0x52, 0x4e, 0xaa, 0xab, 0x47, 0x2e, 0xd6, 0x77, 0x04, 0xfd], "FWPM_LAYER_DATAGRAM_DATA_V4_DISCARD"), + ([0x2f, 0xfe, 0x45, 0xfa, 0xba, 0x3c, 0x27, 0x44, 0x87, 0xfc, 0x57, 0xb9, 0xa4, 0xb1, 0x0d, 0x00], "FWPM_LAYER_DATAGRAM_DATA_V6"), + ([0xe1, 0xdf, 0xd1, 0x09, 0x86, 0x9b, 0x42, 0x4a, 0xbe, 0x9d, 0x8c, 0x31, 0x5b, 0x92, 0xa5, 0xd0], "FWPM_LAYER_DATAGRAM_DATA_V6_DISCARD"), + ([0x90, 0x99, 0x49, 0x61, 0xb6, 0x3c, 0x84, 0x4e, 0xb9, 0x50, 0x53, 0xb9, 0x4b, 0x69, 0x64, 0xf3], "FWPM_LAYER_INBOUND_ICMP_ERROR_V4"), + ([0x75, 0x70, 0xb1, 0xa6, 0xaf, 0xeb, 0x53, 0x40, 0xa4, 0xe7, 0x21, 0x3c, 0x81, 0x21, 0xed, 0xe5], "FWPM_LAYER_INBOUND_ICMP_ERROR_V4_DISCARD"), + ([0xff, 0xbd, 0xf9, 0x65, 0x2d, 0x3b, 0x5d, 0x4e, 0xb8, 0xc6, 0xc7, 0x20, 0x65, 0x1f, 0xe8, 0x98], "FWPM_LAYER_INBOUND_ICMP_ERROR_V6"), + ([0xc0, 0xcc, 0xe7, 0xa6, 0xfb, 0x08, 0x8d, 0x46, 0xa4, 0x72, 0x97, 0x71, 0xd5, 0x59, 0x5e, 0x09], "FWPM_LAYER_INBOUND_ICMP_ERROR_V6_DISCARD"), + ([0x00, 0x01, 0x39, 0x41, 0x4c, 0x56, 0x32, 0x4b, 0xbc, 0x1d, 0x71, 0x80, 0x48, 0x35, 0x4d, 0x7c], "FWPM_LAYER_OUTBOUND_ICMP_ERROR_V4"), + ([0x36, 0x8d, 0x59, 0xb3, 0x61, 0x05, 0x88, 0x45, 0xa6, 0xbf, 0xe9, 0x55, 0xe3, 0xf6, 0x26, 0x4b], "FWPM_LAYER_OUTBOUND_ICMP_ERROR_V4_DISCARD"), + ([0x60, 0x3b, 0xb0, 0x7f, 0x8d, 0x7b, 0xfa, 0x4d, 0xba, 0xdd, 0x98, 0x01, 0x76, 0xfc, 0x4e, 0x12], "FWPM_LAYER_OUTBOUND_ICMP_ERROR_V6"), + ([0x47, 0xe6, 0xf2, 0x65, 0x0c, 0x8d, 0x47, 0x4f, 0xb1, 0x9b, 0x33, 0xa4, 0xd3, 0xf1, 0x35, 0x7c], "FWPM_LAYER_OUTBOUND_ICMP_ERROR_V6_DISCARD"), + ([0x6d, 0xd6, 0x47, 0x12, 0x60, 0x0b, 0x15, 0x4a, 0x8d, 0x44, 0x71, 0x55, 0xd0, 0xf5, 0x3a, 0x0c], "FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4"), + ([0xa2, 0x12, 0x58, 0x0b, 0xff, 0xc3, 0xca, 0x4e, 0xb8, 0x8d, 0xc7, 0x9e, 0x20, 0xac, 0x63, 0x22], "FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4_DISCARD"), + ([0xe1, 0x50, 0xa6, 0x55, 0x0a, 0x5f, 0xca, 0x4e, 0xa6, 0x53, 0x88, 0xf5, 0x3b, 0x26, 0xaa, 0x8c], "FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V6"), + ([0xbb, 0x98, 0xc9, 0xcb, 0x1f, 0xc5, 0x1a, 0x4c, 0xbb, 0x4f, 0x97, 0x75, 0xfc, 0xac, 0xab, 0x2f], "FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V6_DISCARD"), + ([0xad, 0x5d, 0xbb, 0x88, 0xd7, 0x76, 0x27, 0x42, 0x9c, 0x71, 0xdf, 0x0a, 0x3e, 0xd7, 0xbe, 0x7e], "FWPM_LAYER_ALE_AUTH_LISTEN_V4"), + ([0xda, 0xfa, 0x1d, 0x37, 0x26, 0x9f, 0xfd, 0x45, 0xb4, 0xeb, 0xc2, 0x9e, 0xb2, 0x12, 0x89, 0x3f], "FWPM_LAYER_ALE_AUTH_LISTEN_V4_DISCARD"), + ([0x24, 0xde, 0xc9, 0x7a, 0xdd, 0x17, 0x14, 0x48, 0xb4, 0xbd, 0xa9, 0xfb, 0xc9, 0x5a, 0x32, 0x1b], "FWPM_LAYER_ALE_AUTH_LISTEN_V6"), + ([0x07, 0x3b, 0x70, 0x60, 0xc8, 0x63, 0xe9, 0x48, 0xad, 0xa3, 0x12, 0xb1, 0xaf, 0x40, 0xa6, 0x17], "FWPM_LAYER_ALE_AUTH_LISTEN_V6_DISCARD"), + ([0xe7, 0x9f, 0xcd, 0xe1, 0xb5, 0xf4, 0x73, 0x42, 0x96, 0xc0, 0x59, 0x2e, 0x48, 0x7b, 0x86, 0x50], "FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4"), + ([0x9b, 0xa9, 0xea, 0x9e, 0x22, 0xbd, 0x27, 0x42, 0x91, 0x9f, 0x00, 0x73, 0xc6, 0x33, 0x57, 0xb1], "FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4_DISCARD"), + ([0x97, 0x2c, 0xb4, 0xa3, 0x04, 0x9f, 0x72, 0x46, 0xb8, 0x7e, 0xce, 0xe9, 0xc4, 0x83, 0x25, 0x7f], "FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6"), + ([0x97, 0x5b, 0x45, 0x89, 0xe1, 0xdb, 0x3f, 0x45, 0xa2, 0x24, 0x13, 0xda, 0x89, 0x5a, 0xf3, 0x96], "FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6_DISCARD"), + ([0xd1, 0x57, 0x8d, 0xc3, 0xa7, 0x05, 0x33, 0x4c, 0x90, 0x4f, 0x7f, 0xbc, 0xee, 0xe6, 0x0e, 0x82], "FWPM_LAYER_ALE_AUTH_CONNECT_V4"), + ([0x01, 0xa8, 0x32, 0xd6, 0xba, 0xf5, 0xd6, 0x4a, 0x96, 0xe3, 0x60, 0x70, 0x17, 0xd9, 0x83, 0x6a], "FWPM_LAYER_ALE_AUTH_CONNECT_V4_DISCARD"), + ([0x3b, 0x39, 0x72, 0x4a, 0x9f, 0x31, 0xbc, 0x44, 0x84, 0xc3, 0xba, 0x54, 0xdc, 0xb3, 0xb6, 0xb4], "FWPM_LAYER_ALE_AUTH_CONNECT_V6"), + ([0xb8, 0xc3, 0x7b, 0xc9, 0xa3, 0xc9, 0x33, 0x4e, 0x86, 0x95, 0x8e, 0x17, 0xaa, 0xd4, 0xde, 0x09], "FWPM_LAYER_ALE_AUTH_CONNECT_V6_DISCARD"), + ([0x0a, 0x47, 0x80, 0xaf, 0x96, 0x55, 0x13, 0x4c, 0x99, 0x92, 0x53, 0x9e, 0x6f, 0xe5, 0x79, 0x67], "FWPM_LAYER_ALE_FLOW_ESTABLISHED_V4"), + ([0xa9, 0xe4, 0x6a, 0x14, 0xd2, 0xa1, 0x43, 0x4d, 0xa3, 0x1a, 0x4c, 0x42, 0x68, 0x2b, 0x8e, 0x4f], "FWPM_LAYER_ALE_FLOW_ESTABLISHED_V4_DISCARD"), + ([0xb3, 0xd2, 0x21, 0x70, 0xa4, 0xdf, 0x6e, 0x40, 0xaf, 0xeb, 0x6a, 0xfa, 0xf7, 0xe7, 0x0e, 0xfd], "FWPM_LAYER_ALE_FLOW_ESTABLISHED_V6"), + ([0x36, 0x86, 0x92, 0x46, 0xca, 0xbb, 0x76, 0x4b, 0x94, 0x1d, 0x0f, 0xa7, 0xf5, 0xd7, 0xd3, 0x72], "FWPM_LAYER_ALE_FLOW_ESTABLISHED_V6_DISCARD"), + ([0xdb, 0x7e, 0xfb, 0xef, 0x55, 0x00, 0x9a, 0x4f, 0xa2, 0x31, 0x4f, 0xf8, 0x13, 0x1a, 0xd1, 0x91], "FWPM_LAYER_INBOUND_MAC_FRAME_ETHERNET"), + ([0xbc, 0x73, 0x46, 0x69, 0xdb, 0xd6, 0x70, 0x48, 0xad, 0xee, 0x0a, 0xcd, 0xbd, 0xb7, 0xf4, 0xb2], "FWPM_LAYER_OUTBOUND_MAC_FRAME_ETHERNET"), + ([0xd3, 0x0b, 0x22, 0xd4, 0xce, 0x62, 0x08, 0x4f, 0xae, 0x88, 0xb5, 0x6e, 0x85, 0x26, 0xdf, 0x50], "FWPM_LAYER_INBOUND_MAC_FRAME_NATIVE"), + ([0x12, 0x49, 0xc4, 0x94, 0x6f, 0x9d, 0xbf, 0x4e, 0xb9, 0x95, 0x05, 0xab, 0x8a, 0x08, 0x8d, 0x1b], "FWPM_LAYER_OUTBOUND_MAC_FRAME_NATIVE"), + ([0x7a, 0x57, 0x98, 0x7d, 0x87, 0x9a, 0xec, 0x41, 0x97, 0x18, 0x7c, 0xf5, 0x89, 0xc9, 0xf3, 0x2d], "FWPM_LAYER_INGRESS_VSWITCH_ETHERNET"), + ([0xb0, 0x72, 0xc8, 0x86, 0xfa, 0x76, 0x79, 0x4b, 0x93, 0xa4, 0x07, 0x50, 0x53, 0x0a, 0xe2, 0x92], "FWPM_LAYER_EGRESS_VSWITCH_ETHERNET"), + ([0xf6, 0x6f, 0x69, 0xb2, 0x4f, 0x77, 0x54, 0x45, 0x9f, 0x7d, 0x3d, 0xa3, 0x94, 0x5f, 0x8e, 0x85], "FWPM_LAYER_INGRESS_VSWITCH_TRANSPORT_V4"), + ([0xfc, 0x14, 0xe3, 0x5e, 0x8a, 0x7d, 0xf4, 0x47, 0xb7, 0xe3, 0x29, 0x1a, 0x36, 0xda, 0x4e, 0x12], "FWPM_LAYER_INGRESS_VSWITCH_TRANSPORT_V6"), + ([0xb6, 0x50, 0x23, 0xb9, 0xf0, 0x91, 0xb6, 0x46, 0xbd, 0xc4, 0x87, 0x1d, 0xfd, 0x4a, 0x7c, 0x98], "FWPM_LAYER_EGRESS_VSWITCH_TRANSPORT_V4"), + ([0x23, 0xef, 0x2d, 0x1b, 0x81, 0x18, 0xbd, 0x40, 0x82, 0xf4, 0x42, 0x54, 0xe6, 0x31, 0x41, 0xcb], "FWPM_LAYER_EGRESS_VSWITCH_TRANSPORT_V6"), + ([0x19, 0x27, 0x1d, 0xe4, 0xc7, 0x05, 0xf0, 0x40, 0x89, 0x83, 0xea, 0x8d, 0x17, 0xbb, 0xc2, 0xf6], "FWPM_LAYER_INBOUND_TRANSPORT_FAST"), + ([0x88, 0x43, 0xed, 0x13, 0x70, 0xa0, 0x15, 0x48, 0x99, 0x35, 0x7a, 0x9b, 0xe6, 0x40, 0x8b, 0x78], "FWPM_LAYER_OUTBOUND_TRANSPORT_FAST"), + ([0x8e, 0xaa, 0x3a, 0x85, 0x78, 0x2b, 0x24, 0x4d, 0xa8, 0x04, 0x36, 0xdb, 0x08, 0xb2, 0x97, 0x11], "FWPM_LAYER_INBOUND_MAC_FRAME_NATIVE_FAST"), + ([0x46, 0xf9, 0x0d, 0x47, 0x62, 0xc9, 0x6f, 0x48, 0x94, 0x46, 0x82, 0x93, 0xcb, 0xc7, 0x5e, 0xb8], "FWPM_LAYER_OUTBOUND_MAC_FRAME_NATIVE_FAST"), + ([0x26, 0x15, 0x2b, 0xf0, 0x59, 0xa4, 0x51, 0x4a, 0xb9, 0xe3, 0x75, 0x9d, 0xe5, 0x2b, 0x9d, 0x2c], "FWPM_LAYER_IPSEC_KM_DEMUX_V4"), + ([0xf6, 0x5c, 0x75, 0x2f, 0xd4, 0x2f, 0x88, 0x4e, 0xb3, 0xe4, 0xa9, 0x1b, 0xca, 0x49, 0x52, 0x35], "FWPM_LAYER_IPSEC_KM_DEMUX_V6"), + ([0x74, 0x5c, 0xa6, 0xed, 0x0d, 0x61, 0xc5, 0x4b, 0x94, 0x8f, 0x3c, 0x4f, 0x89, 0x55, 0x68, 0x67], "FWPM_LAYER_IPSEC_V4"), + ([0x42, 0x84, 0xc4, 0x13, 0x87, 0x8d, 0x61, 0x42, 0x9a, 0x29, 0x59, 0xd2, 0xab, 0xc3, 0x48, 0xb4], "FWPM_LAYER_IPSEC_V6"), + ([0xdb, 0x7b, 0x4b, 0xb1, 0xbd, 0xdb, 0x3e, 0x47, 0xbe, 0xd4, 0x8b, 0x47, 0x08, 0xd4, 0xf2, 0x70], "FWPM_LAYER_IKEEXT_V4"), + ([0xb3, 0x86, 0x47, 0xb6, 0x87, 0xf6, 0xb9, 0x4e, 0x89, 0xd2, 0x8e, 0xf3, 0x2a, 0xcd, 0xab, 0xe2], "FWPM_LAYER_IKEEXT_V6"), + ([0xda, 0x9d, 0xa8, 0x75, 0xe4, 0x95, 0xf3, 0x40, 0xad, 0xc7, 0x76, 0x88, 0xa9, 0xc8, 0x47, 0xe1], "FWPM_LAYER_RPC_UM"), + ([0x61, 0xbc, 0x47, 0x92, 0x07, 0xeb, 0xee, 0x47, 0x87, 0x2c, 0xbf, 0xd7, 0x8b, 0xfd, 0x16, 0x16], "FWPM_LAYER_RPC_EPMAP"), + ([0xc7, 0xff, 0x8d, 0x61, 0x50, 0xc4, 0x43, 0x49, 0x95, 0xdb, 0x99, 0xb4, 0xc1, 0x6a, 0x55, 0xd4], "FWPM_LAYER_RPC_EP_ADD"), + ([0x0b, 0xb5, 0xa4, 0x94, 0x5c, 0xba, 0x27, 0x4f, 0x90, 0x7a, 0x22, 0x9f, 0xac, 0x0c, 0x2a, 0x7a], "FWPM_LAYER_RPC_PROXY_CONN"), + ([0x15, 0x86, 0xa3, 0xf8, 0x2c, 0xe1, 0xac, 0x41, 0x98, 0xdf, 0x12, 0x1a, 0xd9, 0x81, 0xaa, 0xde], "FWPM_LAYER_RPC_PROXY_IF"), + ([0xe9, 0x26, 0xa2, 0x4a, 0x20, 0x90, 0xfb, 0x45, 0x95, 0x6a, 0xc0, 0x24, 0x9d, 0x84, 0x11, 0x95], "FWPM_LAYER_KM_AUTHORIZATION"), + ([0x81, 0xa6, 0x2a, 0x0c, 0x5b, 0x90, 0xcd, 0x4c, 0xa4, 0x67, 0x4d, 0xd8, 0x11, 0xd0, 0x7b, 0x7b], "FWPM_LAYER_NAME_RESOLUTION_CACHE_V4"), + ([0xfa, 0x92, 0xd5, 0x92, 0x01, 0x6b, 0x4a, 0x43, 0x9d, 0xea, 0xd1, 0xe9, 0x6e, 0xa9, 0x7d, 0xa9], "FWPM_LAYER_NAME_RESOLUTION_CACHE_V6"), + ([0xce, 0x5c, 0x36, 0x74, 0xb0, 0xcc, 0x1a, 0x40, 0xbf, 0xc1, 0xb8, 0x99, 0x34, 0xad, 0x7e, 0x15], "FWPM_LAYER_ALE_RESOURCE_RELEASE_V4"), + ([0x80, 0xce, 0xe5, 0xf4, 0xcc, 0xed, 0x13, 0x4e, 0x8a, 0x2f, 0xb9, 0x14, 0x54, 0xbb, 0x05, 0x7b], "FWPM_LAYER_ALE_RESOURCE_RELEASE_V6"), + ([0x27, 0x64, 0x76, 0xb4, 0xa2, 0xe2, 0x7a, 0x46, 0xbd, 0x7e, 0xdb, 0xcd, 0x1b, 0xd8, 0x5a, 0x09], "FWPM_LAYER_ALE_ENDPOINT_CLOSURE_V4"), + ([0xcd, 0x6c, 0x53, 0xbb, 0x55, 0x47, 0xa9, 0x4b, 0x9f, 0xf7, 0xf9, 0xed, 0xf8, 0x69, 0x9c, 0x7b], "FWPM_LAYER_ALE_ENDPOINT_CLOSURE_V6"), + ([0x8c, 0x3c, 0xe6, 0xc6, 0x84, 0xb7, 0x62, 0x45, 0xaa, 0x7d, 0x0a, 0x67, 0xcf, 0xca, 0xf9, 0xa3], "FWPM_LAYER_ALE_CONNECT_REDIRECT_V4"), + ([0xa7, 0x54, 0x7e, 0x58, 0x46, 0x80, 0xba, 0x42, 0xa0, 0xaa, 0xb7, 0x16, 0x25, 0x0f, 0xc7, 0xfd], "FWPM_LAYER_ALE_CONNECT_REDIRECT_V6"), + ([0xad, 0x8c, 0x97, 0x66, 0x04, 0xc7, 0xac, 0x42, 0x86, 0xac, 0x7c, 0x1a, 0x23, 0x1b, 0xd2, 0x53], "FWPM_LAYER_ALE_BIND_REDIRECT_V4"), + ([0x9c, 0x2c, 0xf0, 0xbe, 0x6b, 0x60, 0x36, 0x45, 0x8c, 0x26, 0x1c, 0x2f, 0xc7, 0xb6, 0x31, 0xd4], "FWPM_LAYER_ALE_BIND_REDIRECT_V6"), + ([0xec, 0xd8, 0x52, 0xaf, 0x2d, 0xcb, 0xe5, 0x44, 0xad, 0x92, 0xf8, 0xdc, 0x38, 0xd2, 0xeb, 0x29], "FWPM_LAYER_STREAM_PACKET_V4"), + ([0xa3, 0x8c, 0x9a, 0x77, 0x99, 0xf0, 0x8f, 0x46, 0xb5, 0xd4, 0x83, 0x53, 0x5c, 0x46, 0x1c, 0x02], "FWPM_LAYER_STREAM_PACKET_V6"), + ([0x55, 0x8d, 0xfb, 0xf4, 0x76, 0xc0, 0xd8, 0x46, 0xa2, 0xc7, 0x6a, 0x4c, 0x72, 0x2c, 0xa4, 0xed], "FWPM_LAYER_INBOUND_RESERVED2"), + ([0xf4, 0x84, 0x8c, 0x75, 0x48, 0xfb, 0xe9, 0x4d, 0x9a, 0xeb, 0x3e, 0xd9, 0x55, 0x1a, 0xb1, 0xfd], "FWPM_SUBLAYER_RPC_AUDIT"), + ([0xed, 0x99, 0xf2, 0x83, 0xf4, 0x9f, 0x67, 0x49, 0xaf, 0xf4, 0xc3, 0x09, 0xf4, 0xda, 0xb8, 0x27], "FWPM_SUBLAYER_IPSEC_TUNNEL"), + ([0x03, 0xcc, 0xbe, 0xee, 0xd4, 0xce, 0x80, 0x43, 0x81, 0x9a, 0x27, 0x34, 0x39, 0x7b, 0x2b, 0x74], "FWPM_SUBLAYER_UNIVERSAL"), + ([0xce, 0xc0, 0x75, 0x1b, 0x60, 0xff, 0x11, 0x47, 0xa7, 0x0f, 0xb4, 0x95, 0x8c, 0xc3, 0xb2, 0xd0], "FWPM_SUBLAYER_LIPS"), + ([0x17, 0x6e, 0xa6, 0x15, 0x3c, 0x3f, 0x7b, 0x4f, 0xaa, 0x6c, 0x81, 0x2a, 0xa6, 0x13, 0xdd, 0x82], "FWPM_SUBLAYER_SECURE_SOCKET"), + ([0xb9, 0x08, 0x76, 0x33, 0xd5, 0xb7, 0x5f, 0x4d, 0x82, 0xf9, 0x36, 0x18, 0x61, 0x8b, 0xc0, 0x58], "FWPM_SUBLAYER_TCP_CHIMNEY_OFFLOAD"), + ([0xe1, 0x19, 0x75, 0x87, 0xa9, 0xe6, 0xa5, 0x41, 0x81, 0xb4, 0x8c, 0x4f, 0x11, 0x8e, 0x4a, 0x60], "FWPM_SUBLAYER_INSPECTION"), + ([0x66, 0xdc, 0x69, 0xba, 0x76, 0x51, 0x79, 0x49, 0x9c, 0x89, 0x26, 0xa7, 0xb4, 0x6a, 0x83, 0x27], "FWPM_SUBLAYER_TEREDO"), + ([0x73, 0x2e, 0x08, 0xa5, 0x71, 0x8f, 0x59, 0x45, 0x8a, 0x9a, 0x10, 0x1c, 0xea, 0x04, 0xef, 0x87], "FWPM_SUBLAYER_IPSEC_FORWARD_OUTBOUND_TUNNEL"), + ([0x72, 0xd5, 0x76, 0xe0, 0x3d, 0x5d, 0xef, 0x48, 0x80, 0x2b, 0x90, 0x9e, 0xdd, 0xb0, 0x98, 0xbd], "FWPM_SUBLAYER_IPSEC_DOSP"), + ([0xcf, 0x1d, 0x42, 0x24, 0xc5, 0x0a, 0xaa, 0x4c, 0x9e, 0x14, 0x50, 0xf6, 0xe3, 0x63, 0x6a, 0xf0], "FWPM_SUBLAYER_TCP_TEMPLATES"), + ([0x01, 0x77, 0xa5, 0x37, 0x84, 0x58, 0x64, 0x49, 0x92, 0xb8, 0x3e, 0x70, 0x46, 0x88, 0xb0, 0xad], "FWPM_SUBLAYER_IPSEC_SECURITY_REALM"), + ([0x41, 0xd4, 0xcd, 0xb3, 0x90, 0xaf, 0xba, 0x41, 0xa7, 0x45, 0x7c, 0x60, 0x08, 0xff, 0x23, 0x00], "FWPM_SUBLAYER_MPSSVC_WSH"), + ([0x41, 0xd4, 0xcd, 0xb3, 0x90, 0xaf, 0xba, 0x41, 0xa7, 0x45, 0x7c, 0x60, 0x08, 0xff, 0x23, 0x01], "FWPM_SUBLAYER_MPSSVC_WF"), + ([0x41, 0xd4, 0xcd, 0xb3, 0x90, 0xaf, 0xba, 0x41, 0xa7, 0x45, 0x7c, 0x60, 0x08, 0xff, 0x23, 0x02], "FWPM_SUBLAYER_MPSSVC_QUARANTINE"), + ([0x38, 0x7e, 0xa4, 0x09, 0x97, 0xfa, 0x1b, 0x47, 0xb1, 0x23, 0x18, 0xbc, 0xd7, 0xe6, 0x50, 0x71], "FWPM_SUBLAYER_MPSSVC_EDP"), + ([0xe1, 0xc7, 0xc6, 0x1e, 0xd9, 0xfd, 0x8a, 0x47, 0xb5, 0x5f, 0xff, 0x8b, 0xa1, 0xd2, 0xc1, 0x7d], "FWPM_SUBLAYER_MPSSVC_TENANT_RESTRICTIONS"), + ([0xc3, 0x21, 0xe2, 0xff, 0xa8, 0x92, 0x64, 0x45, 0xa5, 0x9f, 0xda, 0xfb, 0x70, 0x75, 0x60, 0x20], "FWPM_SUBLAYER_MPSSVC_APP_ISOLATION"), + ([0xce, 0x3d, 0xe6, 0xf6, 0x4b, 0x1f, 0x6b, 0x4c, 0xb6, 0xef, 0x11, 0x65, 0xe7, 0x1f, 0x8e, 0xe7], "FWPM_CONDITION_INTERFACE_MAC_ADDRESS"), + ([0x81, 0xe9, 0x99, 0xd9, 0x48, 0x79, 0x83, 0x4c, 0xb7, 0x42, 0xc8, 0x4e, 0x3b, 0x67, 0x8f, 0x8f], "FWPM_CONDITION_MAC_LOCAL_ADDRESS"), + ([0xd4, 0x2e, 0x8f, 0x40, 0x70, 0x3a, 0x4d, 0x4b, 0x92, 0xa6, 0x41, 0x5a, 0xc2, 0x0e, 0x2f, 0x12], "FWPM_CONDITION_MAC_REMOTE_ADDRESS"), + ([0x8d, 0x94, 0x08, 0xfd, 0x19, 0xa2, 0x52, 0x4d, 0xbb, 0x98, 0x1a, 0x55, 0x40, 0xee, 0x7b, 0x4e], "FWPM_CONDITION_ETHER_TYPE"), + ([0x21, 0xab, 0x8e, 0x93, 0x18, 0x36, 0x64, 0x4e, 0x9c, 0xa5, 0x21, 0x41, 0xeb, 0xda, 0x1c, 0xa2], "FWPM_CONDITION_VLAN_ID"), + ([0x3c, 0x84, 0x04, 0xdc, 0xe6, 0x79, 0x44, 0x4e, 0xa0, 0x25, 0x65, 0xb9, 0xbb, 0x0f, 0x9f, 0x94], "FWPM_CONDITION_VSWITCH_TENANT_NETWORK_ID"), + ([0x2b, 0xb4, 0x7b, 0xdb, 0xac, 0x2d, 0xd4, 0x4c, 0xa5, 0x9a, 0xe0, 0xbd, 0xce, 0x1e, 0x68, 0x34], "FWPM_CONDITION_NDIS_PORT"), + ([0xf1, 0xce, 0x31, 0xcb, 0x1d, 0x79, 0x3b, 0x47, 0x89, 0xd1, 0x61, 0xc5, 0x98, 0x43, 0x04, 0xa0], "FWPM_CONDITION_NDIS_MEDIA_TYPE"), + ([0x23, 0x98, 0xc7, 0x34, 0x29, 0xc2, 0xf2, 0x44, 0xb8, 0x3c, 0x74, 0x02, 0x08, 0x82, 0xae, 0x77], "FWPM_CONDITION_NDIS_PHYSICAL_MEDIA_TYPE"), + ([0xbf, 0x3c, 0xc4, 0x7b, 0xba, 0x37, 0xf1, 0x45, 0xb7, 0x4a, 0x82, 0xff, 0x51, 0x8e, 0xeb, 0x10], "FWPM_CONDITION_L2_FLAGS"), + ([0x5c, 0x35, 0x31, 0xcc, 0x73, 0x30, 0xfb, 0x4f, 0xa1, 0x4f, 0x79, 0x41, 0x5c, 0xb1, 0xea, 0xd1], "FWPM_CONDITION_MAC_LOCAL_ADDRESS_TYPE"), + ([0xb4, 0xed, 0x7f, 0x02, 0xc1, 0xf1, 0x30, 0x40, 0xb5, 0x64, 0xee, 0x77, 0x7f, 0xd8, 0x67, 0xea], "FWPM_CONDITION_MAC_REMOTE_ADDRESS_TYPE"), + ([0xfa, 0x78, 0xbc, 0x71, 0x7c, 0xf1, 0x97, 0x49, 0xa6, 0x02, 0x6a, 0xbb, 0x26, 0x1f, 0x35, 0x1c], "FWPM_CONDITION_ALE_PACKAGE_ID"), + ([0x51, 0x54, 0x79, 0x7b, 0xf6, 0xf1, 0x05, 0x4d, 0xb7, 0xcb, 0x21, 0x77, 0x9d, 0x80, 0x23, 0x36], "FWPM_CONDITION_MAC_SOURCE_ADDRESS"), + ([0x93, 0x2a, 0xea, 0x04, 0x8c, 0x85, 0x27, 0x40, 0xb6, 0x13, 0xb4, 0x31, 0x80, 0xc7, 0x85, 0x9e], "FWPM_CONDITION_MAC_DESTINATION_ADDRESS"), + ([0xe4, 0x72, 0x1b, 0x5c, 0x9e, 0x29, 0x37, 0x44, 0xa2, 0x98, 0xbc, 0x3f, 0x01, 0x4b, 0x3d, 0xc2], "FWPM_CONDITION_MAC_SOURCE_ADDRESS_TYPE"), + ([0x32, 0x29, 0x05, 0xae, 0x42, 0xef, 0x99, 0x4e, 0xb1, 0x29, 0xf3, 0xb3, 0x13, 0x9e, 0x34, 0xf7], "FWPM_CONDITION_MAC_DESTINATION_ADDRESS_TYPE"), + ([0x91, 0xef, 0xaf, 0xa6, 0xf4, 0x3d, 0x30, 0x47, 0xa2, 0x14, 0xf5, 0x42, 0x6a, 0xeb, 0xf8, 0x21], "FWPM_CONDITION_IP_SOURCE_PORT"), + ([0x45, 0xef, 0x6d, 0xce, 0xfb, 0x60, 0x7b, 0x4a, 0xa3, 0x04, 0xaf, 0x30, 0xa1, 0x17, 0x00, 0x0e], "FWPM_CONDITION_IP_DESTINATION_PORT"), + ([0xba, 0x14, 0xa4, 0xc4, 0x7b, 0x43, 0xe6, 0x4d, 0x99, 0x46, 0xd9, 0x9c, 0x1b, 0x95, 0xb3, 0x12], "FWPM_CONDITION_VSWITCH_ID"), + ([0x4b, 0x8b, 0xd4, 0x11, 0x7a, 0xe7, 0xb4, 0x40, 0x91, 0x55, 0x39, 0x2c, 0x90, 0x6c, 0x26, 0x08], "FWPM_CONDITION_VSWITCH_NETWORK_TYPE"), + ([0x4b, 0xf2, 0x4e, 0x7f, 0xc1, 0xb2, 0x38, 0x49, 0xba, 0x33, 0xa1, 0xec, 0xbe, 0xd5, 0x12, 0xba], "FWPM_CONDITION_VSWITCH_SOURCE_INTERFACE_ID"), + ([0xe4, 0x8b, 0xd4, 0x8e, 0x26, 0xc9, 0xf6, 0x49, 0xa4, 0xf6, 0xef, 0x30, 0x30, 0xe3, 0xfc, 0x16], "FWPM_CONDITION_VSWITCH_DESTINATION_INTERFACE_ID"), + ([0xc2, 0x9e, 0x2a, 0x9c, 0xc6, 0x9f, 0xbc, 0x42, 0xbd, 0xd8, 0x40, 0x6d, 0x4d, 0xa0, 0xbe, 0x64], "FWPM_CONDITION_VSWITCH_SOURCE_VM_ID"), + ([0xce, 0xaa, 0x06, 0x61, 0xe1, 0x4d, 0x84, 0x4c, 0x96, 0x71, 0x36, 0x37, 0xf8, 0xbc, 0xf7, 0x31], "FWPM_CONDITION_VSWITCH_DESTINATION_VM_ID"), + ([0xa2, 0x40, 0xb0, 0xe6, 0xaf, 0xed, 0x36, 0x4c, 0x90, 0x8b, 0xf2, 0xf5, 0x8a, 0xe4, 0x38, 0x07], "FWPM_CONDITION_VSWITCH_SOURCE_INTERFACE_TYPE"), + ([0x06, 0x3f, 0x9b, 0xfa, 0x1a, 0x2f, 0x57, 0x4c, 0x9e, 0x68, 0xa7, 0x09, 0x8b, 0x28, 0xdb, 0xfe], "FWPM_CONDITION_VSWITCH_DESTINATION_INTERFACE_TYPE"), + ([0x99, 0x76, 0xa5, 0x37, 0x83, 0x58, 0x63, 0x49, 0x92, 0xb8, 0x3e, 0x70, 0x46, 0x88, 0xb0, 0xad], "FWPM_CONDITION_ALE_SECURITY_ATTRIBUTE_FQBN_VALUE"), + ([0x00, 0x77, 0xa5, 0x37, 0x84, 0x58, 0x64, 0x49, 0x92, 0xb8, 0x3e, 0x70, 0x46, 0x88, 0xb0, 0xad], "FWPM_CONDITION_IPSEC_SECURITY_REALM_ID"), + ([0x9a, 0x7b, 0x27, 0xb1, 0x81, 0xb7, 0xfc, 0x40, 0x96, 0x71, 0xe5, 0xf1, 0xb9, 0x89, 0xf3, 0x4e], "FWPM_CONDITION_ALE_EFFECTIVE_NAME"), + ([0xde, 0x00, 0xee, 0xd9, 0xef, 0xc1, 0x17, 0x46, 0xbf, 0xe3, 0xff, 0xd8, 0xf5, 0xa0, 0x89, 0x57], "FWPM_CONDITION_IP_LOCAL_ADDRESS"), + ([0x9a, 0xae, 0x35, 0xb2, 0x64, 0x1d, 0xb8, 0x49, 0xa4, 0x4c, 0x5f, 0xf3, 0xd9, 0x09, 0x50, 0x45], "FWPM_CONDITION_IP_REMOTE_ADDRESS"), + ([0x7e, 0x89, 0x96, 0xae, 0x94, 0x2e, 0xc9, 0x4b, 0xb3, 0x13, 0xb2, 0x7e, 0xe8, 0x0e, 0x57, 0x4d], "FWPM_CONDITION_IP_SOURCE_ADDRESS"), + ([0x3b, 0x13, 0x79, 0x2d, 0x90, 0xb3, 0xc6, 0x45, 0x86, 0x99, 0xac, 0xac, 0xea, 0xaf, 0xed, 0x33], "FWPM_CONDITION_IP_DESTINATION_ADDRESS"), + ([0xc4, 0xf6, 0xc7, 0x6e, 0x6b, 0x37, 0xd7, 0x45, 0x9e, 0x9c, 0xd3, 0x37, 0xce, 0xdc, 0xd2, 0x37], "FWPM_CONDITION_IP_LOCAL_ADDRESS_TYPE"), + ([0xc9, 0xb7, 0xc1, 0x1e, 0xea, 0x4e, 0x5e, 0x4f, 0xb9, 0xef, 0x76, 0xbe, 0xaa, 0xaf, 0x17, 0xee], "FWPM_CONDITION_IP_DESTINATION_ADDRESS_TYPE"), + ([0x8a, 0x44, 0xbe, 0xea, 0x11, 0xa7, 0x64, 0x4d, 0x85, 0xb7, 0x3f, 0x76, 0xb6, 0x52, 0x99, 0xc7], "FWPM_CONDITION_IP_NEXTHOP_ADDRESS"), + ([0x49, 0x2a, 0xd6, 0x4c, 0xc3, 0x59, 0x69, 0x49, 0xb7, 0xf3, 0xbd, 0xa5, 0xd3, 0x28, 0x90, 0xa4], "FWPM_CONDITION_IP_LOCAL_INTERFACE"), + ([0x6d, 0x9b, 0x8a, 0x61, 0x6b, 0x38, 0x36, 0x41, 0xad, 0x6e, 0xb5, 0x15, 0x87, 0xcf, 0xb1, 0xcd], "FWPM_CONDITION_IP_ARRIVAL_INTERFACE"), + ([0xde, 0x90, 0xf9, 0x89, 0x98, 0xe7, 0x6d, 0x4e, 0xab, 0x76, 0x7c, 0x95, 0x58, 0x29, 0x2e, 0x6f], "FWPM_CONDITION_ARRIVAL_INTERFACE_TYPE"), + ([0xdc, 0x66, 0x11, 0x51, 0x8c, 0x7a, 0xa7, 0x4a, 0xb5, 0x33, 0x95, 0xab, 0x59, 0xfb, 0x03, 0x40], "FWPM_CONDITION_ARRIVAL_TUNNEL_TYPE"), + ([0xb3, 0x8d, 0x08, 0xcc, 0x92, 0x17, 0x71, 0x4a, 0xb0, 0xf9, 0x03, 0x7d, 0x21, 0xcd, 0x82, 0x8b], "FWPM_CONDITION_ARRIVAL_INTERFACE_INDEX"), + ([0x22, 0x61, 0x8a, 0xef, 0x77, 0x05, 0xa7, 0x45, 0x9a, 0xaf, 0x82, 0x5f, 0xbe, 0xb4, 0xfb, 0x95], "FWPM_CONDITION_NEXTHOP_SUB_INTERFACE_INDEX"), + ([0x5b, 0x8f, 0xae, 0x93, 0x6f, 0x7f, 0x19, 0x47, 0x98, 0xc8, 0x14, 0xe9, 0x74, 0x29, 0xef, 0x04], "FWPM_CONDITION_IP_NEXTHOP_INTERFACE"), + ([0x6c, 0x7c, 0x53, 0x97, 0xa3, 0xd9, 0x67, 0x47, 0xa3, 0x81, 0xe9, 0x42, 0x67, 0x5c, 0xd9, 0x20], "FWPM_CONDITION_NEXTHOP_INTERFACE_TYPE"), + ([0x11, 0xa1, 0xb1, 0x72, 0x7b, 0x98, 0x20, 0x47, 0x99, 0xdd, 0xc7, 0xc5, 0x76, 0xfa, 0x2d, 0x4c], "FWPM_CONDITION_NEXTHOP_TUNNEL_TYPE"), + ([0x88, 0x68, 0x8e, 0x13, 0xb8, 0x7a, 0x65, 0x4d, 0x9e, 0xe8, 0x05, 0x91, 0xbc, 0xf6, 0xa4, 0x94], "FWPM_CONDITION_NEXTHOP_INTERFACE_INDEX"), + ([0x51, 0x15, 0xea, 0x46, 0x55, 0x22, 0x2b, 0x49, 0x80, 0x19, 0xaa, 0xbe, 0xee, 0x34, 0x9f, 0x40], "FWPM_CONDITION_ORIGINAL_PROFILE_ID"), + ([0xc9, 0x33, 0x30, 0xab, 0xe3, 0xc0, 0x59, 0x47, 0x93, 0x7d, 0x57, 0x58, 0xc6, 0x5d, 0x4a, 0xe3], "FWPM_CONDITION_CURRENT_PROFILE_ID"), + ([0x62, 0x75, 0xbf, 0x4e, 0x18, 0x9f, 0x06, 0x4d, 0x99, 0x41, 0xa7, 0xa6, 0x25, 0x74, 0x4d, 0x71], "FWPM_CONDITION_LOCAL_INTERFACE_PROFILE_ID"), + ([0xab, 0x6a, 0xfe, 0xcd, 0x83, 0xc0, 0x42, 0x41, 0x86, 0x79, 0xc0, 0x8f, 0x95, 0x32, 0x9c, 0x61], "FWPM_CONDITION_ARRIVAL_INTERFACE_PROFILE_ID"), + ([0x56, 0x9a, 0xff, 0xd7, 0xaa, 0xcd, 0x2b, 0x47, 0x84, 0xdb, 0xd2, 0x39, 0x63, 0xc1, 0xd1, 0xbf], "FWPM_CONDITION_NEXTHOP_INTERFACE_PROFILE_ID"), + ([0x8c, 0x5e, 0x20, 0x11, 0xae, 0x11, 0x7a, 0x45, 0x8a, 0x44, 0x47, 0x70, 0x26, 0xdd, 0x76, 0x4a], "FWPM_CONDITION_REAUTHORIZE_REASON"), + ([0xbe, 0xfd, 0x6d, 0x07, 0x6c, 0xc5, 0x72, 0x4f, 0xae, 0x8a, 0x2c, 0xfe, 0x7e, 0x5c, 0x82, 0x86], "FWPM_CONDITION_ORIGINAL_ICMP_TYPE"), + ([0xc8, 0xd5, 0x50, 0xda, 0x0d, 0xfa, 0x89, 0x4c, 0xb0, 0x32, 0x6e, 0x62, 0x13, 0x6d, 0x1e, 0x96], "FWPM_CONDITION_IP_PHYSICAL_ARRIVAL_INTERFACE"), + ([0xce, 0xd5, 0x9b, 0xf0, 0x50, 0x51, 0xbe, 0x48, 0xb0, 0x98, 0xc2, 0x51, 0x52, 0xfb, 0x1f, 0x92], "FWPM_CONDITION_IP_PHYSICAL_NEXTHOP_INTERFACE"), + ([0x5e, 0x8d, 0xe6, 0xcc, 0x3b, 0x05, 0xa8, 0x43, 0x9a, 0x6f, 0x33, 0x38, 0x4c, 0x28, 0xe4, 0xf6], "FWPM_CONDITION_INTERFACE_QUARANTINE_EPOCH"), + ([0x14, 0xcd, 0xf8, 0xda, 0x9e, 0xe0, 0x93, 0x4c, 0xa5, 0xae, 0xc5, 0xc1, 0x3b, 0x73, 0xff, 0xca], "FWPM_CONDITION_INTERFACE_TYPE"), + ([0x37, 0x04, 0xa4, 0x77, 0x79, 0x87, 0x68, 0x48, 0xa2, 0x61, 0xf5, 0xa9, 0x02, 0xf1, 0xc0, 0xcd], "FWPM_CONDITION_TUNNEL_TYPE"), + ([0xa5, 0xb8, 0x76, 0x10, 0x23, 0x63, 0x5e, 0x4c, 0x98, 0x10, 0xe8, 0xd3, 0xfc, 0x9e, 0x61, 0x36], "FWPM_CONDITION_IP_FORWARD_INTERFACE"), + ([0x2b, 0xef, 0x71, 0x39, 0x3e, 0x62, 0x9a, 0x4f, 0x8c, 0xb1, 0x6e, 0x79, 0xb8, 0x06, 0xb9, 0xa7], "FWPM_CONDITION_IP_PROTOCOL"), + ([0xaf, 0xa1, 0x1b, 0x0c, 0x65, 0x57, 0x3f, 0x45, 0xaf, 0x22, 0xa8, 0xf7, 0x91, 0xac, 0x77, 0x5b], "FWPM_CONDITION_IP_LOCAL_PORT"), + ([0x4d, 0x60, 0x5a, 0xc3, 0x2b, 0xd2, 0x1a, 0x4e, 0x91, 0xb4, 0x68, 0xf6, 0x74, 0xee, 0x67, 0x4b], "FWPM_CONDITION_IP_REMOTE_PORT"), + ([0x68, 0xa4, 0x72, 0x46, 0x0a, 0x8a, 0x02, 0x42, 0xab, 0xb4, 0x84, 0x9e, 0x92, 0xe6, 0x68, 0x09], "FWPM_CONDITION_EMBEDDED_LOCAL_ADDRESS_TYPE"), + ([0x39, 0x4b, 0xee, 0x77, 0x73, 0x32, 0x71, 0x46, 0xb6, 0x3b, 0xab, 0x6f, 0xeb, 0x66, 0xee, 0xb6], "FWPM_CONDITION_EMBEDDED_REMOTE_ADDRESS"), + ([0x07, 0x41, 0x78, 0x07, 0x9e, 0xa2, 0x7b, 0x4c, 0x9e, 0xc7, 0x29, 0xc4, 0x4a, 0xfa, 0xfd, 0xbc], "FWPM_CONDITION_EMBEDDED_PROTOCOL"), + ([0x4d, 0x39, 0xca, 0xbf, 0xdb, 0xac, 0x4e, 0x48, 0xb8, 0xe6, 0x2a, 0xff, 0x79, 0x75, 0x73, 0x45], "FWPM_CONDITION_EMBEDDED_LOCAL_PORT"), + ([0xa1, 0xd6, 0xe4, 0xca, 0x68, 0x29, 0xed, 0x40, 0xa4, 0xce, 0x54, 0x71, 0x60, 0xdd, 0xa8, 0x8d], "FWPM_CONDITION_EMBEDDED_REMOTE_PORT"), + ([0x3b, 0xe2, 0x2c, 0x63, 0x67, 0x51, 0x5c, 0x43, 0x86, 0xd7, 0xe9, 0x03, 0x68, 0x4a, 0xa8, 0x0c], "FWPM_CONDITION_FLAGS"), + ([0x46, 0xc1, 0x84, 0x87, 0x97, 0xca, 0xd6, 0x44, 0x9f, 0xd1, 0x19, 0xfb, 0x18, 0x40, 0xcb, 0xf7], "FWPM_CONDITION_DIRECTION"), + ([0x55, 0xd7, 0x7f, 0x66, 0x95, 0xd6, 0x4a, 0x43, 0x8a, 0xf5, 0xd3, 0x83, 0x5a, 0x12, 0x59, 0xbc], "FWPM_CONDITION_INTERFACE_INDEX"), + ([0x73, 0x24, 0xd4, 0x0c, 0x21, 0xd6, 0xe3, 0x4b, 0xae, 0x8c, 0x72, 0xa3, 0x48, 0xd2, 0x83, 0xe1], "FWPM_CONDITION_SUB_INTERFACE_INDEX"), + ([0x4d, 0x33, 0x11, 0x23, 0x2d, 0xc9, 0xbf, 0x45, 0x94, 0x96, 0xed, 0xf4, 0x47, 0x82, 0x0e, 0x2d], "FWPM_CONDITION_SOURCE_INTERFACE_INDEX"), + ([0x9d, 0xdd, 0x5e, 0x05, 0xd2, 0xac, 0x61, 0x43, 0x8d, 0xab, 0xf9, 0x52, 0x5d, 0x97, 0x66, 0x2f], "FWPM_CONDITION_SOURCE_SUB_INTERFACE_INDEX"), + ([0x22, 0x65, 0xcf, 0x35, 0x39, 0x41, 0xee, 0x45, 0xa0, 0xd5, 0x67, 0xb8, 0x09, 0x49, 0xd8, 0x79], "FWPM_CONDITION_DESTINATION_INTERFACE_INDEX"), + ([0x99, 0x43, 0x7d, 0x2b, 0xc7, 0xd4, 0x38, 0x47, 0xa2, 0xf5, 0xe9, 0x94, 0xb4, 0x3d, 0xa3, 0x88], "FWPM_CONDITION_DESTINATION_SUB_INTERFACE_INDEX"), + ([0x87, 0x1e, 0x8e, 0xd7, 0x44, 0x86, 0xa5, 0x4e, 0x94, 0x37, 0xd8, 0x09, 0xec, 0xef, 0xc9, 0x71], "FWPM_CONDITION_ALE_APP_ID"), + ([0x86, 0xd0, 0x6c, 0x0e, 0xfb, 0xe1, 0x12, 0x42, 0x84, 0x2f, 0x8a, 0x9f, 0x99, 0x3f, 0xb3, 0xf6], "FWPM_CONDITION_ALE_ORIGINAL_APP_ID"), + ([0x0a, 0x3a, 0x04, 0xaf, 0x4d, 0xb3, 0x86, 0x4f, 0x97, 0x9c, 0xc9, 0x03, 0x71, 0xaf, 0x6e, 0x66], "FWPM_CONDITION_ALE_USER_ID"), + ([0xb7, 0x73, 0x30, 0xf6, 0x89, 0x01, 0xb0, 0x4a, 0x95, 0xa4, 0x61, 0x23, 0xcb, 0xfa, 0xb8, 0x62], "FWPM_CONDITION_ALE_REMOTE_USER_ID"), + ([0x51, 0x7f, 0xa4, 0x1a, 0x93, 0x7f, 0x08, 0x45, 0xa2, 0x71, 0x81, 0xab, 0xb0, 0x0c, 0x9c, 0xab], "FWPM_CONDITION_ALE_REMOTE_MACHINE_ID"), + ([0x76, 0x47, 0x97, 0x1c, 0x82, 0x71, 0xe9, 0x46, 0xaf, 0xd3, 0xb0, 0x29, 0x10, 0xe3, 0x03, 0x34], "FWPM_CONDITION_ALE_PROMISCUOUS_MODE"), + ([0x88, 0xe0, 0xf4, 0xb9, 0x98, 0xcb, 0xfb, 0x4e, 0xa2, 0xc7, 0xad, 0x07, 0x33, 0x26, 0x43, 0xdb], "FWPM_CONDITION_ALE_SIO_FIREWALL_SYSTEM_PORT"), + ([0x27, 0xd2, 0x82, 0xb4, 0x79, 0x19, 0x98, 0x4a, 0x80, 0x44, 0x18, 0xbb, 0xe6, 0x23, 0x75, 0x42], "FWPM_CONDITION_ALE_REAUTH_REASON"), + ([0x9d, 0x5a, 0x27, 0x46, 0x3f, 0xc0, 0x77, 0x4d, 0xb7, 0x84, 0x1c, 0x57, 0xf4, 0xd0, 0x27, 0x53], "FWPM_CONDITION_ALE_NAP_CONTEXT"), + ([0x0e, 0xea, 0xd0, 0x35, 0xca, 0x15, 0x2b, 0x49, 0x90, 0x0e, 0x97, 0xfd, 0x46, 0x35, 0x2c, 0xce], "FWPM_CONDITION_KM_AUTH_NAP_CONTEXT"), + ([0x66, 0xee, 0xf0, 0x9b, 0xc9, 0x06, 0xb9, 0x41, 0x84, 0xda, 0x28, 0x8c, 0xb4, 0x3a, 0xf5, 0x1f], "FWPM_CONDITION_REMOTE_USER_TOKEN"), + ([0x9f, 0x7d, 0x9c, 0x7c, 0x75, 0x00, 0x35, 0x4d, 0xa0, 0xd1, 0x83, 0x11, 0xc4, 0xcf, 0x6a, 0xf1], "FWPM_CONDITION_RPC_IF_UUID"), + ([0xb7, 0xd9, 0xbf, 0xea, 0x62, 0x12, 0x2e, 0x4a, 0xad, 0xaa, 0x5f, 0x96, 0xf6, 0xfe, 0x32, 0x6d], "FWPM_CONDITION_RPC_IF_VERSION"), + ([0x32, 0x8a, 0x8a, 0x23, 0x99, 0x31, 0x7d, 0x46, 0x87, 0x1c, 0x27, 0x26, 0x21, 0xab, 0x38, 0x96], "FWPM_CONDITION_RPC_IF_FLAG"), + ([0x4d, 0x7b, 0x2e, 0xff, 0x12, 0x31, 0x70, 0x47, 0xb6, 0x36, 0x4d, 0x24, 0xae, 0x3a, 0x6a, 0xf2], "FWPM_CONDITION_DCOM_APP_ID"), + ([0x4d, 0xde, 0x24, 0xd0, 0xaa, 0xde, 0x17, 0x43, 0x9c, 0x85, 0xe4, 0x0e, 0xf6, 0xe1, 0x40, 0xc3], "FWPM_CONDITION_IMAGE_NAME"), + ([0x74, 0xbc, 0x17, 0x27, 0x35, 0x3a, 0xe7, 0x4c, 0xb7, 0xef, 0xc8, 0x38, 0xfa, 0xbd, 0xec, 0x45], "FWPM_CONDITION_RPC_PROTOCOL"), + ([0xab, 0x74, 0xba, 0xda, 0x67, 0x0d, 0xe7, 0x43, 0x98, 0x6e, 0x75, 0xb8, 0x4f, 0x82, 0xf5, 0x94], "FWPM_CONDITION_RPC_AUTH_TYPE"), + ([0xd5, 0xae, 0xa0, 0xe5, 0xac, 0x59, 0xea, 0x46, 0xbe, 0x05, 0xa5, 0xf0, 0x5e, 0xcf, 0x44, 0x6e], "FWPM_CONDITION_RPC_AUTH_LEVEL"), + ([0xf0, 0x6e, 0x30, 0x0d, 0x74, 0xe9, 0x74, 0x4f, 0xb5, 0xc7, 0x59, 0x1b, 0x0d, 0xa7, 0xd5, 0x62], "FWPM_CONDITION_SEC_ENCRYPT_ALGORITHM"), + ([0x3b, 0x18, 0x72, 0x47, 0xf8, 0xcc, 0xeb, 0x4a, 0xbc, 0xe1, 0xc6, 0xc6, 0x16, 0x1c, 0x8f, 0xe4], "FWPM_CONDITION_SEC_KEY_SIZE"), + ([0xcb, 0x29, 0xa6, 0x03, 0x52, 0x6e, 0xf8, 0x49, 0x9c, 0x41, 0x57, 0x09, 0x63, 0x3c, 0x09, 0xcf], "FWPM_CONDITION_IP_LOCAL_ADDRESS_V4"), + ([0x84, 0xbe, 0x81, 0x23, 0x24, 0x75, 0xb3, 0x45, 0xa0, 0x5b, 0x1e, 0x63, 0x7d, 0x9c, 0x7a, 0x6a], "FWPM_CONDITION_IP_LOCAL_ADDRESS_V6"), + ([0x1d, 0x74, 0xd0, 0x1b, 0xdf, 0xe3, 0x24, 0x4e, 0x86, 0x34, 0x76, 0x20, 0x46, 0xee, 0xf6, 0xeb], "FWPM_CONDITION_PIPE"), + ([0x10, 0xb6, 0xeb, 0x1f, 0xcc, 0x3b, 0xe1, 0x45, 0xbc, 0x36, 0x2e, 0x06, 0x7e, 0x2c, 0xb1, 0x86], "FWPM_CONDITION_IP_REMOTE_ADDRESS_V4"), + ([0x8c, 0x1d, 0x6e, 0x24, 0xee, 0x8b, 0x18, 0x40, 0x9b, 0x98, 0x31, 0xd4, 0x58, 0x2f, 0x33, 0x61], "FWPM_CONDITION_IP_REMOTE_ADDRESS_V6"), + ([0xa8, 0x80, 0x11, 0xe3, 0xbd, 0xbb, 0x14, 0x4d, 0xa6, 0x5e, 0x71, 0x57, 0xb0, 0x62, 0x33, 0xbb], "FWPM_CONDITION_PROCESS_WITH_RPC_IF_UUID"), + ([0xb9, 0xa0, 0xce, 0xdc, 0x86, 0x08, 0x60, 0x43, 0x9c, 0x6a, 0xab, 0x04, 0x3a, 0x24, 0xfb, 0xa9], "FWPM_CONDITION_RPC_EP_VALUE"), + ([0x4a, 0x81, 0x8b, 0x21, 0x39, 0x0a, 0xb8, 0x49, 0x8e, 0x71, 0xc2, 0x0c, 0x39, 0xc7, 0xdd, 0x2e], "FWPM_CONDITION_RPC_EP_FLAGS"), + ([0x1e, 0xfc, 0x28, 0xc2, 0x3a, 0x40, 0x78, 0x44, 0xbe, 0x05, 0xc9, 0xba, 0xa4, 0xc0, 0x5a, 0xce], "FWPM_CONDITION_CLIENT_TOKEN"), + ([0x25, 0xa2, 0x05, 0xb6, 0xb3, 0xc3, 0xc7, 0x48, 0x98, 0x33, 0x7a, 0xef, 0xa9, 0x52, 0x75, 0x46], "FWPM_CONDITION_RPC_SERVER_NAME"), + ([0x45, 0xf6, 0x90, 0x80, 0xd5, 0x9a, 0x3b, 0x4e, 0x9f, 0x9f, 0x80, 0x23, 0xca, 0x09, 0x79, 0x09], "FWPM_CONDITION_RPC_SERVER_PORT"), + ([0xe2, 0x3f, 0x95, 0x40, 0x65, 0x85, 0x59, 0x47, 0x84, 0x88, 0x17, 0x71, 0xb4, 0xb4, 0xb5, 0xdb], "FWPM_CONDITION_RPC_PROXY_AUTH_TYPE"), + ([0xc7, 0x00, 0xec, 0xa3, 0xf4, 0x05, 0xf7, 0x4d, 0x91, 0xf2, 0x5f, 0x60, 0xd9, 0x1f, 0xf4, 0x43], "FWPM_CONDITION_CLIENT_CERT_KEY_LENGTH"), + ([0x5e, 0xad, 0x91, 0xc4, 0x82, 0xf8, 0x83, 0x42, 0xb9, 0x16, 0x43, 0x6b, 0x10, 0x3f, 0xf4, 0xad], "FWPM_CONDITION_CLIENT_CERT_OID"), + ([0x96, 0x99, 0x6e, 0x20, 0x0e, 0x49, 0xcf, 0x40, 0xb8, 0x31, 0xb3, 0x86, 0x41, 0xeb, 0x6f, 0xcb], "FWPM_CONDITION_NET_EVENT_TYPE"), + ([0x82, 0x90, 0x53, 0x9b, 0x90, 0xeb, 0x86, 0x41, 0xa6, 0xcc, 0xde, 0x5b, 0x63, 0x23, 0x50, 0x16], "FWPM_CONDITION_PEER_NAME"), + ([0xfd, 0x66, 0x81, 0xf6, 0x82, 0x06, 0x89, 0x4c, 0xb8, 0xf5, 0x86, 0x43, 0x6c, 0x7e, 0xf9, 0xb7], "FWPM_CONDITION_REMOTE_ID"), + ([0xd5, 0x8c, 0x45, 0xeb, 0x7b, 0xda, 0xf9, 0x4e, 0x8d, 0x43, 0x7b, 0x0a, 0x84, 0x03, 0x32, 0xf2], "FWPM_CONDITION_AUTHENTICATION_TYPE"), + ([0x49, 0x5f, 0x0f, 0xff, 0xeb, 0x0c, 0x1b, 0x48, 0x86, 0x38, 0x14, 0x79, 0x79, 0x1f, 0x3f, 0x2c], "FWPM_CONDITION_KM_TYPE"), + ([0x82, 0x45, 0xef, 0xfe, 0x8f, 0xef, 0x7b, 0x4f, 0x85, 0x8b, 0x90, 0x77, 0xd1, 0x22, 0xde, 0x47], "FWPM_CONDITION_KM_MODE"), + ([0xe3, 0xde, 0x37, 0xad, 0x2f, 0x72, 0xcc, 0x45, 0xa4, 0xe3, 0x06, 0x80, 0x48, 0x12, 0x44, 0x52], "FWPM_CONDITION_IPSEC_POLICY_KEY"), + ([0xd1, 0xc6, 0x4f, 0xf6, 0xcb, 0xf9, 0xd2, 0x43, 0x8a, 0x5f, 0xe1, 0x3b, 0xc8, 0x94, 0xf2, 0x65], "FWPM_CONDITION_QM_MODE"), + ([0xab, 0x91, 0xa7, 0x35, 0xac, 0x04, 0xf2, 0x4f, 0xa6, 0xbb, 0xda, 0x6c, 0xfa, 0xc7, 0x18, 0x06], "FWPM_CONDITION_COMPARTMENT_ID"), + ([0xeb, 0x4d, 0x8f, 0x67, 0xaf, 0x45, 0x82, 0x48, 0x93, 0xfe, 0x19, 0xd4, 0x72, 0x9d, 0x98, 0x34], "FWPM_CONDITION_RESERVED0"), + ([0x27, 0xf8, 0x18, 0xd8, 0x69, 0x5c, 0xeb, 0x48, 0xbf, 0x80, 0xd8, 0x6b, 0x17, 0x75, 0x5f, 0x97], "FWPM_CONDITION_RESERVED1"), + ([0x3d, 0x12, 0xd4, 0x53, 0x5b, 0xe1, 0x84, 0x4e, 0xb7, 0xa8, 0xdc, 0xe1, 0x6f, 0x7b, 0x62, 0xd9], "FWPM_CONDITION_RESERVED2"), + ([0xa3, 0x8c, 0x6e, 0x7f, 0x06, 0x66, 0x32, 0x49, 0x97, 0xc7, 0xe1, 0xf2, 0x07, 0x10, 0xaf, 0x3b], "FWPM_CONDITION_RESERVED3"), + ([0x42, 0xe6, 0x58, 0x5f, 0x37, 0xb9, 0x5e, 0x49, 0xa9, 0x4b, 0xf6, 0xb0, 0x51, 0xa4, 0x92, 0x50], "FWPM_CONDITION_RESERVED4"), + ([0xcd, 0xf6, 0xa8, 0x9b, 0x7c, 0xf7, 0xe6, 0x43, 0x88, 0x47, 0x11, 0x93, 0x9d, 0xc5, 0xdb, 0x5a], "FWPM_CONDITION_RESERVED5"), + ([0xbd, 0x84, 0x3d, 0xf1, 0xd5, 0x59, 0xc4, 0x44, 0x88, 0x17, 0x5e, 0xcd, 0xae, 0x18, 0x05, 0xbd], "FWPM_CONDITION_RESERVED6"), + ([0x30, 0xf9, 0xa0, 0x65, 0xdd, 0x45, 0x83, 0x49, 0xaa, 0x33, 0xef, 0xc7, 0xb6, 0x11, 0xaf, 0x08], "FWPM_CONDITION_RESERVED7"), + ([0x74, 0x49, 0x42, 0x4f, 0x12, 0x0c, 0x16, 0x48, 0x9b, 0x47, 0x9a, 0x54, 0x7d, 0xb3, 0x9a, 0x32], "FWPM_CONDITION_RESERVED8"), + ([0x0f, 0xe1, 0x78, 0xce, 0xff, 0x13, 0x70, 0x4c, 0x86, 0x43, 0x36, 0xad, 0x18, 0x79, 0xaf, 0xa3], "FWPM_CONDITION_RESERVED9"), + ([0x82, 0xe2, 0x79, 0xb9, 0x21, 0xd6, 0x8c, 0x4c, 0xb1, 0x84, 0xb1, 0x05, 0xa6, 0x1c, 0x36, 0xce], "FWPM_CONDITION_RESERVED10"), + ([0x4d, 0xee, 0x62, 0x2d, 0x3d, 0x02, 0x1f, 0x41, 0x95, 0x82, 0x43, 0xac, 0xbb, 0x79, 0x59, 0x75], "FWPM_CONDITION_RESERVED11"), + ([0x32, 0x7c, 0x67, 0xa3, 0x35, 0x7e, 0xdc, 0x4d, 0x93, 0xda, 0xe8, 0xc3, 0x3f, 0xc9, 0x23, 0xc7], "FWPM_CONDITION_RESERVED12"), + ([0x90, 0x3e, 0x5a, 0x33, 0xaa, 0x84, 0xf5, 0x42, 0x9e, 0x6f, 0x59, 0x30, 0x95, 0x36, 0xa4, 0x4c], "FWPM_CONDITION_RESERVED13"), + ([0xa2, 0x4d, 0xe4, 0x30, 0x1a, 0x2f, 0x16, 0x41, 0xa5, 0x59, 0xf9, 0x07, 0xde, 0x83, 0x60, 0x4a], "FWPM_CONDITION_RESERVED14"), + ([0x0f, 0x34, 0xb8, 0xba, 0xe0, 0xaf, 0xd1, 0x43, 0x80, 0xd8, 0x5c, 0xa4, 0x56, 0x96, 0x2d, 0xe3], "FWPM_CONDITION_RESERVED15"), + ([0x16, 0x92, 0xad, 0x10, 0xde, 0xcc, 0x6c, 0x45, 0x8b, 0x16, 0xe9, 0xf0, 0x4e, 0x60, 0xa9, 0x0b], "FWPM_PROVIDER_IKEEXT"), + ([0xa9, 0x05, 0x6c, 0x3c, 0x5c, 0xc0, 0xb9, 0x4b, 0x83, 0x38, 0x23, 0x27, 0x81, 0x4c, 0xe8, 0xbf], "FWPM_PROVIDER_IPSEC_DOSP_CONFIG"), + ([0x9e, 0xa1, 0x6a, 0x89, 0x34, 0x9a, 0xcb, 0x4b, 0xae, 0x79, 0xbe, 0xb9, 0x12, 0x7c, 0x84, 0xb9], "FWPM_PROVIDER_TCP_CHIMNEY_OFFLOAD"), + ([0x30, 0xcd, 0xcf, 0x76, 0x94, 0x33, 0x2d, 0x43, 0xbe, 0xd3, 0x44, 0x1a, 0xe5, 0x0e, 0x63, 0xc3], "FWPM_PROVIDER_TCP_TEMPLATES"), + ([0x35, 0x37, 0x15, 0x4b, 0x49, 0x10, 0x80, 0x44, 0xaa, 0xb4, 0xd1, 0xb9, 0xbd, 0xc0, 0x37, 0x10], "FWPM_PROVIDER_MPSSVC_WSH"), + ([0xca, 0x16, 0xcc, 0xde, 0x33, 0x3f, 0x46, 0x43, 0xbe, 0x1e, 0x8f, 0xb4, 0xae, 0x0f, 0x3d, 0x62], "FWPM_PROVIDER_MPSSVC_WF"), + ([0xf7, 0x96, 0x02, 0xa9, 0xb8, 0x46, 0x57, 0x44, 0x8f, 0x84, 0xb0, 0x5e, 0x05, 0xd3, 0xc6, 0x22], "FWPM_PROVIDER_MPSSVC_EDP"), + ([0xf9, 0x8f, 0x71, 0xd0, 0xda, 0x44, 0x50, 0x4f, 0x9d, 0xc2, 0xc9, 0x63, 0xa4, 0x24, 0x76, 0x13], "FWPM_PROVIDER_MPSSVC_TENANT_RESTRICTIONS"), + ([0x1f, 0x63, 0xc2, 0x3c, 0x5d, 0x2d, 0xa0, 0x43, 0xb1, 0x74, 0x61, 0x48, 0x37, 0xd8, 0x63, 0xa1], "FWPM_PROVIDER_MPSSVC_APP_ISOLATION"), + ([0x0d, 0x90, 0x32, 0x51, 0x84, 0x5e, 0x5f, 0x4b, 0x80, 0xe4, 0x01, 0x74, 0x1e, 0x81, 0xff, 0x10], "FWPM_CALLOUT_IPSEC_INBOUND_TRANSPORT_V4"), + ([0x92, 0xac, 0xd3, 0x49, 0x6c, 0x2a, 0xcf, 0x4d, 0x95, 0x5f, 0x1c, 0x3b, 0xe0, 0x09, 0xdd, 0x99], "FWPM_CALLOUT_IPSEC_INBOUND_TRANSPORT_V6"), + ([0x0a, 0xbf, 0x46, 0x4b, 0x23, 0x45, 0x57, 0x4e, 0xaa, 0x38, 0xa8, 0x79, 0x87, 0xc9, 0x10, 0xd9], "FWPM_CALLOUT_IPSEC_OUTBOUND_TRANSPORT_V4"), + ([0x22, 0x77, 0xd8, 0x38, 0x83, 0xad, 0x11, 0x4f, 0xa9, 0x1f, 0xdf, 0x0f, 0xb0, 0x77, 0x22, 0x5b], "FWPM_CALLOUT_IPSEC_OUTBOUND_TRANSPORT_V6"), + ([0x46, 0x8a, 0x1a, 0x19, 0xf8, 0x0b, 0xcf, 0x46, 0xb0, 0x45, 0x4b, 0x45, 0xdf, 0xa6, 0xa3, 0x24], "FWPM_CALLOUT_IPSEC_INBOUND_TUNNEL_V4"), + ([0xe3, 0x42, 0xc3, 0x80, 0x53, 0x1e, 0x6f, 0x4d, 0x9b, 0x44, 0x03, 0xdf, 0x5a, 0xee, 0xe1, 0x54], "FWPM_CALLOUT_IPSEC_INBOUND_TUNNEL_V6"), + ([0x6c, 0x19, 0xa4, 0x70, 0x5b, 0x83, 0xb0, 0x4f, 0x98, 0xe8, 0x07, 0x5f, 0x4d, 0x97, 0x7d, 0x46], "FWPM_CALLOUT_IPSEC_OUTBOUND_TUNNEL_V4"), + ([0x63, 0x53, 0x83, 0xf1, 0xa5, 0xa6, 0x62, 0x4e, 0xb1, 0x80, 0x23, 0xdb, 0x78, 0x9d, 0x8d, 0xa6], "FWPM_CALLOUT_IPSEC_OUTBOUND_TUNNEL_V6"), + ([0x33, 0x96, 0x82, 0x28, 0xf0, 0xc4, 0x66, 0x4e, 0x87, 0x3f, 0x84, 0x4d, 0xb2, 0xa8, 0x99, 0xc7], "FWPM_CALLOUT_IPSEC_FORWARD_INBOUND_TUNNEL_V4"), + ([0xc2, 0xbe, 0x50, 0xaf, 0x86, 0xc6, 0x9a, 0x42, 0x88, 0x4d, 0xb7, 0x44, 0x43, 0xe7, 0xb0, 0xb4], "FWPM_CALLOUT_IPSEC_FORWARD_INBOUND_TUNNEL_V6"), + ([0x36, 0x21, 0x53, 0xfb, 0xcb, 0x15, 0x0b, 0x44, 0x93, 0x7c, 0x17, 0x17, 0xca, 0x32, 0x0c, 0x40], "FWPM_CALLOUT_IPSEC_FORWARD_OUTBOUND_TUNNEL_V4"), + ([0xcc, 0x40, 0xe6, 0xda, 0x21, 0xe0, 0xee, 0x4b, 0x9e, 0xb6, 0xa4, 0x8b, 0x27, 0x5c, 0x8c, 0x1d], "FWPM_CALLOUT_IPSEC_FORWARD_OUTBOUND_TUNNEL_V6"), + ([0x9b, 0x30, 0xff, 0x7d, 0x7d, 0xba, 0xba, 0x4a, 0x91, 0xaa, 0xae, 0x5c, 0x66, 0x40, 0xc9, 0x44], "FWPM_CALLOUT_IPSEC_INBOUND_INITIATE_SECURE_V4"), + ([0xd9, 0xd6, 0xa0, 0xa9, 0x8c, 0xc5, 0x4e, 0x47, 0x8a, 0xeb, 0x3c, 0xfe, 0x99, 0xd6, 0xd5, 0x3d], "FWPM_CALLOUT_IPSEC_INBOUND_INITIATE_SECURE_V6"), + ([0xde, 0xe7, 0xf6, 0x3d, 0x20, 0xfd, 0xf2, 0x48, 0x9f, 0x26, 0xf8, 0x54, 0x44, 0x4c, 0xba, 0x79], "FWPM_CALLOUT_IPSEC_INBOUND_TUNNEL_ALE_ACCEPT_V4"), + ([0xd3, 0x92, 0xe3, 0xa1, 0xac, 0x72, 0xbb, 0x47, 0x87, 0xa7, 0x01, 0x22, 0xc6, 0x94, 0x34, 0xab], "FWPM_CALLOUT_IPSEC_INBOUND_TUNNEL_ALE_ACCEPT_V6"), + ([0xfc, 0x41, 0xc1, 0x6a, 0x5d, 0xf7, 0x03, 0x42, 0xb9, 0xc8, 0x48, 0xe6, 0x14, 0x9c, 0x27, 0x12], "FWPM_CALLOUT_IPSEC_ALE_CONNECT_V4"), + ([0x05, 0xda, 0x0d, 0x4c, 0x1f, 0xe3, 0x66, 0x46, 0x90, 0xb0, 0xb3, 0xdf, 0xad, 0x34, 0x12, 0x9a], "FWPM_CALLOUT_IPSEC_ALE_CONNECT_V6"), + ([0x42, 0xa3, 0x08, 0x6d, 0x9e, 0xdb, 0xbe, 0x4f, 0x9e, 0xd2, 0x57, 0x37, 0x4c, 0xe8, 0x9f, 0x79], "FWPM_CALLOUT_IPSEC_DOSP_FORWARD_V6"), + ([0xec, 0x56, 0xcb, 0x2f, 0x37, 0xcd, 0x4f, 0x4b, 0xb1, 0x08, 0x62, 0xc2, 0xb1, 0x85, 0x0a, 0x0c], "FWPM_CALLOUT_IPSEC_DOSP_FORWARD_V4"), + ([0x06, 0x86, 0xa0, 0xed, 0x94, 0x24, 0x78, 0x4d, 0x89, 0xbc, 0x67, 0x83, 0x7c, 0x03, 0xb9, 0x69], "FWPM_CALLOUT_WFP_TRANSPORT_LAYER_V4_SILENT_DROP"), + ([0x74, 0xcc, 0x93, 0x86, 0x75, 0xa0, 0x56, 0x41, 0xb4, 0x76, 0x92, 0x86, 0xee, 0xce, 0x81, 0x4e], "FWPM_CALLOUT_WFP_TRANSPORT_LAYER_V6_SILENT_DROP"), + ([0xb3, 0x0a, 0xe1, 0xf3, 0x25, 0x2c, 0x79, 0x42, 0xac, 0x36, 0xc3, 0x0f, 0xc1, 0x81, 0xbe, 0xc4], "FWPM_CALLOUT_TCP_CHIMNEY_CONNECT_LAYER_V4"), + ([0x85, 0x20, 0xe2, 0x39, 0x41, 0xa3, 0xfc, 0x42, 0xa2, 0x79, 0xae, 0xc9, 0x4e, 0x68, 0x9c, 0x56], "FWPM_CALLOUT_TCP_CHIMNEY_CONNECT_LAYER_V6"), + ([0xb2, 0xec, 0x83, 0xe1, 0x7f, 0x3a, 0x54, 0x4b, 0x8a, 0xd9, 0x76, 0x05, 0x0e, 0xd8, 0x80, 0xca], "FWPM_CALLOUT_TCP_CHIMNEY_ACCEPT_LAYER_V4"), + ([0x41, 0xcf, 0x78, 0x03, 0x98, 0xbf, 0x03, 0x46, 0x81, 0xf2, 0x7f, 0x12, 0x58, 0x60, 0x79, 0xf6], "FWPM_CALLOUT_TCP_CHIMNEY_ACCEPT_LAYER_V6"), + ([0x80, 0x22, 0x58, 0xbc, 0x77, 0x16, 0xe9, 0x41, 0x94, 0xab, 0xc2, 0xfc, 0xb1, 0x5c, 0x2e, 0xeb], "FWPM_CALLOUT_SET_OPTIONS_AUTH_CONNECT_LAYER_V4"), + ([0x3c, 0x37, 0xe5, 0x98, 0x84, 0xb8, 0x0f, 0x49, 0xb6, 0x5f, 0x2f, 0x6a, 0x4a, 0x57, 0x51, 0x95], "FWPM_CALLOUT_SET_OPTIONS_AUTH_CONNECT_LAYER_V6"), + ([0x08, 0xf0, 0x55, 0x2d, 0x01, 0x0c, 0x92, 0x4f, 0xb2, 0x6e, 0xa0, 0x8a, 0x94, 0x56, 0x9b, 0x8d], "FWPM_CALLOUT_SET_OPTIONS_AUTH_RECV_ACCEPT_LAYER_V4"), + ([0x37, 0x85, 0x01, 0x63, 0x81, 0xf2, 0xc4, 0x4d, 0x83, 0xd3, 0x8d, 0xec, 0x18, 0xb7, 0xad, 0xe2], "FWPM_CALLOUT_SET_OPTIONS_AUTH_RECV_ACCEPT_LAYER_V6"), + ([0x4d, 0x52, 0x8b, 0x28, 0x66, 0x05, 0x19, 0x4e, 0xb6, 0x12, 0x8f, 0x44, 0x1a, 0x2e, 0x59, 0x49], "FWPM_CALLOUT_RESERVED_AUTH_CONNECT_LAYER_V4"), + ([0x92, 0x4b, 0xb8, 0x00, 0x5e, 0x2b, 0x71, 0x4b, 0xab, 0x0e, 0xaa, 0xca, 0x43, 0xe3, 0x87, 0xe6], "FWPM_CALLOUT_RESERVED_AUTH_CONNECT_LAYER_V6"), + ([0x92, 0x53, 0xb9, 0x31, 0x6e, 0x06, 0xa2, 0x42, 0xb7, 0xdb, 0x92, 0xf8, 0xac, 0xdd, 0x56, 0xf9], "FWPM_CALLOUT_TEREDO_ALE_RESOURCE_ASSIGNMENT_V6"), + ([0x10, 0x10, 0x9b, 0x07, 0xc5, 0xf1, 0xcd, 0x4f, 0xae, 0x05, 0xda, 0x41, 0x10, 0x7a, 0xbd, 0x0b], "FWPM_CALLOUT_EDGE_TRAVERSAL_ALE_RESOURCE_ASSIGNMENT_V4"), + ([0xe7, 0x34, 0xa4, 0x81, 0x0c, 0xf6, 0x78, 0x43, 0xba, 0xb8, 0xc6, 0x25, 0xa3, 0x0f, 0x01, 0x97], "FWPM_CALLOUT_TEREDO_ALE_LISTEN_V6"), + ([0xb5, 0x6a, 0x48, 0x33, 0x5e, 0x6d, 0x65, 0x4e, 0xa0, 0x0b, 0xa7, 0xaf, 0xed, 0x0b, 0xa9, 0xa1], "FWPM_CALLOUT_EDGE_TRAVERSAL_ALE_LISTEN_V4"), + ([0x39, 0x0b, 0x5a, 0x21, 0x7e, 0x4b, 0xda, 0x4e, 0x8c, 0xe4, 0x17, 0x96, 0x79, 0xdf, 0x62, 0x24], "FWPM_CALLOUT_TCP_TEMPLATES_CONNECT_LAYER_V4"), + ([0xa1, 0x37, 0x8b, 0x83, 0x12, 0x5c, 0x34, 0x4d, 0x8b, 0x38, 0x07, 0x87, 0x28, 0xb2, 0xd2, 0x5c], "FWPM_CALLOUT_TCP_TEMPLATES_CONNECT_LAYER_V6"), + ([0xd0, 0xf5, 0x23, 0x2f, 0xc4, 0x40, 0x41, 0x4c, 0xa2, 0x54, 0x46, 0xd8, 0xdb, 0xa8, 0x95, 0x7c], "FWPM_CALLOUT_TCP_TEMPLATES_ACCEPT_LAYER_V4"), + ([0xf0, 0x52, 0x51, 0xb2, 0x1c, 0x99, 0x53, 0x4f, 0xbb, 0xe7, 0xd2, 0x4b, 0x45, 0xfe, 0x63, 0x2c], "FWPM_CALLOUT_TCP_TEMPLATES_ACCEPT_LAYER_V6"), + ([0x1d, 0xc3, 0xbf, 0x5f, 0x1c, 0xa5, 0xdc, 0x44, 0xac, 0xb6, 0x06, 0x24, 0xa0, 0x30, 0xa7, 0x00], "FWPM_CALLOUT_POLICY_SILENT_MODE_AUTH_CONNECT_LAYER_V4"), + ([0x1d, 0xc3, 0xbf, 0x5f, 0x1c, 0xa5, 0xdc, 0x44, 0xac, 0xb6, 0x06, 0x24, 0xa0, 0x30, 0xa7, 0x01], "FWPM_CALLOUT_POLICY_SILENT_MODE_AUTH_CONNECT_LAYER_V6"), + ([0x1d, 0xc3, 0xbf, 0x5f, 0x1c, 0xa5, 0xdc, 0x44, 0xac, 0xb6, 0x06, 0x24, 0xa0, 0x30, 0xa7, 0x02], "FWPM_CALLOUT_POLICY_SILENT_MODE_AUTH_RECV_ACCEPT_LAYER_V4"), + ([0x1d, 0xc3, 0xbf, 0x5f, 0x1c, 0xa5, 0xdc, 0x44, 0xac, 0xb6, 0x06, 0x24, 0xa0, 0x30, 0xa7, 0x03], "FWPM_CALLOUT_POLICY_SILENT_MODE_AUTH_RECV_ACCEPT_LAYER_V6"), + ([0x49, 0x32, 0x42, 0xb3, 0x09, 0x8d, 0x58, 0x48, 0x92, 0x10, 0x95, 0xc7, 0xfd, 0xa8, 0xe3, 0x0f], "FWPM_CALLOUT_HTTP_TEMPLATE_SSL_HANDSHAKE"), + ([0xa4, 0x19, 0x97, 0x77, 0x95, 0xe6, 0xb6, 0x47, 0xa1, 0x99, 0x79, 0x99, 0xfe, 0xc9, 0x16, 0x3b], "FWPM_CALLOUT_BUILT_IN_RESERVED_1"), + ([0xb6, 0x61, 0x96, 0xef, 0x5e, 0x7c, 0xfd, 0x48, 0xa1, 0x30, 0x96, 0x67, 0x8c, 0xea, 0xcc, 0x41], "FWPM_CALLOUT_BUILT_IN_RESERVED_2"), + ([0x7a, 0x9c, 0x72, 0x18, 0x62, 0x2f, 0xe0, 0x4b, 0x96, 0x6f, 0x97, 0x4b, 0x21, 0xb8, 0x6d, 0xf1], "FWPM_CALLOUT_BUILT_IN_RESERVED_3"), + ([0x01, 0xb8, 0x3f, 0x6c, 0xff, 0xda, 0xe9, 0x40, 0x91, 0xe6, 0xf7, 0xff, 0x7e, 0x52, 0xf7, 0xd9], "FWPM_CALLOUT_BUILT_IN_RESERVED_4"), + ([0x00, 0xa8, 0x5e, 0xb2, 0x02, 0x0d, 0xed, 0x46, 0x92, 0xbd, 0x7f, 0xa8, 0x4b, 0xb7, 0x3e, 0x9d], "FWPM_PROVIDER_CONTEXT_SECURE_SOCKET_AUTHIP"), + ([0x44, 0x41, 0x2d, 0x8c, 0xe0, 0xf8, 0xc0, 0x42, 0x94, 0xce, 0x7c, 0xcf, 0xc6, 0x3b, 0x2f, 0x9b], "FWPM_PROVIDER_CONTEXT_SECURE_SOCKET_IPSEC"), + ([0x87, 0xf7, 0xbb, 0xa9, 0xa8, 0x82, 0xbb, 0x45, 0xa4, 0x00, 0x5d, 0x7e, 0x59, 0x52, 0xc7, 0xa9], "FWPM_KEYING_MODULE_IKE"), + ([0xe0, 0xda, 0xe3, 0x11, 0x26, 0xdd, 0x90, 0x45, 0x85, 0x7d, 0xab, 0x4b, 0x28, 0xd1, 0xa0, 0x95], "FWPM_KEYING_MODULE_AUTHIP"), + ([0xcc, 0x92, 0x17, 0x04, 0x07, 0x8f, 0x9d, 0x41, 0xa3, 0x94, 0x71, 0x69, 0x68, 0xcb, 0x16, 0x47], "FWPM_KEYING_MODULE_IKEV2"), +]; diff --git a/crates/compat/compat-common/src/online/fortnite/qos.rs b/crates/compat/compat-common/src/online/fortnite/qos.rs index f9c2e474..d9d97c20 100644 --- a/crates/compat/compat-common/src/online/fortnite/qos.rs +++ b/crates/compat/compat-common/src/online/fortnite/qos.rs @@ -12,7 +12,10 @@ fn responder() -> &'static Option { static P: OnceLock> = OnceLock::new(); P.get_or_init(|| { let sock = match UdpSocket::bind(("127.0.0.1", 0)) { - Ok(s) => s, + Ok(s) => { + crate::netview::sockets::report_std(&s); + s + } Err(e) => { crate::record_raw("online", "[qos]", &format!("bind failed: {e}")); return None; diff --git a/crates/compat/compat-common/src/online/http.rs b/crates/compat/compat-common/src/online/http.rs index e0141c9d..0e5073b9 100644 --- a/crates/compat/compat-common/src/online/http.rs +++ b/crates/compat/compat-common/src/online/http.rs @@ -9,6 +9,7 @@ const MAX_BODY: usize = 64 * 1024 * 1024; pub fn serve(title: Box) -> std::io::Result { let listener = TcpListener::bind(("127.0.0.1", 0))?; + crate::netview::sockets::report_std(&listener); let port = listener.local_addr()?.port(); let title: Arc = Arc::from(title); std::thread::Builder::new().name("tombox-online-accept".into()).spawn(move || { diff --git a/crates/compat/compat-common/src/online/lan.rs b/crates/compat/compat-common/src/online/lan.rs index a0884f14..fd809a92 100644 --- a/crates/compat/compat-common/src/online/lan.rs +++ b/crates/compat/compat-common/src/online/lan.rs @@ -130,6 +130,7 @@ pub fn discover(timeout: Duration, extra: &[SocketAddr]) -> Option { let dp = discovery_port(); crate::net_guard::allow_lan_broadcast(dp); let sock = UdpSocket::bind(("0.0.0.0", 0)).ok()?; + crate::netview::sockets::report_std(&sock); let _ = sock.set_broadcast(true); let _ = sock.set_read_timeout(Some(Duration::from_millis(200))); let ask = format!("{MAGIC_ASK} {}", device_id()); @@ -297,6 +298,7 @@ impl Hub { pub fn start_hub(port: u16) -> std::io::Result { let l = TcpListener::bind(("0.0.0.0", port))?; + crate::netview::sockets::report_std(&l); let bound = l.local_addr()?.port(); let h = hub(); std::thread::Builder::new().name("tombox-lan-hub".into()).spawn(move || { @@ -316,6 +318,7 @@ pub fn start_hub(port: u16) -> std::io::Result { let dp = discovery_port(); match UdpSocket::bind(("0.0.0.0", dp)) { Ok(u) => { + crate::netview::sockets::report_std(&u); let _ = std::thread::Builder::new().name("tombox-lan-discovery".into()).spawn(move || { let mut buf = [0u8; 256]; loop { diff --git a/crates/compat/compat-common/src/online/playfab/qos.rs b/crates/compat/compat-common/src/online/playfab/qos.rs index ca195332..939ba8e6 100644 --- a/crates/compat/compat-common/src/online/playfab/qos.rs +++ b/crates/compat/compat-common/src/online/playfab/qos.rs @@ -30,6 +30,7 @@ pub fn ensure_started() -> Option { let port = std::env::var("TOMBOX_PLAYFAB_QOS_PORT").ok().or_else(|| crate::cfg("playfab_qos_port")).and_then(|p| p.trim().parse().ok()).unwrap_or(QOS_PORT); match UdpSocket::bind(("127.0.0.1", port)) { Ok(sock) => { + crate::netview::sockets::report_std(&sock); let bound = sock.local_addr().map(|a| a.port()).unwrap_or(port); std::thread::Builder::new().name("tombox-playfab-qos".into()).spawn(move || { let mut buf = [0u8; 2048]; diff --git a/crates/compat/compat-common/src/online/trackmania/mod.rs b/crates/compat/compat-common/src/online/trackmania/mod.rs index 8a3da482..20b88c17 100644 --- a/crates/compat/compat-common/src/online/trackmania/mod.rs +++ b/crates/compat/compat-common/src/online/trackmania/mod.rs @@ -25,6 +25,12 @@ fn is_core_host(h: &str) -> bool { h == "nadeo.online" || h.ends_with(".nadeo.online") } +pub const STATUS_HOST: &str = "trackmania-status.cdn.ubi.com"; + +fn is_status_request(req: &Request, host: &str) -> bool { + host == STATUS_HOST && req.method == "GET" && req.path.trim_end_matches('/').eq_ignore_ascii_case("/status.json") +} + pub const NADEO_PARAMETER_GROUP: &str = "NadeoServicesParameters"; pub const MASTERSERVER_INIT_URL: &str = "https://prod.trackmania.core.nadeo.online/api/routes"; @@ -126,6 +132,10 @@ impl TitleService for Trackmania { if is_nadeo_host(&host) { return self.nadeo(req, &host); } + if is_status_request(req, &host) { + crate::record_raw("online", "trackmania", &format!("{STATUS_HOST}/status.json answered 404: the status schema is not decoded (caller is in the encrypted title pack), and 404 is the answer the game is known to tolerate")); + return Some(self.ubi.not_found(req)); + } let r = self.ubi.route(req)?; Some(with_nadeo_parameters(req, r)) } diff --git a/crates/compat/compat-common/src/online/trackmania/tests.rs b/crates/compat/compat-common/src/online/trackmania/tests.rs index 4bc4b48c..f3f797ae 100644 --- a/crates/compat/compat-common/src/online/trackmania/tests.rs +++ b/crates/compat/compat-common/src/online/trackmania/tests.rs @@ -446,3 +446,19 @@ fn waiting_queue_is_clear_before_authentication() { assert!(gbx_iso_ok("2026-11-22T05:44:00+00:00") && gbx_iso_ok("2026-11-22T05:44:00.123Z") && !gbx_iso_ok("yesterday")); assert_eq!(t.route(&req("PUT", CORE, "/waitingQueue/x", &[], &[], b"")).unwrap().status, 400); } + +#[test] +fn status_json_gets_the_tolerated_404() { + let t = tm(); + let r = t.route(&req("GET", STATUS_HOST, "/status.json", &[], &[], b"")).unwrap(); + assert_eq!(r.status, 404); + let reference = t.ubi.not_found(&req("GET", STATUS_HOST, "/status.json", &[], &[], b"")); + assert_eq!(r.content_type, reference.content_type); + let (b, rb) = (body(&r), body(&reference)); + for k in ["errorCode", "httpCode", "message", "errorContext", "environment"] { + assert_eq!(b[k], rb[k], "{k}"); + } + assert_eq!(b["httpCode"], 404); + assert!(t.route(&req("POST", STATUS_HOST, "/status.json", &[], &[], b"")).is_none()); + assert!(t.route(&req("GET", "public-ubiservices.ubi.com", "/status.json", &[], &[], b"")).is_none()); +} diff --git a/crates/compat/compat-common/src/os_host/foreign.rs b/crates/compat/compat-common/src/os_host/foreign.rs new file mode 100644 index 00000000..e37a43dd --- /dev/null +++ b/crates/compat/compat-common/src/os_host/foreign.rs @@ -0,0 +1,223 @@ +use core::ffi::c_void; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +#[link(name = "kernel32")] +extern "system" { + fn GetLongPathNameW(short: *const u16, long: *mut u16, n: u32) -> u32; +} + +pub fn normalize(path: &str) -> String { + let mut s = path.replace('/', "\\"); + for p in ["\\\\?\\UNC\\", "\\??\\UNC\\"] { + if s.len() >= p.len() && s[..p.len()].eq_ignore_ascii_case(p) { + s = format!("\\\\{}", &s[p.len()..]); + } + } + for p in ["\\\\?\\", "\\??\\", "\\\\.\\"] { + if s.starts_with(p) { + s = s[p.len()..].to_string(); + } + } + if s.contains('~') { + let w: Vec = s.encode_utf16().chain(Some(0)).collect(); + let mut buf = vec![0u16; 32768]; + let n = unsafe { GetLongPathNameW(w.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) } as usize; + if n > 0 && n < buf.len() { + s = String::from_utf16_lossy(&buf[..n]); + } + } + while s.contains("\\\\") && !s.starts_with("\\\\") { + s = s.replace("\\\\", "\\"); + } + let mut s = s.to_ascii_lowercase(); + if !s.ends_with('\\') && Path::new(&s).extension().is_none() { + s.push('\\'); + } + s +} + +fn root_form(p: &Path) -> Option { + let s = p.to_string_lossy(); + if s.is_empty() { + return None; + } + let mut n = normalize(&s); + if !n.ends_with('\\') { + n.push('\\'); + } + Some(n) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Origin { + System, + Game, + Emulator, + HostInjected, +} + +pub fn classify_with(path: &str, windows: &str, game: &[String], emulator: &[String]) -> Origin { + let p = normalize(path); + let under = |r: &String| !r.is_empty() && p.starts_with(r.as_str()); + if under(&normalize(windows)) { + return Origin::System; + } + if game.iter().any(under) { + return Origin::Game; + } + if emulator.iter().any(under) { + return Origin::Emulator; + } + Origin::HostInjected +} + +fn game_roots() -> &'static Vec { + static G: OnceLock> = OnceLock::new(); + G.get_or_init(|| { + let mut v: Vec = Vec::new(); + if let Some(d) = std::env::current_exe().ok().and_then(|e| e.parent().map(|p| p.to_path_buf())) { + v.push(d); + } + v.push(super::dlldir::package_root().clone()); + if let Some(d) = crate::gdk::title().dir.clone() { + v.push(d); + } + for k in ["TOMBOX_PACKAGE_ROOT", "TOMBOX_GAME_DIR", "TOMBOX_GAME_ROOT"] { + if let Ok(s) = std::env::var(k) { + v.push(PathBuf::from(s)); + } + } + let mut out: Vec = v.iter().filter_map(|p| root_form(p)).collect(); + out.sort(); + out.dedup(); + out + }) +} + +fn emulator_roots() -> &'static Vec { + static E: OnceLock> = OnceLock::new(); + E.get_or_init(|| { + let mut v: Vec = Vec::new(); + let own = super::patch::self_module(); + if own != 0 { + let p = unsafe { super::patch::module_path(own as *mut c_void) }; + if let Some(d) = Path::new(&p).parent() { + v.push(d.to_path_buf()); + } + } + for k in ["TOMBOX_DLL_DIR", "TOMBOX_ROOT", "TOMBOX_EMULATOR_DIR", "TOMBOX_GDK_ROOT"] { + if let Ok(s) = std::env::var(k) { + v.push(PathBuf::from(s)); + } + } + let mut out: Vec = v.iter().filter_map(|p| root_form(p)).collect(); + out.sort(); + out.dedup(); + out + }) +} + +pub fn prime() { + let _ = (game_roots(), emulator_roots()); +} + +pub fn foreign_allowed() -> bool { + std::env::var("TOMBOX_LATE_LOAD_FOREIGN").map(|v| v == "1").unwrap_or(false) +} + +pub fn origin(path: &str) -> Origin { + classify_with(path, super::patch::windows_dir(), game_roots(), emulator_roots()) +} + +pub fn is_host_injected(path: &str) -> bool { + if path.is_empty() || foreign_allowed() { + return false; + } + if origin(path) != Origin::HostInjected { + return false; + } + static SEEN: OnceLock>> = OnceLock::new(); + let key = normalize(path); + if SEEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()).insert(key) { + crate::record_raw("os_host", "late_load", &format!("late_load: {path} is host-injected (outside game/emulator), imports left native")); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roots() -> (String, Vec, Vec) { + ("C:\\Windows\\".into(), vec![normalize("Y:\\"), normalize("D:\\xbox-pc-port\\games\\Terraria\\extracted\\pkg\\")], vec![normalize("D:\\TomBox\\target\\release\\")]) + } + + #[test] + fn game_mount_and_package_paths_are_game() { + let (w, g, e) = roots(); + assert_eq!(classify_with("Y:\\Terraria.exe", &w, &g, &e), Origin::Game); + assert_eq!(classify_with("y:\\Bin\\XCurl.dll", &w, &g, &e), Origin::Game); + assert_eq!(classify_with("D:\\XBOX-PC-PORT\\games\\Terraria\\extracted\\pkg\\x.dll", &w, &g, &e), Origin::Game); + assert_eq!(classify_with("\\\\?\\Y:\\Bin\\a.dll", &w, &g, &e), Origin::Game); + assert_eq!(classify_with("Y:/Bin/a.dll", &w, &g, &e), Origin::Game); + } + + #[test] + fn emulator_directory_is_emulator() { + let (w, g, e) = roots(); + assert_eq!(classify_with("D:\\TomBox\\target\\release\\xmem.dll", &w, &g, &e), Origin::Emulator); + assert_eq!(classify_with("d:\\tombox\\TARGET\\Release\\d3d12_xs.dll", &w, &g, &e), Origin::Emulator); + } + + #[test] + fn overlays_and_program_files_are_host_injected() { + let (w, g, e) = roots(); + assert_eq!(classify_with("C:\\Users\\someone\\AppData\\Local\\Discord\\app-1.0.9\\modules\\discord_hook\\DiscordHook64.dll", &w, &g, &e), Origin::HostInjected); + assert_eq!(classify_with("C:\\Program Files (x86)\\Steam\\GameOverlayRenderer64.dll", &w, &g, &e), Origin::HostInjected); + assert_eq!(classify_with("C:\\Program Files\\NVIDIA Corporation\\NvContainer\\nvspcap64.dll", &w, &g, &e), Origin::HostInjected); + assert_eq!(classify_with("\\\\server\\share\\hook.dll", &w, &g, &e), Origin::HostInjected); + assert_eq!(classify_with("\\\\?\\UNC\\server\\share\\hook.dll", &w, &g, &e), Origin::HostInjected); + assert_eq!(classify_with("Y:\\..hidden", &w, &g, &e), Origin::Game); + } + + #[test] + fn system_directory_is_system_in_any_case() { + let (w, g, e) = roots(); + assert_eq!(classify_with("C:\\WINDOWS\\System32\\d3d12.dll", &w, &g, &e), Origin::System); + assert_eq!(classify_with("\\??\\c:\\windows\\system32\\nvwgf2umx.dll", &w, &g, &e), Origin::System); + } + + #[test] + fn prefix_match_is_on_directory_boundaries() { + let w = "C:\\Windows\\".to_string(); + let g = vec![normalize("D:\\games\\Terraria\\")]; + let e = vec![normalize("D:\\TomBox\\target\\release\\")]; + assert_eq!(classify_with("D:\\games\\TerrariaMods\\hook.dll", &w, &g, &e), Origin::HostInjected); + assert_eq!(classify_with("D:\\TomBox\\target\\release2\\x.dll", &w, &g, &e), Origin::HostInjected); + } + + #[test] + fn short_names_expand_before_matching() { + let dir = std::env::temp_dir().join("tombox foreign long name test"); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("hook.dll"); + std::fs::write(&file, b"x").unwrap(); + let long = file.to_string_lossy().into_owned(); + let w: Vec = long.encode_utf16().chain(Some(0)).collect(); + let mut buf = vec![0u16; 1024]; + #[link(name = "kernel32")] + extern "system" { + fn GetShortPathNameW(l: *const u16, s: *mut u16, n: u32) -> u32; + } + let n = unsafe { GetShortPathNameW(w.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) } as usize; + let short = String::from_utf16_lossy(&buf[..n]); + let g = vec![normalize(&dir.to_string_lossy())]; + if short.contains('~') { + assert_eq!(classify_with(&short, "C:\\Windows\\", &g, &[]), Origin::Game, "{short}"); + } + assert_eq!(classify_with(&long, "C:\\Windows\\", &g, &[]), Origin::Game); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/compat/compat-common/src/os_host/fortnite_match.rs b/crates/compat/compat-common/src/os_host/fortnite_match.rs index dc5620f8..25b6d2de 100644 --- a/crates/compat/compat-common/src/os_host/fortnite_match.rs +++ b/crates/compat/compat-common/src/os_host/fortnite_match.rs @@ -10,17 +10,45 @@ extern "system" { pub const TITLE_EXE: &str = "fortniteclient-xsx-shipping.exe"; -pub const START_GAME_INSTANCE_SITE: usize = 0xB46800; -pub const START_GAME_INSTANCE_ORIGINAL: [u8; 7] = [0x4C, 0x8D, 0x3D, 0xB9, 0x85, 0x6D, 0x05]; -pub const START_GAME_INSTANCE_PATCHED: [u8; 7] = [0x49, 0x89, 0xC7, 0x90, 0x90, 0x90, 0x90]; - -pub const BROWSE_RVA: usize = 0xB1D51C; -pub const BROWSE_PROLOGUE: [u8; 13] = [0x40, 0x55, 0x53, 0x56, 0x57, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41, 0x57]; -pub const BROWSE_VTABLE_SLOTS: [usize; 3] = [0x624D688 + 0x440, 0x624DDF0 + 0x440, 0x624E3D0 + 0x440]; -pub const FURL_CTOR_RVA: usize = 0xBFA6B4; -pub const FURL_CTOR_PROLOGUE_RVA_CHECK: usize = 0xB468F0; -pub const FURL_DTOR_RVA: usize = 0xD005C0; -pub const FURL_DTOR_PROLOGUE: [u8; 13] = [0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0x48, 0x8B, 0x49, 0x58]; +pub const VALUE_KEYS: [&str; 9] = ["fn.start_game_instance_site", "fn.browse", "fn.browse_vtable_slot0", "fn.browse_vtable_slot1", "fn.browse_vtable_slot2", "fn.furl_ctor", "fn.furl_ctor_call_site", "fn.furl_dtor", "fn.browse_vcall_site"]; +pub const BYTE_KEYS: [&str; 5] = ["fn.start_game_instance_original", "fn.start_game_instance_patched", "fn.browse_prologue", "fn.furl_dtor_prologue", "fn.browse_vcall"]; + +#[derive(Clone, Debug, PartialEq)] +pub struct Layout { + pub site: usize, + pub browse: usize, + pub slots: Vec, + pub ctor: usize, + pub ctor_call_site: usize, + pub dtor: usize, + pub vcall_site: usize, + pub original: [u8; 7], + pub patched: [u8; 7], + pub browse_prologue: Vec, + pub dtor_prologue: Vec, + pub vcall: Vec, +} + +pub fn layout(o: &crate::title_offsets::Offsets) -> Result { + let v = o.require(&VALUE_KEYS)?; + let b = o.require_bytes(&BYTE_KEYS)?; + let seven = |i: usize| -> Result<[u8; 7], String> { b[i].as_slice().try_into().map_err(|_| format!("{}: {} must be 7 bytes", o.source, BYTE_KEYS[i])) }; + Ok(Layout { + site: v[0], + browse: v[1], + slots: vec![v[2], v[3], v[4]], + ctor: v[5], + ctor_call_site: v[6], + dtor: v[7], + vcall_site: v[8], + original: seven(0)?, + patched: seven(1)?, + browse_prologue: b[2].clone(), + dtor_prologue: b[3].clone(), + vcall: b[4].clone(), + }) +} + pub const FURL_SIZE: usize = 0x68; pub const TRAVEL_PARTIAL: u32 = 1; @@ -93,13 +121,13 @@ pub enum SiteState { Mismatch, } -pub fn classify_site(call_byte: u8, bytes: &[u8; 7]) -> SiteState { +pub fn classify_site(call_byte: u8, bytes: &[u8; 7], original: &[u8; 7], patched: &[u8; 7]) -> SiteState { if call_byte != 0xE8 { return SiteState::Mismatch; } - if *bytes == START_GAME_INSTANCE_ORIGINAL { + if bytes == original { SiteState::Original - } else if *bytes == START_GAME_INSTANCE_PATCHED { + } else if bytes == patched { SiteState::AlreadyPatched } else { SiteState::Mismatch @@ -122,13 +150,13 @@ unsafe fn protected_write(dst: *mut u8, src: &[u8]) -> bool { true } -pub unsafe fn patch_cmdline_at(site: *mut u8) -> Result { +pub unsafe fn patch_cmdline_at(site: *mut u8, original: &[u8; 7], patched: &[u8; 7]) -> Result { let call_byte = *site.sub(5); let mut cur = [0u8; 7]; core::ptr::copy_nonoverlapping(site, cur.as_mut_ptr(), 7); - match classify_site(call_byte, &cur) { + match classify_site(call_byte, &cur, original, patched) { SiteState::Original => { - if protected_write(site, &START_GAME_INSTANCE_PATCHED) { + if protected_write(site, patched) { Ok(SiteState::Original) } else { Err(format!("VirtualProtect failed at {:#x}", site as usize)) @@ -215,6 +243,8 @@ type UrlCtorFn = unsafe extern "system" fn(*mut u8, *const u8, *const u16, u32) type UrlDtorFn = unsafe extern "system" fn(*mut u8); static BASE: AtomicUsize = AtomicUsize::new(0); +static CTOR: AtomicUsize = AtomicUsize::new(0); +static DTOR: AtomicUsize = AtomicUsize::new(0); static ORIG_BROWSE: AtomicUsize = AtomicUsize::new(0); static BROWSE_LOGS: AtomicUsize = AtomicUsize::new(0); @@ -224,7 +254,8 @@ struct UrlBuf([u8; 0x100]); unsafe extern "system" fn browse_hook(this: *mut c_void, ctx: *mut c_void, url: *mut u8, err: *mut c_void) -> usize { let orig: BrowseFn = core::mem::transmute(ORIG_BROWSE.load(Ordering::Acquire)); let base = BASE.load(Ordering::Acquire); - if url.is_null() || base == 0 { + let (ctor_at, dtor_at) = (CTOR.load(Ordering::Acquire), DTOR.load(Ordering::Acquire)); + if url.is_null() || base == 0 || ctor_at == 0 || dtor_at == 0 { return orig(this, ctx, url, err); } let view = read_url(url); @@ -232,8 +263,8 @@ unsafe extern "system" fn browse_hook(this: *mut c_void, ctx: *mut c_void, url: match rewrite_text(&view, &sent, &map(), &gamemode(), &playlist()) { Some(text) => { let wide: Vec = text.encode_utf16().chain(Some(0)).collect(); - let ctor: UrlCtorFn = core::mem::transmute(base + FURL_CTOR_RVA); - let dtor: UrlDtorFn = core::mem::transmute(base + FURL_DTOR_RVA); + let ctor: UrlCtorFn = core::mem::transmute(ctor_at); + let dtor: UrlDtorFn = core::mem::transmute(dtor_at); let mut tmp = UrlBuf([0u8; 0x100]); ctor(tmp.0.as_mut_ptr(), url, wide.as_ptr(), TRAVEL_PARTIAL); let new_view = read_url(tmp.0.as_ptr()); @@ -255,39 +286,48 @@ unsafe fn bytes_at(p: *const u8, want: &[u8]) -> bool { core::slice::from_raw_parts(p, want.len()) == want } -unsafe fn ctor_call_target_ok(base: usize) -> bool { - let site = (base + FURL_CTOR_PROLOGUE_RVA_CHECK) as *const u8; - if *site != 0xE8 { - return false; +pub fn call_target(site: usize, call: &[u8]) -> Option { + if call.len() < 5 || call[0] != 0xE8 { + return None; } - let rel = core::ptr::read_unaligned(site.add(1) as *const i32) as isize; - (site as isize + 5 + rel) as usize == base + FURL_CTOR_RVA + let rel = i32::from_le_bytes(call[1..5].try_into().ok()?) as isize; + Some((site as isize + 5 + rel) as usize) +} + +unsafe fn ctor_call_target_ok(base: usize, l: &Layout) -> bool { + let site = base + l.ctor_call_site; + call_target(site, core::slice::from_raw_parts(site as *const u8, 5)) == Some(base + l.ctor) } -unsafe fn install_browse(base: usize) -> Result { - let f = (base + BROWSE_RVA) as *const u8; - if !bytes_at(f, &BROWSE_PROLOGUE) { - return Err(format!("Browse prologue mismatch {}", hex(core::slice::from_raw_parts(f, 13)))); +unsafe fn install_browse(base: usize, l: &Layout) -> Result { + let f = (base + l.browse) as *const u8; + if !bytes_at(f, &l.browse_prologue) { + return Err(format!("Browse prologue mismatch {}", hex(core::slice::from_raw_parts(f, l.browse_prologue.len())))); } - if !bytes_at((base + FURL_DTOR_RVA) as *const u8, &FURL_DTOR_PROLOGUE) { + if !bytes_at((base + l.dtor) as *const u8, &l.dtor_prologue) { return Err("FURL destructor bytes mismatch".into()); } - if !ctor_call_target_ok(base) { + if !ctor_call_target_ok(base, l) { return Err("FURL constructor call site mismatch".into()); } + if !bytes_at((base + l.vcall_site) as *const u8, &l.vcall) { + return Err("Browse virtual call site mismatch".into()); + } + CTOR.store(base + l.ctor, Ordering::Release); + DTOR.store(base + l.dtor, Ordering::Release); BASE.store(base, Ordering::Release); - ORIG_BROWSE.store(base + BROWSE_RVA, Ordering::Release); + ORIG_BROWSE.store(base + l.browse, Ordering::Release); let hook = browse_hook as *const () as usize; let mut n = 0; - for rva in BROWSE_VTABLE_SLOTS { + for &rva in &l.slots { let slot = (base + rva) as *mut usize; let cur = core::ptr::read_volatile(slot); if cur == hook { n += 1; continue; } - if cur != base + BROWSE_RVA { - return Err(format!("vtable slot {rva:#x} holds {cur:#x}, expected {:#x}", base + BROWSE_RVA)); + if cur != base + l.browse { + return Err(format!("vtable slot {rva:#x} holds {cur:#x}, expected {:#x}", base + l.browse)); } if !protected_write(slot as *mut u8, &hook.to_le_bytes()) { return Err(format!("VirtualProtect failed on vtable slot {rva:#x}")); @@ -317,8 +357,35 @@ pub fn apply() { Some(b) => b, None => return, }; - let site = (base + START_GAME_INSTANCE_SITE) as *mut u8; - match unsafe { patch_cmdline_at(site) } { + let from_symbols = crate::title_symbols::for_this_title().and_then(|t| { + let (size, data) = unsafe { image_sections(base as *const u8) }; + let img = unsafe { core::slice::from_raw_parts(base as *const u8, size) }; + layout_from_image(img, base, &data, t).map(|l| (l, t.source.clone())) + }); + let chosen = match from_symbols { + Ok(v) => Ok(v), + Err(se) => crate::title_offsets::load_for(TITLE_EXE) + .and_then(|o| { + let stamp = unsafe { crate::title_offsets::image_timestamp(base as *const u8) }; + if o.pe_timestamp.is_none() || !o.matches_image(stamp) { + return Err(format!("{} does not match image timestamp {stamp:#x}", o.source)); + } + layout(&o).map(|l| (l, o.source.clone())) + }) + .map_err(|je| format!("symbols: {se}; offsets file: {je}")), + }; + let l = match chosen { + Ok((l, source)) => { + crate::record_raw("fn-match", "layout", &format!("from {source}: {} Browse vtable slots", l.slots.len())); + l + } + Err(e) => { + crate::record_raw("fn-match", "inert", &format!("{e} - StartGameInstance patch and Browse hook NOT installed")); + return; + } + }; + let site = (base + l.site) as *mut u8; + match unsafe { patch_cmdline_at(site, &l.original, &l.patched) } { Ok(SiteState::AlreadyPatched) => crate::record_raw("fn-match", "patched", &format!("StartGameInstance cmdline at {:#x} (already in place)", site as usize)), Ok(_) => crate::record_raw("fn-match", "patched", &format!("StartGameInstance cmdline at {:#x}", site as usize)), Err(e) => crate::record_raw("fn-match", "StartGameInstance", &format!("bytes mismatch {e}")), @@ -327,17 +394,119 @@ pub fn apply() { let raw = std::env::var("TOMBOX_FN_MATCH").unwrap_or_else(|_| "".into()); crate::record_raw("fn-match", "mode", &format!("{m:?} (TOMBOX_FN_MATCH={raw}) map={} game={} playlist={} sentinel={sh}:{sp}", map(), gamemode(), playlist())); if m == Mode::Play { - match unsafe { install_browse(base) } { - Ok(n) => crate::record_raw("fn-match", "browse", &format!("hooked UEngine::Browse at {:#x} in {n} vtables", base + BROWSE_RVA)), + match unsafe { install_browse(base, &l) } { + Ok(n) => crate::record_raw("fn-match", "browse", &format!("hooked UEngine::Browse at {:#x} in {n} vtables", base + l.browse)), Err(e) => crate::record_raw("fn-match", "browse", &format!("hook NOT installed: {e}")), } } } +pub const SYMBOLS: [&str; 4] = ["UGameInstance::StartGameInstance", "UEngine::Browse", "FURL::FURL", "FURL::~FURL"]; +pub const UNIQUE_SYMBOLS: [&str; 3] = ["UGameInstance::StartGameInstance", "UEngine::Browse", "FURL::~FURL"]; + +pub fn mov_from_rax(lea: &[u8]) -> Option<[u8; 7]> { + if lea.len() < 7 || lea[0] & 0xFB != 0x48 || lea[1] != 0x8D || lea[2] & 0xC7 != 0x05 { + return None; + } + let dst = ((lea[0] >> 2) & 1) << 3 | (lea[2] >> 3) & 7; + Some([0x48 | (dst >> 3), 0x89, 0xC0 | (dst & 7), 0x90, 0x90, 0x90, 0x90]) +} + +fn unique(hits: Vec, what: &str) -> Result { + match hits.as_slice() { + [one] => Ok(*one), + [] => Err(format!("no {what} found")), + many => Err(format!("{} candidates for {what}", many.len())), + } +} + +pub fn layout_from_image(img: &[u8], base: usize, data: &[(usize, usize)], t: &crate::title_symbols::Table) -> Result { + let s = t.require(&UNIQUE_SYMBOLS)?; + let (start, browse, dtor) = (s[0], s[1], s[2]); + let ctors: Vec = t.all("FURL::FURL").iter().map(|c| c.rva).collect(); + if ctors.is_empty() { + return Err(format!("{} has no FURL::FURL", t.source)); + } + let body = img.get(start.rva..start.rva + start.size).ok_or("StartGameInstance lies outside the image")?; + let at = |i: usize| start.rva + i; + let site = unique( + (5..body.len().saturating_sub(7)).filter(|&i| body[i - 5] == 0xE8 && mov_from_rax(&body[i..i + 7]).is_some()).map(at).collect(), + "StartGameInstance command-line load after a call", + )?; + let sets_travel_type = |i: usize| body[i.saturating_sub(24)..i].windows(2).any(|w| w == [0x41, 0xB9]); + let ctor_call_site = unique( + (0..body.len().saturating_sub(5)) + .filter(|&i| call_target(at(i), &body[i..i + 5]).map(|c| ctors.contains(&c)).unwrap_or(false) && sets_travel_type(i)) + .map(at) + .collect(), + "FURL(Base, URL, TravelType) constructor call in StartGameInstance", + )?; + let ctor = call_target(ctor_call_site, &img[ctor_call_site..ctor_call_site + 5]).unwrap(); + let vcall_site = unique((0..body.len().saturating_sub(7)).filter(|&i| body[i..i + 3] == [0x41, 0xFF, 0x92]).map(at).collect(), "Browse virtual call in StartGameInstance")?; + let original: [u8; 7] = img[site..site + 7].try_into().unwrap(); + let patched = mov_from_rax(&original).unwrap(); + let want = ((base + browse.rva) as u64).to_le_bytes(); + let mut slots = Vec::new(); + for &(rva, len) in data { + let Some(sec) = img.get(rva..rva + len) else { continue }; + for (k, q) in sec.chunks_exact(8).enumerate() { + if q == want { + slots.push(rva + k * 8); + } + } + } + if slots.is_empty() || slots.len() > 16 { + return Err(format!("{} vtable slots hold UEngine::Browse", slots.len())); + } + Ok(Layout { + site, + browse: browse.rva, + slots, + ctor, + ctor_call_site, + dtor: dtor.rva, + vcall_site, + original, + patched, + browse_prologue: Vec::new(), + dtor_prologue: Vec::new(), + vcall: img[vcall_site..vcall_site + 7].to_vec(), + }) +} + +pub const SCN_INITIALIZED_DATA: u32 = 1 << 6; +pub const SCN_DISCARDABLE: u32 = 1 << 25; +pub const SCN_EXECUTE: u32 = 1 << 29; + +pub fn is_data_section(ch: u32) -> bool { + ch & SCN_EXECUTE == 0 && ch & SCN_DISCARDABLE == 0 && ch & SCN_INITIALIZED_DATA != 0 +} + +pub unsafe fn image_sections(base: *const u8) -> (usize, Vec<(usize, usize)>) { + let pe = core::ptr::read_unaligned(base.add(0x3c) as *const u32) as usize; + let n = core::ptr::read_unaligned(base.add(pe + 6) as *const u16) as usize; + let opt = core::ptr::read_unaligned(base.add(pe + 20) as *const u16) as usize; + let size = core::ptr::read_unaligned(base.add(pe + 24 + 56) as *const u32) as usize; + let mut data = Vec::new(); + for i in 0..n { + let s = base.add(pe + 24 + opt + i * 40); + let vsz = core::ptr::read_unaligned(s.add(8) as *const u32) as usize; + let va = core::ptr::read_unaligned(s.add(12) as *const u32) as usize; + let ch = core::ptr::read_unaligned(s.add(36) as *const u32); + if is_data_section(ch) { + data.push((va, vsz & !7)); + } + } + (size, data) +} + #[cfg(test)] mod tests { use super::*; + const ORIGINAL: [u8; 7] = [0x4C, 0x8D, 0x3D, 0x11, 0x22, 0x33, 0x04]; + const PATCHED: [u8; 7] = [0x49, 0x89, 0xC7, 0x90, 0x90, 0x90, 0x90]; + fn site_buf(call: u8, bytes: &[u8; 7]) -> Vec { let mut v = vec![0u8; 32]; v[8] = call; @@ -347,24 +516,51 @@ mod tests { #[test] fn patch_only_on_exact_bytes() { - let mut good = site_buf(0xE8, &START_GAME_INSTANCE_ORIGINAL); - let r = unsafe { patch_cmdline_at(good.as_mut_ptr().add(13)) }; + let mut good = site_buf(0xE8, &ORIGINAL); + let r = unsafe { patch_cmdline_at(good.as_mut_ptr().add(13), &ORIGINAL, &PATCHED) }; assert_eq!(r, Ok(SiteState::Original)); - assert_eq!(&good[13..20], &START_GAME_INSTANCE_PATCHED); - let again = unsafe { patch_cmdline_at(good.as_mut_ptr().add(13)) }; + assert_eq!(&good[13..20], &PATCHED); + let again = unsafe { patch_cmdline_at(good.as_mut_ptr().add(13), &ORIGINAL, &PATCHED) }; assert_eq!(again, Ok(SiteState::AlreadyPatched)); - assert_eq!(&good[13..20], &START_GAME_INSTANCE_PATCHED); + assert_eq!(&good[13..20], &PATCHED); let wrong = [0x4C, 0x8D, 0x3D, 0x00, 0x00, 0x00, 0x00]; let mut bad = site_buf(0xE8, &wrong); - let r = unsafe { patch_cmdline_at(bad.as_mut_ptr().add(13)) }; + let r = unsafe { patch_cmdline_at(bad.as_mut_ptr().add(13), &ORIGINAL, &PATCHED) }; assert!(r.is_err()); assert_eq!(&bad[13..20], &wrong); - let mut nocall = site_buf(0x90, &START_GAME_INSTANCE_ORIGINAL); - let r = unsafe { patch_cmdline_at(nocall.as_mut_ptr().add(13)) }; + let mut nocall = site_buf(0x90, &ORIGINAL); + let r = unsafe { patch_cmdline_at(nocall.as_mut_ptr().add(13), &ORIGINAL, &PATCHED) }; assert!(r.is_err()); - assert_eq!(&nocall[13..20], &START_GAME_INSTANCE_ORIGINAL); + assert_eq!(&nocall[13..20], &ORIGINAL); + } + + fn fixture() -> String { + let vals: Vec = VALUE_KEYS.iter().enumerate().map(|(i, k)| format!("\"{k}\":{}", 0x1000 + i * 0x10)).collect(); + let bytes = ["4C8D3D11223304", "4989C790909090", "4055", "4053", "41FF92"]; + let b: Vec = BYTE_KEYS.iter().zip(bytes).map(|(k, v)| format!("\"{k}\":\"{v}\"")).collect(); + format!("{{\"exe\":\"{TITLE_EXE}\",\"values\":{{{}}},\"bytes\":{{{}}}}}", vals.join(","), b.join(",")) + } + + #[test] + fn the_layout_comes_from_the_offsets_file() { + let o = crate::title_offsets::parse(&fixture(), "t").unwrap(); + let l = layout(&o).unwrap(); + assert_eq!((l.site, l.slots.clone(), l.vcall_site), (0x1000, vec![0x1020, 0x1030, 0x1040], 0x1080)); + assert_eq!((l.original, l.patched), (ORIGINAL, PATCHED)); + assert_eq!(l.vcall, vec![0x41, 0xFF, 0x92]); + let short = fixture().replace("4989C790909090", "4989C7"); + assert!(layout(&crate::title_offsets::parse(&short, "t").unwrap()).unwrap_err().contains("7 bytes")); + let missing = fixture().replace("fn.furl_dtor\"", "fn.other\""); + assert!(layout(&crate::title_offsets::parse(&missing, "t").unwrap()).unwrap_err().contains("fn.furl_dtor")); + } + + #[test] + fn call_targets_decode_rel32() { + assert_eq!(call_target(0x1000, &[0xE8, 0x10, 0x00, 0x00, 0x00]), Some(0x1015)); + assert_eq!(call_target(0x1000, &[0xE8, 0xFB, 0xFF, 0xFF, 0xFF]), Some(0x1000)); + assert_eq!(call_target(0x1000, &[0xE9, 0, 0, 0, 0]), None); } fn url(host: &str, port: i32, map: &str) -> UrlView { @@ -406,7 +602,9 @@ mod tests { struct Pe { f: std::fs::File, base: u64, + stamp: u32, secs: Vec<(u32, u32, u32)>, + data: Vec<(usize, usize)>, } impl Pe { @@ -416,20 +614,26 @@ mod tests { let mut h = vec![0u8; 0x1000]; f.read_exact(&mut h).ok()?; let pe = u32::from_le_bytes(h[0x3c..0x40].try_into().ok()?) as usize; + let stamp = u32::from_le_bytes(h[pe + 8..pe + 12].try_into().ok()?); let nsec = u16::from_le_bytes(h[pe + 6..pe + 8].try_into().ok()?) as usize; let opt = u16::from_le_bytes(h[pe + 20..pe + 22].try_into().ok()?) as usize; let base = u64::from_le_bytes(h[pe + 24 + 24..pe + 24 + 32].try_into().ok()?); let st = pe + 24 + opt; let mut secs = Vec::new(); + let mut data = Vec::new(); for i in 0..nsec { let s = &h[st + i * 40..st + i * 40 + 40]; let vsz = u32::from_le_bytes(s[8..12].try_into().ok()?); let va = u32::from_le_bytes(s[12..16].try_into().ok()?); let raw = u32::from_le_bytes(s[20..24].try_into().ok()?); + let ch = u32::from_le_bytes(s[36..40].try_into().ok()?); + if is_data_section(ch) { + data.push((va as usize, vsz as usize & !7)); + } secs.push((va, vsz, raw)); } f.seek(SeekFrom::Start(0)).ok()?; - Some(Pe { f, base, secs }) + Some(Pe { f, base, stamp, secs, data }) } fn read(&mut self, rva: usize, n: usize) -> Vec { use std::io::{Read, Seek, SeekFrom}; @@ -442,30 +646,35 @@ mod tests { } #[test] - fn dump_constants_match() { - let path = std::env::var("TOMBOX_FN_DUMP_EXE").unwrap_or_else(|_| r"D:\xbox-pc-port\games\Fortnite\extracted\Mount\FortniteGame\Binaries\XSX\FortniteClient-XSX-Shipping.exe".into()); + fn local_offsets_match_the_dump() { + let Ok(o) = crate::title_offsets::load_for(TITLE_EXE) else { + eprintln!("no local offsets for {TITLE_EXE}; dump check not run"); + return; + }; + let Ok(path) = std::env::var("TOMBOX_FN_DUMP_EXE") else { + eprintln!("TOMBOX_FN_DUMP_EXE unset; dump check not run"); + return; + }; let Some(mut pe) = Pe::open(&path) else { - eprintln!("dump exe not present at {path}; constant check not run"); + eprintln!("dump exe not present at {path}; dump check not run"); return; }; - let call = pe.read(START_GAME_INSTANCE_SITE - 5, 12); - assert_eq!(classify_site(call[0], &call[5..12].try_into().unwrap()), SiteState::Original); - let rel = i32::from_le_bytes(call[1..5].try_into().unwrap()) as isize; - let getter = (START_GAME_INSTANCE_SITE as isize + rel) as usize; + let l = layout(&o).unwrap(); + assert!(o.matches_image(pe.stamp), "offsets file is for another build"); + let call = pe.read(l.site - 5, 12); + assert_eq!(classify_site(call[0], &call[5..12].try_into().unwrap(), &l.original, &l.patched), SiteState::Original); + let getter = call_target(l.site - 5, &call[..5]).unwrap(); let g = pe.read(getter, 0x1d); assert_eq!(&g[0x11..0x14], &[0x48, 0x8D, 0x05]); assert_eq!(g[0x1c], 0xC3); - assert_eq!(pe.read(BROWSE_RVA, 13), BROWSE_PROLOGUE.to_vec()); - assert_eq!(pe.read(FURL_DTOR_RVA, 13), FURL_DTOR_PROLOGUE.to_vec()); - let c = pe.read(FURL_CTOR_PROLOGUE_RVA_CHECK, 5); - assert_eq!(c[0], 0xE8); - let rel = i32::from_le_bytes(c[1..5].try_into().unwrap()) as isize; - assert_eq!((FURL_CTOR_PROLOGUE_RVA_CHECK as isize + 5 + rel) as usize, FURL_CTOR_RVA); - let vcall = pe.read(0xB46923, 7); - assert_eq!(vcall, vec![0x41, 0xFF, 0x92, 0x40, 0x04, 0x00, 0x00]); - for slot in BROWSE_VTABLE_SLOTS { + assert_eq!(pe.read(l.browse, l.browse_prologue.len()), l.browse_prologue); + assert_eq!(pe.read(l.dtor, l.dtor_prologue.len()), l.dtor_prologue); + let c = pe.read(l.ctor_call_site, 5); + assert_eq!(call_target(l.ctor_call_site, &c), Some(l.ctor)); + assert_eq!(pe.read(l.vcall_site, l.vcall.len()), l.vcall); + for &slot in &l.slots { let v = u64::from_le_bytes(pe.read(slot, 8).try_into().unwrap()); - assert_eq!(v, pe.base + BROWSE_RVA as u64, "slot {slot:#x}"); + assert_eq!(v, pe.base + l.browse as u64, "slot {slot:#x}"); } } @@ -474,4 +683,86 @@ mod tests { let u = url("127.0.0.1", 7777, "/Game/Maps/Frontend"); assert_eq!(u.describe(), "127.0.0.1:7777/Game/Maps/Frontend?Name=XboxEmulator"); } + + #[test] + fn mov_from_rax_follows_the_lea_destination() { + assert_eq!(mov_from_rax(&[0x4C, 0x8D, 0x3D, 1, 2, 3, 4]), Some([0x49, 0x89, 0xC7, 0x90, 0x90, 0x90, 0x90])); + assert_eq!(mov_from_rax(&[0x48, 0x8D, 0x0D, 1, 2, 3, 4]), Some([0x48, 0x89, 0xC1, 0x90, 0x90, 0x90, 0x90])); + assert_eq!(mov_from_rax(&[0x4C, 0x8D, 0x7D, 1, 2, 3, 4]), None); + assert_eq!(mov_from_rax(&[0x4C, 0x8B, 0x3D, 1, 2, 3, 4]), None); + } + + fn synthetic_image(base: usize) -> (Vec, crate::title_symbols::Table) { + let mut img = vec![0u8; 0x4000]; + img[0x110] = 0xE8; + img[0x115..0x11c].copy_from_slice(&[0x4C, 0x8D, 0x3D, 0x10, 0x20, 0x30, 0x00]); + img[0x124..0x12a].copy_from_slice(&[0x41, 0xB9, 0x01, 0x00, 0x00, 0x00]); + img[0x130] = 0xE8; + img[0x131..0x135].copy_from_slice(&((0x800i32 - 0x135) as i32).to_le_bytes()); + img[0x170] = 0xE8; + img[0x171..0x175].copy_from_slice(&((0xc00i32 - 0x175) as i32).to_le_bytes()); + img[0x150..0x157].copy_from_slice(&[0x41, 0xFF, 0x92, 0x40, 0x04, 0x00, 0x00]); + img[0x2040..0x2048].copy_from_slice(&((base + 0x900) as u64).to_le_bytes()); + img[0x2088..0x2090].copy_from_slice(&((base + 0x900) as u64).to_le_bytes()); + let f = crate::title_symbols::build_for_test(TITLE_EXE, &[("UGameInstance::StartGameInstance", 0x100, 0x80), ("UEngine::Browse", 0x900, 0x40), ("FURL::FURL", 0x800, 0x40), ("FURL::FURL", 0xc00, 0x40), ("FURL::~FURL", 0xa00, 0x20)]); + let t = crate::title_symbols::parse_bytes(&f, &SYMBOLS, "t").unwrap(); + (img, t) + } + + #[test] + fn symbols_and_the_image_give_the_whole_layout() { + let base = 5usize << 30; + let (img, t) = synthetic_image(base); + let l = layout_from_image(&img, base, &[(0x2000, 0x100)], &t).unwrap(); + assert_eq!((l.site, l.ctor_call_site, l.vcall_site, l.browse, l.ctor, l.dtor), (0x115, 0x130, 0x150, 0x900, 0x800, 0xa00)); + assert_eq!(l.slots, vec![0x2040, 0x2088]); + assert_eq!(l.original, [0x4C, 0x8D, 0x3D, 0x10, 0x20, 0x30, 0x00]); + assert_eq!(l.patched, [0x49, 0x89, 0xC7, 0x90, 0x90, 0x90, 0x90]); + assert!(layout_from_image(&img, base, &[(0x3000, 0x100)], &t).unwrap_err().contains("0 vtable slots")); + let mut two = img.clone(); + two[0x160] = 0xE8; + two[0x165..0x16c].copy_from_slice(&[0x48, 0x8D, 0x05, 0, 0, 0, 0]); + assert!(layout_from_image(&two, base, &[(0x2000, 0x100)], &t).unwrap_err().contains("2 candidates")); + let missing = crate::title_symbols::parse_bytes(&crate::title_symbols::build_for_test(TITLE_EXE, &[("UEngine::Browse", 0x900, 0x40)]), &SYMBOLS, "t").unwrap(); + assert!(layout_from_image(&img, base, &[(0x2000, 0x100)], &missing).unwrap_err().contains("StartGameInstance")); + } + + #[test] + fn dump_symbols_reproduce_the_offsets_file() { + let Ok(path) = std::env::var("TOMBOX_FN_DUMP_EXE") else { + eprintln!("TOMBOX_FN_DUMP_EXE unset; symbol check not run"); + return; + }; + let Some(mut pe) = Pe::open(&path) else { + eprintln!("dump exe not present at {path}; symbol check not run"); + return; + }; + let t = match crate::title_symbols::load(std::path::Path::new(&path), &SYMBOLS) { + Ok(t) => t, + Err(e) => { + eprintln!("{e}; symbol check not run"); + return; + } + }; + let end = pe.secs.iter().map(|(va, vsz, _)| (*va + *vsz) as usize).max().unwrap(); + let mut img = vec![0u8; end]; + let secs = pe.secs.clone(); + for (va, vsz, _) in &secs { + let b = pe.read(*va as usize, *vsz as usize); + img[*va as usize..*va as usize + b.len()].copy_from_slice(&b); + } + let data: Vec<(usize, usize)> = pe.data.clone(); + let l = layout_from_image(&img, pe.base as usize, &data, &t).unwrap(); + eprintln!("symbol layout: site {:#x} slots {}", l.site, l.slots.len()); + if let Ok(o) = crate::title_offsets::load_for(TITLE_EXE) { + let j = layout(&o).unwrap(); + assert_eq!((l.site, l.browse, l.ctor, l.ctor_call_site, l.dtor, l.vcall_site), (j.site, j.browse, j.ctor, j.ctor_call_site, j.dtor, j.vcall_site)); + assert_eq!((l.original, l.patched, &l.vcall), (j.original, j.patched, &j.vcall)); + let mut a = l.slots.clone(); + let mut b = j.slots.clone(); + a.sort(); + b.sort(); + assert_eq!(a, b); + } + } } diff --git a/crates/compat/compat-common/src/os_host/mod.rs b/crates/compat/compat-common/src/os_host/mod.rs index cede6825..50902c26 100644 --- a/crates/compat/compat-common/src/os_host/mod.rs +++ b/crates/compat/compat-common/src/os_host/mod.rs @@ -1,6 +1,7 @@ pub mod affinity; pub mod coverage; pub mod dlldir; +pub mod foreign; pub mod fortnite_match; pub mod k32legacy; pub mod patch; @@ -8,6 +9,8 @@ pub mod plm; pub mod quiesce; pub mod routes; pub mod routes_rt; +pub mod webm_probe; +pub mod tm_race_probe; use core::ffi::c_void; use patch::Hook; @@ -117,7 +120,7 @@ pub unsafe extern "system" fn dll_loaded(reason: u32, data: *const u8, _ctx: *mu return; } let path = String::from_utf16_lossy(core::slice::from_raw_parts(buf, len)); - if !patch::is_title_module(&path, base as usize) { + if !patch::is_title_module(&path, base as usize) || foreign::is_host_injected(&path) { return; } let mut hits = Vec::new(); @@ -135,6 +138,7 @@ pub fn load_watch_active() -> bool { } unsafe fn watch_loads() -> bool { + foreign::prime(); let p = resolve("ntdll.dll", "LdrRegisterDllNotification"); if p.is_null() { return false; @@ -173,6 +177,8 @@ unsafe fn install() { k32legacy::publish(); let n = sweep_now(); fortnite_match::apply(); + webm_probe::start(); + tm_race_probe::start(); let watching = watch_loads(); let n = n + if watching { unsafe { routes::sweep(hook_table(), &mut Vec::new()) } } else { 0 }; crate::record_raw("os_host", "install", &format!("{n} import slots patched; late-load watch {}; {}", if watching { "on" } else { "UNAVAILABLE" }, coverage::summary())); diff --git a/crates/compat/compat-common/src/os_host/patch.rs b/crates/compat/compat-common/src/os_host/patch.rs index 8f52577d..f2394f7c 100644 --- a/crates/compat/compat-common/src/os_host/patch.rs +++ b/crates/compat/compat-common/src/os_host/patch.rs @@ -9,6 +9,7 @@ extern "system" { fn GetModuleFileNameW(m: *mut c_void, buf: *mut u16, n: u32) -> u32; fn GetSystemWindowsDirectoryW(buf: *mut u16, n: u32) -> u32; fn GetModuleHandleExW(flags: u32, addr: *const u16, out: *mut *mut c_void) -> i32; + fn FreeLibrary(m: *mut c_void) -> i32; } #[derive(Clone, Copy)] @@ -187,20 +188,97 @@ pub unsafe fn loaded_modules() -> Vec<*mut c_void> { v } -pub unsafe fn sweep(hooks: &[Hook], report: &mut Vec<(String, Vec)>) -> usize { +pub unsafe fn pin_module(m: *mut c_void) -> Option<*mut c_void> { + let mut h = core::ptr::null_mut(); + if m.is_null() || GetModuleHandleExW(0x4, m as *const u16, &mut h) == 0 || h.is_null() { + return None; + } + if h != m { + FreeLibrary(h); + return None; + } + Some(h) +} + +pub unsafe fn unpin_module(m: *mut c_void) { + FreeLibrary(m); +} + +pub unsafe fn sweep_modules(mods: &[*mut c_void], hooks: &[Hook], report: &mut Vec<(String, Vec)>) -> usize { let mut total = 0; - for m in loaded_modules() { - let path = module_path(m); - if !is_title_module(&path, m as usize) { - continue; - } - let mut hits = Vec::new(); - let n = patch_image(m as *mut u8, hooks, &mut hits); - if n > 0 { - total += n; - let name = path.rsplit('\\').next().unwrap_or(&path).to_string(); - report.push((name, hits)); + for &m in mods { + let Some(pinned) = pin_module(m) else { continue }; + let path = module_path(pinned); + if !path.is_empty() && is_title_module(&path, pinned as usize) && !super::foreign::is_host_injected(&path) { + let mut hits = Vec::new(); + let n = patch_image(pinned as *mut u8, hooks, &mut hits); + if n > 0 { + total += n; + let name = path.rsplit('\\').next().unwrap_or(&path).to_string(); + report.push((name, hits)); + } } + FreeLibrary(pinned); } total } + +pub unsafe fn sweep(hooks: &[Hook], report: &mut Vec<(String, Vec)>) -> usize { + sweep_modules(&loaded_modules(), hooks, report) +} + +#[cfg(test)] +mod sweep_race_tests { + use super::*; + + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(name: *const u16) -> *mut c_void; + fn GetModuleHandleW(name: *const u16) -> *mut c_void; + } + + fn w(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() + } + + static MSIMG: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn sweep_skips_a_module_unloaded_after_enumeration() { + let _g = MSIMG.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let name = w("msimg32.dll"); + if !GetModuleHandleW(name.as_ptr()).is_null() { + return; + } + let base = LoadLibraryW(name.as_ptr()); + assert!(!base.is_null()); + let listed = vec![base]; + while !GetModuleHandleW(name.as_ptr()).is_null() { + FreeLibrary(base); + } + assert!(pin_module(base).is_none(), "an unloaded base cannot be pinned"); + let mut report = Vec::new(); + assert_eq!(sweep_modules(&listed, &[], &mut report), 0, "the stale base is skipped, never read"); + assert!(report.is_empty()); + } + } + + #[test] + fn pinning_a_live_module_keeps_it_loaded_and_releases_the_reference() { + let _g = MSIMG.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let name = w("msimg32.dll"); + if !GetModuleHandleW(name.as_ptr()).is_null() { + return; + } + let base = LoadLibraryW(name.as_ptr()); + let pinned = pin_module(base).expect("a loaded module pins"); + assert_eq!(pinned, base); + FreeLibrary(base); + assert!(!GetModuleHandleW(name.as_ptr()).is_null(), "the pin holds the module while a sweep patches it"); + unpin_module(pinned); + assert!(GetModuleHandleW(name.as_ptr()).is_null(), "unpin drops the only reference"); + } + } +} diff --git a/crates/compat/compat-common/src/os_host/plm.rs b/crates/compat/compat-common/src/os_host/plm.rs index 8c0b9389..3d813973 100644 --- a/crates/compat/compat-common/src/os_host/plm.rs +++ b/crates/compat/compat-common/src/os_host/plm.rs @@ -275,6 +275,12 @@ fn start_watcher() { constrained = v; } signal_local(k, v); + } else if let Some(signed_in) = crate::gdk::user::parse_user_command(line) { + if signed_in { + crate::gdk::user::sign_in(); + } else { + crate::gdk::user::sign_out(); + } } } } diff --git a/crates/compat/compat-common/src/os_host/routes.rs b/crates/compat/compat-common/src/os_host/routes.rs index 3f7a4904..ae895016 100644 --- a/crates/compat/compat-common/src/os_host/routes.rs +++ b/crates/compat/compat-common/src/os_host/routes.rs @@ -446,16 +446,17 @@ pub unsafe fn sweep(skip: &[Hook], report: &mut Vec<(String, Vec)>) -> u return 0; } for m in patch::loaded_modules() { - let path = patch::module_path(m); - if !patch::is_title_module(&path, m as usize) || skip_module(&path, m as usize) { - continue; - } - let mut hits = Vec::new(); - let n = patch_image(m as *mut u8, skip, &mut hits); - if n > 0 { - total += n; - report.push((path.rsplit('\\').next().unwrap_or(&path).to_string(), hits)); + let Some(pinned) = patch::pin_module(m) else { continue }; + let path = patch::module_path(pinned); + if !path.is_empty() && patch::is_title_module(&path, pinned as usize) && !skip_module(&path, pinned as usize) && !super::foreign::is_host_injected(&path) { + let mut hits = Vec::new(); + let n = patch_image(pinned as *mut u8, skip, &mut hits); + if n > 0 { + total += n; + report.push((path.rsplit('\\').next().unwrap_or(&path).to_string(), hits)); + } } + patch::unpin_module(pinned); } total } diff --git a/crates/compat/compat-common/src/os_host/tm_race_probe.rs b/crates/compat/compat-common/src/os_host/tm_race_probe.rs new file mode 100644 index 00000000..b38a71ed --- /dev/null +++ b/crates/compat/compat-common/src/os_host/tm_race_probe.rs @@ -0,0 +1,320 @@ +use core::ffi::c_void; + +#[link(name = "kernel32")] +extern "system" { + fn GetModuleHandleW(n: *const u16) -> *mut c_void; + fn ReadProcessMemory(h: *mut c_void, addr: *const c_void, buf: *mut c_void, n: usize, read: *mut usize) -> i32; + fn GetCurrentProcess() -> *mut c_void; + fn VirtualQuery(addr: *const c_void, mbi: *mut Mbi, len: usize) -> usize; +} + +#[repr(C)] +#[derive(Default, Clone, Copy)] +struct Mbi { + base: usize, + alloc_base: usize, + alloc_protect: u32, + partition: u16, + region_size: usize, + state: u32, + protect: u32, + kind: u32, +} + +pub const VAR: &str = "TOMBOX_TM_RACE_PROBE"; +pub const KEYS: [&str; 18] = ["race.script_player_vtable", "race.game_time_ms", "race.sp_player", "race.player_race_state", "race.rs_cur", "race.rs_running", "race.player_race", "race.player_lap_waypoints", "race.player_lap", "race.race_start_ms", "race.waypoint_count", "race.player_entity", "race.player_flags", "race.offzone_bit", "race.player_position", "race.player_vehicle_state", "race.vs_surface", "race.surface_water"]; + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Layout { + pub vtable: usize, + pub game_time: usize, + pub sp_player: usize, + pub race_state: usize, + pub rs_cur: usize, + pub rs_running: usize, + pub race: usize, + pub lap_waypoints: usize, + pub lap: usize, + pub race_start: usize, + pub waypoint_count: usize, + pub entity: usize, + pub flags: usize, + pub offzone_bit: usize, + pub position: usize, + pub vehicle_state: usize, + pub surface: usize, + pub water: usize, +} + +pub fn layout(o: &crate::title_offsets::Offsets) -> Result { + let v = o.require(&KEYS)?; + Ok(Layout { vtable: v[0], game_time: v[1], sp_player: v[2], race_state: v[3], rs_cur: v[4], rs_running: v[5], race: v[6], lap_waypoints: v[7], lap: v[8], race_start: v[9], waypoint_count: v[10], entity: v[11], flags: v[12], offzone_bit: v[13], position: v[14], vehicle_state: v[15], surface: v[16], water: v[17] }) +} + +const MAX_LINES: u32 = 4000; +const RUN_MS: u64 = 600_000; +const RESCAN_MS: u64 = 5000; +const CHUNK: usize = 1 << 20; +const MAX_CANDIDATES: usize = 16; + +fn read_bytes(addr: usize, out: &mut [u8]) -> bool { + let mut got = 0usize; + unsafe { ReadProcessMemory(GetCurrentProcess(), addr as *const c_void, out.as_mut_ptr() as *mut c_void, out.len(), &mut got) != 0 && got == out.len() } +} + +fn rd(addr: usize) -> Option<[u8; N]> { + let mut b = [0u8; N]; + read_bytes(addr, &mut b).then_some(b) +} + +fn u32_at(a: usize) -> Option { + rd::<4>(a).map(u32::from_le_bytes) +} + +fn i32_at(a: usize) -> Option { + rd::<4>(a).map(i32::from_le_bytes) +} + +fn ptr_at(a: usize) -> Option { + rd::<8>(a).map(|b| u64::from_le_bytes(b) as usize).filter(|&p| p >= 0x10000 && p < 0x7fff_ffff_0000) +} + +fn f32_at(a: usize) -> Option { + rd::<4>(a).map(f32::from_le_bytes) +} + +pub fn find_script_players(vtable: usize, cap: usize) -> Vec { + let mut out = Vec::new(); + let mut buf = vec![0u8; CHUNK]; + let mut p = 0x1_0000usize; + let want = (vtable as u64).to_le_bytes(); + while p < 0x7fff_ffff_0000 && out.len() < cap { + let mut m = Mbi::default(); + if unsafe { VirtualQuery(p as *const c_void, &mut m, core::mem::size_of::()) } == 0 { + break; + } + let next = m.base + m.region_size; + if m.state == 0x1000 && m.kind == 0x2_0000 && m.protect & 0x04 != 0 && m.protect & 0x100 == 0 { + let mut a = m.base; + while a < next && out.len() < cap { + let n = CHUNK.min(next - a); + if read_bytes(a, &mut buf[..n]) { + for (i, c) in buf[..n].chunks_exact(8).enumerate() { + if c == want { + out.push(a + i * 8); + if out.len() >= cap { + break; + } + } + } + } + a += n; + } + } + if next <= p { + break; + } + p = next; + } + out +} + +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Sample { + pub racing: bool, + pub race_ms: Option, + pub checkpoints: Option, + pub lap_checkpoints: Option, + pub lap: Option, + pub pos: Option<[f32; 3]>, + pub surface: Option, + pub offzone: Option, +} + +pub fn sample(l: &Layout, base: usize, player: usize) -> Sample { + let mut s = Sample::default(); + let rs = player + l.race_state; + let running = i32_at(rs + l.rs_running); + let cur = i32_at(rs + l.rs_cur); + s.racing = matches!((running, cur), (Some(r), Some(c)) if r != -1 && r == c); + let race = ptr_at(player + l.race); + if let (true, Some(r), Some(now)) = (s.racing, race, u32_at(base.wrapping_add(l.game_time))) { + s.race_ms = u32_at(r + l.race_start).map(|st| now.wrapping_sub(st) as i32 as i64); + } + s.checkpoints = race.and_then(|r| u32_at(r + l.waypoint_count)); + s.lap_checkpoints = ptr_at(player + l.lap_waypoints).and_then(|w| u32_at(w + l.waypoint_count)); + s.lap = u32_at(player + l.lap); + if i32_at(player + l.entity).map(|e| e != -1).unwrap_or(false) { + let x = f32_at(player + l.position); + let y = f32_at(player + l.position + 4); + let z = f32_at(player + l.position + 8); + if let (Some(x), Some(y), Some(z)) = (x, y, z) { + if x.is_finite() && y.is_finite() && z.is_finite() { + s.pos = Some([x, y, z]); + } + } + } + s.surface = ptr_at(player + l.vehicle_state).and_then(|v| u32_at(v + l.surface)); + s.offzone = u32_at(player + l.flags).map(|f| f >> l.offzone_bit & 1 != 0); + s +} + +pub fn line(l: &Layout, t_ms: u64, sp: usize, player: usize, s: &Sample) -> String { + let opt = |v: Option| v.unwrap_or_else(|| "?".into()); + format!( + "t={t_ms}ms sp={sp:#x} player={player:#x} racing={} race_ms={} cp={} lap_cp={} lap={} pos={} surface={} water={} offzone={}", + s.racing as u8, + opt(s.race_ms.map(|v| v.to_string())), + opt(s.checkpoints.map(|v| v.to_string())), + opt(s.lap_checkpoints.map(|v| v.to_string())), + opt(s.lap.map(|v| v.to_string())), + opt(s.pos.map(|p| format!("{:.1},{:.1},{:.1}", p[0], p[1], p[2]))), + opt(s.surface.map(|v| v.to_string())), + opt(s.surface.map(|v| ((v as usize == l.water) as u8).to_string())), + opt(s.offzone.map(|v| (v as u8).to_string())), + ) +} + +fn pick(l: &Layout, candidates: &[usize]) -> Option<(usize, usize)> { + let mut first = None; + for &sp in candidates { + let Some(p) = ptr_at(sp + l.sp_player) else { continue }; + if ptr_at(p + l.race).is_some() { + return Some((sp, p)); + } + first.get_or_insert((sp, p)); + } + first +} + +pub fn enabled() -> bool { + std::env::var(VAR).ok().map(|v| v.trim() != "0" && !v.trim().is_empty()).unwrap_or(false) +} + +pub fn start() { + if !enabled() { + return; + } + let base = unsafe { GetModuleHandleW(core::ptr::null()) } as usize; + if base == 0 { + return; + } + let Some(o) = crate::title_offsets::for_this_title() else { + crate::record_raw("tm_race", "inert", &crate::title_offsets::status_for_this_title()); + return; + }; + let l = match layout(o) { + Ok(l) => l, + Err(e) => { + crate::record_raw("tm_race", "inert", &e); + return; + } + }; + let stamp = unsafe { crate::title_offsets::image_timestamp(base as *const u8) }; + if !o.matches_image(stamp) { + crate::record_raw("tm_race", "inert", &format!("{} was made for another build (image timestamp {stamp:#x})", o.source)); + return; + } + let source = o.source.clone(); + let period = std::env::var(VAR).ok().and_then(|v| v.trim().parse::().ok()).filter(|v| *v >= 50).unwrap_or(250); + let _ = std::thread::Builder::new().name("tombox-tm-race-probe".into()).spawn(move || { + crate::record_raw("tm_race", "start", &format!("base={base:#x} period={period}ms offsets={source}")); + let t0 = std::time::Instant::now(); + let mut cur: Option<(usize, usize)> = None; + let mut last_scan: Option = None; + let mut lines = 0u32; + let mut last_found = 0usize; + while (t0.elapsed().as_millis() as u64) < RUN_MS && lines < MAX_LINES { + std::thread::sleep(std::time::Duration::from_millis(period)); + let valid = cur.map(|(sp, p)| ptr_at(sp).map(|v| v == base + l.vtable).unwrap_or(false) && ptr_at(sp + l.sp_player) == Some(p)).unwrap_or(false); + if !valid { + cur = None; + if last_scan.map(|t| t.elapsed().as_millis() as u64 >= RESCAN_MS).unwrap_or(true) { + let st = std::time::Instant::now(); + let found = find_script_players(base + l.vtable, MAX_CANDIDATES); + last_scan = Some(std::time::Instant::now()); + cur = pick(&l, &found); + if found.len() != last_found || cur.is_some() { + crate::record_raw("tm_race", "scan", &format!("t={}ms candidates={} picked={} scan={}ms", t0.elapsed().as_millis(), found.len(), cur.map(|(sp, p)| format!("{sp:#x}/{p:#x}")).unwrap_or_else(|| "none".into()), st.elapsed().as_millis())); + lines += 1; + last_found = found.len(); + } + } + } + if let Some((sp, p)) = cur { + let s = sample(&l, base, p); + crate::record_raw("tm_race", "s", &line(&l, t0.elapsed().as_millis() as u64, sp, p, &s)); + lines += 1; + } + } + crate::record_raw("tm_race", "stop", &format!("lines={lines}")); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn synthetic() -> Layout { + Layout { vtable: 0, game_time: 0x40, sp_player: 0x8, race_state: 0x100, rs_cur: 0x4, rs_running: 0x8, race: 0x200, lap_waypoints: 0x208, lap: 0x210, race_start: 0x8, waypoint_count: 0x18, entity: 0x300, flags: 0x304, offzone_bit: 2, position: 0x310, vehicle_state: 0x320, surface: 0x10, water: 6 } + } + + #[test] + fn the_layout_comes_from_the_offsets_file() { + let vals: Vec = KEYS.iter().enumerate().map(|(i, k)| format!("\"{k}\":{}", i + 1)).collect(); + let o = crate::title_offsets::parse(&format!("{{\"exe\":\"T.exe\",\"values\":{{{}}}}}", vals.join(",")), "t").unwrap(); + let l = layout(&o).unwrap(); + assert_eq!((l.vtable, l.game_time, l.water), (1, 2, KEYS.len())); + let partial = crate::title_offsets::parse(r#"{"exe":"T.exe","values":{"race.script_player_vtable":1}}"#, "t").unwrap(); + assert!(layout(&partial).unwrap_err().contains("race.surface_water")); + } + + #[test] + fn sample_decodes_a_synthetic_player() { + let l = synthetic(); + let mut game = vec![0u8; 0x10]; + let mut player = vec![0u8; 0x400]; + let mut race = vec![0u8; 0x20]; + let mut lapw = vec![0u8; 0x20]; + let mut veh = vec![0u8; 0x20]; + let fake_base = (game.as_mut_ptr() as usize).wrapping_sub(l.game_time); + game[0..4].copy_from_slice(&5000u32.to_le_bytes()); + race[8..12].copy_from_slice(&1500u32.to_le_bytes()); + race[0x18..0x1c].copy_from_slice(&3u32.to_le_bytes()); + lapw[0x18..0x1c].copy_from_slice(&2u32.to_le_bytes()); + veh[0x10..0x14].copy_from_slice(&6u32.to_le_bytes()); + let put = |b: &mut Vec, off: usize, v: &[u8]| b[off..off + v.len()].copy_from_slice(v); + put(&mut player, l.race_state + l.rs_cur, &7i32.to_le_bytes()); + put(&mut player, l.race_state + l.rs_running, &7i32.to_le_bytes()); + put(&mut player, l.race, &(race.as_ptr() as u64).to_le_bytes()); + put(&mut player, l.lap_waypoints, &(lapw.as_ptr() as u64).to_le_bytes()); + put(&mut player, l.lap, &1u32.to_le_bytes()); + put(&mut player, l.entity, &0i32.to_le_bytes()); + put(&mut player, l.flags, &4u32.to_le_bytes()); + put(&mut player, l.position, &1.5f32.to_le_bytes()); + put(&mut player, l.position + 4, &(-2.0f32).to_le_bytes()); + put(&mut player, l.position + 8, &300.25f32.to_le_bytes()); + put(&mut player, l.vehicle_state, &(veh.as_ptr() as u64).to_le_bytes()); + let s = sample(&l, fake_base, player.as_ptr() as usize); + assert_eq!(s, Sample { racing: true, race_ms: Some(3500), checkpoints: Some(3), lap_checkpoints: Some(2), lap: Some(1), pos: Some([1.5, -2.0, 300.25]), surface: Some(6), offzone: Some(true) }); + let t = line(&l, 10, 1, 2, &s); + assert!(t.contains("race_ms=3500 cp=3 lap_cp=2 lap=1 pos=1.5,-2.0,300.2") && t.contains("water=1 offzone=1"), "{t}"); + put(&mut player, l.race_state + l.rs_running, &(-1i32).to_le_bytes()); + put(&mut player, l.entity, &(-1i32).to_le_bytes()); + let s = sample(&l, fake_base, player.as_ptr() as usize); + assert!(!s.racing && s.race_ms.is_none() && s.pos.is_none()); + drop((game, race, lapw, veh)); + } + + #[test] + fn the_scan_finds_objects_by_their_vtable() { + let tag = 0x1357_9bdf_2468_ace0usize; + let mut v = vec![0usize; 4096]; + v[100] = tag; + v[3000] = tag; + let got = find_script_players(tag, 1 << 16); + let a = v.as_ptr() as usize; + assert!(got.contains(&(a + 800)) && got.contains(&(a + 24000)), "{got:x?}"); + drop(v); + } +} diff --git a/crates/compat/compat-common/src/os_host/webm_probe.rs b/crates/compat/compat-common/src/os_host/webm_probe.rs new file mode 100644 index 00000000..9a5d175c --- /dev/null +++ b/crates/compat/compat-common/src/os_host/webm_probe.rs @@ -0,0 +1,198 @@ +use core::ffi::c_void; + +#[link(name = "kernel32")] +extern "system" { + fn GetModuleHandleW(n: *const u16) -> *mut c_void; + fn ReadProcessMemory(h: *mut c_void, addr: *const c_void, buf: *mut c_void, n: usize, read: *mut usize) -> i32; + fn GetCurrentProcess() -> *mut c_void; + fn GetThreadId(h: *mut c_void) -> u32; + fn GetExitCodeThread(h: *mut c_void, code: *mut u32) -> i32; + fn QueryThreadCycleTime(h: *mut c_void, cycles: *mut u64) -> i32; + fn GetThreadDescription(h: *mut c_void, desc: *mut *mut u16) -> i32; + fn LocalFree(p: *mut c_void) -> *mut c_void; + fn GetLastError() -> u32; +} + +pub const VAR: &str = "TOMBOX_WEBM_PROBE"; +pub const KEYS: [&str; 8] = ["webm.init_count", "webm.thread_handle", "webm.quit_flag", "webm.affinity_mask", "webm.decoders", "webm.decoder_count", "webm.round_robin", "webm.wake_time"]; +pub const DECODER_FIELDS: &str = "webm.decoder"; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Globals { + pub init_count: usize, + pub thread_handle: usize, + pub quit_flag: usize, + pub affinity_mask: usize, + pub decoders: usize, + pub decoder_count: usize, + pub round_robin: usize, + pub wake_time: usize, +} + +pub fn layout(o: &crate::title_offsets::Offsets) -> Result<(Globals, Vec<(String, usize, usize)>), String> { + let v = o.require(&KEYS)?; + let g = Globals { init_count: v[0], thread_handle: v[1], quit_flag: v[2], affinity_mask: v[3], decoders: v[4], decoder_count: v[5], round_robin: v[6], wake_time: v[7] }; + Ok((g, o.fields(DECODER_FIELDS).to_vec())) +} + +pub const MAX_DECODERS: usize = 8; + +fn read(addr: usize, len: usize) -> Option { + let mut v = 0u64; + let mut got = 0usize; + let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), addr as *const c_void, &mut v as *mut u64 as *mut c_void, len.min(8), &mut got) }; + (ok != 0 && got == len.min(8)).then_some(v) +} + +fn thread_line(h: usize) -> (String, u64) { + if h == 0 { + return ("thread handle 0 (not created)".into(), 0); + } + let hp = h as *mut c_void; + let tid = unsafe { GetThreadId(hp) }; + let mut code = 0u32; + let alive = unsafe { GetExitCodeThread(hp, &mut code) } != 0; + let mut cyc = 0u64; + let cyc_ok = unsafe { QueryThreadCycleTime(hp, &mut cyc) } != 0; + let mut p: *mut u16 = core::ptr::null_mut(); + let name = if unsafe { GetThreadDescription(hp, &mut p) } >= 0 && !p.is_null() { + let mut n = 0usize; + while n < 128 && unsafe { *p.add(n) } != 0 { + n += 1; + } + let s = String::from_utf16_lossy(unsafe { core::slice::from_raw_parts(p, n) }); + unsafe { LocalFree(p as *mut c_void) }; + s + } else { + String::new() + }; + let exit = if !alive { format!("exitcode? err={}", unsafe { GetLastError() }) } else if code == 259 { "running".into() } else { format!("exited {code:#x}") }; + (format!("thread h={h:#x} tid={tid} name='{name}' {exit} cycle_query={}", if cyc_ok { "ok" } else { "failed" }), cyc) +} + +fn snapshot(base: usize, l: &Globals, fields: &[(String, usize, usize)]) -> (String, Vec, u64) { + let g = |rva: usize, len: usize| read(base + rva, len).unwrap_or(u64::MAX); + let h = g(l.thread_handle, 8) as usize; + let mask = g(l.affinity_mask, 4); + let topo = super::affinity::topology(); + let host = topo.to_host(mask, super::affinity::process_console_mask()); + let (tl, cycles) = thread_line(if h == usize::MAX { 0 } else { h }); + let head = format!( + "init={} quit={} mask={mask:#x} host={} count={} rr={} wake={} {}", + g(l.init_count, 4), + g(l.quit_flag, 4), + host.map(|v| format!("{v:#x}")).unwrap_or_else(|| "REJECTED".into()), + g(l.decoder_count, 4), + g(l.round_robin, 4), + g(l.wake_time, 4), + tl + ); + let arr = g(l.decoders, 8) as usize; + let n = (g(l.decoder_count, 4) as usize).min(MAX_DECODERS); + let mut decs = Vec::new(); + for i in 0..n { + let d = read(arr + i * 8, 8).unwrap_or(0) as usize; + if d == 0 { + decs.push(format!("dec[{i}]=0")); + continue; + } + let parts: Vec = fields.iter().map(|(k, off, len)| match read(d + off, *len) { + Some(v) => format!("{k}={v:#x}"), + None => format!("{k}=?"), + }).collect(); + decs.push(format!("dec[{i}]@{d:#x} {}", parts.join(" "))); + } + (head, decs, cycles) +} + +pub fn enabled() -> bool { + std::env::var(VAR).ok().map(|v| v.trim() != "0" && !v.trim().is_empty()).unwrap_or(false) +} + +pub fn start() { + if !enabled() { + return; + } + let base = unsafe { GetModuleHandleW(core::ptr::null()) } as usize; + if base == 0 { + return; + } + let Some(o) = crate::title_offsets::for_this_title() else { + crate::record_raw("webm_probe", "inert", &crate::title_offsets::status_for_this_title()); + return; + }; + let (l, fields) = match layout(o) { + Ok(v) => v, + Err(e) => { + crate::record_raw("webm_probe", "inert", &e); + return; + } + }; + let stamp = unsafe { crate::title_offsets::image_timestamp(base as *const u8) }; + if !o.matches_image(stamp) { + crate::record_raw("webm_probe", "inert", &format!("{} was made for another build (image timestamp {stamp:#x})", o.source)); + return; + } + let period = std::env::var(VAR).ok().and_then(|v| v.trim().parse::().ok()).filter(|v| *v >= 100).unwrap_or(1000); + let _ = std::thread::Builder::new().name("tombox-webm-probe".into()).spawn(move || { + crate::record_raw("webm_probe", "start", &format!("base={base:#x} period={period}ms offsets={}", o.source)); + let mut last_head = String::new(); + let mut last_decs: Vec = Vec::new(); + let mut last_cycles = 0u64; + let mut last_running: Option = None; + let mut lines = 0u32; + for tick in 0..(240_000 / period) { + std::thread::sleep(std::time::Duration::from_millis(period)); + let (head, decs, cycles) = snapshot(base, &l, &fields); + let ran = if last_cycles == 0 { 0 } else { cycles.saturating_sub(last_cycles) }; + let running = ran > 0; + if head != last_head || (last_cycles != 0 && last_running != Some(running)) { + if last_cycles != 0 { + last_running = Some(running); + } + crate::record_raw("webm_probe", "state", &format!("t={}ms {head} cycles_delta={ran}", (tick + 1) * period)); + last_head = head; + lines += 1; + } + for (i, d) in decs.iter().enumerate() { + if last_decs.get(i) != Some(d) { + crate::record_raw("webm_probe", "decoder", &format!("t={}ms cycles_delta={ran} {d}", (tick + 1) * period)); + lines += 1; + } + } + last_decs = decs; + last_cycles = cycles; + if lines > 600 { + crate::record_raw("webm_probe", "stop", "line cap reached"); + break; + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_layout_comes_from_the_offsets_file() { + let o = crate::title_offsets::parse(r#"{"exe":"T.exe","values":{"webm.init_count":1,"webm.thread_handle":2,"webm.quit_flag":3,"webm.affinity_mask":4,"webm.decoders":5,"webm.decoder_count":6,"webm.round_robin":7,"webm.wake_time":8},"fields":{"webm.decoder":[["frames","0x10",4]]}}"#, "t").unwrap(); + let (g, f) = layout(&o).unwrap(); + assert_eq!((g.init_count, g.wake_time, g.decoders), (1, 8, 5)); + assert_eq!(f, vec![("frames".to_string(), 0x10, 4)]); + let partial = crate::title_offsets::parse(r#"{"exe":"T.exe","values":{"webm.init_count":1}}"#, "t").unwrap(); + assert!(layout(&partial).unwrap_err().contains("webm.wake_time")); + } + + #[test] + fn a_snapshot_reads_through_the_layout() { + let mut img = vec![0u8; 0x100]; + img[0x10..0x14].copy_from_slice(&7u32.to_le_bytes()); + img[0x30..0x34].copy_from_slice(&0u32.to_le_bytes()); + let base = img.as_ptr() as usize; + let l = Globals { init_count: 0x10, thread_handle: 0x18, quit_flag: 0x20, affinity_mask: 0x24, decoders: 0x28, decoder_count: 0x30, round_robin: 0x34, wake_time: 0x38 }; + let (head, decs, _) = snapshot(base, &l, &[]); + assert!(head.starts_with("init=7 quit=0"), "{head}"); + assert!(decs.is_empty()); + } +} diff --git a/crates/compat/compat-common/src/pad_host.rs b/crates/compat/compat-common/src/pad_host.rs new file mode 100644 index 00000000..7f909b5d --- /dev/null +++ b/crates/compat/compat-common/src/pad_host.rs @@ -0,0 +1,451 @@ + +use crate::gamepad::*; +use core::ffi::c_void; +use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +#[link(name = "user32")] +extern "system" { + fn GetAsyncKeyState(vk: i32) -> i16; + fn GetForegroundWindow() -> *mut c_void; + fn GetWindowThreadProcessId(h: *mut c_void, pid: *mut u32) -> u32; + fn GetClassNameW(h: *mut c_void, buf: *mut u16, n: i32) -> i32; +} +#[link(name = "kernel32")] +extern "system" { + fn LoadLibraryW(name: *const u16) -> *mut c_void; + fn GetProcAddress(m: *mut c_void, name: *const u8) -> *mut c_void; + fn GetCurrentProcessId() -> u32; +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct XinputGamepad { + pub buttons: u16, + pub left_trigger: u8, + pub right_trigger: u8, + pub thumb_lx: i16, + pub thumb_ly: i16, + pub thumb_rx: i16, + pub thumb_ry: i16, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct XinputState { + packet: u32, + pad: XinputGamepad, +} + +#[repr(C)] +struct XinputVibration { + left: u16, + right: u16, +} + +pub const XINPUT_BUTTONS: [(u16, u32); 14] = [ + (0x0001, BTN_UP), + (0x0002, BTN_DOWN), + (0x0004, BTN_LEFT), + (0x0008, BTN_RIGHT), + (0x0010, BTN_MENU), + (0x0020, BTN_VIEW), + (0x0040, BTN_LS), + (0x0080, BTN_RS), + (0x0100, BTN_LB), + (0x0200, BTN_RB), + (0x1000, BTN_A), + (0x2000, BTN_B), + (0x4000, BTN_X), + (0x8000, BTN_Y), +]; + +pub fn thumb(v: i16) -> f32 { + if v < 0 { v as f32 / 32768.0 } else { v as f32 / 32767.0 } +} + +pub fn from_xinput(g: &XinputGamepad) -> PadState { + let mut s = PadState::default(); + for (x, b) in XINPUT_BUTTONS { + if g.buttons & x != 0 { + s.buttons |= b; + } + } + s.axes[AX_LT] = g.left_trigger as f32 / 255.0; + s.axes[AX_RT] = g.right_trigger as f32 / 255.0; + s.axes[AX_LX] = thumb(g.thumb_lx); + s.axes[AX_LY] = thumb(g.thumb_ly); + s.axes[AX_RX] = thumb(g.thumb_rx); + s.axes[AX_RY] = thumb(g.thumb_ry); + s +} + +pub const KEY_BUTTONS: [(i32, u32); 14] = [ + (0x20, BTN_A), + (0x08, BTN_B), + (b'E' as i32, BTN_X), + (b'R' as i32, BTN_Y), + (b'Q' as i32, BTN_LB), + (b'F' as i32, BTN_RB), + (0xA0, BTN_LS), + (b'C' as i32, BTN_RS), + (b'I' as i32, BTN_UP), + (b'K' as i32, BTN_DOWN), + (b'J' as i32, BTN_LEFT), + (b'L' as i32, BTN_RIGHT), + (0x1B, BTN_MENU), + (0x09, BTN_VIEW), +]; + +pub const KEY_TRIGGERS: [(i32, usize); 4] = [ + (b'Z' as i32, AX_LT), + (b'X' as i32, AX_RT), + (0x02, AX_LT), + (0x01, AX_RT), +]; + +pub const KEY_STICKS: [([i32; 4], usize, usize); 2] = [ + ([b'A' as i32, b'D' as i32, b'S' as i32, b'W' as i32], AX_LX, AX_LY), + ([0x25, 0x27, 0x28, 0x26], AX_RX, AX_RY), +]; + +pub fn from_keys(down: impl Fn(i32) -> bool) -> PadState { + let mut s = PadState::default(); + for (vk, b) in KEY_BUTTONS { + if down(vk) { + s.buttons |= b; + } + } + for (vk, a) in KEY_TRIGGERS { + if down(vk) { + s.axes[a] = 1.0; + } + } + let dir = |neg: i32, pos: i32| (down(pos) as i32 - down(neg) as i32) as f32; + for ([l, r, d, u], ax, ay) in KEY_STICKS { + let (x, y) = (dir(l, r), dir(d, u)); + let k = if x != 0.0 && y != 0.0 { core::f32::consts::FRAC_1_SQRT_2 } else { 1.0 }; + s.axes[ax] = x * k; + s.axes[ay] = y * k; + } + s +} + +pub fn combine(a: PadState, b: PadState) -> PadState { + let mut s = PadState { buttons: a.buttons | b.buttons, axes: a.axes }; + for t in [AX_LT, AX_RT] { + if b.axes[t] > s.axes[t] { + s.axes[t] = b.axes[t]; + } + } + for (x, y) in [(AX_LX, AX_LY), (AX_RX, AX_RY)] { + if b.axes[x].powi(2) + b.axes[y].powi(2) > a.axes[x].powi(2) + a.axes[y].powi(2) { + s.axes[x] = b.axes[x]; + s.axes[y] = b.axes[y]; + } + } + s +} + +pub fn merge(script: PadState, script_active: bool, host: PadState) -> PadState { + if script_active || script != PadState::default() { script } else { host } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Mode { + Off, + Auto, + Force, +} + +pub fn parse_mode(v: Option<&str>) -> Mode { + match v.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("0" | "off" | "false" | "no") => Mode::Off, + Some("1" | "on" | "force" | "always") => Mode::Force, + Some("auto") => Mode::Auto, + _ => Mode::Off, + } +} + +fn setting(env: &str, key: &str) -> Mode { + parse_mode(std::env::var(env).ok().or_else(|| crate::cfg(key)).as_deref()) +} + +pub const HELPER_CLASSES: [&str; 2] = [crate::gdk::win::DIALOG_CLASS, "TomBoxFrontPanel"]; + +pub fn is_title_class(class: &str) -> bool { + !HELPER_CLASSES.contains(&class) +} + +pub fn title_foreground() -> bool { + unsafe { + let h = GetForegroundWindow(); + if h.is_null() { + return false; + } + let mut pid = 0u32; + GetWindowThreadProcessId(h, &mut pid); + if pid != GetCurrentProcessId() { + return false; + } + let mut cls = [0u16; 64]; + let n = GetClassNameW(h, cls.as_mut_ptr(), cls.len() as i32).max(0) as usize; + is_title_class(&String::from_utf16_lossy(&cls[..n])) + } +} + +type GetState = unsafe extern "system" fn(u32, *mut XinputState) -> u32; +type SetState = unsafe extern "system" fn(u32, *mut XinputVibration) -> u32; + +static XI_GET: AtomicUsize = AtomicUsize::new(0); +static XI_SET: AtomicUsize = AtomicUsize::new(0); +const NO_SLOT: u32 = u32::MAX; +static FEED_SLOT: AtomicU32 = AtomicU32::new(NO_SLOT); + +fn load_xinput() -> bool { + unsafe { + let name: Vec = "xinput1_4.dll".encode_utf16().chain(Some(0)).collect(); + let m = LoadLibraryW(name.as_ptr()); + if m.is_null() { + return false; + } + let g = GetProcAddress(m, b"XInputGetState\0".as_ptr()); + let s = GetProcAddress(m, b"XInputSetState\0".as_ptr()); + XI_GET.store(g as usize, Ordering::SeqCst); + XI_SET.store(s as usize, Ordering::SeqCst); + !g.is_null() + } +} + +fn xinput_state(slot: u32) -> Option { + let f = XI_GET.load(Ordering::SeqCst); + if f == 0 { + return None; + } + let f: GetState = unsafe { core::mem::transmute(f) }; + let mut st = XinputState::default(); + (unsafe { f(slot, &mut st) } == 0).then_some(st.pad) +} + +pub fn motor_speed(v: f32) -> u16 { + (if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } * 65535.0).round() as u16 +} + +pub fn forward_rumble(low: f32, high: f32) -> Option { + let slot = FEED_SLOT.load(Ordering::SeqCst); + let f = XI_SET.load(Ordering::SeqCst); + if slot == NO_SLOT || f == 0 { + return None; + } + let f: SetState = unsafe { core::mem::transmute(f) }; + let mut v = XinputVibration { left: motor_speed(low), right: motor_speed(high) }; + (unsafe { f(slot, &mut v) } == 0).then_some(slot) +} + +const TICK: Duration = Duration::from_millis(4); +const SCAN: Duration = Duration::from_secs(1); +const HOST_CHECK: Duration = Duration::from_secs(2); + +fn log(func: &str, detail: &str) { + crate::record_raw("gamepad", func, detail); +} + +pub fn start() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let xi = setting("TOMBOX_PAD_XINPUT", "pad_xinput"); + let keys = setting("TOMBOX_PAD_KEYS", "pad_keys"); + if xi == Mode::Off && keys == Mode::Off { + log("host", "XInput and keyboard sources both off; virtual pad is scripted only"); + return; + } + let xi = if xi != Mode::Off && !load_xinput() { + log("host", "xinput1_4.dll not available - real controllers not polled"); + Mode::Off + } else { + xi + }; + log("host", &format!("host input to the virtual pad: XInput {xi:?}, keyboard mapping {keys:?}")); + let _ = std::thread::Builder::new().name("tombox-pad-host".into()).spawn(move || poll_loop(xi, keys)); + }); +} + +fn poll_loop(xi: Mode, keys: Mode) { + let mut slot: Option = None; + let mut last_scan: Option = None; + let mut last_check: Option = None; + let mut host_pad = false; + let mut feeding = false; + let mut keys_were_on = false; + loop { + let mut pad = PadState::default(); + if xi != Mode::Off { + if slot.is_none() && last_scan.map_or(true, |t| t.elapsed() >= SCAN) { + last_scan = Some(Instant::now()); + slot = (0..4).find(|i| xinput_state(*i).is_some()); + if let Some(i) = slot { + log("host", &format!("XInput pad connected at user index {i}")); + last_check = None; + } + } + if let Some(i) = slot { + match xinput_state(i) { + Some(g) => pad = from_xinput(&g), + None => { + log("host", &format!("XInput pad at user index {i} disconnected")); + slot = None; + } + } + } + if slot.is_some() && xi == Mode::Auto && last_check.map_or(true, |t| t.elapsed() >= HOST_CHECK) { + last_check = Some(Instant::now()); + let has = host_has_gamepad(); + if has != host_pad { + log("host", if has { "host GameInput reports a gamepad itself - XInput feed paused so the pad is not doubled" } else { "host GameInput reports no gamepad - XInput feeds the virtual pad" }); + } + host_pad = has; + } + } + let keys_on = !crate::host_input::kbm_hidden() && (keys == Mode::Force || (keys == Mode::Auto && !title_reads_keyboard())); + if keys_were_on && !keys_on { + log("host", "title reads the keyboard through GameInput - keyboard-to-pad mapping off"); + } + keys_were_on = keys_on; + let kb = if keys_on && title_foreground() { from_keys(|vk| unsafe { GetAsyncKeyState(vk) } < 0) } else { PadState::default() }; + let feed = slot.filter(|_| !crate::host_input::pad_hidden() && (xi == Mode::Force || !host_pad)); + FEED_SLOT.store(feed.unwrap_or(NO_SLOT), Ordering::SeqCst); + set_host(combine(if feed.is_some() { pad } else { PadState::default() }, kb)); + if feed.is_some() && !feeding { + host_connect(true, "XInput pad"); + } else if feed.is_none() && feeding && !keys_on { + host_connect(false, "XInput pad gone"); + } + if kb != PadState::default() { + host_connect(true, "keyboard mapping"); + } + feeding = feed.is_some(); + std::thread::sleep(TICK); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-6 + } + + #[test] + fn xinput_buttons_map_to_gameinput_bits() { + let all = from_xinput(&XinputGamepad { buttons: 0xF3FF, ..Default::default() }); + assert_eq!(all.buttons, 0x3FFF); + let a = from_xinput(&XinputGamepad { buttons: 0x1000 | 0x0010 | 0x0001, ..Default::default() }); + assert_eq!(a.buttons, BTN_A | BTN_MENU | BTN_UP); + assert_eq!(from_xinput(&XinputGamepad { buttons: 0x0C00, ..Default::default() }).buttons, 0); + } + + #[test] + fn xinput_axes_normalise_to_gameinput_ranges() { + let g = XinputGamepad { left_trigger: 255, right_trigger: 0, thumb_lx: -32768, thumb_ly: 32767, thumb_rx: 0, thumb_ry: -16384, ..Default::default() }; + let s = from_xinput(&g); + assert_eq!(s.axes[AX_LT], 1.0); + assert_eq!(s.axes[AX_RT], 0.0); + assert_eq!(s.axes[AX_LX], -1.0); + assert_eq!(s.axes[AX_LY], 1.0); + assert_eq!(s.axes[AX_RX], 0.0); + assert!(close(s.axes[AX_RY], -0.5)); + assert!(close(from_xinput(&XinputGamepad { left_trigger: 128, ..Default::default() }).axes[AX_LT], 128.0 / 255.0)); + } + + #[test] + fn xinput_has_no_dead_zone_like_gameinput() { + let s = from_xinput(&XinputGamepad { thumb_lx: 1, thumb_ly: -1, right_trigger: 1, ..Default::default() }); + assert!(s.axes[AX_LX] > 0.0 && s.axes[AX_LX] < 1e-4); + assert!(s.axes[AX_LY] < 0.0 && s.axes[AX_LY] > -1e-4); + assert!(s.axes[AX_RT] > 0.0); + assert_eq!(from_xinput(&XinputGamepad::default()), PadState::default()); + for v in [i16::MIN, -1, 0, 1, i16::MAX] { + assert!((-1.0..=1.0).contains(&thumb(v))); + } + } + + #[test] + fn keys_map_to_buttons_sticks_and_triggers() { + let set = |keys: &'static [i32]| from_keys(move |vk| keys.contains(&vk)); + assert_eq!(set(&[]), PadState::default()); + let s = set(&[b'W' as i32, 0x20, 0x01]); + assert_eq!(s.buttons, BTN_A); + assert_eq!(s.axes[AX_LY], 1.0); + assert_eq!(s.axes[AX_LX], 0.0); + assert_eq!(s.axes[AX_RT], 1.0); + let s = set(&[b'A' as i32, b'D' as i32, 0x28]); + assert_eq!(s.axes[AX_LX], 0.0, "opposite keys cancel"); + assert_eq!(s.axes[AX_RY], -1.0); + let s = set(&[b'W' as i32, b'D' as i32]); + assert!(close(s.axes[AX_LX], core::f32::consts::FRAC_1_SQRT_2)); + assert!(close(s.axes[AX_LX].hypot(s.axes[AX_LY]), 1.0), "diagonal stays on the unit circle"); + let s = set(&[0x1B, 0x09, b'I' as i32, b'L' as i32, 0xA0, b'C' as i32, b'Q' as i32, b'F' as i32, b'E' as i32, b'R' as i32, 0x08]); + assert_eq!(s.buttons, BTN_MENU | BTN_VIEW | BTN_UP | BTN_RIGHT | BTN_LS | BTN_RS | BTN_LB | BTN_RB | BTN_X | BTN_Y | BTN_B); + assert_eq!(set(&[b'Z' as i32, 0x02]).axes[AX_LT], 1.0); + } + + #[test] + fn combine_ors_buttons_and_takes_the_larger_stick_whole() { + let mut pad = PadState::default(); + pad.buttons = BTN_A; + pad.axes[AX_LX] = 0.3; + pad.axes[AX_LY] = 0.3; + pad.axes[AX_RT] = 0.4; + let mut kb = PadState::default(); + kb.buttons = BTN_B; + kb.axes[AX_LY] = 1.0; + kb.axes[AX_RX] = -1.0; + let s = combine(pad, kb); + assert_eq!(s.buttons, BTN_A | BTN_B); + assert_eq!((s.axes[AX_LX], s.axes[AX_LY]), (0.0, 1.0)); + assert_eq!((s.axes[AX_RX], s.axes[AX_RY]), (-1.0, 0.0)); + assert!(close(s.axes[AX_RT], 0.4)); + assert_eq!(combine(pad, PadState::default()), pad); + assert_eq!(combine(PadState::default(), kb), kb); + } + + #[test] + fn scripted_pad_wins_while_running_or_holding() { + let mut host = PadState::default(); + host.buttons = BTN_X; + host.axes[AX_LX] = 1.0; + let neutral = PadState::default(); + assert_eq!(merge(neutral, false, host), host); + assert_eq!(merge(neutral, true, host), neutral, "a running script masks host input even between presses"); + let mut held = PadState::default(); + held.apply(Input::Button(BTN_A), true); + assert_eq!(merge(held, false, host), held, "a scripted 'down' masks host input until its 'up'"); + assert_eq!(merge(held, true, neutral), held); + } + + #[test] + fn modes_and_title_window_classes() { + assert_eq!(parse_mode(None), Mode::Off); + assert_eq!(parse_mode(Some("yes please")), Mode::Off); + assert_eq!(parse_mode(Some(" 0 ")), Mode::Off); + assert_eq!(parse_mode(Some("off")), Mode::Off); + assert_eq!(parse_mode(Some("Force")), Mode::Force); + assert_eq!(parse_mode(Some("1")), Mode::Force); + assert_eq!(parse_mode(Some("auto")), Mode::Auto); + assert!(is_title_class("UnrealWindow")); + assert!(is_title_class("XboxEmulatorHostWindow")); + assert!(!is_title_class("TomBoxGdkDialog")); + assert!(!is_title_class("TomBoxFrontPanel")); + } + + #[test] + fn rumble_levels_to_xinput_motor_speeds() { + assert_eq!(motor_speed(0.0), 0); + assert_eq!(motor_speed(1.0), 65535); + assert_eq!(motor_speed(2.0), 65535); + assert_eq!(motor_speed(-1.0), 0); + assert_eq!(motor_speed(f32::NAN), 0); + assert_eq!(motor_speed(0.5), 32768); + } +} diff --git a/crates/compat/compat-common/src/partition_heap.rs b/crates/compat/compat-common/src/partition_heap.rs new file mode 100644 index 00000000..035c227b --- /dev/null +++ b/crates/compat/compat-common/src/partition_heap.rs @@ -0,0 +1,60 @@ +use core::ffi::c_void; + +type Handle = *mut c_void; +const HEAP_FLAGS: u32 = 0x102; +pub const ERROR_BAD_ARGUMENTS: u32 = 0xa0; + +#[link(name = "ntdll", kind = "raw-dylib")] +extern "system" { + fn RtlCreateHeap(flags: u32, base: *mut c_void, reserve: usize, commit: usize, lock: *mut c_void, params: *mut c_void) -> Handle; +} + +#[link(name = "kernel32")] +extern "system" { + fn SetLastError(code: u32); +} + +#[repr(C)] +#[derive(Default)] +pub struct SegmentHeapParameters { + pub version_size: u32, + pub flags: u32, + pub source_flags: u32, + pub memory_type_mask: u32, + pub numa_node: u32, + pub partition: usize, + pub reserved: [usize; 2], + pub tail: [u64; 4], +} + +pub fn segment_parameters(partition: usize, memory_type: u32) -> SegmentHeapParameters { + let mut mask = 1u32.wrapping_shl(memory_type); + if memory_type == 4 { + mask |= 8; + } + SegmentHeapParameters { + version_size: 0x50_0003, + numa_node: 0xffff_ffff, + memory_type_mask: mask & 0xff, + partition: if memory_type >= 2 { partition } else { 0 }, + ..Default::default() + } +} + +pub unsafe fn partition_create_heap(partition: usize, memory_type: u32, flags: u32, base: *mut c_void, reserve: usize, commit: usize, lock: *mut c_void, params: *mut c_void) -> Handle { + let mut built = segment_parameters(partition, memory_type); + let (flags, reserve, commit, params) = if params.is_null() { + (flags | HEAP_FLAGS, 0, 0, (&mut built as *mut SegmentHeapParameters).cast()) + } else { + (flags, reserve, commit, params) + }; + let mut h = RtlCreateHeap(flags, base, reserve, commit, lock, params); + if h.is_null() && params == (&mut built as *mut SegmentHeapParameters).cast() && partition == 0 && built.memory_type_mask != 1 { + built.memory_type_mask = 1; + h = RtlCreateHeap(flags, base, reserve, commit, lock, params); + } + if h.is_null() { + SetLastError(ERROR_BAD_ARGUMENTS); + } + h +} diff --git a/crates/compat/compat-common/src/physical_pages.rs b/crates/compat/compat-common/src/physical_pages.rs new file mode 100644 index 00000000..dab48c89 --- /dev/null +++ b/crates/compat/compat-common/src/physical_pages.rs @@ -0,0 +1,4 @@ +pub const PAGE_BYTES: usize = 0x1_0000; +pub const FIRST_TITLE_PAGE: u64 = 0x1000; +const FIRST_TITLE_FRAME: u64 = FIRST_TITLE_PAGE * (PAGE_BYTES as u64 / 4096); +pub const TITLE_LAYOUT_19041: [u64; 2] = [FIRST_TITLE_FRAME; 2]; diff --git a/crates/compat/compat-common/src/title_offsets.rs b/crates/compat/compat-common/src/title_offsets.rs new file mode 100644 index 00000000..b6c75b19 --- /dev/null +++ b/crates/compat/compat-common/src/title_offsets.rs @@ -0,0 +1,215 @@ +use std::collections::HashMap; +use std::sync::OnceLock; + +pub const VAR: &str = "TOMBOX_PROBE_OFFSETS"; + +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Offsets { + pub source: String, + pub exe: String, + pub pe_timestamp: Option, + values: HashMap, + fields: HashMap>, + bytes: HashMap>, +} + +impl Offsets { + pub fn get(&self, key: &str) -> Option { + self.values.get(key).copied() + } + + pub fn require(&self, keys: &[&str]) -> Result, String> { + let missing: Vec<&str> = keys.iter().copied().filter(|k| !self.values.contains_key(*k)).collect(); + if missing.is_empty() { + Ok(keys.iter().map(|k| self.values[*k]).collect()) + } else { + Err(format!("{} lacks {}", self.source, missing.join(", "))) + } + } + + pub fn fields(&self, key: &str) -> &[(String, usize, usize)] { + self.fields.get(key).map(|v| v.as_slice()).unwrap_or(&[]) + } + + pub fn bytes(&self, key: &str) -> Option<&[u8]> { + self.bytes.get(key).map(|v| v.as_slice()) + } + + pub fn require_bytes(&self, keys: &[&str]) -> Result>, String> { + let missing: Vec<&str> = keys.iter().copied().filter(|k| !self.bytes.contains_key(*k)).collect(); + if missing.is_empty() { + Ok(keys.iter().map(|k| self.bytes[*k].clone()).collect()) + } else { + Err(format!("{} lacks bytes {}", self.source, missing.join(", "))) + } + } + + pub fn matches_image(&self, stamp: u32) -> bool { + self.pe_timestamp.map(|t| t == stamp).unwrap_or(true) + } +} + +pub fn parse_num(v: &serde_json::Value) -> Option { + match v { + serde_json::Value::Number(n) => n.as_u64().map(|x| x as usize), + serde_json::Value::String(s) => { + let t = s.trim().replace('_', ""); + match t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) { + Some(h) => usize::from_str_radix(h, 16).ok(), + None => t.parse().ok(), + } + } + _ => None, + } +} + +pub fn parse_bytes(v: &str) -> Option> { + let t: String = v.chars().filter(|c| !c.is_whitespace()).collect(); + if t.is_empty() || t.len() % 2 != 0 { + return None; + } + (0..t.len()).step_by(2).map(|i| u8::from_str_radix(&t[i..i + 2], 16).ok()).collect() +} + +pub fn parse(text: &str, source: &str) -> Result { + let j: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("{source}: {e}"))?; + let exe = j.get("exe").and_then(|v| v.as_str()).ok_or_else(|| format!("{source}: no \"exe\""))?.to_string(); + let pe_timestamp = match j.get("pe_timestamp") { + Some(v) => Some(parse_num(v).ok_or_else(|| format!("{source}: bad pe_timestamp"))? as u32), + None => None, + }; + let mut values = HashMap::new(); + if let Some(m) = j.get("values").and_then(|v| v.as_object()) { + for (k, v) in m { + values.insert(k.clone(), parse_num(v).ok_or_else(|| format!("{source}: bad value for {k}"))?); + } + } + let mut fields = HashMap::new(); + if let Some(m) = j.get("fields").and_then(|v| v.as_object()) { + for (k, v) in m { + let arr = v.as_array().ok_or_else(|| format!("{source}: fields.{k} is not a list"))?; + let mut out = Vec::new(); + for e in arr { + let t = e.as_array().filter(|t| t.len() == 3).ok_or_else(|| format!("{source}: fields.{k} entries are [name, offset, size]"))?; + let name = t[0].as_str().ok_or_else(|| format!("{source}: fields.{k} name"))?.to_string(); + let off = parse_num(&t[1]).ok_or_else(|| format!("{source}: fields.{k}.{name} offset"))?; + let size = parse_num(&t[2]).filter(|s| (1..=8).contains(s)).ok_or_else(|| format!("{source}: fields.{k}.{name} size"))?; + out.push((name, off, size)); + } + fields.insert(k.clone(), out); + } + } + let mut bytes = HashMap::new(); + if let Some(m) = j.get("bytes").and_then(|v| v.as_object()) { + for (k, v) in m { + let b = v.as_str().and_then(parse_bytes).ok_or_else(|| format!("{source}: bytes.{k} is not a hex byte string"))?; + bytes.insert(k.clone(), b); + } + } + Ok(Offsets { source: source.to_string(), exe, pe_timestamp, values, fields, bytes }) +} + +fn dir() -> Option { + if let Ok(p) = std::env::var(VAR) { + if !p.trim().is_empty() { + return Some(std::path::PathBuf::from(p.trim())); + } + } + std::env::var("LOCALAPPDATA").ok().map(|d| std::path::PathBuf::from(d).join("TomBox").join("probe_offsets")) +} + +pub fn path_for(exe: &str) -> Option { + let d = dir()?; + if d.extension().map(|e| e.eq_ignore_ascii_case("json")).unwrap_or(false) { + return Some(d); + } + let stem = std::path::Path::new(exe).file_stem()?.to_string_lossy().to_string(); + Some(d.join(format!("{stem}.json"))) +} + +pub fn load_for(exe: &str) -> Result { + let p = path_for(exe).ok_or_else(|| "no offsets directory (LOCALAPPDATA unset)".to_string())?; + let text = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?; + let o = parse(&text, &p.display().to_string())?; + if !o.exe.eq_ignore_ascii_case(exe) { + return Err(format!("{} is for {}, not {exe}", o.source, o.exe)); + } + Ok(o) +} + +pub fn current_exe_name() -> Option { + std::env::current_exe().ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string())) +} + +pub fn for_this_title() -> Option<&'static Offsets> { + static O: OnceLock> = OnceLock::new(); + O.get_or_init(|| current_exe_name().and_then(|n| load_for(&n).ok())).as_ref() +} + +pub fn status_for_this_title() -> String { + match current_exe_name() { + Some(n) => match load_for(&n) { + Ok(o) => format!("offsets from {}", o.source), + Err(e) => e, + }, + None => "no executable name".into(), + } +} + +pub unsafe fn image_timestamp(base: *const u8) -> u32 { + let pe = core::ptr::read_unaligned(base.add(0x3c) as *const u32) as usize; + core::ptr::read_unaligned(base.add(pe + 8) as *const u32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_values_fields_and_timestamp() { + let o = parse(r#"{"exe":"Game.exe","pe_timestamp":"0x12345678","values":{"a":"0x10","b":32,"c":"1_000"},"fields":{"rec":[["x","0x8",4],["y",12,8]]}}"#, "t").unwrap(); + assert_eq!(o.exe, "Game.exe"); + assert_eq!(o.pe_timestamp, Some(0x1234_5678)); + assert_eq!((o.get("a"), o.get("b"), o.get("c"), o.get("d")), (Some(0x10), Some(32), Some(1000), None)); + assert_eq!(o.fields("rec"), &[("x".to_string(), 8, 4), ("y".to_string(), 12, 8)]); + assert!(o.fields("none").is_empty()); + assert_eq!(o.require(&["a", "b"]), Ok(vec![0x10, 32])); + assert!(o.require(&["a", "zz"]).unwrap_err().contains("zz")); + assert!(o.matches_image(0x1234_5678) && !o.matches_image(1)); + } + + #[test] + fn parses_byte_strings() { + let o = parse(r#"{"exe":"a","bytes":{"p":"4C 8d3D","q":"00"}}"#, "t").unwrap(); + assert_eq!(o.bytes("p"), Some(&[0x4c, 0x8d, 0x3d][..])); + assert_eq!(o.require_bytes(&["q"]), Ok(vec![vec![0]])); + assert!(o.require_bytes(&["z"]).unwrap_err().contains("z")); + assert!(parse(r#"{"exe":"a","bytes":{"p":"4C 8"}}"#, "t").unwrap_err().contains("bytes.p")); + assert!(parse(r#"{"exe":"a","bytes":{"p":"zz"}}"#, "t").is_err()); + } + + #[test] + fn rejects_bad_files() { + assert!(parse("{", "t").is_err()); + assert!(parse(r#"{"values":{}}"#, "t").unwrap_err().contains("exe")); + assert!(parse(r#"{"exe":"a","values":{"k":"zz"}}"#, "t").unwrap_err().contains("k")); + assert!(parse(r#"{"exe":"a","fields":{"r":[["x",1,9]]}}"#, "t").unwrap_err().contains("size")); + let o = parse(r#"{"exe":"a"}"#, "t").unwrap(); + assert!(o.matches_image(7)); + } + + #[test] + fn loads_by_exe_stem_from_the_override_directory() { + let d = std::env::temp_dir().join(format!("tombox_offsets_test_{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("Sample.json"), r#"{"exe":"Sample.exe","values":{"k":"0x40"}}"#).unwrap(); + std::env::set_var(VAR, &d); + let o = load_for("Sample.exe").unwrap(); + assert_eq!(o.get("k"), Some(0x40)); + assert!(load_for("Other.exe").is_err()); + std::fs::write(d.join("Wrong.json"), r#"{"exe":"NotWrong.exe"}"#).unwrap(); + assert!(load_for("Wrong.exe").unwrap_err().contains("not Wrong.exe")); + std::env::remove_var(VAR); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/compat/compat-common/src/title_symbols.rs b/crates/compat/compat-common/src/title_symbols.rs new file mode 100644 index 00000000..e06aef99 --- /dev/null +++ b/crates/compat/compat-common/src/title_symbols.rs @@ -0,0 +1,474 @@ +use std::collections::HashMap; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use miniz_oxide::inflate::stream::{inflate, InflateState}; +use miniz_oxide::{DataFormat, MZFlush, MZStatus}; + +pub const VAR: &str = "TOMBOX_TITLE_SYMBOLS"; +const MAX_RAW: usize = 1 << 30; +const CHUNK: usize = 1 << 16; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Sym { + pub rva: usize, + pub size: usize, +} + +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Table { + pub source: String, + pub image: String, + pub total: usize, + found: HashMap>, +} + +impl Table { + pub fn get(&self, name: &str) -> Option { + match self.all(name) { + [one] => Some(*one), + _ => None, + } + } + + pub fn all(&self, name: &str) -> &[Sym] { + self.found.get(name).map(|v| v.as_slice()).unwrap_or(&[]) + } + + pub fn unique_found(&self) -> usize { + self.found.values().filter(|v| v.len() == 1).count() + } + + pub fn require(&self, names: &[&str]) -> Result, String> { + let missing: Vec<&str> = names.iter().copied().filter(|n| self.get(n).is_none()).collect(); + if missing.is_empty() { + Ok(names.iter().map(|n| self.get(n).unwrap()).collect()) + } else { + Err(format!("{} lacks a unique symbol for {}", self.source, missing.join(", "))) + } + } +} + +struct Z { + src: R, + inbuf: Vec, + in_pos: usize, + in_len: usize, + src_done: bool, + state: Box, + out: Vec, + out_pos: usize, + out_len: usize, + ended: bool, + total: usize, +} + +impl Z { + fn new(src: R) -> Self { + Z { src, inbuf: vec![0; CHUNK], in_pos: 0, in_len: 0, src_done: false, state: InflateState::new_boxed(DataFormat::Zlib), out: vec![0; CHUNK], out_pos: 0, out_len: 0, ended: false, total: 0 } + } + + fn fill(&mut self) -> Result { + while self.out_pos == self.out_len { + if self.ended { + return Ok(false); + } + if self.in_pos == self.in_len && !self.src_done { + self.in_len = self.src.read(&mut self.inbuf).map_err(|e| e.to_string())?; + self.in_pos = 0; + self.src_done = self.in_len == 0; + } + let r = inflate(&mut self.state, &self.inbuf[self.in_pos..self.in_len], &mut self.out, MZFlush::None); + self.in_pos += r.bytes_consumed; + self.out_pos = 0; + self.out_len = r.bytes_written; + self.total += r.bytes_written; + match r.status { + Ok(MZStatus::StreamEnd) => self.ended = true, + Ok(_) => {} + Err(e) => return Err(format!("inflate failed: {e:?}")), + } + if r.bytes_consumed == 0 && r.bytes_written == 0 && self.src_done && !self.ended { + return Err("compressed data ends early".into()); + } + } + Ok(true) + } + + fn read(&mut self, buf: &mut [u8]) -> Result<(), String> { + let mut at = 0; + while at < buf.len() { + if !self.fill()? { + return Err(format!("unpacked data ends early at {:#x}", self.total)); + } + let n = (self.out_len - self.out_pos).min(buf.len() - at); + buf[at..at + n].copy_from_slice(&self.out[self.out_pos..self.out_pos + n]); + self.out_pos += n; + at += n; + } + Ok(()) + } + + fn skip(&mut self, mut n: usize) -> Result<(), String> { + while n > 0 { + if !self.fill()? { + return Err(format!("unpacked data ends early at {:#x}", self.total)); + } + let k = (self.out_len - self.out_pos).min(n); + self.out_pos += k; + n -= k; + } + Ok(()) + } + + fn u32(&mut self) -> Result { + let mut b = [0u8; 4]; + self.read(&mut b)?; + Ok(u32::from_le_bytes(b)) + } + + fn at_end(&mut self) -> Result { + Ok(!self.fill()?) + } +} + +fn header(src: &mut impl Read, len: u64) -> Result { + let mut h = [0u8; 8]; + src.read_exact(&mut h).map_err(|e| format!("header: {e}"))?; + let raw = u32::from_le_bytes(h[0..4].try_into().unwrap()) as usize; + let packed = u32::from_le_bytes(h[4..8].try_into().unwrap()) as u64; + if packed + 8 != len { + return Err(format!("header says {packed} packed bytes, file has {}", len.saturating_sub(8))); + } + if raw > MAX_RAW { + return Err(format!("unpacked size {raw} is too large")); + } + Ok(raw) +} + +fn prologue(z: &mut Z) -> Result<(String, usize), String> { + let version = z.u32()?; + if version != 1 { + return Err(format!("unknown version {version}")); + } + let name_len = z.u32()? as usize; + if name_len > 4096 { + return Err(format!("image name length {name_len}")); + } + let mut name = vec![0u8; name_len]; + z.read(&mut name)?; + z.skip(8)?; + let image = String::from_utf8_lossy(name.split(|&c| c == 0).next().unwrap_or(&[])).to_string(); + Ok((image, z.u32()? as usize)) +} + +pub fn parse_with(open: impl Fn() -> Result<(R, u64), String>, wanted: &[&str], source: &str) -> Result { + let err = |e: String| format!("{source}: {e}"); + let (mut f, len) = open().map_err(err)?; + let raw = header(&mut f, len).map_err(err)?; + let mut z = Z::new(f); + let (image, count) = prologue(&mut z).map_err(err)?; + z.skip(count.checked_mul(12).ok_or_else(|| err("record count overflows".into()))?).map_err(err)?; + if z.u32().map_err(err)? as usize != count { + return Err(err("name count does not match record count".into())); + } + let want: HashMap<&[u8], &str> = wanted.iter().map(|w| (w.as_bytes(), *w)).collect(); + let longest = wanted.iter().map(|w| w.len() + 1).max().unwrap_or(0); + let mut hits: Vec<(usize, &str)> = Vec::new(); + let mut buf = vec![0u8; longest]; + for i in 0..count { + let n = z.u32().map_err(err)? as usize; + if n == 0 || n > 1 << 20 { + return Err(err(format!("name {i} has length {n}"))); + } + if n > longest { + z.skip(n).map_err(err)?; + continue; + } + z.read(&mut buf[..n]).map_err(err)?; + let s = &buf[..n]; + let s = s.strip_suffix(&[0]).unwrap_or(s); + if let Some(w) = want.get(s) { + hits.push((i, w)); + } + } + if !z.at_end().map_err(err)? { + return Err(err("trailing bytes after the name table".into())); + } + if z.total != raw { + return Err(err(format!("unpacked {} bytes, header says {raw}", z.total))); + } + let mut found: HashMap> = HashMap::new(); + if !hits.is_empty() { + hits.sort(); + let (mut f, len) = open().map_err(err)?; + header(&mut f, len).map_err(err)?; + let mut z = Z::new(f); + prologue(&mut z).map_err(err)?; + let mut next = 0usize; + for &(i, w) in &hits { + z.skip((i - next) * 12).map_err(err)?; + let rva = z.u32().map_err(err)? as usize; + let size = z.u32().map_err(err)? as usize; + z.skip(4).map_err(err)?; + next = i + 1; + found.entry(w.to_string()).or_default().push(Sym { rva, size }); + } + } + Ok(Table { source: source.to_string(), image, total: count, found }) +} + +pub fn parse_bytes(file: &[u8], wanted: &[&str], source: &str) -> Result { + parse_with(|| Ok((std::io::Cursor::new(file), file.len() as u64)), wanted, source) +} + +pub fn candidates(exe: &Path) -> Vec { + let mut out = Vec::new(); + if let Ok(p) = std::env::var(VAR) { + let p = p.trim(); + if p == "0" { + return out; + } + if !p.is_empty() { + out.push(PathBuf::from(p)); + return out; + } + } + let Some(stem) = exe.file_stem().map(|s| s.to_string_lossy().to_string()) else { return out }; + let file = format!("{stem}-Symbols.bin"); + let mut dir = exe.parent(); + for depth in 0..6 { + let Some(d) = dir else { break }; + if depth == 0 { + out.push(d.join(&file)); + } + out.push(d.join("Symbols").join(&file)); + dir = d.parent(); + } + out +} + +pub fn locate(exe: &Path) -> Option { + candidates(exe).into_iter().find(|p| p.is_file()) +} + +pub fn load(exe: &Path, wanted: &[&str]) -> Result { + let stem = exe.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + let path = locate(exe).ok_or_else(|| format!("no {stem}-Symbols.bin next to the title"))?; + let source = path.display().to_string(); + let open = || { + let f = std::fs::File::open(&path).map_err(|e| e.to_string())?; + let len = f.metadata().map_err(|e| e.to_string())?.len(); + Ok((std::io::BufReader::with_capacity(CHUNK, f), len)) + }; + let t = parse_with(open, wanted, &source)?; + if !t.image.eq_ignore_ascii_case(&stem) { + return Err(format!("{source} describes {}, not {stem}", t.image)); + } + Ok(t) +} + +pub fn all_wanted() -> Vec<&'static str> { + let mut v: Vec<&'static str> = Vec::new(); + v.extend_from_slice(&crate::gdk_user::XASYNC_NAMES); + v.extend_from_slice(&crate::gdk_user::XUSER_NAMES); + v.extend_from_slice(&crate::gdk_store::XSTORE_NAMES); + v.extend_from_slice(&crate::os_host::fortnite_match::SYMBOLS); + v +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Cost { + pub ms: u128, + pub peak_private_delta: usize, +} + +#[repr(C)] +#[derive(Default)] +struct Counters { + cb: u32, + page_faults: u32, + peak_ws: usize, + ws: usize, + quota_peak_paged: usize, + quota_paged: usize, + quota_peak_nonpaged: usize, + quota_nonpaged: usize, + pagefile: usize, + peak_pagefile: usize, +} + +#[link(name = "kernel32")] +extern "system" { + fn K32GetProcessMemoryInfo(p: *mut core::ffi::c_void, c: *mut Counters, cb: u32) -> i32; + fn GetCurrentProcess() -> *mut core::ffi::c_void; +} + +fn counters() -> Counters { + let mut c = Counters { cb: core::mem::size_of::() as u32, ..Default::default() }; + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + c +} + +pub fn measured(f: impl FnOnce() -> T) -> (T, Cost) { + let before = counters(); + let st = std::time::Instant::now(); + let r = f(); + let ms = st.elapsed().as_millis(); + let after = counters(); + (r, Cost { ms, peak_private_delta: after.peak_pagefile.saturating_sub(before.pagefile.max(before.peak_pagefile)) }) +} + +pub fn for_this_title() -> Result<&'static Table, String> { + static T: OnceLock> = OnceLock::new(); + T.get_or_init(|| { + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + if locate(&exe).is_none() { + return Err(format!("no {}-Symbols.bin next to the title", exe.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default())); + } + let wanted = all_wanted(); + let (t, cost) = measured(|| load(&exe, &wanted)); + match &t { + Ok(t) => crate::record_raw("title_symbols", "load", &format!("{} symbols in {}; {} of {} wanted found once; {} ms, peak private +{} KB", t.total, t.source, t.unique_found(), wanted.len(), cost.ms, cost.peak_private_delta / 1024)), + Err(e) => crate::record_raw("title_symbols", "load", &format!("{e} ({} ms)", cost.ms)), + } + t + }) + .as_ref() + .map_err(|e| e.clone()) +} + +#[cfg(test)] +pub fn build_for_test(image: &str, syms: &[(&str, u32, u32)]) -> Vec { + let mut p = Vec::new(); + p.extend_from_slice(&1u32.to_le_bytes()); + let mut name = image.as_bytes().to_vec(); + name.push(0); + while name.len() % 4 != 0 { + name.push(0); + } + p.extend_from_slice(&(name.len() as u32).to_le_bytes()); + p.extend_from_slice(&name); + p.extend_from_slice(&[0u8; 8]); + p.extend_from_slice(&(syms.len() as u32).to_le_bytes()); + for (_, rva, size) in syms { + p.extend_from_slice(&rva.to_le_bytes()); + p.extend_from_slice(&size.to_le_bytes()); + p.extend_from_slice(&0u32.to_le_bytes()); + } + p.extend_from_slice(&(syms.len() as u32).to_le_bytes()); + for (n, _, _) in syms { + p.extend_from_slice(&(n.len() as u32 + 1).to_le_bytes()); + p.extend_from_slice(n.as_bytes()); + p.push(0); + } + pack_for_test(&p) +} + +#[cfg(test)] +pub fn pack_for_test(p: &[u8]) -> Vec { + let z = miniz_oxide::deflate::compress_to_vec_zlib(p, 6); + let mut f = Vec::new(); + f.extend_from_slice(&(p.len() as u32).to_le_bytes()); + f.extend_from_slice(&(z.len() as u32).to_le_bytes()); + f.extend_from_slice(&z); + f +} + +#[cfg(test)] +pub fn table_for_test(image: &str, syms: &[(&str, u32, u32)], wanted: &[&str]) -> Table { + parse_bytes(&build_for_test(image, syms), wanted, "t").unwrap() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_only_the_wanted_names() { + let t = table_for_test("Game", &[("A", 0x100, 0x20), ("B::c", 0x200, 0x40), ("Other", 0x300, 8)], &["A", "B::c", "Missing"]); + assert_eq!((t.image.as_str(), t.total), ("Game", 3)); + assert_eq!(t.get("B::c"), Some(Sym { rva: 0x200, size: 0x40 })); + assert_eq!(t.get("Other"), None); + assert!(t.require(&["A", "Missing"]).unwrap_err().contains("Missing")); + } + + #[test] + fn large_tables_stream_across_many_chunks() { + let names: Vec = (0..40_000).map(|i| format!("Namespace::Function_{i}_with_a_long_decorated_name")).collect(); + let syms: Vec<(&str, u32, u32)> = names.iter().enumerate().map(|(i, n)| (n.as_str(), 0x1000 + i as u32 * 16, 16)).collect(); + let t = table_for_test("Big", &syms, &[names[3].as_str(), names[39_999].as_str()]); + assert_eq!(t.get(&names[3]), Some(Sym { rva: 0x1030, size: 16 })); + assert_eq!(t.get(&names[39_999]), Some(Sym { rva: 0x1000 + 39_999 * 16, size: 16 })); + } + + #[test] + fn duplicated_names_are_not_trusted() { + let t = table_for_test("Game", &[("A", 0x100, 0x20), ("A", 0x500, 0x20)], &["A"]); + assert_eq!(t.get("A"), None); + assert_eq!(t.all("A"), &[Sym { rva: 0x100, size: 0x20 }, Sym { rva: 0x500, size: 0x20 }]); + } + + #[test] + fn damaged_files_are_rejected() { + let f = build_for_test("Game", &[("A", 0x100, 0x20)]); + assert!(parse_bytes(&f[..f.len() - 1], &["A"], "t").unwrap_err().contains("packed")); + let mut bad = f.clone(); + bad[0] ^= 1; + assert!(parse_bytes(&bad, &["A"], "t").unwrap_err().contains("header says")); + let mut corrupt = f.clone(); + let n = corrupt.len(); + corrupt[n - 3] ^= 0xff; + assert!(parse_bytes(&corrupt, &["A"], "t").is_err()); + let base = { + let mut p = Vec::new(); + p.extend_from_slice(&1u32.to_le_bytes()); + p.extend_from_slice(&4u32.to_le_bytes()); + p.extend_from_slice(b"Gam\0"); + p.extend_from_slice(&[0u8; 8]); + p.extend_from_slice(&1u32.to_le_bytes()); + p.extend_from_slice(&[0x10, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0]); + p.extend_from_slice(&1u32.to_le_bytes()); + p.extend_from_slice(&2u32.to_le_bytes()); + p.extend_from_slice(b"A\0"); + p + }; + assert_eq!(parse_bytes(&pack_for_test(&base), &["A"], "t").unwrap().get("A"), Some(Sym { rva: 0x10, size: 0x20 })); + let mut trailing = base.clone(); + trailing.push(0); + assert!(parse_bytes(&pack_for_test(&trailing), &["A"], "t").unwrap_err().contains("trailing")); + let mut v2 = base.clone(); + v2[0] = 2; + assert!(parse_bytes(&pack_for_test(&v2), &["A"], "t").unwrap_err().contains("version")); + assert!(parse_bytes(&pack_for_test(&base[..base.len() - 1]), &["A"], "t").unwrap_err().contains("ends early")); + } + + #[test] + fn the_file_is_found_beside_the_exe_or_in_an_ancestor_symbols_folder() { + let root = std::env::temp_dir().join(format!("tombox_syms_{}", std::process::id())); + let bin = root.join("Game").join("Binaries").join("XSX"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::create_dir_all(root.join("Symbols")).unwrap(); + let exe = bin.join("Title-XSX.exe"); + assert!(locate(&exe).is_none()); + assert!(load(&exe, &["A"]).unwrap_err().contains("no Title-XSX-Symbols.bin")); + std::fs::write(root.join("Symbols").join("Title-XSX-Symbols.bin"), build_for_test("Title-XSX", &[("A", 0x10, 0x20)])).unwrap(); + assert_eq!(load(&exe, &["A"]).unwrap().get("A"), Some(Sym { rva: 0x10, size: 0x20 })); + std::fs::write(bin.join("Title-XSX-Symbols.bin"), build_for_test("SomethingElse", &[("A", 0x10, 0x20)])).unwrap(); + assert!(load(&exe, &["A"]).unwrap_err().contains("not Title-XSX")); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + #[ignore] + fn cost_of_loading_the_dump_symbols() { + let Ok(path) = std::env::var("TOMBOX_FN_DUMP_EXE") else { return }; + let wanted = all_wanted(); + let (t, cost) = measured(|| load(Path::new(&path), &wanted)); + let t = t.unwrap(); + let overloaded: Vec<&str> = wanted.iter().copied().filter(|w| t.all(w).len() > 1).collect(); + eprintln!("symbols_cost total={} unique={}/{} overloaded={overloaded:?} ms={} peak_private_delta_kb={}", t.total, t.unique_found(), wanted.len(), cost.ms, cost.peak_private_delta / 1024); + assert!(wanted.iter().all(|w| !t.all(w).is_empty())); + } +} diff --git a/crates/compat/compat-common/tests/gdk_fs_redirect.rs b/crates/compat/compat-common/tests/gdk_fs_redirect.rs new file mode 100644 index 00000000..45d0f644 --- /dev/null +++ b/crates/compat/compat-common/tests/gdk_fs_redirect.rs @@ -0,0 +1,240 @@ +use std::sync::OnceLock; + +extern "system" { + fn LoadLibraryW(n: *const u16) -> usize; + fn GetProcAddress(m: usize, n: *const u8) -> usize; +} + +fn real(name: &str) -> usize { + real_in("kernel32.dll", name) +} + +fn real_in(dll: &str, name: &str) -> usize { + let k: Vec = dll.encode_utf16().chain([0]).collect(); + let n: Vec = name.bytes().chain([0]).collect(); + let f = unsafe { GetProcAddress(LoadLibraryW(k.as_ptr()), n.as_ptr()) }; + assert_ne!(f, 0, "{name}"); + f +} + +const PREFIX: &str = "\\\\?\\GlobalRoot\\Device\\Harddisk0\\Partition9\\"; + +fn root() -> &'static std::path::PathBuf { + static R: OnceLock = OnceLock::new(); + R.get_or_init(|| { + let d = std::env::temp_dir().join(format!("tombox_fs_redirect_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + }) +} + +unsafe extern "system" fn resolve(p: *const u16, out: *mut u16, cap: u32) -> u32 { + let mut n = 0; + while *p.add(n) != 0 { + n += 1; + } + let s = String::from_utf16_lossy(core::slice::from_raw_parts(p, n)); + if s.len() < PREFIX.len() || !s[..PREFIX.len()].eq_ignore_ascii_case(PREFIX) { + return 0; + } + let t: Vec = root().join(&s[PREFIX.len()..]).to_string_lossy().encode_utf16().collect(); + if t.len() as u32 >= cap { + return t.len() as u32 + 1; + } + core::ptr::copy_nonoverlapping(t.as_ptr(), out, t.len()); + *out.add(t.len()) = 0; + t.len() as u32 +} + +fn w(s: &str) -> Vec { + s.encode_utf16().chain([0]).collect() +} + +fn console(name: &str) -> Vec { + w(&format!("{PREFIX}{name}")) +} + +fn console_a(name: &str) -> Vec { + format!("{PREFIX}{name}").bytes().chain([0]).collect() +} + +fn hook(name: &str, real: usize) -> usize { + compat_common::gdk::xcrd_paths::register(resolve as *const () as usize); + let t = compat_common::gdk::fs::targets(); + let (_, h, orig) = t.iter().find(|r| r.0 == name).unwrap_or_else(|| panic!("{name} is not redirected")); + orig.store(real, std::sync::atomic::Ordering::Release); + *h +} + +fn put(name: &str, body: &[u8]) { + std::fs::write(root().join(name), body).unwrap(); +} + +fn get(name: &str) -> Option> { + std::fs::read(root().join(name)).ok() +} + +#[test] +fn copy_move_and_replace_calls_follow_the_console_path_like_create_file() { + unsafe { + put("a.bin", b"one"); + let f: unsafe extern "system" fn(*const u16, *const u16, i32) -> i32 = core::mem::transmute(hook("CopyFileW", real("CopyFileW"))); + assert_ne!(f(console("a.bin").as_ptr(), console("b.bin").as_ptr(), 1), 0); + assert_eq!(get("b.bin").as_deref(), Some(&b"one"[..])); + + let f: unsafe extern "system" fn(*const u16, *const u16, usize, usize, usize, u32) -> i32 = core::mem::transmute(hook("CopyFileExW", real("CopyFileExW"))); + assert_ne!(f(console("a.bin").as_ptr(), console("c.bin").as_ptr(), 0, 0, 0, 0), 0); + assert_eq!(get("c.bin").as_deref(), Some(&b"one"[..])); + + let f: unsafe extern "system" fn(*const u16, *const u16, usize) -> i32 = core::mem::transmute(hook("CopyFile2", real("CopyFile2"))); + assert_eq!(f(console("a.bin").as_ptr(), console("d.bin").as_ptr(), 0), 0); + assert_eq!(get("d.bin").as_deref(), Some(&b"one"[..])); + + let f: unsafe extern "system" fn(*const u16, *const u16, u32) -> i32 = core::mem::transmute(hook("MoveFileExW", real("MoveFileExW"))); + assert_ne!(f(console("b.bin").as_ptr(), console("e.bin").as_ptr(), 0), 0); + assert!(get("b.bin").is_none()); + assert_eq!(get("e.bin").as_deref(), Some(&b"one"[..])); + + let f: unsafe extern "system" fn(*const u16, *const u16, usize, usize, u32) -> i32 = core::mem::transmute(hook("MoveFileWithProgressW", real("MoveFileWithProgressW"))); + assert_ne!(f(console("c.bin").as_ptr(), console("f.bin").as_ptr(), 0, 0, 0), 0); + assert!(get("c.bin").is_none()); + assert_eq!(get("f.bin").as_deref(), Some(&b"one"[..])); + + put("new.bin", b"two"); + let f: unsafe extern "system" fn(*const u16, *const u16, *const u16, u32, usize, usize) -> i32 = core::mem::transmute(hook("ReplaceFileW", real("ReplaceFileW"))); + assert_ne!(f(console("f.bin").as_ptr(), console("new.bin").as_ptr(), console("bak.bin").as_ptr(), 0, 0, 0), 0); + assert_eq!(get("f.bin").as_deref(), Some(&b"two"[..])); + assert_eq!(get("bak.bin").as_deref(), Some(&b"one"[..])); + assert!(get("new.bin").is_none()); + + put("new2.bin", b"three"); + assert_ne!(f(console("f.bin").as_ptr(), console("new2.bin").as_ptr(), core::ptr::null(), 0, 0, 0), 0); + assert_eq!(get("f.bin").as_deref(), Some(&b"three"[..])); + } +} + +#[test] +fn ansi_and_crt_path_calls_follow_the_console_path_too() { + unsafe { + type A1 = unsafe extern "system" fn(*const u8) -> i32; + type A2 = unsafe extern "system" fn(*const u8, usize) -> i32; + let f: unsafe extern "system" fn(*const u8, usize) -> i32 = core::mem::transmute(hook("CreateDirectoryA", real("CreateDirectoryA"))); + assert_ne!(f(console_a("da").as_ptr(), 0), 0); + assert!(root().join("da").is_dir()); + + let f: unsafe extern "system" fn(*const u8, u32, u32, usize, u32, u32, usize) -> isize = core::mem::transmute(hook("CreateFileA", real("CreateFileA"))); + let h = f(console_a("da\\fa.bin").as_ptr(), 0x4000_0000, 0, 0, 2, 0x80, 0); + assert_ne!(h, -1); + let close: unsafe extern "system" fn(isize) -> i32 = core::mem::transmute(real("CloseHandle")); + close(h); + assert!(root().join("da").join("fa.bin").is_file()); + + let f: unsafe extern "system" fn(*const u8, u32) -> i32 = core::mem::transmute(hook("SetFileAttributesA", real("SetFileAttributesA"))); + assert_ne!(f(console_a("da\\fa.bin").as_ptr(), 0x80), 0); + + let mut data = [0u8; 600]; + let f: unsafe extern "system" fn(*const u8, u32, *mut u8, u32, usize, u32) -> isize = core::mem::transmute(hook("FindFirstFileExA", real("FindFirstFileExA"))); + let fh = f(console_a("da\\*.bin").as_ptr(), 0, data.as_mut_ptr(), 0, 0, 0); + assert_ne!(fh, -1); + let fclose: unsafe extern "system" fn(isize) -> i32 = core::mem::transmute(real("FindClose")); + fclose(fh); + assert_eq!(&data[44..50], b"fa.bin"); + + let f: A1 = core::mem::transmute(hook("DeleteFileA", real("DeleteFileA"))); + assert_ne!(f(console_a("da\\fa.bin").as_ptr()), 0); + assert!(!root().join("da").join("fa.bin").exists()); + + let crt = |n: &str| real_in("ucrtbase.dll", n); + let f: A1 = core::mem::transmute(hook("_mkdir", crt("_mkdir"))); + assert_eq!(f(console_a("db").as_ptr()), 0); + assert!(root().join("db").is_dir()); + + let f: unsafe extern "system" fn(*const u8, i32, i32) -> i32 = core::mem::transmute(hook("_open", crt("_open"))); + let fd = f(console_a("db\\o.bin").as_ptr(), 0x0100 | 0x0001 | 0x8000, 0x0180); + assert!(fd >= 0); + let cl: unsafe extern "system" fn(i32) -> i32 = core::mem::transmute(crt("_close")); + cl(fd); + assert!(root().join("db").join("o.bin").is_file()); + + let f: A2 = core::mem::transmute(hook("_access", crt("_access"))); + assert_eq!(f(console_a("db\\o.bin").as_ptr(), 0), 0); + + let mut st = [0u8; 64]; + let f: A2 = core::mem::transmute(hook("_stat64", crt("_stat64"))); + assert_eq!(f(console_a("db\\o.bin").as_ptr(), st.as_mut_ptr() as usize), 0); + + let f: unsafe extern "system" fn(*const u8, *const u8) -> i32 = core::mem::transmute(hook("rename", crt("rename"))); + assert_eq!(f(console_a("db\\o.bin").as_ptr(), console_a("db\\r.bin").as_ptr()), 0); + assert!(root().join("db").join("r.bin").is_file()); + + let f: unsafe extern "system" fn(*const u16, *const u16) -> i32 = core::mem::transmute(hook("_wrename", crt("_wrename"))); + assert_eq!(f(console("db\\r.bin").as_ptr(), console("db\\s.bin").as_ptr()), 0); + assert!(root().join("db").join("s.bin").is_file()); + + let f: unsafe extern "system" fn(*const u16, usize) -> i32 = core::mem::transmute(hook("_wstat64", crt("_wstat64"))); + assert_eq!(f(console("db\\s.bin").as_ptr(), st.as_mut_ptr() as usize), 0); + + let mut fp = 0usize; + let mode = w("rb"); + let f: unsafe extern "system" fn(*mut usize, *const u16, *const u16) -> i32 = core::mem::transmute(hook("_wfopen_s", crt("_wfopen_s"))); + assert_eq!(f(&mut fp, console("db\\s.bin").as_ptr(), mode.as_ptr()), 0); + let fc: unsafe extern "system" fn(usize) -> i32 = core::mem::transmute(crt("fclose")); + fc(fp); + + let f: unsafe extern "system" fn(*const u16) -> i32 = core::mem::transmute(hook("_wremove", crt("_wremove"))); + assert_eq!(f(console("db\\s.bin").as_ptr()), 0); + assert!(!root().join("db").join("s.bin").exists()); + + let f: unsafe extern "system" fn(*const u16, i32, i32) -> i32 = core::mem::transmute(hook("_wopen", crt("_wopen"))); + let fd = f(console("db\\wo.bin").as_ptr(), 0x0100 | 0x0001 | 0x8000, 0x0180); + assert!(fd >= 0); + cl(fd); + assert!(root().join("db").join("wo.bin").is_file()); + + let errno: unsafe extern "system" fn() -> *mut i32 = core::mem::transmute(crt("_errno")); + let gle: unsafe extern "system" fn() -> u32 = core::mem::transmute(real("GetLastError")); + let sle: unsafe extern "system" fn(u32) = core::mem::transmute(real("SetLastError")); + let pc = root().join("db").join("wo.bin").to_string_lossy().into_owned(); + let pc_a: Vec = pc.bytes().chain([0]).collect(); + let missing_a: Vec = root().join("nope").join("x.bin").to_string_lossy().bytes().chain([0]).collect(); + let rel_a = b"tombox_no_such_relative_file.bin\0"; + let empty_a = b"\0"; + + let f: A2 = core::mem::transmute(hook("_access", crt("_access"))); + assert_eq!(f(pc_a.as_ptr(), 0), 0); + for p in [&missing_a[..], &rel_a[..], &empty_a[..]] { + *errno() = 0; + assert_eq!(f(p.as_ptr(), 0), -1, "{p:?}"); + assert_eq!(*errno(), 2, "{p:?}"); + } + let f: A2 = core::mem::transmute(hook("_stat64", crt("_stat64"))); + assert_eq!(f(pc_a.as_ptr(), st.as_mut_ptr() as usize), 0); + for p in [&missing_a[..], &rel_a[..], &empty_a[..]] { + *errno() = 0; + assert_eq!(f(p.as_ptr(), st.as_mut_ptr() as usize), -1, "{p:?}"); + assert_eq!(*errno(), 2, "{p:?}"); + } + let f: unsafe extern "system" fn(*const u8, u32, u32, usize, u32, u32, usize) -> isize = core::mem::transmute(hook("CreateFileA", real("CreateFileA"))); + let h = f(pc_a.as_ptr(), 0x8000_0000, 1, 0, 3, 0x80, 0); + assert_ne!(h, -1); + close(h); + for (p, want) in [(&missing_a[..], 3u32), (&rel_a[..], 2), (&empty_a[..], 3)] { + sle(0); + assert_eq!(f(p.as_ptr(), 0x8000_0000, 1, 0, 3, 0x80, 0), -1, "{p:?}"); + assert_eq!(gle(), want, "{p:?}"); + } + + static SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + unsafe extern "system" fn spy(p: *const u8, _m: usize) -> i32 { + SEEN.store(p as usize, std::sync::atomic::Ordering::SeqCst); + -7 + } + let f: A2 = core::mem::transmute(hook("_access", spy as *const () as usize)); + for p in [&pc_a[..], &missing_a[..], &rel_a[..], &empty_a[..]] { + assert_eq!(f(p.as_ptr(), 0), -7); + assert_eq!(SEEN.load(std::sync::atomic::Ordering::SeqCst), p.as_ptr() as usize, "{p:?}"); + } + hook("_access", crt("_access")); + } +} diff --git a/crates/compat/compat-common/tests/gdk_save.rs b/crates/compat/compat-common/tests/gdk_save.rs index 26e79678..81cf98f3 100644 --- a/crates/compat/compat-common/tests/gdk_save.rs +++ b/crates/compat/compat-common/tests/gdk_save.rs @@ -254,3 +254,62 @@ fn async_read_all_blobs_and_empty_container() { let _ = std::fs::remove_dir_all(root); } } + +#[test] +fn names_that_are_not_windows_file_names_round_trip() { + let st = save::Store::open(tmp("names")).unwrap(); + let long_ascii = "n".repeat(256); + let long_wide = "\u{00e9}".repeat(128); + let names: Vec = ["ab", "a:b", "a\"b", "a/b", "a\\b", "a|b", "a?b", "a*b", "CON", "nul", "Com1", "LPT9.txt", "AUX.", "end.", "end ", " lead", ".hidden", "..", ".", "~7E", "~", "tab\tnl\n", "\u{00dc}n\u{00ef}c\u{00f6}d\u{00e9}", "a.b.c"] + .iter() + .map(|s| s.to_string()) + .chain([long_ascii.clone(), long_wide.clone()]) + .collect(); + let writes: Vec<(String, Vec)> = names.iter().enumerate().map(|(i, n)| (n.clone(), vec![i as u8; i + 1])).collect(); + let containers = ["CON".to_string(), "slot:1".into(), "end.".into(), long_ascii.clone()]; + for c in &containers { + st.commit(c, Some("d"), &writes, &[]).unwrap_or_else(|e| panic!("commit to container {c:?}: {e}")); + let mut got: Vec = st.blobs(c).into_iter().map(|b| b.0).collect(); + got.sort(); + let mut want = names.clone(); + want.sort(); + assert_eq!(got, want, "container {c:?}"); + for (i, n) in names.iter().enumerate() { + assert_eq!(st.read_blob(c, n), Some(vec![i as u8; i + 1]), "blob {n:?} in {c:?}"); + } + } + let mut cs: Vec = st.containers().into_iter().map(|c| c.name).collect(); + cs.sort(); + let mut want = containers.to_vec(); + want.sort(); + assert_eq!(cs, want); + st.commit("CON", None, &[], &names[..3].to_vec()).unwrap(); + assert_eq!(st.blobs("CON").len(), names.len() - 3); + assert!(st.delete_container("end.").unwrap()); +} + +#[test] +fn long_names_keep_their_case_and_fit_the_file_name_limit() { + let root = tmp("long"); + let st = save::Store::open(root.clone()).unwrap(); + let upper = "N".repeat(300); + let lower = "n".repeat(300); + st.commit(&upper, None, &[(upper.clone(), b"x".to_vec())], &[]).unwrap(); + assert_eq!(st.read_blob(&lower, &lower), Some(b"x".to_vec())); + assert_eq!(st.blobs(&upper), vec![(upper.clone(), 1)]); + assert_eq!(st.containers().into_iter().map(|c| c.name).collect::>(), vec![upper.clone()]); + fn walk(p: &std::path::Path) { + for e in std::fs::read_dir(p).unwrap().flatten() { + assert!(e.file_name().len() <= 255, "{:?}", e.file_name()); + if e.path().is_dir() { + walk(&e.path()); + } + } + } + walk(&root); + st.commit(&upper, None, &[], &[upper.clone()]).unwrap(); + assert!(st.blobs(&upper).is_empty()); + let d = std::fs::read_dir(&root).unwrap().flatten().next().unwrap().path(); + let left: Vec = std::fs::read_dir(&d).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(left, vec![".name".to_string()]); +} diff --git a/crates/compat/compat-common/tests/gdk_user_events.rs b/crates/compat/compat-common/tests/gdk_user_events.rs new file mode 100644 index 00000000..6bd629c6 --- /dev/null +++ b/crates/compat/compat-common/tests/gdk_user_events.rs @@ -0,0 +1,224 @@ +use compat_common::gdk::{self, events::Registry, user, xasync, Guid}; +use core::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::SeqCst}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +const MANUAL: u32 = 0; +const POOL: u32 = 1; +const COMPLETION: u32 = 1; + +fn xa() -> usize { + let mut o: *mut c_void = core::ptr::null_mut(); + assert_eq!(unsafe { gdk::query_api_impl(&xasync::XASYNC, &xasync::XASYNC, &mut o) }, 0); + o as usize +} + +unsafe fn slot(obj: usize, n: usize) -> usize { + *(*(obj as *const *const usize)).add(n) +} + +fn manual_completion_queue() -> usize { + let a = xa(); + let mut q = 0usize; + let f: unsafe extern "system" fn(usize, u32, u32, *mut usize) -> i32 = unsafe { core::mem::transmute(slot(a, 12)) }; + assert_eq!(unsafe { f(a, POOL, MANUAL, &mut q) }, 0); + assert_ne!(q, 0); + q +} + +fn dispatch(q: usize, timeout: u32) -> bool { + let a = xa(); + let f: unsafe extern "system" fn(usize, usize, u32, u32) -> bool = unsafe { core::mem::transmute(slot(a, 16)) }; + unsafe { f(a, q, COMPLETION, timeout) } +} + +fn drain(q: usize) -> usize { + let mut n = 0; + while dispatch(q, 0) { + n += 1; + } + n +} + +fn iface(clsid: Guid, iid: Guid) -> usize { + let mut o: *mut c_void = core::ptr::null_mut(); + assert_eq!(unsafe { gdk::query_api_impl(&clsid, &iid, &mut o) }, 0); + o as usize +} + +type Register = unsafe extern "system" fn(usize, usize, *mut c_void, usize, *mut u64) -> i32; +type Unregister = unsafe extern "system" fn(usize, u64, bool) -> bool; + +static EVENTS: Mutex> = Mutex::new(Vec::new()); + +unsafe extern "system" fn on_change(ctx: *mut c_void, local: u64, event: u32) { + EVENTS.lock().unwrap().push((ctx as usize, local, event)); +} + +#[test] +fn user_change_events_reach_the_registered_callback_in_order_and_stop_after_unregister() { + let q = manual_completion_queue(); + let u = iface(user::CLSID, user::IID_V2); + unsafe { + let reg: Register = core::mem::transmute(slot(u, 33)); + let unreg: Unregister = core::mem::transmute(slot(u, 34)); + let state: unsafe extern "system" fn(usize, usize, *mut u32) -> i32 = core::mem::transmute(slot(u, 14)); + let mut token = 0u64; + assert_eq!(reg(u, q, 0x5150 as *mut c_void, on_change as *const () as usize, &mut token), 0); + assert_ne!(token, 0); + let mut st = 9u32; + assert_eq!(state(u, 1, &mut st), 0); + assert_eq!(st, user::STATE_SIGNED_IN); + + assert!(user::sign_out()); + assert!(!user::sign_out()); + assert_eq!(state(u, 1, &mut st), 0); + assert_eq!(st, user::STATE_SIGNED_OUT); + assert_eq!(drain(q), 2); + assert!(user::sign_in()); + assert_eq!(drain(q), 1); + assert_eq!(state(u, 1, &mut st), 0); + assert_eq!(st, user::STATE_SIGNED_IN); + let got: Vec<_> = EVENTS.lock().unwrap().drain(..).collect(); + assert_eq!(got, vec![(0x5150, user::LOCAL_ID, user::EVENT_SIGNING_OUT), (0x5150, user::LOCAL_ID, user::EVENT_SIGNED_OUT), (0x5150, user::LOCAL_ID, user::EVENT_SIGNED_IN_AGAIN)]); + + user::fire_change(user::EVENT_GAMERTAG); + assert!(unreg(u, token, false)); + assert!(!unreg(u, token, false)); + drain(q); + assert!(EVENTS.lock().unwrap().is_empty(), "a callback queued before unregister must not run after it"); + user::fire_change(user::EVENT_PRIVILEGES); + assert_eq!(drain(q), 0); + assert!(EVENTS.lock().unwrap().is_empty()); + } +} + +static ASSOC: Mutex> = Mutex::new(Vec::new()); + +#[repr(C)] +struct Assoc { + device: [u8; 32], + old_user: u64, + new_user: u64, +} + +unsafe extern "system" fn on_assoc(ctx: *mut c_void, c: *const Assoc) { + ASSOC.lock().unwrap().push(((*c).device, (*c).old_user, (*c).new_user, ctx as usize)); +} + +static AUDIO: Mutex> = Mutex::new(Vec::new()); + +unsafe fn wide(p: *const u16) -> String { + let mut n = 0; + while *p.add(n) != 0 { + n += 1; + } + String::from_utf16_lossy(core::slice::from_raw_parts(p, n)) +} + +unsafe extern "system" fn on_audio(_ctx: *mut c_void, local: u64, kind: u32, old: *const u16, new: *const u16) { + AUDIO.lock().unwrap().push((local, kind, wide(old), wide(new))); +} + +#[test] +fn device_association_and_audio_endpoint_registrations_deliver_their_payloads() { + let q = manual_completion_queue(); + let d = iface(user::DEVICE, user::DEVICE_V2); + unsafe { + let reg_a: Register = core::mem::transmute(slot(d, 4)); + let unreg_a: Unregister = core::mem::transmute(slot(d, 5)); + let reg_e: Register = core::mem::transmute(slot(d, 7)); + let unreg_e: Unregister = core::mem::transmute(slot(d, 8)); + let (mut ta, mut te) = (0u64, 0u64); + assert_eq!(reg_a(d, q, 7 as *mut c_void, on_assoc as *const () as usize, &mut ta), 0); + assert_eq!(reg_e(d, q, core::ptr::null_mut(), on_audio as *const () as usize, &mut te), 0); + assert_eq!(reg_a(d, q, core::ptr::null_mut(), 0, &mut ta), gdk::E_INVALIDARG); + let mut dev = [0u8; 32]; + dev[0] = 0xab; + dev[31] = 0xcd; + assert_eq!(user::fire_device_association(dev, 0, user::LOCAL_ID), 1); + assert_eq!(user::fire_audio_endpoint(1, "old-ep", "new-ep"), 1); + assert_eq!(drain(q), 2); + assert_eq!(*ASSOC.lock().unwrap(), vec![(dev, 0, user::LOCAL_ID, 7)]); + assert_eq!(*AUDIO.lock().unwrap(), vec![(user::LOCAL_ID, 1, "old-ep".to_string(), "new-ep".to_string())]); + assert!(unreg_a(d, ta, true)); + assert!(unreg_e(d, te, true)); + assert_eq!(user::fire_device_association(dev, user::LOCAL_ID, 0), 0); + assert_eq!(drain(q), 0); + } +} + +static WAITED: Registry = Registry::new(); + +#[test] +fn unregister_with_wait_blocks_until_a_running_callback_returns() { + let started = Box::leak(Box::new(AtomicBool::new(false))); + let finished = Box::leak(Box::new(AtomicBool::new(false))); + let mut token = 0u64; + unsafe { + assert_eq!(WAITED.register(0, 0, core::ptr::null_mut(), 1, &mut token), 0); + } + let (s, f) = (&*started, &*finished); + assert_eq!( + WAITED.fire_token(token, move |_| { + s.store(true, SeqCst); + std::thread::sleep(Duration::from_millis(300)); + f.store(true, SeqCst); + }), + 0 + ); + let t0 = Instant::now(); + while !started.load(SeqCst) { + assert!(t0.elapsed() < Duration::from_secs(5), "callback never started"); + std::thread::yield_now(); + } + assert_eq!(WAITED.in_flight(token), 1); + assert!(WAITED.unregister(None, token, true)); + assert!(finished.load(SeqCst), "unregister(wait=true) returned while the callback was still running"); + assert_eq!(WAITED.in_flight(token), 0); +} + +static NOWAIT: Registry = Registry::new(); + +#[test] +fn unregister_without_wait_returns_while_the_callback_runs_and_a_callback_may_unregister_itself() { + let finished = Box::leak(Box::new(AtomicBool::new(false))); + let started = Box::leak(Box::new(AtomicBool::new(false))); + let mut token = 0u64; + unsafe { + assert_eq!(NOWAIT.register(0, 0, core::ptr::null_mut(), 1, &mut token), 0); + } + let (s, f) = (&*started, &*finished); + NOWAIT.fire_token(token, move |_| { + s.store(true, SeqCst); + std::thread::sleep(Duration::from_millis(300)); + f.store(true, SeqCst); + }); + let t0 = Instant::now(); + while !started.load(SeqCst) { + assert!(t0.elapsed() < Duration::from_secs(5)); + std::thread::yield_now(); + } + assert!(NOWAIT.unregister(None, token, false)); + assert!(!finished.load(SeqCst)); + while !finished.load(SeqCst) { + assert!(t0.elapsed() < Duration::from_secs(5)); + std::thread::yield_now(); + } + + static SELF_DONE: AtomicU32 = AtomicU32::new(0); + let mut t2 = 0u64; + unsafe { + assert_eq!(NOWAIT.register(0, 0, core::ptr::null_mut(), 1, &mut t2), 0); + } + NOWAIT.fire_token(t2, move |r| { + let removed = NOWAIT.unregister(None, r.token, true); + SELF_DONE.store(if removed { 1 } else { 2 }, SeqCst); + }); + while SELF_DONE.load(SeqCst) == 0 { + assert!(t0.elapsed() < Duration::from_secs(5), "a callback unregistering itself with wait=true deadlocked"); + std::thread::yield_now(); + } + assert_eq!(SELF_DONE.load(SeqCst), 1); +} diff --git a/crates/compat/compat-common/tests/gdk_xtaskqueue_conformance.rs b/crates/compat/compat-common/tests/gdk_xtaskqueue_conformance.rs new file mode 100644 index 00000000..27eb73de --- /dev/null +++ b/crates/compat/compat-common/tests/gdk_xtaskqueue_conformance.rs @@ -0,0 +1,50 @@ +use compat_common::gdk::{self, xasync}; +use std::sync::OnceLock; + +#[macro_use] +#[path = "support/xtq.rs"] +mod xtq; + +const DIFFERS: &[(&str, &str)] = &[ + ("verify_cancellation", "XAsyncCancel completes the call itself with E_ABORT, reference leaves it pending until the provider completes it"), + ("verify_cleanup_waits_for_work", "XAsyncCancel completes the call itself with E_ABORT, reference leaves it pending until the provider completes it"), + ("verify_cleanup_waits_for_work_distributed", "XAsyncCancel completes the call itself with E_ABORT, reference leaves it pending until the provider completes it"), + ("verify_close_keeps_queued_callbacks", "closing the handle cancels the 21 queued callbacks, reference runs all 21"), + ("verify_dispatch_on_pool_port", "XTaskQueueDispatch on a thread-pool port with a queued item returns false"), + ("verify_duplicate_queue_handle", "XTaskQueueDuplicateHandle returns the same handle, reference a new one"), + ("verify_get_async_status_no_deadlock", "does not finish: a call begun on a block whose previous call has just completed can lose its state"), + ("verify_multithread_manual_dispatch", "terminating the queue does not release XTaskQueueDispatch(INFINITE)"), + ("verify_no_write_after_get_status_race", "under load, intermittent: the async block is written after XAsyncGetStatus(wait) has returned"), + ("verify_queue_monitor_has_correct_ports", "the base queue monitor does not report its port for a shared port"), + ("verify_queue_termination", "XTaskQueueRegisterWaiter returns E_NOTIMPL"), + ("verify_register_with_auto_reset", "XTaskQueueRegisterWaiter returns E_NOTIMPL"), + ("verify_shared_port_queue_rundown_drops_its_wait_handles", "XTaskQueueRegisterWaiter returns E_NOTIMPL"), + ("verify_shared_port_queue_rundown_keeps_other_waiters", "XTaskQueueRegisterWaiter returns E_NOTIMPL"), + ("verify_terminate_waits_for_async_in_flight", "termination finishes while an XAsync call on the queue is still pending"), + ("verify_termination_of_base_queue_keeps_composites", "the composite's pending callback runs canceled, reference runs it normally"), + ("verify_termination_of_composite_queue", "XTaskQueueRegisterWaiter returns E_NOTIMPL"), + ("verify_thread_pool_callbacks_can_block", "24 blocking thread-pool callbacks cannot all run at once"), + ("verify_wait_for_completion", "intermittent: XAsyncGetStatus(wait) on a completed call with a result returns before the completion callback has finished"), +]; + +fn setup(scenario: &str) -> bool { + if let Some((_, what)) = DIFFERS.iter().find(|(n, _)| *n == scenario) { + if std::env::var("TOMBOX_XTQ_ALL").as_deref() != Ok("1") { + eprintln!("SKIP: {scenario}: {what}"); + return false; + } + } + static READY: OnceLock = OnceLock::new(); + *READY.get_or_init(|| { + std::env::set_var("TOMBOX_GDK_XASYNC", "emulated"); + std::env::set_var("TOMBOX_GDK_ROOT", std::env::temp_dir().join(format!("tombox_gdk_xtq_{}", std::process::id()))); + assert!(gdk::rt::active()); + let mut obj = core::ptr::null_mut(); + assert_eq!(unsafe { gdk::query_api_impl(&xasync::XASYNC, &xasync::XASYNC, &mut obj) }, 0); + xtq::install(obj); + xtq::set_console_model(true); + true + }) +} + +xtq_tests!(setup); diff --git a/crates/compat/compat-common/tests/gdk_xtaskqueue_conformance_real.rs b/crates/compat/compat-common/tests/gdk_xtaskqueue_conformance_real.rs new file mode 100644 index 00000000..e105637a --- /dev/null +++ b/crates/compat/compat-common/tests/gdk_xtaskqueue_conformance_real.rs @@ -0,0 +1,50 @@ +use core::ffi::c_void; +use std::sync::OnceLock; + +#[macro_use] +#[path = "support/xtq.rs"] +mod xtq; + +extern "system" { + fn LoadLibraryExW(name: *const u16, file: *mut c_void, flags: u32) -> *mut c_void; + fn GetProcAddress(h: *mut c_void, name: *const u8) -> *mut c_void; +} + +#[repr(C)] +struct Guid(u32, u16, u16, [u8; 8]); +const XASYNC: Guid = Guid(0x073b7dcb, 0x1fcf, 0x4030, [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28]); + +const NEWER_THAN_RUNTIME: &[&str] = &[ + "verify_shared_port_queue_rundown_keeps_other_waiters", + "verify_shared_port_queue_rundown_drops_its_wait_handles", + "verify_serialized_thread_pool_does_not_strand_items", +]; + +fn setup(scenario: &str) -> bool { + if NEWER_THAN_RUNTIME.contains(&scenario) { + eprintln!("SKIP: {scenario} checks a libHttpClient fix newer than the installed runtime"); + return false; + } + static READY: OnceLock = OnceLock::new(); + *READY.get_or_init(|| unsafe { + let name: Vec = "xgameruntime.dll".encode_utf16().chain(Some(0)).collect(); + let h = LoadLibraryExW(name.as_ptr(), core::ptr::null_mut(), 0x800); + if h.is_null() { + eprintln!("SKIP: no System32 xgameruntime.dll (Gaming Services not installed)"); + return false; + } + let init: unsafe extern "system" fn(u32, u32) -> i32 = core::mem::transmute(GetProcAddress(h, b"InitializeApiImpl\0".as_ptr())); + let hr = init(0x4a61, 0x2712); + if hr < 0 { + eprintln!("SKIP: InitializeApiImpl failed hr={hr:#010x}"); + return false; + } + let query: unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> i32 = core::mem::transmute(GetProcAddress(h, b"QueryApiImpl\0".as_ptr())); + let mut obj = core::ptr::null_mut(); + assert_eq!(query(&XASYNC, &XASYNC, &mut obj), 0); + xtq::install(obj); + true + }) +} + +xtq_tests!(setup); diff --git a/crates/compat/compat-common/tests/os_host.rs b/crates/compat/compat-common/tests/os_host.rs index 0d5eea8c..87f68566 100644 --- a/crates/compat/compat-common/tests/os_host.rs +++ b/crates/compat/compat-common/tests/os_host.rs @@ -334,7 +334,8 @@ fn windows_modules_are_never_patched() { #[test] fn late_load_notification_patches_a_title_module() { let mut img = synthetic_pe(); - let path: Vec = "G:\\Data\\Plugins\\Fake.dll".encode_utf16().collect(); + let game = std::env::current_exe().unwrap().parent().unwrap().to_string_lossy().into_owned(); + let path: Vec = format!("{game}\\Data\\Plugins\\Fake.dll").encode_utf16().collect(); let mut us = [0u8; 16]; us[0..2].copy_from_slice(&((path.len() * 2) as u16).to_le_bytes()); us[2..4].copy_from_slice(&((path.len() * 2) as u16).to_le_bytes()); @@ -361,6 +362,15 @@ fn late_load_notification_patches_a_title_module() { unsafe { compat_common::os_host::dll_loaded(1, data.as_ptr(), core::ptr::null_mut()) }; assert_eq!(rd(&sys, 0x500), 0); assert_eq!(rd(&sys, 0x800), 0x1234); + let mut overlay = synthetic_pe(); + let opath: Vec = "C:\\Users\\someone\\AppData\\Local\\Discord\\app-1.0.9\\modules\\discord_hook\\DiscordHook64.dll".encode_utf16().collect(); + us[0..2].copy_from_slice(&((opath.len() * 2) as u16).to_le_bytes()); + us[2..4].copy_from_slice(&((opath.len() * 2) as u16).to_le_bytes()); + us[8..16].copy_from_slice(&(opath.as_ptr() as u64).to_le_bytes()); + data[24..32].copy_from_slice(&(overlay.as_mut_ptr() as u64).to_le_bytes()); + unsafe { compat_common::os_host::dll_loaded(1, data.as_ptr(), core::ptr::null_mut()) }; + assert_eq!(rd(&overlay, 0x500), 0, "a host-injected overlay keeps its native imports"); + assert_eq!(rd(&overlay, 0x800), 0x1234); } #[test] diff --git a/crates/compat/compat-common/tests/pad_host.rs b/crates/compat/compat-common/tests/pad_host.rs new file mode 100644 index 00000000..aefce4bb --- /dev/null +++ b/crates/compat/compat-common/tests/pad_host.rs @@ -0,0 +1,82 @@ +use compat_common::gamepad::{published, PadState, AX_LY}; +use core::ffi::c_void; +use std::time::{Duration, Instant}; + +#[link(name = "user32")] +extern "system" { + fn CreateWindowExW(ex: u32, cls: *const u16, name: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, inst: *mut c_void, p: *mut c_void) -> *mut c_void; + fn DestroyWindow(h: *mut c_void) -> i32; + fn SetForegroundWindow(h: *mut c_void) -> i32; + fn GetForegroundWindow() -> *mut c_void; + fn SendInput(n: u32, inputs: *const Input, size: i32) -> u32; + fn PeekMessageW(m: *mut [u8; 48], h: *mut c_void, lo: u32, hi: u32, flags: u32) -> i32; + fn DispatchMessageW(m: *const [u8; 48]) -> isize; +} + +#[repr(C)] +struct Input { + kind: u32, + align: u32, + vk: u16, + scan: u16, + flags: u32, + time: u32, + extra: usize, + pad: [u8; 8], +} + +fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() +} + +fn pump() { + let mut m = [0u8; 48]; + while unsafe { PeekMessageW(&mut m, core::ptr::null_mut(), 0, 0, 1) } != 0 { + unsafe { DispatchMessageW(&m) }; + } +} + +fn key(vk: u16, up: bool) { + let i = Input { kind: 1, align: 0, vk, scan: 0, flags: if up { 2 } else { 0 }, time: 0, extra: 0, pad: [0; 8] }; + assert_eq!(unsafe { SendInput(1, &i, core::mem::size_of::() as i32) }, 1); +} + +fn wait_for(f: impl Fn(PadState) -> bool) -> bool { + let t = Instant::now(); + while t.elapsed() < Duration::from_secs(2) { + pump(); + if f(published()) { + return true; + } + std::thread::sleep(Duration::from_millis(10)); + } + false +} + +#[test] +fn foreground_key_reaches_the_published_pad_reading() { + let mut log = std::env::temp_dir(); + log.push("tombox_pad_host_test.log"); + std::env::set_var("TOMBOX_LOG", log); + std::env::set_var("TOMBOX_PAD_XINPUT", "0"); + std::env::set_var("TOMBOX_PAD_KEYS", "auto"); + assert_eq!(core::mem::size_of::(), 40); + let (cls, name) = (wide("Static"), wide("tombox pad host test")); + let h = unsafe { CreateWindowExW(0, cls.as_ptr(), name.as_ptr(), 0x10CF_0000, 50, 50, 300, 120, core::ptr::null_mut(), core::ptr::null_mut(), core::ptr::null_mut(), core::ptr::null_mut()) }; + assert!(!h.is_null()); + unsafe { SetForegroundWindow(h) }; + pump(); + if unsafe { GetForegroundWindow() } != h { + eprintln!("skipped: this process cannot take the foreground (foreground lock), so no key is injected"); + unsafe { DestroyWindow(h) }; + return; + } + compat_common::pad_host::start(); + assert!(wait_for(|s| s == PadState::default()), "pad not neutral before any key: {:?}", published()); + key(0x57, false); + let pressed = wait_for(|s| s.axes[AX_LY] == 1.0); + key(0x57, true); + assert!(pressed, "W did not reach the left stick: {:?}", published()); + assert!(wait_for(|s| s == PadState::default()), "release not published: {:?}", published()); + unsafe { DestroyWindow(h) }; +} diff --git a/crates/compat/compat-common/tests/support/built_dlls.rs b/crates/compat/compat-common/tests/support/built_dlls.rs index 420a81c5..f808cd69 100644 --- a/crates/compat/compat-common/tests/support/built_dlls.rs +++ b/crates/compat/compat-common/tests/support/built_dlls.rs @@ -26,14 +26,21 @@ pub fn ensure(pkgs: &[(&str, &str)]) -> PathBuf { cmd.arg("build").current_dir(env!("CARGO_MANIFEST_DIR")); for (k, _) in std::env::vars_os() { let key = k.to_string_lossy().to_ascii_uppercase(); - let injected = (key.starts_with("CARGO_") && key != "CARGO_HOME") || key == "OUT_DIR" || key.starts_with("RUST_TEST") || key.starts_with("TOMBOX_"); + let dxc = key == "TOMBOX_DXC" || key == "TOMBOX_DXC_DIR"; + let injected = (key.starts_with("CARGO_") && key != "CARGO_HOME") || key == "OUT_DIR" || key.starts_with("RUST_TEST") || (key.starts_with("TOMBOX_") && !dxc); if injected { cmd.env_remove(&k); } } cmd.env("CARGO_TARGET_DIR", target_dir()); - if dir.file_name().and_then(|n| n.to_str()) == Some("release") { - cmd.arg("--release"); + match dir.file_name().and_then(|n| n.to_str()) { + Some("release") => { + cmd.arg("--release"); + } + Some("debug") | None => {} + Some(p) => { + cmd.arg("--profile").arg(p); + } } for p in &todo { cmd.arg("-p").arg(p); diff --git a/crates/compat/compat-common/tests/support/xtq.rs b/crates/compat/compat-common/tests/support/xtq.rs new file mode 100644 index 00000000..3ed79ac4 --- /dev/null +++ b/crates/compat/compat-common/tests/support/xtq.rs @@ -0,0 +1,2261 @@ +#![allow(dead_code)] + +use core::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicUsize, Ordering::SeqCst}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +pub const MANUAL: u32 = 0; +pub const THREAD_POOL: u32 = 1; +pub const SERIALIZED: u32 = 2; +pub const IMMEDIATE: u32 = 3; +pub const WORK: u32 = 0; +pub const COMPLETION: u32 = 1; +pub const INFINITE: u32 = u32::MAX; + +pub const E_ABORT: i32 = 0x8000_4004u32 as i32; +pub const E_FAIL: i32 = 0x8000_4005u32 as i32; +pub const E_PENDING: i32 = 0x8000_000Au32 as i32; +pub const E_UNEXPECTED: i32 = 0x8000_FFFFu32 as i32; +pub const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; +pub const E_ILLEGAL_METHOD_CALL: i32 = 0x8000_000Eu32 as i32; +pub const E_NOT_SUFFICIENT_BUFFER: i32 = 0x8007_007Au32 as i32; +pub const E_NO_TASK_QUEUE: i32 = 0x8007_01ABu32 as i32; +pub const E_ACCESSDENIED: i32 = 0x8007_0005u32 as i32; + +pub type TaskCb = unsafe extern "system" fn(*mut c_void, bool); +pub type MonitorCb = unsafe extern "system" fn(*mut c_void, usize, u32); +pub type TermCb = unsafe extern "system" fn(*mut c_void); +pub type Provider = unsafe extern "system" fn(u32, *const Data) -> i32; +pub type Completion = unsafe extern "system" fn(*mut Block); +pub type Work = unsafe extern "system" fn(*mut Block) -> i32; + +pub const OP_BEGIN: u32 = 0; +pub const OP_DO_WORK: u32 = 1; +pub const OP_GET_RESULT: u32 = 2; +pub const OP_CANCEL: u32 = 3; +pub const OP_CLEANUP: u32 = 4; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Block { + pub queue: usize, + pub context: usize, + pub callback: Option, + pub internal: [u8; 32], +} + +impl Block { + pub fn new(queue: usize) -> Box { + Box::new(Block { queue, context: 0, callback: None, internal: [0; 32] }) + } + fn bytes(&self) -> [u8; 56] { + unsafe { core::mem::transmute_copy(self) } + } +} + +#[repr(C)] +pub struct Data { + pub block: *mut Block, + pub size: usize, + pub buffer: *mut u8, + pub context: usize, +} + +extern "system" { + fn CreateEventW(attrs: *const c_void, manual: i32, initial: i32, name: *const u16) -> usize; + fn SetEvent(h: usize) -> i32; + fn ResetEvent(h: usize) -> i32; + fn CloseHandle(h: usize) -> i32; + fn WaitForSingleObject(h: usize, ms: u32) -> u32; +} + +pub struct Event(pub usize); +impl Event { + pub fn new(manual: bool) -> Event { + let h = unsafe { CreateEventW(core::ptr::null(), manual as i32, 0, core::ptr::null()) }; + assert_ne!(h, 0); + Event(h) + } + pub fn set(&self) { + unsafe { SetEvent(self.0) }; + } + pub fn reset(&self) { + unsafe { ResetEvent(self.0) }; + } + pub fn wait(&self, ms: u32) -> bool { + unsafe { WaitForSingleObject(self.0, ms) == 0 } + } +} +impl Drop for Event { + fn drop(&mut self) { + unsafe { CloseHandle(self.0) }; + } +} + +#[derive(Clone, Copy)] +pub struct Api { + obj: usize, +} + +static API: OnceLock = OnceLock::new(); + +pub fn install(obj: *mut c_void) { + assert!(!obj.is_null()); + let _ = API.set(Api { obj: obj as usize }); +} + +pub fn api() -> Api { + *API.get().expect("XAsync interface not installed") +} + +static CONSOLE_MODEL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub fn set_console_model(on: bool) { + CONSOLE_MODEL.store(on, SeqCst); +} + +fn console_model() -> bool { + CONSOLE_MODEL.load(SeqCst) +} + +type Once = Box; +unsafe extern "system" fn once(ctx: *mut c_void, canceled: bool) { + Box::from_raw(ctx as *mut Once)(canceled) +} +type Many = dyn Fn(bool) + Send + Sync; +unsafe extern "system" fn many(ctx: *mut c_void, canceled: bool) { + (*(ctx as *const Box))(canceled) +} +type Mon = Box; +unsafe extern "system" fn monitor_tramp(ctx: *mut c_void, queue: usize, port: u32) { + (*(ctx as *const Mon))(queue, port) +} +type Term = Box; +unsafe extern "system" fn term_tramp(ctx: *mut c_void) { + Box::from_raw(ctx as *mut Term)() +} + +fn leak(v: T) -> *mut c_void { + Box::into_raw(Box::new(v)) as *mut c_void +} + +impl Api { + fn f(&self, slot: usize) -> usize { + unsafe { *(*(self.obj as *const *const usize)).add(slot) } + } + fn o(&self) -> *mut c_void { + self.obj as *mut c_void + } + + pub fn try_create(&self, work: u32, completion: u32, out: &mut usize) -> i32 { + let f: unsafe extern "system" fn(*mut c_void, u32, u32, *mut usize) -> i32 = unsafe { core::mem::transmute(self.f(12)) }; + unsafe { f(self.o(), work, completion, out) } + } + pub fn create(&self, work: u32, completion: u32) -> usize { + let mut q = 0; + assert_eq!(self.try_create(work, completion, &mut q), 0); + assert_ne!(q, 0); + q + } + pub fn try_composite(&self, work: usize, completion: usize, out: &mut usize) -> i32 { + let f: unsafe extern "system" fn(*mut c_void, usize, usize, *mut usize) -> i32 = unsafe { core::mem::transmute(self.f(13)) }; + unsafe { f(self.o(), work, completion, out) } + } + pub fn composite(&self, work: usize, completion: usize) -> usize { + let mut q = 0; + assert_eq!(self.try_composite(work, completion, &mut q), 0); + q + } + pub fn port(&self, q: usize, port: u32) -> usize { + let f: unsafe extern "system" fn(*mut c_void, usize, u32, *mut usize) -> i32 = unsafe { core::mem::transmute(self.f(14)) }; + let mut p = 0; + assert_eq!(unsafe { f(self.o(), q, port, &mut p) }, 0); + assert_ne!(p, 0); + p + } + pub fn try_dup(&self, q: usize, out: &mut usize) -> i32 { + let f: unsafe extern "system" fn(*mut c_void, usize, *mut usize) -> i32 = unsafe { core::mem::transmute(self.f(15)) }; + unsafe { f(self.o(), q, out) } + } + pub fn dup(&self, q: usize) -> usize { + let mut d = 0; + assert_eq!(self.try_dup(q, &mut d), 0); + d + } + pub fn dispatch(&self, q: usize, port: u32, timeout: u32) -> bool { + let f: unsafe extern "system" fn(*mut c_void, usize, u32, u32) -> bool = unsafe { core::mem::transmute(self.f(16)) }; + unsafe { f(self.o(), q, port, timeout) } + } + pub fn close(&self, q: usize) { + let f: unsafe extern "system" fn(*mut c_void, usize) = unsafe { core::mem::transmute(self.f(17)) }; + unsafe { f(self.o(), q) } + } + pub fn submit_raw(&self, q: usize, port: u32, delay: u32, ctx: *mut c_void, cb: TaskCb) -> i32 { + if delay == 0 { + let f: unsafe extern "system" fn(*mut c_void, usize, u32, *mut c_void, TaskCb) -> i32 = unsafe { core::mem::transmute(self.f(18)) }; + unsafe { f(self.o(), q, port, ctx, cb) } + } else { + let f: unsafe extern "system" fn(*mut c_void, usize, u32, u32, *mut c_void, TaskCb) -> i32 = unsafe { core::mem::transmute(self.f(19)) }; + unsafe { f(self.o(), q, port, delay, ctx, cb) } + } + } + pub fn submit(&self, q: usize, port: u32, delay: u32, f: impl FnOnce(bool) + Send + 'static) -> i32 { + let ctx = leak::(Box::new(f)); + let hr = self.submit_raw(q, port, delay, ctx, once); + if hr < 0 { + drop(unsafe { Box::from_raw(ctx as *mut Once) }); + } + hr + } + pub fn submit_delayed_slot(&self, q: usize, port: u32, delay: u32, f: impl FnOnce(bool) + Send + 'static) -> i32 { + let f2: unsafe extern "system" fn(*mut c_void, usize, u32, u32, *mut c_void, TaskCb) -> i32 = unsafe { core::mem::transmute(self.f(19)) }; + let ctx = leak::(Box::new(f)); + let hr = unsafe { f2(self.o(), q, port, delay, ctx, once) }; + if hr < 0 { + drop(unsafe { Box::from_raw(ctx as *mut Once) }); + } + hr + } + pub fn register_waiter(&self, q: usize, port: u32, handle: usize, f: impl Fn(bool) + Send + Sync + 'static) -> Result { + let g: unsafe extern "system" fn(*mut c_void, usize, u32, usize, *mut c_void, TaskCb, *mut u64) -> i32 = unsafe { core::mem::transmute(self.f(20)) }; + let ctx = leak::>(Box::new(f)); + let mut token = 0u64; + let hr = unsafe { g(self.o(), q, port, handle, ctx, many, &mut token) }; + if hr < 0 { + Err(hr) + } else { + Ok(token) + } + } + pub fn unregister_waiter(&self, q: usize, token: u64) { + let g: unsafe extern "system" fn(*mut c_void, usize, u64) = unsafe { core::mem::transmute(self.f(21)) }; + unsafe { g(self.o(), q, token) } + } + pub fn terminate(&self, q: usize, wait: bool, f: Option>) -> i32 { + let g: unsafe extern "system" fn(*mut c_void, usize, bool, *mut c_void, Option) -> i32 = unsafe { core::mem::transmute(self.f(22)) }; + match f { + Some(f) => unsafe { g(self.o(), q, wait, leak::(f), Some(term_tramp)) }, + None => unsafe { g(self.o(), q, wait, core::ptr::null_mut(), None) }, + } + } + pub fn register_monitor(&self, q: usize, f: impl Fn(usize, u32) + Send + Sync + 'static) -> u64 { + let g: unsafe extern "system" fn(*mut c_void, usize, *mut c_void, MonitorCb, *mut u64) -> i32 = unsafe { core::mem::transmute(self.f(23)) }; + let ctx = leak::(Box::new(f)); + let mut token = 0u64; + assert_eq!(unsafe { g(self.o(), q, ctx, monitor_tramp, &mut token) }, 0); + token + } + pub fn unregister_monitor(&self, q: usize, token: u64) { + let g: unsafe extern "system" fn(*mut c_void, usize, u64) = unsafe { core::mem::transmute(self.f(24)) }; + unsafe { g(self.o(), q, token) } + } + pub fn process_queue(&self) -> (bool, usize) { + let g: unsafe extern "system" fn(*mut c_void, *mut usize) -> bool = unsafe { core::mem::transmute(self.f(25)) }; + let mut q = 0usize; + let ok = unsafe { g(self.o(), &mut q) }; + (ok, q) + } + pub fn set_process_queue(&self, q: usize) { + let g: unsafe extern "system" fn(*mut c_void, usize) = unsafe { core::mem::transmute(self.f(26)) }; + unsafe { g(self.o(), q) } + } + + pub fn status(&self, b: *mut Block, wait: bool) -> i32 { + let g: unsafe extern "system" fn(*mut c_void, *mut Block, bool) -> i32 = unsafe { core::mem::transmute(self.f(3)) }; + unsafe { g(self.o(), b, wait) } + } + pub fn result_size(&self, b: *mut Block, out: &mut usize) -> i32 { + let g: unsafe extern "system" fn(*mut c_void, *mut Block, *mut usize) -> i32 = unsafe { core::mem::transmute(self.f(4)) }; + unsafe { g(self.o(), b, out) } + } + pub fn cancel(&self, b: *mut Block) { + let g: unsafe extern "system" fn(*mut c_void, *mut Block) = unsafe { core::mem::transmute(self.f(5)) }; + unsafe { g(self.o(), b) } + } + pub fn run(&self, b: *mut Block, w: Work) -> i32 { + let g: unsafe extern "system" fn(*mut c_void, *mut Block, Work) -> i32 = unsafe { core::mem::transmute(self.f(6)) }; + unsafe { g(self.o(), b, w) } + } + pub fn begin(&self, b: *mut Block, ctx: usize, identity: usize, p: Provider) -> i32 { + let g: unsafe extern "system" fn(*mut c_void, *mut Block, usize, usize, *const u8, Provider) -> i32 = unsafe { core::mem::transmute(self.f(7)) }; + unsafe { g(self.o(), b, ctx, identity, core::ptr::null(), p) } + } + pub fn schedule(&self, b: *mut Block, delay: u32) -> i32 { + let g: unsafe extern "system" fn(*mut c_void, *mut Block, u32) -> i32 = unsafe { core::mem::transmute(self.f(9)) }; + unsafe { g(self.o(), b, delay) } + } + pub fn complete(&self, b: *mut Block, hr: i32, size: usize) { + let g: unsafe extern "system" fn(*mut c_void, *mut Block, i32, usize) = unsafe { core::mem::transmute(self.f(10)) }; + unsafe { g(self.o(), b, hr, size) } + } + pub fn result(&self, b: *mut Block, identity: usize, size: usize, buf: *mut c_void, used: *mut usize) -> i32 { + let g: unsafe extern "system" fn(*mut c_void, *mut Block, usize, usize, *mut c_void, *mut usize) -> i32 = unsafe { core::mem::transmute(self.f(11)) }; + unsafe { g(self.o(), b, identity, size, buf, used) } + } +} + +fn until(ms: u64, mut f: impl FnMut() -> bool) -> bool { + let end = Instant::now() + Duration::from_millis(ms); + while Instant::now() < end { + if f() { + return true; + } + std::thread::sleep(Duration::from_millis(2)); + } + f() +} + +fn counter() -> Arc { + Arc::new(AtomicU32::new(0)) +} + +fn bump(c: &Arc) -> impl FnOnce(bool) + Send + 'static { + let c = c.clone(); + move |_| { + c.fetch_add(1, SeqCst); + } +} + +fn drain(q: usize) { + let a = api(); + while a.dispatch(q, WORK, 0) | a.dispatch(q, COMPLETION, 0) {} +} + +pub fn verify_stock_queue() { + let a = api(); + let q = a.create(THREAD_POOL, MANUAL); + let (work, done) = (counter(), counter()); + let (w, d) = (work.clone(), bump(&done)); + assert_eq!( + a.submit(q, WORK, 0, move |_| { + w.fetch_add(1, SeqCst); + assert_eq!(api().submit(q, COMPLETION, 0, d), 0); + }), + 0 + ); + assert!(a.dispatch(q, COMPLETION, 5000), "completion submitted from a thread-pool work callback never reached the manual port"); + assert_eq!((work.load(SeqCst), done.load(SeqCst)), (1, 1)); + a.close(q); +} + +pub fn verify_composite_queue() { + let a = api(); + let q = a.create(THREAD_POOL, MANUAL); + let calls = counter(); + let c = calls.clone(); + assert_eq!( + a.submit(q, WORK, 0, move |_| { + c.fetch_add(1, SeqCst); + let a = api(); + let wp = a.port(q, WORK); + let comp = a.composite(wp, wp); + assert_eq!(a.submit(comp, WORK, 0, bump(&c)), 0); + a.close(comp); + }), + 0 + ); + assert!(until(1000, || calls.load(SeqCst) == 2), "work submitted to a composite over the work port did not run on the thread pool"); + assert!(!a.dispatch(q, COMPLETION, 0), "nothing may be queued on the completion port"); + a.close(q); +} + +pub fn verify_duplicate_queue_handle() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let dups: Vec = (0..10).map(|_| a.dup(q)).collect(); + for d in &dups { + assert_ne!(*d, q, "XTaskQueueDuplicateHandle must return a new handle"); + } + let c = counter(); + assert_eq!(a.submit(dups[3], WORK, 0, bump(&c)), 0); + assert!(a.dispatch(dups[7], WORK, 0)); + assert_eq!(c.load(SeqCst), 1); + for d in dups { + a.close(d); + } + let fake = Box::new([0usize; 8]); + let mut out = 0usize; + assert!(a.try_dup(fake.as_ptr() as usize, &mut out) < 0, "a fake handle must not duplicate"); + assert_eq!(a.submit(q, WORK, 0, bump(&c)), 0); + assert!(a.dispatch(q, WORK, 0)); + assert_eq!(c.load(SeqCst), 2); + a.close(q); +} + +pub fn verify_dispatch() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let (work, comp) = (counter(), counter()); + for _ in 0..10 { + assert_eq!(a.submit(q, WORK, 0, bump(&work)), 0); + } + for _ in 0..10 { + assert_eq!(a.submit(q, COMPLETION, 0, bump(&comp)), 0); + } + let mut n = 0; + while a.dispatch(q, WORK, 0) { + n += 1; + } + assert_eq!((n, work.load(SeqCst), comp.load(SeqCst)), (10, 10, 0)); + n = 0; + while a.dispatch(q, COMPLETION, 0) { + n += 1; + } + assert_eq!((n, work.load(SeqCst), comp.load(SeqCst)), (10, 10, 10)); + a.close(q); + + let q = a.create(MANUAL, THREAD_POOL); + let me = std::thread::current().id(); + let threads = Arc::new(Mutex::new(Vec::new())); + for _ in 0..2 { + let t = threads.clone(); + assert_eq!(a.submit(q, WORK, 0, move |_| t.lock().unwrap().push(("work", std::thread::current().id()))), 0); + } + assert!(a.dispatch(q, WORK, 0)); + assert_eq!(threads.lock().unwrap().len(), 1); + assert!(a.dispatch(q, WORK, 0)); + assert_eq!(threads.lock().unwrap().len(), 2); + assert!(threads.lock().unwrap().iter().all(|(_, id)| *id == me), "manual work must run on the dispatching thread"); + let t = threads.clone(); + assert_eq!(a.submit(q, COMPLETION, 0, move |_| t.lock().unwrap().push(("completion", std::thread::current().id()))), 0); + assert!(until(1000, || threads.lock().unwrap().len() == 3)); + assert_ne!(threads.lock().unwrap()[2].1, me, "thread-pool completion ran on the test thread"); + + threads.lock().unwrap().clear(); + let t = threads.clone(); + assert_eq!( + a.submit(q, COMPLETION, 0, move |_| { + let t2 = t.clone(); + assert_eq!(api().submit(q, WORK, 0, move |_| t2.lock().unwrap().push(("work", std::thread::current().id()))), 0); + }), + 0 + ); + assert!(a.dispatch(q, WORK, 1000), "work handed off from the completion port did not wake the manual dispatcher"); + assert_eq!(threads.lock().unwrap()[0], ("work", me)); + a.close(q); +} + +pub fn verify_submitted_callback() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let (w, c) = (counter(), counter()); + let (w2, c2) = (w.clone(), c.clone()); + let token = a.register_monitor(q, move |_, port| { + if port == WORK { + w2.fetch_add(1, SeqCst); + } else { + c2.fetch_add(1, SeqCst); + } + }); + for _ in 0..4 { + assert_eq!(a.submit(q, WORK, 0, |_| {}), 0); + } + for _ in 0..7 { + assert_eq!(a.submit(q, COMPLETION, 0, |_| {}), 0); + } + assert_eq!((w.load(SeqCst), c.load(SeqCst)), (4, 7), "monitor must fire synchronously on every submit"); + a.unregister_monitor(q, token); + drain(q); + a.close(q); +} + +pub fn verify_submit_callback_with_wait() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + for port in [WORK, COMPLETION] { + let base = Instant::now(); + let times = Arc::new(Mutex::new([None::; 3])); + for (i, delay) in [(0usize, 1000u32), (1, 0), (2, 500)] { + let t = times.clone(); + assert_eq!(a.submit(q, port, delay, move |_| t.lock().unwrap()[i] = Some(base.elapsed())), 0); + } + assert!(a.dispatch(q, port, 0)); + assert!(!a.dispatch(q, port, 0), "a delayed callback was dispatchable before its delay"); + assert!(a.dispatch(q, port, 700), "500 ms callback did not wake a 700 ms dispatch"); + assert!(a.dispatch(q, port, 1200), "1000 ms callback did not wake a 1200 ms dispatch"); + assert!(!a.dispatch(q, port, 0)); + let t = *times.lock().unwrap(); + let ms = |d: Option| d.expect("callback never ran").as_millis(); + assert!(ms(t[0]) >= 1000 && ms(t[0]) < 1600, "1000 ms callback at {} ms", ms(t[0])); + assert!(ms(t[1]) < 500, "immediate callback at {} ms", ms(t[1])); + assert!(ms(t[2]) >= 500 && ms(t[2]) < 1000, "500 ms callback at {} ms", ms(t[2])); + } + a.close(q); +} + +pub fn verify_register_callback_submitted() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let calls: Vec> = (0..5).map(|_| counter()).collect(); + let tokens: Vec = calls + .iter() + .map(|c| { + let c = c.clone(); + a.register_monitor(q, move |_, _| { + c.fetch_add(1, SeqCst); + }) + }) + .collect(); + let mut seen = std::collections::HashSet::new(); + assert!(tokens.iter().all(|t| seen.insert(*t)), "registration tokens must be unique: {tokens:?}"); + for _ in 0..3 { + assert_eq!(a.submit(q, WORK, 0, |_| {}), 0); + } + assert!(calls.iter().all(|c| c.load(SeqCst) == 3)); + for i in (1..5).step_by(2) { + a.unregister_monitor(q, tokens[i]); + } + for _ in 0..3 { + assert_eq!(a.submit(q, WORK, 0, |_| {}), 0); + } + let got: Vec = calls.iter().map(|c| c.load(SeqCst)).collect(); + assert_eq!(got, vec![6, 3, 6, 3, 6]); + drain(q); + a.close(q); +} + +pub fn verify_immediate_dispatch() { + let a = api(); + let q = a.create(MANUAL, IMMEDIATE); + let c = counter(); + for i in 1..=10 { + assert_eq!(a.submit(q, COMPLETION, 0, bump(&c)), 0); + assert_eq!(c.load(SeqCst), i, "immediate port must run the callback inside the submit"); + } + assert_eq!(a.submit(q, COMPLETION, 200, bump(&c)), 0); + assert_eq!(c.load(SeqCst), 10, "a delayed callback on an immediate port ran early"); + std::thread::sleep(Duration::from_millis(500)); + assert_eq!(c.load(SeqCst), 11, "a delayed callback on an immediate port never ran"); + a.close(q); +} + +pub fn verify_serialized_thread_pool_dispatch() { + let a = api(); + let q = a.create(THREAD_POOL, SERIALIZED); + let order = Arc::new(Mutex::new(Vec::new())); + let active = Arc::new(AtomicUsize::new(0)); + let overlap = Arc::new(AtomicBool::new(false)); + for i in 0..100u32 { + let (o, act, ov) = (order.clone(), active.clone(), overlap.clone()); + assert_eq!( + a.submit(q, COMPLETION, 0, move |_| { + if act.fetch_add(1, SeqCst) != 0 { + ov.store(true, SeqCst); + } + o.lock().unwrap().push(i); + std::thread::yield_now(); + act.fetch_sub(1, SeqCst); + }), + 0 + ); + } + assert!(until(2000, || order.lock().unwrap().len() == 100)); + assert!(!overlap.load(SeqCst), "serialized thread-pool callbacks overlapped"); + assert_eq!(*order.lock().unwrap(), (0..100).collect::>(), "serialized thread-pool callbacks ran out of order"); + a.close(q); +} + +pub fn verify_serialized_thread_pool_does_not_strand_items() { + let a = api(); + let q = a.create(SERIALIZED, SERIALIZED); + let ev = Arc::new(Event::new(false)); + for round in 0..5000 { + let e = ev.clone(); + assert_eq!(a.submit(q, COMPLETION, 0, move |_| e.set()), 0); + assert!(ev.wait(5000), "item {round} was not dispatched"); + } + a.close(q); +} + +pub fn verify_multithread_manual_dispatch() { + let a = api(); + let q = a.create(MANUAL, IMMEDIATE); + let ran = counter(); + let spawn = || { + std::thread::spawn(move || { + let a = api(); + while a.dispatch(q, WORK, INFINITE) {} + }) + }; + let (t1, t2) = (spawn(), spawn()); + for _ in 0..5 { + assert_eq!(a.submit(q, WORK, 0, bump(&ran)), 0); + } + std::thread::sleep(Duration::from_millis(750)); + assert!(!t1.is_finished() && !t2.is_finished(), "XTaskQueueDispatch(INFINITE) returned without termination"); + assert_eq!(ran.load(SeqCst), 5); + + let comp = a.composite(a.port(q, WORK), a.port(q, COMPLETION)); + for _ in 0..5 { + assert_eq!(a.submit(comp, WORK, 0, bump(&ran)), 0); + } + assert_eq!(a.terminate(comp, true, None), 0); + std::thread::sleep(Duration::from_millis(750)); + assert!(!t1.is_finished() && !t2.is_finished(), "terminating a composite stopped the base queue's dispatchers"); + + assert_eq!(a.terminate(q, true, None), 0); + assert!(until(750, || t1.is_finished() && t2.is_finished()), "terminating the queue did not release XTaskQueueDispatch(INFINITE)"); + t1.join().unwrap(); + t2.join().unwrap(); + a.close(comp); + a.close(q); +} + +pub struct Pumped { + pub q: usize, + stop: Arc, + threads: Vec>, + events: [Arc; 2], +} + +impl Pumped { + pub fn new() -> Pumped { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let events = [Arc::new(Event::new(false)), Arc::new(Event::new(false))]; + let ev = events.clone(); + a.register_monitor(q, move |_, port| ev[port as usize].set()); + let stop = Arc::new(AtomicBool::new(false)); + let threads = (0..2u32) + .map(|port| { + let (e, s) = (events[port as usize].clone(), stop.clone()); + std::thread::spawn(move || loop { + e.wait(INFINITE); + if s.load(SeqCst) { + return; + } + while api().dispatch(q, port, 0) {} + }) + }) + .collect(); + Pumped { q, stop, threads, events } + } +} + +impl Drop for Pumped { + fn drop(&mut self) { + self.stop.store(true, SeqCst); + for e in &self.events { + e.set(); + } + for t in self.threads.drain(..) { + t.join().unwrap(); + } + api().close(self.q); + } +} + +fn register_with_auto_reset(q: usize) { + let a = api(); + for port in [WORK, COMPLETION] { + let wait = Event::new(false); + let signaled = Arc::new(Event::new(false)); + let count = counter(); + let (s, c) = (signaled.clone(), count.clone()); + let token = a + .register_waiter(q, port, wait.0, move |_| { + c.fetch_add(1, SeqCst); + s.set(); + }) + .expect("XTaskQueueRegisterWaiter"); + for i in 1..=5 { + wait.set(); + assert!(signaled.wait(1000), "port {port}: waiter callback did not run"); + assert!(!signaled.wait(100), "port {port}: an auto-reset event ran the waiter twice"); + assert_eq!(count.load(SeqCst), i); + } + a.unregister_waiter(q, token); + } +} + +pub fn verify_register_with_auto_reset() { + let a = api(); + let q = a.create(THREAD_POOL, THREAD_POOL); + register_with_auto_reset(q); + a.close(q); + let pumped = Pumped::new(); + register_with_auto_reset(pumped.q); +} + +pub fn verify_shared_port_queue_rundown_keeps_other_waiters() { + let a = api(); + for terminate in [true, false] { + let q = a.create(THREAD_POOL, THREAD_POOL); + let signaled = Arc::new(Event::new(false)); + let wait = Event::new(false); + let count = counter(); + let (s, c) = (signaled.clone(), count.clone()); + let token = a + .register_waiter(q, WORK, wait.0, move |canceled| { + if !canceled { + c.fetch_add(1, SeqCst); + s.set(); + } + }) + .unwrap(); + wait.set(); + assert!(signaled.wait(1000)); + let wp = a.port(q, WORK); + let sibling = a.composite(wp, wp); + if terminate { + assert_eq!(a.terminate(sibling, true, None), 0); + } + a.close(sibling); + wait.set(); + assert!(signaled.wait(1000), "terminate={terminate}: a sibling's rundown broke this queue's waiter"); + assert_eq!(count.load(SeqCst), 2); + a.unregister_waiter(q, token); + wait.set(); + assert!(!signaled.wait(300), "terminate={terminate}: waiter fired after XTaskQueueUnregisterWaiter"); + assert_eq!(count.load(SeqCst), 2); + a.close(q); + } +} + +pub fn verify_shared_port_queue_rundown_drops_its_wait_handles() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let wp = a.port(q, WORK); + let sibling = a.composite(wp, wp); + let wait = Event::new(true); + a.register_waiter(sibling, WORK, wait.0, |_| {}).unwrap(); + a.close(sibling); + wait.set(); + let returned = Arc::new(AtomicBool::new(false)); + let r = returned.clone(); + let t = std::thread::spawn(move || { + api().dispatch(q, WORK, 100); + r.store(true, SeqCst); + }); + let ok = until(2000, || returned.load(SeqCst)); + wait.reset(); + t.join().unwrap(); + assert!(ok, "Dispatch(100 ms) kept spinning on a closed sibling's wait handle"); + a.close(q); +} + +fn queue_termination(work_mode: u32, wait: bool, serialized: bool, empty: bool) { + let a = api(); + let q = a.create(work_mode, work_mode); + struct D { + q: usize, + work: AtomicU32, + completion: AtomicU32, + serialized: bool, + failure: Mutex>, + } + let d = Arc::new(D { q, work: AtomicU32::new(0), completion: AtomicU32::new(0), serialized, failure: Mutex::new(None) }); + let fail = |d: &D, line: u32, hr: i32| { + d.failure.lock().unwrap().get_or_insert((line, hr)); + }; + unsafe extern "system" fn completion_cb(ctx: *mut c_void, cancel: bool) { + let d = &*(ctx as *const D); + if d.serialized && !cancel { + d.failure.lock().unwrap().get_or_insert((line!(), E_UNEXPECTED)); + } + d.completion.fetch_add(1, SeqCst); + } + unsafe extern "system" fn work_cb(ctx: *mut c_void, cancel: bool) { + let d = &*(ctx as *const D); + let a = api(); + if d.serialized { + if !cancel && d.work.load(SeqCst) != 0 { + d.failure.lock().unwrap().get_or_insert((line!(), E_UNEXPECTED)); + } + let start = Instant::now(); + while a.submit(d.q, WORK, 0, |_| {}) != E_ABORT { + if start.elapsed() > Duration::from_secs(30) { + d.failure.lock().unwrap().get_or_insert((line!(), E_UNEXPECTED)); + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + } + d.work.fetch_add(1, SeqCst); + let hr = a.submit_raw(d.q, COMPLETION, 0, ctx, completion_cb); + if hr < 0 { + d.failure.lock().unwrap().get_or_insert((line!(), hr)); + } + } + let ctx = Arc::as_ptr(&d) as *mut c_void; + let (normal, future, events) = if empty { (0, 0, 0) } else { (5, 5, 5) }; + for _ in 0..normal { + assert_eq!(a.submit_raw(q, WORK, 0, ctx, work_cb), 0); + } + for _ in 0..future { + assert_eq!(a.submit_raw(q, WORK, 10000, ctx, work_cb), 0); + } + let handles: Vec = (0..events).map(|_| Event::new(false)).collect(); + for h in &handles { + let dd = d.clone(); + a.register_waiter(q, WORK, h.0, move |cancel| unsafe { work_cb(Arc::as_ptr(&dd) as *mut c_void, cancel) }).unwrap(); + } + if wait { + assert_eq!(a.terminate(q, true, None), 0); + } else { + let done = Arc::new(Event::new(true)); + let dn = done.clone(); + assert_eq!(a.terminate(q, false, Some(Box::new(move || dn.set()))), 0); + assert!(done.wait(5000), "termination callback never ran"); + } + assert_eq!(a.submit_raw(q, WORK, 0, ctx, work_cb), E_ABORT, "submit to a terminated work port"); + assert_eq!(a.submit_raw(q, COMPLETION, 0, ctx, completion_cb), E_ABORT, "submit to a terminated completion port"); + let expected = normal + future + events; + if !wait { + until(5000, || d.work.load(SeqCst) == expected && d.completion.load(SeqCst) == expected); + } + assert_eq!(*d.failure.lock().unwrap(), None); + assert_eq!(d.work.load(SeqCst), expected, "every pending, delayed and waiter work item must run (canceled) before termination completes"); + assert_eq!(d.completion.load(SeqCst), expected); + let _ = fail; + a.close(q); +} + +pub fn verify_queue_termination() { + queue_termination(THREAD_POOL, false, false, false); + queue_termination(THREAD_POOL, true, false, false); + queue_termination(SERIALIZED, true, true, false); +} + +pub fn verify_empty_queue_termination() { + queue_termination(THREAD_POOL, false, false, true); + queue_termination(THREAD_POOL, true, false, true); + queue_termination(SERIALIZED, true, true, true); +} + +pub fn verify_global_queue() { + let a = api(); + let (ok, global) = a.process_queue(); + assert!(ok); + assert_ne!(global, 0); + assert_eq!(a.submit(global, WORK, 0, |_| {}), 0); + + let ours = a.create(MANUAL, MANUAL); + a.set_process_queue(ours); + let (ok, q) = a.process_queue(); + assert!(ok); + let c = counter(); + assert_eq!(a.submit(q, WORK, 0, bump(&c)), 0); + assert!(a.dispatch(ours, WORK, 0), "the queue set with XTaskQueueSetCurrentProcessTaskQueue is not the process queue"); + assert_eq!(c.load(SeqCst), 1); + a.close(q); + a.set_process_queue(0); + let (ok, q) = a.process_queue(); + assert!(!ok); + assert_eq!(q, 0); + + let mut b = Block::new(0); + assert_eq!(a.begin(&mut *b, 0, 0, abort_on_cancel), E_NO_TASK_QUEUE, "XAsyncBegin with no process queue"); + a.set_process_queue(global); + let mut b = Block::new(0); + assert_eq!(a.begin(&mut *b, 0, 0, abort_on_cancel), 0); + a.cancel(&mut *b); + assert_eq!(a.status(&mut *b, true), E_ABORT); + + let p = a.port(global, WORK); + let comp = a.composite(p, p); + assert_eq!(a.terminate(comp, true, None), 0); + a.close(comp); + let ev = Arc::new(Event::new(false)); + let e = ev.clone(); + assert_eq!(a.submit(global, WORK, 0, move |_| e.set()), 0); + assert!(ev.wait(5000)); + if console_model() { + assert_eq!(a.terminate(global, true, None), E_ACCESSDENIED); + assert_eq!(a.submit(global, WORK, 0, |_| {}), 0); + } else { + assert_eq!(a.terminate(global, true, None), 0); + assert_eq!(a.submit(global, WORK, 0, |_| {}), E_ABORT); + } + a.close(global); + a.close(ours); +} + +pub fn verify_close_in_termination_for_thread_pool() { + let a = api(); + let q = a.create(THREAD_POOL, THREAD_POOL); + let called = Arc::new(AtomicBool::new(false)); + let c = called.clone(); + assert_eq!( + a.terminate( + q, + false, + Some(Box::new(move || { + api().close(q); + c.store(true, SeqCst); + })) + ), + 0 + ); + assert!(until(5000, || called.load(SeqCst))); +} + +pub fn verify_close_in_termination_for_manual() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let called = Arc::new(AtomicBool::new(false)); + let c = called.clone(); + assert_eq!( + a.terminate( + q, + false, + Some(Box::new(move || { + c.store(true, SeqCst); + api().close(q); + })) + ), + 0 + ); + assert!(!called.load(SeqCst), "a manual queue's termination callback must wait for dispatch"); + let end = Instant::now() + Duration::from_secs(5); + while !called.load(SeqCst) && Instant::now() < end { + a.dispatch(q, WORK, 0); + if !called.load(SeqCst) { + a.dispatch(q, COMPLETION, 0); + } + std::thread::sleep(Duration::from_millis(20)); + } + assert!(called.load(SeqCst)); +} + +pub fn verify_wait_termination() { + let a = api(); + let start = Instant::now(); + while start.elapsed() < Duration::from_secs(1) { + let q = a.create(THREAD_POOL, THREAD_POOL); + assert_eq!(a.terminate(q, true, None), 0); + a.close(q); + } +} + +pub fn verify_manual_dispatch_at_termination() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + a.register_monitor(q, |queue, port| { + api().dispatch(queue, port, 0); + }); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(api().terminate(q, true, None)).unwrap()); + assert_eq!(rx.recv_timeout(Duration::from_secs(5)), Ok(0), "Terminate(wait) on a monitor-dispatched manual queue did not finish"); + a.close(q); +} + +#[derive(Default)] +struct CompositeData { + q: AtomicUsize, + work: AtomicI32, + completion: AtomicI32, + future: AtomicI32, + waiter: AtomicI32, + terminated: AtomicBool, +} + +fn record(slot: &AtomicI32, canceled: bool) { + slot.store(1 + canceled as i32, SeqCst); +} + +pub fn verify_termination_of_composite_queue() { + let a = api(); + let data = Arc::new(CompositeData::default()); + let comp = Arc::new(CompositeData::default()); + let wait = Event::new(false); + let cwait = Event::new(false); + let q = a.create(MANUAL, MANUAL); + data.q.store(q, SeqCst); + let wp = a.port(q, WORK); + let cq = a.composite(wp, wp); + comp.q.store(cq, SeqCst); + + let submit_all = |d: &Arc, ev: &Event| { + let q = d.q.load(SeqCst); + let d1 = d.clone(); + assert_eq!( + a.submit(q, WORK, 0, move |canceled| { + record(&d1.work, canceled); + let d2 = d1.clone(); + assert_eq!(api().submit(d1.q.load(SeqCst), COMPLETION, 0, move |c| record(&d2.completion, c)), 0); + }), + 0 + ); + let d1 = d.clone(); + assert_eq!(a.submit(q, WORK, 300, move |c| record(&d1.future, c)), 0); + let d1 = d.clone(); + a.register_waiter(q, WORK, ev.0, move |c| record(&d1.waiter, c)).unwrap(); + }; + submit_all(&data, &wait); + submit_all(&comp, &cwait); + let c1 = comp.clone(); + assert_eq!( + a.terminate( + cq, + false, + Some(Box::new(move || { + c1.terminated.store(true, SeqCst); + api().close(c1.q.load(SeqCst)); + })) + ), + 0 + ); + while a.dispatch(q, WORK, 500) | a.dispatch(q, COMPLETION, 500) {} + + assert_eq!( + (data.work.load(SeqCst), data.completion.load(SeqCst), data.future.load(SeqCst), data.waiter.load(SeqCst)), + (1, 1, 1, 0), + "base queue callbacks must run normally" + ); + assert_eq!( + (comp.work.load(SeqCst), comp.completion.load(SeqCst), comp.future.load(SeqCst), comp.waiter.load(SeqCst)), + (2, 2, 2, 2), + "composite callbacks must all run canceled" + ); + assert!(comp.terminated.load(SeqCst)); + + data.work.store(0, SeqCst); + data.waiter.store(0, SeqCst); + comp.waiter.store(0, SeqCst); + let d1 = data.clone(); + assert_eq!(a.submit(q, WORK, 0, move |c| record(&d1.work, c)), 0); + wait.set(); + cwait.set(); + while a.dispatch(q, WORK, 500) | a.dispatch(q, COMPLETION, 500) {} + assert_eq!(data.work.load(SeqCst), 1); + assert_eq!(data.waiter.load(SeqCst), 1, "the base queue's waiter must survive the composite's termination"); + assert_eq!(comp.waiter.load(SeqCst), 0, "the terminated composite's waiter must be gone"); + a.close(q); +} + +pub fn verify_termination_of_base_queue_keeps_composites() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let (w, c) = (a.port(q, WORK), a.port(q, COMPLETION)); + let comp = a.composite(w, c); + let slots: Arc<[AtomicI32; 3]> = Arc::new(Default::default()); + let s = slots.clone(); + assert_eq!(a.submit(comp, WORK, 0, move |cn| record(&s[0], cn)), 0); + let s = slots.clone(); + assert_eq!(a.submit(q, WORK, 0, move |cn| record(&s[1], cn)), 0); + let done = Arc::new(AtomicBool::new(false)); + let d = done.clone(); + assert_eq!(a.terminate(q, false, Some(Box::new(move || d.store(true, SeqCst)))), 0); + let delivered = until(2000, || { + a.dispatch(q, WORK, 0); + a.dispatch(q, COMPLETION, 0); + done.load(SeqCst) + }); + assert!(delivered, "the termination callback was not delivered"); + assert_eq!(slots[0].load(SeqCst), 1, "the composite's pending callback must run normally"); + assert_eq!(slots[1].load(SeqCst), 2, "the terminated queue's pending callback must run canceled"); + assert_eq!(a.submit(q, WORK, 0, |_| {}), E_ABORT); + let s = slots.clone(); + assert_eq!(a.submit(comp, WORK, 0, move |cn| record(&s[2], cn)), 0); + assert_eq!(a.submit(comp, COMPLETION, 0, |_| {}), 0); + assert_eq!(a.submit(comp, WORK, 10, |_| {}), 0); + let mut comp2 = 0; + assert_eq!(a.try_composite(w, c, &mut comp2), 0); + assert!(until(2000, || { + a.dispatch(comp, WORK, 0); + a.dispatch(comp, COMPLETION, 0); + slots[2].load(SeqCst) != 0 + })); + assert_eq!(slots[2].load(SeqCst), 1, "a callback queued on the composite afterwards must run normally"); + std::thread::sleep(Duration::from_millis(30)); + drain(comp); + a.close(comp2); + a.close(comp); + a.close(q); +} + +pub fn verify_queue_monitor_has_correct_ports() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let wp = a.port(q, WORK); + let cq = a.composite(wp, wp); + let qp = Arc::new(AtomicU32::new(u32::MAX)); + let cp = Arc::new(AtomicU32::new(u32::MAX)); + let (q1, c1) = (qp.clone(), cp.clone()); + a.register_monitor(q, move |_, port| q1.store(port, SeqCst)); + a.register_monitor(cq, move |_, port| c1.store(port, SeqCst)); + assert_eq!(a.submit(cq, COMPLETION, 0, |_| {}), 0); + while a.dispatch(cq, COMPLETION, 100) {} + assert_eq!(qp.load(SeqCst), WORK, "base queue monitor must report its own port for the shared port"); + assert_eq!(cp.load(SeqCst), COMPLETION); + a.close(cq); + a.close(q); +} + +pub fn verify_nested_queue_dispatch_order() { + let a = api(); + let nest = |q: usize| { + let p = a.port(q, WORK); + a.composite(p, p) + }; + let q = a.create(MANUAL, MANUAL); + let outer = nest(q); + let inner = nest(outer); + let step = Arc::new(Mutex::new(Vec::new())); + let s = step.clone(); + assert_eq!(a.submit(outer, WORK, 3000, move |_| s.lock().unwrap().push("delayed outer")), 0); + let s = step.clone(); + assert_eq!(a.submit(inner, WORK, 0, move |_| s.lock().unwrap().push("inner")), 0); + a.dispatch(outer, WORK, 0); + a.dispatch(outer, COMPLETION, 0); + assert_eq!(*step.lock().unwrap(), ["inner"]); + a.close(inner); + a.dispatch(outer, WORK, 0); + a.dispatch(outer, COMPLETION, 0); + assert_eq!(*step.lock().unwrap(), ["inner"]); + a.dispatch(outer, WORK, 4000); + a.dispatch(outer, COMPLETION, 1000); + assert_eq!(*step.lock().unwrap(), ["inner", "delayed outer"]); + a.close(outer); + a.close(q); +} + +pub fn verify_terminate_waits_for_async_in_flight() { + let a = api(); + let q = a.create(THREAD_POOL, THREAD_POOL); + let mut b = Block::new(q); + assert_eq!(a.begin(&mut *b, 0, 0, nop_provider), 0); + let done = Arc::new(Event::new(true)); + let d = done.clone(); + assert_eq!(a.terminate(q, false, Some(Box::new(move || d.set()))), 0); + assert!(!done.wait(1000), "termination finished while an XAsync call on the queue was still pending"); + a.complete(&mut *b, 0, 0); + assert!(done.wait(2000), "termination did not finish after the pending XAsync call completed"); + assert_eq!(a.status(&mut *b, true), 0); + a.close(q); +} + +pub fn verify_single_queue_delayed_poll_strand() { + let a = api(); + for iter in 0..10 { + let q = a.create(MANUAL, MANUAL); + let pumping = Arc::new(AtomicBool::new(true)); + let p = pumping.clone(); + let pump = std::thread::spawn(move || { + while p.load(SeqCst) { + api().dispatch(q, WORK, 50); + } + }); + let keep = Arc::new(AtomicBool::new(true)); + let polls = counter(); + fn poll(q: usize, keep: Arc, polls: Arc) -> impl FnOnce(bool) + Send { + move |canceled| { + if canceled { + return; + } + polls.fetch_add(1, SeqCst); + if keep.load(SeqCst) { + let (k, p) = (keep.clone(), polls.clone()); + api().submit(q, WORK, 2, poll(q, k, p)); + } + } + } + assert_eq!(a.submit(q, WORK, 2, poll(q, keep.clone(), polls.clone())), 0); + assert!(until(1000, || polls.load(SeqCst) > 0)); + let outstanding = Arc::new(AtomicI32::new(0)); + let burst: Vec<_> = (0..4) + .map(|_| { + let o = outstanding.clone(); + std::thread::spawn(move || { + for _ in 0..250 { + o.fetch_add(1, SeqCst); + let o2 = o.clone(); + if api().submit(q, WORK, 1, move |_| { + o2.fetch_sub(1, SeqCst); + }) < 0 + { + o.fetch_sub(1, SeqCst); + } + } + }) + }) + .collect(); + for t in burst { + t.join().unwrap(); + } + assert!(until(5000, || outstanding.load(SeqCst) == 0), "iteration {iter}: burst callbacks did not drain"); + let target = polls.load(SeqCst) + 30; + let progressed = until(5000, || polls.load(SeqCst) >= target); + keep.store(false, SeqCst); + pumping.store(false, SeqCst); + pump.join().unwrap(); + a.terminate(q, false, None); + drain(q); + a.close(q); + assert!(progressed, "iteration {iter}: delayed poll loop stranded at {} polls", polls.load(SeqCst)); + } +} + +pub fn verify_composite_queue_delayed_callback_starvation() { + struct Req { + comp: usize, + target: u32, + delay: u32, + polls: AtomicU32, + done: AtomicBool, + term: AtomicBool, + completed: Arc, + } + impl Req { + fn mark(&self) { + if !self.done.swap(true, SeqCst) { + self.completed.fetch_add(1, SeqCst); + } + } + fn terminate(&self) { + if !self.term.swap(true, SeqCst) { + api().terminate(self.comp, false, None); + } + } + } + unsafe extern "system" fn poll(ctx: *mut c_void, canceled: bool) { + let r = &*(ctx as *const Req); + if canceled { + return r.mark(); + } + let n = r.polls.fetch_add(1, SeqCst) + 1; + if n < r.target { + if api().submit_raw(r.comp, WORK, r.delay, ctx, poll) < 0 { + r.mark(); + } + } else { + r.terminate(); + r.mark(); + } + } + let a = api(); + let (threads, per) = (6usize, 24usize); + let total = threads * per; + for iter in 0..5 { + let q = a.create(MANUAL, MANUAL); + let wp = a.port(q, WORK); + let pumping = Arc::new(AtomicBool::new(true)); + let pumps: Vec<_> = (0..2) + .map(|_| { + let p = pumping.clone(); + std::thread::spawn(move || { + while p.load(SeqCst) { + api().dispatch(q, WORK, 50); + } + }) + }) + .collect(); + let completed = Arc::new(AtomicU32::new(0)); + let slots: Arc> = Arc::new((0..total).map(|_| AtomicUsize::new(0)).collect()); + let submitters: Vec<_> = (0..threads) + .map(|t| { + let (c, s) = (completed.clone(), slots.clone()); + std::thread::spawn(move || { + let a = api(); + for i in 0..per { + let idx = t * per + i; + let r = Box::into_raw(Box::new(Req { + comp: a.composite(wp, wp), + target: if idx % 3 == 0 { u32::MAX } else { 20 }, + delay: if i & 1 == 1 { 1 } else { 2 }, + polls: AtomicU32::new(0), + done: AtomicBool::new(false), + term: AtomicBool::new(false), + completed: c.clone(), + })); + s[idx].store(r as usize, SeqCst); + if a.submit_raw(unsafe { (*r).comp }, WORK, 0, r as *mut c_void, poll) < 0 { + unsafe { (*r).mark() }; + } + } + }) + }) + .collect(); + let s = slots.clone(); + let canceller = std::thread::spawn(move || loop { + let mut handled = 0; + for i in 0..total { + if i % 3 != 0 { + handled += 1; + continue; + } + let r = s[i].load(SeqCst) as *const Req; + if !r.is_null() { + unsafe { (*r).terminate() }; + handled += 1; + } + } + if handled == total { + return; + } + std::thread::sleep(Duration::from_millis(1)); + }); + for t in submitters { + t.join().unwrap(); + } + canceller.join().unwrap(); + let ok = until(15000, || completed.load(SeqCst) as usize == total); + pumping.store(false, SeqCst); + for p in pumps { + p.join().unwrap(); + } + for slot in slots.iter() { + let r = slot.load(SeqCst) as *const Req; + unsafe { + (*r).terminate(); + a.close((*r).comp); + } + } + let fin = Arc::new(AtomicBool::new(false)); + let f = fin.clone(); + a.terminate(q, false, Some(Box::new(move || f.store(true, SeqCst)))); + let end = Instant::now() + Duration::from_secs(5); + while !fin.load(SeqCst) && Instant::now() < end { + a.dispatch(q, WORK, 10); + a.dispatch(q, COMPLETION, 0); + } + assert!(fin.load(SeqCst), "iteration {iter}: queue termination stalled"); + a.close(q); + assert!(ok, "iteration {iter}: starvation, {} of {total} poll loops finished", completed.load(SeqCst)); + } +} + +pub fn verify_termination_cancels_delayed_callbacks() { + let a = api(); + for mode in [THREAD_POOL, MANUAL] { + let q = a.create(mode, mode); + let log = Arc::new(Mutex::new(Vec::new())); + let l = log.clone(); + assert_eq!(a.submit(q, WORK, 10000, move |canceled| l.lock().unwrap().push(if canceled { "delayed canceled" } else { "delayed ran" })), 0); + let l = log.clone(); + assert_eq!(a.terminate(q, false, Some(Box::new(move || l.lock().unwrap().push("terminated")))), 0); + let end = Instant::now() + Duration::from_secs(2); + while !log.lock().unwrap().contains(&"terminated") && Instant::now() < end { + if mode == MANUAL { + a.dispatch(q, WORK, 10); + a.dispatch(q, COMPLETION, 10); + } else { + std::thread::sleep(Duration::from_millis(10)); + } + } + assert_eq!(*log.lock().unwrap(), ["delayed canceled", "terminated"], "mode {mode}"); + a.close(q); + } +} + +pub fn verify_close_keeps_queued_callbacks() { + let a = api(); + let q = a.create(SERIALIZED, SERIALIZED); + let gate = Arc::new(Event::new(true)); + let (ran, canceled) = (counter(), counter()); + let g = gate.clone(); + assert_eq!(a.submit(q, WORK, 0, move |_| { g.wait(5000); }), 0); + for delay in std::iter::repeat(0).take(20).chain([200]) { + let (r, c) = (ran.clone(), canceled.clone()); + assert_eq!( + a.submit(q, WORK, delay, move |cx| { + if cx { c.fetch_add(1, SeqCst) } else { r.fetch_add(1, SeqCst) }; + }), + 0 + ); + } + a.close(q); + gate.set(); + assert!(until(3000, || ran.load(SeqCst) + canceled.load(SeqCst) == 21)); + assert_eq!((ran.load(SeqCst), canceled.load(SeqCst)), (21, 0), "closing the handle canceled queued callbacks"); +} + +pub fn verify_dispatch_on_pool_port() { + let a = api(); + let q = a.create(MANUAL, SERIALIZED); + let gate = Arc::new(Event::new(true)); + let started = Arc::new(Event::new(true)); + let (g, s) = (gate.clone(), started.clone()); + assert_eq!( + a.submit(q, COMPLETION, 0, move |_| { + s.set(); + g.wait(5000); + }), + 0 + ); + assert!(started.wait(2000)); + let ran_on = Arc::new(Mutex::new(None)); + let r = ran_on.clone(); + assert_eq!(a.submit(q, COMPLETION, 0, move |_| *r.lock().unwrap() = Some(std::thread::current().id())), 0); + assert!(a.dispatch(q, COMPLETION, 0), "dispatch on a thread-pool port with a queued item"); + assert_eq!(*ran_on.lock().unwrap(), Some(std::thread::current().id())); + gate.set(); + a.close(q); +} + +pub fn verify_thread_pool_callbacks_can_block() { + let a = api(); + let q = a.create(THREAD_POOL, THREAD_POOL); + const N: u32 = 24; + let pair = Arc::new((Mutex::new(0u32), std::sync::Condvar::new())); + let met = counter(); + for _ in 0..N { + let (p, m) = (pair.clone(), met.clone()); + assert_eq!( + a.submit(q, WORK, 0, move |_| { + let (lock, cv) = &*p; + let mut n = lock.lock().unwrap(); + *n += 1; + cv.notify_all(); + let (n, _) = cv.wait_timeout_while(n, Duration::from_secs(10), |n| *n < N).unwrap(); + if *n >= N { + m.fetch_add(1, SeqCst); + } + }), + 0 + ); + } + assert!(until(12000, || met.load(SeqCst) == N), "{} thread-pool callbacks could not all run at once", N); + a.close(q); +} + +#[repr(C)] +struct ThreadEntry { + size: u32, + usage: u32, + tid: u32, + pid: u32, + base: i32, + delta: i32, + flags: u32, +} + +extern "system" { + fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> usize; + fn Thread32First(snap: usize, e: *mut ThreadEntry) -> i32; + fn Thread32Next(snap: usize, e: *mut ThreadEntry) -> i32; + fn GetCurrentProcessId() -> u32; +} + +fn thread_count() -> usize { + unsafe { + let snap = CreateToolhelp32Snapshot(4, 0); + let mut e = ThreadEntry { size: 28, usage: 0, tid: 0, pid: 0, base: 0, delta: 0, flags: 0 }; + let me = GetCurrentProcessId(); + let mut n = 0; + let mut ok = Thread32First(snap, &mut e); + while ok != 0 { + n += (e.pid == me) as usize; + ok = Thread32Next(snap, &mut e); + } + CloseHandle(snap); + n + } +} + +pub fn verify_serialized_queues_do_not_keep_threads() { + let a = api(); + let before = thread_count(); + let ran = counter(); + for _ in 0..256 { + let q = a.create(SERIALIZED, SERIALIZED); + assert_eq!(a.submit(q, WORK, 0, bump(&ran)), 0); + assert_eq!(a.submit(q, COMPLETION, 0, bump(&ran)), 0); + a.close(q); + } + assert!(until(5000, || ran.load(SeqCst) == 512)); + std::thread::sleep(Duration::from_millis(200)); + let after = thread_count(); + assert!(after < before + 192, "threads went from {before} to {after} for 256 closed serialized queues"); +} + + +pub fn verify_serialized_port_final_release() { + let a = api(); + let before = thread_count(); + for _ in 0..64 { + let q = a.create(SERIALIZED, SERIALIZED); + let ev = Arc::new(Event::new(true)); + let e = ev.clone(); + assert_eq!(a.submit(q, WORK, 0, move |canceled| if !canceled { e.set() }), 0); + assert!(ev.wait(5000), "serialized callback never ran"); + let d = a.dup(q); + a.close(q); + a.close(d); + } + std::thread::sleep(Duration::from_millis(200)); + let after = thread_count(); + assert!(after < before + 48, "threads went from {before} to {after} after releasing 64 serialized queues"); +} + +pub fn verify_serialized_port_survives_one_release() { + let a = api(); + let q = a.create(SERIALIZED, SERIALIZED); + let d = a.dup(q); + let ev = Arc::new(Event::new(true)); + let e = ev.clone(); + assert_eq!(a.submit(q, WORK, 0, move |canceled| if !canceled { e.set() }), 0); + assert!(ev.wait(5000)); + a.close(q); + ev.reset(); + let got = Arc::new(Mutex::new(None)); + let (e, g) = (ev.clone(), got.clone()); + assert_eq!(a.submit(d, WORK, 0, move |canceled| { *g.lock().unwrap() = Some(canceled); e.set() }), 0); + assert!(ev.wait(5000), "the remaining handle's serialized port stopped running"); + assert_eq!(*got.lock().unwrap(), Some(false), "a callback through the remaining handle was canceled"); + a.close(d); +} + +pub fn verify_serialized_idle_port_delivers_termination() { + let a = api(); + let q = a.create(SERIALIZED, SERIALIZED); + let ev = Arc::new(Event::new(true)); + let e = ev.clone(); + assert_eq!(a.submit(q, COMPLETION, 0, move |_| e.set()), 0); + assert!(ev.wait(5000)); + std::thread::sleep(Duration::from_millis(50)); + let done = Arc::new(Event::new(true)); + let dn = done.clone(); + assert_eq!(a.terminate(q, false, Some(Box::new(move || dn.set()))), 0); + assert!(done.wait(5000), "termination callback of an idle serialized queue never ran"); + a.close(q); +} + +pub fn verify_serialized_termination_during_callback() { + let a = api(); + let q = a.create(SERIALIZED, SERIALIZED); + let order = Arc::new(Mutex::new(Vec::new())); + let (started, gate) = (Arc::new(Event::new(true)), Arc::new(Event::new(true))); + let (s, g, o) = (started.clone(), gate.clone(), order.clone()); + assert_eq!(a.submit(q, WORK, 0, move |_| { s.set(); g.wait(5000); o.lock().unwrap().push("first") }), 0); + assert!(started.wait(5000)); + let o = order.clone(); + assert_eq!(a.submit(q, WORK, 0, move |canceled| o.lock().unwrap().push(if canceled { "second canceled" } else { "second ran" })), 0); + let done = Arc::new(Event::new(true)); + let (dn, o) = (done.clone(), order.clone()); + assert_eq!(a.terminate(q, false, Some(Box::new(move || { o.lock().unwrap().push("terminated"); dn.set() }))), 0); + assert!(!done.wait(100), "termination completed while a callback was still running"); + gate.set(); + assert!(done.wait(5000), "termination callback never ran"); + let order = order.lock().unwrap().clone(); + assert_eq!(order.len(), 3, "{order:?}"); + assert!(order.contains(&"first") && order.contains(&"second canceled"), "{order:?}"); + assert_eq!(order[2], "terminated", "the termination callback ran before the port's callbacks: {order:?}"); + a.close(q); +} + + +const FACTORIAL_ID: usize = 0xFAC7; + +#[derive(Default)] +pub struct Factorial { + pub value: AtomicU32, + pub result: AtomicU32, + pub wait_ms: u32, + pub work_thread: Mutex>, + pub ops: Mutex>, + pub in_work: AtomicI32, + pub canceled: AtomicBool, + pub cleanup_in_work: AtomicBool, +} + +impl Factorial { + pub fn new(value: u32, wait_ms: u32) -> Arc { + Arc::new(Factorial { value: AtomicU32::new(value), wait_ms, ..Default::default() }) + } + fn ops(&self) -> Vec { + self.ops.lock().unwrap().clone() + } + fn common(&self, op: u32, d: *const Data) -> Option { + self.ops.lock().unwrap().push(op); + match op { + OP_CANCEL => self.canceled.store(true, SeqCst), + OP_CLEANUP => { + if self.in_work.load(SeqCst) != 0 { + self.cleanup_in_work.store(true, SeqCst); + } + } + OP_GET_RESULT => unsafe { ((*d).buffer as *mut u32).write_unaligned(self.result.load(SeqCst)) }, + OP_DO_WORK => return None, + _ => {} + } + Some(0) + } +} + +unsafe extern "system" fn factorial_simple(op: u32, d: *const Data) -> i32 { + let f = &*((*d).context as *const Factorial); + if let Some(hr) = f.common(op, d) { + return hr; + } + f.in_work.fetch_add(1, SeqCst); + *f.work_thread.lock().unwrap() = Some(std::thread::current().id()); + let mut r = 1u32; + let mut v = f.value.load(SeqCst); + while v != 0 { + r = r.wrapping_mul(v); + v -= 1; + } + f.result.store(r, SeqCst); + if f.wait_ms != 0 { + std::thread::sleep(Duration::from_millis(f.wait_ms as u64)); + } + f.in_work.fetch_sub(1, SeqCst); + api().complete((*d).block, if f.canceled.load(SeqCst) { E_ABORT } else { 0 }, 4); + 0 +} + +unsafe extern "system" fn factorial_distributed(op: u32, d: *const Data) -> i32 { + let f = &*((*d).context as *const Factorial); + if let Some(hr) = f.common(op, d) { + return hr; + } + f.in_work.fetch_add(1, SeqCst); + *f.work_thread.lock().unwrap() = Some(std::thread::current().id()); + if f.result.load(SeqCst) == 0 { + f.result.store(1, SeqCst); + } + let v = f.value.load(SeqCst); + if v != 0 { + if f.canceled.load(SeqCst) { + f.in_work.fetch_sub(1, SeqCst); + return E_ABORT; + } + f.result.store(f.result.load(SeqCst) * v, SeqCst); + f.value.store(v - 1, SeqCst); + let hr = api().schedule((*d).block, f.wait_ms); + f.in_work.fetch_sub(1, SeqCst); + return if hr >= 0 { E_PENDING } else { hr }; + } + f.in_work.fetch_sub(1, SeqCst); + api().complete((*d).block, 0, 4); + 0 +} + +fn factorial_async(f: &Arc, b: &mut Block, distributed: bool) -> i32 { + let a = api(); + let p: Provider = if distributed { factorial_distributed } else { factorial_simple }; + let hr = a.begin(b, Arc::as_ptr(f) as usize, FACTORIAL_ID, p); + if hr < 0 { + return hr; + } + a.schedule(b, 0) +} + +fn factorial_result(b: *mut Block, out: &mut u32) -> i32 { + let mut used = 0usize; + let hr = api().result(b, FACTORIAL_ID, 4, out as *mut u32 as *mut c_void, &mut used); + if hr >= 0 { + assert_eq!(used, 4); + } + hr +} + +type Done = Box; +unsafe extern "system" fn done_tramp(b: *mut Block) { + (*((*b).context as *const Done))(b) +} +fn on_done(b: &mut Block, f: impl Fn(*mut Block) + Send + Sync + 'static) { + b.context = leak::(Box::new(f)) as usize; + b.callback = Some(done_tramp); +} + +unsafe extern "system" fn nop_provider(op: u32, d: *const Data) -> i32 { + let _ = (op, d); + 0 +} + +unsafe extern "system" fn abort_on_cancel(op: u32, d: *const Data) -> i32 { + if op == OP_CANCEL { + api().complete((*d).block, E_ABORT, 0); + } + 0 +} + +fn thread_pool_queue() -> usize { + api().create(THREAD_POOL, THREAD_POOL) +} + +fn settle(q: usize) { + let _ = q; + std::thread::sleep(Duration::from_millis(50)); +} + +pub fn verify_simple_async_call() { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 0); + let mut b = Block::new(q); + let result = Arc::new(AtomicI32::new(-1)); + let r = result.clone(); + on_done(&mut b, move |b| { + let mut v = 0; + let hr = factorial_result(b, &mut v); + r.store(if hr >= 0 { v as i32 } else { hr }, SeqCst); + }); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert_eq!(a.status(&mut *b, true), 0); + assert_eq!(result.load(SeqCst), 120, "XAsyncGetStatus(wait) returned before the completion callback ran"); + settle(q); + assert_eq!(f.ops(), vec![OP_BEGIN, OP_DO_WORK, OP_GET_RESULT, OP_CLEANUP]); + a.close(q); +} + +pub fn verify_multiple_calls() { + let a = api(); + let q = thread_pool_queue(); + let done = counter(); + let mut blocks = Vec::new(); + for i in 0..10u32 { + let f = Factorial::new(5 * (i + 1), 0); + let mut b = Block::new(q); + let (d, f2) = (done.clone(), f.clone()); + on_done(&mut b, move |b| { + let mut v = 0; + if factorial_result(b, &mut v) >= 0 && v == f2.result.load(SeqCst) { + d.fetch_add(1, SeqCst); + } + }); + assert_eq!(factorial_async(&f, &mut b, false), 0); + blocks.push((b, f)); + } + assert!(until(5000, || done.load(SeqCst) == 10)); + a.close(q); +} + +pub fn verify_distributed_async_call() { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 100); + let mut b = Block::new(q); + let result = Arc::new(AtomicI32::new(-1)); + let r = result.clone(); + on_done(&mut b, move |b| { + let mut v = 0; + let hr = factorial_result(b, &mut v); + r.store(if hr >= 0 { v as i32 } else { hr }, SeqCst); + }); + let start = Instant::now(); + assert_eq!(factorial_async(&f, &mut b, true), 0); + assert_eq!(a.status(&mut *b, true), 0); + let took = start.elapsed(); + assert_eq!(result.load(SeqCst), 120); + assert!(took >= Duration::from_millis(400), "rescheduled DoWork ignored its delay ({took:?})"); + settle(q); + let mut ops = vec![OP_BEGIN]; + ops.extend([OP_DO_WORK; 6]); + ops.extend([OP_GET_RESULT, OP_CLEANUP]); + assert_eq!(f.ops(), ops); + a.close(q); +} + +pub fn verify_async_block_reuse() { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 0); + let mut b = Box::new(Block { queue: q, context: 0, callback: None, internal: [0xCD; 32] }); + let result = Arc::new(AtomicI32::new(-1)); + let r = result.clone(); + on_done(&mut b, move |b| { + let mut v = 0; + let hr = factorial_result(b, &mut v); + r.store(if hr >= 0 { v as i32 } else { hr }, SeqCst); + }); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert_eq!(a.status(&mut *b, true), 0); + assert_eq!(result.load(SeqCst), 120); + b.callback = None; + f.value.store(6, SeqCst); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert_eq!(factorial_async(&f, &mut b, false), E_INVALIDARG, "an async block in use must not be reusable"); + assert_eq!(a.status(&mut *b, true), 0); + let mut v = 0; + assert_eq!(factorial_result(&mut *b, &mut v), 0); + assert_eq!(v, 720); + a.close(q); +} + +pub fn verify_cancellation() { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 100); + let mut b = Block::new(q); + let in_cb = Arc::new(AtomicI32::new(1)); + let c = in_cb.clone(); + on_done(&mut b, move |b| c.store(api().status(b, false), SeqCst)); + assert_eq!(factorial_async(&f, &mut b, true), 0); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(a.status(&mut *b, false), E_PENDING); + a.cancel(&mut *b); + assert_eq!(a.status(&mut *b, true), E_ABORT); + assert_eq!(in_cb.load(SeqCst), E_ABORT); + settle(q); + let ops = f.ops(); + assert!(ops.contains(&OP_CANCEL) && ops.contains(&OP_CLEANUP), "{ops:?}"); + a.close(q); +} + +fn cleanup_waits_for_work(distributed: bool) { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 500); + let mut b = Block::new(q); + let in_cb = Arc::new(AtomicI32::new(1)); + let c = in_cb.clone(); + on_done(&mut b, move |b| { + let mut v = 0; + c.store(factorial_result(b, &mut v), SeqCst) + }); + assert_eq!(factorial_async(&f, &mut b, distributed), 0); + std::thread::sleep(Duration::from_millis(if distributed { 700 } else { 50 })); + assert_eq!(a.status(&mut *b, false), E_PENDING); + a.cancel(&mut *b); + assert_eq!(a.status(&mut *b, true), E_ABORT); + assert_eq!(in_cb.load(SeqCst), E_ABORT); + assert!(until(2000, || f.ops().contains(&OP_CLEANUP))); + let ops = f.ops(); + assert!(ops.contains(&OP_CANCEL) && ops.contains(&OP_DO_WORK), "{ops:?}"); + assert!(!f.cleanup_in_work.load(SeqCst), "XAsyncOp::Cleanup ran while DoWork was still running: {ops:?}"); + a.close(q); +} + +pub fn verify_cleanup_waits_for_work() { + cleanup_waits_for_work(false); +} + +pub fn verify_cleanup_waits_for_work_distributed() { + cleanup_waits_for_work(true); +} + +static RUN_EXPECTED: AtomicI32 = AtomicI32::new(0); +unsafe extern "system" fn run_work(_b: *mut Block) -> i32 { + RUN_EXPECTED.load(SeqCst) +} + +pub fn verify_run_async() { + let a = api(); + let q = thread_pool_queue(); + RUN_EXPECTED.store(0x12345678, SeqCst); + let mut b = Block::new(q); + assert_eq!(a.run(&mut *b, run_work), 0); + assert_eq!(a.status(&mut *b, true), 0x12345678); + a.close(q); +} + +pub fn verify_custom_queue() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let f = Factorial::new(5, 0); + let mut b = Block::new(q); + let seen = Arc::new(Mutex::new(None)); + let s = seen.clone(); + on_done(&mut b, move |b| { + let mut v = 0; + let hr = factorial_result(b, &mut v); + *s.lock().unwrap() = Some((hr, v, std::thread::current().id())); + }); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert!(a.dispatch(q, WORK, 100), "XAsyncSchedule did not post DoWork to the work port"); + assert_eq!(f.result.load(SeqCst), 120); + assert_eq!(*f.work_thread.lock().unwrap(), Some(std::thread::current().id())); + assert!(seen.lock().unwrap().is_none(), "completion ran before its port was dispatched"); + assert!(a.dispatch(q, COMPLETION, 100), "completion was not posted to the completion port"); + assert_eq!(*seen.lock().unwrap(), Some((0, 120, std::thread::current().id()))); + assert!(!a.dispatch(q, WORK, 0) && !a.dispatch(q, COMPLETION, 0)); + a.close(q); +} + +pub fn verify_cant_schedule_twice() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + let f = Factorial::new(5, 0); + let mut b = Block::new(q); + assert_eq!(a.begin(&mut *b, Arc::as_ptr(&f) as usize, 0, factorial_simple), 0); + assert_eq!(a.schedule(&mut *b, 0), 0); + assert_eq!(a.schedule(&mut *b, 0), E_UNEXPECTED); + a.cancel(&mut *b); + drain(q); + assert_ne!(a.status(&mut *b, false), E_PENDING); + a.close(q); +} + +pub fn verify_wait_for_completion() { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 0); + let mut b = Block::new(q); + let finished = Arc::new(AtomicBool::new(false)); + let fin = finished.clone(); + on_done(&mut b, move |b| { + std::thread::sleep(Duration::from_millis(300)); + let mut v = 0; + if factorial_result(b, &mut v) >= 0 && v == 120 { + fin.store(true, SeqCst); + } + }); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert_eq!(a.status(&mut *b, true), 0); + assert!(finished.load(SeqCst), "XAsyncGetStatus(wait) must wait for the completion callback to finish"); + a.close(q); +} + +pub fn verify_periodic_pattern() { + let a = api(); + let q = thread_pool_queue(); + struct Ctl { + q: usize, + enabled: AtomicBool, + count: AtomicU32, + } + unsafe extern "system" fn provider(op: u32, d: *const Data) -> i32 { + if op == OP_DO_WORK { + api().complete((*d).block, 0, 0); + } + 0 + } + unsafe extern "system" fn done(b: *mut Block) { + let c = &*((*b).context as *const Ctl); + c.count.fetch_add(1, SeqCst); + if c.enabled.load(SeqCst) { + schedule(c); + } + drop(Box::from_raw(b)); + } + fn schedule(c: &Ctl) { + let b = Box::into_raw(Box::new(Block { queue: c.q, context: c as *const Ctl as usize, callback: Some(done), internal: [0; 32] })); + assert_eq!(api().begin(b, 0, 0, provider), 0); + assert_eq!(api().schedule(b, 30), 0); + } + let c = Arc::new(Ctl { q, enabled: AtomicBool::new(true), count: AtomicU32::new(0) }); + schedule(&c); + assert!(until(10000, || c.count.load(SeqCst) >= 10)); + c.enabled.store(false, SeqCst); + assert_eq!(a.terminate(q, true, None), 0); + a.close(q); +} + +unsafe extern "system" fn zero_work(_b: *mut Block) -> i32 { + 0 +} + +pub fn verify_run_alot_async() { + let a = api(); + let q = thread_pool_queue(); + let mut blocks: Vec = (0..20000).map(|_| *Block::new(q)).collect(); + for b in blocks.iter_mut() { + assert_eq!(a.run(b, zero_work), 0); + } + for b in blocks.iter_mut() { + assert_eq!(a.status(b, true), 0); + } + a.close(q); +} + +unsafe extern "system" fn short_work(_b: *mut Block) -> i32 { + std::thread::sleep(Duration::from_millis(1)); + 0 +} + +pub fn verify_get_async_status_no_deadlock() { + let a = api(); + let q = thread_pool_queue(); + let mut b = Block::new(q); + for _ in 0..300 { + assert_eq!(a.run(&mut *b, short_work), 0); + while a.status(&mut *b, false) == E_PENDING { + std::thread::yield_now(); + } + } + a.close(q); +} + +pub fn verify_failed_begin_completes() { + let a = api(); + let q = thread_pool_queue(); + unsafe extern "system" fn fail(op: u32, _d: *const Data) -> i32 { + if op == OP_BEGIN { + E_FAIL + } else { + E_UNEXPECTED + } + } + let mut b = Block::new(q); + let called = Arc::new(AtomicI32::new(1)); + let c = called.clone(); + on_done(&mut b, move |b| c.store(api().status(b, false), SeqCst)); + assert_eq!(a.begin(&mut *b, 0, 0, fail), 0, "XAsyncBegin succeeds even when the Begin op fails"); + assert_eq!(a.status(&mut *b, true), E_FAIL); + assert!(until(2000, || called.load(SeqCst) == E_FAIL), "a failed Begin still completes through the callback"); + a.close(q); +} + +pub fn verify_pending_begin_stays_pending() { + let a = api(); + let q = thread_pool_queue(); + unsafe extern "system" fn pending(op: u32, _d: *const Data) -> i32 { + if op == OP_BEGIN { + E_PENDING + } else { + 0 + } + } + let mut b = Block::new(q); + let called = Arc::new(AtomicI32::new(1)); + let c = called.clone(); + on_done(&mut b, move |b| c.store(api().status(b, false), SeqCst)); + let hr = a.begin(&mut *b, 0, 0, pending); + assert!(hr == 0 || hr == E_PENDING, "XAsyncBegin with a Begin op returning E_PENDING returned {hr:#x}"); + assert_eq!(a.status(&mut *b, false), E_PENDING, "a Begin op returning E_PENDING must leave the call pending"); + assert!(!until(300, || called.load(SeqCst) != 1), "the completion callback ran for a call still pending"); + a.complete(&mut *b, 0, 0); + assert_eq!(a.status(&mut *b, true), 0); + assert!(until(2000, || called.load(SeqCst) == 0), "completing the pending call must run the callback"); + a.close(q); +} + +pub fn verify_zero_payload_cleans_up_fast() { + let a = api(); + let q = a.create(MANUAL, MANUAL); + unsafe extern "system" fn empty(op: u32, d: *const Data) -> i32 { + match op { + OP_BEGIN => { + assert_eq!(api().schedule((*d).block, 0), 0); + } + OP_DO_WORK => api().complete((*d).block, 0, 0), + OP_CLEANUP => { + (*((*d).context as *const AtomicU32)).fetch_add(1, SeqCst); + } + _ => {} + } + 0 + } + let cleanups = AtomicU32::new(0); + let mut b = Block::new(q); + assert_eq!(a.begin(&mut *b, &cleanups as *const AtomicU32 as usize, 0, empty), 0); + assert!(a.dispatch(q, WORK, 0)); + assert_eq!(cleanups.load(SeqCst), 1, "a zero-payload call must clean up when DoWork completes it"); + drain(q); + assert_eq!(cleanups.load(SeqCst), 1, "cleanup ran twice"); + a.close(q); +} + +pub fn verify_complete_in_begin() { + let a = api(); + let q = thread_pool_queue(); + unsafe extern "system" fn provider(op: u32, d: *const Data) -> i32 { + if op == OP_BEGIN { + api().complete((*d).block, 0, 0); + } + 0 + } + let ev = Arc::new(Event::new(true)); + let mut b = Block::new(q); + let e = ev.clone(); + on_done(&mut b, move |_| e.set()); + assert_eq!(a.begin(&mut *b, 0, 0, provider), 0); + assert_eq!(a.status(&mut *b, true), 0); + assert!(ev.wait(2500)); + a.close(q); +} + +pub fn verify_begin_after_terminate() { + let a = api(); + let q = thread_pool_queue(); + assert_eq!(a.terminate(q, true, None), 0); + let mut b = Block::new(q); + assert_eq!(a.begin(&mut *b, 0, 0, nop_provider), E_ABORT); + a.close(q); +} + +pub fn verify_failure_in_do_work() { + let a = api(); + let q = thread_pool_queue(); + unsafe extern "system" fn special(op: u32, d: *const Data) -> i32 { + match op { + OP_BEGIN => api().schedule((*d).block, 0), + OP_DO_WORK => 0x8009_ABCDu32 as i32, + _ => 0, + } + } + unsafe extern "system" fn forgets(op: u32, d: *const Data) -> i32 { + match op { + OP_BEGIN => api().schedule((*d).block, 0), + _ => 0, + } + } + let mut b = Block::new(q); + assert_eq!(a.begin(&mut *b, 0, 0, special), 0); + assert_eq!(a.status(&mut *b, true), 0x8009_ABCDu32 as i32); + let mut b = Block::new(q); + assert_eq!(a.begin(&mut *b, 0, 0, forgets), 0); + assert_eq!(a.status(&mut *b, true), E_UNEXPECTED, "DoWork returning S_OK without XAsyncComplete"); + a.close(q); +} + +pub fn verify_duplicate_result_calls_fail() { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 0); + let mut b = Block::new(q); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert_eq!(a.status(&mut *b, true), 0); + let mut v = 0; + assert_eq!(factorial_result(&mut *b, &mut v), 0); + assert_eq!(factorial_result(&mut *b, &mut v), E_ILLEGAL_METHOD_CALL); + a.close(q); +} + +pub fn verify_duplicate_pending_result_calls_succeed() { + let a = api(); + let q = thread_pool_queue(); + struct Ctx { + complete: Event, + waiting: Event, + } + unsafe extern "system" fn provider(op: u32, d: *const Data) -> i32 { + match op { + OP_BEGIN => api().schedule((*d).block, 0), + OP_DO_WORK => { + let c = &*((*(*d).block).context as *const Ctx); + c.waiting.set(); + c.complete.wait(INFINITE); + api().complete((*d).block, 0, 0); + 0 + } + _ => 0, + } + } + let ctx = Ctx { complete: Event::new(true), waiting: Event::new(true) }; + let mut b = Block::new(q); + b.context = &ctx as *const Ctx as usize; + assert_eq!(a.begin(&mut *b, 0, 0, provider), 0); + assert!(ctx.waiting.wait(2000)); + for _ in 0..10 { + assert_eq!(a.result(&mut *b, 0, 0, core::ptr::null_mut(), core::ptr::null_mut()), E_PENDING); + } + ctx.complete.set(); + assert_eq!(a.status(&mut *b, true), 0); + assert_eq!(a.result(&mut *b, 0, 0, core::ptr::null_mut(), core::ptr::null_mut()), 0); + assert_eq!(a.result(&mut *b, 0, 0, core::ptr::null_mut(), core::ptr::null_mut()), 0, "a zero-payload result stays readable"); + a.close(q); +} + +pub fn verify_no_write_after_get_status_race() { + let a = api(); + let q = thread_pool_queue(); + struct Ctx { + m: Mutex<(usize, bool, bool, bool)>, + cv: std::sync::Condvar, + } + unsafe extern "system" fn provider(op: u32, d: *const Data) -> i32 { + if op == OP_CANCEL { + let c = &*((*d).context as *const Ctx); + c.m.lock().unwrap().1 = true; + c.cv.notify_all(); + } + 0 + } + let ctx = Arc::new(Ctx { m: Mutex::new((0, false, false, false)), cv: std::sync::Condvar::new() }); + let c = ctx.clone(); + let worker = std::thread::spawn(move || loop { + let ctx = &*c; + let block = { + let mut g = ctx.cv.wait_while(ctx.m.lock().unwrap(), |g| !g.3 && !g.1).unwrap(); + if g.3 { + return; + } + g.1 = false; + g.0 + }; + api().complete(block as *mut Block, E_ABORT, 0); + ctx.m.lock().unwrap().2 = true; + ctx.cv.notify_all(); + }); + for i in 0..2000 { + let mut b = Block::new(q); + *ctx.m.lock().unwrap() = (&mut *b as *mut Block as usize, false, false, false); + assert_eq!(a.begin(&mut *b, Arc::as_ptr(&ctx) as usize, 0, provider), 0); + a.cancel(&mut *b); + assert_eq!(a.status(&mut *b, true), E_ABORT); + let snap = b.bytes(); + drop(ctx.cv.wait_while(ctx.m.lock().unwrap(), |g| !g.2).unwrap()); + assert_eq!(snap, b.bytes(), "iteration {i}: the async block was written after XAsyncGetStatus(wait) returned"); + } + ctx.m.lock().unwrap().3 = true; + ctx.cv.notify_all(); + worker.join().unwrap(); + a.close(q); +} + +pub fn verify_result_buffer_checks() { + let a = api(); + let q = thread_pool_queue(); + let f = Factorial::new(5, 0); + let mut b = Block::new(q); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert_eq!(a.status(&mut *b, true), 0); + let mut size = 0usize; + assert_eq!(a.result_size(&mut *b, &mut size), 0); + assert_eq!(size, 4); + let mut used = 0usize; + assert_eq!(a.result(&mut *b, FACTORIAL_ID, 4, core::ptr::null_mut(), &mut used), E_INVALIDARG); + + let f = Factorial::new(5, 0); + let mut b = Block::new(q); + assert_eq!(factorial_async(&f, &mut b, false), 0); + assert_eq!(a.status(&mut *b, true), 0); + let mut v = 0u16; + assert_eq!(a.result(&mut *b, FACTORIAL_ID, 2, &mut v as *mut u16 as *mut c_void, &mut used), E_NOT_SUFFICIENT_BUFFER); + + unsafe extern "system" fn failing(op: u32, d: *const Data) -> i32 { + match op { + OP_BEGIN => api().schedule((*d).block, 0), + OP_DO_WORK => { + api().complete((*d).block, E_FAIL, 16); + 0 + } + _ => 0, + } + } + let mut b = Block::new(q); + assert_eq!(a.begin(&mut *b, 0, 0, failing), 0); + assert_eq!(a.status(&mut *b, true), E_FAIL); + let mut size = 99usize; + assert_eq!(a.result_size(&mut *b, &mut size), E_FAIL); + assert_eq!(size, 0); + a.close(q); +} + + +macro_rules! xtq_tests { + ($setup:path) => { + xtq_tests!(@ $setup; + verify_stock_queue, verify_composite_queue, verify_duplicate_queue_handle, verify_dispatch, + verify_submitted_callback, verify_submit_callback_with_wait, verify_register_callback_submitted, + verify_immediate_dispatch, verify_serialized_thread_pool_dispatch, + verify_serialized_thread_pool_does_not_strand_items, verify_multithread_manual_dispatch, + verify_register_with_auto_reset, verify_shared_port_queue_rundown_keeps_other_waiters, + verify_shared_port_queue_rundown_drops_its_wait_handles, verify_queue_termination, + verify_empty_queue_termination, verify_global_queue, verify_close_in_termination_for_thread_pool, + verify_close_in_termination_for_manual, verify_wait_termination, verify_manual_dispatch_at_termination, + verify_termination_of_composite_queue, verify_termination_of_base_queue_keeps_composites, + verify_queue_monitor_has_correct_ports, + verify_nested_queue_dispatch_order, verify_terminate_waits_for_async_in_flight, + verify_single_queue_delayed_poll_strand, verify_composite_queue_delayed_callback_starvation, + verify_termination_cancels_delayed_callbacks, verify_close_keeps_queued_callbacks, + verify_dispatch_on_pool_port, verify_thread_pool_callbacks_can_block, + verify_serialized_queues_do_not_keep_threads, verify_serialized_port_final_release, + verify_serialized_port_survives_one_release, verify_serialized_idle_port_delivers_termination, + verify_serialized_termination_during_callback, + verify_simple_async_call, verify_multiple_calls, verify_distributed_async_call, verify_async_block_reuse, + verify_cancellation, verify_cleanup_waits_for_work, verify_cleanup_waits_for_work_distributed, + verify_run_async, verify_custom_queue, verify_cant_schedule_twice, verify_wait_for_completion, + verify_periodic_pattern, verify_run_alot_async, verify_get_async_status_no_deadlock, + verify_failed_begin_completes, verify_pending_begin_stays_pending, verify_zero_payload_cleans_up_fast, verify_complete_in_begin, + verify_begin_after_terminate, verify_failure_in_do_work, verify_duplicate_result_calls_fail, + verify_duplicate_pending_result_calls_succeed, verify_no_write_after_get_status_race, + verify_result_buffer_checks); + }; + (@ $setup:path; $($name:ident),* $(,)?) => { + $( + #[test] + fn $name() { + if $setup(stringify!($name)) { + xtq::$name(); + } + } + )* + }; +} diff --git a/crates/compat/connectedstorageservice_proxystub/build.rs b/crates/compat/connectedstorageservice_proxystub/build.rs index 3c02b7cf..10da1553 100644 --- a/crates/compat/connectedstorageservice_proxystub/build.rs +++ b/crates/compat/connectedstorageservice_proxystub/build.rs @@ -1,4 +1,8 @@ fn main() { println!("cargo:rerun-if-changed=data/proxy_19041.bin"); + let data = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")).join("data/proxy_19041.bin"); + if !data.is_file() { + panic!("missing input file {}: it is generated locally from a system binary and is not part of the repository (*.bin is in .gitignore), so this crate does not build without it", data.display()); + } xone_exports::emit_link_args("proxy_exports.txt"); } diff --git a/crates/compat/console-sandbox/src/comreg.rs b/crates/compat/console-sandbox/src/comreg.rs new file mode 100644 index 00000000..c4ee4186 --- /dev/null +++ b/crates/compat/console-sandbox/src/comreg.rs @@ -0,0 +1,252 @@ +use core::ffi::c_void; +use std::sync::{Mutex, MutexGuard}; + +pub const S_OK: i32 = 0; +pub const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; +pub const E_POINTER: i32 = 0x8000_4003u32 as i32; +pub const E_OUTOFMEMORY: i32 = 0x8007_000Eu32 as i32; +pub const E_NOINTERFACE: i32 = 0x8000_4002u32 as i32; +pub const CLASS_E_NOAGGREGATION: i32 = 0x8004_0110u32 as i32; +pub const CO_E_OBJISREG: i32 = 0x8004_01FBu32 as i32; +pub const REGDB_E_CLASSNOTREG: i32 = 0x8004_0154u32 as i32; +pub const CO_E_ERRORINAPP: i32 = 0x8000_4019u32 as i32; + +pub const CLSCTX_INPROC_SERVER: u32 = 0x1; +pub const CLSCTX_LOCAL_SERVER: u32 = 0x4; +pub const REGCLS_SINGLEUSE: u32 = 0; +pub const REGCLS_MULTIPLEUSE: u32 = 1; +pub const REGCLS_MULTI_SEPARATE: u32 = 2; +pub const REGCLS_SUSPENDED: u32 = 4; + +pub const IID_IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46]; +pub const IID_ICLASSFACTORY: [u8; 16] = [1, 0, 0, 0, 0, 0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46]; + +#[link(name = "ole32")] +extern "system" { + fn CoCreateInstance(clsid: *const [u8; 16], outer: *mut c_void, ctx: u32, iid: *const [u8; 16], out: *mut *mut c_void) -> i32; + fn CoGetClassObject(clsid: *const [u8; 16], ctx: u32, info: *mut c_void, iid: *const [u8; 16], out: *mut *mut c_void) -> i32; +} + +#[link(name = "runtimeobject")] +extern "system" { + fn RoGetActivationFactory(id: *mut c_void, iid: *const [u8; 16], out: *mut *mut c_void) -> i32; + fn WindowsGetStringRawBuffer(h: *mut c_void, len: *mut u32) -> *const u16; +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ClassEntry { + pub cookie: u32, + pub clsid: [u8; 16], + pub object: usize, + pub context: u32, + pub flags: u32, + pub suspended: bool, + pub used: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FactoryEntry { + pub cookie: usize, + pub class: String, + pub callback: usize, +} + +#[derive(Default)] +struct Table { + classes: Vec, + factories: Vec, + next_cookie: u32, + next_factory: usize, +} + +fn table() -> MutexGuard<'static, Table> { + static T: Mutex = Mutex::new(Table { classes: Vec::new(), factories: Vec::new(), next_cookie: 0, next_factory: 0 }); + T.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub fn classes() -> Vec { + table().classes.clone() +} + +pub fn factories() -> Vec { + table().factories.clone() +} + +unsafe fn vcall(obj: usize, slot: usize) -> F { + let vt = (obj as *const usize).read(); + core::mem::transmute_copy(&((vt + slot * 8) as *const usize).read()) +} + +pub unsafe fn add_ref(obj: usize) -> u32 { + let f: unsafe extern "system" fn(usize) -> u32 = vcall(obj, 1); + f(obj) +} + +pub unsafe fn release(obj: usize) -> u32 { + let f: unsafe extern "system" fn(usize) -> u32 = vcall(obj, 2); + f(obj) +} + +pub unsafe fn query_interface(obj: usize, iid: &[u8; 16], out: *mut *mut c_void) -> i32 { + let f: unsafe extern "system" fn(usize, *const [u8; 16], *mut *mut c_void) -> i32 = vcall(obj, 0); + f(obj, iid, out) +} + +unsafe fn guid(p: *const [u8; 16]) -> [u8; 16] { + p.read_unaligned() +} + +pub unsafe extern "system" fn co_register_class_object(clsid: *const [u8; 16], unk: *mut c_void, ctx: u32, flags: u32, cookie: *mut u32) -> i32 { + if clsid.is_null() || unk.is_null() || cookie.is_null() { + return E_INVALIDARG; + } + if flags & !(REGCLS_MULTIPLEUSE | REGCLS_MULTI_SEPARATE | REGCLS_SUSPENDED | 8 | 0x10 | 0x20) != 0 { + return E_INVALIDARG; + } + let c = guid(clsid); + let registered = table().classes.iter().any(|e| e.clsid == c && e.context & ctx != 0 && !(e.flags & 3 == REGCLS_SINGLEUSE && e.used)); + if registered && flags & REGCLS_MULTIPLEUSE == 0 { + return CO_E_OBJISREG; + } + add_ref(unk as usize); + let mut t = table(); + t.next_cookie += 1; + let k = t.next_cookie; + t.classes.push(ClassEntry { cookie: k, clsid: c, object: unk as usize, context: ctx, flags, suspended: flags & REGCLS_SUSPENDED != 0, used: false }); + *cookie = k; + S_OK +} + +pub unsafe extern "system" fn co_revoke_class_object(cookie: u32) -> i32 { + let e = { + let mut t = table(); + match t.classes.iter().position(|e| e.cookie == cookie) { + Some(i) => t.classes.remove(i), + None => return E_INVALIDARG, + } + }; + release(e.object); + S_OK +} + +pub unsafe extern "system" fn co_resume_class_objects() -> i32 { + for e in table().classes.iter_mut() { + e.suspended = false; + } + S_OK +} + +fn take_class(clsid: &[u8; 16], ctx: u32, local: bool) -> Option { + let mut t = table(); + let e = t.classes.iter_mut().find(|e| &e.clsid == clsid && e.context & ctx != 0 && !(local && e.suspended) && !(e.flags & 3 == REGCLS_SINGLEUSE && e.used))?; + if e.flags & 3 == REGCLS_SINGLEUSE { + e.used = true; + } + Some(e.object) +} + +pub unsafe fn class_object(clsid: &[u8; 16], ctx: u32, iid: &[u8; 16], out: *mut *mut c_void) -> Option { + let obj = take_class(clsid, ctx, ctx & CLSCTX_INPROC_SERVER == 0)?; + Some(query_interface(obj, iid, out)) +} + +pub unsafe extern "system" fn co_get_class_object(clsid: *const [u8; 16], ctx: u32, info: *mut c_void, iid: *const [u8; 16], out: *mut *mut c_void) -> i32 { + if clsid.is_null() || iid.is_null() || out.is_null() { + return E_INVALIDARG; + } + *out = core::ptr::null_mut(); + match class_object(&guid(clsid), ctx, &guid(iid), out) { + Some(r) => r, + None => CoGetClassObject(clsid, ctx, info, iid, out), + } +} + +pub unsafe fn create_from_table(clsid: &[u8; 16], outer: *mut c_void, ctx: u32, iid: &[u8; 16], out: *mut *mut c_void) -> Option { + let mut cf: *mut c_void = core::ptr::null_mut(); + let r = class_object(clsid, ctx, &IID_ICLASSFACTORY, &mut cf)?; + if r < 0 { + return Some(r); + } + let f: unsafe extern "system" fn(usize, *mut c_void, *const [u8; 16], *mut *mut c_void) -> i32 = vcall(cf as usize, 3); + let hr = f(cf as usize, outer, iid, out); + release(cf as usize); + Some(hr) +} + +pub unsafe extern "system" fn co_create_instance(clsid: *const [u8; 16], outer: *mut c_void, ctx: u32, iid: *const [u8; 16], out: *mut *mut c_void) -> i32 { + if out.is_null() { + return E_POINTER; + } + *out = core::ptr::null_mut(); + if clsid.is_null() || iid.is_null() { + return E_INVALIDARG; + } + match create_from_table(&guid(clsid), outer, ctx, &guid(iid), out) { + Some(r) => r, + None => CoCreateInstance(clsid, outer, ctx, iid, out), + } +} + +unsafe fn hstring_text(h: *mut c_void) -> String { + if h.is_null() { + return String::new(); + } + let mut n = 0u32; + let p = WindowsGetStringRawBuffer(h, &mut n); + if p.is_null() { + return String::new(); + } + String::from_utf16_lossy(std::slice::from_raw_parts(p, n as usize)) +} + +pub unsafe extern "system" fn ro_register_activation_factories(ids: *const *mut c_void, callbacks: *const usize, count: u32, cookie: *mut usize) -> i32 { + if ids.is_null() || callbacks.is_null() || cookie.is_null() || count == 0 { + return E_INVALIDARG; + } + let names: Vec = (0..count as usize).map(|i| hstring_text(*ids.add(i))).collect(); + if names.iter().any(|n| n.is_empty()) || (0..count as usize).any(|i| *callbacks.add(i) == 0) { + return E_INVALIDARG; + } + let mut t = table(); + if names.iter().any(|n| t.factories.iter().any(|f| &f.class == n)) { + return CO_E_OBJISREG; + } + t.next_factory += 1; + let k = t.next_factory; + for (i, n) in names.into_iter().enumerate() { + t.factories.push(FactoryEntry { cookie: k, class: n, callback: *callbacks.add(i) }); + } + *cookie = k; + S_OK +} + +pub unsafe extern "system" fn ro_revoke_activation_factories(cookie: usize) { + table().factories.retain(|f| f.cookie != cookie); +} + +pub unsafe fn activation_factory(class: &str, id: *mut c_void, iid: &[u8; 16], out: *mut *mut c_void) -> Option { + let cb = table().factories.iter().find(|f| f.class == class).map(|f| f.callback)?; + let f: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> i32 = core::mem::transmute(cb); + let mut fac: *mut c_void = core::ptr::null_mut(); + let hr = f(id, &mut fac); + if hr < 0 { + return Some(hr); + } + if fac.is_null() { + return Some(CO_E_ERRORINAPP); + } + let r = query_interface(fac as usize, iid, out); + release(fac as usize); + Some(r) +} + +pub unsafe extern "system" fn ro_get_activation_factory(id: *mut c_void, iid: *const [u8; 16], out: *mut *mut c_void) -> i32 { + if out.is_null() || iid.is_null() { + return E_INVALIDARG; + } + *out = core::ptr::null_mut(); + match activation_factory(&hstring_text(id), id, &guid(iid), out) { + Some(r) => r, + None => RoGetActivationFactory(id, iid, out), + } +} diff --git a/crates/compat/console-sandbox/src/crossvm.rs b/crates/compat/console-sandbox/src/crossvm.rs index e6e6821f..21ac278c 100644 --- a/crates/compat/console-sandbox/src/crossvm.rs +++ b/crates/compat/console-sandbox/src/crossvm.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use std::sync::atomic::{AtomicU32, Ordering}; -use std::sync::{Mutex, MutexGuard, OnceLock}; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; use crate::gcdcom::Guid; use crate::wasapi; @@ -56,6 +56,11 @@ pub const SPATIAL_STREAM_AVAILABLE: u32 = 0x35; pub const FORMAT_ENUM_COUNT: u32 = 0x3a; pub const FORMAT_ENUM_GET: u32 = 0x3b; pub const CLOCK_SET_SAMPLE_RATE: u32 = 0x47; +pub const ITEM_GET: u32 = 0x3c; +pub const ITEM_COUNT: u32 = 0x3d; +pub const ITEM_FLAG: u32 = 0x3e; +pub const ITEM_VALUE: u32 = 0x3f; +pub const ITEM_SERVICE_TYPE: u32 = 0xb; pub const ENDPOINT_REGISTER: u32 = 0x4f; pub const ENDPOINT_UNREGISTER: u32 = 0x50; pub const ENDPOINT_CHANNEL_COUNT: u32 = 0x51; @@ -94,6 +99,36 @@ pub const METHOD_DEFAULT_ENDPOINT_19041: u32 = 0x22; pub const METHOD_ENDPOINT_19041: u32 = 0x25; pub const METHOD_DEFAULT_ENDPOINT: u32 = 0x80; pub const METHOD_ENDPOINT: u32 = 0x81; +pub const METHOD_SESSION_ENUMERATOR: u32 = 0x77; +pub const METHOD_ENUMERATED_SESSION: u32 = 0x78; +pub const METHOD_MEDIA_MANAGER: u32 = 0x61; +pub const METHOD_EXISTING_SESSION: u32 = 0x7b; +pub const MEDIA_MANAGER_TYPE: u32 = 0x13; +pub const EXISTING_SESSION_TYPE: u32 = 0x19; +pub const EXISTING_SESSION_CHARS: usize = 0x200; +pub const MEDIA_PLAY_TO_STREAM_STATE: u32 = 0x64; +pub const MEDIA_CASTING_APP_STATE: u32 = 0x65; +pub const MEDIA_VOIP_CALL_STATE: u32 = 0x66; +pub const METHOD_ARGS: usize = 0x14; +pub const SPATIAL_STREAM_TYPE: u32 = 0xf; +pub const SPATIAL_HRTF_STREAM_TYPE: u32 = 0x10; +pub const SPATIAL_METADATA_STREAM_TYPE: u32 = 0x16; +pub const METHOD_SPATIAL_STREAM: u32 = 0x36; +pub const METHOD_SPATIAL_HRTF_STREAM: u32 = 0x37; +pub const METHOD_SPATIAL_METADATA_STREAM: u32 = 0x38; +pub const METHOD_SPATIAL_STREAM2: u32 = 0x82; +pub const METHOD_SPATIAL_HRTF_STREAM2: u32 = 0x83; +pub const METHOD_SPATIAL_METADATA_STREAM2: u32 = 0x84; +pub const SPATIAL_ARG_MASK: usize = 0x14; +pub const SPATIAL_ARG_MIN: usize = 0x18; +pub const SPATIAL_ARG_MAX: usize = 0x1c; +pub const SPATIAL_ARG_CATEGORY: usize = 0x20; +pub const SPATIAL_ARG_FORMAT: usize = 0x24; +pub const SPATIAL_FORMAT_MAX: usize = 0x48; +pub const SPATIAL_ARG_OPTIONS: usize = 0x70; +pub const SPATIAL_PROPERTY_BYTES: u32 = 0x20; +pub const CLSID_SPATIAL_CLIENT_OUTPUT_ENDPOINT: Guid = Guid { data1: 0x9371E7FF, data2: 0xDF2D, data3: 0x4962, data4: [0x95, 0x85, 0x40, 0x42, 0x4D, 0x05, 0x45, 0x50] }; +pub const METHOD_REPLY_COUNT: usize = 0x14; pub const BLOB_ID: usize = 0x1c; pub const BLOB_ID_CHARS: usize = 0x37; @@ -152,6 +187,10 @@ pub const SPATIAL_CATEGORY_AT: usize = 0x48; pub const SPATIAL_FRAMES_AT: usize = 0x4c; pub const SPATIAL_OFFLOAD_AT: usize = 0x50; pub const FORMAT_ENUM_AT: usize = 4; +pub const FORMAT_ENUM_TYPE: u32 = 4; +pub const FORMAT_ENUM_CB_AT: usize = 0x14; +pub const FORMAT_ENUM_ROOM: usize = 0x48; +const E_BOUNDS: i32 = 0x8000_000bu32 as i32; pub const PLAIN_FORMAT: usize = 0x12; pub struct InitLayout { @@ -188,6 +227,7 @@ pub const KIND_NONE: u32 = 0; pub const KIND_CROSS_VM_EVENT: u32 = 2; pub const KIND_CROSS_VM_MEMORY: u32 = 3; +pub const CLSID_CLIENT_INPUT_ENDPOINT: Guid = Guid { data1: 0xF64A6DA6, data2: 0xE8AF, data3: 0x4B7B, data4: [0xBC, 0xA8, 0x84, 0x7A, 0xE7, 0x65, 0xD5, 0x38] }; pub const CLSID_CLIENT_OUTPUT_ENDPOINT: Guid = Guid { data1: 0xCD773740, data2: 0xB187, data3: 0x4974, data4: [0xA1, 0xD5, 0xE0, 0xFF, 0x91, 0x37, 0x22, 0x77] }; pub const CLSID_XVM_EVENT: Guid = Guid { data1: 0x148EC3BF, data2: 0x349C, data3: 0x4EAC, data4: [0xB3, 0x73, 0x9F, 0xD5, 0x7C, 0xB4, 0x6D, 0x88] }; pub const GUID_XVM_EVENT: Guid = Guid { data1: 0xA963C7E3, data2: 0x8A0A, data3: 0x45FA, data4: [0xBD, 0x23, 0xAA, 0x51, 0xE4, 0xCF, 0x85, 0x1E] }; @@ -245,17 +285,22 @@ struct Object { parent: u32, device: Option, stream: Option, - gain: f32, - mute: bool, volumes: Option>, properties: Option<[u32; 4]>, notify: bool, + notify_id: u32, + watch: Option, list_cursor: usize, + pc_sessions: Vec>, + pc_session: Option>, + media: Option<(wasapi::MediaManager, i64)>, + spatial: Option, + formats: Option, } impl Object { fn new(kind: u32, parent: u32, device: Option) -> Self { - Object { kind, parent, device, stream: None, gain: 1.0, mute: false, volumes: None, properties: None, notify: false, list_cursor: 0 } + Object { kind, parent, device, stream: None, volumes: None, properties: None, notify: false, notify_id: 0, watch: None, list_cursor: 0, pc_sessions: Vec::new(), pc_session: None, media: None, spatial: None, formats: None } } } @@ -273,6 +318,7 @@ struct State { next_event: u32, session: Option, session_channels: Option>, + session_simple: Option<(f32, bool)>, } fn state() -> MutexGuard<'static, State> { @@ -413,8 +459,26 @@ fn device_for(object: u32) -> Option { device_of(&state(), object) } -fn session_guid() -> Guid { - state().session.unwrap_or(GUID_NULL) +fn pc_session_of(s: &State, mut object: u32) -> Option> { + for _ in 0..16 { + let o = s.objects.get(&object)?; + if let Some(p) = &o.pc_session { + return Some(p.clone()); + } + if o.parent == 0 || o.parent == object { + return None; + } + object = o.parent; + } + None +} + +fn session_ref(object: u32) -> wasapi::SessionRef { + let s = state(); + match pc_session_of(&s, object) { + Some(p) => wasapi::SessionRef::Pc(p), + None => wasapi::SessionRef::Title(device_of(&s, object), s.session.unwrap_or(GUID_NULL)), + } } fn endpoint_key(dev: &Option) -> String { @@ -443,7 +507,8 @@ fn apply_all(s: &mut State) { let (es, em, ech) = s.endpoints.get(&key).map(|e| (e.scalar, e.mute, e.channels.clone())).unwrap_or((1.0, false, Vec::new())); let o = s.objects.get(&k).unwrap(); let st = o.stream.as_ref().unwrap(); - let gain = if o.mute || em { 0.0 } else { o.gain * es }; + let (sg, sm) = s.session_simple.unwrap_or((1.0, false)); + let gain = if sm || em { 0.0 } else { sg * es }; *st.renderer.shared.gain.lock().unwrap() = Some(gain.clamp(0.0, 1.0)); let n = wasapi::channels(&st.format) as usize; let mut v = o.volumes.clone().unwrap_or_else(|| vec![1.0; n]); @@ -471,16 +536,42 @@ fn scalar_to_level(v: f32, caps: &wasapi::EndpointCaps) -> f32 { } unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { + if id != CREATE_OBJECT && id != RELEASE_OBJECT { + if let Some(hr) = spatial_call(id, object, a) { + return hr; + } + let enumerator = state().objects.get(&object).map(|o| o.kind == FORMAT_ENUM_TYPE).unwrap_or(false); + if enumerator || id == FORMAT_ENUM_COUNT || id == FORMAT_ENUM_GET { + return format_enum(id, object, a); + } + } match id { CREATE_OBJECT => create_object(a, room), RELEASE_OBJECT => { let o = state().objects.remove(&object); + if let Some(Object { media: Some((m, token)), .. }) = &o { + let hr = m.remove_handler(*token); + compat_common::record_raw("crossvm-audio", "media-manager", &format!("object {object:#x} released, PC MediaManager handler {token:#x} removed -> {:#010x}", hr as u32)); + } if let Some(Object { stream: Some(st), .. }) = o { drop(st.renderer); crate::logan::pool_release(st.pool_index as usize); } S_OK } + MEDIA_PLAY_TO_STREAM_STATE | MEDIA_CASTING_APP_STATE | MEDIA_VOIP_CALL_STATE => { + let value: u32 = rd(a, 0); + let method = match id { + MEDIA_PLAY_TO_STREAM_STATE => wasapi::MEDIA_PLAY_TO_STREAM_STATE, + MEDIA_CASTING_APP_STATE => wasapi::MEDIA_CASTING_APP_STATE, + _ => wasapi::MEDIA_VOIP_CALL_STATE, + }; + let s = state(); + match s.objects.get(&object).and_then(|o| o.media.as_ref()) { + Some((m, _)) => m.state_changed(method, value), + None => E_INVALIDARG, + } + } GET_MIX_FORMAT => match wasapi::device_info_for(device_for(object).as_deref()) { Ok(d) => { core::ptr::write_bytes(a, 0, wasapi::MAX_FORMAT.min(room)); @@ -569,32 +660,79 @@ unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { Err(hr) => hr, }, STREAM_GET_CHANNEL_COUNT | STREAM_SET_CHANNEL_VOLUME | STREAM_GET_CHANNEL_VOLUME | STREAM_SET_ALL_VOLUMES | STREAM_GET_ALL_VOLUMES => stream_volume(id, object, a), + SET_SIMPLE_VOLUME | SET_SIMPLE_MUTE | GET_SIMPLE_VOLUME | GET_SIMPLE_MUTE if matches!(session_ref(object), wasapi::SessionRef::Pc(_)) => { + let r = session_ref(object); + match id { + SET_SIMPLE_VOLUME => { + let v: f32 = rd(a, 0); + if !(0.0..=1.0).contains(&v) { + return E_INVALIDARG; + } + wasapi::session_simple_set(&r, Some(v), None, &guid_from(&ctx_at(a, 4))) + } + SET_SIMPLE_MUTE => { + let m: u8 = rd(a, 0); + wasapi::session_simple_set(&r, None, Some(m != 0), &guid_from(&ctx_at(a, 1))) + } + _ => match wasapi::session_simple_get(&r) { + Ok((g, m)) => { + if id == GET_SIMPLE_VOLUME { + wr(a, 0, g); + } else { + wr(a, 0, m as u8); + } + S_OK + } + Err(hr) => hr, + }, + } + } SET_SIMPLE_VOLUME => { let v: f32 = rd(a, 0); if !(0.0..=1.0).contains(&v) { return E_INVALIDARG; } - simple(object, |o| o.gain = v).map(|_| S_OK).unwrap_or(E_INVALIDARG) + let ctx = ctx_at(a, 4); + match simple(object, |g, m| { + *g = v; + (*g, *m) + }) { + Some((g, m)) => { + session_changed(|sid| session_simple_record(sid, &ctx, g, m)); + S_OK + } + None => E_INVALIDARG, + } } SET_SIMPLE_MUTE => { let m: u8 = rd(a, 0); - simple(object, |o| o.mute = m != 0).map(|_| S_OK).unwrap_or(E_INVALIDARG) + let ctx = ctx_at(a, 1); + match simple(object, |g, mu| { + *mu = m != 0; + (*g, *mu) + }) { + Some((g, m)) => { + session_changed(|sid| session_simple_record(sid, &ctx, g, m)); + S_OK + } + None => E_INVALIDARG, + } } - GET_SIMPLE_VOLUME => match simple(object, |o| o.gain) { + GET_SIMPLE_VOLUME => match simple(object, |g, _| *g) { Some(g) => { wr(a, 0, g); S_OK } None => E_INVALIDARG, }, - GET_SIMPLE_MUTE => match simple(object, |o| o.mute) { + GET_SIMPLE_MUTE => match simple(object, |_, m| *m) { Some(m) => { wr(a, 0, m as u8); S_OK } None => E_INVALIDARG, }, - SESSION_GET_STATE => match wasapi::session_state(device_for(object).as_deref(), &session_guid()) { + SESSION_GET_STATE => match wasapi::session_state(&session_ref(object)) { Ok(st) => { wr(a, 0, st); S_OK @@ -607,7 +745,7 @@ unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { SESSION_GET_IDENTIFIER => (12, SESSION_STRING_CHARS), _ => (13, SESSION_STRING_CHARS), }; - match wasapi::session_string(device_for(object).as_deref(), &session_guid(), slot) { + match wasapi::session_string(&session_ref(object), slot) { Ok(t) => { if put_wide(a, &t, chars) { S_OK } else { E_OUTOFMEMORY } } @@ -618,9 +756,9 @@ unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { let Some(name) = wide_at(a, DISPLAY_NAME_CHARS) else { return E_INVALIDARG }; let ctx = guid_from(core::slice::from_raw_parts(a.add(DISPLAY_NAME_CHARS * 2), 16)); let w: Vec = name.encode_utf16().chain(Some(0)).collect(); - wasapi::session_set_display_name(device_for(object).as_deref(), &session_guid(), &w, &ctx) + wasapi::session_set_display_name(&session_ref(object), &w, &ctx) } - SESSION_GET_GROUPING => match wasapi::session_grouping(device_for(object).as_deref(), &session_guid()) { + SESSION_GET_GROUPING => match wasapi::session_grouping(&session_ref(object)) { Ok(g) => { core::ptr::copy_nonoverlapping(guid_bytes(&g).as_ptr(), a, 16); S_OK @@ -630,10 +768,10 @@ unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { SESSION_SET_GROUPING => { let g = guid_from(core::slice::from_raw_parts(a, 16)); let ctx = guid_from(core::slice::from_raw_parts(a.add(16), 16)); - wasapi::session_set_grouping(device_for(object).as_deref(), &session_guid(), &g, &ctx) + wasapi::session_set_grouping(&session_ref(object), &g, &ctx) } SESSION_IS_SYSTEM_SOUNDS => { - let hr = wasapi::session_is_system_sounds(device_for(object).as_deref(), &session_guid()); + let hr = wasapi::session_is_system_sounds(&session_ref(object)); if hr < 0 { return hr; } @@ -642,12 +780,10 @@ unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { } SESSION_SET_DUCKING => { let b: u32 = rd(a, 0); - wasapi::session_set_ducking(device_for(object).as_deref(), &session_guid(), b != 0) + wasapi::session_set_ducking(&session_ref(object), b != 0) } - SESSION_REGISTER_NOTIFICATION | SESSION_MANAGER_REGISTER | ENDPOINT_REGISTER => register(object, true), - SESSION_MANAGER_UNREGISTER | ENDPOINT_UNREGISTER => register(object, false), - ENUMERATOR_SUBSCRIBE => register(object, true), - ENUMERATOR_UNSUBSCRIBE => register(object, false), + SESSION_REGISTER_NOTIFICATION | SESSION_MANAGER_REGISTER | ENDPOINT_REGISTER | ENUMERATOR_SUBSCRIBE => subscribe(object, id, true), + SESSION_MANAGER_UNREGISTER | ENDPOINT_UNREGISTER | ENUMERATOR_UNSUBSCRIBE => subscribe(object, id, false), ENDPOINT_HOST_STREAM_MODES => { wr(a, 0, 0u32); wr(a, 4, 0u32); @@ -660,6 +796,22 @@ unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { } Err(hr) => hr, }, + ITEM_GET | ITEM_COUNT | ITEM_FLAG | ITEM_VALUE => { + let s = state(); + let Some(st) = stream_owner(&s, object).and_then(|k| s.objects.get(&k)).and_then(|o| o.stream.as_ref()) else { + return AUDCLNT_E_NOT_INITIALIZED; + }; + let r = &st.renderer; + let index: u32 = rd(a, 0); + match id { + ITEM_COUNT => r.item_count().map(|n| wr(a, 0, n)), + ITEM_FLAG => r.item_flag().map(|b| wr(a, 0, b as u8)), + ITEM_GET => r.item_value(index).map(|_| ()), + _ => r.item_value(index).map(|v| wr(a, 4, v)), + } + .err() + .unwrap_or(S_OK) + } CLOCK_SET_SAMPLE_RATE => { let r: f32 = rd(a, 0); let s = state(); @@ -703,8 +855,8 @@ unsafe fn dispatch(id: u32, object: u32, a: *mut u8, room: usize) -> i32 { Err(hr) => hr, } } - PROPERTY_GET_VALUE => property_value(object, a), - SPATIAL_STATIC_POSITION | SPATIAL_NATIVE_MASK | SPATIAL_MAX_DYNAMIC | SPATIAL_MAX_FRAMES | SPATIAL_FORMAT_SUPPORTED | SPATIAL_STREAM_AVAILABLE | SPATIAL_OFFLOAD_CAPABLE | SPATIAL_MAX_FRAMES_FOR_CATEGORY | FORMAT_ENUM_COUNT | FORMAT_ENUM_GET => spatial(id, object, a), + PROPERTY_GET_VALUE => property_value(object, a, room), + SPATIAL_STATIC_POSITION | SPATIAL_NATIVE_MASK | SPATIAL_MAX_DYNAMIC | SPATIAL_MAX_FRAMES | SPATIAL_FORMAT_SUPPORTED | SPATIAL_STREAM_AVAILABLE | SPATIAL_OFFLOAD_CAPABLE | SPATIAL_MAX_FRAMES_FOR_CATEGORY => spatial(id, object, a), ENDPOINT_CHANNEL_COUNT => { wr(a, 0, endpoint_channels(&device_for(object))); S_OK @@ -736,6 +888,10 @@ unsafe fn create_object(a: *mut u8, room: usize) -> i32 { if kind >= max_object_type() || flag > 1 { return E_INVALIDARG; } + if (kind == MEDIA_MANAGER_TYPE) != (method == METHOD_MEDIA_MANAGER) || (kind == EXISTING_SESSION_TYPE) != (method == METHOD_EXISTING_SESSION) { + compat_common::record_raw("crossvm-audio", "CreateObject", &format!("type {kind:#x} with method {method:#x}: the host creator for this type checks its method; E_INVALIDARG")); + return E_INVALIDARG; + } let device = match method { METHOD_DEFAULT_ENDPOINT | METHOD_DEFAULT_ENDPOINT_19041 => { let flow: u32 = rd(a, 0x14); @@ -764,15 +920,1043 @@ unsafe fn create_object(a: *mut u8, room: usize) -> i32 { }, _ => None, }; + if let Some(hr) = spatial_stream_create(kind, method, parent, a, room) { + return hr; + } + let mut formats = None; + if kind == FORMAT_ENUM_TYPE { + let pc = wasapi::spatial(device_for(parent).as_deref()).and_then(|sp| sp.format_enumerator()); + match pc { + Ok(e) => formats = Some(e), + Err(hr) => { + compat_common::record_raw("crossvm-audio", "CreateObject", &format!("type 4 (125980 -> 124574, IAudioFormatEnumerator child of the spatial client) parent {parent:#x}: PC ISpatialAudioClient::GetSupportedAudioObjectFormatEnumerator -> {:#010x}", hr as u32)); + return hr; + } + } + } + let mut sessions = Vec::new(); + let mut session = None; + let mut session_parent = None; + let mut media = None; + match method { + METHOD_MEDIA_MANAGER => { + let m = match wasapi::media_manager() { + Ok(m) => m, + Err(hr) => return hr, + }; + let token = match m.add_handler() { + Ok(t) => t, + Err(hr) => return hr, + }; + media = Some((m, token)); + } + METHOD_EXISTING_SESSION => { + if room < METHOD_ARGS + EXISTING_SESSION_CHARS * 2 { + return E_INVALIDARG; + } + let chars = core::slice::from_raw_parts(a.add(METHOD_ARGS) as *const u16, EXISTING_SESSION_CHARS); + if chars[EXISTING_SESSION_CHARS - 1] != 0 { + return E_INVALIDARG; + } + let Some(key) = wide_at(a.add(METHOD_ARGS), EXISTING_SESSION_CHARS) else { return E_INVALIDARG }; + let p = match wasapi::session_existing(device_for(parent).as_deref(), &key) { + Ok(p) => p, + Err(hr) => { + compat_common::record_raw("crossvm-audio", "CreateObject", &format!("existing session {key:?} -> {:#010x}", hr as u32)); + return hr; + } + }; + let title = { + let s = state(); + wasapi::SessionRef::Title(device_of(&s, parent), s.session.unwrap_or(GUID_NULL)) + }; + let same = wasapi::session_instance(&title).map(|t| t.eq_ignore_ascii_case(&key)).unwrap_or(false); + if !same { + session = Some(p); + } + session_parent = Some(parent); + } + METHOD_SESSION_ENUMERATOR => { + sessions = match wasapi::session_enumerate(device_for(parent).as_deref()) { + Ok(l) => l, + Err(hr) => return hr, + }; + wr(a, METHOD_REPLY_COUNT, sessions.len() as u32); + } + METHOD_ENUMERATED_SESSION => { + let index: u32 = rd(a, METHOD_ARGS); + let s = state(); + let Some(e) = s.objects.get(&parent) else { return E_INVALIDARG }; + let Some(p) = e.pc_sessions.get(index as usize).cloned() else { return E_INVALIDARG }; + let title = wasapi::SessionRef::Title(device_of(&s, parent), s.session.unwrap_or(GUID_NULL)); + drop(s); + let same = match (wasapi::session_instance(&wasapi::SessionRef::Pc(p.clone())), wasapi::session_instance(&title)) { + (Ok(a), Ok(b)) => a.eq_ignore_ascii_case(&b), + (Err(hr), _) => return hr, + _ => false, + }; + if !same { + session = Some(p); + } + session_parent = Some(parent); + } + _ => {} + } let mut s = state(); let n = s.next; s.next += 1; - compat_common::record_raw("crossvm-audio", "CreateObject", &format!("type {kind:#x} flag {flag} parent {parent:#x} method {method:#x} device {device:?} -> object {n:#x}")); - s.objects.insert(n, Object::new(kind, if flag == 1 { 0 } else { parent }, device)); + compat_common::record_raw("crossvm-audio", "CreateObject", &format!("type {kind:#x} flag {flag} parent {parent:#x} method {method:#x} device {device:?} sessions {} -> object {n:#x}", sessions.len())); + let mut o = Object::new(kind, session_parent.unwrap_or(if flag == 1 { 0 } else { parent }), device); + o.pc_sessions = sessions; + o.pc_session = session; + o.media = media; + o.formats = formats; + s.objects.insert(n, o); wr(a, 0xc, n); S_OK } +pub fn spatial_stream_methods(kind: u32) -> Option<(u32, u32)> { + match kind { + SPATIAL_STREAM_TYPE => Some((METHOD_SPATIAL_STREAM, METHOD_SPATIAL_STREAM2)), + SPATIAL_HRTF_STREAM_TYPE => Some((METHOD_SPATIAL_HRTF_STREAM, METHOD_SPATIAL_HRTF_STREAM2)), + SPATIAL_METADATA_STREAM_TYPE => Some((METHOD_SPATIAL_METADATA_STREAM, METHOD_SPATIAL_METADATA_STREAM2)), + _ => None, + } +} + +pub struct SpatialLayout { + pub format: usize, + pub options: Option, + pub reply: SpatialReply, + pub tail: Option, +} + +pub const SPATIAL_HRTF_FLAGS: usize = 0x24; +pub const SPATIAL_HRTF_DECAY: usize = 0x28; +pub const SPATIAL_HRTF_DIRECTIVITY: usize = 0x3c; +pub const SPATIAL_HRTF_ENVIRONMENT: usize = 0x4c; +pub const SPATIAL_HRTF_ORIENTATION: usize = 0x50; +pub const SPATIAL_METADATA_FORMAT_ID: usize = 0x24; +pub const SPATIAL_METADATA_MAX_ITEMS: usize = 0x34; + +pub fn spatial_layout(kind: u32, method: u32) -> Option { + Some(match (kind, method) { + (SPATIAL_STREAM_TYPE, METHOD_SPATIAL_STREAM) => SpatialLayout { format: SPATIAL_ARG_FORMAT, options: None, reply: SPATIAL_REPLY, tail: None }, + (SPATIAL_STREAM_TYPE, METHOD_SPATIAL_STREAM2) => SpatialLayout { format: SPATIAL_ARG_FORMAT, options: Some(SPATIAL_ARG_OPTIONS), reply: SPATIAL_REPLY2, tail: None }, + (SPATIAL_HRTF_STREAM_TYPE, METHOD_SPATIAL_HRTF_STREAM) => SpatialLayout { format: 0x74, options: None, reply: SpatialReply { extra: 0xbc, clsid: 0xc0, endpoint_value: 0xd0, token: 0xd4, stream_id: 0xdc, event: 0xe4, stream_value: 0x208, memory: 0x20c }, tail: None }, + (SPATIAL_HRTF_STREAM_TYPE, METHOD_SPATIAL_HRTF_STREAM2) => SpatialLayout { format: 0x74, options: Some(0xc0), reply: SpatialReply { extra: 0xbc, clsid: 0xc4, endpoint_value: 0xd4, token: 0xd8, stream_id: 0xe0, event: 0xe8, stream_value: 0x20c, memory: 0x210 }, tail: None }, + (SPATIAL_METADATA_STREAM_TYPE, METHOD_SPATIAL_METADATA_STREAM) => SpatialLayout { format: 0x36, options: None, reply: SpatialReply { extra: 0x7e, clsid: 0x82, endpoint_value: 0x92, token: 0x96, stream_id: 0x9e, event: 0xa6, stream_value: 0x1ca, memory: 0x1ce }, tail: Some(0x2f2) }, + (SPATIAL_METADATA_STREAM_TYPE, METHOD_SPATIAL_METADATA_STREAM2) => SpatialLayout { format: 0x38, options: Some(0x84), reply: SpatialReply { extra: 0x80, clsid: 0x88, endpoint_value: 0x98, token: 0x9c, stream_id: 0xa4, event: 0xac, stream_value: 0x1d0, memory: 0x1d4 }, tail: Some(0x2f8) }, + _ => return None, + }) +} + +pub fn spatial_layout_end(l: &SpatialLayout) -> usize { + l.tail.map(|t| t + 8).unwrap_or(l.reply.memory + SPATIAL_DESCRIPTOR_BYTES).max(l.options.map(|o| o + 4).unwrap_or(0)).max(l.format + 0x12) +} + +unsafe fn spatial_extra(kind: u32, method: u32, a: *const u8) -> wasapi::SpatialExtra { + let copy = |o: usize, n: usize| core::slice::from_raw_parts(a.add(o), n).to_vec(); + match kind { + SPATIAL_HRTF_STREAM_TYPE => { + let has = |i: usize| *a.add(SPATIAL_HRTF_FLAGS + i) != 0; + wasapi::SpatialExtra::Hrtf { + decay: has(0).then(|| copy(SPATIAL_HRTF_DECAY, 0x14).try_into().unwrap()), + directivity: has(1).then(|| copy(SPATIAL_HRTF_DIRECTIVITY, 0x10).try_into().unwrap()), + environment: has(2).then(|| rd(a, SPATIAL_HRTF_ENVIRONMENT)), + orientation: has(3).then(|| copy(SPATIAL_HRTF_ORIENTATION, 0x24).try_into().unwrap()), + } + } + SPATIAL_METADATA_STREAM_TYPE => wasapi::SpatialExtra::Metadata { + format_id: copy(SPATIAL_METADATA_FORMAT_ID, 16).try_into().unwrap(), + max_items: if method == METHOD_SPATIAL_METADATA_STREAM2 { rd::(a, SPATIAL_METADATA_MAX_ITEMS) } else { rd::(a, SPATIAL_METADATA_MAX_ITEMS) as u32 }, + }, + _ => wasapi::SpatialExtra::Plain, + } +} + +unsafe fn spatial_stream_create(kind: u32, method: u32, parent: u32, a: *mut u8, room: usize) -> Option { + spatial_stream_methods(kind)?; + let Some(lay) = spatial_layout(kind, method) else { return Some(E_INVALIDARG) }; + if room < spatial_layout_end(&lay) { + return Some(E_INVALIDARG); + } + let head = core::slice::from_raw_parts(a.add(lay.format), 0x12); + let flen = u16::from_le_bytes([head[0x10], head[0x11]]) as usize + 0x12; + if flen > SPATIAL_FORMAT_MAX || lay.format + flen > room { + return Some(E_INVALIDARG); + } + let params = wasapi::SpatialStreamParams { + format: core::slice::from_raw_parts(a.add(lay.format), flen).to_vec(), + mask: rd(a, SPATIAL_ARG_MASK), + min: rd(a, SPATIAL_ARG_MIN), + max: rd(a, SPATIAL_ARG_MAX), + category: rd(a, SPATIAL_ARG_CATEGORY), + options: lay.options.map(|o| rd(a, o)).unwrap_or(0), + extra: spatial_extra(kind, method, a), + }; + let dev = device_for(parent); + let sp = match wasapi::spatial(dev.as_deref()) { + Ok(sp) => sp, + Err(hr) => return Some(hr), + }; + let stream = match sp.activate_stream(¶ms) { + Ok(st) => st, + Err(hr) => { + compat_common::record_raw("crossvm-audio", "CreateObject", &format!("spatial stream type {kind:#x} method {method:#x} mask {:#x} min {} max {} category {}: PC ActivateSpatialAudioStream -> {:#010x}", params.mask, params.min, params.max, params.category, hr as u32)); + return Some(hr); + } + }; + SPATIAL_ACTIVATIONS.fetch_add(1, Ordering::SeqCst); + if kind == SPATIAL_METADATA_STREAM_TYPE { + drop(stream); + compat_common::record_raw("crossvm-audio", "CreateObject", &format!("spatial type {kind:#x} method {method:#x}: PC metadata stream activated, but the DCAS metadata bytes per object and the reply qword at p+0x2e4 come from the audio engine, which is in no dump; no guest object; E_NOTIMPL")); + return Some(E_NOTIMPL); + } + let props = if kind == SPATIAL_HRTF_STREAM_TYPE { SPATIAL_HRTF_PROPERTY_BYTES } else { SPATIAL_PROPERTY_BYTES }; + let reply = &lay.reply; + let rate = wasapi::sample_rate(¶ms.format); + let frames = match sp.max_frames(¶ms.format) { + Ok(f) => f, + Err(hr) => return Some(hr), + }; + let (packet, mix_rate) = match wasapi::device_info_for(dev.as_deref()) { + Ok(d) => (((d.default_period * rate as i64 / HNS) as u32).min(frames), wasapi::sample_rate(&d.mix)), + Err(hr) => return Some(hr), + }; + let frames = engine_frames(frames, rate, mix_rate); + let statics = (params.mask & !AUDIO_OBJECT_DYNAMIC).count_ones(); + let dynamic = params.max; + let total = match dcas::total(frames, statics, dynamic, props, 0) { + Ok(t) => t, + Err(hr) => return Some(hr), + }; + let pages = (total as usize).div_ceil(crate::logan::PAGE); + let Some(index) = crate::logan::pool_alloc(pages) else { + return Some(E_OUTOFMEMORY); + }; + let base = crate::logan::pool() + index as usize * crate::logan::PAGE; + let name = format!("\\BaseNamedObjects\\AudioEngineDuplicateHandleApiPort-{index}"); + let mem = core::slice::from_raw_parts_mut(base as *mut u8, total as usize); + let shape = match dcas::write(mem, &name, frames, packet, statics, dynamic, props, 0, ¶ms.format).and_then(|sh| dcas::regions(&sh).map(|r| (sh, r))) { + Ok(v) => v, + Err(hr) => { + crate::logan::pool_release(index as usize); + return Some(hr); + } + }; + let event_id = { + let mut s = state(); + s.next_event += 1; + s.next_event + }; + let event_name = event_name(event_id as u16); + let event = match crate::vab::create_event(&event_name) { + Ok(h) => h, + Err(e) => { + crate::logan::pool_release(index as usize); + return Some((0x8007_0000 | (e & 0xffff)) as i32); + } + }; + let dynamic_now = stream.available_dynamic().unwrap_or(0); + core::ptr::write_bytes(a.add(reply.extra), 0, spatial_layout_end(&lay) - reply.extra); + core::ptr::copy_nonoverlapping(guid_bytes(&CLSID_SPATIAL_CLIENT_OUTPUT_ENDPOINT).as_ptr(), a.add(reply.clsid), 16); + write_event_descriptor(a.add(reply.event), EVENT_KIND_GAMECORE, event_id as u16); + wr(a, reply.memory, KIND_CROSS_VM_MEMORY); + core::ptr::copy_nonoverlapping(guid_bytes(&CLSID_XVM_BUFFER).as_ptr(), a.add(reply.memory + 4), 16); + core::ptr::copy_nonoverlapping(guid_bytes(&GUID_XVM_BUFFER).as_ptr(), a.add(reply.memory + 0x14), 16); + wr(a, reply.memory + 0x24, index as u32); + let pump = Arc::new(SpatialPump { + stream, + objects: Mutex::new(Vec::new()), + control: pingpong::Control::at(base as *mut u8), + base, + shape: shape.0, + regions: shape.1, + mask: params.mask, + hrtf: kind == SPATIAL_HRTF_STREAM_TYPE, + event: event as usize, + running: AtomicBool::new(false), + quit: AtomicBool::new(false), + counters: Arc::new(SpatialCounters::default()), + status: AtomicI32::new(0), + }); + let worker = pump.clone(); + let thread = match std::thread::Builder::new().name("tombox-spatial".into()).spawn(move || worker.run()) { + Ok(t) => t, + Err(_) => { + crate::logan::pool_release(index as usize); + return Some(E_OUTOFMEMORY); + } + }; + let host = SpatialHost { pool_index: index, started: false, pump, thread: Some(thread) }; + let mut s = state(); + let n = s.next; + s.next += 1; + compat_common::record_raw("crossvm-audio", "CreateObject", &format!("spatial stream type {kind:#x} method {method:#x} mask {:#x} min {} max {} category {}: PC stream activated ({dynamic_now} dynamic available), DCAS {name} at pool page {index}: {frames} frames, {packet} per packet, {statics} static + {dynamic} dynamic, {total:#x} bytes, period event {event_name} -> object {n:#x}", params.mask, params.min, params.max, params.category)); + let mut o = Object::new(kind, parent, dev); + o.spatial = Some(host); + s.objects.insert(n, o); + wr(a, 0xc, n); + Some(S_OK) +} + +pub static SPATIAL_ACTIVATIONS: AtomicU32 = AtomicU32::new(0); + +pub struct SpatialReply { + pub extra: usize, + pub clsid: usize, + pub endpoint_value: usize, + pub token: usize, + pub stream_id: usize, + pub event: usize, + pub stream_value: usize, + pub memory: usize, +} + +pub const SPATIAL_DESCRIPTOR_BYTES: usize = 0x124; +pub const SPATIAL_REPLY: SpatialReply = SpatialReply { extra: 0x6c, clsid: 0x70, endpoint_value: 0x80, token: 0x84, stream_id: 0x8c, event: 0x94, stream_value: 0x1b8, memory: 0x1bc }; +pub const SPATIAL_REPLY2: SpatialReply = SpatialReply { extra: 0x6c, clsid: 0x74, endpoint_value: 0x84, token: 0x88, stream_id: 0x90, event: 0x98, stream_value: 0x1bc, memory: 0x1c0 }; +pub const SPATIAL_PHASE_THREE: u32 = 0x39; +pub const SPATIAL_PRE_START: u32 = 0x44; +pub const SPATIAL_PRE_STOP: u32 = 0x45; +pub const SPATIAL_RESET: u32 = 0x46; +pub const RECORD_COOKIE: usize = 0; +pub const RECORD_FRAMES: usize = 4; +pub const RECORD_TYPE: usize = 8; +pub const RECORD_FLAGS: usize = 0xc; +pub const RECORD_VOLUME: usize = 0x1c; +pub const RECORD_BUFFER: u32 = 1; +pub const RECORD_ACTIVE: u32 = 2; +pub const RECORD_END_OF_STREAM: u32 = 8; +pub const AUDIO_OBJECT_DYNAMIC: u32 = 1; +pub const SPATIAL_HRTF_PROPERTY_BYTES: u32 = 0xb4; +pub const RECORD_HRTF: u32 = 0x10; +pub const HRTF_DIRTY: usize = 0x20; +pub const HRTF_GAIN: usize = 0x24; +pub const HRTF_ORIENTATION: usize = 0x28; +pub const HRTF_ENVIRONMENT: usize = 0x4c; +pub const HRTF_DECAY: usize = 0x50; +pub const HRTF_DIRECTIVITY: usize = 0x64; +pub const HRTF_UNKNOWN: usize = 0x74; +pub const HRTF_DIRTY_GAIN: u32 = 1; +pub const HRTF_DIRTY_ORIENTATION: u32 = 2; +pub const HRTF_DIRTY_ENVIRONMENT: u32 = 4; +pub const HRTF_DIRTY_DECAY: u32 = 8; +pub const HRTF_DIRTY_DIRECTIVITY: u32 = 0x10; +pub const HRTF_DIRTY_UNKNOWN: u32 = 0x20; +const SPTLAUDCLNT_E_STREAM_NOT_STOPPED: i32 = 0x8889_010au32 as i32; +pub const SPTLAUDCLNT_E_DESTROYED: i32 = 0x8889_0100u32 as i32; +pub const AUDCLNT_E_DEVICE_INVALIDATED: i32 = 0x8889_0004u32 as i32; +pub const AUDCLNT_E_RESOURCES_INVALIDATED: i32 = 0x8889_0026u32 as i32; +pub const ENGINE_HEADROOM: f32 = 1.1; +pub const SRC_PRIMING_FRAMES: u32 = 7; + +pub fn engine_frames(max: u32, stream_rate: u32, mix_rate: u32) -> u32 { + let n = max + if stream_rate != mix_rate { SRC_PRIMING_FRAMES } else { 0 }; + (n as f32 * ENGINE_HEADROOM) as u32 +} + +pub fn stream_status_error(hr: i32) -> bool { + matches!(hr, SPTLAUDCLNT_E_DESTROYED | AUDCLNT_E_DEVICE_INVALIDATED | AUDCLNT_E_RESOURCES_INVALIDATED) +} + +#[derive(Default)] +pub struct SpatialCounters { + pub passes: AtomicI64, + pub reads: AtomicI64, + pub starved: AtomicI64, + pub faults: AtomicI64, + pub buffers: AtomicI64, + pub silent: AtomicI64, + pub end_of_stream: AtomicI64, + pub volumes: AtomicI64, + pub dynamic_skipped: AtomicI64, + pub hrtf_properties: AtomicI64, + pub hrtf_unknown: AtomicI64, + pub errors: AtomicI64, + pub last_error: AtomicU32, +} + +struct SpatialPump { + stream: wasapi::SpatialStream, + objects: Mutex>, + control: pingpong::Control, + base: usize, + shape: dcas::Shape, + regions: dcas::Regions, + mask: u32, + hrtf: bool, + event: usize, + running: AtomicBool, + quit: AtomicBool, + counters: Arc, + status: AtomicI32, +} + +unsafe impl Send for SpatialPump {} +unsafe impl Sync for SpatialPump {} + +struct SpatialHost { + pool_index: u16, + started: bool, + pump: Arc, + thread: Option>, +} + +impl Drop for SpatialHost { + fn drop(&mut self) { + self.pump.running.store(false, Ordering::SeqCst); + self.pump.quit.store(true, Ordering::SeqCst); + wasapi::signal_event(self.pump.stream.event()); + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + let _ = self.pump.stream.stop(); + self.pump.objects.lock().unwrap_or_else(|e| e.into_inner()).clear(); + crate::logan::pool_release(self.pool_index as usize); + } +} + +impl SpatialPump { + fn object(&self, list: &mut Vec<(u32, wasapi::SpatialObject, f32)>, kind: u32) -> Option { + if let Some(i) = list.iter().position(|o| o.0 == kind) { + return Some(i); + } + if kind == AUDIO_OBJECT_DYNAMIC || kind & self.mask != kind || kind.count_ones() != 1 { + self.counters.dynamic_skipped.fetch_add(1, Ordering::SeqCst); + return None; + } + match self.stream.activate_object(kind) { + Ok(o) => { + list.push((kind, o, 1.0)); + Some(list.len() - 1) + } + Err(hr) => { + self.fail(hr); + None + } + } + } + + fn fail(&self, hr: i32) { + self.counters.errors.fetch_add(1, Ordering::SeqCst); + self.counters.last_error.store(hr as u32, Ordering::SeqCst); + if stream_status_error(hr) { + let _ = self.status.compare_exchange(0, hr, Ordering::SeqCst, Ordering::SeqCst); + } + } + + fn status(&self) -> i32 { + self.status.load(Ordering::SeqCst) + } + + unsafe fn pass(&self) { + let (_, frames) = match self.stream.begin_updating() { + Ok(v) => v, + Err(hr) => { + self.fail(hr); + return; + } + }; + self.counters.passes.fetch_add(1, Ordering::SeqCst); + self.control.set_frames_per_packet(frames); + match self.control.read_acquire() { + Ok(index) => { + self.counters.reads.fetch_add(1, Ordering::SeqCst); + self.read(index, frames); + if self.control.read_commit(index) < 0 { + self.counters.faults.fetch_add(1, Ordering::SeqCst); + } + } + Err(pingpong::E_READ_STARVED) => { + self.counters.starved.fetch_add(1, Ordering::SeqCst); + } + Err(_) => { + self.counters.faults.fetch_add(1, Ordering::SeqCst); + } + } + let hr = self.stream.end_updating(); + if hr < 0 { + self.fail(hr); + } + wasapi::signal_event(self.event); + } + + unsafe fn read(&self, index: u32, frames: u32) { + let data = self.base + dcas::DATA; + let props = self.shape.properties as usize; + let frame_bytes = self.shape.frame_bytes as usize; + let mut list = self.objects.lock().unwrap_or_else(|e| e.into_inner()); + for k in 0..self.shape.objects as usize { + let r = (data + self.regions.properties[index as usize] + k * props) as *const u8; + let kind: u32 = rd(r, RECORD_TYPE); + let flags: u32 = rd(r, RECORD_FLAGS); + if kind == 0 || flags & (RECORD_BUFFER | RECORD_ACTIVE | RECORD_END_OF_STREAM | RECORD_HRTF) == 0 { + continue; + } + let Some(i) = self.object(&mut list, kind) else { continue }; + let count: u32 = rd(r, RECORD_FRAMES); + let volume: f32 = rd(r, RECORD_VOLUME); + if self.hrtf && flags & RECORD_HRTF != 0 { + self.hrtf_properties(&list[i].1, r); + } + if !self.hrtf && volume != list[i].2 { + let hr = list[i].1.set_volume(volume); + if hr < 0 { + self.fail(hr); + } else { + list[i].2 = volume; + self.counters.volumes.fetch_add(1, Ordering::SeqCst); + } + } + if flags & RECORD_BUFFER != 0 { + match list[i].1.buffer() { + Ok((dst, len)) => { + let n = (len as usize).min(count.min(frames) as usize * 4).min(frame_bytes); + if wasapi::muted() { + core::ptr::write_bytes(dst, 0, len as usize); + self.counters.silent.fetch_add(1, Ordering::SeqCst); + } else { + let src = (data + self.regions.samples[index as usize] + k * frame_bytes) as *const u8; + core::ptr::copy_nonoverlapping(src, dst, n); + core::ptr::write_bytes(dst.add(n), 0, len as usize - n); + } + self.counters.buffers.fetch_add(1, Ordering::SeqCst); + } + Err(hr) => self.fail(hr), + } + } + if flags & RECORD_END_OF_STREAM != 0 { + let hr = list[i].1.set_end_of_stream(if flags & RECORD_BUFFER != 0 { count.min(frames) } else { 0 }); + if hr < 0 { + self.fail(hr); + } + self.counters.end_of_stream.fetch_add(1, Ordering::SeqCst); + list.remove(i); + } + } + } + + unsafe fn hrtf_properties(&self, o: &wasapi::SpatialObject, r: *const u8) { + let dirty: u32 = rd(r, HRTF_DIRTY); + let mut hrs = Vec::new(); + if dirty & HRTF_DIRTY_GAIN != 0 { + hrs.push(o.set_hrtf_gain(rd(r, HRTF_GAIN))); + } + if dirty & HRTF_DIRTY_ORIENTATION != 0 { + hrs.push(o.set_hrtf_block(wasapi::HRTF_SET_ORIENTATION, r.add(HRTF_ORIENTATION))); + } + if dirty & HRTF_DIRTY_ENVIRONMENT != 0 { + hrs.push(o.set_hrtf_environment(rd(r, HRTF_ENVIRONMENT))); + } + if dirty & HRTF_DIRTY_DECAY != 0 { + hrs.push(o.set_hrtf_block(wasapi::HRTF_SET_DISTANCE_DECAY, r.add(HRTF_DECAY))); + } + if dirty & HRTF_DIRTY_DIRECTIVITY != 0 { + hrs.push(o.set_hrtf_block(wasapi::HRTF_SET_DIRECTIVITY, r.add(HRTF_DIRECTIVITY))); + } + if dirty & HRTF_DIRTY_UNKNOWN != 0 { + self.counters.hrtf_unknown.fetch_add(1, Ordering::SeqCst); + } + for hr in hrs { + if hr < 0 { + self.fail(hr); + } else { + self.counters.hrtf_properties.fetch_add(1, Ordering::SeqCst); + } + } + } + + fn run(self: Arc) { + unsafe { wasapi::com_init() }; + while !self.quit.load(Ordering::SeqCst) { + if !self.running.load(Ordering::SeqCst) { + wasapi::wait_event(self.stream.event(), 20); + continue; + } + if wasapi::wait_event(self.stream.event(), 50) && self.running.load(Ordering::SeqCst) && !self.quit.load(Ordering::SeqCst) { + unsafe { self.pass() }; + } + } + } + + fn prepare(&self) -> i32 { + let mut list = self.objects.lock().unwrap_or_else(|e| e.into_inner()); + let mut bit = 2u32; + while bit != 0 { + if self.mask & bit != 0 && !list.iter().any(|o| o.0 == bit) { + match self.stream.activate_object(bit) { + Ok(o) => list.push((bit, o, 1.0)), + Err(hr) => return hr, + } + } + bit = bit.wrapping_shl(1); + } + S_OK + } +} + +pub fn spatial_counters(object: u32) -> Option> { + state().objects.get(&object)?.spatial.as_ref().map(|h| h.pump.counters.clone()) +} + +pub fn spatial_control(object: u32) -> Option<(usize, u16, dcas::Shape, dcas::Regions)> { + let s = state(); + let h = s.objects.get(&object)?.spatial.as_ref()?; + Some((h.pump.base, h.pool_index, h.pump.shape, h.pump.regions)) +} + +pub fn spatial_static_objects(object: u32) -> Option> { + let s = state(); + let h = s.objects.get(&object)?.spatial.as_ref()?; + let list = h.pump.objects.lock().unwrap_or_else(|e| e.into_inner()); + Some(list.iter().map(|o| o.0).collect()) +} + +unsafe fn spatial_call(id: u32, object: u32, a: *mut u8) -> Option { + let mut s = state(); + let h = s.objects.get_mut(&object)?.spatial.as_mut()?; + let pump = h.pump.clone(); + Some(match id { + SPATIAL_PHASE_THREE => { + drop(s); + pump.prepare() + } + SPATIAL_PRE_START => { + wr(a, 0, 0u8); + if pump.status() < 0 { + return Some(pump.status()); + } + if h.started { + return Some(SPTLAUDCLNT_E_STREAM_NOT_STOPPED); + } + h.started = true; + if !pump.running.load(Ordering::SeqCst) { + wr(a, 0, 1u8); + } + S_OK + } + START => { + drop(s); + let hr = pump.stream.start(); + if hr < 0 { + pump.fail(hr); + return Some(hr); + } + pump.running.store(true, Ordering::SeqCst); + wasapi::signal_event(pump.event); + S_OK + } + SPATIAL_PRE_STOP => { + if !h.started { + return Some(S_FALSE); + } + h.started = false; + S_OK + } + STOP => { + drop(s); + let hr = pump.stream.stop(); + if hr < 0 { + pump.fail(hr); + return Some(hr); + } + if hr != S_FALSE { + pump.running.store(false, Ordering::SeqCst); + } + hr + } + SPATIAL_RESET => { + if pump.status() < 0 { + pump.status() + } else if h.started { + SPTLAUDCLNT_E_STREAM_NOT_STOPPED + } else { + S_OK + } + } + + _ => return None, + }) +} + + +pub mod dcas { + pub const HEADER: u32 = 0x326; + pub const MAGIC: u32 = 0x5341_4344; + pub const DATA: usize = 0x340; + pub const DATA_HEADER: u32 = 0x1c; + pub const DATA_MAGIC: u32 = 0x5341_4244; + pub const NAME: usize = 0x184; + pub const NAME_CHARS: usize = 0x40; + pub const FRAMES: usize = 0x204; + pub const STATIC_OBJECTS: usize = 0x208; + pub const DYNAMIC_OBJECTS: usize = 0x20c; + pub const TOTAL: usize = 0x210; + pub const FORMAT: usize = 0x214; + pub const FORMAT_EXTRA_MAX: usize = 0x100; + pub const STATE: usize = 0x30; + pub const STATE_INITIAL: u32 = 6; + pub const E_INVALID_CONTROL: i32 = 0x887c_0045u32 as i32; + pub const E_MISALIGNED: i32 = 0x887c_0054u32 as i32; + pub const E_OVERFLOW: i32 = 0x8007_0216u32 as i32; + const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Shape { + pub objects: u32, + pub properties: u32, + pub metadata: u32, + pub frame_bytes: u32, + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Regions { + pub properties: [usize; 2], + pub metadata: [usize; 2], + pub samples: [usize; 2], + } + + pub fn align32(v: u32) -> Result { + if v & 0x1f == 0 { + return Ok(v); + } + let r = (v - (v & 0x1f)).wrapping_add(0x20); + if r < v { Err(E_OVERFLOW) } else { Ok(r) } + } + + pub fn data_size(sample_bytes: u32, properties: u32, metadata: u32, objects: u32) -> Result { + let frame = align32(sample_bytes)? as u64; + let n = objects as u64; + let p = properties as u64 * n * 2; + let m = metadata as u64 * n * 2; + let s = frame * n * 2; + if p > u32::MAX as u64 || m > u32::MAX as u64 || s > u32::MAX as u64 { + return Err(E_OVERFLOW); + } + let head = align32(u32::try_from(DATA_HEADER as u64 + p + m).map_err(|_| E_OVERFLOW)?)? as u64; + u32::try_from(head + s).map_err(|_| E_OVERFLOW) + } + + pub fn regions(shape: &Shape) -> Result { + let n = shape.objects as usize; + let p0 = DATA_HEADER as usize; + let p1 = p0 + shape.properties as usize * n; + let m0 = p1 + shape.properties as usize * n; + let m1 = m0 + shape.metadata as usize * n; + let end = m1 + shape.metadata as usize * n; + let s0 = align32(u32::try_from(end).map_err(|_| E_OVERFLOW)?)? as usize; + let s1 = s0 + shape.frame_bytes as usize * n; + Ok(Regions { properties: [p0, p1], metadata: [m0, m1], samples: [s0, s1] }) + } + + pub fn total(frames: u32, static_objects: u32, dynamic_objects: u32, properties: u32, metadata: u32) -> Result { + let objects = static_objects.checked_add(dynamic_objects).ok_or(E_OVERFLOW)?; + let bytes = frames.checked_mul(4).ok_or(E_OVERFLOW)?; + data_size(bytes, properties, metadata, objects)?.checked_add(DATA as u32).ok_or(E_OVERFLOW) + } + + fn put(b: &mut [u8], o: usize, v: u32) { + b[o..o + 4].copy_from_slice(&v.to_le_bytes()); + } + + fn get(b: &[u8], o: usize) -> u32 { + u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) + } + + #[allow(clippy::too_many_arguments)] + pub fn write(b: &mut [u8], name: &str, frames: u32, packet: u32, static_objects: u32, dynamic_objects: u32, properties: u32, metadata: u32, format: &[u8]) -> Result { + let total = total(frames, static_objects, dynamic_objects, properties, metadata)?; + if format.len() < 0x12 { + return Err(E_INVALIDARG); + } + let extra = u16::from_le_bytes([format[0x10], format[0x11]]) as usize; + if extra > FORMAT_EXTRA_MAX || format.len() < 0x12 + extra { + return Err(E_INVALIDARG); + } + if b.len() < total as usize { + return Err(0x8007_000Eu32 as i32); + } + if (b.as_ptr() as usize + DATA) & 0x1f != 0 { + return Err(E_MISALIGNED); + } + b[..DATA].fill(0); + put(b, 0, HEADER); + put(b, 4, MAGIC); + put(b, STATE, STATE_INITIAL); + put(b, super::pingpong::FRAMES_PER_PACKET, packet); + put(b, super::pingpong::FLAGS, super::pingpong::FLAG_VALID); + let w: Vec = name.encode_utf16().take(NAME_CHARS - 1).collect(); + for (i, c) in w.iter().enumerate() { + b[NAME + i * 2..NAME + i * 2 + 2].copy_from_slice(&c.to_le_bytes()); + } + put(b, FRAMES, frames); + put(b, STATIC_OBJECTS, static_objects); + put(b, DYNAMIC_OBJECTS, dynamic_objects); + put(b, TOTAL, total); + b[FORMAT..FORMAT + 0x12 + extra].copy_from_slice(&format[..0x12 + extra]); + let objects = static_objects + dynamic_objects; + let shape = Shape { objects, properties, metadata, frame_bytes: align32(frames * 4)? }; + let d = &mut b[DATA..total as usize]; + d.fill(0); + put(d, 0, DATA_HEADER); + put(d, 4, total - DATA as u32); + put(d, 8, objects); + put(d, 0xc, properties); + put(d, 0x10, metadata); + put(d, 0x14, shape.frame_bytes); + put(d, 0x18, DATA_MAGIC); + Ok(shape) + } + + pub fn validate(b: &[u8]) -> i32 { + if b.len() < DATA { + return E_INVALID_CONTROL; + } + if get(b, 0) != HEADER || get(b, 4) != MAGIC || get(b, STATIC_OBJECTS).wrapping_add(get(b, DYNAMIC_OBJECTS)) == 0 || (get(b, TOTAL) as usize) < DATA { + return E_INVALID_CONTROL; + } + 0 + } + + pub fn parse(b: &[u8]) -> Result<(Shape, Regions), i32> { + let hr = validate(b); + if hr < 0 { + return Err(hr); + } + let total = get(b, TOTAL) as usize; + if b.len() < total { + return Err(E_INVALID_CONTROL); + } + let d = &b[DATA..total]; + let size = d.len() as u32; + if size <= DATA_HEADER { + return Err(E_INVALID_CONTROL); + } + let shape = Shape { objects: get(d, 8), properties: get(d, 0xc), metadata: get(d, 0x10), frame_bytes: get(d, 0x14) }; + if data_size(shape.frame_bytes, shape.properties, shape.metadata, shape.objects)? != size { + return Err(E_INVALID_CONTROL); + } + Ok((shape, regions(&shape)?)) + } +} + +pub mod pingpong { + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + + pub const STATES: usize = 17; + pub const FAULTED: u32 = 16; + pub const WRITE_ACQUIRE: [u32; STATES] = [1, 16, 2, 4, 16, 5, 7, 16, 9, 16, 10, 12, 16, 13, 15, 16, 16]; + pub const WRITE_COMMIT: [u32; STATES] = [16, 2, 16, 16, 5, 16, 16, 8, 16, 10, 16, 16, 13, 16, 16, 0, 16]; + pub const WRITE_CANCEL: [u32; STATES] = [0, 0, 2, 3, 3, 5, 6, 6, 8, 8, 10, 11, 11, 13, 14, 14, 16]; + pub const READ_ACQUIRE: [u32; STATES] = [3, 4, 5, 16, 16, 16, 6, 7, 11, 12, 13, 16, 16, 16, 14, 15, 16]; + pub const READ_COMMIT: [u32; STATES] = [16, 16, 16, 6, 7, 8, 16, 16, 16, 16, 16, 14, 15, 0, 16, 16, 16]; + pub const FLUSH: [u32; STATES] = [6, 7, 6, 3, 4, 3, 6, 7, 14, 15, 14, 11, 12, 11, 14, 15, 6]; + pub const READER_INDEX: [u32; STATES] = [1, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 3]; + pub const WRITER_INDEX: [u32; STATES] = [0, 0, 2, 0, 0, 2, 0, 0, 1, 1, 2, 1, 1, 2, 1, 1, 3]; + pub const INDEX_STARVED: u32 = 2; + pub const INDEX_FAULT: u32 = 3; + + pub const POSITION: usize = 0x08; + pub const GRANT_POSITION: usize = 0x10; + pub const DYNAMIC_REQUESTED: usize = 0x18; + pub const DYNAMIC_GRANTED: usize = 0x1c; + pub const BUFFER_OBJECTS: usize = 0x20; + pub const FRAMES_COMMITTED: usize = 0x28; + pub const STATE: usize = 0x30; + pub const FRAMES_PER_PACKET: usize = 0x34; + pub const BUFFER_FRAMES: usize = 0x38; + pub const DYNAMIC_IN_USE: usize = 0x40; + pub const FLAGS: usize = 0x48; + pub const READ_STARVED: usize = 0x4c; + pub const WRITE_STARVED: usize = 0x50; + + pub const FLAG_VALID: u32 = 1; + pub const FLAG_STARTED: u32 = 2; + pub const FLAG_POSITION: u32 = 4; + pub const FLAG_POSITION_LATCHED: u32 = 8; + pub const FLAG_DISCONTINUITY: u32 = 0x10; + pub const FLAG_EVENT_SET: u32 = 0x20; + pub const FLAG_GRANT_PENDING: u32 = 0x40; + pub const FLAG_CLOSED: u32 = 0x80; + + pub const E_INVALID_CONTROL: i32 = 0x887c_0045u32 as i32; + pub const E_WRITE_STARVED: i32 = 0x887c_0061u32 as i32; + pub const E_READ_STARVED: i32 = 0x887c_0062u32 as i32; + pub const E_BAD_WRITE_INDEX: i32 = 0x887c_006fu32 as i32; + pub const E_NOT_STARTED: i32 = 0x887c_0013u32 as i32; + const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Control { + base: usize, + } + + impl Control { + pub unsafe fn at(base: *mut u8) -> Self { + Control { base: base as usize } + } + + fn u32(&self, o: usize) -> &AtomicU32 { + unsafe { &*((self.base + o) as *const AtomicU32) } + } + + fn u64(&self, o: usize) -> &AtomicU64 { + unsafe { &*((self.base + o) as *const AtomicU64) } + } + + pub fn state(&self) -> u32 { + let s = self.u32(STATE).load(Ordering::SeqCst); + if s > FAULTED { + self.u32(STATE).swap(FAULTED, Ordering::SeqCst); + return FAULTED; + } + s + } + + fn step(&self, table: &[u32; STATES]) -> u32 { + let mut s = self.state(); + loop { + let next = table[s as usize]; + match self.u32(STATE).compare_exchange(s, next, Ordering::SeqCst, Ordering::SeqCst) { + Ok(_) => return next, + Err(cur) if cur > FAULTED => return FAULTED, + Err(cur) => s = cur, + } + } + } + + pub fn flush(&self) { + self.u32(FLAGS).fetch_or(FLAG_DISCONTINUITY, Ordering::SeqCst); + self.u64(FRAMES_COMMITTED).store(0, Ordering::SeqCst); + self.step(&FLUSH); + } + + pub fn write_acquire(&self) -> Result { + let next = self.step(&WRITE_ACQUIRE); + match WRITER_INDEX[next as usize] { + INDEX_FAULT => { + self.step(&FLUSH); + Err(E_INVALID_CONTROL) + } + INDEX_STARVED => { + self.u32(WRITE_STARVED).fetch_add(1, Ordering::SeqCst); + Err(E_WRITE_STARVED) + } + i => { + let packet = self.u32(FRAMES_PER_PACKET).load(Ordering::SeqCst); + self.u32(BUFFER_FRAMES + i as usize * 4).store(packet, Ordering::SeqCst); + Ok(i) + } + } + } + + pub fn write_commit(&self, index: u32, objects: u32, packet_frames: u32) -> i32 { + if index > 1 { + return E_BAD_WRITE_INDEX; + } + self.u32(BUFFER_OBJECTS + index as usize * 4).swap(objects, Ordering::SeqCst); + let next = self.step(&WRITE_COMMIT); + if WRITER_INDEX[next as usize] == INDEX_FAULT { + return E_INVALID_CONTROL; + } + self.u64(FRAMES_COMMITTED).fetch_add(if objects != 0 { packet_frames as u64 } else { 0 }, Ordering::SeqCst); + 0 + } + + pub fn write_cancel(&self) { + self.step(&WRITE_CANCEL); + } + + pub fn read_acquire(&self) -> Result { + let next = self.step(&READ_ACQUIRE); + match READER_INDEX[next as usize] { + INDEX_FAULT => { + self.step(&FLUSH); + Err(E_INVALID_CONTROL) + } + INDEX_STARVED => { + self.u32(READ_STARVED).fetch_add(1, Ordering::SeqCst); + Err(E_READ_STARVED) + } + i => Ok(i), + } + } + + pub fn read_commit(&self, index: u32) -> i32 { + if index > 1 { + return E_INVALIDARG; + } + let next = self.step(&READ_COMMIT); + if READER_INDEX[next as usize] == INDEX_FAULT { + return E_INVALID_CONTROL; + } + 0 + } + + pub fn frames_per_packet(&self, max: u32) -> u32 { + let v = self.u32(FRAMES_PER_PACKET).load(Ordering::SeqCst); + let m = v.min(max); + if m == 0 { max } else { m } + } + + pub fn set_frames_per_packet(&self, frames: u32) { + self.u32(FRAMES_PER_PACKET).store(frames, Ordering::SeqCst); + } + + pub fn buffer_objects(&self, index: u32) -> u32 { + self.u32(BUFFER_OBJECTS + index as usize * 4).load(Ordering::SeqCst) + } + + pub fn buffer_frames(&self, index: u32) -> u32 { + self.u32(BUFFER_FRAMES + index as usize * 4).load(Ordering::SeqCst) + } + + pub fn frames_committed(&self) -> u64 { + self.u64(FRAMES_COMMITTED).load(Ordering::SeqCst) + } + + pub fn flags(&self) -> u32 { + self.u32(FLAGS).load(Ordering::SeqCst) + } + + pub fn set_flags(&self, set: u32, clear: u32) { + self.u32(FLAGS).fetch_and(!clear, Ordering::SeqCst); + self.u32(FLAGS).fetch_or(set, Ordering::SeqCst); + } + + pub fn counters(&self) -> (u32, u32) { + (self.u32(READ_STARVED).load(Ordering::SeqCst), self.u32(WRITE_STARVED).load(Ordering::SeqCst)) + } + + pub fn take_counters(&self) -> (u32, u32) { + (self.u32(READ_STARVED).swap(0, Ordering::SeqCst), self.u32(WRITE_STARVED).swap(0, Ordering::SeqCst)) + } + + pub fn transport(&self, start: bool) -> i32 { + if self.flags() & (FLAG_VALID | FLAG_CLOSED) != FLAG_VALID { + return E_INVALID_CONTROL; + } + if start { + self.set_flags(FLAG_STARTED, 0); + } else { + self.set_flags(0, FLAG_STARTED | FLAG_POSITION_LATCHED); + } + 0 + } + + pub fn reset(&self) -> i32 { + if self.flags() & (FLAG_VALID | FLAG_CLOSED) != FLAG_VALID { + return E_INVALID_CONTROL; + } + self.flush(); + 0 + } + } +} + unsafe fn is_format_supported(object: u32, a: *mut u8) -> i32 { let want: u8 = rd(a, 0); let mode: u32 = rd(a, 2); @@ -827,10 +2011,14 @@ unsafe fn transport(id: u32, object: u32) -> i32 { } } -fn simple(object: u32, f: impl FnOnce(&mut Object) -> R) -> Option { +fn simple(object: u32, f: impl FnOnce(&mut f32, &mut bool) -> R) -> Option { let mut s = state(); - let k = stream_owner(&s, object).unwrap_or(object); - let r = f(s.objects.get_mut(&k)?); + if !s.objects.contains_key(&object) { + return None; + } + let (mut g, mut m) = s.session_simple.unwrap_or((1.0, false)); + let r = f(&mut g, &mut m); + s.session_simple = Some((g, m)); apply_all(&mut s); Some(r) } @@ -901,34 +2089,316 @@ unsafe fn channel_op(op: u32, v: &mut Vec, a: *mut u8) -> i32 { } unsafe fn session_volume(id: u32, object: u32, a: *mut u8) -> i32 { + if let r @ wasapi::SessionRef::Pc(_) = session_ref(object) { + let mut v = match wasapi::session_channels_get(&r) { + Ok(v) => v, + Err(hr) => return hr, + }; + let hr = channel_op(id - SESSION_CHANNEL_COUNT, &mut v, a); + return match id { + SESSION_SET_CHANNEL_VOLUME if hr >= 0 => wasapi::session_channels_set(&r, &v, &guid_from(&ctx_at(a, 8))), + SESSION_SET_ALL_VOLUMES if hr >= 0 => wasapi::session_channels_set(&r, &v, &guid_from(&ctx_at(a, SESSION_ALL_VOLUMES_CTX))), + _ => hr, + }; + } let dev = device_for(object); let n = wasapi::device_info_for(dev.as_deref()).map(|d| wasapi::channels(&d.mix) as usize).unwrap_or(2); let mut s = state(); let mut v = s.session_channels.clone().unwrap_or_else(|| vec![1.0; n]); let r = channel_op(id - SESSION_CHANNEL_COUNT, &mut v, a); if r >= 0 && (id == SESSION_SET_CHANNEL_VOLUME || id == SESSION_SET_ALL_VOLUMES) { - s.session_channels = Some(v); + s.session_channels = Some(v.clone()); apply_all(&mut s); + drop(s); + let (changed, ctx) = if id == SESSION_SET_CHANNEL_VOLUME { (rd::(a, 0), ctx_at(a, 8)) } else { (u32::MAX, ctx_at(a, SESSION_ALL_VOLUMES_CTX)) }; + session_changed(|sid| session_channel_record(sid, &ctx, changed, &v)); } r } -fn register(object: u32, on: bool) -> i32 { +fn subscribe(object: u32, id: u32, on: bool) -> i32 { + if !state().objects.contains_key(&object) { + return E_INVALIDARG; + } + let mut watch = None; + if on { + wasapi::set_event_sink(pc_event); + let hr = match id { + ENUMERATOR_SUBSCRIBE => wasapi::watch_devices(), + ENDPOINT_REGISTER => { + watch = Some(endpoint_key(&device_for(object))); + S_OK + } + SESSION_REGISTER_NOTIFICATION | SESSION_MANAGER_REGISTER => match wasapi::watch_session(&session_ref(object)) { + Ok(sid) => { + watch = Some(sid); + S_OK + } + Err(hr) => hr, + }, + _ => S_OK, + }; + if hr < 0 { + return hr; + } + } let mut s = state(); match s.objects.get_mut(&object) { Some(o) => { o.notify = on; - compat_common::record_raw("crossvm-audio", "notify", &format!("object {object:#x} notifications {}", if on { "registered" } else { "unregistered" })); + o.notify_id = if on { id } else { 0 }; + o.watch = watch; + compat_common::record_raw("crossvm-audio", "notify", &format!("object {object:#x} notifications {} by {id:#x}", if on { "registered" } else { "unregistered" })); S_OK } None => E_INVALIDARG, } } +pub const NOTIFY_RECORD: usize = 0xc; +pub const DEVICE_RECORD_ID: usize = 0x34; +pub const DEVICE_RECORD_MAX_CHARS: usize = (gchost_frame() - NOTIFY_RECORD - DEVICE_RECORD_ID) / 2; +pub const VOLUME_RECORD_CHANNELS: usize = 0x38; + +const fn gchost_frame() -> usize { + crate::gchost::AUDIO_FRAME +} + +pub fn device_record(kind: u32, id: &str, a: u32, b: u32, key: Option<&wasapi::PropertyKey>) -> Option> { + let w: Vec = id.encode_utf16().chain(Some(0)).collect(); + if w.len() > DEVICE_RECORD_MAX_CHARS { + return None; + } + let mut r = vec![0u8; DEVICE_RECORD_ID + w.len() * 2]; + let n = r.len() as u32; + r[0..4].copy_from_slice(&n.to_le_bytes()); + r[0x18..0x1c].copy_from_slice(&kind.to_le_bytes()); + match kind { + 1 => r[0x1c..0x20].copy_from_slice(&a.to_le_bytes()), + 4 => { + r[0x1c..0x20].copy_from_slice(&a.to_le_bytes()); + r[0x20..0x24].copy_from_slice(&b.to_le_bytes()); + } + 5 => { + let k = key?; + r[0x1c..0x2c].copy_from_slice(&k.fmtid); + r[0x2c..0x30].copy_from_slice(&k.pid.to_le_bytes()); + } + _ => {} + } + for (i, c) in w.iter().enumerate() { + r[DEVICE_RECORD_ID + 2 * i..DEVICE_RECORD_ID + 2 * i + 2].copy_from_slice(&c.to_le_bytes()); + } + Some(r) +} + +pub fn volume_record(ctx: &[u8; 16], muted: bool, master: f32, channels: &[f32]) -> Option> { + let mut r = vec![0u8; VOLUME_RECORD_CHANNELS + 4 * channels.len()]; + if NOTIFY_RECORD + r.len() > gchost_frame() { + return None; + } + r[0x18..0x28].copy_from_slice(ctx); + r[0x28..0x2c].copy_from_slice(&(muted as u32).to_le_bytes()); + r[0x2c..0x30].copy_from_slice(&master.to_le_bytes()); + r[0x30..0x34].copy_from_slice(&(channels.len() as u32).to_le_bytes()); + for (i, c) in channels.iter().enumerate() { + r[VOLUME_RECORD_CHANNELS + 4 * i..VOLUME_RECORD_CHANNELS + 4 * i + 4].copy_from_slice(&c.to_le_bytes()); + } + Some(r) +} + +pub fn notify_frame(listener: u32, record: &[u8]) -> Vec { + let mut f = vec![0u8; gchost_frame()]; + f[4..8].copy_from_slice(&listener.to_le_bytes()); + f[NOTIFY_RECORD..NOTIFY_RECORD + record.len()].copy_from_slice(record); + f +} + +fn sent() -> std::sync::MutexGuard<'static, Vec<(i32, Vec)>> { + static S: std::sync::OnceLock)>>> = std::sync::OnceLock::new(); + S.get_or_init(|| Mutex::new(Vec::new())).lock().unwrap_or_else(|e| e.into_inner()) +} + +pub fn sent_notifications() -> Vec<(i32, Vec)> { + sent().clone() +} + +fn repeated(e: &wasapi::PcEvent) -> bool { + static LAST: Mutex> = Mutex::new(None); + let wasapi::PcEvent::Session { sid, kind, ctx, text, guid, value, volume, volumes } = e else { return false }; + let key = format!("{sid}|{kind}|{ctx:?}|{text}|{guid:?}|{value}|{}|{:?}", volume.to_bits(), volumes.iter().map(|v| v.to_bits()).collect::>()); + let mut l = LAST.lock().unwrap_or_else(|p| p.into_inner()); + let now = std::time::Instant::now(); + let dup = matches!(&*l, Some((k, t)) if *k == key && now.duration_since(*t) < std::time::Duration::from_millis(PC_REPEAT_MS)); + *l = Some((key, now)); + dup +} + +pub const PC_REPEAT_MS: u64 = 100; + +fn pc_event(e: wasapi::PcEvent) { + if repeated(&e) { + return; + } + let mut frames = Vec::new(); + { + let s = state(); + for (&k, o) in s.objects.iter().filter(|(_, o)| o.notify) { + let rec = match (&e, o.notify_id) { + (wasapi::PcEvent::Device { kind, id, a, b, key }, ENUMERATOR_SUBSCRIBE) => device_record(*kind, id, *a, *b, key.as_ref()), + (wasapi::PcEvent::Session { sid, kind, ctx, text, guid, value, volume, volumes }, SESSION_REGISTER_NOTIFICATION | SESSION_MANAGER_REGISTER) if o.watch.as_deref() == Some(sid.as_str()) => match *kind { + 1 if pc_session_of(&s, k).is_some() => session_simple_record(sid, ctx, *volume, *value != 0), + 2 if pc_session_of(&s, k).is_some() => session_channel_record(sid, ctx, *value, volumes), + 0x10 | 0x100 => session_text_record(*kind, sid, ctx, text), + 4 => session_record(4, sid, ctx, guid, &[]), + 8 | 0x20 => session_value_record(*kind, sid, *value), + _ => None, + }, + _ => None, + }; + if let Some(r) = rec { + frames.push(notify_frame(k, &r)); + } + } + } + deliver(frames); +} + +fn endpoint_changed(object: u32, ctx: &[u8; 16]) { + let key = endpoint_key(&device_for(object)); + let mut frames = Vec::new(); + { + let s = state(); + let Some(e) = s.endpoints.get(&key) else { return }; + let Some(r) = volume_record(ctx, e.mute, e.scalar, &e.channels) else { return }; + for (&k, _) in s.objects.iter().filter(|(_, o)| o.notify && o.notify_id == ENDPOINT_REGISTER && o.watch.as_deref() == Some(key.as_str())) { + frames.push(notify_frame(k, &r)); + } + } + deliver(frames); +} + +pub const SESSION_RECORD_SID: usize = 0x48; +pub const SESSION_ALL_VOLUMES_CTX: usize = 0xcc; +pub const SESSION_RECORD_ARGS: usize = 0x30; + +pub fn session_record(kind: u32, sid: &str, ctx: &[u8; 16], args: &[u8], tail: &[u8]) -> Option> { + let w: Vec = sid.encode_utf16().chain(Some(0)).flat_map(|c| c.to_le_bytes()).collect(); + let base = SESSION_RECORD_SID + w.len(); + if args.len() > SESSION_RECORD_SID - SESSION_RECORD_ARGS { + return None; + } + let mut r = vec![0u8; base]; + r[4..8].copy_from_slice(&kind.to_le_bytes()); + r[0x18..0x1c].copy_from_slice(&(w.len() as u32).to_le_bytes()); + r[0x1c..0x2c].copy_from_slice(ctx); + r[SESSION_RECORD_ARGS..SESSION_RECORD_ARGS + args.len()].copy_from_slice(args); + r[SESSION_RECORD_SID..base].copy_from_slice(&w); + r.extend_from_slice(tail); + if r.len() < 0x50 { + return None; + } + if NOTIFY_RECORD + r.len() > gchost_frame() { + return None; + } + let n = r.len() as u32; + r[0..4].copy_from_slice(&n.to_le_bytes()); + Some(r) +} + +fn session_sid_len(sid: &str) -> usize { + SESSION_RECORD_SID + 2 * (sid.encode_utf16().count() + 1) +} + +pub fn session_text_record(kind: u32, sid: &str, ctx: &[u8; 16], text: &str) -> Option> { + let t: Vec = text.encode_utf16().chain(Some(0)).flat_map(|c| c.to_le_bytes()).collect(); + let mut a = (t.len() as u32).to_le_bytes().to_vec(); + a.extend_from_slice(&(session_sid_len(sid) as u32).to_le_bytes()); + session_record(kind, sid, ctx, &a, &t) +} + +pub fn session_value_record(kind: u32, sid: &str, value: u32) -> Option> { + if kind == 8 && value > 2 || kind == 0x20 && !matches!(value, 0 | 1 | 2 | 4 | 5) { + return None; + } + session_record(kind, sid, &[0; 16], &value.to_le_bytes(), &[]) +} + +pub fn session_simple_record(sid: &str, ctx: &[u8; 16], volume: f32, mute: bool) -> Option> { + let mut a = volume.to_le_bytes().to_vec(); + a.push(mute as u8); + session_record(1, sid, ctx, &a, &[]) +} + +pub fn session_channel_record(sid: &str, ctx: &[u8; 16], changed: u32, volumes: &[f32]) -> Option> { + let base = session_sid_len(sid); + let off = (base + 3) & !3; + let mut a = (off as u32).to_le_bytes().to_vec(); + a.extend_from_slice(&changed.to_le_bytes()); + a.extend_from_slice(&(volumes.len() as u32).to_le_bytes()); + let mut t = vec![0u8; off - base]; + for v in volumes { + t.extend_from_slice(&v.to_le_bytes()); + } + let r = session_record(2, sid, ctx, &a, &t)?; + if r.len() != off + 4 * volumes.len() { + return None; + } + Some(r) +} + +fn session_changed(build: impl Fn(&str) -> Option>) { + let mut frames = Vec::new(); + { + let s = state(); + for (&k, o) in s.objects.iter().filter(|(_, o)| o.notify && matches!(o.notify_id, SESSION_REGISTER_NOTIFICATION | SESSION_MANAGER_REGISTER)) { + if pc_session_of(&s, k).is_some() { + continue; + } + if let Some(r) = o.watch.as_deref().and_then(&build) { + frames.push(notify_frame(k, &r)); + } + } + } + deliver(frames); +} + +unsafe fn ctx_at(a: *const u8, o: usize) -> [u8; 16] { + let mut g = [0u8; 16]; + core::ptr::copy_nonoverlapping(a.add(o), g.as_mut_ptr(), 16); + g +} + +fn deliver(frames: Vec>) { + for f in frames { + let hr = crate::gchost::push_audio(&f); + compat_common::record_raw("crossvm-audio", "notify", &format!("host->guest notification to listener {:#x}, record kind {:#x} -> {hr:#010x}", u32::from_le_bytes(f[4..8].try_into().unwrap()), u32::from_le_bytes(f[0x24..0x28].try_into().unwrap()))); + let mut l = sent(); + if l.len() >= 256 { + l.remove(0); + } + l.push((hr, f)); + } +} + pub fn notifications_registered(object: u32) -> bool { state().objects.get(&object).map(|o| o.notify).unwrap_or(false) } -unsafe fn property_value(object: u32, a: *mut u8) -> i32 { +pub fn serialized_prop(vt: u16, count: Option, bytes: &[u8]) -> Vec { + let mut d = vec![0u8; 8]; + d[0..2].copy_from_slice(&vt.to_le_bytes()); + if let Some(n) = count { + d[4..8].copy_from_slice(&n.to_le_bytes()); + } + d.extend_from_slice(bytes); + d +} + +pub const PROP_TAG: usize = 0x14; +pub const PROP_BYTES: usize = 0x18; +pub const PROP_LEN: usize = PROP_BYTES + PROP_DATA; + +unsafe fn property_value(object: u32, a: *mut u8, room: usize) -> i32 { let mut key = wasapi::PropertyKey::default(); core::ptr::copy_nonoverlapping(a, key.fmtid.as_mut_ptr(), 16); key.pid = rd(a, 0x10); @@ -941,23 +2411,24 @@ unsafe fn property_value(object: u32, a: *mut u8) -> i32 { Some(wasapi::Prop::Empty) => (0, Vec::new()), Some(wasapi::Prop::Text(w)) => (1, w.iter().flat_map(|c| c.to_le_bytes()).collect()), Some(wasapi::Prop::Dword(d)) => (4, d.to_le_bytes().to_vec()), - Some(wasapi::Prop::Serialized(vt, bytes)) => { - let mut d = vec![0u8; 8]; - d[0..2].copy_from_slice(&vt.to_le_bytes()); - d.extend_from_slice(&bytes); - (3, d) - } + Some(wasapi::Prop::Serialized(vt, bytes)) => (3, serialized_prop(vt, None, &bytes)), + Some(wasapi::Prop::Vector(vt, count, bytes)) => (3, serialized_prop(vt, Some(count), &bytes)), None => { compat_common::record_raw("crossvm-audio", "property", "PC property type has no decoded guest serialisation; E_NOTIMPL"); return E_NOTIMPL; } }; - if data.len() > PROP_DATA { + put_property(a, room, tag, &data) +} + +pub unsafe fn put_property(a: *mut u8, room: usize, tag: u32, data: &[u8]) -> i32 { + if PROP_BYTES + data.len() > room { + compat_common::record_raw("crossvm-audio", "property", &format!("serialised value of {} bytes passes the {room:#x}-byte envelope payload; the console memcpy would write past its 0x810 allocation, host answers E_OUTOFMEMORY", data.len())); return E_OUTOFMEMORY; } - wr(a, 0x14, tag); - core::ptr::copy_nonoverlapping(data.as_ptr(), a.add(0x18), data.len()); - wr(a, 0x18 + PROP_DATA, data.len() as u64); + core::ptr::copy_nonoverlapping(data.as_ptr(), a.add(PROP_BYTES), data.len()); + wr(a, PROP_TAG, tag); + wr(a, PROP_LEN, data.len() as u64); S_OK } @@ -1000,19 +2471,48 @@ unsafe fn spatial(id: u32, object: u32, a: *mut u8) -> i32 { let offload: u8 = rd(a, SPATIAL_OFFLOAD_AT); put(sp.max_frames_for_category(cat, offload != 0, &f), SPATIAL_FRAMES_AT) } - FORMAT_ENUM_COUNT => put(sp.format_count(), 0), - FORMAT_ENUM_GET => match sp.format_at(0) { - Ok(f) => { - let plain = plain_format(&f); - core::ptr::copy_nonoverlapping(plain.as_ptr(), a.add(FORMAT_ENUM_AT), PLAIN_FORMAT); + _ => { + let cat: u32 = rd(a, 0); + put(sp.offload_capable(cat), 4) + } + } +} + +unsafe fn format_enum(id: u32, object: u32, a: *mut u8) -> i32 { + let s = state(); + let Some(e) = s.objects.get(&object).filter(|o| o.kind == FORMAT_ENUM_TYPE).and_then(|o| o.formats.as_ref()) else { + compat_common::record_raw("crossvm-audio", "format-enum", &format!("call id {id:#x} on object {object:#x}: only the type 4 object (map 1ac4d0: 0x3a -> 125a10, 0x3b -> 125a90) serves 0x3a / 0x3b and it serves nothing else; 125e00 answers E_NOTIMPL")); + return E_NOTIMPL; + }; + match id { + FORMAT_ENUM_COUNT => match e.count() { + Ok(n) => { + wr(a, 0, n); S_OK } Err(hr) => hr, }, - _ => { - let cat: u32 = rd(a, 0); - put(sp.offload_capable(cat), 4) + FORMAT_ENUM_GET => { + let cb: u16 = rd(a, FORMAT_ENUM_CB_AT); + if cb as usize + PLAIN_FORMAT > FORMAT_ENUM_ROOM { + return E_INVALIDARG; + } + let index: u32 = rd(a, 0); + match e.count() { + Ok(n) if index >= n => return E_BOUNDS, + Err(hr) => return hr, + _ => {} + } + match e.get(index) { + Ok(f) => { + let plain = plain_format(&f); + core::ptr::copy_nonoverlapping(plain.as_ptr(), a.add(FORMAT_ENUM_AT), PLAIN_FORMAT); + S_OK + } + Err(hr) => hr, + } } + _ => E_NOTIMPL, } } @@ -1028,6 +2528,26 @@ pub fn plain_format(f: &[u8]) -> [u8; PLAIN_FORMAT] { } unsafe fn endpoint_volume(id: u32, object: u32, a: *mut u8) -> i32 { + let ctx_at = match id { + SET_ENDPOINT_VOLUME_LEVEL | SET_ENDPOINT_VOLUME_SCALAR => Some(4), + SET_ENDPOINT_CHANNEL_LEVEL | SET_ENDPOINT_CHANNEL_SCALAR => Some(8), + SET_ENDPOINT_MUTE => Some(1), + ENDPOINT_STEP_UP | ENDPOINT_STEP_DOWN => Some(0), + _ => None, + }; + let ctx = ctx_at.map(|o| { + let mut g = [0u8; 16]; + core::ptr::copy_nonoverlapping(a.add(o), g.as_mut_ptr(), 16); + g + }); + let hr = endpoint_volume_call(id, object, a); + if let (Some(g), S_OK) = (ctx, hr) { + endpoint_changed(object, &g); + } + hr +} + +unsafe fn endpoint_volume_call(id: u32, object: u32, a: *mut u8) -> i32 { let dev = device_for(object); let caps = match wasapi::endpoint_caps(dev.as_deref()) { Ok(c) => c, @@ -1234,7 +2754,13 @@ unsafe fn initialize(object: u32, a: *mut u8, room: usize, lay: &InitLayout) -> write_control_block(base, &format, hns, &l); let ring = wasapi::Ring { base, start: l.start, end: l.end, align }; let open = wasapi::Open { device: dev.clone(), format: format.clone(), duration: hns, session, properties: props, flags, period_frames: period }; - let (renderer, device_frames) = match wasapi::open(open, ring) { + let capture = dev.is_some() && wasapi::device_flow(dev.as_deref()) == Ok(1); + let opened = if capture { + wasapi::open_capture(open, ring, wasapi::CaptureQueue { base, queue: l.queue as usize, entries: l.entries }) + } else { + wasapi::open(open, ring) + }; + let (renderer, device_frames) = match opened { Ok(r) => r, Err(hr) => { crate::logan::pool_release(index as usize); @@ -1256,7 +2782,7 @@ unsafe fn initialize(object: u32, a: *mut u8, room: usize, lay: &InitLayout) -> }; core::ptr::write_bytes(a.add(lay.clsid), 0, lay.size - lay.clsid); core::ptr::copy_nonoverlapping(format.as_ptr(), a.add(lay.format), flen); - core::ptr::copy_nonoverlapping(guid_bytes(&CLSID_CLIENT_OUTPUT_ENDPOINT).as_ptr(), a.add(lay.clsid), 16); + core::ptr::copy_nonoverlapping(guid_bytes(if capture { &CLSID_CLIENT_INPUT_ENDPOINT } else { &CLSID_CLIENT_OUTPUT_ENDPOINT }).as_ptr(), a.add(lay.clsid), 16); wr(a, lay.event1, KIND_NONE); wr(a, lay.event2, KIND_NONE); write_event_descriptor(a.add(lay.event3), EVENT_KIND_GAMECORE, event_id as u16); @@ -1264,7 +2790,7 @@ unsafe fn initialize(object: u32, a: *mut u8, room: usize, lay: &InitLayout) -> core::ptr::copy_nonoverlapping(guid_bytes(&CLSID_XVM_BUFFER).as_ptr(), a.add(lay.memory + 4), 16); core::ptr::copy_nonoverlapping(guid_bytes(&GUID_XVM_BUFFER).as_ptr(), a.add(lay.memory + 0x14), 16); wr(a, lay.memory + 0x24, index as u32); - compat_common::record_raw("crossvm-audio", "Initialize", &format!("object {object:#x}: {frames} frames ({} bytes) at pool page {index}, WASAPI buffer {device_frames} frames, period {period:?}, flags {flags:#x}, period event {name}", l.bytes)); + compat_common::record_raw("crossvm-audio", "Initialize", &format!("object {object:#x}: {frames} frames ({} bytes) at pool page {index}, WASAPI buffer {device_frames} frames, period {period:?}, flags {flags:#x}, period event {name}, {}", l.bytes, if capture { "capture" } else { "render" })); let mut s = state(); s.session.get_or_insert(session); if let Some(o) = s.objects.get_mut(&object) { diff --git a/crates/compat/console-sandbox/src/gcdcom.rs b/crates/compat/console-sandbox/src/gcdcom.rs index a1c80e16..291f25ae 100644 --- a/crates/compat/console-sandbox/src/gcdcom.rs +++ b/crates/compat/console-sandbox/src/gcdcom.rs @@ -538,20 +538,18 @@ static NET_SECURITY_REFS: AtomicU32 = AtomicU32::new(0); static NET_RESULT_REFS: AtomicU32 = AtomicU32::new(0); macro_rules! unserved { - ($name:ident, $iface:literal, $slot:literal) => { + ($name:ident, $iface:literal, $slot:literal, $why:literal) => { unsafe extern "system" fn $name(_this: *mut c_void) -> i32 { - compat_common::record_raw("gamecore-host", $iface, concat!("slot ", $slot, " has no decoded meaning; E_NOTIMPL")); + compat_common::record_raw("gamecore-host", $iface, concat!("slot ", $slot, ": ", $why, "; E_NOTIMPL")); E_NOTIMPL } }; } -unserved!(v7_7, "PackageV7", 7); -unserved!(v7_17, "PackageV7", 17); -unserved!(v7_18, "PackageV7", 18); -unserved!(v7_19, "PackageV7", 19); -unserved!(v7_24, "PackageV7", 24); -unserved!(v7_25, "PackageV7", 25); +unserved!(v7_17, "PackageV7", 17, "in const GUID*, reached only from package-server slot 23 (19041 fn 8d10), which no title path in any dump calls"); +unserved!(v7_18, "PackageV7", 18, "in const GUID*, reached only from package-server slot 24 (19041 fn 8df0), which no title path in any dump calls"); +unserved!(v7_24, "PackageV7", 24, "batch id query with {HSTRING, u8} results; no console client calls it and the server body is in no dump"); +unserved!(v7_25, "PackageV7", 25, "batch id query with {HSTRING, i32} results; no console client calls it and the server body is in no dump"); unsafe fn wide_text(p: *const u16) -> Option { if p.is_null() { @@ -651,7 +649,7 @@ pub fn features_record(f: &[compat_common::gdk::package::Feature]) -> Vec { v } -unsafe extern "system" fn v7_features(_this: *mut c_void, pkg: *const u16, _kind: i32, out: *mut *mut c_void) -> i32 { +unsafe fn serve_features(slot: u32, pkg: *const u16, out: *mut *mut c_void) -> i32 { if out.is_null() { return E_POINTER; } @@ -660,10 +658,18 @@ unsafe extern "system" fn v7_features(_this: *mut c_void, pkg: *const u16, _kind return compat_common::gdk::E_NOT_FOUND; } let f = compat_common::gdk::package::features(); - compat_common::record_raw("gamecore-host", "PackageV7", &format!("slot 26 features -> {} records", f.len())); + compat_common::record_raw("gamecore-host", "PackageV7", &format!("slot {slot} features -> {} records", f.len())); put_hstring(out, &features_record(f)) } +unsafe extern "system" fn v7_features(_this: *mut c_void, pkg: *const u16, _kind: i32, out: *mut *mut c_void) -> i32 { + serve_features(26, pkg, out) +} + +unsafe extern "system" fn v7_19(_this: *mut c_void, pkg: *const u16, out: *mut *mut c_void) -> i32 { + serve_features(19, pkg, out) +} + unsafe extern "system" fn v7_uninstall(_this: *mut c_void, pkg: *const u16) -> i32 { if !package_known(wide_text(pkg)) { return compat_common::gdk::E_NOT_FOUND; @@ -691,7 +697,7 @@ unsafe fn fill_details(d: *mut PkgDetails) -> i32 { core::ptr::write_bytes(d as *mut u8, 0, core::mem::size_of::()); let d = &mut *d; d.version = [t.version[3], t.version[2], t.version[1], t.version[0]]; - for (slot, text) in [(&mut d.id, compat_common::gdk::package::package_id()), (&mut d.display, t.display.clone()), (&mut d.publisher, t.publisher.clone())] { + for (slot, text) in [(&mut d.id, compat_common::gdk::package::package_id()), (&mut d.display, t.display.clone()), (&mut d.publisher, t.publisher.clone()), (&mut d.store_id, compat_common::gdk::store::game_store_id())] { let hr = put_hstring(slot, &wide(&text)); if hr < 0 { return hr; @@ -918,6 +924,24 @@ unsafe extern "system" fn v7_14(_this: *mut c_void, watched: *const u16, install S_OK } +pub fn alias_identity(kind: i32, id: &str) -> Option { + (kind == 0 && !id.is_empty() && id.eq_ignore_ascii_case(&compat_common::gdk::store::game_store_id())).then(compat_common::gdk::package::package_id) +} + +unsafe extern "system" fn v7_7(_this: *mut c_void, kind: i32, id: *const u16, out: *mut *mut c_void) -> i32 { + if out.is_null() { + return E_POINTER; + } + *out = core::ptr::null_mut(); + let id = wide_text(id).unwrap_or_default(); + let hit = alias_identity(kind, &id); + compat_common::record_raw("gamecore-host", "PackageV7", &format!("slot 7 alias kind {kind} '{id}' -> {}", hit.as_deref().unwrap_or("not found"))); + match hit { + Some(p) => put_hstring(out, &wide(&p)), + None => compat_common::gdk::E_NOT_FOUND, + } +} + unsafe extern "system" fn v7_16(_this: *mut c_void, kind: i32, id: *const u16, out: *mut *mut c_void, kind_out: *mut i32) -> i32 { if out.is_null() || kind_out.is_null() { return E_POINTER; @@ -925,12 +949,12 @@ unsafe extern "system" fn v7_16(_this: *mut c_void, kind: i32, id: *const u16, o *out = core::ptr::null_mut(); *kind_out = 0; let id = wide_text(id).unwrap_or_default(); - let hit = kind == 0 && id.eq_ignore_ascii_case(&compat_common::gdk::store::game_store_id()); - compat_common::record_raw("gamecore-host", "PackageV7", &format!("slot 16 resolve kind {kind} '{id}' -> {}", if hit { "this package" } else { "not found" })); - if !hit { - return compat_common::gdk::E_NOT_FOUND; + let hit = alias_identity(kind, &id); + compat_common::record_raw("gamecore-host", "PackageV7", &format!("slot 16 resolve kind {kind} '{id}' -> {}", if hit.is_some() { "this package" } else { "not found" })); + match hit { + Some(p) => put_hstring(out, &wide(&p)), + None => compat_common::gdk::E_NOT_FOUND, } - put_hstring(out, &wide(&compat_common::gdk::package::package_id())) } unsafe extern "system" fn v7_mount_step(slot: u32, target: *const u16, caller: *const u16) -> i32 { diff --git a/crates/compat/console-sandbox/src/gchost.rs b/crates/compat/console-sandbox/src/gchost.rs index 9e9564d6..1e88262d 100644 --- a/crates/compat/console-sandbox/src/gchost.rs +++ b/crates/compat/console-sandbox/src/gchost.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, OnceLock}; pub const DISPLAY_MODE_1: u32 = 0x0001_0007; @@ -7,6 +8,27 @@ pub const PROXY_APP: u32 = 0x0064_003f; pub const CHANNEL_OPEN: u32 = 0x0000_0005; pub const WINDOW_MESSAGING: u32 = 0x0000_0001; pub const AUDIO_HELLO: u32 = 0x0008; +pub const AUDIO_NOTIFY: u32 = 0x0002; +pub const AUDIO_FRAME: usize = 0x810; + +static AUDIO_STREAM: AtomicU64 = AtomicU64::new(0); + +pub fn audio_stream() -> Option { + match AUDIO_STREAM.load(Ordering::SeqCst) { + 0 => None, + v => Some(v - 1), + } +} + +pub fn push_audio(frame: &[u8]) -> i32 { + if frame.len() != AUDIO_FRAME { + return -2147024809; + } + let Some(id) = audio_stream() else { + return -2147483638; + }; + push(id, (crate::crossvm::generation() << 16) | AUDIO_NOTIFY, frame) +} #[derive(Default)] struct Stream { @@ -87,6 +109,7 @@ pub fn push_input(id: u64, records: &[(u32, u64, u64)]) -> i32 { pub fn forget(id: u64) { streams().remove(&id); + let _ = AUDIO_STREAM.compare_exchange(id + 1, 0, Ordering::SeqCst, Ordering::SeqCst); } pub fn on_bytes(id: u64, data: &[u8]) -> Vec { @@ -101,6 +124,7 @@ pub fn on_bytes(id: u64, data: &[u8]) -> Vec { if kind & 0xffff == AUDIO_HELLO && payload.is_empty() { let ack = kind & 0xffff_0000; crate::crossvm::set_hello((kind >> 16) as u16); + AUDIO_STREAM.store(id + 1, Ordering::SeqCst); compat_common::record_raw("gamecore-host", "audio", &format!("XVMAudioService hello {kind:#010x}; host ack frame {ack:#010x}")); out.extend(frame(st.prev_out, ack, &[])); st.prev_out = 0; diff --git a/crates/compat/console-sandbox/src/lib.rs b/crates/compat/console-sandbox/src/lib.rs index 55195590..d2d8db16 100644 --- a/crates/compat/console-sandbox/src/lib.rs +++ b/crates/compat/console-sandbox/src/lib.rs @@ -16,6 +16,8 @@ pub mod modules; pub mod power; pub mod regnt; pub mod rpc; +pub mod rpcsrv; +pub mod comreg; pub mod wnf; pub mod host; pub mod notify; @@ -60,6 +62,8 @@ const SYSINFO: &[&str] = &["api-ms-win-core-sysinfo-", "kernelbase", "kernel32"] const THREADS: &[&str] = &["api-ms-win-core-processthreads-", "kernelbase", "kernel32"]; const SERVICE: &[&str] = &["api-ms-win-service-", "advapi32", "sechost"]; const RPC: &[&str] = &["rpcrt4"]; +const COM: &[&str] = &["api-ms-win-core-com-", "combase", "ole32"]; +const WINRT: &[&str] = &["api-ms-win-core-winrt-", "combase"]; const POWER: &[&str] = &["api-ms-win-power-setting-", "powrprof", "umpdc"]; const DEVCFG: &[&str] = &["api-ms-win-devices-config-", "cfgmgr32"]; const LOADER: &[&str] = &["api-ms-win-core-libraryloader-", "kernelbase", "kernel32"]; @@ -123,6 +127,31 @@ pub fn hooks() -> Vec { hook!("RtlAllocateWnfSerializationGroup", NTDLL, wnf::rtl_allocate_wnf_serialization_group), hook!("RtlWaitForWnfMetaNotification", NTDLL, wnf::rtl_wait_for_wnf_meta_notification), hook!("RpcServerUseProtseqW", RPC, rpc::rpc_server_use_protseq_w), + hook!("RpcServerInqDefaultPrincNameW", RPC, rpcsrv::rpc_server_inq_default_princ_name_w), + hook!("RpcServerRegisterAuthInfoW", RPC, rpcsrv::rpc_server_register_auth_info_w), + hook!("RpcServerRegisterIf", RPC, rpcsrv::rpc_server_register_if), + hook!("RpcServerRegisterIfEx", RPC, rpcsrv::rpc_server_register_if_ex), + hook!("RpcServerRegisterIf2", RPC, rpcsrv::rpc_server_register_if2), + hook!("RpcServerRegisterIf3", RPC, rpcsrv::rpc_server_register_if3), + hook!("RpcServerUnregisterIf", RPC, rpcsrv::rpc_server_unregister_if), + hook!("RpcServerInqBindings", RPC, rpcsrv::rpc_server_inq_bindings), + hook!("RpcBindingVectorFree", RPC, rpcsrv::rpc_binding_vector_free), + hook!("RpcBindingToStringBindingW", RPC, rpcsrv::rpc_binding_to_string_binding_w), + hook!("RpcStringFreeW", RPC, rpcsrv::rpc_string_free_w), + hook!("RpcServerInqCallAttributesW", RPC, rpcsrv::rpc_server_inq_call_attributes_w), + hook!("RpcServerTestCancel", RPC, rpcsrv::rpc_server_test_cancel), + hook!("RpcServerSubscribeForNotification", RPC, rpcsrv::rpc_server_subscribe_for_notification), + hook!("RpcServerUnsubscribeForNotification", RPC, rpcsrv::rpc_server_unsubscribe_for_notification), + hook!("RpcAsyncCompleteCall", RPC, rpcsrv::rpc_async_complete_call), + hook!("RpcAsyncAbortCall", RPC, rpcsrv::rpc_async_abort_call), + hook!("CoRegisterClassObject", COM, comreg::co_register_class_object), + hook!("CoRevokeClassObject", COM, comreg::co_revoke_class_object), + hook!("CoResumeClassObjects", COM, comreg::co_resume_class_objects), + hook!("CoGetClassObject", COM, comreg::co_get_class_object), + hook!("CoCreateInstance", COM, comreg::co_create_instance), + hook!("RoRegisterActivationFactories", WINRT, comreg::ro_register_activation_factories), + hook!("RoRevokeActivationFactories", WINRT, comreg::ro_revoke_activation_factories), + hook!("RoGetActivationFactory", WINRT, comreg::ro_get_activation_factory), hook!("RpcServerUseProtseqEpW", RPC, rpc::rpc_server_use_protseq_ep_w), hook!("RpcEpRegisterW", RPC, rpc::rpc_ep_register_w), hook!("RpcEpRegisterNoReplaceW", RPC, rpc::rpc_ep_register_no_replace_w), diff --git a/crates/compat/console-sandbox/src/rpc.rs b/crates/compat/console-sandbox/src/rpc.rs index d1802e14..317263b2 100644 --- a/crates/compat/console-sandbox/src/rpc.rs +++ b/crates/compat/console-sandbox/src/rpc.rs @@ -15,7 +15,6 @@ pub const RPC_BHT_OBJECT_UUID_VALID: u32 = 1; #[link(name = "rpcrt4")] extern "system" { - fn RpcServerUseProtseqEpW(protseq: *const u16, max: u32, ep: *const u16, sd: *mut c_void) -> i32; fn RpcBindingToStringBindingW(b: *mut c_void, out: *mut *mut u16) -> i32; fn RpcStringBindingParseW(s: *const u16, obj: *mut *mut u16, protseq: *mut *mut u16, addr: *mut *mut u16, ep: *mut *mut u16, opts: *mut *mut u16) -> i32; fn RpcStringFreeW(s: *mut *mut u16) -> i32; @@ -90,45 +89,19 @@ fn is_lrpc(p: &str) -> bool { p.eq_ignore_ascii_case("ncalrpc") } -fn known_protseq(p: &str) -> bool { - ["ncalrpc", "ncacn_ip_tcp", "ncacn_np", "ncacn_http", "ncadg_ip_udp", "ncacn_hvsocket"].iter().any(|k| k.eq_ignore_ascii_case(p)) -} - pub unsafe extern "system" fn rpc_server_use_protseq_w(protseq: *const u16, max: u32, sd: *mut c_void) -> i32 { let p = from_ptr(protseq); - if !known_protseq(&p) { - return RPC_S_INVALID_RPC_PROTSEQ; - } - if !is_lrpc(&p) { - note(format!("RpcServerUseProtseqW {p} refused: the emulator is offline")); - return RPC_S_PROTSEQ_NOT_SUPPORTED; - } - if map().dynamic_listening { - return RPC_S_OK; - } - let ep = wide(&dynamic_endpoint()); - let r = RpcServerUseProtseqEpW(protseq, max, ep.as_ptr(), sd); - if r == RPC_S_OK || r == RPC_S_DUPLICATE_ENDPOINT { + let r = crate::rpcsrv::rpc_server_use_protseq_w(protseq, max, sd); + note(format!("RpcServerUseProtseqW {p} = {r} (in-process)")); + if r == RPC_S_OK && is_lrpc(&p) { map().dynamic_listening = true; - note(format!("RpcServerUseProtseqW ncalrpc -> {}", dynamic_endpoint())); - return RPC_S_OK; } r } pub unsafe extern "system" fn rpc_server_use_protseq_ep_w(protseq: *const u16, max: u32, ep: *const u16, sd: *mut c_void) -> i32 { - let p = from_ptr(protseq); - if !known_protseq(&p) { - return RPC_S_INVALID_RPC_PROTSEQ; - } - if !is_lrpc(&p) { - note(format!("RpcServerUseProtseqEpW {p} refused: the emulator is offline")); - return RPC_S_PROTSEQ_NOT_SUPPORTED; - } - let e = from_ptr(ep); - let n = wide(&namespaced(&e)); - let r = RpcServerUseProtseqEpW(protseq, max, n.as_ptr(), sd); - note(format!("RpcServerUseProtseqEpW ncalrpc {e} -> {} = {r}", namespaced(&e))); + let r = crate::rpcsrv::rpc_server_use_protseq_ep_w(protseq, max, ep, sd); + note(format!("RpcServerUseProtseqEpW {} {} = {r} (in-process)", from_ptr(protseq), from_ptr(ep))); r } @@ -146,6 +119,9 @@ unsafe fn interface_of(ifspec: *const c_void) -> ([u8; 16], u16, u16) { } unsafe fn binding_parts(b: *mut c_void) -> Option<(String, String)> { + if let Some((ps, ep, _)) = crate::rpcsrv::binding_parts(b as usize) { + return Some((ps, ep)); + } let mut s: *mut u16 = core::ptr::null_mut(); if RpcBindingToStringBindingW(b, &mut s) != RPC_S_OK { return None; diff --git a/crates/compat/console-sandbox/src/rpcsrv.rs b/crates/compat/console-sandbox/src/rpcsrv.rs new file mode 100644 index 00000000..f5e5be7c --- /dev/null +++ b/crates/compat/console-sandbox/src/rpcsrv.rs @@ -0,0 +1,874 @@ +use core::ffi::c_void; +use std::cell::Cell; +use std::collections::{HashMap, HashSet}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +use crate::wstr::{from_ptr, wide}; + +pub const RPC_S_OK: i32 = 0; +pub const RPC_S_ACCESS_DENIED: i32 = 5; +pub const RPC_S_OUT_OF_MEMORY: i32 = 14; +pub const RPC_S_INVALID_ARG: i32 = 87; +pub const ERROR_MORE_DATA: i32 = 234; +pub const RPC_S_INVALID_BINDING: i32 = 1702; +pub const RPC_S_PROTSEQ_NOT_SUPPORTED: i32 = 1703; +pub const RPC_S_INVALID_RPC_PROTSEQ: i32 = 1704; +pub const RPC_S_INVALID_ENDPOINT_FORMAT: i32 = 1706; +pub const RPC_S_TYPE_ALREADY_REGISTERED: i32 = 1711; +pub const RPC_S_UNKNOWN_IF: i32 = 1717; +pub const RPC_S_NO_BINDINGS: i32 = 1718; +pub const RPC_S_SERVER_TOO_BUSY: i32 = 1723; +pub const RPC_S_NO_CALL_ACTIVE: i32 = 1725; +pub const RPC_S_DUPLICATE_ENDPOINT: i32 = 1740; +pub const RPC_S_UNKNOWN_AUTHN_SERVICE: i32 = 1747; +pub const RPC_S_PROCNUM_OUT_OF_RANGE: i32 = 1745; +pub const RPC_S_CALL_IN_PROGRESS: i32 = 1791; +pub const RPC_S_INVALID_ASYNC_HANDLE: i32 = 1914; + +pub const RPC_IF_AUTOLISTEN: u32 = 0x1; +pub const RPC_IF_ALLOW_SECURE_ONLY: u32 = 0x8; +pub const RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH: u32 = 0x10; +pub const RPC_IF_ALLOW_LOCAL_ONLY: u32 = 0x20; + +pub const RPC_C_AUTHN_NONE: u32 = 0; +pub const RPC_C_AUTHN_GSS_NEGOTIATE: u32 = 9; +pub const RPC_C_AUTHN_WINNT: u32 = 10; +pub const RPC_C_AUTHN_GSS_SCHANNEL: u32 = 14; +pub const RPC_C_AUTHN_GSS_KERBEROS: u32 = 16; +pub const RPC_C_AUTHN_DEFAULT: u32 = 0xffff_ffff; +pub const RPC_C_AUTHN_LEVEL_NONE: u32 = 1; +pub const RPC_C_AUTHN_LEVEL_PKT_PRIVACY: u32 = 6; + +pub const RPC_PROTSEQ_LRPC: u32 = 3; +pub const RPC_PROTSEQ_HVSOCKET: u32 = 5; + +pub const RPC_QUERY_SERVER_PRINCIPAL_NAME: u32 = 0x2; +pub const RPC_QUERY_CLIENT_PRINCIPAL_NAME: u32 = 0x4; +pub const RPC_QUERY_CLIENT_PID: u32 = 0x10; +pub const RPC_QUERY_IS_CLIENT_LOCAL: u32 = 0x20; +pub const RPC_QUERY_CLIENT_ID: u32 = 0x80; + +pub const RCCL_LOCAL: u32 = 1; +pub const RCCL_REMOTE: u32 = 2; +pub const RPC_CALL_STATUS_IN_PROGRESS: u32 = 1; +pub const RPC_CALL_STATUS_CANCELLED: u32 = 2; +pub const RPC_CALL_STATUS_DISCONNECTED: u32 = 3; +pub const RCT_NORMAL: u32 = 1; + +pub const RPC_NOTIFICATION_CLIENT_DISCONNECT: u32 = 1; +pub const RPC_NOTIFICATION_CALL_CANCEL: u32 = 2; +pub const RPC_NOTIFICATION_TYPE_EVENT: u32 = 1; +pub const RPC_NOTIFICATION_TYPE_CALLBACK: u32 = 5; +pub const RPC_ASYNC_EVENT_CLIENT_DISCONNECT: u32 = 3; +pub const RPC_ASYNC_EVENT_CLIENT_CANCEL: u32 = 4; +pub const RPC_ASYNC_STATE_SIZE: u32 = 0x70; +pub const RPC_ASYNC_SIGNATURE: u32 = 0x4352_4153; + +pub const DEFAULT_PRINCIPAL: &str = "NT AUTHORITY\\LOCAL SERVICE"; + +const HANDLE_MAGIC: u64 = 0x4e49_5652_4553_4254; + +#[link(name = "rpcrt4")] +extern "system" { + fn RpcBindingToStringBindingW(b: *mut c_void, out: *mut *mut u16) -> i32; + fn RpcBindingVectorFree(v: *mut *mut c_void) -> i32; + fn RpcStringFreeW(s: *mut *mut u16) -> i32; + fn RpcAsyncCompleteCall(a: *mut c_void, reply: *mut c_void) -> i32; + fn RpcAsyncAbortCall(a: *mut c_void, code: u32) -> i32; + fn UuidToStringW(u: *const [u8; 16], out: *mut *mut u16) -> i32; +} + +#[link(name = "kernel32")] +extern "system" { + fn GetProcessHeap() -> *mut c_void; + fn HeapAlloc(h: *mut c_void, flags: u32, n: usize) -> *mut c_void; + fn HeapFree(h: *mut c_void, flags: u32, p: *mut c_void) -> i32; + fn SetEvent(h: usize) -> i32; +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Endpoint { + pub protseq: String, + pub endpoint: String, + pub max_calls: u32, + pub dynamic: bool, + pub security: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AuthInfo { + pub principal: String, + pub service: u32, + pub get_key: usize, + pub arg: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Interface { + pub ifspec: usize, + pub uuid: [u8; 16], + pub major: u16, + pub minor: u16, + pub mgr_type: [u8; 16], + pub epv: usize, + pub flags: u32, + pub max_calls: u32, + pub max_rpc_size: u32, + pub callback: usize, + pub security: usize, + pub active: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Client { + pub protseq: String, + pub endpoint: String, + pub local: bool, + pub pid: u32, + pub principal: String, + pub authn_service: u32, + pub authn_level: u32, + pub client_id: Vec, + pub object: [u8; 16], +} + +impl Client { + pub fn lrpc(endpoint: &str) -> Self { + Client { protseq: "ncalrpc".into(), endpoint: endpoint.into(), local: true, pid: std::process::id(), principal: DEFAULT_PRINCIPAL.into(), authn_service: RPC_C_AUTHN_WINNT, authn_level: RPC_C_AUTHN_LEVEL_PKT_PRIVACY, client_id: Vec::new(), object: [0; 16] } + } + + pub fn hvsocket(endpoint: &str, vm_id: [u8; 16]) -> Self { + Client { protseq: "ncacn_hvsocket".into(), endpoint: endpoint.into(), local: false, pid: 0, principal: String::new(), authn_service: RPC_C_AUTHN_NONE, authn_level: RPC_C_AUTHN_LEVEL_NONE, client_id: vm_id.to_vec(), object: [0; 16] } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Server(usize), + Call(u64), +} + +struct Subscription { + kind: u32, + info: [usize; 4], +} + +struct Call { + client: Client, + iface: [u8; 16], + opnum: u16, + status: u32, + async_state: usize, + reply: Option>, + subs: HashMap, + queued: u32, +} + +#[derive(Default)] +struct State { + endpoints: Vec, + auth: Vec, + interfaces: Vec, + handles: HashMap, + calls: HashMap, + vectors: HashSet, + strings: HashSet, + next_call: u64, + next_dynamic: u32, +} + +struct Shared { + state: Mutex, + idle: Condvar, +} + +fn shared() -> &'static Shared { + static S: OnceLock = OnceLock::new(); + S.get_or_init(|| Shared { state: Mutex::new(State::default()), idle: Condvar::new() }) +} + +fn lock() -> MutexGuard<'static, State> { + shared().state.lock().unwrap_or_else(|e| e.into_inner()) +} + +thread_local! { + static CURRENT: Cell = const { Cell::new(0) }; +} + +pub fn endpoints() -> Vec { + lock().endpoints.clone() +} + +pub fn auth_info() -> Vec { + lock().auth.clone() +} + +pub fn interfaces() -> Vec { + lock().interfaces.clone() +} + +pub fn reset() { + let mut s = lock(); + for (&h, _) in s.handles.iter() { + unsafe { drop(Box::from_raw(h as *mut [u64; 2])) }; + } + *s = State::default(); +} + +fn known_protseq(p: &str) -> bool { + ["ncalrpc", "ncacn_ip_tcp", "ncacn_np", "ncacn_http", "ncadg_ip_udp", "ncacn_hvsocket"].iter().any(|k| k.eq_ignore_ascii_case(p)) +} + +fn in_process(p: &str) -> bool { + p.eq_ignore_ascii_case("ncalrpc") || p.eq_ignore_ascii_case("ncacn_hvsocket") +} + +fn protseq_id(p: &str) -> u32 { + if p.eq_ignore_ascii_case("ncalrpc") { + RPC_PROTSEQ_LRPC + } else { + RPC_PROTSEQ_HVSOCKET + } +} + +fn new_handle(s: &mut State, k: Kind) -> usize { + let h = Box::into_raw(Box::new([HANDLE_MAGIC, 0u64])) as usize; + s.handles.insert(h, k); + h +} + +pub fn kind_of(h: usize) -> Option { + if h == 0 { + return None; + } + lock().handles.get(&h).copied() +} + +pub fn is_ours(h: usize) -> bool { + kind_of(h).is_some() +} + +pub fn listen(protseq: &str, max_calls: u32, endpoint: Option<&str>, security: usize) -> i32 { + if !known_protseq(protseq) { + return RPC_S_INVALID_RPC_PROTSEQ; + } + if !in_process(protseq) { + return RPC_S_PROTSEQ_NOT_SUPPORTED; + } + let mut s = lock(); + match endpoint { + None => { + if s.endpoints.iter().any(|e| e.dynamic && e.protseq.eq_ignore_ascii_case(protseq)) { + return RPC_S_OK; + } + if protseq.eq_ignore_ascii_case("ncacn_hvsocket") { + return RPC_S_INVALID_ENDPOINT_FORMAT; + } + let ep = if s.next_dynamic == 0 { crate::rpc::dynamic_endpoint() } else { format!("{}{}", crate::rpc::dynamic_endpoint(), s.next_dynamic) }; + s.next_dynamic += 1; + s.endpoints.push(Endpoint { protseq: protseq.to_ascii_lowercase(), endpoint: ep, max_calls, dynamic: true, security }); + RPC_S_OK + } + Some(ep) => { + if ep.is_empty() { + return RPC_S_INVALID_ENDPOINT_FORMAT; + } + if s.endpoints.iter().any(|e| e.protseq.eq_ignore_ascii_case(protseq) && e.endpoint.eq_ignore_ascii_case(ep)) { + return RPC_S_DUPLICATE_ENDPOINT; + } + s.endpoints.push(Endpoint { protseq: protseq.to_ascii_lowercase(), endpoint: ep.to_string(), max_calls, dynamic: false, security }); + RPC_S_OK + } + } +} + +pub unsafe extern "system" fn rpc_server_use_protseq_w(protseq: *const u16, max: u32, sd: *mut c_void) -> i32 { + if protseq.is_null() { + return RPC_S_INVALID_RPC_PROTSEQ; + } + listen(&from_ptr(protseq), max, None, sd as usize) +} + +pub unsafe extern "system" fn rpc_server_use_protseq_ep_w(protseq: *const u16, max: u32, ep: *const u16, sd: *mut c_void) -> i32 { + if protseq.is_null() { + return RPC_S_INVALID_RPC_PROTSEQ; + } + if ep.is_null() { + return RPC_S_INVALID_ENDPOINT_FORMAT; + } + listen(&from_ptr(protseq), max, Some(&from_ptr(ep)), sd as usize) +} + +fn known_authn(svc: u32) -> bool { + matches!(svc, RPC_C_AUTHN_GSS_NEGOTIATE | RPC_C_AUTHN_WINNT | RPC_C_AUTHN_GSS_SCHANNEL | RPC_C_AUTHN_GSS_KERBEROS | RPC_C_AUTHN_DEFAULT) +} + +unsafe fn alloc_string(s: &str) -> *mut u16 { + let w = wide(s); + let p = HeapAlloc(GetProcessHeap(), 0, w.len() * 2) as *mut u16; + if p.is_null() { + return p; + } + core::ptr::copy_nonoverlapping(w.as_ptr(), p, w.len()); + lock().strings.insert(p as usize); + p +} + +pub fn owns_string(p: usize) -> bool { + lock().strings.contains(&p) +} + +pub unsafe extern "system" fn rpc_server_inq_default_princ_name_w(svc: u32, out: *mut *mut u16) -> i32 { + if out.is_null() { + return RPC_S_INVALID_ARG; + } + if !known_authn(svc) || svc == RPC_C_AUTHN_DEFAULT { + return RPC_S_UNKNOWN_AUTHN_SERVICE; + } + let p = alloc_string(DEFAULT_PRINCIPAL); + if p.is_null() { + return RPC_S_OUT_OF_MEMORY; + } + *out = p; + RPC_S_OK +} + +pub unsafe extern "system" fn rpc_server_register_auth_info_w(principal: *const u16, svc: u32, get_key: *const c_void, arg: *mut c_void) -> i32 { + if !known_authn(svc) { + return RPC_S_UNKNOWN_AUTHN_SERVICE; + } + let mut s = lock(); + let a = AuthInfo { principal: from_ptr(principal), service: svc, get_key: get_key as usize, arg: arg as usize }; + s.auth.retain(|x| x.service != svc); + s.auth.push(a); + RPC_S_OK +} + +unsafe fn guid_at(p: *const u8) -> [u8; 16] { + let mut g = [0u8; 16]; + if !p.is_null() { + core::ptr::copy_nonoverlapping(p, g.as_mut_ptr(), 16); + } + g +} + +pub unsafe fn interface_id(ifspec: usize) -> ([u8; 16], u16, u16) { + let p = ifspec as *const u8; + (guid_at(p.add(4)), (p.add(20) as *const u16).read_unaligned(), (p.add(22) as *const u16).read_unaligned()) +} + +unsafe fn default_epv(ifspec: usize) -> usize { + ((ifspec + 72) as *const usize).read_unaligned() +} + +unsafe fn interpreter_info(ifspec: usize) -> usize { + ((ifspec + 80) as *const usize).read_unaligned() +} + +#[allow(clippy::too_many_arguments)] +pub unsafe fn register_interface(ifspec: usize, mgr_type: *const u8, mgr_epv: usize, flags: u32, max_calls: u32, max_rpc_size: u32, callback: usize, security: usize) -> i32 { + if ifspec == 0 { + return RPC_S_INVALID_ARG; + } + let (uuid, major, minor) = interface_id(ifspec); + let mt = guid_at(mgr_type); + let epv = if mgr_epv != 0 { mgr_epv } else { default_epv(ifspec) }; + let mut s = lock(); + if s.interfaces.iter().any(|i| i.uuid == uuid && i.major == major && i.mgr_type == mt) { + return RPC_S_TYPE_ALREADY_REGISTERED; + } + s.interfaces.push(Interface { ifspec, uuid, major, minor, mgr_type: mt, epv, flags, max_calls, max_rpc_size, callback, security, active: 0 }); + RPC_S_OK +} + +pub unsafe extern "system" fn rpc_server_register_if(ifspec: *const c_void, mgr_type: *const u8, epv: *const c_void) -> i32 { + register_interface(ifspec as usize, mgr_type, epv as usize, 0, 1234, u32::MAX, 0, 0) +} + +pub unsafe extern "system" fn rpc_server_register_if_ex(ifspec: *const c_void, mgr_type: *const u8, epv: *const c_void, flags: u32, max_calls: u32, callback: *const c_void) -> i32 { + register_interface(ifspec as usize, mgr_type, epv as usize, flags, max_calls, u32::MAX, callback as usize, 0) +} + +pub unsafe extern "system" fn rpc_server_register_if2(ifspec: *const c_void, mgr_type: *const u8, epv: *const c_void, flags: u32, max_calls: u32, max_size: u32, callback: *const c_void) -> i32 { + register_interface(ifspec as usize, mgr_type, epv as usize, flags, max_calls, max_size, callback as usize, 0) +} + +#[allow(clippy::too_many_arguments)] +pub unsafe extern "system" fn rpc_server_register_if3(ifspec: *const c_void, mgr_type: *const u8, epv: *const c_void, flags: u32, max_calls: u32, max_size: u32, callback: *const c_void, sd: *mut c_void) -> i32 { + register_interface(ifspec as usize, mgr_type, epv as usize, flags, max_calls, max_size, callback as usize, sd as usize) +} + +pub unsafe extern "system" fn rpc_server_unregister_if(ifspec: *const c_void, mgr_type: *const u8, wait: u32) -> i32 { + let target = if ifspec.is_null() { None } else { Some(interface_id(ifspec as usize)) }; + let mt = if mgr_type.is_null() { None } else { Some(guid_at(mgr_type)) }; + let hit = |i: &Interface| target.map(|(u, ma, _)| i.uuid == u && i.major == ma).unwrap_or(true) && mt.map(|m| i.mgr_type == m).unwrap_or(true); + let mut s = lock(); + if target.is_some() && !s.interfaces.iter().any(|i| hit(i)) { + return RPC_S_UNKNOWN_IF; + } + if wait != 0 { + while s.interfaces.iter().any(|i| hit(i) && i.active > 0) { + s = shared().idle.wait(s).unwrap_or_else(|e| e.into_inner()); + } + } + s.interfaces.retain(|i| !hit(i)); + RPC_S_OK +} + +pub unsafe extern "system" fn rpc_server_inq_bindings(out: *mut *mut u8) -> i32 { + if out.is_null() { + return RPC_S_INVALID_ARG; + } + let mut s = lock(); + let n = s.endpoints.len(); + if n == 0 { + *out = core::ptr::null_mut(); + return RPC_S_NO_BINDINGS; + } + let v = HeapAlloc(GetProcessHeap(), 8, 8 + n * 8) as *mut u8; + if v.is_null() { + return RPC_S_OUT_OF_MEMORY; + } + (v as *mut u32).write_unaligned(n as u32); + for i in 0..n { + let h = new_handle(&mut s, Kind::Server(i)); + (v.add(8 + i * 8) as *mut usize).write_unaligned(h); + } + s.vectors.insert(v as usize); + *out = v; + RPC_S_OK +} + +pub unsafe extern "system" fn rpc_binding_vector_free(v: *mut *mut u8) -> i32 { + if v.is_null() || (*v).is_null() { + return RPC_S_INVALID_ARG; + } + let p = *v; + let mut s = lock(); + if !s.vectors.remove(&(p as usize)) { + drop(s); + return RpcBindingVectorFree(v as *mut *mut c_void); + } + let n = (p as *const u32).read_unaligned() as usize; + for i in 0..n { + let h = (p.add(8 + i * 8) as *const usize).read_unaligned(); + if s.handles.remove(&h).is_some() { + drop(Box::from_raw(h as *mut [u64; 2])); + } + } + HeapFree(GetProcessHeap(), 0, p as *mut c_void); + *v = core::ptr::null_mut(); + RPC_S_OK +} + +pub fn binding_parts(h: usize) -> Option<(String, String, [u8; 16])> { + let s = lock(); + match s.handles.get(&h)? { + Kind::Server(i) => s.endpoints.get(*i).map(|e| (e.protseq.clone(), e.endpoint.clone(), [0u8; 16])), + Kind::Call(c) => s.calls.get(c).map(|c| (c.client.protseq.clone(), c.client.endpoint.clone(), c.client.object)), + } +} + +unsafe fn uuid_text(u: &[u8; 16]) -> String { + let mut p: *mut u16 = core::ptr::null_mut(); + if UuidToStringW(u, &mut p) != RPC_S_OK { + return String::new(); + } + let t = from_ptr(p); + RpcStringFreeW(&mut p); + t +} + +pub unsafe fn string_binding(h: usize) -> Option { + let (ps, ep, obj) = binding_parts(h)?; + let o = if obj == [0u8; 16] { String::new() } else { format!("{}@", uuid_text(&obj)) }; + Some(format!("{o}{ps}:[{ep}]")) +} + +pub unsafe extern "system" fn rpc_binding_to_string_binding_w(b: *mut c_void, out: *mut *mut u16) -> i32 { + if !is_ours(b as usize) { + return RpcBindingToStringBindingW(b, out); + } + if out.is_null() { + return RPC_S_INVALID_ARG; + } + match string_binding(b as usize) { + Some(t) => { + let p = alloc_string(&t); + if p.is_null() { + return RPC_S_OUT_OF_MEMORY; + } + *out = p; + RPC_S_OK + } + None => RPC_S_INVALID_BINDING, + } +} + +pub unsafe extern "system" fn rpc_string_free_w(s: *mut *mut u16) -> i32 { + if s.is_null() { + return RPC_S_INVALID_ARG; + } + let p = *s as usize; + if p != 0 && lock().strings.remove(&p) { + HeapFree(GetProcessHeap(), 0, p as *mut c_void); + *s = core::ptr::null_mut(); + return RPC_S_OK; + } + RpcStringFreeW(s) +} + +fn call_of(s: &State, b: usize) -> Result { + let h = if b == 0 { CURRENT.with(|c| c.get()) } else { b }; + if h == 0 { + return Err(RPC_S_NO_CALL_ACTIVE); + } + match s.handles.get(&h) { + Some(Kind::Call(c)) if s.calls.contains_key(c) => Ok(*c), + _ if b == 0 => Err(RPC_S_NO_CALL_ACTIVE), + _ => Err(RPC_S_INVALID_BINDING), + } +} + +pub fn current_call() -> usize { + CURRENT.with(|c| c.get()) +} + +unsafe fn put_name(base: *mut u8, len_off: usize, ptr_off: usize, name: &str) -> bool { + let w = wide(name); + let need = (w.len() * 2) as u32; + let lp = base.add(len_off) as *mut u32; + let have = lp.read_unaligned(); + let dst = (base.add(ptr_off) as *const *mut u16).read_unaligned(); + lp.write_unaligned(need); + if dst.is_null() || have < need { + return dst.is_null() && have == 0; + } + core::ptr::copy_nonoverlapping(w.as_ptr(), dst, w.len()); + true +} + +pub unsafe extern "system" fn rpc_server_inq_call_attributes_w(b: *mut c_void, attrs: *mut u8) -> i32 { + if attrs.is_null() { + return RPC_S_INVALID_ARG; + } + let version = (attrs as *const u32).read_unaligned(); + if !(1..=3).contains(&version) { + return RPC_S_INVALID_ARG; + } + let s = lock(); + let id = match call_of(&s, b as usize) { + Ok(c) => c, + Err(e) => return e, + }; + let c = &s.calls[&id]; + let flags = (attrs.add(4) as *const u32).read_unaligned(); + let server_principal = s.auth.iter().find(|a| a.service == c.client.authn_service).map(|a| a.principal.clone()).unwrap_or_default(); + let mut more = false; + if flags & RPC_QUERY_SERVER_PRINCIPAL_NAME != 0 && !put_name(attrs, 8, 0x10, &server_principal) { + more = true; + } + if flags & RPC_QUERY_CLIENT_PRINCIPAL_NAME != 0 && !put_name(attrs, 0x18, 0x20, &c.client.principal) { + more = true; + } + let wr = |o: usize, v: u32| (attrs.add(o) as *mut u32).write_unaligned(v); + wr(0x28, c.client.authn_level); + wr(0x2c, c.client.authn_service); + wr(0x30, (c.client.authn_level == RPC_C_AUTHN_LEVEL_NONE) as u32); + if version >= 2 { + wr(0x34, 0); + wr(0x38, protseq_id(&c.client.protseq)); + if flags & RPC_QUERY_IS_CLIENT_LOCAL != 0 { + wr(0x3c, if c.client.local { RCCL_LOCAL } else { RCCL_REMOTE }); + } + if flags & RPC_QUERY_CLIENT_PID != 0 { + (attrs.add(0x40) as *mut usize).write_unaligned(c.client.pid as usize); + } + wr(0x48, c.status); + wr(0x4c, RCT_NORMAL); + (attrs.add(0x58) as *mut u16).write_unaligned(c.opnum); + core::ptr::copy_nonoverlapping(c.iface.as_ptr(), attrs.add(0x5c), 16); + } + if version >= 3 && flags & RPC_QUERY_CLIENT_ID != 0 { + let lp = attrs.add(0x6c) as *mut u32; + let have = lp.read_unaligned() as usize; + let dst = (attrs.add(0x70) as *const *mut u8).read_unaligned(); + lp.write_unaligned(c.client.client_id.len() as u32); + if have < c.client.client_id.len() || (dst.is_null() && !c.client.client_id.is_empty()) { + more = true; + } else if !c.client.client_id.is_empty() { + core::ptr::copy_nonoverlapping(c.client.client_id.as_ptr(), dst, c.client.client_id.len()); + } + } + if more { + ERROR_MORE_DATA + } else { + RPC_S_OK + } +} + +pub unsafe extern "system" fn rpc_server_test_cancel(b: *mut c_void) -> i32 { + let s = lock(); + match call_of(&s, b as usize) { + Err(e) => e, + Ok(c) if s.calls[&c].status == RPC_CALL_STATUS_CANCELLED => RPC_S_OK, + Ok(_) => RPC_S_CALL_IN_PROGRESS, + } +} + +pub unsafe extern "system" fn rpc_server_subscribe_for_notification(b: *mut c_void, notification: u32, kind: u32, info: *const usize) -> i32 { + if !(RPC_NOTIFICATION_CLIENT_DISCONNECT..=RPC_NOTIFICATION_CALL_CANCEL).contains(¬ification) || !(1..=5).contains(&kind) || info.is_null() { + return RPC_S_INVALID_ARG; + } + let mut s = lock(); + let id = match call_of(&s, b as usize) { + Ok(c) => c, + Err(e) => return e, + }; + let mut i = [0usize; 4]; + core::ptr::copy_nonoverlapping(info, i.as_mut_ptr(), 4); + s.calls.get_mut(&id).unwrap().subs.insert(notification, Subscription { kind, info: i }); + RPC_S_OK +} + +pub unsafe extern "system" fn rpc_server_unsubscribe_for_notification(b: *mut c_void, notification: u32, queued: *mut u32) -> i32 { + let mut s = lock(); + let id = match call_of(&s, b as usize) { + Ok(c) => c, + Err(e) => return e, + }; + let c = s.calls.get_mut(&id).unwrap(); + if c.subs.remove(¬ification).is_none() { + return RPC_S_INVALID_ARG; + } + if !queued.is_null() { + *queued = c.queued; + } + RPC_S_OK +} + +fn async_call(s: &State, a: usize) -> Option { + if a == 0 { + return None; + } + let rt = unsafe { ((a + 0x20) as *const usize).read_unaligned() }; + match s.handles.get(&rt) { + Some(Kind::Call(c)) if s.calls.get(c).map(|x| x.async_state == a).unwrap_or(false) => Some(*c), + _ => None, + } +} + +pub unsafe extern "system" fn rpc_async_complete_call(a: *mut c_void, reply: *mut c_void) -> i32 { + let mut s = lock(); + let Some(id) = async_call(&s, a as usize) else { + drop(s); + return RpcAsyncCompleteCall(a, reply); + }; + let c = s.calls.get_mut(&id).unwrap(); + if c.reply.is_some() { + return RPC_S_INVALID_ASYNC_HANDLE; + } + let v = if reply.is_null() { 0 } else { (reply as *const u32).read_unaligned() }; + c.reply = Some(Ok(v)); + shared().idle.notify_all(); + RPC_S_OK +} + +pub unsafe extern "system" fn rpc_async_abort_call(a: *mut c_void, code: u32) -> i32 { + let mut s = lock(); + let Some(id) = async_call(&s, a as usize) else { + drop(s); + return RpcAsyncAbortCall(a, code); + }; + let c = s.calls.get_mut(&id).unwrap(); + if c.reply.is_some() { + return RPC_S_INVALID_ASYNC_HANDLE; + } + c.reply = Some(Err(code)); + shared().idle.notify_all(); + RPC_S_OK +} + +pub struct Dispatch { + pub routine: usize, + pub call: usize, + pub ifspec: usize, +} + +fn begin(iface: &[u8; 16], major: u16, opnum: u16, client: &Client, is_async: bool) -> Result<(Dispatch, u64, usize), i32> { + let mut s = lock(); + if !s.endpoints.iter().any(|e| e.protseq.eq_ignore_ascii_case(&client.protseq) && e.endpoint.eq_ignore_ascii_case(&client.endpoint)) { + return Err(RPC_S_INVALID_BINDING); + } + let Some(ix) = s.interfaces.iter().position(|i| &i.uuid == iface && i.major == major && (i.mgr_type == client.object || i.mgr_type == [0u8; 16])) else { + return Err(RPC_S_UNKNOWN_IF); + }; + let i = s.interfaces[ix].clone(); + if i.flags & RPC_IF_ALLOW_LOCAL_ONLY != 0 && !client.local { + return Err(RPC_S_ACCESS_DENIED); + } + if i.flags & RPC_IF_ALLOW_SECURE_ONLY != 0 && client.authn_level <= RPC_C_AUTHN_LEVEL_NONE { + return Err(RPC_S_ACCESS_DENIED); + } + if i.active >= i.max_calls.max(1) { + return Err(RPC_S_SERVER_TOO_BUSY); + } + let routine = unsafe { + if i.epv != 0 { + ((i.epv + opnum as usize * 8) as *const usize).read_unaligned() + } else { + let info = interpreter_info(i.ifspec); + if info == 0 { + return Err(RPC_S_PROCNUM_OUT_OF_RANGE); + } + let table = ((info + 8) as *const usize).read_unaligned(); + ((table + opnum as usize * 8) as *const usize).read_unaligned() + } + }; + if routine == 0 { + return Err(RPC_S_PROCNUM_OUT_OF_RANGE); + } + s.next_call += 1; + let id = s.next_call; + let h = new_handle(&mut s, Kind::Call(id)); + let a = if is_async { + let st = Box::into_raw(Box::new([0u8; RPC_ASYNC_STATE_SIZE as usize])) as *mut u8; + unsafe { + (st as *mut u32).write_unaligned(RPC_ASYNC_STATE_SIZE); + (st.add(4) as *mut u32).write_unaligned(RPC_ASYNC_SIGNATURE); + (st.add(0x20) as *mut usize).write_unaligned(h); + } + st as usize + } else { + 0 + }; + s.calls.insert(id, Call { client: client.clone(), iface: *iface, opnum, status: RPC_CALL_STATUS_IN_PROGRESS, async_state: a, reply: None, subs: HashMap::new(), queued: 0 }); + s.interfaces[ix].active += 1; + Ok((Dispatch { routine, call: h, ifspec: i.ifspec }, id, i.callback)) +} + +fn finish(id: u64, h: usize, iface: &[u8; 16], major: u16) { + let mut s = lock(); + if let Some(c) = s.calls.remove(&id) { + if c.async_state != 0 { + unsafe { drop(Box::from_raw(c.async_state as *mut [u8; RPC_ASYNC_STATE_SIZE as usize])) }; + } + } + if s.handles.remove(&h).is_some() { + unsafe { drop(Box::from_raw(h as *mut [u64; 2])) }; + } + if let Some(i) = s.interfaces.iter_mut().find(|i| &i.uuid == iface && i.major == major && i.active > 0) { + i.active -= 1; + } + drop(s); + shared().idle.notify_all(); +} + +unsafe fn security_check(callback: usize, ifspec: usize, call: usize) -> i32 { + if callback == 0 { + return RPC_S_OK; + } + let f: unsafe extern "system" fn(usize, usize) -> i32 = core::mem::transmute(callback); + let prev = CURRENT.with(|c| c.replace(call)); + let r = f(ifspec, call); + CURRENT.with(|c| c.set(prev)); + if r != RPC_S_OK { + RPC_S_ACCESS_DENIED + } else { + RPC_S_OK + } +} + +pub unsafe fn invoke(iface: &[u8; 16], major: u16, opnum: u16, client: &Client, f: impl FnOnce(&Dispatch) -> R) -> Result { + let (d, id, cb) = begin(iface, major, opnum, client, false)?; + let sec = security_check(cb, d.ifspec, d.call); + if sec != RPC_S_OK { + finish(id, d.call, iface, major); + return Err(sec); + } + let prev = CURRENT.with(|c| c.replace(d.call)); + let r = f(&d); + CURRENT.with(|c| c.set(prev)); + finish(id, d.call, iface, major); + Ok(r) +} + +pub struct AsyncCall { + pub dispatch: Dispatch, + pub state: usize, + id: u64, + iface: [u8; 16], + major: u16, +} + +pub unsafe fn invoke_async(iface: &[u8; 16], major: u16, opnum: u16, client: &Client, f: impl FnOnce(&Dispatch, usize)) -> Result { + let (d, id, cb) = begin(iface, major, opnum, client, true)?; + let sec = security_check(cb, d.ifspec, d.call); + if sec != RPC_S_OK { + finish(id, d.call, iface, major); + return Err(sec); + } + let state = lock().calls[&id].async_state; + let prev = CURRENT.with(|c| c.replace(d.call)); + f(&d, state); + CURRENT.with(|c| c.set(prev)); + Ok(AsyncCall { dispatch: d, state, id, iface: *iface, major }) +} + +impl AsyncCall { + pub fn reply(&self) -> Option> { + lock().calls.get(&self.id).and_then(|c| c.reply) + } + + pub fn wait(self, timeout: std::time::Duration) -> Option> { + let end = std::time::Instant::now() + timeout; + let mut s = lock(); + loop { + if let Some(r) = s.calls.get(&self.id).and_then(|c| c.reply) { + drop(s); + finish(self.id, self.dispatch.call, &self.iface, self.major); + return Some(r); + } + let now = std::time::Instant::now(); + if now >= end { + return None; + } + s = shared().idle.wait_timeout(s, end - now).unwrap_or_else(|e| e.into_inner()).0; + } + } + + pub unsafe fn notify(&self, notification: u32) -> bool { + let mut s = lock(); + let Some(c) = s.calls.get_mut(&self.id) else { return false }; + c.status = if notification == RPC_NOTIFICATION_CALL_CANCEL { RPC_CALL_STATUS_CANCELLED } else { RPC_CALL_STATUS_DISCONNECTED }; + let Some(sub) = c.subs.get(¬ification) else { return false }; + let (kind, info, state) = (sub.kind, sub.info, c.async_state); + c.queued += 1; + drop(s); + match kind { + RPC_NOTIFICATION_TYPE_EVENT => SetEvent(info[0]) != 0, + RPC_NOTIFICATION_TYPE_CALLBACK => { + let f: unsafe extern "system" fn(usize, usize, u32) = core::mem::transmute(info[0]); + f(state, 0, if notification == RPC_NOTIFICATION_CALL_CANCEL { RPC_ASYNC_EVENT_CLIENT_CANCEL } else { RPC_ASYNC_EVENT_CLIENT_DISCONNECT }); + true + } + _ => false, + } + } +} + +pub fn cancel(call: usize) -> bool { + let mut s = lock(); + let Some(Kind::Call(id)) = s.handles.get(&call).copied() else { return false }; + match s.calls.get_mut(&id) { + Some(c) => { + c.status = RPC_CALL_STATUS_CANCELLED; + true + } + None => false, + } +} + +pub fn active_calls(iface: &[u8; 16]) -> u32 { + lock().interfaces.iter().filter(|i| &i.uuid == iface).map(|i| i.active).sum() +} diff --git a/crates/compat/console-sandbox/src/tests.rs b/crates/compat/console-sandbox/src/tests.rs index 6320ec5a..fbef4c90 100644 --- a/crates/compat/console-sandbox/src/tests.rs +++ b/crates/compat/console-sandbox/src/tests.rs @@ -769,6 +769,11 @@ fn host_serves_audio_cursor_and_hdr_classes() { assert_ne!(created, 0, "the new object id sits at env+0x1c"); let mut env = vec![0u8; AUDIO_ENVELOPE as usize]; env[8..12].copy_from_slice(&0x64u32.to_le_bytes()); + env[0xc..0x10].copy_from_slice(&created.to_le_bytes()); + assert_eq!(call(a, AUDIO_ENVELOPE, env.as_mut_ptr()), S_OK); + assert_eq!(i32::from_le_bytes(env[4..8].try_into().unwrap()), E_INVALIDARG, "0x64 on an object that is not a 0x61 MediaManager is refused"); + let mut env = vec![0u8; AUDIO_ENVELOPE as usize]; + env[8..12].copy_from_slice(&0xfffu32.to_le_bytes()); assert_eq!(call(a, AUDIO_ENVELOPE, env.as_mut_ptr()), S_OK); assert_eq!(i32::from_le_bytes(env[4..8].try_into().unwrap()), E_NOTIMPL, "ids with no decoded layout report E_NOTIMPL in the envelope"); let mut env = vec![0u8; AUDIO_ENVELOPE as usize]; @@ -939,6 +944,10 @@ fn host_serves_package_v7_and_net_security_classes() { let t = compat_common::gdk::title(); assert_eq!(d.version, [t.version[3], t.version[2], t.version[1], t.version[0]], "PkgDetails +0x10 is rev, build, minor, major"); assert_eq!(String::from_utf16_lossy(&hstring_units(d.display)), t.display); + let sid = String::from_utf16_lossy(&hstring_units(d.store_id)); + assert_eq!(sid, compat_common::gdk::store::game_store_id(), "PkgDetails +0x38 carries the MicrosoftGame.config StoreId"); + assert_eq!(alias_identity(0, &sid), Some(compat_common::gdk::package::package_id()), "the kind-0 alias the client learns from +0x38 resolves back through slot 7/16"); + assert!(d.alias.is_null() && d.alias4.is_null(), "kind-1 and kind-4 aliases have no source in any dump"); let enumerate: unsafe extern "system" fn(*mut c_void, *const u16, i32, i32, *mut u32, *mut *mut PkgDetails) -> i32 = core::mem::transmute(slot(v7, 28)); let (mut n, mut arr) = (9u32, core::ptr::null_mut()); assert_eq!(enumerate(v7, core::ptr::null(), 0, 0, &mut n, &mut arr), S_OK); @@ -946,8 +955,28 @@ fn host_serves_package_v7_and_net_security_classes() { assert_eq!(String::from_utf16_lossy(&hstring_units((*arr).id)), compat_common::gdk::package::package_id()); assert_eq!(enumerate(v7, core::ptr::null(), 1, 0, &mut n, &mut arr), S_OK); assert_eq!((n, arr.is_null()), (0, true), "no content packages are installed"); - let undecoded: unsafe extern "system" fn(*mut c_void) -> i32 = core::mem::transmute(slot(v7, 7)); - assert_eq!(undecoded(v7), E_NOTIMPL, "undecoded slots fail per call, never with a retryable RPC code"); + let alias: unsafe extern "system" fn(*mut c_void, i32, *const u16, *mut *mut c_void) -> i32 = core::mem::transmute(slot(v7, 7)); + let store_id: Vec = compat_common::gdk::store::game_store_id().encode_utf16().chain(Some(0)).collect(); + let mut ah = 1usize as *mut c_void; + assert_eq!(alias(v7, 0, store_id.as_ptr(), &mut ah), S_OK); + assert_eq!(String::from_utf16_lossy(&hstring_units(ah)), compat_common::gdk::package::package_id(), "a kind 0 store id alias resolves to the package identifier"); + for (kind, id) in [(0, other.as_ptr()), (1, store_id.as_ptr()), (2, store_id.as_ptr()), (1, pkg.as_ptr()), (0, core::ptr::null())] { + let mut ah = 1usize as *mut c_void; + assert_eq!(alias(v7, kind, id, &mut ah), compat_common::gdk::E_NOT_FOUND, "kind {kind}: the client moves on to the next alias kind only on E_NOT_FOUND"); + assert!(ah.is_null()); + } + assert_eq!(alias(v7, 0, store_id.as_ptr(), core::ptr::null_mut()), E_POINTER); + let legacy: unsafe extern "system" fn(*mut c_void, *const u16, *mut *mut c_void) -> i32 = core::mem::transmute(slot(v7, 19)); + let mut fh = 1usize as *mut c_void; + assert_eq!(legacy(v7, pkg.as_ptr(), &mut fh), S_OK); + assert_eq!(hstring_units(fh), features_record(compat_common::gdk::package::features()), "slot 19 returns the slot 26 feature records"); + assert_eq!(legacy(v7, other.as_ptr(), &mut fh), compat_common::gdk::E_NOT_FOUND); + assert!(fh.is_null()); + assert_eq!(legacy(v7, pkg.as_ptr(), core::ptr::null_mut()), E_POINTER); + for s in [17usize, 18, 24, 25] { + let undecoded: unsafe extern "system" fn(*mut c_void) -> i32 = core::mem::transmute(slot(v7, s)); + assert_eq!(undecoded(v7), E_NOTIMPL, "slot {s} has no console caller; it fails per call, never with a retryable RPC code"); + } let state: unsafe extern "system" fn(*mut c_void, *const u16, *mut StateRec) -> i32 = core::mem::transmute(slot(v7, 3)); let mut st = StateRec { a: 9, b: 9, selection: 1usize as *mut c_void }; assert_eq!(state(v7, pkg.as_ptr(), &mut st), S_OK); diff --git a/crates/compat/console-sandbox/src/wasapi.rs b/crates/compat/console-sandbox/src/wasapi.rs index 022b970d..2d49294e 100644 --- a/crates/compat/console-sandbox/src/wasapi.rs +++ b/crates/compat/console-sandbox/src/wasapi.rs @@ -17,6 +17,9 @@ const IID_IAUDIO_SESSION_CONTROL2: Guid = Guid { data1: 0xBFB7FF88, data2: 0x723 const IID_ISPATIAL_AUDIO_CLIENT: Guid = Guid { data1: 0xBBF8E066, data2: 0xAAAA, data3: 0x49BE, data4: [0x9A, 0x4D, 0xFD, 0x2A, 0x85, 0x8E, 0xA2, 0x7F] }; const IID_ISPATIAL_AUDIO_CLIENT2: Guid = Guid { data1: 0xCAABE452, data2: 0xA66A, data3: 0x4BEE, data4: [0xA9, 0x3E, 0xE3, 0x20, 0x46, 0x3F, 0x6A, 0x53] }; const IID_IAUDIO_CLOCK: Guid = Guid { data1: 0xCD63314F, data2: 0x3FBA, data3: 0x4A1B, data4: [0x81, 0x2C, 0xEF, 0x96, 0x35, 0x87, 0x28, 0xE7] }; +const IID_IAUDIO_CAPTURE_CLIENT: Guid = Guid { data1: 0xC8ADBD64, data2: 0xE71E, data3: 0x48A0, data4: [0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17] }; +const IID_IMM_ENDPOINT: Guid = Guid { data1: 0x1BE09788, data2: 0x6894, data3: 0x4089, data4: [0x85, 0x86, 0x9A, 0x2A, 0x6C, 0x26, 0x5A, 0xC5] }; +const IID_CLIENT_ITEM_SERVICE: Guid = Guid { data1: 0xD19F8E95, data2: 0xB126, data3: 0x4446, data4: [0x89, 0x0C, 0x5D, 0xCB, 0x7A, 0xD7, 0x14, 0x53] }; const IID_IAUDIO_CLOCK_ADJUSTMENT: Guid = Guid { data1: 0xF6E4C0A0, data2: 0x46D9, data3: 0x4FB8, data4: [0xBE, 0x21, 0x57, 0xA3, 0xEF, 0x2B, 0x62, 0x6C] }; pub const STREAMFLAGS_RATEADJUST: u32 = 0x0010_0000; pub const AUDIO_CATEGORIES: u32 = 12; @@ -53,6 +56,9 @@ extern "system" { extern "system" { fn SetEvent(h: usize) -> i32; fn Sleep(ms: u32); + fn CreateEventW(a: *mut c_void, manual: i32, initial: i32, name: *const u16) -> usize; + fn CloseHandle(h: usize) -> i32; + fn WaitForSingleObject(h: usize, ms: u32) -> u32; } #[repr(C)] @@ -354,6 +360,7 @@ pub enum Prop { Text(Vec), Dword(u32), Serialized(u16, Vec), + Vector(u16, u32, Vec), } unsafe fn property_store(id: Option<&str>) -> Result { @@ -417,6 +424,43 @@ pub fn property_value(id: Option<&str>, key: &PropertyKey) -> Result { + let p = v.a as *const u8; + Some(Prop::Serialized(72, if p.is_null() { vec![0; 16] } else { core::slice::from_raw_parts(p, 16).to_vec() })) + } + 30 => { + let p = v.a as *const u8; + let mut n = 0; + while !p.is_null() && *p.add(n) != 0 { + n += 1; + } + let mut b = if p.is_null() { Vec::new() } else { core::slice::from_raw_parts(p, n).to_vec() }; + b.push(0); + Some(Prop::Serialized(30, b)) + } + t if t & 0x1000 != 0 => { + let count = v.a as u32; + let p = v.b as *const u8; + match (t & 0xfff, scalar_size(t & 0xfff)) { + (_, Some(n)) => Some(Prop::Vector(t, count, if p.is_null() { Vec::new() } else { core::slice::from_raw_parts(p, n * count as usize).to_vec() })), + (31, None) => { + let mut b = Vec::new(); + for i in 0..count as usize { + let w = *(p as *const *const u16).add(i); + let mut n = 0; + while !w.is_null() && *w.add(n) != 0 { + n += 1; + } + if !w.is_null() { + b.extend(core::slice::from_raw_parts(w, n).iter().flat_map(|c| c.to_le_bytes())); + } + b.extend_from_slice(&[0, 0]); + } + Some(Prop::Vector(t, count, b)) + } + _ => None, + } + } t => scalar_size(t).map(|n| Prop::Serialized(t, v.a.to_le_bytes()[..n].to_vec())), }; PropVariantClear(&mut v); @@ -424,7 +468,138 @@ pub fn property_value(id: Option<&str>, key: &PropertyKey) -> Result, session: &Guid) -> Result { +const IID_IAUDIO_SESSION_MANAGER2: Guid = Guid { data1: 0x77AA99A0, data2: 0x1BD6, data3: 0x484F, data4: [0x8B, 0xC7, 0x2C, 0x65, 0x4C, 0x9A, 0x9B, 0x6F] }; +const IID_ICHANNEL_AUDIO_VOLUME: Guid = Guid { data1: 0x1C158861, data2: 0xB533, data3: 0x4B30, data4: [0xB1, 0xCF, 0xE8, 0x53, 0xE5, 0x1C, 0x59, 0xB8] }; + +pub struct PcSession(usize); + +unsafe impl Send for PcSession {} +unsafe impl Sync for PcSession {} + +impl Drop for PcSession { + fn drop(&mut self) { + unsafe { release(self.0 as *mut c_void) } + } +} + +#[derive(Clone)] +pub enum SessionRef { + Title(Option, Guid), + Pc(Arc), +} + +pub fn session_instance(r: &SessionRef) -> Result { + session_string(r, 13) +} + +pub fn session_enumerate(id: Option<&str>) -> Result>, i32> { + unsafe { + let dev = device(id)?; + let mgr = activate(&dev, &IID_IAUDIO_SESSION_MANAGER2)?; + let mut en = core::ptr::null_mut(); + let hr = slot:: i32>(mgr.0, 5)(mgr.0, &mut en); + if hr < 0 { + return Err(hr); + } + let en = Com(en); + let mut n = 0i32; + let hr = slot:: i32>(en.0, 3)(en.0, &mut n); + if hr < 0 { + return Err(hr); + } + let mut out = Vec::new(); + for i in 0..n.max(0) { + let mut c = core::ptr::null_mut(); + let hr = slot:: i32>(en.0, 4)(en.0, i, &mut c); + if hr < 0 { + return Err(hr); + } + let c = Com(c); + let mut c2 = core::ptr::null_mut(); + let hr = slot:: i32>(c.0, 0)(c.0, &IID_IAUDIO_SESSION_CONTROL2, &mut c2); + if hr < 0 { + return Err(hr); + } + let c2 = PcSession(c2 as usize); + let mut pid = 0u32; + let hr = slot:: i32>(c2.0 as *mut c_void, 14)(c2.0 as *mut c_void, &mut pid); + if hr >= 0 && pid == std::process::id() { + out.push(Arc::new(c2)); + } + } + Ok(out) + } +} + +unsafe fn session_iface(r: &SessionRef, iid: &Guid) -> Result { + let c = session_control(r)?; + let mut v = core::ptr::null_mut(); + let hr = slot:: i32>(c.0, 0)(c.0, iid, &mut v); + if hr < 0 { Err(hr) } else { Ok(Com(v)) } +} + +pub fn session_simple_get(r: &SessionRef) -> Result<(f32, bool), i32> { + unsafe { + let v = session_iface(r, &IID_ISIMPLE_AUDIO_VOLUME)?; + let mut g = 0f32; + let hr = slot:: i32>(v.0, 4)(v.0, &mut g); + if hr < 0 { + return Err(hr); + } + let mut m = 0i32; + let hr = slot:: i32>(v.0, 6)(v.0, &mut m); + if hr < 0 { Err(hr) } else { Ok((g, m != 0)) } + } +} + +pub fn session_simple_set(r: &SessionRef, volume: Option, mute: Option, ctx: &Guid) -> i32 { + unsafe { + let v = match session_iface(r, &IID_ISIMPLE_AUDIO_VOLUME) { + Ok(v) => v, + Err(hr) => return hr, + }; + let mut hr = 0; + if let Some(x) = volume { + hr = slot:: i32>(v.0, 3)(v.0, x, ctx); + } + if let (Some(m), true) = (mute, hr >= 0) { + hr = slot:: i32>(v.0, 5)(v.0, m as i32, ctx); + } + hr + } +} + +pub fn session_channels_get(r: &SessionRef) -> Result, i32> { + unsafe { + let v = session_iface(r, &IID_ICHANNEL_AUDIO_VOLUME)?; + let mut n = 0u32; + let hr = slot:: i32>(v.0, 3)(v.0, &mut n); + if hr < 0 { + return Err(hr); + } + let mut out = vec![0f32; n as usize]; + let hr = slot:: i32>(v.0, 7)(v.0, n, out.as_mut_ptr()); + if hr < 0 { Err(hr) } else { Ok(out) } + } +} + +pub fn session_channels_set(r: &SessionRef, volumes: &[f32], ctx: &Guid) -> i32 { + unsafe { + match session_iface(r, &IID_ICHANNEL_AUDIO_VOLUME) { + Ok(v) => slot:: i32>(v.0, 6)(v.0, volumes.len() as u32, volumes.as_ptr(), ctx), + Err(hr) => hr, + } + } +} + +unsafe fn session_control(r: &SessionRef) -> Result { + let (id, session) = match r { + SessionRef::Title(id, g) => (id.as_deref(), g), + SessionRef::Pc(p) => { + slot:: u32>(p.0 as *mut c_void, 1)(p.0 as *mut c_void); + return Ok(Com(p.0 as *mut c_void)); + } + }; let dev = device(id)?; let mgr = activate(&dev, &IID_IAUDIO_SESSION_MANAGER)?; let mut ctl = core::ptr::null_mut(); @@ -438,18 +613,18 @@ unsafe fn session_control(id: Option<&str>, session: &Guid) -> Result if hr < 0 { Err(hr) } else { Ok(Com(c2)) } } -pub fn session_state(id: Option<&str>, session: &Guid) -> Result { +pub fn session_state(r: &SessionRef) -> Result { unsafe { - let c = session_control(id, session)?; + let c = session_control(r)?; let mut st = 0u32; let hr = slot:: i32>(c.0, 3)(c.0, &mut st); if hr < 0 { Err(hr) } else { Ok(st) } } } -pub fn session_string(id: Option<&str>, session: &Guid, n: usize) -> Result { +pub fn session_string(r: &SessionRef, n: usize) -> Result { unsafe { - let c = session_control(id, session)?; + let c = session_control(r)?; let mut p: *mut u16 = core::ptr::null_mut(); let hr = slot:: i32>(c.0, n)(c.0, &mut p); if hr < 0 { @@ -459,51 +634,182 @@ pub fn session_string(id: Option<&str>, session: &Guid, n: usize) -> Result, session: &Guid, name: &[u16], ctx: &Guid) -> i32 { +pub fn session_set_display_name(r: &SessionRef, name: &[u16], ctx: &Guid) -> i32 { unsafe { - match session_control(id, session) { + match session_control(r) { Ok(c) => slot:: i32>(c.0, 5)(c.0, name.as_ptr(), ctx), Err(hr) => hr, } } } -pub fn session_grouping(id: Option<&str>, session: &Guid) -> Result { +pub fn session_grouping(r: &SessionRef) -> Result { unsafe { - let c = session_control(id, session)?; + let c = session_control(r)?; let mut g = Guid { data1: 0, data2: 0, data3: 0, data4: [0; 8] }; let hr = slot:: i32>(c.0, 8)(c.0, &mut g); if hr < 0 { Err(hr) } else { Ok(g) } } } -pub fn session_set_grouping(id: Option<&str>, session: &Guid, g: &Guid, ctx: &Guid) -> i32 { +pub fn session_set_grouping(r: &SessionRef, g: &Guid, ctx: &Guid) -> i32 { unsafe { - match session_control(id, session) { + match session_control(r) { Ok(c) => slot:: i32>(c.0, 9)(c.0, g, ctx), Err(hr) => hr, } } } -pub fn session_is_system_sounds(id: Option<&str>, session: &Guid) -> i32 { +pub fn session_is_system_sounds(r: &SessionRef) -> i32 { unsafe { - match session_control(id, session) { + match session_control(r) { Ok(c) => slot:: i32>(c.0, 15)(c.0), Err(hr) => hr, } } } -pub fn session_set_ducking(id: Option<&str>, session: &Guid, opt_out: bool) -> i32 { +pub fn session_set_ducking(r: &SessionRef, opt_out: bool) -> i32 { unsafe { - match session_control(id, session) { + match session_control(r) { Ok(c) => slot:: i32>(c.0, 16)(c.0, opt_out as i32), Err(hr) => hr, } } } +pub const SESSION_NOT_FOUND: i32 = 0x8007_0002u32 as i32; +pub const SESSION_KEY_INVALID: i32 = 0x8000_4005u32 as i32; + +pub fn session_existing(id: Option<&str>, instance: &str) -> Result, i32> { + if instance.is_empty() { + return Err(SESSION_KEY_INVALID); + } + for p in session_enumerate(id)? { + let r = SessionRef::Pc(p.clone()); + if session_instance(&r)?.eq_ignore_ascii_case(instance) { + return Ok(p); + } + } + Err(SESSION_NOT_FOUND) +} + +#[link(name = "runtimeobject")] +extern "system" { + fn RoGetActivationFactory(id: *mut c_void, iid: *const Guid, out: *mut *mut c_void) -> i32; + fn WindowsCreateString(s: *const u16, len: u32, out: *mut *mut c_void) -> i32; + fn WindowsDeleteString(h: *mut c_void) -> i32; +} + +pub const MEDIA_MANAGER_CLASS: &str = "Windows.Media.Internal.MediaManager"; +pub const IID_MEDIA_MANAGER_STATICS: Guid = Guid { data1: 0xD6F7BE30, data2: 0x77CD, data3: 0x4139, data4: [0x96, 0xD0, 0xC7, 0xA2, 0x69, 0xBD, 0xCE, 0x79] }; +pub const IID_EVENT_HANDLER_OBJECT: Guid = Guid { data1: 0xC50898F6, data2: 0xC536, data3: 0x5F47, data4: [0x85, 0x83, 0x8B, 0x2C, 0x24, 0x38, 0xA1, 0x3B] }; +pub const MEDIA_ADD_HANDLER: usize = 6; +pub const MEDIA_REMOVE_HANDLER: usize = 7; +pub const MEDIA_PLAY_TO_STREAM_STATE: usize = 8; +pub const MEDIA_CASTING_APP_STATE: usize = 9; +pub const MEDIA_VOIP_CALL_STATE: usize = 10; + +#[repr(C)] +struct Handler { + vtbl: *const HandlerVtbl, + refs: AtomicU32, +} + +#[repr(C)] +struct HandlerVtbl { + query: unsafe extern "system" fn(*mut Handler, *const Guid, *mut *mut c_void) -> i32, + add_ref: unsafe extern "system" fn(*mut Handler) -> u32, + release: unsafe extern "system" fn(*mut Handler) -> u32, + invoke: unsafe extern "system" fn(*mut Handler, *mut c_void, *mut c_void) -> i32, +} + +pub static HANDLER_INVOKES: AtomicU32 = AtomicU32::new(0); +pub static HANDLER_LIVE: AtomicU32 = AtomicU32::new(0); + +unsafe extern "system" fn handler_query(h: *mut Handler, iid: *const Guid, out: *mut *mut c_void) -> i32 { + if out.is_null() { + return 0x8000_4003u32 as i32; + } + if *iid == IID_IUNKNOWN || *iid == IID_EVENT_HANDLER_OBJECT { + handler_add_ref(h); + *out = h as *mut c_void; + 0 + } else { + *out = core::ptr::null_mut(); + E_NOINTERFACE + } +} + +unsafe extern "system" fn handler_add_ref(h: *mut Handler) -> u32 { + (*h).refs.fetch_add(1, Ordering::SeqCst) + 1 +} + +unsafe extern "system" fn handler_release(h: *mut Handler) -> u32 { + let n = (*h).refs.fetch_sub(1, Ordering::SeqCst) - 1; + if n == 0 { + drop(Box::from_raw(h)); + HANDLER_LIVE.fetch_sub(1, Ordering::SeqCst); + } + n +} + +unsafe extern "system" fn handler_invoke(_h: *mut Handler, _sender: *mut c_void, _args: *mut c_void) -> i32 { + HANDLER_INVOKES.fetch_add(1, Ordering::SeqCst); + 0 +} + +static HANDLER_VTBL: HandlerVtbl = HandlerVtbl { query: handler_query, add_ref: handler_add_ref, release: handler_release, invoke: handler_invoke }; + +pub struct MediaManager(usize); + +unsafe impl Send for MediaManager {} +unsafe impl Sync for MediaManager {} + +impl Drop for MediaManager { + fn drop(&mut self) { + unsafe { release(self.0 as *mut c_void) } + } +} + +pub fn media_manager() -> Result { + unsafe { + CoInitializeEx(core::ptr::null_mut(), 0); + let name: Vec = MEDIA_MANAGER_CLASS.encode_utf16().collect(); + let mut h = core::ptr::null_mut(); + let hr = WindowsCreateString(name.as_ptr(), name.len() as u32, &mut h); + if hr < 0 { + return Err(hr); + } + let mut f = core::ptr::null_mut(); + let hr = RoGetActivationFactory(h, &IID_MEDIA_MANAGER_STATICS, &mut f); + WindowsDeleteString(h); + if hr < 0 { Err(hr) } else { Ok(MediaManager(f as usize)) } + } +} + +impl MediaManager { + pub fn state_changed(&self, method: usize, value: u32) -> i32 { + unsafe { slot:: i32>(self.0 as *mut c_void, method)(self.0 as *mut c_void, value) } + } + + pub fn add_handler(&self) -> Result { + unsafe { + let h = Box::into_raw(Box::new(Handler { vtbl: &HANDLER_VTBL, refs: AtomicU32::new(1) })); + HANDLER_LIVE.fetch_add(1, Ordering::SeqCst); + let mut token = 0i64; + let hr = slot:: i32>(self.0 as *mut c_void, MEDIA_ADD_HANDLER)(self.0 as *mut c_void, h as *mut c_void, &mut token); + handler_release(h); + if hr < 0 { Err(hr) } else { Ok(token) } + } + } + + pub fn remove_handler(&self, token: i64) -> i32 { + unsafe { slot:: i32>(self.0 as *mut c_void, MEDIA_REMOVE_HANDLER)(self.0 as *mut c_void, token) } + } +} + pub fn endpoint_offload(id: Option<&str>) -> Result { let mut any = 0u32; for cat in 0..AUDIO_CATEGORIES { @@ -516,6 +822,177 @@ pub fn endpoint_offload(id: Option<&str>) -> Result { Ok(any) } +const IID_ISPATIAL_AUDIO_OBJECT_RENDER_STREAM: Guid = Guid { data1: 0xBAB5F473, data2: 0xB423, data3: 0x477B, data4: [0x85, 0xF5, 0xB5, 0xA3, 0x32, 0xA0, 0x41, 0x53] }; +const VT_BLOB: u16 = 0x41; +pub const SPATIAL_PARAMS2_BYTES: u32 = 0x2c; +const E_OUTOFMEMORY_HR: i32 = 0x8007_000Eu32 as i32; + +pub struct SpatialStreamParams { + pub format: Vec, + pub mask: u32, + pub min: u32, + pub max: u32, + pub category: u32, + pub options: u32, + pub extra: SpatialExtra, +} + +pub enum SpatialExtra { + Plain, + Hrtf { decay: Option<[u8; 0x14]>, directivity: Option<[u8; 0x10]>, environment: Option, orientation: Option<[u8; 0x24]> }, + Metadata { format_id: [u8; 16], max_items: u32 }, +} + +const IID_ISPATIAL_AUDIO_OBJECT_RENDER_STREAM_FOR_HRTF: Guid = Guid { data1: 0xE08DEEF9, data2: 0x5363, data3: 0x406E, data4: [0x9F, 0xDC, 0x08, 0x0E, 0xE2, 0x47, 0xBB, 0xE0] }; +const IID_ISPATIAL_AUDIO_OBJECT_RENDER_STREAM_FOR_METADATA: Guid = Guid { data1: 0xBBC9C907, data2: 0x48D5, data3: 0x4A2E, data4: [0xA0, 0xC7, 0xF7, 0xF0, 0xD6, 0x7C, 0x1F, 0xB1] }; +pub const SPATIAL_HRTF_PARAMS2_BYTES: u32 = 0x4c; +pub const SPATIAL_METADATA_PARAMS2_BYTES: u32 = 0x48; + +pub fn spatial_params_blob(p: &SpatialStreamParams, event: usize) -> (Vec, Guid) { + let put = |b: &mut Vec, o: usize, v: &[u8]| b[o..o + v.len()].copy_from_slice(v); + let size = match p.extra { + SpatialExtra::Plain => SPATIAL_PARAMS2_BYTES, + SpatialExtra::Hrtf { .. } => SPATIAL_HRTF_PARAMS2_BYTES, + SpatialExtra::Metadata { .. } => SPATIAL_METADATA_PARAMS2_BYTES, + } as usize; + let mut b = vec![0u8; size]; + put(&mut b, 0, &(p.format.as_ptr() as usize as u64).to_le_bytes()); + put(&mut b, 8, &p.mask.to_le_bytes()); + put(&mut b, 0xc, &p.min.to_le_bytes()); + put(&mut b, 0x10, &p.max.to_le_bytes()); + put(&mut b, 0x14, &p.category.to_le_bytes()); + put(&mut b, 0x18, &(event as u64).to_le_bytes()); + let iid = match &p.extra { + SpatialExtra::Plain => { + put(&mut b, 0x28, &p.options.to_le_bytes()); + IID_ISPATIAL_AUDIO_OBJECT_RENDER_STREAM + } + SpatialExtra::Hrtf { decay, directivity, environment, orientation } => { + let ptr = |o: Option<*const u8>| o.map(|x| x as usize as u64).unwrap_or(0).to_le_bytes(); + put(&mut b, 0x28, &ptr(decay.as_ref().map(|d| d.as_ptr()))); + put(&mut b, 0x30, &ptr(directivity.as_ref().map(|d| d.as_ptr()))); + put(&mut b, 0x38, &ptr(environment.as_ref().map(|d| d as *const u32 as *const u8))); + put(&mut b, 0x40, &ptr(orientation.as_ref().map(|d| d.as_ptr()))); + put(&mut b, 0x48, &p.options.to_le_bytes()); + IID_ISPATIAL_AUDIO_OBJECT_RENDER_STREAM_FOR_HRTF + } + SpatialExtra::Metadata { format_id, max_items } => { + put(&mut b, 0x20, format_id); + put(&mut b, 0x30, &max_items.to_le_bytes()); + put(&mut b, 0x44, &p.options.to_le_bytes()); + IID_ISPATIAL_AUDIO_OBJECT_RENDER_STREAM_FOR_METADATA + } + }; + (b, iid) +} + +pub struct SpatialStream { + com: Com, + event: usize, +} + +unsafe impl Send for SpatialStream {} + +impl SpatialStream { + pub fn available_dynamic(&self) -> Result { + unsafe { + let mut n = 0u32; + let hr = slot:: i32>(self.com.0, 3)(self.com.0, &mut n); + if hr < 0 { Err(hr) } else { Ok(n) } + } + } +} + +impl Drop for SpatialStream { + fn drop(&mut self) { + unsafe { CloseHandle(self.event) }; + } +} + +unsafe impl Sync for SpatialStream {} + +impl SpatialStream { + pub fn event(&self) -> usize { + self.event + } + unsafe fn call0(&self, n: usize) -> i32 { + slot:: i32>(self.com.0, n)(self.com.0) + } + pub fn start(&self) -> i32 { + unsafe { self.call0(5) } + } + pub fn stop(&self) -> i32 { + unsafe { self.call0(6) } + } + pub fn reset(&self) -> i32 { + unsafe { self.call0(7) } + } + pub fn begin_updating(&self) -> Result<(u32, u32), i32> { + unsafe { + let (mut n, mut f) = (0u32, 0u32); + let hr = slot:: i32>(self.com.0, 8)(self.com.0, &mut n, &mut f); + if hr < 0 { Err(hr) } else { Ok((n, f)) } + } + } + pub fn end_updating(&self) -> i32 { + unsafe { self.call0(9) } + } + pub fn activate_object(&self, kind: u32) -> Result { + unsafe { + let mut o = core::ptr::null_mut(); + let hr = slot:: i32>(self.com.0, 10)(self.com.0, kind, &mut o); + if hr < 0 || o.is_null() { Err(hr) } else { Ok(SpatialObject(Com(o))) } + } + } +} + +pub struct SpatialObject(Com); + +pub const HRTF_SET_GAIN: usize = 8; +pub const HRTF_SET_ORIENTATION: usize = 9; +pub const HRTF_SET_ENVIRONMENT: usize = 10; +pub const HRTF_SET_DISTANCE_DECAY: usize = 11; +pub const HRTF_SET_DIRECTIVITY: usize = 12; + +unsafe impl Send for SpatialObject {} + +impl SpatialObject { + pub fn buffer(&self) -> Result<(*mut u8, u32), i32> { + unsafe { + let (mut p, mut n) = (core::ptr::null_mut::(), 0u32); + let hr = slot:: i32>(self.0 .0, 3)(self.0 .0, &mut p, &mut n); + if hr < 0 || p.is_null() { Err(hr) } else { Ok((p, n)) } + } + } + pub fn set_end_of_stream(&self, frames: u32) -> i32 { + unsafe { slot:: i32>(self.0 .0, 4)(self.0 .0, frames) } + } + pub fn set_volume(&self, v: f32) -> i32 { + unsafe { slot:: i32>(self.0 .0, 8)(self.0 .0, v) } + } + pub fn set_hrtf_gain(&self, v: f32) -> i32 { + unsafe { slot:: i32>(self.0 .0, HRTF_SET_GAIN)(self.0 .0, v) } + } + pub fn set_hrtf_environment(&self, v: u32) -> i32 { + unsafe { slot:: i32>(self.0 .0, HRTF_SET_ENVIRONMENT)(self.0 .0, v) } + } + pub unsafe fn set_hrtf_block(&self, n: usize, p: *const u8) -> i32 { + slot:: i32>(self.0 .0, n)(self.0 .0, p) + } +} + +pub unsafe fn com_init() { + CoInitializeEx(core::ptr::null_mut(), 0); +} + +pub fn wait_event(h: usize, ms: u32) -> bool { + unsafe { WaitForSingleObject(h, ms) == 0 } +} + +pub fn signal_event(h: usize) { + unsafe { SetEvent(h) }; +} + pub struct Spatial(Com); pub fn spatial(id: Option<&str>) -> Result { @@ -574,6 +1051,27 @@ impl Spatial { if hr < 0 { Err(hr) } else { Ok(n) } } } + pub fn activate_stream(&self, p: &SpatialStreamParams) -> Result { + unsafe { + let event = CreateEventW(core::ptr::null_mut(), 0, 0, core::ptr::null()); + if event == 0 { + return Err(E_OUTOFMEMORY_HR); + } + let (blob, iid) = spatial_params_blob(p, event); + let mut pv: PropVariant = core::mem::zeroed(); + pv.vt = VT_BLOB; + let raw = &mut pv as *mut PropVariant as *mut u8; + core::ptr::write_unaligned(raw.add(8) as *mut u32, blob.len() as u32); + core::ptr::write_unaligned(raw.add(16) as *mut *const u8, blob.as_ptr()); + let mut st = core::ptr::null_mut(); + let hr = slot:: i32>(self.0 .0, 10)(self.0 .0, &pv, &iid, &mut st); + if hr < 0 { + CloseHandle(event); + return Err(hr); + } + Ok(SpatialStream { com: Com(st), event }) + } + } pub fn static_position(&self, kind: u32) -> Result<[f32; 3], i32> { unsafe { let mut p = [0f32; 3]; @@ -586,24 +1084,40 @@ impl Spatial { let hr = slot:: i32>(self.0 .0, 6)(self.0 .0, &mut e); if hr < 0 { Err(hr) } else { Ok(Com(e)) } } + pub fn format_enumerator(&self) -> Result { + unsafe { self.formats().map(FormatEnumerator) } + } pub fn format_count(&self) -> Result { + self.format_enumerator()?.count() + } + pub fn format_at(&self, index: u32) -> Result, i32> { + self.format_enumerator()?.get(index) + } +} + +pub struct FormatEnumerator(Com); + +unsafe impl Send for FormatEnumerator {} + +impl FormatEnumerator { + pub fn count(&self) -> Result { unsafe { - let e = self.formats()?; let mut n = 0u32; - let hr = slot:: i32>(e.0, 3)(e.0, &mut n); + let hr = slot:: i32>(self.0 .0, 3)(self.0 .0, &mut n); if hr < 0 { Err(hr) } else { Ok(n) } } } - pub fn format_at(&self, index: u32) -> Result, i32> { + pub fn get(&self, index: u32) -> Result, i32> { unsafe { - let e = self.formats()?; let mut f: *mut u8 = core::ptr::null_mut(); - let hr = slot:: i32>(e.0, 4)(e.0, index, &mut f); + let hr = slot:: i32>(self.0 .0, 4)(self.0 .0, index, &mut f); if hr < 0 || f.is_null() { - return Err(hr); + return Err(if hr < 0 { hr } else { 0x8000_4003u32 as i32 }); } let head = core::slice::from_raw_parts(f, 0x12); - Ok(core::slice::from_raw_parts(f, format_len(head)).to_vec()) + let out = core::slice::from_raw_parts(f, format_len(head)).to_vec(); + CoTaskMemFree(f as *mut c_void); + Ok(out) } } } @@ -747,6 +1261,45 @@ impl Renderer { hr } } + unsafe fn item_service(&self) -> Result { + let c = self.shared.client.load(Ordering::SeqCst) as *mut c_void; + if c.is_null() { + return Err(AUDCLNT_E_NOT_INITIALIZED); + } + let mut svc = core::ptr::null_mut(); + let hr = slot:: i32>(c, 14)(c, &IID_CLIENT_ITEM_SERVICE, &mut svc); + if hr < 0 { Err(hr) } else { Ok(Com(svc)) } + } + pub fn item_count(&self) -> Result { + unsafe { + let svc = self.item_service()?; + let mut n = 0u32; + let hr = slot:: i32>(svc.0, 3)(svc.0, &mut n); + if hr < 0 { Err(hr) } else { Ok(n) } + } + } + pub fn item_flag(&self) -> Result { + unsafe { + let svc = self.item_service()?; + let mut b = 0i32; + let hr = slot:: i32>(svc.0, 5)(svc.0, &mut b); + if hr < 0 { Err(hr) } else { Ok(b != 0) } + } + } + pub fn item_value(&self, index: u32) -> Result { + unsafe { + let svc = self.item_service()?; + let mut ch = core::ptr::null_mut(); + let hr = slot:: i32>(svc.0, 4)(svc.0, index, &mut ch); + if hr < 0 { + return Err(hr); + } + let ch = Com(ch); + let mut v = 0u32; + let hr = slot:: i32>(ch.0, 3)(ch.0, &mut v); + if hr < 0 { Err(hr) } else { Ok(v) } + } + } pub fn current_rate(&self) -> f32 { f32::from_bits(self.shared.rate.load(Ordering::SeqCst)) } @@ -948,3 +1501,423 @@ unsafe fn pump(c: *mut c_void, rc: *mut c_void, frames: u32, ring: &Ring, align: let _ = ring.read_pos().compare_exchange(r, r + total as i64, Ordering::AcqRel, Ordering::Acquire); s.rendered.fetch_add(total as i64, Ordering::SeqCst); } + +pub const CAPTURE_QUEUE_READ: usize = 0; +pub const CAPTURE_QUEUE_WRITE: usize = 4; +pub const CAPTURE_ENTRY: usize = 0x40; +pub const CAPTURE_KIND_DATA: u32 = 1; +pub const CAPTURE_KIND_SILENT: u32 = 2; +pub const CAPTURE_DISCONTINUITY: u32 = 1; +pub const CAPTURE_TIMESTAMP_ERROR: u32 = 4; +const BUFFERFLAGS_SILENT: u32 = 2; + +pub fn device_flow(id: Option<&str>) -> Result { + unsafe { + let dev = device(id)?; + let mut ep = core::ptr::null_mut(); + let hr = slot:: i32>(dev.0, 0)(dev.0, &IID_IMM_ENDPOINT, &mut ep); + if hr < 0 { + return Err(hr); + } + let ep = Com(ep); + let mut flow = 0u32; + let hr = slot:: i32>(ep.0, 3)(ep.0, &mut flow); + if hr < 0 { Err(hr) } else { Ok(flow) } + } +} + +pub struct CaptureQueue { + pub base: usize, + pub queue: usize, + pub entries: u32, +} + +impl CaptureQueue { + fn index(&self, o: usize) -> &AtomicU32 { + unsafe { &*((self.base + o) as *const AtomicU32) } + } + fn next(&self, i: u32) -> u32 { + if i + 1 >= self.entries { 0 } else { i + 1 } + } + fn entry(&self, i: u32) -> *mut u8 { + (self.base + self.queue + i as usize * CAPTURE_ENTRY) as *mut u8 + } + pub fn drop_unread(&self) { + let r = self.index(CAPTURE_QUEUE_READ).load(Ordering::Acquire); + self.index(CAPTURE_QUEUE_WRITE).swap(r, Ordering::AcqRel); + } + fn oldest_offset(&self) -> Option { + let mut r = self.index(CAPTURE_QUEUE_READ).load(Ordering::Acquire); + let w = self.index(CAPTURE_QUEUE_WRITE).load(Ordering::Acquire); + while r != w { + let e = self.entry(r); + unsafe { + if (e.add(8) as *const u32).read_volatile() != CAPTURE_KIND_SILENT { + return Some((e.add(4) as *const u32).read_volatile()); + } + } + r = self.next(r); + } + None + } + fn place(&self, ring: &Ring, at: u32, bytes: u32) -> Option { + let at = if at + bytes > ring.end { ring.start } else { at }; + if at + bytes > ring.end { + return None; + } + match self.oldest_offset() { + None => Some(at), + Some(old) if at <= old && at + bytes <= old => Some(at), + Some(old) if at > old && at + bytes <= ring.end => Some(at), + _ => None, + } + } + pub unsafe fn post(&self, ring: &Ring, at: &mut u32, data: Option<&[u8]>, frames: u32, devpos: u64, qpc: u64, rate: f32, flags: u32) -> bool { + let w = self.index(CAPTURE_QUEUE_WRITE).load(Ordering::Acquire); + let n = self.next(w); + if n == self.index(CAPTURE_QUEUE_READ).load(Ordering::Acquire) { + return false; + } + let (kind, off) = match data { + Some(d) => { + let Some(off) = self.place(ring, *at, d.len() as u32) else { + return false; + }; + core::ptr::copy_nonoverlapping(d.as_ptr(), (ring.base + off as usize) as *mut u8, d.len()); + *at = off + d.len() as u32; + (CAPTURE_KIND_DATA, off) + } + None => (CAPTURE_KIND_SILENT, *at), + }; + let e = self.entry(w); + core::ptr::write_bytes(e, 0, CAPTURE_ENTRY); + (e as *mut u32).write_volatile(1); + (e.add(4) as *mut u32).write_volatile(off); + (e.add(8) as *mut u32).write_volatile(kind); + (e.add(0x10) as *mut u64).write_volatile(devpos); + (e.add(0x18) as *mut u64).write_volatile(devpos); + (e.add(0x28) as *mut u64).write_volatile(qpc); + (e.add(0x30) as *mut f32).write_volatile(rate); + (e.add(0x34) as *mut u32).write_volatile(flags); + (e.add(0x38) as *mut u32).write_volatile(frames); + self.index(CAPTURE_QUEUE_WRITE).swap(n, Ordering::AcqRel); + ring.write_pos().fetch_add(frames as i64 * ring.align as i64, Ordering::AcqRel); + true + } +} + +pub fn open_capture(o: Open, ring: Ring, queue: CaptureQueue) -> Result<(Renderer, u32), i32> { + let shared = Arc::new(Shared::default()); + let (tx, rx) = std::sync::mpsc::channel::>(); + let s2 = shared.clone(); + let t = std::thread::spawn(move || unsafe { run_capture(o, ring, queue, s2, tx) }); + match rx.recv() { + Ok(Ok(frames)) => Ok((Renderer { shared, thread: Some(t) }, frames)), + Ok(Err(hr)) => { + let _ = t.join(); + Err(hr) + } + Err(_) => Err(-2147467259), + } +} + +unsafe fn run_capture(o: Open, ring: Ring, q: CaptureQueue, s: Arc, tx: std::sync::mpsc::Sender>) { + let c = match client(o.device.as_deref()) { + Ok(c) => c, + Err(hr) => { + let _ = tx.send(Err(hr)); + return; + } + }; + if let Some(p) = o.properties { + let props = [16u32, p[0], p[1], p[2]]; + slot:: i32>(c.0, 16)(c.0, props.as_ptr()); + } + let flags = o.flags & STREAMFLAGS_RATEADJUST; + let hr = match o.period_frames { + Some(p) => { + let mut c3 = core::ptr::null_mut(); + let hr = slot:: i32>(c.0, 0)(c.0, &IID_IAUDIO_CLIENT3, &mut c3); + if hr < 0 { + let _ = tx.send(Err(hr)); + return; + } + let c3 = Com(c3); + slot:: i32>(c3.0, 20)(c3.0, flags, p, o.format.as_ptr(), &o.session) + } + None => slot:: i32>(c.0, 3)(c.0, SHARED, AUTOCONVERT | flags, o.duration, 0, o.format.as_ptr(), &o.session), + }; + if hr < 0 { + let _ = tx.send(Err(hr)); + return; + } + let mut frames = 0u32; + slot:: i32>(c.0, 4)(c.0, &mut frames); + let mut lat = 0i64; + slot:: i32>(c.0, 5)(c.0, &mut lat); + s.latency.store(lat, Ordering::SeqCst); + let (mut dp, mut mp) = (0i64, 0i64); + slot:: i32>(c.0, 9)(c.0, &mut dp, &mut mp); + s.period.store(dp.max(10_000), Ordering::SeqCst); + let mut cc = core::ptr::null_mut(); + let hr = slot:: i32>(c.0, 14)(c.0, &IID_IAUDIO_CAPTURE_CLIENT, &mut cc); + if hr < 0 { + let _ = tx.send(Err(hr)); + return; + } + let cc = Com(cc); + let nominal = sample_rate(&o.format) as f32; + s.rate.store(nominal.to_bits(), Ordering::SeqCst); + s.client.store(c.0 as usize, Ordering::SeqCst); + let _ = tx.send(Ok(frames)); + let align = ring.align.max(1) as usize; + let rate = sample_rate(&o.format).max(1) as i64; + let tick = ((frames as i64 * 1000 / rate) / 4).clamp(1, 10) as u32; + let mut playing = false; + let mut at = ring.start; + let mut lost = false; + while !s.quit.load(Ordering::SeqCst) { + let want = s.running.load(Ordering::SeqCst); + if s.reset.swap(false, Ordering::SeqCst) { + if playing { + slot:: i32>(c.0, 11)(c.0); + playing = false; + } + slot:: i32>(c.0, 12)(c.0); + q.drop_unread(); + at = ring.start; + lost = false; + s.rebases.fetch_add(1, Ordering::SeqCst); + } + if want != playing { + slot:: i32>(c.0, if want { 10 } else { 11 })(c.0); + playing = want; + } + let mut posted = false; + while playing { + let mut next = 0u32; + if slot:: i32>(cc.0, 5)(cc.0, &mut next) < 0 || next == 0 { + break; + } + let (mut data, mut n, mut f, mut devpos, mut qpc) = (core::ptr::null_mut::(), 0u32, 0u32, 0u64, 0u64); + if slot:: i32>(cc.0, 3)(cc.0, &mut data, &mut n, &mut f, &mut devpos, &mut qpc) != 0 { + break; + } + let bytes = n as usize * align; + let payload = if f & BUFFERFLAGS_SILENT != 0 || data.is_null() { None } else { Some(core::slice::from_raw_parts(data, bytes)) }; + let pf = (f & (CAPTURE_DISCONTINUITY | CAPTURE_TIMESTAMP_ERROR)) | if lost { CAPTURE_DISCONTINUITY } else { 0 }; + if n != 0 && q.post(&ring, &mut at, payload, n, devpos, qpc, nominal, pf) { + lost = false; + posted = true; + s.records.fetch_add(1, Ordering::SeqCst); + s.rendered.fetch_add(bytes as i64, Ordering::SeqCst); + } else if n != 0 { + lost = true; + } + slot:: i32>(cc.0, 4)(cc.0, n); + } + if posted { + for &e in s.signal.lock().unwrap().iter() { + SetEvent(e as usize); + } + s.signals.fetch_add(1, Ordering::SeqCst); + } + std::thread::sleep(std::time::Duration::from_millis(tick as u64)); + } + slot:: i32>(c.0, 11)(c.0); + s.client.store(0, Ordering::SeqCst); +} + +const IID_IUNKNOWN: Guid = Guid { data1: 0, data2: 0, data3: 0, data4: [0xC0, 0, 0, 0, 0, 0, 0, 0x46] }; +const IID_IAUDIO_SESSION_EVENTS: Guid = Guid { data1: 0x24918ACC, data2: 0x64B3, data3: 0x37C1, data4: [0x8C, 0xA9, 0x74, 0xA6, 0x6E, 0x99, 0x57, 0xA8] }; +const IID_IMM_NOTIFICATION_CLIENT: Guid = Guid { data1: 0x7991EEC9, data2: 0x7E89, data3: 0x4D85, data4: [0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0] }; + +pub enum PcEvent { + Device { kind: u32, id: String, a: u32, b: u32, key: Option }, + Session { sid: String, kind: u32, ctx: [u8; 16], text: String, guid: [u8; 16], value: u32, volume: f32, volumes: Vec }, +} + +static EVENT_SINK: std::sync::OnceLock = std::sync::OnceLock::new(); + +pub fn set_event_sink(f: fn(PcEvent)) { + let _ = EVENT_SINK.set(f); +} + +fn emit(e: PcEvent) { + if let Some(f) = EVENT_SINK.get() { + f(e); + } +} + +unsafe fn wide_str(p: *const u16) -> String { + if p.is_null() { + return String::new(); + } + let mut n = 0; + while *p.add(n) != 0 { + n += 1; + } + String::from_utf16_lossy(core::slice::from_raw_parts(p, n)) +} + +fn same_guid(a: &Guid, b: &Guid) -> bool { + a.data1 == b.data1 && a.data2 == b.data2 && a.data3 == b.data3 && a.data4 == b.data4 +} + +#[repr(C)] +struct Callback { + vtbl: *const *const (), + iid: Guid, + sid: String, +} + +unsafe extern "system" fn cb_qi(this: *mut Callback, riid: *const Guid, out: *mut *mut c_void) -> i32 { + if same_guid(&*riid, &IID_IUNKNOWN) || same_guid(&*riid, &(*this).iid) { + *out = this as *mut c_void; + 0 + } else { + *out = core::ptr::null_mut(); + -2147467262 + } +} + +unsafe extern "system" fn cb_ref(_this: *mut Callback) -> u32 { + 1 +} + +unsafe extern "system" fn dev_state(_this: *mut Callback, id: *const u16, state: u32) -> i32 { + emit(PcEvent::Device { kind: 1, id: wide_str(id), a: state, b: 0, key: None }); + 0 +} + +unsafe extern "system" fn dev_added(_this: *mut Callback, id: *const u16) -> i32 { + emit(PcEvent::Device { kind: 2, id: wide_str(id), a: 0, b: 0, key: None }); + 0 +} + +unsafe extern "system" fn dev_removed(_this: *mut Callback, id: *const u16) -> i32 { + emit(PcEvent::Device { kind: 3, id: wide_str(id), a: 0, b: 0, key: None }); + 0 +} + +unsafe extern "system" fn dev_default(_this: *mut Callback, flow: u32, role: u32, id: *const u16) -> i32 { + emit(PcEvent::Device { kind: 4, id: wide_str(id), a: flow, b: role, key: None }); + 0 +} + +unsafe extern "system" fn dev_property(_this: *mut Callback, id: *const u16, key: *const PropertyKey) -> i32 { + let k = PropertyKey { fmtid: (*key).fmtid, pid: (*key).pid }; + emit(PcEvent::Device { kind: 5, id: wide_str(id), a: 0, b: 0, key: Some(k) }); + 0 +} + +unsafe fn guid16(p: *const Guid) -> [u8; 16] { + let mut g = [0u8; 16]; + if !p.is_null() { + core::ptr::copy_nonoverlapping(p as *const u8, g.as_mut_ptr(), 16); + } + g +} + +unsafe fn session_emit(this: *mut Callback, kind: u32, ctx: *const Guid, text: String, guid: [u8; 16], value: u32) -> i32 { + emit(PcEvent::Session { sid: (*this).sid.clone(), kind, ctx: guid16(ctx), text, guid, value, volume: 0.0, volumes: Vec::new() }); + 0 +} + +unsafe extern "system" fn sess_name(this: *mut Callback, name: *const u16, ctx: *const Guid) -> i32 { + session_emit(this, 0x10, ctx, wide_str(name), [0; 16], 0) +} + +unsafe extern "system" fn sess_icon(this: *mut Callback, path: *const u16, ctx: *const Guid) -> i32 { + session_emit(this, 0x100, ctx, wide_str(path), [0; 16], 0) +} + +unsafe extern "system" fn sess_simple(this: *mut Callback, v: f32, m: i32, ctx: *const Guid) -> i32 { + emit(PcEvent::Session { sid: (*this).sid.clone(), kind: 1, ctx: guid16(ctx), text: String::new(), guid: [0; 16], value: (m != 0) as u32, volume: v, volumes: Vec::new() }); + 0 +} + +unsafe extern "system" fn sess_channel(this: *mut Callback, n: u32, v: *const f32, changed: u32, ctx: *const Guid) -> i32 { + let volumes = if v.is_null() { Vec::new() } else { core::slice::from_raw_parts(v, n as usize).to_vec() }; + emit(PcEvent::Session { sid: (*this).sid.clone(), kind: 2, ctx: guid16(ctx), text: String::new(), guid: [0; 16], value: changed, volume: 0.0, volumes }); + 0 +} + +unsafe extern "system" fn sess_grouping(this: *mut Callback, g: *const Guid, ctx: *const Guid) -> i32 { + session_emit(this, 4, ctx, String::new(), guid16(g), 0) +} + +unsafe extern "system" fn sess_state(this: *mut Callback, st: u32) -> i32 { + session_emit(this, 8, core::ptr::null(), String::new(), [0; 16], st) +} + +unsafe extern "system" fn sess_disconnected(this: *mut Callback, reason: u32) -> i32 { + session_emit(this, 0x20, core::ptr::null(), String::new(), [0; 16], reason) +} + +struct Vtbl([*const (); 10]); +unsafe impl Sync for Vtbl {} + +static DEVICE_VTBL: Vtbl = Vtbl([cb_qi as *const (), cb_ref as *const (), cb_ref as *const (), dev_state as *const (), dev_added as *const (), dev_removed as *const (), dev_default as *const (), dev_property as *const (), core::ptr::null(), core::ptr::null()]); +static SESSION_VTBL: Vtbl = Vtbl([cb_qi as *const (), cb_ref as *const (), cb_ref as *const (), sess_name as *const (), sess_icon as *const (), sess_simple as *const (), sess_channel as *const (), sess_grouping as *const (), sess_state as *const (), sess_disconnected as *const ()]); + +fn watch Result<(), i32> + Send + 'static>(f: F) -> i32 { + let (tx, rx) = std::sync::mpsc::channel::(); + std::thread::spawn(move || unsafe { + CoInitializeEx(core::ptr::null_mut(), 0); + let hr = match f() { + Ok(()) => 0, + Err(hr) => hr, + }; + let _ = tx.send(hr); + if hr >= 0 { + loop { + std::thread::park(); + } + } + }); + rx.recv().unwrap_or(-2147467259) +} + +pub fn watch_devices() -> i32 { + static DONE: std::sync::OnceLock = std::sync::OnceLock::new(); + *DONE.get_or_init(|| { + watch(|| unsafe { + let en = enumerator()?; + let cb = Box::leak(Box::new(Callback { vtbl: DEVICE_VTBL.0.as_ptr(), iid: IID_IMM_NOTIFICATION_CLIENT, sid: String::new() })); + let hr = slot:: i32>(en.0, 6)(en.0, cb); + if hr < 0 { + return Err(hr); + } + core::mem::forget(en); + Ok(()) + }) + }) +} + +pub fn watch_session(r: &SessionRef) -> Result { + static DONE: std::sync::OnceLock>>> = std::sync::OnceLock::new(); + let map = DONE.get_or_init(|| Mutex::new(std::collections::HashMap::new())); + let sid = session_string(r, 13)?; + let key = sid.to_lowercase(); + if let Some(res) = map.lock().unwrap().get(&key) { + return res.clone(); + } + let res = Ok(sid).and_then(|sid: String| { + let r2 = r.clone(); + let reg_sid = sid.clone(); + let hr = watch(move || unsafe { + let c = session_control(&r2)?; + let cb = Box::leak(Box::new(Callback { vtbl: SESSION_VTBL.0.as_ptr(), iid: IID_IAUDIO_SESSION_EVENTS, sid: reg_sid })); + let hr = slot:: i32>(c.0, 10)(c.0, cb); + if hr < 0 { + return Err(hr); + } + core::mem::forget(c); + Ok(()) + }); + if hr < 0 { Err(hr) } else { Ok(sid) } + }); + map.lock().unwrap().insert(key, res.clone()); + res +} diff --git a/crates/compat/console-sandbox/src/xvcmgmt.rs b/crates/compat/console-sandbox/src/xvcmgmt.rs index ad736866..1b656b4c 100644 --- a/crates/compat/console-sandbox/src/xvcmgmt.rs +++ b/crates/compat/console-sandbox/src/xvcmgmt.rs @@ -14,6 +14,7 @@ pub const IOCTL_ACCEPT: u32 = 0x1500a4; pub const IOCTL_SEND: u32 = 0x1500a8; pub const IOCTL_RECEIVE: u32 = 0x1500ac; pub const IOCTL_CLOSE: u32 = 0x1500b0; +pub const IOCTL_PHYSICAL_MEMORY_LAYOUT: u32 = 0x1500d4; pub const IOCTL_SHUTDOWN: u32 = 0x1500f4; pub const STATUS_SUCCESS: i32 = 0; @@ -472,6 +473,13 @@ pub unsafe fn ioctl(io: *mut usize, event: usize, apc: usize, ctx: usize, code: } let irp = Irp::new(io, event, apc, ctx, outb, outl); match code { + IOCTL_PHYSICAL_MEMORY_LAYOUT if compat_common::os_host::routes::current_build() == 19041 => { + if outl < 16 || outb.is_null() { + return finish(irp, STATUS_BUFFER_TOO_SMALL, 0); + } + outb.cast::<[u64; 2]>().write_unaligned(compat_common::physical_pages::TITLE_LAYOUT_19041); + finish(irp, STATUS_SUCCESS, 16) + } IOCTL_CREATE => { if inl < 0x20 || outl < 8 || inb.is_null() || outb.is_null() { return finish(irp, STATUS_INVALID_PARAMETER, 0); diff --git a/crates/compat/console-sandbox/tests/verify_comreg.rs b/crates/compat/console-sandbox/tests/verify_comreg.rs new file mode 100644 index 00000000..7886cb8f --- /dev/null +++ b/crates/compat/console-sandbox/tests/verify_comreg.rs @@ -0,0 +1,128 @@ +use console_sandbox::comreg; +use core::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::Mutex; + +static LOCK: Mutex<()> = Mutex::new(()); +static REFS: AtomicU32 = AtomicU32::new(1); +static CREATED: AtomicU32 = AtomicU32::new(0); +static FACTORY_CALLS: AtomicU32 = AtomicU32::new(0); + +unsafe extern "system" fn qi(this: usize, iid: *const [u8; 16], out: *mut usize) -> i32 { + if *iid == comreg::IID_IUNKNOWN || *iid == comreg::IID_ICLASSFACTORY { + REFS.fetch_add(1, Ordering::SeqCst); + *out = this; + 0 + } else { + *out = 0; + comreg::E_NOINTERFACE + } +} + +unsafe extern "system" fn add(_: usize) -> u32 { + REFS.fetch_add(1, Ordering::SeqCst) + 1 +} + +unsafe extern "system" fn rel(_: usize) -> u32 { + REFS.fetch_sub(1, Ordering::SeqCst) - 1 +} + +unsafe extern "system" fn create(this: usize, outer: usize, iid: *const [u8; 16], out: *mut usize) -> i32 { + if outer != 0 { + return comreg::CLASS_E_NOAGGREGATION; + } + CREATED.fetch_add(1, Ordering::SeqCst); + qi(this, iid, out) +} + +fn object() -> usize { + let vt: &'static [usize; 5] = Box::leak(Box::new([qi as *const () as usize, add as *const () as usize, rel as *const () as usize, create as *const () as usize, 0])); + Box::leak(Box::new([vt.as_ptr() as usize])).as_ptr() as usize +} + +unsafe extern "system" fn get_factory(_id: *mut c_void, out: *mut usize) -> i32 { + FACTORY_CALLS.fetch_add(1, Ordering::SeqCst); + static F: std::sync::OnceLock = std::sync::OnceLock::new(); + let f = *F.get_or_init(object); + REFS.fetch_add(1, Ordering::SeqCst); + *out = f; + 0 +} + +#[link(name = "runtimeobject")] +extern "system" { + fn WindowsCreateString(s: *const u16, n: u32, out: *mut *mut c_void) -> i32; + fn WindowsDeleteString(s: *mut c_void) -> i32; +} + +#[test] +fn class_objects_serve_in_process_with_single_use_suspension_and_duplicates() { + let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let obj = object(); + let multi = [0x61u8; 16]; + let mut c1 = 0u32; + assert_eq!(comreg::co_register_class_object(&multi, obj as *mut _, comreg::CLSCTX_LOCAL_SERVER, comreg::REGCLS_MULTIPLEUSE | comreg::REGCLS_SUSPENDED, &mut c1), 0); + let mut out: *mut c_void = core::ptr::null_mut(); + assert!(comreg::create_from_table(&multi, core::ptr::null_mut(), comreg::CLSCTX_LOCAL_SERVER, &comreg::IID_IUNKNOWN, &mut out).is_none()); + assert_eq!(comreg::co_resume_class_objects(), 0); + assert_eq!(comreg::co_create_instance(&multi, core::ptr::null_mut(), comreg::CLSCTX_LOCAL_SERVER, &comreg::IID_IUNKNOWN, &mut out), 0); + assert_eq!(out as usize, obj); + comreg::release(obj); + let mut cf: *mut c_void = core::ptr::null_mut(); + assert_eq!(comreg::co_get_class_object(&multi, comreg::CLSCTX_LOCAL_SERVER, core::ptr::null_mut(), &comreg::IID_ICLASSFACTORY, &mut cf), 0); + assert_eq!(cf as usize, obj); + comreg::release(obj); + assert_eq!(comreg::co_create_instance(&multi, 1usize as *mut _, comreg::CLSCTX_LOCAL_SERVER, &comreg::IID_IUNKNOWN, &mut out), comreg::CLASS_E_NOAGGREGATION); + let mut c2 = 0u32; + assert_eq!(comreg::co_register_class_object(&multi, obj as *mut _, comreg::CLSCTX_LOCAL_SERVER, comreg::REGCLS_MULTIPLEUSE, &mut c2), 0); + assert_ne!(c1, c2); + + let single = [0x62u8; 16]; + let mut c3 = 0u32; + assert_eq!(comreg::co_register_class_object(&single, obj as *mut _, comreg::CLSCTX_INPROC_SERVER, comreg::REGCLS_SINGLEUSE, &mut c3), 0); + let mut c4 = 0u32; + assert_eq!(comreg::co_register_class_object(&single, obj as *mut _, comreg::CLSCTX_INPROC_SERVER, comreg::REGCLS_SINGLEUSE, &mut c4), comreg::CO_E_OBJISREG); + assert_eq!(comreg::co_create_instance(&single, core::ptr::null_mut(), comreg::CLSCTX_INPROC_SERVER, &comreg::IID_IUNKNOWN, &mut out), 0); + comreg::release(obj); + assert!(comreg::create_from_table(&single, core::ptr::null_mut(), comreg::CLSCTX_INPROC_SERVER, &comreg::IID_IUNKNOWN, &mut out).is_none()); + assert_eq!(CREATED.load(Ordering::SeqCst), 2); + + for c in [c1, c2, c3] { + assert_eq!(comreg::co_revoke_class_object(c), 0); + } + assert_eq!(comreg::co_revoke_class_object(c1), comreg::E_INVALIDARG); + assert_eq!(REFS.load(Ordering::SeqCst), 1); + assert_eq!(comreg::co_register_class_object(core::ptr::null(), obj as *mut _, 4, 1, &mut c1), comreg::E_INVALIDARG); + } +} + +#[test] +fn activation_factories_resolve_through_the_registered_callback() { + let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let name: Vec = "TomBox.Test.ActivatableClass".encode_utf16().collect(); + let mut h: *mut c_void = core::ptr::null_mut(); + assert_eq!(WindowsCreateString(name.as_ptr(), name.len() as u32, &mut h), 0); + let ids = [h]; + let cbs = [get_factory as *const () as usize]; + let mut cookie = 0usize; + assert_eq!(comreg::ro_register_activation_factories(ids.as_ptr(), cbs.as_ptr(), 1, &mut cookie), 0); + let mut again = 0usize; + assert_eq!(comreg::ro_register_activation_factories(ids.as_ptr(), cbs.as_ptr(), 1, &mut again), comreg::CO_E_OBJISREG); + let before = REFS.load(Ordering::SeqCst); + let mut out: *mut c_void = core::ptr::null_mut(); + assert_eq!(comreg::ro_get_activation_factory(h, &comreg::IID_IUNKNOWN, &mut out), 0); + assert!(!out.is_null()); + assert_eq!(FACTORY_CALLS.load(Ordering::SeqCst), 1); + assert_eq!(REFS.load(Ordering::SeqCst), before + 1); + comreg::release(out as usize); + let bad = [7u8; 16]; + assert_eq!(comreg::ro_get_activation_factory(h, &bad, &mut out), comreg::E_NOINTERFACE); + comreg::ro_revoke_activation_factories(cookie); + assert!(comreg::factories().iter().all(|f| f.cookie != cookie)); + assert!(comreg::activation_factory("TomBox.Test.ActivatableClass", h, &comreg::IID_IUNKNOWN, &mut out).is_none()); + assert_eq!(comreg::ro_register_activation_factories(ids.as_ptr(), cbs.as_ptr(), 0, &mut cookie), comreg::E_INVALIDARG); + WindowsDeleteString(h); + } +} diff --git a/crates/compat/console-sandbox/tests/verify_rpcsrv.rs b/crates/compat/console-sandbox/tests/verify_rpcsrv.rs new file mode 100644 index 00000000..63a1b982 --- /dev/null +++ b/crates/compat/console-sandbox/tests/verify_rpcsrv.rs @@ -0,0 +1,141 @@ +use console_sandbox::rpcsrv::{self, Client}; +use console_sandbox::wstr::wide; +use std::sync::Mutex; + +static LOCK: Mutex<()> = Mutex::new(()); + +fn ifspec(uuid: [u8; 16], table: &[usize]) -> (Box<[u8; 0x60]>, Box>) { + let mut b = Box::new([0u8; 0x60]); + b[0..4].copy_from_slice(&0x60u32.to_le_bytes()); + b[4..20].copy_from_slice(&uuid); + b[20..22].copy_from_slice(&2u16.to_le_bytes()); + (b, Box::new(table.to_vec())) +} + +extern "system" fn op0() {} +extern "system" fn op1() {} + +#[test] +fn endpoints_are_in_process_and_offline_protocols_are_refused() { + let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + rpcsrv::reset(); + unsafe { + let tcp = wide("ncacn_ip_tcp"); + assert_eq!(rpcsrv::rpc_server_use_protseq_w(tcp.as_ptr(), 10, core::ptr::null_mut()), rpcsrv::RPC_S_PROTSEQ_NOT_SUPPORTED); + let bad = wide("ncabogus"); + assert_eq!(rpcsrv::rpc_server_use_protseq_w(bad.as_ptr(), 10, core::ptr::null_mut()), rpcsrv::RPC_S_INVALID_RPC_PROTSEQ); + let lrpc = wide("ncalrpc"); + assert_eq!(rpcsrv::rpc_server_use_protseq_w(lrpc.as_ptr(), 10, core::ptr::null_mut()), 0); + assert_eq!(rpcsrv::rpc_server_use_protseq_w(lrpc.as_ptr(), 10, core::ptr::null_mut()), 0); + let ep = wide("NetProfOracle"); + assert_eq!(rpcsrv::rpc_server_use_protseq_ep_w(lrpc.as_ptr(), 4, ep.as_ptr(), core::ptr::null_mut()), 0); + assert_eq!(rpcsrv::rpc_server_use_protseq_ep_w(lrpc.as_ptr(), 4, ep.as_ptr(), core::ptr::null_mut()), rpcsrv::RPC_S_DUPLICATE_ENDPOINT); + let hv = wide("ncacn_hvsocket"); + assert_eq!(rpcsrv::rpc_server_use_protseq_w(hv.as_ptr(), 10, core::ptr::null_mut()), rpcsrv::RPC_S_INVALID_ENDPOINT_FORMAT); + assert_eq!(rpcsrv::endpoints().len(), 2); + + let mut v: *mut u8 = core::ptr::null_mut(); + assert_eq!(rpcsrv::rpc_server_inq_bindings(&mut v), 0); + assert_eq!((v as *const u32).read(), 2); + let h = (v.add(8) as *const usize).read(); + let mut s: *mut u16 = core::ptr::null_mut(); + assert_eq!(rpcsrv::rpc_binding_to_string_binding_w(h as *mut _, &mut s), 0); + let text = console_sandbox::wstr::from_ptr(s); + assert_eq!(text, format!("ncalrpc:[{}]", console_sandbox::rpc::dynamic_endpoint())); + assert!(rpcsrv::owns_string(s as usize)); + assert_eq!(rpcsrv::rpc_string_free_w(&mut s), 0); + assert!(s.is_null()); + assert_eq!(rpcsrv::rpc_binding_vector_free(&mut v), 0); + assert!(v.is_null()); + assert!(!rpcsrv::is_ours(h)); + + let mut name: *mut u16 = core::ptr::null_mut(); + assert_eq!(rpcsrv::rpc_server_inq_default_princ_name_w(10, &mut name), 0); + assert_eq!(console_sandbox::wstr::from_ptr(name), rpcsrv::DEFAULT_PRINCIPAL); + assert_eq!(rpcsrv::rpc_string_free_w(&mut name), 0); + assert_eq!(rpcsrv::rpc_server_inq_default_princ_name_w(77, &mut name), rpcsrv::RPC_S_UNKNOWN_AUTHN_SERVICE); + assert_eq!(rpcsrv::rpc_server_register_auth_info_w(core::ptr::null(), 77, core::ptr::null(), core::ptr::null_mut()), rpcsrv::RPC_S_UNKNOWN_AUTHN_SERVICE); + } + rpcsrv::reset(); +} + +#[test] +fn calls_carry_attributes_cancel_and_async_completion_and_unregister_waits() { + let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + rpcsrv::reset(); + unsafe { + let ep = console_sandbox::rpc::dynamic_endpoint(); + assert_eq!(rpcsrv::listen("ncalrpc", 10, None, 0), 0); + let uuid = [0x33u8; 16]; + let (spec, table) = ifspec(uuid, &[op0 as *const () as usize, op1 as *const () as usize]); + let sp = spec.as_ptr() as *const core::ffi::c_void; + assert_eq!(rpcsrv::rpc_server_register_if3(sp, core::ptr::null(), table.as_ptr() as *const _, rpcsrv::RPC_IF_AUTOLISTEN | rpcsrv::RPC_IF_ALLOW_LOCAL_ONLY, 1, 0, core::ptr::null(), core::ptr::null_mut()), 0); + assert_eq!(rpcsrv::rpc_server_register_if3(sp, core::ptr::null(), table.as_ptr() as *const _, 1, 1, 0, core::ptr::null(), core::ptr::null_mut()), rpcsrv::RPC_S_TYPE_ALREADY_REGISTERED); + + assert_eq!(rpcsrv::rpc_server_test_cancel(core::ptr::null_mut()), rpcsrv::RPC_S_NO_CALL_ACTIVE); + let mut attrs = [0u8; 0x78]; + attrs[0] = 2; + assert_eq!(rpcsrv::rpc_server_inq_call_attributes_w(core::ptr::null_mut(), attrs.as_mut_ptr()), rpcsrv::RPC_S_NO_CALL_ACTIVE); + + let client = Client::lrpc(&ep); + let seen = rpcsrv::invoke(&uuid, 2, 1, &client, |d| { + let mut a = [0u8; 0x78]; + a[0] = 2; + a[4] = (rpcsrv::RPC_QUERY_CLIENT_PID | rpcsrv::RPC_QUERY_IS_CLIENT_LOCAL) as u8; + let r = rpcsrv::rpc_server_inq_call_attributes_w(core::ptr::null_mut(), a.as_mut_ptr()); + let before = rpcsrv::rpc_server_test_cancel(core::ptr::null_mut()); + rpcsrv::cancel(d.call); + let after = rpcsrv::rpc_server_test_cancel(d.call as *mut _); + let busy = rpcsrv::invoke(&uuid, 2, 0, &client, |_| ()).err(); + (d.routine, r, a, before, after, busy) + }) + .unwrap(); + assert_eq!(seen.0, op1 as *const () as usize); + assert_eq!(seen.1, 0); + let rd = |o: usize| u32::from_le_bytes(seen.2[o..o + 4].try_into().unwrap()); + assert_eq!((rd(0x38), rd(0x3c), rd(0x40), rd(0x48), rd(0x4c)), (rpcsrv::RPC_PROTSEQ_LRPC, rpcsrv::RCCL_LOCAL, std::process::id(), rpcsrv::RPC_CALL_STATUS_IN_PROGRESS, rpcsrv::RCT_NORMAL)); + assert_eq!(u16::from_le_bytes([seen.2[0x58], seen.2[0x59]]), 1); + assert_eq!(&seen.2[0x5c..0x6c], &uuid); + assert_eq!((seen.3, seen.4, seen.5), (rpcsrv::RPC_S_CALL_IN_PROGRESS, 0, Some(rpcsrv::RPC_S_SERVER_TOO_BUSY))); + assert_eq!(rpcsrv::invoke(&uuid, 2, 0, &Client::hvsocket(&ep, [1; 16]), |_| ()).err(), Some(rpcsrv::RPC_S_INVALID_BINDING)); + + static HITS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + unsafe extern "system" fn on_disconnect(_a: usize, _c: usize, ev: u32) { + if ev == rpcsrv::RPC_ASYNC_EVENT_CLIENT_DISCONNECT { + HITS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + } + let call = rpcsrv::invoke_async(&uuid, 2, 0, &client, |d, state| { + assert_eq!((state as *const u32).read(), rpcsrv::RPC_ASYNC_STATE_SIZE); + assert_eq!(((state + 0x20) as *const usize).read(), d.call); + let info = [on_disconnect as *const () as usize, 0, 0, 0]; + assert_eq!(rpcsrv::rpc_server_subscribe_for_notification(d.call as *mut _, rpcsrv::RPC_NOTIFICATION_CLIENT_DISCONNECT, rpcsrv::RPC_NOTIFICATION_TYPE_CALLBACK, info.as_ptr()), 0); + }) + .unwrap(); + assert!(call.notify(rpcsrv::RPC_NOTIFICATION_CLIENT_DISCONNECT)); + assert_eq!(HITS.load(std::sync::atomic::Ordering::SeqCst), 1); + let mut queued = 0u32; + assert_eq!(rpcsrv::rpc_server_unsubscribe_for_notification(call.dispatch.call as *mut _, rpcsrv::RPC_NOTIFICATION_CLIENT_DISCONNECT, &mut queued), 0); + assert_eq!(queued, 1); + assert_eq!(rpcsrv::active_calls(&uuid), 1); + let spu = sp as usize; + let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let d2 = done.clone(); + let unreg = std::thread::spawn(move || { + let r = rpcsrv::rpc_server_unregister_if(spu as *const core::ffi::c_void, core::ptr::null(), 1); + d2.store(true, std::sync::atomic::Ordering::SeqCst); + r + }); + std::thread::sleep(std::time::Duration::from_millis(50)); + assert!(!done.load(std::sync::atomic::Ordering::SeqCst)); + let reply = 0x1234u32; + assert_eq!(rpcsrv::rpc_async_complete_call(call.state as *mut _, &reply as *const u32 as *mut _), 0); + assert_eq!(rpcsrv::rpc_async_complete_call(call.state as *mut _, &reply as *const u32 as *mut _), rpcsrv::RPC_S_INVALID_ASYNC_HANDLE); + assert_eq!(call.wait(std::time::Duration::from_secs(5)), Some(Ok(0x1234))); + assert_eq!(unreg.join().unwrap(), 0); + assert_eq!(rpcsrv::active_calls(&uuid), 0); + assert_eq!(rpcsrv::rpc_server_unregister_if(sp, core::ptr::null(), 1), rpcsrv::RPC_S_UNKNOWN_IF); + drop(table); + } + rpcsrv::reset(); +} diff --git a/crates/compat/console-sandbox/tests/verify_xvcmgmt.rs b/crates/compat/console-sandbox/tests/verify_xvcmgmt.rs index ce62fae2..23c38225 100644 --- a/crates/compat/console-sandbox/tests/verify_xvcmgmt.rs +++ b/crates/compat/console-sandbox/tests/verify_xvcmgmt.rs @@ -173,3 +173,26 @@ fn client_flow_against_the_emulated_host() { assert_eq!(Call::new().run(xvcmgmt::IOCTL_CLOSE, &q.to_le_bytes(), &mut []), 0); assert_eq!(r.wait(5000).map(|x| x.0), Some(xvcmgmt::STATUS_CANCELLED)); } + +#[test] +fn layout_ioctl_returns_two_frames_in_19041() { + if std::env::var_os("XVC_LAYOUT_TEST_CHILD").is_none() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "layout_ioctl_returns_two_frames_in_19041"]) + .env("XVC_LAYOUT_TEST_CHILD", "1") + .env("TOMBOX_CONSOLE_OSBUILD", "19041") + .status().unwrap(); + assert!(status.success()); + return; + } + let mut bytes = [0xaa; 18]; + let code = xvcmgmt::IOCTL_PHYSICAL_MEMORY_LAYOUT; + assert_eq!(sync_fail(code, &[], &mut bytes[1..16]), xvcmgmt::STATUS_BUFFER_TOO_SMALL); + assert_eq!(bytes, [0xaa; 18]); + let mut call = Call::new(); + assert_eq!(call.run(code, &[], &mut bytes[1..]), 0); + assert_eq!(call.wait(0), Some((0, 16))); + assert_eq!(u64::from_le_bytes(bytes[1..9].try_into().unwrap()), 0x10000); + assert_eq!(bytes[1..9], bytes[9..17]); + assert_eq!((bytes[0], bytes[17]), (0xaa, 0xaa)); +} diff --git a/crates/compat/d3d12_x/src/pixie.rs b/crates/compat/d3d12_x/src/pixie.rs index 532ce48b..71a775fc 100644 --- a/crates/compat/d3d12_x/src/pixie.rs +++ b/crates/compat/d3d12_x/src/pixie.rs @@ -423,7 +423,10 @@ mod tests { let (mut a, mut b, mut c) = (0u64, 0u64, 0u32); unsafe { assert_eq!(read_u32(h, &mut c), not_supported); - assert_eq!(read_pair(h, &mut a, &mut b), not_supported); + let t0 = core::arch::x86_64::_rdtsc(); + assert_eq!(read_pair(h, &mut a, &mut b), 0); + assert!(a >= t0 && a <= core::arch::x86_64::_rdtsc()); + assert!(b != 0); assert_eq!(query_fresh(0, 0, &mut a, null_mut()), not_supported); assert_eq!(c20b(buf.as_ptr().cast()), STATUS_UNSUCCESSFUL); assert_eq!(c207(1, 2), STATUS_UNSUCCESSFUL); diff --git a/crates/compat/d3d12_xs/build.rs b/crates/compat/d3d12_xs/build.rs index 75496e4b..bdbb5c1b 100644 --- a/crates/compat/d3d12_xs/build.rs +++ b/crates/compat/d3d12_xs/build.rs @@ -50,41 +50,4 @@ fn main() { }; let code = compiled.unwrap_or_else(|e| checked_in(&dir, &e)); std::fs::write(&out, code).expect("write query_accum.dxil"); - translator_hash(); -} - -fn collect(dir: &Path, out: &mut Vec) { - let Ok(rd) = std::fs::read_dir(dir) else { return }; - for e in rd.flatten() { - let p = e.path(); - if p.is_dir() { - collect(&p, out); - } else { - out.push(p); - } - } -} - -fn translator_hash() { - let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()); - let xshader = manifest.join("..").join("..").join("tombox-xshader"); - let mut files = Vec::new(); - collect(&xshader.join("src"), &mut files); - files.push(xshader.join("Cargo.toml")); - for f in ["shader_xlat.rs", "cbv_raw.rs", "mip_bind.rs", "global_bind.rs", "centroid_bind.rs", "xlat_index.rs"] { - files.push(manifest.join("src").join(f)); - } - files.sort(); - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for f in &files { - println!("cargo:rerun-if-changed={}", f.display()); - let Ok(data) = std::fs::read(f) else { continue }; - let name = f.strip_prefix(&manifest.join("..").join("..")).unwrap_or(f).to_string_lossy().replace('\\', "/"); - for b in name.bytes().chain(data.into_iter().filter(|&b| b != b'\r')) { - h ^= b as u64; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - } - } - println!("cargo:rerun-if-changed={}", xshader.join("src").display()); - println!("cargo:rustc-env=TOMBOX_XLAT_SRC_HASH={h:016x}"); } diff --git a/crates/compat/d3d12_xs/src/alias.rs b/crates/compat/d3d12_xs/src/alias.rs index faad0c6d..306562f1 100644 --- a/crates/compat/d3d12_xs/src/alias.rs +++ b/crates/compat/d3d12_xs/src/alias.rs @@ -517,6 +517,7 @@ pub unsafe fn create_placed_x(real: *mut c_void, va: u64, pc_desc: &[u8; 0x38], let sp = g.get_or_insert_with(Spans::default); housekeeping(sp); let mut chosen: Option<((u64, usize), u64, bool)> = None; + let mut msaa_align = 0u64; if dim == 1 && va % PLACEMENT_ALIGN == 0 && title_buffers_enabled() { let width = u64::from_le_bytes(desc[0x10..0x18].try_into().unwrap()); let flags = u32::from_le_bytes(desc[0x30..0x34].try_into().unwrap()); @@ -573,11 +574,12 @@ pub unsafe fn create_placed_x(real: *mut c_void, va: u64, pc_desc: &[u8; 0x38], } let (size, align) = info; if size != 0 && size != u64::MAX && align != 0 && align <= crate::msaa_place::max_align(samples) && va % align.min(PLACEMENT_ALIGN) == 0 { - if samples <= 1 { + let tiles = samples > 1 && crate::msaa_place::tiles_usable(); + if samples <= 1 || tiles { unsafe { migrate_shadow(real, sp, va, size) }; } let private = if dim >= 2 { oversize_span(va, size, xbox_size) } else { None }; - let key = match (private, sp.find(Kind::Local, va, size, align)) { + let key = match (private, sp.find(Kind::Local, va, size, crate::msaa_place::span_align(samples, align))) { (Some((lo, hi)), _) => unsafe { create_local_heap(real, size, samples > 1) }.map(|h| { STATS.heaps.fetch_add(1, Ordering::Relaxed); static N: AtomicUsize = AtomicUsize::new(0); @@ -586,11 +588,11 @@ pub unsafe fn create_placed_x(real: *mut c_void, va: u64, pc_desc: &[u8; 0x38], } (sp.insert(Span { lo, hi, kind: Kind::Local, heap: h as usize, retired: false, live: HashSet::new() }), true) }), - (None, Some(k)) if samples > 1 && !crate::msaa_place::capable(sp.get(k).heap) => None, + (None, Some(k)) if samples > 1 && !tiles && !crate::msaa_place::capable(sp.get(k).heap) => None, (None, Some(k)) => Some((k, false)), (None, None) => { let (lo, hi) = local_span(va, size.max(xbox_size), reservation(va)); - let fits = crate::msaa_place::span_fits(samples, va, lo, align); + let fits = tiles || crate::msaa_place::span_fits(samples, va, lo, align); if fits { unsafe { create_local_heap(real, hi - lo, samples > 1) } } else { None }.map(|h| { STATS.heaps.fetch_add(1, Ordering::Relaxed); (sp.insert(Span { lo, hi, kind: Kind::Local, heap: h as usize, retired: false, live: HashSet::new() }), true) @@ -599,6 +601,7 @@ pub unsafe fn create_placed_x(real: *mut c_void, va: u64, pc_desc: &[u8; 0x38], }; if let Some((k, fresh)) = key { chosen = Some((k, va - k.0, fresh)); + msaa_align = align; } } } @@ -607,8 +610,15 @@ pub unsafe fn create_placed_x(real: *mut c_void, va: u64, pc_desc: &[u8; 0x38], return None; }; let (heap, kind) = { let s = sp.get(key); (s.heap, s.kind) }; + let tiled = kind == Kind::Local && crate::msaa_place::needs_tiles(samples, offset, msaa_align, crate::msaa_place::capable(heap)); let hr = if kind == Kind::Shadow { unsafe { crate::title_shadow::place_reserved(real, heap, offset, &desc, init_state, ppv) } + } else if tiled { + let hr = unsafe { crate::title_shadow::place_tiled(real, heap, offset, &desc, init_state, pclear, ppv) }; + if hr < 0 && hr != 0x8007_000eu32 as i32 { + crate::msaa_place::note_tiles_refused(hr); + } + hr } else { unsafe { vcall!(real, 29, fn(*mut c_void, u64, *const u8, u32, *const c_void, *const Guid, *mut *mut c_void) -> i32, diff --git a/crates/compat/d3d12_xs/src/bindtrace.rs b/crates/compat/d3d12_xs/src/bindtrace.rs index d5b46955..6d1f541f 100644 --- a/crates/compat/d3d12_xs/src/bindtrace.rs +++ b/crates/compat/d3d12_xs/src/bindtrace.rs @@ -116,7 +116,22 @@ pub fn note_desc_after(dest: usize, heap_type: u32, d: Desc) { } } +pub fn all_views() -> Vec<(usize, bool)> { + with(|s| { + s.descs.values().filter_map(|e| match &e.d { + Desc::Srv { res, .. } if *res != 0 => Some((*res, false)), + Desc::Uav { res, .. } if *res != 0 => Some((*res, true)), + _ => None, + }).collect() + }) +} + pub fn note_desc(dest: usize, d: Desc) { + match &d { + Desc::Srv { res, .. } => crate::firstuse::note(*res, crate::firstuse::SRV), + Desc::Uav { res, .. } => crate::firstuse::note(*res, crate::firstuse::UAV), + _ => {} + } with(|s| { let frame = s.frame; s.descs.insert(dest, Entry { d, frame }); @@ -229,7 +244,15 @@ pub unsafe fn read_va(va: u64, n: usize) -> Option> { Some(core::slice::from_raw_parts((mapped + off) as *const u8, n).to_vec()) } +pub fn note_heap_inc(cpu: usize, gpu: u64, count: u32, inc: usize) { + with(|s| { + s.heaps.retain(|h| h.cpu != cpu); + s.heaps.push(Heap { cpu, gpu, count: count as usize, inc }); + }); +} + pub fn set_table(list: usize, compute: bool, index: u32, handle: u64) { + let handle = crate::title_heap::locate(handle).map_or(handle, |t| t.2); with(|s| { let v = s.tables.entry((list, compute)).or_default(); if (index as usize) < 64 { @@ -375,6 +398,100 @@ fn fmt_words(bytes: &[u8]) -> String { } /// Text describing every table bound on `list` (graphics or compute). +pub fn table_srv(list: usize, compute: bool, param: u32, slot: u32) -> Option<(usize, u32, u32)> { + with(|s| { + let h = *s.tables.get(&(list, compute))?.get(param as usize)?; + if h == 0 { + return None; + } + let heap = s.heaps.iter().find(|x| x.gpu != 0 && x.inc != 0 && h >= x.gpu && h < x.gpu + (x.count * x.inc) as u64)?; + let idx = (h - heap.gpu) as usize / heap.inc + slot as usize; + if idx >= heap.count { + return None; + } + let cpu = heap.cpu + idx * heap.inc; + let d = match s.descs.get(&cpu) { + Some(e) => e.d.clone(), + None => unsafe { desc_bytes(cpu, heap.inc) }.and_then(|b| s.by_bytes.get(&b).cloned())?, + }; + match d { + Desc::Srv { res, desc } => { + let u = |o: usize| desc.map(|d| u32::from_le_bytes(d[o..o + 4].try_into().unwrap())).unwrap_or(0); + Some((res, u(4), u(8))) + } + _ => None, + } + }) +} + +pub fn table_srv_fmt(list: usize, compute: bool, param: u32, slot: u32) -> Option<(usize, u32, u32, u32)> { + with(|s| { + let h = *s.tables.get(&(list, compute))?.get(param as usize)?; + if h == 0 { + return None; + } + let heap = s.heaps.iter().find(|x| x.gpu != 0 && x.inc != 0 && h >= x.gpu && h < x.gpu + (x.count * x.inc) as u64)?; + let idx = (h - heap.gpu) as usize / heap.inc + slot as usize; + if idx >= heap.count { + return None; + } + let cpu = heap.cpu + idx * heap.inc; + let d = match s.descs.get(&cpu) { + Some(e) => e.d.clone(), + None => unsafe { desc_bytes(cpu, heap.inc) }.and_then(|b| s.by_bytes.get(&b).cloned())?, + }; + match d { + Desc::Srv { res, desc } => { + let u = |o: usize| desc.map(|d| u32::from_le_bytes(d[o..o + 4].try_into().unwrap())).unwrap_or(0); + Some((res, u(0), u(4), u(8))) + } + _ => None, + } + }) +} + +pub fn table_uav(list: usize, compute: bool, param: u32, slot: u32) -> Option<(usize, Option<[u8; 40]>)> { + with(|s| { + let h = *s.tables.get(&(list, compute))?.get(param as usize)?; + if h == 0 { + return None; + } + let heap = s.heaps.iter().find(|x| x.gpu != 0 && x.inc != 0 && h >= x.gpu && h < x.gpu + (x.count * x.inc) as u64)?; + let idx = (h - heap.gpu) as usize / heap.inc + slot as usize; + if idx >= heap.count { + return None; + } + let cpu = heap.cpu + idx * heap.inc; + let d = match s.descs.get(&cpu) { + Some(e) => e.d.clone(), + None => unsafe { desc_bytes(cpu, heap.inc) }.and_then(|b| s.by_bytes.get(&b).cloned())?, + }; + match d { + Desc::Uav { res, desc } => Some((res, desc)), + _ => None, + } + }) +} + +pub fn uav_view_text(desc: Option<[u8; 40]>) -> String { + let Some(d) = desc else { return "default view (null desc)".to_string() }; + let u = |o: usize| u32::from_le_bytes(d[o..o + 4].try_into().unwrap()); + let (fmt, dim) = (u(0), u(4)); + match dim { + 4 => format!("fmt={fmt} Texture2D MipSlice={} PlaneSlice={}", u(8), u(12)), + 5 => format!("fmt={fmt} Texture2DArray MipSlice={} First={} Size={} PlaneSlice={}", u(8), u(12), u(16), u(20)), + 3 => format!("fmt={fmt} Texture1DArray MipSlice={} First={} Size={}", u(8), u(12), u(16)), + 2 => format!("fmt={fmt} Texture1D MipSlice={}", u(8)), + 8 => format!("fmt={fmt} Texture3D MipSlice={} FirstW={} WSize={}", u(8), u(12), u(16)), + 1 => format!("fmt={fmt} Buffer first={} n={} stride={}", u64::from_le_bytes(d[8..16].try_into().unwrap()), u(16), u(20)), + _ => format!("fmt={fmt} ViewDimension={dim}"), + } +} + +pub fn table_count(list: usize, compute: bool) -> usize { + with(|s| s.tables.get(&(list, compute)).map_or(0, |t| t.len())) +} + pub unsafe fn dump(list: usize, compute: bool, name: &dyn Fn(usize) -> String) -> String { // Collect under the lock, read memory after it (Map may take driver locks). struct Item { @@ -383,6 +500,7 @@ pub unsafe fn dump(list: usize, compute: bool, name: &dyn Fn(usize) -> String) - /// None: no record written this frame (`age` frames old, or never recorded). d: Option, age: u32, + why: String, } let (items, frame) = with(|s| { let mut items = Vec::new(); @@ -393,6 +511,10 @@ pub unsafe fn dump(list: usize, compute: bool, name: &dyn Fn(usize) -> String) - } let Some(heap) = s.heaps.iter().find(|x| x.gpu != 0 && x.inc != 0 && h >= x.gpu && h < x.gpu + (x.count * x.inc) as u64) else { continue }; let first = (h - heap.gpu) as usize / heap.inc; + let hlo = heap.cpu; + let hhi = heap.cpu + heap.count * heap.inc; + let in_heap = s.descs.keys().filter(|&&k| k >= hlo && k < hhi).count(); + let mut why_once = true; // A table ends where the next table bound on this list begins (the title // allocates them back to back), or after 64 slots. let next = tables.iter().filter(|&&o| o > h && o < heap.gpu + (heap.count * heap.inc) as u64).min().copied(); @@ -402,13 +524,27 @@ pub unsafe fn dump(list: usize, compute: bool, name: &dyn Fn(usize) -> String) - break; } match s.descs.get(&(heap.cpu + (first + slot) * heap.inc)) { - Some(e) if s.frame.wrapping_sub(e.frame) <= 1 => items.push(Item { param, slot, d: Some(e.d.clone()), age: 0 }), - Some(e) => items.push(Item { param, slot, d: Some(e.d.clone()), age: s.frame.wrapping_sub(e.frame) }), + Some(e) if s.frame.wrapping_sub(e.frame) <= 1 => items.push(Item { param, slot, d: Some(e.d.clone()), age: 0, why: String::new() }), + Some(e) => items.push(Item { param, slot, d: Some(e.d.clone()), age: s.frame.wrapping_sub(e.frame), why: String::new() }), None => { - let found = unsafe { desc_bytes(heap.cpu + (first + slot) * heap.inc, heap.inc) }.and_then(|b| s.by_bytes.get(&b).cloned()); + let addr = heap.cpu + (first + slot) * heap.inc; + let raw = unsafe { desc_bytes(addr, heap.inc) }; + let found = raw.as_ref().and_then(|b| s.by_bytes.get(b).cloned()); match found { - Some(d) => items.push(Item { param, slot, d: Some(d), age: 0 }), - None => items.push(Item { param, slot, d: None, age: u32::MAX }), + Some(d) => items.push(Item { param, slot, d: Some(d), age: 0, why: String::new() }), + None => { + let why = if why_once { + why_once = false; + let bytes = match &raw { + Some(v) => format!("bytes {} not among {} recorded byte patterns", v.iter().take(16).map(|x| format!("{x:02x}")).collect::(), s.by_bytes.len()), + None => "bytes unreadable or all zero".to_string(), + }; + format!(" [table gpu {h:#x} -> heap cpu {:#x} gpu {:#x} inc {} count {}; slot cpu {addr:#x}; {in_heap} of {} recorded descriptors lie in this heap; {bytes}]", heap.cpu, heap.gpu, heap.inc, heap.count, s.descs.len()) + } else { + String::new() + }; + items.push(Item { param, slot, d: None, age: u32::MAX, why }) + } } } } @@ -421,8 +557,8 @@ pub unsafe fn dump(list: usize, compute: bool, name: &dyn Fn(usize) -> String) - for it in items { let Some(d) = it.d.clone() else { if it.age == u32::MAX { - out.push_str(&format!(" param[{}]+{} (no descriptor recorded) -", it.param, it.slot)); + out.push_str(&format!(" param[{}]+{} (no descriptor recorded){} +", it.param, it.slot, it.why)); } continue; }; @@ -471,7 +607,17 @@ pub unsafe fn dump(list: usize, compute: bool, name: &dyn Fn(usize) -> String) - }; let aged = if it.age > 1 { format!(" (written {} frames ago)", it.age) } else { String::new() }; let st = crate::rtcap::state_of(res).or_else(|| Some(crate::gpu_va::state(res)).filter(|&x| x != 0)).map(|x| format!(" state={x:#x}")).unwrap_or_default(); - out.push_str(&format!(" param[{}]+{} {kind} {what} | {view}{aged}{st}\n", it.param, it.slot)); + let loc = if res == 0 { + String::new() + } else if let Some(p) = crate::placed::lookup(res as *mut c_void) { + format!(" placed title va={:#x} {}x{} dim={}", p.va, p.width(), p.height(), p.dim()) + } else if let Some(v) = crate::gpu_va::texture_va(res) { + format!(" texture va={v:#x}") + } else { + " not placed".to_string() + }; + let fu = if res == 0 { String::new() } else { crate::firstuse::describe(res) }; + out.push_str(&format!(" param[{}]+{} {kind} {what} | {view}{aged}{st}{loc}{fu}\n", it.param, it.slot)); } Desc::Sampler { desc } => { let u = |o: usize| u32::from_le_bytes(desc[o..o + 4].try_into().unwrap()); diff --git a/crates/compat/d3d12_xs/src/bl_alias.rs b/crates/compat/d3d12_xs/src/bl_alias.rs index 04ed36ca..77949e36 100644 --- a/crates/compat/d3d12_xs/src/bl_alias.rs +++ b/crates/compat/d3d12_xs/src/bl_alias.rs @@ -31,7 +31,17 @@ pub fn add_aliases(body: &[u8]) -> Result>, String> { let (nr, ro) = (rd(body, payload)? as usize, rd(body, payload + 4)? as usize); let mut ranges: Vec> = Vec::with_capacity(nr); let mut extra: Vec> = Vec::new(); + let mut have: Vec<(u32, u32, u32)> = Vec::with_capacity(nr); let mut next = 0u32; + for r in 0..nr { + let ra = ro + r * rs; + let d = body.get(ra..ra + rs).ok_or("RTS0 range out of bounds")?; + let (ty, num, space, off) = (rd(d, 0)?, rd(d, 4)?, rd(d, 12)?, rd(d, rs - 4)?); + let start = if off == u32::MAX { next } else { off }; + next = start.saturating_add(num); + have.push((ty, space, start)); + } + next = 0; for r in 0..nr { let ra = ro + r * rs; let d = body.get(ra..ra + rs).ok_or("RTS0 range out of bounds")?.to_vec(); @@ -40,6 +50,9 @@ pub fn add_aliases(body: &[u8]) -> Result>, String> { next = start.saturating_add(num); if (ty == RANGE_SRV || ty == RANGE_UAV) && space < 100_000 && start != u32::MAX { for k in 1..=BL_ALIASES { + if have.contains(&(ty, bl_alias_space(k, space), start)) { + continue; + } let mut a = d.clone(); wr(&mut a, 12, bl_alias_space(k, space)); wr(&mut a, rs - 4, start); @@ -133,6 +146,29 @@ mod tests { assert!(add_aliases(&no).unwrap().is_none()); } + #[test] + fn aliasing_an_already_aliased_root_signature_changes_nothing() { + let rs = 24; + let mut b = vec![0u8; 24 + 12 + 8 + 2 * rs]; + let w = |b: &mut Vec, o: usize, v: u32| b[o..o + 4].copy_from_slice(&v.to_le_bytes()); + w(&mut b, 0, 2); + w(&mut b, 4, 1); + w(&mut b, 8, 24); + w(&mut b, 32, 36); + w(&mut b, 36, 2); + w(&mut b, 40, 44); + for (k, r) in [[1u32, 4, 0, 0, 0, 0], [0, u32::MAX, 0, 5, 0, u32::MAX]].iter().enumerate() { + for (i, v) in r.iter().enumerate() { + w(&mut b, 44 + k * rs + i * 4, *v); + } + } + let once = add_aliases(&b).unwrap().unwrap(); + assert!(add_aliases(&once).unwrap().is_none(), "a second pass must not add duplicate alias ranges"); + let p = tombox_xshader::meta::parse_rts0(&once).unwrap(); + let tombox_xshader::meta::RootParamKind::Table(r) = &p.params[0].kind else { panic!() }; + assert_eq!(r.len(), 2 + 2 * BL_ALIASES as usize); + } + #[test] fn dxbc_container_is_rebuilt_around_the_new_rts0() { let mut blob = Vec::new(); diff --git a/crates/compat/d3d12_xs/src/blend_probe.rs b/crates/compat/d3d12_xs/src/blend_probe.rs new file mode 100644 index 00000000..a9d02fc2 --- /dev/null +++ b/crates/compat/d3d12_xs/src/blend_probe.rs @@ -0,0 +1,307 @@ +use core::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::OnceLock; + +use compat_common::record; + +use crate::device_wrap::Guid; + +const IID_QUEUE: Guid = Guid { d1: 0x0ec8_70a6, d2: 0x5d7e, d3: 0x4c22, d4: [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed] }; +const IID_ALLOCATOR: Guid = Guid { d1: 0x6102_dee4, d2: 0xaf59, d3: 0x4b09, d4: [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24] }; +const IID_LIST: Guid = Guid { d1: 0x5b16_0d0f, d2: 0xac1b, d3: 0x4185, d4: [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55] }; +const IID_RESOURCE: Guid = Guid { d1: 0x6964_42be, d2: 0xa72e, d3: 0x4059, d4: [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad] }; +const IID_FENCE: Guid = Guid { d1: 0x0a75_3dcf, d2: 0xc4d8, d3: 0x4b91, d4: [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76] }; +const IID_ROOT_SIGNATURE: Guid = Guid { d1: 0xc54a_6b66, d2: 0x72df, d3: 0x4ee8, d4: [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14] }; +const IID_PSO: Guid = Guid { d1: 0x765a_30f3, d2: 0xf624, d3: 0x4c6f, d4: [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45] }; +const IID_DESC_HEAP: Guid = Guid { d1: 0x8efb_471d, d2: 0x616c, d3: 0x4f49, d4: [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51] }; + +const VERSION: u32 = 1; +const SIDE: u32 = 8; +const PITCH: u32 = 256; +const ST_RT: u32 = 4; +const ST_COPY_SOURCE: u32 = 0x800; +const ST_COPY_DEST: u32 = 0x400; +const FMT_RGBA16F: u32 = 10; +const FMT_R11G11B10: u32 = 26; + +const RS: &str = "#define RS \"RootFlags(0), RootConstants(num32BitConstants=4, b0)\"\n"; +const VS: &str = "[RootSignature(RS)]\nfloat4 main(uint id : SV_VertexID) : SV_Position { float2 p = float2((id << 1) & 2, id & 2); return float4(p * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); }\n"; +const PS: &str = "cbuffer C : register(b0) { float4 c; };\nfloat4 main() : SV_Target { return c; }\n"; + +static DEVICE: AtomicUsize = AtomicUsize::new(0); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Overflow { + Saturates, + Inf, +} + +pub fn note_device(real: *mut c_void) { + if !real.is_null() { + let _ = DEVICE.compare_exchange(0, real as usize, Ordering::AcqRel, Ordering::Relaxed); + } +} + +pub fn cache_line(adapter: &str, o: Overflow) -> String { + format!("v{VERSION} {} {adapter}", match o { Overflow::Saturates => "saturates", Overflow::Inf => "inf" }) +} + +pub fn parse_cache(text: &str, adapter: &str) -> Option { + text.lines().find_map(|l| { + let mut it = l.splitn(3, ' '); + let (v, o, a) = (it.next()?, it.next()?, it.next()?); + if v != format!("v{VERSION}") || a != adapter { + return None; + } + match o { + "saturates" => Some(Overflow::Saturates), + "inf" => Some(Overflow::Inf), + _ => None, + } + }) +} + +pub fn classify(fmt: u32, px: &[u8]) -> Option { + let r = if fmt == FMT_RGBA16F { + u16::from_le_bytes([*px.first()?, *px.get(1)?]) as u32 + } else { + u32::from_le_bytes(px.get(0..4)?.try_into().ok()?) & 0x7ff + }; + match (fmt, r) { + (FMT_RGBA16F, 0x7bff) | (FMT_R11G11B10, 0x7bf) => Some(Overflow::Saturates), + (FMT_RGBA16F, 0x7c00) | (FMT_R11G11B10, 0x7c0) => Some(Overflow::Inf), + _ => None, + } +} + +pub fn overflow() -> Option { + static R: OnceLock> = OnceLock::new(); + *R.get_or_init(|| { + let dev = DEVICE.load(Ordering::Acquire); + if dev == 0 { + record("d3d12_xs", "blend_probe", "no device yet when the blend overflow probe was first needed; eager blendclamp kept"); + return None; + } + let adapter = tombox_xshader::fma_probe::probe().adapter.clone(); + let file = tombox_xshader::shader_cache::root().join("blend_probe.txt"); + let text = std::fs::read_to_string(&file).unwrap_or_default(); + if let Some(o) = parse_cache(&text, &adapter) { + record("d3d12_xs", "blend_probe", &format!("{adapter}: blend overflow {o:?} (cached in {})", file.display())); + return Some(o); + } + let t0 = std::time::Instant::now(); + match unsafe { probe(dev as *mut c_void) } { + Ok(o) => { + record("d3d12_xs", "blend_probe", &format!("{adapter}: 40000+40000 additive into RGBA16F and R11G11B10 gives {o:?} (probed in {:.1} ms)", t0.elapsed().as_secs_f64() * 1000.0)); + let mut keep: Vec<&str> = text.lines().filter(|l| !l.ends_with(adapter.as_str())).collect(); + let line = cache_line(&adapter, o); + keep.push(&line); + let _ = std::fs::create_dir_all(file.parent().unwrap_or(std::path::Path::new("."))); + let _ = std::fs::write(&file, keep.join("\n") + "\n"); + Some(o) + } + Err(e) => { + record("d3d12_xs", "blend_probe", &format!("{adapter}: blend overflow probe failed ({e}); eager blendclamp kept")); + None + } + } + }) +} + +unsafe fn slot(o: usize, i: usize) -> usize { + unsafe { *(*(o as *const *const usize)).add(i) } +} + +macro_rules! vc { + ($o:expr, $i:expr, fn($($t:ty),*) -> $r:ty $(, $a:expr)*) => {{ + let o = $o as usize; + let f: unsafe extern "system" fn(*mut c_void $(, $t)*) -> $r = core::mem::transmute(slot(o, $i)); + f(o as *mut c_void $(, $a)*) + }}; +} + +struct Bag(Vec); + +impl Bag { + fn keep(&mut self, o: usize) -> usize { + self.0.push(o); + o + } +} + +impl Drop for Bag { + fn drop(&mut self) { + for &o in self.0.iter().rev() { + if o != 0 { + unsafe { vc!(o, 2, fn() -> u32) }; + } + } + } +} + +fn check(hr: i32, p: *mut c_void, what: &str) -> Result { + if hr < 0 || p.is_null() { Err(format!("{what} hr={hr:#010x}")) } else { Ok(p as usize) } +} + +unsafe fn committed(dev: usize, heap: u32, dim: u32, w: u64, fmt: u32, flags: u32, state: u32) -> Result { + let props: [u32; 5] = [heap, 0, 0, 1, 1]; + let mut d = [0u8; 56]; + let h = if dim == 1 { 1u32 } else { SIDE }; + d[0..4].copy_from_slice(&dim.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&w.to_le_bytes()); + d[0x18..0x1c].copy_from_slice(&h.to_le_bytes()); + d[0x1c..0x1e].copy_from_slice(&1u16.to_le_bytes()); + d[0x1e..0x20].copy_from_slice(&1u16.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2c..0x30].copy_from_slice(&(if dim == 1 { 1u32 } else { 0 }).to_le_bytes()); + d[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + let mut clear = [0u8; 24]; + clear[0..4].copy_from_slice(&fmt.to_le_bytes()); + let cv = if dim == 1 { core::ptr::null() } else { clear.as_ptr() }; + let mut r: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { vc!(dev, 27, fn(*const u32, u32, *const u8, u32, *const u8, *const Guid, *mut *mut c_void) -> i32, props.as_ptr(), 0, d.as_ptr(), state, cv, &IID_RESOURCE, &mut r) }; + check(hr, r, "CreateCommittedResource") +} + +pub unsafe fn probe(dev: *mut c_void) -> Result { + if !tombox_xshader::dxc::available() { + return Err("DXC not available".into()); + } + let vs = tombox_xshader::dxc::compile(&format!("{RS}{VS}"), "vs_6_0").map_err(|e| format!("vs: {e}"))?; + let ps = tombox_xshader::dxc::compile(PS, "ps_6_0").map_err(|e| format!("ps: {e}"))?; + let dev = dev as usize; + let mut bag = Bag(Vec::new()); + unsafe { + let qd = [0u32; 4]; + let mut queue: *mut c_void = core::ptr::null_mut(); + let queue = bag.keep(check(vc!(dev, 8, fn(*const u32, *const Guid, *mut *mut c_void) -> i32, qd.as_ptr(), &IID_QUEUE, &mut queue), queue, "CreateCommandQueue")?); + let mut alloc: *mut c_void = core::ptr::null_mut(); + let alloc = bag.keep(check(vc!(dev, 9, fn(u32, *const Guid, *mut *mut c_void) -> i32, 0, &IID_ALLOCATOR, &mut alloc), alloc, "CreateCommandAllocator")?); + let mut list: *mut c_void = core::ptr::null_mut(); + let list = bag.keep(check(vc!(dev, 12, fn(u32, u32, *mut c_void, *mut c_void, *const Guid, *mut *mut c_void) -> i32, 0, 0, alloc as *mut c_void, core::ptr::null_mut(), &IID_LIST, &mut list), list, "CreateCommandList")?); + let mut fence: *mut c_void = core::ptr::null_mut(); + let fence = bag.keep(check(vc!(dev, 36, fn(u64, u32, *const Guid, *mut *mut c_void) -> i32, 0, 0, &IID_FENCE, &mut fence), fence, "CreateFence")?); + let mut rs: *mut c_void = core::ptr::null_mut(); + let rs = bag.keep(check(vc!(dev, 16, fn(u32, *const u8, usize, *const Guid, *mut *mut c_void) -> i32, 0, vs.as_ptr(), vs.len(), &IID_ROOT_SIGNATURE, &mut rs), rs, "CreateRootSignature")?); + let hd = [2u32, 2, 0, 0]; + let mut heap: *mut c_void = core::ptr::null_mut(); + let heap = bag.keep(check(vc!(dev, 14, fn(*const u32, *const Guid, *mut *mut c_void) -> i32, hd.as_ptr(), &IID_DESC_HEAP, &mut heap), heap, "CreateDescriptorHeap")?); + let mut base = 0usize; + vc!(heap, 9, fn(*mut usize) -> *mut usize, &mut base); + let inc = vc!(dev, 15, fn(u32) -> u32, 2) as usize; + let fmts = [FMT_RGBA16F, FMT_R11G11B10]; + let mut targets = Vec::new(); + for (i, &fmt) in fmts.iter().enumerate() { + let rt = bag.keep(committed(dev, 1, 3, SIDE as u64, fmt, 1, ST_RT)?); + let rb = bag.keep(committed(dev, 3, 1, (PITCH * SIDE) as u64, 0, 0, ST_COPY_DEST)?); + let mut d = vec![0u8; 0x290]; + d[0..8].copy_from_slice(&(rs as u64).to_le_bytes()); + d[0x08..0x10].copy_from_slice(&(vs.as_ptr() as u64).to_le_bytes()); + d[0x10..0x18].copy_from_slice(&(vs.len() as u64).to_le_bytes()); + d[0x18..0x20].copy_from_slice(&(ps.as_ptr() as u64).to_le_bytes()); + d[0x20..0x28].copy_from_slice(&(ps.len() as u64).to_le_bytes()); + for (o, v) in [(0x80usize, 1u32), (0x88, 2), (0x8c, 2), (0x90, 1), (0x94, 2), (0x98, 2), (0x9c, 1), (0x1c0, u32::MAX), (0x1c4, 3), (0x1c8, 1), (0x1dc, 1), (0x23c, 3), (0x240, 1), (0x244, fmt), (0x268, 1)] { + d[o..o + 4].copy_from_slice(&v.to_le_bytes()); + } + d[0xa4] = 0xf; + let mut pso: *mut c_void = core::ptr::null_mut(); + let pso = bag.keep(check(vc!(dev, 10, fn(*const u8, *const Guid, *mut *mut c_void) -> i32, d.as_ptr(), &IID_PSO, &mut pso), pso, "CreateGraphicsPipelineState")?); + let rtv = base + i * inc; + vc!(dev, 20, fn(*mut c_void, *const c_void, usize) -> (), rt as *mut c_void, core::ptr::null(), rtv); + targets.push((fmt, rt, rb, pso, rtv)); + } + let l = list; + let barrier = |res: usize, a: u32, b: u32| { + let mut e = [0u8; 32]; + e[8..16].copy_from_slice(&(res as u64).to_le_bytes()); + e[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + e[20..24].copy_from_slice(&a.to_le_bytes()); + e[24..28].copy_from_slice(&b.to_le_bytes()); + vc!(l, 26, fn(u32, *const u8) -> (), 1, e.as_ptr()); + }; + let vp = [0f32, 0.0, SIDE as f32, SIDE as f32, 0.0, 1.0]; + let sc = [0i32, 0, SIDE as i32, SIDE as i32]; + let c = [40000.0f32, 40000.0, 40000.0, 1.0]; + for &(fmt, rt, rb, pso, rtv) in &targets { + vc!(l, 48, fn(usize, *const f32, u32, *const c_void) -> (), rtv, [0f32; 4].as_ptr(), 0, core::ptr::null()); + vc!(l, 46, fn(u32, *const usize, i32, *const usize) -> (), 1, &rtv, 0, core::ptr::null()); + vc!(l, 21, fn(u32, *const f32) -> (), 1, vp.as_ptr()); + vc!(l, 22, fn(u32, *const i32) -> (), 1, sc.as_ptr()); + vc!(l, 30, fn(*mut c_void) -> (), rs as *mut c_void); + vc!(l, 25, fn(*mut c_void) -> (), pso as *mut c_void); + vc!(l, 20, fn(u32) -> (), 4); + vc!(l, 36, fn(u32, u32, *const f32, u32) -> (), 0, 4, c.as_ptr(), 0); + vc!(l, 12, fn(u32, u32, u32, u32) -> (), 3, 1, 0, 0); + vc!(l, 12, fn(u32, u32, u32, u32) -> (), 3, 1, 0, 0); + barrier(rt, ST_RT, ST_COPY_SOURCE); + let mut dst = [0u8; 48]; + dst[0..8].copy_from_slice(&(rb as u64).to_le_bytes()); + dst[8..12].copy_from_slice(&1u32.to_le_bytes()); + for (o, v) in [(24usize, fmt), (28, SIDE), (32, SIDE), (36, 1), (40, PITCH)] { + dst[o..o + 4].copy_from_slice(&v.to_le_bytes()); + } + let mut src = [0u8; 48]; + src[0..8].copy_from_slice(&(rt as u64).to_le_bytes()); + vc!(l, 16, fn(*const u8, u32, u32, u32, *const u8, *const c_void) -> (), dst.as_ptr(), 0, 0, 0, src.as_ptr(), core::ptr::null()); + barrier(rt, ST_COPY_SOURCE, ST_RT); + } + let hr = vc!(l, 9, fn() -> i32); + if hr < 0 { + return Err(format!("Close hr={hr:#010x}")); + } + let lists = [list]; + vc!(queue, 10, fn(u32, *const usize) -> (), 1, lists.as_ptr()); + if vc!(queue, 14, fn(*mut c_void, u64) -> i32, fence as *mut c_void, 1) < 0 { + return Err("Signal failed".into()); + } + let t0 = std::time::Instant::now(); + while vc!(fence, 8, fn() -> u64) < 1 { + if t0.elapsed().as_millis() > 2000 { + core::mem::forget(bag); + return Err("GPU did not finish within 2 s (objects leaked rather than freed in flight)".into()); + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let mut verdicts = Vec::new(); + for &(fmt, _, rb, _, _) in &targets { + let mut m: *mut u8 = core::ptr::null_mut(); + if vc!(rb, 8, fn(u32, *const c_void, *mut *mut u8) -> i32, 0, core::ptr::null(), &mut m) < 0 || m.is_null() { + return Err("readback Map failed".into()); + } + let bpp = if fmt == FMT_RGBA16F { 8 } else { 4 }; + let off = (SIDE / 2 * PITCH + SIDE / 2 * bpp) as usize; + let px = core::slice::from_raw_parts(m.add(off), bpp as usize).to_vec(); + vc!(rb, 9, fn(u32, *const c_void) -> (), 0, core::ptr::null()); + match classify(fmt, &px) { + Some(o) => verdicts.push(o), + None => return Err(format!("fmt {fmt}: unexpected result {px:02x?}")), + } + } + Ok(if verdicts.iter().all(|&o| o == Overflow::Saturates) { Overflow::Saturates } else { Overflow::Inf }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cache_lines_round_trip_per_adapter_and_version() { + let a = "NVIDIA X [10de:2d05] driver 32.0.16.1742"; + let text = format!("{}\n{}\n", cache_line("other", Overflow::Inf), cache_line(a, Overflow::Saturates)); + assert_eq!(parse_cache(&text, a), Some(Overflow::Saturates)); + assert_eq!(parse_cache(&text, "other"), Some(Overflow::Inf)); + assert_eq!(parse_cache(&text, "NVIDIA X [10de:2d05] driver 32.0.16.1800"), None); + assert_eq!(parse_cache(&format!("v0 saturates {a}"), a), None); + } + + #[test] + fn results_classify_by_format() { + assert_eq!(classify(10, &[0xff, 0x7b, 0, 0, 0, 0, 0, 0]), Some(Overflow::Saturates)); + assert_eq!(classify(10, &[0x00, 0x7c, 0, 0, 0, 0, 0, 0]), Some(Overflow::Inf)); + assert_eq!(classify(26, &0x7bfu32.to_le_bytes()), Some(Overflow::Saturates)); + assert_eq!(classify(26, &0x7c0u32.to_le_bytes()), Some(Overflow::Inf)); + assert_eq!(classify(26, &0x3c0u32.to_le_bytes()), None); + } +} diff --git a/crates/compat/d3d12_xs/src/blendclamp.rs b/crates/compat/d3d12_xs/src/blendclamp.rs index 1ea687c8..7f9b3f53 100644 --- a/crates/compat/d3d12_xs/src/blendclamp.rs +++ b/crates/compat/d3d12_xs/src/blendclamp.rs @@ -22,16 +22,171 @@ struct ListState { scissors: Vec<[i32; 4]>, topo: Option, dirty: Vec<(usize, u32, u32)>, + lazy: Vec, } +#[derive(Clone, Copy, PartialEq, Debug)] +struct Lazy { + res: usize, + view: Option<[u8; 24]>, + fmt: u32, + samples: u32, +} + +#[derive(Debug, PartialEq)] +enum Sel { + None, + All, + Only(Vec), +} + +type View = (usize, Option<[u8; 24]>); + +const IID_DESC_HEAP: Guid = Guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); +const ST_RENDER_TARGET: u32 = 4; + static LISTS: Mutex>> = Mutex::new(None); +static RTVS: Mutex>> = Mutex::new(None); +static OWN_RTV: Mutex>> = Mutex::new(None); +static LAZY_PASSES: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0); +#[cfg(test)] +static TEST_LAZY: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0); +#[cfg(test)] +static TEST_PS: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0); +#[cfg(test)] +static TEST_REAL: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); + +pub fn lazy() -> bool { + #[cfg(test)] + { + let t = TEST_LAZY.load(core::sync::atomic::Ordering::Relaxed); + if t != 0 { + return t == 2; + } + } + static L: OnceLock = OnceLock::new(); + *L.get_or_init(|| { + let on = std::env::var("TOMBOX_BLEND_CLAMP_LAZY").map(|v| v.trim() == "1").unwrap_or(false); + if on { + record("d3d12_xs", "blendclamp", "lazy clamping (TOMBOX_BLEND_CLAMP_LAZY=1): additive/min/max blends into a small-float target clamp once, when the target is read (a barrier out of RENDER_TARGET, a copy or resolve from it, or Close); blends whose factors read the destination still clamp at every boundary and before the draw"); + } + on + }) +} + +pub fn lazy_passes() -> u64 { + LAZY_PASSES.load(core::sync::atomic::Ordering::Relaxed) +} + +pub unsafe fn note_rtv(handle: usize, res: usize, pdesc: *const u8) { + if !lazy() || handle == 0 { + return; + } + let view = if pdesc.is_null() { + None + } else { + let mut v = [0u8; 24]; + unsafe { core::ptr::copy_nonoverlapping(pdesc, v.as_mut_ptr(), 24) }; + Some(v) + }; + let mut g = RTVS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + if res == 0 { + m.remove(&handle); + } else { + m.insert(handle, (res, view)); + } +} + +fn rtv_view(handle: usize) -> Option { + RTVS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(&handle).copied()) +} + +fn lazy_safe(d: &[u8], b: usize, fmt: u32) -> bool { + let u = |o: usize| u32::from_le_bytes(d[b + o..b + o + 4].try_into().unwrap()); + let reads_dst = |f: u32| matches!(f, 7..=11); + let ok = |src: u32, dst: u32, op: u32| match op { + 4 | 5 => true, + 1 => dst == 2 && !reads_dst(src), + _ => false, + }; + let alpha_used = fmt != 26 && d[b + 0x24] & 8 != 0; + ok(u(0x08), u(0x0c), u(0x10)) && (!alpha_used || ok(u(0x14), u(0x18), u(0x1c))) +} + +fn barrier_hits(b: &[u8], dirty: &[usize]) -> Sel { + if dirty.is_empty() { + return Sel::None; + } + let mut hit = Vec::new(); + for e in b.chunks_exact(32) { + let u = |o: usize| u32::from_le_bytes(e[o..o + 4].try_into().unwrap()); + let p = |o: usize| u64::from_le_bytes(e[o..o + 8].try_into().unwrap()) as usize; + match u(0) { + 0 => { + let r = p(8); + if u(20) & ST_RENDER_TARGET != 0 && u(24) & ST_RENDER_TARGET == 0 && dirty.contains(&r) { + hit.push(r); + } + } + 1 => { + let (a, z) = (p(8), p(16)); + if a == 0 || z == 0 { + return Sel::All; + } + hit.extend([a, z].into_iter().filter(|r| dirty.contains(r))); + } + 2 => { + let r = p(8); + if r != 0 && dirty.contains(&r) { + hit.push(r); + } + } + _ => return Sel::All, + } + } + hit.dedup(); + if hit.is_empty() { Sel::None } else { Sel::Only(hit) } +} static PSOS: Mutex>> = Mutex::new(None); static RTV_INC: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); static PASSES: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0); static LIVE: crate::live_sw::Armed = crate::live_sw::Armed::new("TOMBOX_BLEND_CLAMP", "blend_clamp", true); +pub fn ps_mode() -> bool { + #[cfg(test)] + { + let t = TEST_PS.load(core::sync::atomic::Ordering::Relaxed); + if t != 0 { + return t == 2; + } + } + static P: OnceLock = OnceLock::new(); + *P.get_or_init(|| { + let v = compat_common::live::value("TOMBOX_BLEND_CLAMP", "blend_clamp").map(|v| v.trim().to_ascii_lowercase()); + if v.as_deref() == Some("auto") { + let o = crate::blend_probe::overflow(); + let on = o == Some(crate::blend_probe::Overflow::Saturates); + record("d3d12_xs", "blendclamp", &if on { + "TOMBOX_BLEND_CLAMP=auto: this adapter saturates blend overflow like the console, so ps mode is used (shader-side Inf/NaN clamp, no full-target passes)".to_string() + } else { + format!("TOMBOX_BLEND_CLAMP=auto: blend overflow probe gave {o:?}, so the eager full-target clamp passes are kept") + }); + return on; + } + let on = v.as_deref() == Some("ps"); + if on { + record("d3d12_xs", "blendclamp", "TOMBOX_BLEND_CLAMP=ps: pixel shaders writing fp16 or R11G11B10 targets clamp their colour outputs to the largest finite value (NaN to +max, as the eager clamp pass gives), and the full-target clamp passes are off; needs export_fmt on (the default); read once at start, not live"); + } + on + }) +} + pub fn enabled() -> bool { + if ps_mode() { + return false; + } static E: OnceLock = OnceLock::new(); E.get_or_init(|| { let on = LIVE.armed(); @@ -142,11 +297,30 @@ pub fn on_draw(list: usize) { return; } let Some((d, _keep)) = crate::device_wrap::gfx_pso_desc(s.pso) else { return }; + let samples = u32::from_le_bytes(d[0x268..0x26c].try_into().unwrap()).max(1); + let lz = lazy(); + for (h, fmt, b) in blended_targets(&d, s) { + if lz && lazy_safe(&d, b, fmt) { + if let Some((res, view)) = rtv_view(h) { + let e = Lazy { res, view, fmt, samples }; + if !s.lazy.contains(&e) { + s.lazy.push(e); + } + continue; + } + } + if !s.dirty.iter().any(|e| e.0 == h) { + s.dirty.push((h, fmt, samples)); + } + } +} + +fn blended_targets(d: &[u8], s: &ListState) -> Vec<(usize, u32, usize)> { let u = |o: usize| u32::from_le_bytes(d[o..o + 4].try_into().unwrap()); let independent = u(0x7c) != 0; - let samples = u(0x268).max(1); let n = u(0x240).min(s.rt_count).min(8); let inc = RTV_INC.load(core::sync::atomic::Ordering::Relaxed); + let mut out = Vec::new(); for i in 0..n as usize { let fmt = u(0x244 + 4 * i); if small_float(fmt).is_none() { @@ -168,9 +342,52 @@ pub fn on_draw(list: usize) { None => continue, } }; - if h != 0 && !s.dirty.iter().any(|e| e.0 == h) { - s.dirty.push((h, fmt, samples)); + if h != 0 { + out.push((h, fmt, b)); + } + } + out +} + +unsafe fn pre_draw(list: *mut c_void) { + if !lazy() || !enabled() { + return; + } + let hit: Vec = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return }; + if s.lazy.is_empty() || s.pso == 0 || s.rt_count == 0 { + return; + } + let Some((d, _keep)) = crate::device_wrap::gfx_pso_desc(s.pso) else { return }; + let mut hit = Vec::new(); + for (h, fmt, b) in blended_targets(&d, s) { + if lazy_safe(&d, b, fmt) { + continue; + } + if let Some((res, _)) = rtv_view(h) { + if s.lazy.iter().any(|e| e.res == res) && !hit.contains(&res) { + hit.push(res); + } + } } + hit + }; + if !hit.is_empty() { + unsafe { flush_sel(list, false, Sel::Only(hit)) }; + } +} + +unsafe fn flush_reads(list: *mut c_void, src: usize) { + if src == 0 || !lazy() { + return; + } + let dirty = { + let g = LISTS.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.lazy.iter().any(|e| e.res == src)) + }; + if dirty { + unsafe { flush_sel(list, false, Sel::Only(vec![src])) }; } } @@ -184,12 +401,15 @@ pub unsafe fn install() { if !enabled() { return; } - let hooks: [(usize, usize); 12] = [ + let mut hooks: Vec<(usize, usize)> = vec![ (9, h_close as usize), (10, h_reset as usize), (12, h_draw as usize), (13, h_draw_indexed as usize), (20, h_topo as usize), (21, h_viewports as usize), (22, h_scissors as usize), (25, h_set_pso as usize), (26, h_barrier as usize), (34, h_root_sig as usize), (50, h_targets as usize), (59, h_indirect as usize), ]; - for (slot, _) in hooks { + if lazy() { + hooks.extend([(16, h_copy_texture as usize), (17, h_copy_resource as usize), (19, h_resolve as usize)]); + } + for &(slot, _) in &hooks { let prev = crate::cmdlist_wrap::vt_get(slot); if prev == 0 { record("d3d12_xs", "blendclamp", &format!("command-list slot {slot} empty - clamp hooks not installed")); @@ -202,6 +422,26 @@ pub unsafe fn install() { } } +unsafe extern "system" fn h_copy_texture(this: *mut c_void, dst: *const u8, x: u32, y: u32, z: u32, src: *const u8, b: *const c_void) { + if !src.is_null() { + unsafe { flush_reads(this, *(src as *const usize)) }; + } + let f: unsafe extern "system" fn(*mut c_void, *const u8, u32, u32, u32, *const u8, *const c_void) = unsafe { core::mem::transmute(next(16)) }; + unsafe { f(this, dst, x, y, z, src, b) } +} + +unsafe extern "system" fn h_copy_resource(this: *mut c_void, dst: *mut c_void, src: *mut c_void) { + unsafe { flush_reads(this, src as usize) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) = unsafe { core::mem::transmute(next(17)) }; + unsafe { f(this, dst, src) } +} + +unsafe extern "system" fn h_resolve(this: *mut c_void, dst: *mut c_void, dst_sub: u32, src: *mut c_void, src_sub: u32, fmt: u32) { + unsafe { flush_reads(this, src as usize) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u32, u32) = unsafe { core::mem::transmute(next(19)) }; + unsafe { f(this, dst, dst_sub, src, src_sub, fmt) } +} + unsafe extern "system" fn h_close(this: *mut c_void) -> i32 { unsafe { flush(this) }; let f: unsafe extern "system" fn(*mut c_void) -> i32 = unsafe { core::mem::transmute(next(9)) }; @@ -218,12 +458,14 @@ unsafe extern "system" fn h_reset(this: *mut c_void, alloc: *mut c_void, pso: *m } unsafe extern "system" fn h_draw(this: *mut c_void, a: u32, b: u32, c: u32, d: u32) { + unsafe { pre_draw(this) }; let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = unsafe { core::mem::transmute(next(12)) }; unsafe { f(this, a, b, c, d) }; on_draw(this as usize); } unsafe extern "system" fn h_draw_indexed(this: *mut c_void, a: u32, b: u32, c: u32, d: i32, e: u32) { + unsafe { pre_draw(this) }; let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32) = unsafe { core::mem::transmute(next(13)) }; unsafe { f(this, a, b, c, d, e) }; on_draw(this as usize); @@ -254,7 +496,13 @@ unsafe extern "system" fn h_set_pso(this: *mut c_void, pso: *mut c_void) { } unsafe extern "system" fn h_barrier(this: *mut c_void, n: u32, b: *const u8) { - unsafe { flush(this) }; + let sel = if b.is_null() || n == 0 { + Sel::None + } else { + let dirty: Vec = with(this as usize, |s| s.lazy.iter().map(|e| e.res).collect()); + barrier_hits(unsafe { core::slice::from_raw_parts(b, n.min(4096) as usize * 32) }, &dirty) + }; + unsafe { flush_sel(this, true, sel) }; let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(next(26)) }; unsafe { f(this, n, b) } } @@ -269,7 +517,7 @@ unsafe extern "system" fn h_root_sig(this: *mut c_void, rs: *mut c_void) { } unsafe extern "system" fn h_targets(this: *mut c_void, n: u32, handles: *const usize, single: i32, dsv: *const usize) { - unsafe { flush(this) }; + unsafe { flush_sel(this, true, Sel::None) }; if single != 0 && RTV_INC.load(core::sync::atomic::Ordering::Relaxed) == 0 { unsafe { device_of(this) }; } @@ -279,12 +527,20 @@ unsafe extern "system" fn h_targets(this: *mut c_void, n: u32, handles: *const u } unsafe extern "system" fn h_indirect(this: *mut c_void, sig: *mut c_void, n: u32, buf: *mut c_void, off: u64, cbuf: *mut c_void, coff: u64) { + unsafe { pre_draw(this) }; let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64) = unsafe { core::mem::transmute(next(59)) }; unsafe { f(this, sig, n, buf, off, cbuf, coff) }; on_draw(this as usize); } unsafe fn real(slot: usize) -> usize { + #[cfg(test)] + { + let p = TEST_REAL.load(core::sync::atomic::Ordering::Relaxed); + if p != 0 { + return unsafe { *(p as *const usize).add(slot) }; + } + } unsafe { crate::cmdlist_wrap::real_method(slot) } } @@ -369,16 +625,62 @@ unsafe fn clamp_pso(dev: *mut c_void, root_sig: usize, fmt: u32, samples: u32, n } pub unsafe fn flush(list: *mut c_void) { + unsafe { flush_sel(list, true, Sel::All) }; +} + +unsafe fn own_rtv(dev: *mut c_void, res: usize, view: &Option<[u8; 24]>, heaps: &mut HashMap) -> usize { + let vt = unsafe { *(dev as *const *const usize) }; + let h = match heaps.get(&(dev as usize)) { + Some(&h) => h, + None => { + let hd = [2u32, 1, 0, 0]; + let mut heap: *mut c_void = core::ptr::null_mut(); + let create: unsafe extern "system" fn(*mut c_void, *const u32, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(*vt.add(14)) }; + let hr = unsafe { create(dev, hd.as_ptr(), &IID_DESC_HEAP, &mut heap) }; + let mut h = 0usize; + if hr >= 0 && !heap.is_null() { + let start: unsafe extern "system" fn(*mut c_void, *mut usize) -> *mut usize = unsafe { core::mem::transmute(*(*(heap as *const *const usize)).add(9)) }; + unsafe { start(heap, &mut h) }; + } else { + record("d3d12_xs", "blendclamp", &format!("lazy clamp RTV heap create failed hr={hr:#010x}; lazy targets are left unclamped")); + } + heaps.insert(dev as usize, h); + h + } + }; + if h != 0 { + let rtv: unsafe extern "system" fn(*mut c_void, usize, *const u8, usize) = unsafe { core::mem::transmute(*vt.add(20)) }; + unsafe { rtv(dev, res, view.as_ref().map_or(core::ptr::null(), |v| v.as_ptr()), h) }; + } + h +} + +unsafe fn flush_sel(list: *mut c_void, eager: bool, sel: Sel) { + let _ij = crate::inject::mark(crate::inject::DRAW); if !enabled() { return; } let (dirty, pso, root_sig, rtv, rt_count, single, dsv, vps, scs, topo) = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return }; - if s.dirty.is_empty() { + let mut t: Vec<(Option, View, u32, u32)> = Vec::new(); + if eager { + t.extend(core::mem::take(&mut s.dirty).into_iter().map(|(h, f, n)| (Some(h), (0, None), f, n))); + } + let picked: Vec = match sel { + Sel::None => Vec::new(), + Sel::All => core::mem::take(&mut s.lazy), + Sel::Only(r) => { + let (hit, keep): (Vec, Vec) = core::mem::take(&mut s.lazy).into_iter().partition(|e| r.contains(&e.res)); + s.lazy = keep; + hit + } + }; + t.extend(picked.into_iter().map(|e| (None, (e.res, e.view), e.fmt, e.samples))); + if t.is_empty() { return; } - (core::mem::take(&mut s.dirty), s.pso, s.root_sig, s.rtv.clone(), s.rt_count, s.single, s.dsv, s.viewports.clone(), s.scissors.clone(), s.topo) + (t, s.pso, s.root_sig, s.rtv.clone(), s.rt_count, s.single, s.dsv, s.viewports.clone(), s.scissors.clone(), s.topo) }; if root_sig == 0 { return; @@ -396,17 +698,44 @@ pub unsafe fn flush(list: *mut c_void) { let vp = [0.0f32, 0.0, 16384.0, 16384.0, 0.0, 1.0]; let sc = [0i32, 0, 16384, 16384]; let mut did = false; - for (h, fmt, samples) in dirty { + for (handle, view, fmt, samples) in dirty { let neg_too = small_float(fmt) == Some(true); let passes: &[bool] = if neg_too { &[false, true] } else { &[false] }; + let mut bound = false; for &neg in passes { let p = unsafe { clamp_pso(dev, root_sig, fmt, samples, neg) }; if p == 0 { continue; } + if !did { + unsafe { crate::gpuprof::pass_begin(list, crate::gpuprof::TAG_BLENDCLAMP) }; + } + if !bound { + let ok = match handle { + Some(h) => { + unsafe { om(list, 1, &h, 0, core::ptr::null()) }; + true + } + None => { + let mut g = OWN_RTV.lock().unwrap_or_else(|e| e.into_inner()); + let h = unsafe { own_rtv(dev, view.0, &view.1, g.get_or_insert_with(HashMap::new)) }; + if h != 0 { + unsafe { om(list, 1, &h, 0, core::ptr::null()) }; + } + h != 0 + } + }; + if !ok { + break; + } + bound = true; + } + unsafe { set_pso(list, p) }; + if handle.is_none() { + LAZY_PASSES.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + } + let h = handle.unwrap_or(view.0); unsafe { - set_pso(list, p); - om(list, 1, &h, 0, core::ptr::null()); set_vp(list, 1, &vp); set_sc(list, 1, &sc); set_topo(list, 4); @@ -419,6 +748,7 @@ pub unsafe fn flush(list: *mut c_void) { } } if !did { + unsafe { crate::gpuprof::pass_end(list) }; return; } unsafe { @@ -436,5 +766,139 @@ pub unsafe fn flush(list: *mut c_void) { if let Some(t) = topo { set_topo(list, t); } + crate::gpuprof::pass_end(list); + } +} + +#[cfg(test)] +pub(crate) mod test_api { + use super::*; + use core::sync::atomic::Ordering::Relaxed; + + pub(crate) static LOCK: Mutex<()> = Mutex::new(()); + + pub(crate) unsafe fn wire(pc_vt: *const usize) { + TEST_REAL.store(pc_vt as usize, Relaxed); + for x in [9usize, 10, 12, 13, 16, 17, 19, 20, 21, 22, 25, 26, 34, 50, 59] { + let pc = crate::cmdlist_wrap::map_slot(x).unwrap(); + NEXT[x].store(unsafe { *pc_vt.add(pc) }, Relaxed); + } + } + + pub(crate) fn hook(x: usize) -> usize { + match x { + 9 => h_close as usize, + 10 => h_reset as usize, + 12 => h_draw as usize, + 13 => h_draw_indexed as usize, + 16 => h_copy_texture as usize, + 17 => h_copy_resource as usize, + 19 => h_resolve as usize, + 20 => h_topo as usize, + 21 => h_viewports as usize, + 22 => h_scissors as usize, + 25 => h_set_pso as usize, + 26 => h_barrier as usize, + 34 => h_root_sig as usize, + 50 => h_targets as usize, + 59 => h_indirect as usize, + _ => panic!("no blendclamp hook on slot {x}"), + } + } + + pub(crate) fn set_ps(on: bool) { + TEST_PS.store(if on { 2 } else { 1 }, Relaxed); + } + + pub(crate) fn set_lazy(on: bool) { + TEST_LAZY.store(if on { 2 } else { 1 }, Relaxed); + } + + pub(crate) fn reset() { + TEST_REAL.store(0, Relaxed); + TEST_LAZY.store(0, Relaxed); + TEST_PS.store(0, Relaxed); + *LISTS.lock().unwrap_or_else(|e| e.into_inner()) = None; + *PSOS.lock().unwrap_or_else(|e| e.into_inner()) = None; + *OWN_RTV.lock().unwrap_or_else(|e| e.into_inner()) = None; + *RTVS.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + + pub(crate) fn passes() -> u64 { + PASSES.load(Relaxed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn blend(src: u32, dst: u32, op: u32, srca: u32, dsta: u32, opa: u32, mask: u8) -> Vec { + let mut d = vec![0u8; 0x290]; + for (o, v) in [(0x80usize, 1u32), (0x88, src), (0x8c, dst), (0x90, op), (0x94, srca), (0x98, dsta), (0x9c, opa)] { + d[o..o + 4].copy_from_slice(&v.to_le_bytes()); + } + d[0xa4] = mask; + d + } + + fn transition(res: usize, before: u32, after: u32) -> [u8; 32] { + let mut e = [0u8; 32]; + e[8..16].copy_from_slice(&(res as u64).to_le_bytes()); + e[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + e[20..24].copy_from_slice(&before.to_le_bytes()); + e[24..28].copy_from_slice(&after.to_le_bytes()); + e + } + + #[test] + fn additive_min_and_max_blends_may_defer_their_clamp() { + assert!(lazy_safe(&blend(2, 2, 1, 2, 2, 1, 0xf), 0x80, 26)); + assert!(lazy_safe(&blend(5, 2, 1, 2, 2, 1, 0xf), 0x80, 10)); + assert!(lazy_safe(&blend(2, 2, 4, 2, 2, 5, 0xf), 0x80, 10)); + assert!(lazy_safe(&blend(2, 2, 1, 2, 6, 1, 0xf), 0x80, 26)); + } + + #[test] + fn blends_that_scale_or_subtract_the_destination_clamp_at_every_boundary() { + assert!(!lazy_safe(&blend(5, 6, 1, 2, 2, 1, 0xf), 0x80, 26)); + assert!(!lazy_safe(&blend(9, 2, 1, 2, 2, 1, 0xf), 0x80, 26)); + assert!(!lazy_safe(&blend(11, 2, 1, 2, 2, 1, 0xf), 0x80, 26)); + assert!(!lazy_safe(&blend(2, 2, 2, 2, 2, 1, 0xf), 0x80, 26)); + assert!(!lazy_safe(&blend(2, 2, 3, 2, 2, 1, 0xf), 0x80, 26)); + assert!(!lazy_safe(&blend(2, 2, 1, 2, 6, 1, 0xf), 0x80, 10)); + assert!(lazy_safe(&blend(2, 2, 1, 2, 6, 1, 0x7), 0x80, 10)); + } + + #[test] + fn only_a_barrier_that_takes_a_dirty_target_out_of_render_target_flushes_it() { + let dirty = [0x1000usize, 0x2000]; + let b = [transition(0x3000, 4, 0x80), transition(0x1000, 4, 4)]; + assert_eq!(barrier_hits(&b.concat(), &dirty), Sel::None); + let b = [transition(0x1000, 0x400, 4)]; + assert_eq!(barrier_hits(&b.concat(), &dirty), Sel::None); + let b = [transition(0x3000, 4, 0x80), transition(0x2000, 4, 0x80)]; + assert_eq!(barrier_hits(&b.concat(), &dirty), Sel::Only(vec![0x2000])); + assert_eq!(barrier_hits(&transition(0x2000, 4, 0x80), &[]), Sel::None); + } + + #[test] + fn aliasing_uav_and_unknown_barriers_are_handled_conservatively() { + let dirty = [0x1000usize]; + let mut a = [0u8; 32]; + a[0] = 1; + a[8..16].copy_from_slice(&0x1000u64.to_le_bytes()); + a[16..24].copy_from_slice(&0x5000u64.to_le_bytes()); + assert_eq!(barrier_hits(&a, &dirty), Sel::Only(vec![0x1000])); + a[8..16].fill(0); + assert_eq!(barrier_hits(&a, &dirty), Sel::All); + let mut u = [0u8; 32]; + u[0] = 2; + assert_eq!(barrier_hits(&u, &dirty), Sel::None); + u[8..16].copy_from_slice(&0x1000u64.to_le_bytes()); + assert_eq!(barrier_hits(&u, &dirty), Sel::Only(vec![0x1000])); + let mut x = [0u8; 32]; + x[0] = 7; + assert_eq!(barrier_hits(&x, &dirty), Sel::All); } } diff --git a/crates/compat/d3d12_xs/src/blendclamp_hw.rs b/crates/compat/d3d12_xs/src/blendclamp_hw.rs new file mode 100644 index 00000000..ebb75d95 --- /dev/null +++ b/crates/compat/d3d12_xs/src/blendclamp_hw.rs @@ -0,0 +1,540 @@ +use core::ffi::c_void; + +use crate::blendclamp::test_api; +use crate::device_wrap::Guid; + +const IID_DEVICE: Guid = Guid { d1: 0x1898_19f1, d2: 0x1db6, d3: 0x4b57, d4: [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7] }; +const IID_QUEUE: Guid = Guid { d1: 0x0ec8_70a6, d2: 0x5d7e, d3: 0x4c22, d4: [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed] }; +const IID_ALLOCATOR: Guid = Guid { d1: 0x6102_dee4, d2: 0xaf59, d3: 0x4b09, d4: [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24] }; +const IID_LIST: Guid = Guid { d1: 0x5b16_0d0f, d2: 0xac1b, d3: 0x4185, d4: [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55] }; +const IID_RESOURCE: Guid = Guid { d1: 0x6964_42be, d2: 0xa72e, d3: 0x4059, d4: [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad] }; +const IID_FENCE: Guid = Guid { d1: 0x0a75_3dcf, d2: 0xc4d8, d3: 0x4b91, d4: [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76] }; +const IID_ROOT_SIGNATURE: Guid = Guid { d1: 0xc54a_6b66, d2: 0x72df, d3: 0x4ee8, d4: [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14] }; +const IID_PSO: Guid = Guid { d1: 0x765a_30f3, d2: 0xf624, d3: 0x4c6f, d4: [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45] }; +const IID_DESC_HEAP: Guid = Guid { d1: 0x8efb_471d, d2: 0x616c, d3: 0x4f49, d4: [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51] }; +const IID_FACTORY4: Guid = Guid { d1: 0x1bc6_ea02, d2: 0xef36, d3: 0x464f, d4: [0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a] }; +const IID_ADAPTER: Guid = Guid { d1: 0x2411_e7e1, d2: 0x12ac, d3: 0x4ccf, d4: [0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0] }; + +const W: u32 = 64; +const H: u32 = 64; +const FMT_R11G11B10: u32 = 26; +const FMT_RGBA16F: u32 = 10; +const ST_RT: u32 = 4; +const ST_COPY_SOURCE: u32 = 0x800; +const ST_COPY_DEST: u32 = 0x400; +const PC_ROOT_CONSTANTS: usize = 36; +const PC_CLEAR_RTV: usize = 48; + +extern "system" { + fn LoadLibraryW(p: *const u16) -> *mut c_void; + fn GetProcAddress(h: *mut c_void, n: *const u8) -> *mut c_void; +} + +unsafe fn slot(o: usize, i: usize) -> usize { + unsafe { *(*(o as *const *const usize)).add(i) } +} + +macro_rules! vc { + ($o:expr, $i:expr, fn($($t:ty),*) -> $r:ty $(, $a:expr)*) => {{ + let o = $o as usize; + let f: unsafe extern "system" fn(*mut c_void $(, $t)*) -> $r = core::mem::transmute(slot(o, $i)); + f(o as *mut c_void $(, $a)*) + }}; +} + +unsafe fn warp_adapter() -> usize { + let name: Vec = "dxgi.dll\0".encode_utf16().collect(); + let h = unsafe { LoadLibraryW(name.as_ptr()) }; + assert!(!h.is_null()); + let p = unsafe { GetProcAddress(h, b"CreateDXGIFactory2\0".as_ptr()) }; + assert!(!p.is_null()); + let create: unsafe extern "system" fn(u32, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(p) }; + let mut f: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { create(0, &IID_FACTORY4, &mut f) } >= 0); + let mut a: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { vc!(f, 27, fn(*const Guid, *mut *mut c_void) -> i32, &IID_ADAPTER, &mut a) } >= 0); + a as usize +} + +unsafe fn committed(dev: usize, heap: u32, dim: u32, w: u64, h: u32, fmt: u32, flags: u32, state: u32) -> usize { + let props: [u32; 5] = [heap, 0, 0, 1, 1]; + let mut d = [0u8; 56]; + d[0..4].copy_from_slice(&dim.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&w.to_le_bytes()); + d[0x18..0x1c].copy_from_slice(&h.to_le_bytes()); + d[0x1c..0x1e].copy_from_slice(&1u16.to_le_bytes()); + d[0x1e..0x20].copy_from_slice(&1u16.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2c..0x30].copy_from_slice(&(if dim == 1 { 1u32 } else { 0 }).to_le_bytes()); + d[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + let mut clear = [0u8; 24]; + clear[0..4].copy_from_slice(&fmt.to_le_bytes()); + let cv = if dim == 1 { core::ptr::null() } else { clear.as_ptr() }; + let mut r: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { vc!(dev, 27, fn(*const u32, u32, *const u8, u32, *const u8, *const Guid, *mut *mut c_void) -> i32, props.as_ptr(), 0, d.as_ptr(), state, cv, &IID_RESOURCE, &mut r) }; + assert!(hr >= 0 && !r.is_null(), "CreateCommittedResource dim={dim} hr={hr:#010x}"); + r as usize +} + +const RS: &str = "#define RS \"RootFlags(0), RootConstants(num32BitConstants=4, b0)\"\n"; +const VS: &str = "[RootSignature(RS)]\nfloat4 main(uint id : SV_VertexID) : SV_Position { float2 p = float2((id << 1) & 2, id & 2); return float4(p * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); }\n"; +const PS: &str = "cbuffer C : register(b0) { float4 c; };\nfloat4 main() : SV_Target { return c; }\n"; + +struct Kit { + dev: usize, + queue: usize, + alloc: usize, + list: usize, + fence: usize, + value: u64, + rs: usize, + rt: usize, + rtv: usize, + aux: usize, + rb: usize, + pso: usize, + fmt: u32, +} + +unsafe fn rtv_for(dev: usize, res: usize) -> usize { + unsafe { + let hd = [2u32, 1, 0, 0]; + let mut heap: *mut c_void = core::ptr::null_mut(); + assert!(vc!(dev, 14, fn(*const u32, *const Guid, *mut *mut c_void) -> i32, hd.as_ptr(), &IID_DESC_HEAP, &mut heap) >= 0); + let mut h = 0usize; + vc!(heap, 9, fn(*mut usize) -> *mut usize, &mut h); + vc!(dev, 20, fn(*mut c_void, *const c_void, usize) -> (), res as *mut c_void, core::ptr::null(), h); + h + } +} + +fn bpp(fmt: u32) -> u32 { + if fmt == FMT_RGBA16F { 8 } else { 4 } +} + +unsafe fn kit(fmt: u32) -> Kit { + unsafe { kit_on(warp_adapter(), fmt, true) } +} + +unsafe fn kit_on(adapter: usize, fmt: u32, blend: bool) -> Kit { + unsafe { kit_with(adapter, fmt, blend, PS) } +} + +unsafe fn kit_with(adapter: usize, fmt: u32, blend: bool, ps_src: &str) -> Kit { + unsafe { + let p = crate::host_proc(b"D3D12CreateDevice\0"); + let create: extern "system" fn(usize, u32, *const Guid, *mut *mut c_void) -> i32 = core::mem::transmute(p); + let mut dev: *mut c_void = core::ptr::null_mut(); + let hr = create(adapter, 0xb000, &IID_DEVICE, &mut dev); + assert!(hr >= 0 && !dev.is_null(), "D3D12CreateDevice (adapter {adapter:#x}) hr={hr:#010x}"); + let dev = dev as usize; + let qd = [0u32; 4]; + let mut queue: *mut c_void = core::ptr::null_mut(); + assert!(vc!(dev, 8, fn(*const u32, *const Guid, *mut *mut c_void) -> i32, qd.as_ptr(), &IID_QUEUE, &mut queue) >= 0); + let mut alloc: *mut c_void = core::ptr::null_mut(); + assert!(vc!(dev, 9, fn(u32, *const Guid, *mut *mut c_void) -> i32, 0, &IID_ALLOCATOR, &mut alloc) >= 0); + let mut list: *mut c_void = core::ptr::null_mut(); + assert!(vc!(dev, 12, fn(u32, u32, *mut c_void, *mut c_void, *const Guid, *mut *mut c_void) -> i32, 0, 0, alloc, core::ptr::null_mut(), &IID_LIST, &mut list) >= 0); + assert!(vc!(list, 9, fn() -> i32) >= 0); + let mut fence: *mut c_void = core::ptr::null_mut(); + assert!(vc!(dev, 36, fn(u64, u32, *const Guid, *mut *mut c_void) -> i32, 0, 0, &IID_FENCE, &mut fence) >= 0); + let vs = tombox_xshader::dxc::compile(&format!("{RS}{VS}"), "vs_6_0").expect("vs"); + let ps = tombox_xshader::dxc::compile(ps_src, "ps_6_0").unwrap_or_else(|e| panic!("ps: {e}")); + let mut rs: *mut c_void = core::ptr::null_mut(); + assert!(vc!(dev, 16, fn(u32, *const u8, usize, *const Guid, *mut *mut c_void) -> i32, 0, vs.as_ptr(), vs.len(), &IID_ROOT_SIGNATURE, &mut rs) >= 0); + let rt = committed(dev, 1, 3, W as u64, H, fmt, 1, ST_RT); + let aux = committed(dev, 1, 3, W as u64, H, fmt, 1, ST_RT); + let rtv = rtv_for(dev, rt); + let rb = committed(dev, 3, 1, (W * bpp(fmt) * H) as u64, 1, 0, 0, ST_COPY_DEST); + let mut d = vec![0u8; 0x290]; + d[0..8].copy_from_slice(&(rs as u64).to_le_bytes()); + d[0x08..0x10].copy_from_slice(&(vs.as_ptr() as u64).to_le_bytes()); + d[0x10..0x18].copy_from_slice(&(vs.len() as u64).to_le_bytes()); + d[0x18..0x20].copy_from_slice(&(ps.as_ptr() as u64).to_le_bytes()); + d[0x20..0x28].copy_from_slice(&(ps.len() as u64).to_le_bytes()); + for (o, v) in [(0x80usize, blend as u32), (0x88, 2), (0x8c, 2), (0x90, 1), (0x94, 2), (0x98, 2), (0x9c, 1), (0xa0, 0), (0x1c0, u32::MAX), (0x1c4, 3), (0x1c8, 1), (0x1dc, 1), (0x23c, 3), (0x240, 1), (0x244, fmt), (0x268, 1)] { + d[o..o + 4].copy_from_slice(&v.to_le_bytes()); + } + d[0xa4] = 0xf; + let mut pso: *mut c_void = core::ptr::null_mut(); + let hr = vc!(dev, 10, fn(*const u8, *const Guid, *mut *mut c_void) -> i32, d.as_ptr(), &IID_PSO, &mut pso); + assert!(hr >= 0 && !pso.is_null(), "CreateGraphicsPipelineState hr={hr:#010x}"); + let shaders = vec![std::sync::Arc::new(vs.clone()), std::sync::Arc::new(ps.clone())]; + d[0x08..0x10].copy_from_slice(&(shaders[0].as_ptr() as u64).to_le_bytes()); + d[0x18..0x20].copy_from_slice(&(shaders[1].as_ptr() as u64).to_le_bytes()); + crate::device_wrap::register_gfx_pso(pso, d, shaders); + Kit { dev, queue: queue as usize, alloc: alloc as usize, list: list as usize, fence: fence as usize, value: 0, rs: rs as usize, rt, rtv, aux, rb, pso: pso as usize, fmt } + } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Mode { + Raw, + Eager, + Lazy, +} + +unsafe fn method(k: &Kit, mode: Mode, x: usize) -> usize { + if mode == Mode::Raw { + unsafe { slot(k.list, crate::cmdlist_wrap::map_slot(x).unwrap()) } + } else { + test_api::hook(x) + } +} + +unsafe fn transition(k: &Kit, mode: Mode, res: usize, before: u32, after: u32) { + let mut e = [0u8; 32]; + e[8..16].copy_from_slice(&(res as u64).to_le_bytes()); + e[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + e[20..24].copy_from_slice(&before.to_le_bytes()); + e[24..28].copy_from_slice(&after.to_le_bytes()); + let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(method(k, mode, 26)) }; + unsafe { f(k.list as *mut c_void, 1, e.as_ptr()) }; +} + +unsafe fn run(k: &mut Kit, mode: Mode) -> Vec<[u32; 4]> { + unsafe { run_adds(k, mode, [40000.0, f32::INFINITY, 40000.0]) } +} + +unsafe fn run_adds(k: &mut Kit, mode: Mode, adds: [f32; 3]) -> Vec<[u32; 4]> { + let l = k.list as *mut c_void; + unsafe { + assert!(vc!(k.alloc, 8, fn() -> i32) >= 0); + let reset: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> i32 = core::mem::transmute(method(k, mode, 10)); + assert!(reset(l, k.alloc as *mut c_void, core::ptr::null_mut()) >= 0); + vc!(l, PC_CLEAR_RTV, fn(usize, *const f32, u32, *const c_void) -> (), k.rtv, [0f32; 4].as_ptr(), 0, core::ptr::null()); + let targets: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = core::mem::transmute(method(k, mode, 50)); + targets(l, 1, &k.rtv, 0, core::ptr::null()); + let vp = [0f32, 0.0, W as f32, H as f32, 0.0, 1.0]; + let f: unsafe extern "system" fn(*mut c_void, u32, *const f32) = core::mem::transmute(method(k, mode, 21)); + f(l, 1, vp.as_ptr()); + let sc = [0i32, 0, W as i32, H as i32]; + let f: unsafe extern "system" fn(*mut c_void, u32, *const i32) = core::mem::transmute(method(k, mode, 22)); + f(l, 1, sc.as_ptr()); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = core::mem::transmute(method(k, mode, 34)); + f(l, k.rs as *mut c_void); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = core::mem::transmute(method(k, mode, 25)); + f(l, k.pso as *mut c_void); + let f: unsafe extern "system" fn(*mut c_void, u32) = core::mem::transmute(method(k, mode, 20)); + f(l, 4); + let draw_add = |v: f32| { + let c = [v, v, v, 1.0f32]; + vc!(l, PC_ROOT_CONSTANTS, fn(u32, u32, *const f32, u32) -> (), 0, 4, c.as_ptr(), 0); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = core::mem::transmute(method(k, mode, 12)); + draw(l, 3, 1, 0, 0); + }; + draw_add(adds[0]); + transition(k, mode, k.aux, ST_RT, ST_COPY_SOURCE); + transition(k, mode, k.aux, ST_COPY_SOURCE, ST_RT); + targets(l, 1, &k.rtv, 0, core::ptr::null()); + draw_add(adds[1]); + transition(k, mode, k.aux, ST_RT, ST_COPY_SOURCE); + transition(k, mode, k.aux, ST_COPY_SOURCE, ST_RT); + draw_add(adds[2]); + transition(k, mode, k.rt, ST_RT, ST_COPY_SOURCE); + let mut dst = [0u8; 48]; + dst[0..8].copy_from_slice(&(k.rb as u64).to_le_bytes()); + dst[8..12].copy_from_slice(&1u32.to_le_bytes()); + for (o, v) in [(24usize, k.fmt), (28, W), (32, H), (36, 1), (40, W * bpp(k.fmt))] { + dst[o..o + 4].copy_from_slice(&v.to_le_bytes()); + } + let mut src = [0u8; 48]; + src[0..8].copy_from_slice(&(k.rt as u64).to_le_bytes()); + let copy: unsafe extern "system" fn(*mut c_void, *const u8, u32, u32, u32, *const u8, *const c_void) = core::mem::transmute(method(k, mode, 16)); + copy(l, dst.as_ptr(), 0, 0, 0, src.as_ptr(), core::ptr::null()); + transition(k, mode, k.rt, ST_COPY_SOURCE, ST_RT); + let close: unsafe extern "system" fn(*mut c_void) -> i32 = core::mem::transmute(method(k, mode, 9)); + assert!(close(l) >= 0, "Close"); + let lists = [k.list]; + vc!(k.queue, 10, fn(u32, *const usize) -> (), 1, lists.as_ptr()); + k.value += 1; + assert!(vc!(k.queue, 14, fn(*mut c_void, u64) -> i32, k.fence as *mut c_void, k.value) >= 0); + let mut n = 0; + while vc!(k.fence, 8, fn() -> u64) < k.value { + std::thread::sleep(std::time::Duration::from_millis(1)); + n += 1; + assert!(n < 20000, "GPU never finished (removed reason {:#010x})", vc!(k.dev, 37, fn() -> i32)); + } + let mut m: *mut u8 = core::ptr::null_mut(); + assert!(vc!(k.rb, 8, fn(u32, *const c_void, *mut *mut u8) -> i32, 0, core::ptr::null(), &mut m) >= 0); + let bytes = core::slice::from_raw_parts(m, (W * H * bpp(k.fmt)) as usize); + let out = bytes.chunks_exact(bpp(k.fmt) as usize).map(|px| channels(k.fmt, px)).collect(); + vc!(k.rb, 9, fn(u32, *const c_void) -> (), 0, core::ptr::null()); + out + } +} + +fn channels(fmt: u32, px: &[u8]) -> [u32; 4] { + if fmt == FMT_RGBA16F { + let h = |i: usize| u16::from_le_bytes([px[2 * i], px[2 * i + 1]]) as u32; + [h(0), h(1), h(2), h(3)] + } else { + let p = u32::from_le_bytes(px.try_into().unwrap()); + [p & 0x7ff, (p >> 11) & 0x7ff, p >> 22, 0] + } +} + +fn is_inf(fmt: u32, c: [u32; 4]) -> bool { + if fmt == FMT_RGBA16F { c[0] & 0x7fff == 0x7c00 } else { c[0] == 0x7c0 } +} + +fn largest(fmt: u32) -> [u32; 4] { + if fmt == FMT_RGBA16F { [0x7bff, 0x7bff, 0x7bff, 0x4200] } else { [0x7bf, 0x7bf, 0x3df, 0] } +} + +fn gpu_free() -> bool { + let dir = std::path::Path::new(r"D:\TomBox\tools\dev"); + let busy = std::fs::read_dir(dir).map(|it| it.flatten().any(|e| { + let n = e.file_name().to_string_lossy().to_ascii_uppercase(); + n.starts_with("GAME_LOCK") || n.starts_with("USER_PLAYING") + })).unwrap_or(false); + if busy { + println!("GPU test skipped: a GAME_LOCK or USER_PLAYING file exists in {}", dir.display()); + } + !busy +} + +struct Outcome { + raw_inf: usize, + eager: Vec<[u32; 4]>, + lazy: Vec<[u32; 4]>, + eager_passes: u64, + lazy_passes: u64, + lazy_own: u64, +} + +unsafe fn chain(fmt: u32) -> Outcome { + unsafe { + test_api::reset(); + let mut k = kit(fmt); + test_api::wire(*(k.list as *const *const usize)); + let raw = run(&mut k, Mode::Raw); + test_api::set_lazy(false); + let p0 = test_api::passes(); + let eager = run(&mut k, Mode::Eager); + let eager_passes = test_api::passes() - p0; + test_api::set_lazy(true); + crate::blendclamp::note_rtv(k.rtv, k.rt, core::ptr::null()); + let p0 = test_api::passes(); + let l0 = crate::blendclamp::lazy_passes(); + let lazy = run(&mut k, Mode::Lazy); + let lazy_passes = test_api::passes() - p0; + let lazy_own = crate::blendclamp::lazy_passes() - l0; + test_api::reset(); + Outcome { raw_inf: raw.iter().filter(|&&c| is_inf(fmt, c)).count(), eager, lazy, eager_passes, lazy_passes, lazy_own } + } +} + +fn check(fmt: u32, o: &Outcome, per_flush: u64, bad: &mut Vec) { + for (i, (e, z)) in o.eager.iter().zip(o.lazy.iter()).enumerate() { + if e != z && bad.len() < 8 { + bad.push(format!("fmt {fmt} pixel {i}: eager {e:x?} lazy {z:x?}")); + } + } + for (i, e) in o.eager.iter().enumerate() { + if *e != largest(fmt) && bad.len() < 16 { + bad.push(format!("fmt {fmt} pixel {i}: eager {e:x?} want {:x?}", largest(fmt))); + } + } + if o.eager_passes != 3 * per_flush { + bad.push(format!("fmt {fmt}: eager ran {} clamp passes, want {} (two unrelated barriers and the read barrier)", o.eager_passes, 3 * per_flush)); + } + if o.lazy_passes != per_flush || o.lazy_own != per_flush { + bad.push(format!("fmt {fmt}: lazy ran {} clamp passes ({} through its own view), want {per_flush} at the read barrier", o.lazy_passes, o.lazy_own)); + } +} + +#[test] +#[ignore = "needs D3D12 WARP: cargo test -p d3d12_xs --lib warp_blendclamp -- --ignored"] +fn warp_blendclamp_lazy_matches_eager_for_an_additive_chain_that_overflows_to_inf() { + if !gpu_free() { + return; + } + if !tombox_xshader::dxc::available() { + println!("DXC not available: WARP blendclamp test not run"); + return; + } + let _g = test_api::LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut bad = Vec::new(); + let half = unsafe { chain(FMT_RGBA16F) }; + if half.raw_inf == 0 { + bad.push("fmt 10: the unclamped control never reached Inf, so the chain does not exercise the clamp".to_string()); + } + check(FMT_RGBA16F, &half, 2, &mut bad); + let small = unsafe { chain(FMT_R11G11B10) }; + if small.raw_inf == 0 { + bad.push("fmt 26: the unclamped control never reached Inf, so the chain does not exercise the clamp".to_string()); + } + check(FMT_R11G11B10, &small, 1, &mut bad); + assert!(bad.is_empty(), "{}", bad.join(" +")); +} + +fn verdict(fmt: u32, c: [u32; 4]) -> &'static str { + let (exp_all, mant) = if fmt == FMT_RGBA16F { (c[0] & 0x7c00 == 0x7c00, c[0] & 0x3ff) } else { (c[0] >> 6 == 0x1f, c[0] & 0x3f) }; + if exp_all && mant != 0 { + "NaN" + } else if exp_all { + "Inf" + } else if c[..3] == largest(fmt)[..3] { + "max-finite" + } else if c[0] == 0 { + "zero" + } else { + "other" + } +} + +unsafe fn matrix(adapter: usize, who: &str) -> Vec { + let cases: [(&str, bool, Mode, [f32; 3]); 7] = [ + ("blended 40000+40000", true, Mode::Raw, [40000.0, 40000.0, 0.0]), + ("unblended write 100000", false, Mode::Raw, [100000.0; 3]), + ("unblended shader Inf", false, Mode::Raw, [f32::INFINITY; 3]), + ("blended 0+shader Inf", true, Mode::Raw, [f32::INFINITY, 0.0, 0.0]), + ("blended 0+shader NaN", true, Mode::Raw, [f32::NAN, 0.0, 0.0]), + ("blendclamp eager on shader Inf", true, Mode::Eager, [f32::INFINITY, 0.0, 0.0]), + ("blendclamp eager on shader NaN", true, Mode::Eager, [f32::NAN, 0.0, 0.0]), + ]; + let mut lines = Vec::new(); + for (fmt, name) in [(FMT_RGBA16F, "R16G16B16A16_FLOAT"), (FMT_R11G11B10, "R11G11B10_FLOAT")] { + for (what, blend, mode, adds) in cases { + unsafe { + test_api::reset(); + let mut k = kit_on(adapter, fmt, blend); + test_api::wire(*(k.list as *const *const usize)); + test_api::set_lazy(false); + let img = run_adds(&mut k, mode, adds); + test_api::reset(); + let c = img[(H / 2 * W + W / 2) as usize]; + let kinds: std::collections::BTreeMap<&str, usize> = img.iter().fold(Default::default(), |mut m, &p| { + *m.entry(verdict(fmt, p)).or_default() += 1; + m + }); + lines.push(format!("{who} blend probe {name}: {what} -> {} (centre {c:x?}, all {kinds:?})", verdict(fmt, c))); + } + } + } + lines +} + +#[test] +#[ignore = "needs D3D12 WARP: cargo test -p d3d12_xs --lib warp_blend_overflow_matrix -- --ignored --nocapture"] +fn warp_blend_overflow_matrix() { + if !gpu_free() || !tombox_xshader::dxc::available() { + return; + } + let _g = test_api::LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for l in unsafe { matrix(warp_adapter(), "WARP") } { + println!("{l}"); + } +} + +#[test] +#[ignore = "real GPU: cargo test -p d3d12_xs --lib hw_blend_overflow_probe -- --ignored --nocapture"] +fn hw_blend_overflow_probe() { + if !gpu_free() { + return; + } + if !tombox_xshader::dxc::available() { + println!("DXC not available: HW blend overflow probe not run"); + return; + } + let _g = test_api::LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for l in unsafe { matrix(0, "HW") } { + println!("{l}"); + } + let k = unsafe { kit_on(0, FMT_RGBA16F, true) }; + println!("HW blend_probe (the TOMBOX_BLEND_CLAMP=auto detector): {:?}", unsafe { crate::blend_probe::probe(k.dev as *mut c_void) }); +} + +fn ps_clamp_source(fmt: u32) -> String { + let body = format!( + "{}\ncbuffer C : register(b0) {{ float4 c; }};\nstruct O {{ float4 o0 : SV_Target0; }};\nO main() {{\n O o;\n o.o0 = c;\n{} return o;\n}}\n", + tombox_xshader::hlsl::ps_helpers(), + tombox_xshader::hlsl::ps_clamp_epilogue(&[(0, 0, 4)]) + ); + let mut rtfmt = [0u8; 8]; + rtfmt[0] = crate::shader_xlat::export_kind(fmt, true); + tombox_xshader::runtime_hlsl::finalize(&body, &rtfmt, true) +} + +#[test] +fn ps_clamp_kinds_only_change_the_small_float_formats() { + for (fmt, off, on) in [(10u32, 1u8, 3u8), (34, 1, 3), (54, 1, 3), (26, 2, 4), (2, 0, 0), (28, 0, 0)] { + assert_eq!(crate::shader_xlat::export_kind(fmt, false), off, "fmt {fmt}"); + assert_eq!(crate::shader_xlat::export_kind(fmt, true), on, "fmt {fmt}"); + } + let src = ps_clamp_source(26); + assert!(src.contains("#define TB_RTFMT0 4u"), "{}", &src[..200.min(src.len())]); + assert!(src.contains("o.o0.z = tb_psclamp(o.o0.z, TB_RTFMT0, 2u);")); +} + +#[test] +#[ignore = "needs D3D12 WARP: cargo test -p d3d12_xs --lib warp_ps_clamp -- --ignored"] +fn warp_ps_clamp_matches_eager_blendclamp_for_shader_inf_and_nan() { + if !gpu_free() { + return; + } + if !tombox_xshader::dxc::available() { + println!("DXC not available: WARP ps-clamp test not run"); + return; + } + let _g = test_api::LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let cases: [(&str, [f32; 3]); 5] = [ + ("+Inf", [f32::INFINITY, 0.0, 0.0]), + ("NaN", [f32::NAN, 0.0, 0.0]), + ("-Inf", [f32::NEG_INFINITY, 0.0, 0.0]), + ("40000 then +Inf then 40000", [40000.0, f32::INFINITY, 40000.0]), + ("NaN then 40000", [f32::NAN, 40000.0, 0.0]), + ]; + let mut bad = Vec::new(); + for fmt in [FMT_RGBA16F, FMT_R11G11B10] { + let src = ps_clamp_source(fmt); + for (what, adds) in cases { + unsafe { + test_api::reset(); + test_api::set_lazy(false); + test_api::set_ps(false); + let mut k = kit_on(warp_adapter(), fmt, true); + test_api::wire(*(k.list as *const *const usize)); + let p0 = test_api::passes(); + let eager = run_adds(&mut k, Mode::Eager, adds); + let eager_passes = test_api::passes() - p0; + test_api::reset(); + test_api::set_ps(true); + let mut k = kit_with(warp_adapter(), fmt, true, &src); + test_api::wire(*(k.list as *const *const usize)); + let p0 = test_api::passes(); + let ps = run_adds(&mut k, Mode::Eager, adds); + let ps_passes = test_api::passes() - p0; + test_api::reset(); + if eager_passes == 0 { + bad.push(format!("fmt {fmt} {what}: eager ran no clamp pass, so the comparison proves nothing")); + } + if ps_passes != 0 { + bad.push(format!("fmt {fmt} {what}: ps mode still ran {ps_passes} full-target clamp passes")); + } + let diff = eager.iter().zip(ps.iter()).filter(|(a, b)| a != b).count(); + if diff != 0 { + bad.push(format!("fmt {fmt} {what}: {diff} pixels differ, eager {:x?} ({}) vs ps {:x?} ({})", eager[0], verdict(fmt, eager[0]), ps[0], verdict(fmt, ps[0]))); + } + } + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + +#[test] +#[ignore = "needs D3D12 WARP: cargo test -p d3d12_xs --lib warp_blend_probe -- --ignored"] +fn warp_blend_probe_detects_saturating_overflow() { + if !gpu_free() || !tombox_xshader::dxc::available() { + return; + } + let _g = test_api::LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let k = unsafe { kit(FMT_RGBA16F) }; + let t0 = std::time::Instant::now(); + let r = unsafe { crate::blend_probe::probe(k.dev as *mut c_void) }; + println!("WARP blend_probe: {r:?} in {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0); + assert_eq!(r, Ok(crate::blend_probe::Overflow::Saturates)); +} diff --git a/crates/compat/d3d12_xs/src/bop64.rs b/crates/compat/d3d12_xs/src/bop64.rs index d009f7f2..44d1efb6 100644 --- a/crates/compat/d3d12_xs/src/bop64.rs +++ b/crates/compat/d3d12_xs/src/bop64.rs @@ -131,7 +131,7 @@ unsafe fn vslot(obj: *mut c_void, i: usize) -> usize { unsafe fn flush_barrier(list: *mut c_void) { let mut b = [0u8; 32]; b[0..4].copy_from_slice(&BARRIER_TYPE_UAV.to_le_bytes()); - let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(vslot(list, PC_SLOT_RESOURCE_BARRIER)) }; + let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SLOT_RESOURCE_BARRIER)) }; unsafe { f(list, 1, b.as_ptr()) }; } @@ -146,6 +146,10 @@ pub unsafe extern "system" fn write64(this: *mut c_void, va: u64, value: u64, fl return; } Plan::Write { eop, diagnostic } => { + static FIRST: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); + if !FIRST.swap(true, Ordering::Relaxed) { + record("d3d12_xs", "bop64", &format!("first call {W}(va={va:#x}, value={value:#x}, flush={flush:#x}, flags={flags:#x}) list type {ty}: recorded as {:?}", eop.kind)); + } if let Some(d) = diagnostic { if once(16) { record("d3d12_xs", "bop64", &format!("{W}(va={va:#x}, value={value:#x}, flush={flush:#x}, flags={flags:#x}): debug UMD reports \"{d}\"; the console UMD still emits the end-of-pipe packet it encodes ({eop:?}), emulated the same")); @@ -225,6 +229,7 @@ unsafe fn scratch(list: *mut c_void) -> Option { } unsafe fn write_value(list: *mut c_void, va: u64, value: u64) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::COPY) }; let words = [value as u32, (value >> 32) as u32]; let fallback = |why: &str| { if once(16) { @@ -254,16 +259,16 @@ unsafe fn write_value(list: *mut c_void, va: u64, value: u64) { let modes = [WBI_MODE_MARKER_OUT; 2]; let pred = crate::cl2_state::predication_of(list); unsafe { - let sp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, u32) = core::mem::transmute(vslot(list, PC_SLOT_SET_PREDICATION)); + let sp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, u32) = core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SLOT_SET_PREDICATION)); if pred.is_some() { sp(list, core::ptr::null_mut(), 0, 0); } crate::fill::barrier_pub(list, s.res, STATE_COMMON, STATE_COPY_DEST); - let wbi: unsafe extern "system" fn(*mut c_void, u32, *const crate::console_slots::WbiParam, *const u32) = core::mem::transmute(vslot(list, PC_SLOT_WRITE_BUFFER_IMMEDIATE)); + let wbi: unsafe extern "system" fn(*mut c_void, u32, *const crate::console_slots::WbiParam, *const u32) = core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SLOT_WRITE_BUFFER_IMMEDIATE)); wbi(list, 2, params.as_ptr(), modes.as_ptr()); crate::fill::barrier_pub(list, s.res, STATE_COPY_DEST, STATE_COPY_SOURCE); if let Some((a, b)) = db { crate::fill::barrier_pub(list, e.res, a, b); } - let cp: unsafe extern "system" fn(*mut c_void, usize, u64, usize, u64, u64) = core::mem::transmute(vslot(list, PC_SLOT_COPY_BUFFER_REGION)); + let cp: unsafe extern "system" fn(*mut c_void, usize, u64, usize, u64, u64) = core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SLOT_COPY_BUFFER_REGION)); cp(list, e.res, off, s.res, soff, 8); if let Some((a, b)) = db { crate::fill::barrier_pub(list, e.res, b, a); } crate::fill::barrier_pub(list, s.res, STATE_COPY_SOURCE, STATE_COMMON); diff --git a/crates/compat/d3d12_xs/src/cbv_copy.rs b/crates/compat/d3d12_xs/src/cbv_copy.rs new file mode 100644 index 00000000..d5d89586 --- /dev/null +++ b/crates/compat/d3d12_xs/src/cbv_copy.rs @@ -0,0 +1,1349 @@ +use compat_common::record; +use core::ffi::c_void; +use core::sync::atomic::{AtomicUsize, Ordering}; +use std::collections::{BTreeMap, HashMap}; +use std::sync::Mutex; + +pub const SLOT_ALIGN: u64 = 256; +pub const MAX_CB: u64 = 65536; +pub const CHUNK_BYTES: u64 = 1 << 20; +pub const ST_COMMON: u32 = 0; +pub const ST_VCB: u32 = 0x1; +pub const ST_COPY_DEST: u32 = 0x400; +pub const ST_COPY_SOURCE: u32 = 0x800; +const ST_WRITE_MASK: u32 = 0x4 | 0x8 | 0x10 | 0x100 | 0x400 | 0x1000; +pub const SIDE_COMPUTE: u8 = 0; +pub const SIDE_GRAPHICS: u8 = 1; +pub const MASK_COMPUTE: u8 = 1; +pub const MASK_GRAPHICS: u8 = 2; +const LIST_TYPE_BUNDLE: u32 = 1; + +const X_RESET: usize = 10; +const X_CLEAR_STATE: usize = 11; +const X_DRAW: usize = 12; +const X_DRAW_INDEXED: usize = 13; +const X_DISPATCH: usize = 14; +const X_EXEC_BUNDLE: usize = 27; +const X_SET_COMPUTE_RS: usize = 33; +const X_SET_GRAPHICS_RS: usize = 34; +const X_COMPUTE_ROOT_CBV: usize = 41; +const X_GRAPHICS_ROOT_CBV: usize = 42; +const X_EXECUTE_INDIRECT: usize = 59; +const X_DISPATCH_X: usize = 78; +const X_DRAW_INDEXED_X: usize = 81; +const X_DISPATCH_MESH_X: usize = 98; +const X_DISPATCH_MESH: usize = 127; +const PC_COPY_BUFFER: usize = 15; +const PC_BARRIER: usize = 26; +const PC_SET_COMPUTE_ROOT_CBV: usize = 37; +const PC_SET_GRAPHICS_ROOT_CBV: usize = 38; +const PC_SET_PREDICATION: usize = 55; +const LIST_GET_DEVICE: usize = 7; +const LIST_GET_TYPE: usize = 8; +const DEV_CREATE_COMMITTED: usize = 27; +const RES_GET_GPU_VA: usize = 11; + +const DRAW_SLOTS: [usize; 8] = [X_DRAW, X_DRAW_INDEXED, X_DISPATCH, X_EXECUTE_INDIRECT, X_DISPATCH_X, X_DRAW_INDEXED_X, X_DISPATCH_MESH_X, X_DISPATCH_MESH]; +const WRITE_SLOTS: [usize; 22] = [15, 16, 17, 26, 27, 53, 54, 55, 60, 61, 62, 63, 69, 70, 71, 72, 74, 83, 84, 88, 89, 90]; + +#[repr(C)] +struct Guid { + d1: u32, + d2: u16, + d3: u16, + d4: [u8; 8], +} + +const IID_DEVICE: Guid = Guid { d1: 0x1898_19f1, d2: 0x1db6, d3: 0x4b57, d4: [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7] }; +const IID_RESOURCE: Guid = Guid { d1: 0x6964_42be, d2: 0xa72e, d3: 0x4059, d4: [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad] }; + +pub fn round_up(n: u64, a: u64) -> u64 { + n.div_ceil(a) * a +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SizePlan { + pub alloc: u64, + pub copy: u64, + pub zero: u64, +} + +pub fn size_plan(declared: Option, left: u64, limit: Option) -> Option { + if left == 0 { + return None; + } + let alloc = match declared { + Some(d) => round_up(d.clamp(1, MAX_CB), SLOT_ALIGN), + None => MAX_CB, + }; + let copy = alloc.min(left).min(limit.unwrap_or(u64::MAX)); + Some(SizePlan { alloc, copy, zero: alloc - copy }) +} + +pub fn read_state(_list_type: u32) -> u32 { + ST_VCB +} + +pub fn source_barrier(state: u32) -> Option<(u32, u32)> { + if state == ST_COMMON || state & ST_COPY_SOURCE != 0 { + return None; + } + let during = if state & ST_WRITE_MASK == 0 { state | ST_COPY_SOURCE } else { ST_COPY_SOURCE }; + Some((state, during)) +} + +#[derive(Default, Clone)] +struct ListRing { + chunks: Vec, + used: u64, + state: HashMap, + stamps: Vec<(usize, u64)>, +} + +#[derive(Default)] +pub struct Ring { + pub chunks: Vec<(usize, u64)>, + free: Vec, + retired: Vec<(usize, Vec<(usize, u64)>)>, + lists: HashMap, +} + +impl Ring { + pub fn add_chunk(&mut self, res: usize, va: u64) -> usize { + self.chunks.push((res, va)); + let id = self.chunks.len() - 1; + self.free.push(id); + id + } + + pub fn reclaim(&mut self, done: &dyn Fn(usize, u64) -> bool) { + let mut back = Vec::new(); + self.retired.retain(|(c, s)| { + let ready = s.iter().all(|&(f, v)| done(f, v)); + if ready { + back.push(*c); + } + !ready + }); + self.free.extend(back); + } + + pub fn alloc(&mut self, list: usize, bytes: u64, done: &dyn Fn(usize, u64) -> bool) -> Option<(usize, u64)> { + let bytes = round_up(bytes.max(1), SLOT_ALIGN); + if bytes > CHUNK_BYTES { + return None; + } + let lr = self.lists.entry(list).or_default(); + if let Some(&c) = lr.chunks.last() { + if lr.used + bytes <= CHUNK_BYTES { + let off = lr.used; + lr.used += bytes; + return Some((c, off)); + } + } + if self.free.is_empty() { + self.reclaim(done); + } + let c = self.free.pop()?; + let lr = self.lists.entry(list).or_default(); + lr.chunks.push(c); + lr.used = bytes; + Some((c, 0)) + } + + pub fn loc(&self, chunk: usize, off: u64) -> (usize, u64) { + let (r, va) = self.chunks[chunk]; + (r, va + off) + } + + pub fn state(&self, list: usize, chunk: usize) -> u32 { + self.lists.get(&list).and_then(|l| l.state.get(&chunk).copied()).unwrap_or(ST_COMMON) + } + + pub fn set_state(&mut self, list: usize, chunk: usize, st: u32) { + self.lists.entry(list).or_default().state.insert(chunk, st); + } + + pub fn holds(&self, list: usize) -> bool { + self.lists.get(&list).is_some_and(|l| !l.chunks.is_empty()) + } + + pub fn stamp(&mut self, list: usize, fence: usize, value: u64) { + if let Some(l) = self.lists.get_mut(&list) { + match l.stamps.iter_mut().find(|s| s.0 == fence) { + Some(s) => s.1 = s.1.max(value), + None => l.stamps.push((fence, value)), + } + l.state.clear(); + } + } + + pub fn release(&mut self, list: usize) { + let Some(l) = self.lists.remove(&list) else { return }; + if l.stamps.is_empty() { + self.free.extend(l.chunks); + } else { + for c in l.chunks { + self.retired.push((c, l.stamps.clone())); + } + } + } + + #[cfg(test)] + pub fn free_count(&self) -> usize { + self.free.len() + } + + #[cfg(test)] + pub fn retired_count(&self) -> usize { + self.retired.len() + } +} + +#[derive(Default)] +struct ListSt { + pending: BTreeMap<(u8, u32), u64>, + dedupe: HashMap<(u64, u64), u64>, + rs: [usize; 2], + dev: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Forward, + Hold, + Provisional(u64), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CopyOp { + pub dst: usize, + pub dst_off: u64, + pub src: usize, + pub src_off: u64, + pub n: u64, + pub zero: u64, +} + +#[derive(Default, Debug, PartialEq)] +pub struct Job { + pub copies: Vec, + pub chunks: Vec<(usize, u32, u32)>, + pub sources: Vec<(usize, u32, u32)>, + pub binds: Vec<(u8, u32, u64)>, + pub unresolved: Vec<(u8, u32, u64)>, + pub no_room: Vec<(u8, u32, u64)>, + pub detail: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Detail { + pub side: u8, + pub idx: u32, + pub va: u64, + pub reg: Option<(u32, u32)>, + pub declared: Option, + pub limit: Option, + pub left: u64, + pub copy: u64, + pub zero: u64, +} + +pub struct Src { + pub res: usize, + pub off: u64, + pub left: u64, + pub state: u32, +} + +#[derive(Default)] +pub struct Engine { + lists: HashMap, + rings: HashMap, + pub rs_params: HashMap>, + pub pso_sizes: HashMap>, + pub cb_limits: HashMap>, + pub pso_stages: HashMap>, +} + +impl Engine { + pub fn on_root_cbv(&mut self, list: usize, side: u8, idx: u32, va: u64, bundle: bool) -> Action { + let st = self.lists.entry(list).or_default(); + if va % SLOT_ALIGN == 0 || bundle { + st.pending.remove(&(side, idx)); + return Action::Forward; + } + st.pending.insert((side, idx), va); + match st.dedupe.iter().filter(|(k, _)| k.0 == va).max_by_key(|(k, _)| k.1) { + Some((_, &slot)) => Action::Provisional(slot), + None => Action::Hold, + } + } + + pub fn on_root_signature(&mut self, list: usize, side: u8, rs: usize) { + let st = self.lists.entry(list).or_default(); + if st.rs[side as usize] != rs { + st.pending.retain(|k, _| k.0 != side); + st.rs[side as usize] = rs; + } + } + + pub fn invalidate(&mut self, list: usize) { + if let Some(st) = self.lists.get_mut(&list) { + st.dedupe.clear(); + } + } + + pub fn clear_state(&mut self, list: usize) { + if let Some(st) = self.lists.get_mut(&list) { + st.pending.clear(); + st.dedupe.clear(); + st.rs = [0, 0]; + } + } + + pub fn forget(&mut self, list: usize) { + if let Some(st) = self.lists.remove(&list) { + if let Some(r) = self.rings.get_mut(&st.dev) { + r.release(list); + } + } + for r in self.rings.values_mut() { + r.release(list); + } + } + + #[cfg(test)] + pub fn pending(&self, list: usize) -> Vec<((u8, u32), u64)> { + self.lists.get(&list).map(|s| s.pending.iter().map(|(k, v)| (*k, *v)).collect()).unwrap_or_default() + } + + pub fn has_pending(&self, list: usize, mask: u8) -> bool { + self.lists.get(&list).is_some_and(|s| s.pending.keys().any(|k| mask & (1 << k.0) != 0)) + } + + pub fn ring(&mut self, dev: usize) -> &mut Ring { + self.rings.entry(dev).or_default() + } + + pub fn holds(&self, list: usize) -> bool { + self.rings.values().any(|r| r.holds(list)) + } + + pub fn stamp(&mut self, list: usize, fence: usize, value: u64) { + for r in self.rings.values_mut() { + r.stamp(list, fence, value); + } + } + + pub fn materialize(&mut self, pso: usize, meta: &dyn Fn(u64) -> Option) -> bool { + if self.pso_sizes.contains_key(&pso) { + return true; + } + let Some(stages) = self.pso_stages.get(&pso) else { return false }; + let mut sizes = Vec::new(); + let mut limits = Vec::new(); + for &(vis, h) in stages { + let Some(m) = meta(h) else { return false }; + sizes.extend(m.sizes.iter().map(|&(r, sp, b)| (vis, r, sp, b))); + limits.extend(m.limits.iter().map(|&(r, sp, b)| (vis, r, sp, b))); + } + self.pso_sizes.insert(pso, sizes); + if !limits.is_empty() { + self.cb_limits.insert(pso, limits); + } + true + } + + pub fn declared(&self, pso: Option, rs: usize, idx: u32) -> Option { + Self::per_stage(&self.pso_sizes, &self.rs_params, pso, rs, idx).into_iter().max() + } + + pub fn limit(&self, pso: Option, rs: usize, idx: u32) -> Option { + let v = Self::per_stage(&self.cb_limits, &self.rs_params, pso, rs, idx); + let stages = Self::per_stage(&self.pso_sizes, &self.rs_params, pso, rs, idx).len(); + (!v.is_empty() && v.len() >= stages).then(|| v.into_iter().max().unwrap_or(0)) + } + + pub fn reg_of(&self, rs: usize, idx: u32) -> Option<(u32, u32)> { + self.rs_params.get(&rs)?.iter().find(|p| p.0 == idx as usize).map(|p| (p.1, p.2)) + } + + fn per_stage(m: &HashMap>, rsp: &HashMap>, pso: Option, rs: usize, idx: u32) -> Vec { + let Some(&(_, reg, space, vis)) = rsp.get(&rs).and_then(|v| v.iter().find(|p| p.0 == idx as usize)) else { return Vec::new() }; + let Some(l) = pso.and_then(|k| m.get(&k)) else { return Vec::new() }; + l.iter().filter(|e| e.1 == reg && e.2 == space && (vis == 0 || e.0 == 0 || e.0 == vis)).map(|e| e.3).collect() + } + + #[allow(clippy::too_many_arguments)] + pub fn plan( + &mut self, + list: usize, + dev: usize, + list_type: u32, + mask: u8, + pso: Option, + lookup: &dyn Fn(u64) -> Option, + mk_chunk: &mut dyn FnMut() -> Option<(usize, u64)>, + done: &dyn Fn(usize, u64) -> bool, + ) -> Job { + let mut job = Job::default(); + let st = self.lists.entry(list).or_default(); + st.dev = dev; + let todo: Vec<((u8, u32), u64)> = st.pending.iter().filter(|(k, _)| mask & (1 << k.0) != 0).map(|(k, v)| (*k, *v)).collect(); + if todo.is_empty() { + return job; + } + st.pending.retain(|k, _| mask & (1 << k.0) == 0); + let rs = st.rs; + if let Some(p) = pso { + if !self.materialize(p, &shader_cb) && self.pso_stages.contains_key(&p) { + note(&SIZE_UNKNOWN, 4, &|| format!("pso {p:#x}: a stage's constant buffer sizes were not recorded by its translation; its unaligned root CBVs use a 64 KiB slot zero-filled past the source")); + } + } + let sizes: Vec<(Option, Option, Option<(u32, u32)>)> = todo.iter().map(|((side, idx), _)| { + let r = rs[*side as usize]; + (self.declared(pso, r, *idx), self.limit(pso, r, *idx), self.reg_of(r, *idx)) + }).collect(); + let rstate = read_state(list_type); + for (((side, idx), va), (declared, limit, reg)) in todo.into_iter().zip(sizes) { + let Some(src) = lookup(va) else { + job.unresolved.push((side, idx, va)); + continue; + }; + let Some(p) = size_plan(declared, src.left, limit) else { + job.unresolved.push((side, idx, va)); + continue; + }; + if let Some(&slot) = self.lists.get(&list).and_then(|s| s.dedupe.get(&(va, p.alloc))) { + job.binds.push((side, idx, slot)); + continue; + } + let ring = self.rings.entry(dev).or_default(); + let mut got = ring.alloc(list, p.alloc, done); + if got.is_none() { + if let Some((res, cva)) = mk_chunk() { + ring.add_chunk(res, cva); + got = ring.alloc(list, p.alloc, done); + } + } + let Some((chunk, off)) = got else { + job.no_room.push((side, idx, va)); + continue; + }; + let (cres, slot_va) = ring.loc(chunk, off); + if !job.chunks.iter().any(|c| c.0 == cres) { + job.chunks.push((cres, ring.state(list, chunk), rstate)); + ring.set_state(list, chunk, rstate); + } + if let Some((before, during)) = source_barrier(src.state) { + if !job.sources.iter().any(|s| s.0 == src.res) { + job.sources.push((src.res, before, during)); + } + } + job.copies.push(CopyOp { dst: cres, dst_off: off, src: src.res, src_off: src.off, n: p.copy, zero: p.zero }); + job.detail.push(Detail { side, idx, va, reg, declared, limit, left: src.left, copy: p.copy, zero: p.zero }); + if let Some(s) = self.lists.get_mut(&list) { + s.dedupe.insert((va, p.alloc), slot_va); + } + job.binds.push((side, idx, slot_va)); + } + job + } +} + +static ENGINE: Mutex> = Mutex::new(None); + +pub fn with(f: impl FnOnce(&mut Engine) -> R) -> R { + f(ENGINE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Engine::default)) +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ShaderCb { + pub sizes: Vec<(u32, u32, u64)>, + pub limits: Vec<(u32, u32, u64)>, +} + +pub fn slot_limits(m: &std::collections::BTreeMap) -> Vec<(u32, u32, u64)> { + m.iter().filter(|(slot, _)| **slot & 0x8000_0000 == 0).map(|(slot, b)| (slot & 0xffff, slot >> 16, *b)).collect() +} + +static SHADER_CB: Mutex>> = Mutex::new(None); + +pub fn note_shader_cb(hash: u64, meta: ShaderCb) { + SHADER_CB.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new).insert(hash, meta); +} + +pub fn shader_cb(hash: u64) -> Option { + SHADER_CB.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.get(&hash).cloned() +} + +pub fn meta_of(t: &tombox_xshader::hlsl::Translated) -> ShaderCb { + ShaderCb { sizes: tombox_xshader::cbv_raw_hlsl::declared_sizes(&t.hlsl), limits: slot_limits(&t.cb_limits) } +} + +pub fn encode_meta(m: &ShaderCb) -> Vec { + let mut v = b"TBCBM1".to_vec(); + for part in [&m.sizes, &m.limits] { + v.extend_from_slice(&(part.len() as u32).to_le_bytes()); + for &(r, sp, b) in part.iter() { + v.extend_from_slice(&r.to_le_bytes()); + v.extend_from_slice(&sp.to_le_bytes()); + v.extend_from_slice(&b.to_le_bytes()); + } + } + v +} + +pub fn decode_meta(b: &[u8]) -> Option { + let mut at = 6; + if b.get(..6)? != b"TBCBM1" { + return None; + } + let mut take = |n: usize| -> Option<&[u8]> { + let s = b.get(at..at + n)?; + at += n; + Some(s) + }; + let mut parts = Vec::new(); + for _ in 0..2 { + let n = u32::from_le_bytes(take(4)?.try_into().ok()?) as usize; + if n > 4096 { + return None; + } + let mut v = Vec::with_capacity(n); + for _ in 0..n { + let r = u32::from_le_bytes(take(4)?.try_into().ok()?); + let sp = u32::from_le_bytes(take(4)?.try_into().ok()?); + let bytes = u64::from_le_bytes(take(8)?.try_into().ok()?); + v.push((r, sp, bytes)); + } + parts.push(v); + } + let limits = parts.pop()?; + let sizes = parts.pop()?; + Some(ShaderCb { sizes, limits }) +} + +unsafe fn stage_hashes(desc: *const u8, stages: &[(u32, usize)]) -> Vec<(u32, u64)> { + let mut out = Vec::new(); + for &(vis, off) in stages { + let p = unsafe { core::ptr::read_unaligned(desc.add(off) as *const u64) } as *const u8; + let n = unsafe { core::ptr::read_unaligned(desc.add(off + 8) as *const u64) } as usize; + if p.is_null() || !(32..=0x40_0000).contains(&n) { + continue; + } + out.push((vis, crate::shader_xlat::fnv1a(unsafe { core::slice::from_raw_parts(p, n) }))); + } + out +} + +pub fn store_pso(pso: usize, stages: Vec<(u32, u64)>) { + with(|e| { + e.pso_sizes.remove(&pso); + e.cb_limits.remove(&pso); + e.pso_stages.insert(pso, stages); + }); +} + +const GFX_STAGES: [(u32, usize); 5] = [(1, 0x08), (5, 0x18), (3, 0x28), (2, 0x38), (4, 0x48)]; + +pub fn after_gfx_pso(hr: i32, pdesc: *const u8, ppv: *mut *mut c_void) -> i32 { + if crate::cbv_raw::copy_on() { + unsafe { record_pso(hr, pdesc, ppv, &GFX_STAGES) }; + } + hr +} + +unsafe fn record_pso(hr: i32, pdesc: *const u8, ppv: *mut *mut c_void, stages: &[(u32, usize)]) { + if hr >= 0 && !pdesc.is_null() && !ppv.is_null() { + let pso = unsafe { *ppv } as usize; + if pso != 0 { + store_pso(pso, unsafe { stage_hashes(pdesc, stages) }); + } + } +} + +pub fn alias_pso(from: usize, to: usize) { + if from == 0 || to == 0 || from == to { + return; + } + with(|e| { + if let Some(v) = e.pso_sizes.get(&from).cloned() { + e.pso_sizes.entry(to).or_insert(v); + } + if let Some(v) = e.cb_limits.get(&from).cloned() { + e.cb_limits.entry(to).or_insert(v); + } + if let Some(v) = e.pso_stages.get(&from).cloned() { + e.pso_stages.entry(to).or_insert(v); + } + }); +} + +pub fn after_compute_pso(hr: i32, pdesc: *const u8, ppv: *mut *mut c_void) -> i32 { + if crate::cbv_raw::copy_on() { + unsafe { record_pso(hr, pdesc, ppv, &[(0, 0x08)]) }; + } + hr +} + +fn rs_params_of(rs: usize) -> Option> { + let (_, blob, _) = crate::pso_lib::root_info(rs)?; + Some(crate::cbv_raw::root_cbv_params(&blob)) +} + +static SIZE_UNKNOWN: AtomicUsize = AtomicUsize::new(0); +static UNRESOLVED: AtomicUsize = AtomicUsize::new(0); +static NO_ROOM: AtomicUsize = AtomicUsize::new(0); +static BUNDLE_REFUSED: AtomicUsize = AtomicUsize::new(0); +static COPIES: AtomicUsize = AtomicUsize::new(0); +static REUSED: AtomicUsize = AtomicUsize::new(0); +static NO_FENCE: AtomicUsize = AtomicUsize::new(0); +static ILLEGAL: AtomicUsize = AtomicUsize::new(0); + +fn note(c: &AtomicUsize, first: usize, text: &dyn Fn() -> String) { + let n = c.fetch_add(1, Ordering::Relaxed); + if n < first || (n + 1).is_power_of_two() { + record("d3d12_xs", "cbv_copy", &format!("#{} {}", n + 1, text())); + } +} + +pub use tombox_xshader::cbv_raw_hlsl::{in_table, table_cbv_ranges}; + +unsafe fn vslot(o: *mut c_void, i: usize) -> usize { + unsafe { *(*(o as *const *const usize)).add(i) } +} + +pub unsafe fn device_of(list: *mut c_void) -> usize { + let get: unsafe extern "system" fn(*mut c_void, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(vslot(list, LIST_GET_DEVICE)) }; + let mut d: *mut c_void = core::ptr::null_mut(); + if unsafe { get(list, &IID_DEVICE, &mut d) } < 0 || d.is_null() { + return 0; + } + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = unsafe { core::mem::transmute(vslot(d, 2)) }; + unsafe { rel(d) }; + d as usize +} + +pub unsafe fn list_type(list: *mut c_void) -> u32 { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = unsafe { core::mem::transmute(vslot(list, LIST_GET_TYPE)) }; + unsafe { f(list) } +} + +pub unsafe fn create_buffer(dev: usize, size: u64) -> Option<(usize, u64)> { + if dev == 0 { + return None; + } + let heap: [u32; 5] = [1, 0, 0, 1, 1]; + let mut rd = [0u8; 56]; + rd[0..4].copy_from_slice(&1u32.to_le_bytes()); + rd[0x10..0x18].copy_from_slice(&size.to_le_bytes()); + rd[0x18..0x1c].copy_from_slice(&1u32.to_le_bytes()); + rd[0x1c..0x1e].copy_from_slice(&1u16.to_le_bytes()); + rd[0x1e..0x20].copy_from_slice(&1u16.to_le_bytes()); + rd[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + rd[0x2c..0x30].copy_from_slice(&1u32.to_le_bytes()); + let d = dev as *mut c_void; + let cc: unsafe extern "system" fn(*mut c_void, *const u32, u32, *const u8, u32, *const c_void, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(vslot(d, DEV_CREATE_COMMITTED)) }; + let mut buf: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { cc(d, heap.as_ptr(), 0, rd.as_ptr(), ST_COMMON, core::ptr::null(), &IID_RESOURCE, &mut buf) }; + if hr < 0 || buf.is_null() { + record("d3d12_xs", "cbv_copy", &format!("DEFAULT-heap buffer of {size:#x} bytes FAILED hr={hr:#010x}")); + return None; + } + let va: unsafe extern "system" fn(*mut c_void) -> u64 = unsafe { core::mem::transmute(vslot(buf, RES_GET_GPU_VA)) }; + Some((buf as usize, unsafe { va(buf) })) +} + +static ZERO: Mutex>> = Mutex::new(None); + +unsafe fn zero_block(dev: usize) -> Option { + let mut g = ZERO.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + if let Some(&z) = m.get(&dev) { + return Some(z); + } + let (z, _) = unsafe { create_buffer(dev, MAX_CB) }?; + m.insert(dev, z); + Some(z) +} + +pub fn lookup_source(va: u64) -> Option { + if let Some((e, off)) = crate::gpu_va::lookup_buffer(va) { + if off < e.len { + return Some(Src { res: e.res, off, left: e.len - off, state: crate::gpu_va::state(e.res) }); + } + } + let (base, res, size, _) = crate::bindtrace::buffer_at(va)?; + let off = va - base; + (off < size).then(|| Src { res, off, left: size - off, state: crate::gpu_va::state(res) }) +} + +fn trace_targets() -> &'static Vec { + static T: std::sync::OnceLock> = std::sync::OnceLock::new(); + T.get_or_init(|| crate::hang_cap::parse_targets(std::env::var("TOMBOX_CBRAW_CAP_PS").ok().as_deref())) +} + +fn ps_hash(pso: usize) -> u64 { + if let Some(h) = crate::dred_marks::hashes(pso) { + return h.ps; + } + crate::device_wrap::pso_summary(pso) + .map(|(_, p, _)| if p == 0 { 0 } else { crate::shader_xlat::origin_hash(p).unwrap_or(0) }) + .unwrap_or(0) +} + +pub fn detail_text(d: &Detail) -> String { + let reg = d.reg.map(|(r, s)| format!("b{r} space{s}")).unwrap_or_else(|| "b?".into()); + let lim = d.limit.map(|l| format!("{l:#x}")).unwrap_or_else(|| "unknown (the translator does not export it yet)".into()); + let decl = d.declared.map(|l| format!("{l:#x}")).unwrap_or_else(|| "unknown".into()); + let past = if d.declared.is_some_and(|m| m > d.left) { " SHADER MAX READ PASSES THE SOURCE END" } else { "" }; + format!("param {} side {} {reg}: va={:#x} shader max read (declared cbuffer bytes)={decl} NR*stride={lim} source bytes left={:#x} copied={:#x} zero tail={:#x}{past}", d.idx, d.side, d.va, d.left, d.copy, d.zero) +} + +static TRACED: AtomicUsize = AtomicUsize::new(0); + +fn trace_cap() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("TOMBOX_CBRAW_CAP_N").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64)) +} + +unsafe fn trace_target(list: *mut c_void, pso: Option, job: &Job) { + if TRACED.load(Ordering::Relaxed) >= trace_cap() { + return; + } + let Some(pso) = pso else { return }; + let ps = ps_hash(pso); + if ps == 0 || !trace_targets().contains(&ps) { + return; + } + for d in &job.detail { + if TRACED.fetch_add(1, Ordering::Relaxed) >= trace_cap() { + return; + } + record("d3d12_xs", "cbv_copy", &format!("target PS {ps:016x} draw on list {list:p}: {}", detail_text(d))); + } +} + +fn describe_miss(va: u64) -> String { + let near: Vec = crate::gpu_va::near(va, 2).iter().map(|e| format!("{}{:#x}..{:#x} res {:#x}", if e.buffer { "buffer " } else { "texture " }, e.start, e.start.saturating_add(e.len), e.res)).collect(); + let hit = match crate::gpu_va::lookup(va) { + Some((e, off)) => format!("the address map has only a {} entry here (res {:#x} +{off:#x} of {:#x})", if e.buffer { "buffer past-the-end" } else { "texture" }, e.res, e.len), + None => "no address-map entry".to_string(), + }; + format!("{hit}; neighbours [{}]", near.join(", ")) +} + +fn transition(res: usize, before: u32, after: u32) -> [u8; 32] { + let mut b = [0u8; 32]; + b[8..16].copy_from_slice(&(res as u64).to_le_bytes()); + b[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + b[20..24].copy_from_slice(&before.to_le_bytes()); + b[24..28].copy_from_slice(&after.to_le_bytes()); + b +} + +unsafe fn barriers(list: *mut c_void, b: &[[u8; 32]]) { + if b.is_empty() { + return; + } + let f: unsafe extern "system" fn(*mut c_void, u32, *const [u8; 32]) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_BARRIER)) }; + unsafe { f(list, b.len() as u32, b.as_ptr()) }; +} + +pub unsafe fn bind(list: *mut c_void, side: u8, idx: u32, va: u64) { + let slot = if side == SIDE_COMPUTE { PC_SET_COMPUTE_ROOT_CBV } else { PC_SET_GRAPHICS_ROOT_CBV }; + let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, slot)) }; + unsafe { f(list, idx, va) }; +} + +pub unsafe fn run(list: *mut c_void, job: &Job, zero: Option, ty: u32, pred: Option<(usize, u64, u32)>) { + let _ij = crate::inject::mark(crate::inject::COPY); + if !job.copies.is_empty() { + let setp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, u32) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SET_PREDICATION)) }; + if pred.is_some() { + unsafe { setp(list, core::ptr::null_mut(), 0, 0) }; + } + let legal = |s: u32| crate::fill::state_legal_on(ty, s); + let srcs: Vec<&(usize, u32, u32)> = job.sources.iter().filter(|s| { + let ok = legal(s.1) && legal(s.2); + if !ok { + note(&ILLEGAL, 4, &|| format!("copy source {:#x} is in state {:#x}, which a type-{ty} list cannot transition; copied without a barrier", s.0, s.1)); + } + ok + }).collect(); + let mut pre: Vec<[u8; 32]> = job.chunks.iter().filter(|c| c.1 != ST_COPY_DEST).map(|c| transition(c.0, c.1, ST_COPY_DEST)).collect(); + pre.extend(srcs.iter().map(|s| transition(s.0, s.1, s.2))); + unsafe { barriers(list, &pre) }; + let cp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_COPY_BUFFER)) }; + for c in &job.copies { + if c.n != 0 { + unsafe { cp(list, c.dst as *mut c_void, c.dst_off, c.src as *mut c_void, c.src_off, c.n) }; + } + if c.zero != 0 { + match zero { + Some(z) => unsafe { cp(list, c.dst as *mut c_void, c.dst_off + c.n, z as *mut c_void, 0, c.zero) }, + None => note(&UNRESOLVED, 8, &|| format!("no zero block for a {}-byte tail; the tail keeps old ring contents", c.zero)), + } + } + } + let mut post: Vec<[u8; 32]> = job.chunks.iter().map(|c| transition(c.0, ST_COPY_DEST, c.2)).collect(); + post.extend(srcs.iter().map(|s| transition(s.0, s.2, s.1))); + unsafe { barriers(list, &post) }; + if let Some((r, o, op)) = pred { + unsafe { setp(list, r as *mut c_void, o, op) }; + } + } + for &(side, idx, va) in &job.binds { + unsafe { bind(list, side, idx, va) }; + } +} + +pub unsafe fn resolve_with(list: *mut c_void, mask: u8, pso: Option, pred: Option<(usize, u64, u32)>) { + if !with(|e| e.has_pending(list as usize, mask)) { + return; + } + if crate::dred::removed() { + with(|e| { + if let Some(s) = e.lists.get_mut(&(list as usize)) { + s.pending.retain(|k, _| mask & (1 << k.0) == 0); + } + }); + return; + } + let dev = unsafe { device_of(list) }; + let ty = unsafe { list_type(list) }; + let rs_missing: Vec = with(|e| { + let rs = e.lists.get(&(list as usize)).map(|s| s.rs).unwrap_or_default(); + rs.into_iter().filter(|r| *r != 0 && !e.rs_params.contains_key(r)).collect() + }); + for rs in rs_missing { + if let Some(p) = rs_params_of(rs) { + with(|e| e.rs_params.insert(rs, p)); + } + } + let job = with(|e| { + e.plan(list as usize, dev, ty, mask, pso, &lookup_source, &mut || unsafe { create_buffer(dev, CHUNK_BYTES) }, &|f, v| unsafe { crate::cl2_state::fence_passed(f, v) }) + }); + let zero = if job.copies.iter().any(|c| c.zero != 0) { unsafe { zero_block(dev) } } else { None }; + if !job.copies.is_empty() { + let n = COPIES.fetch_add(job.copies.len(), Ordering::Relaxed); + if n == 0 { + let c = job.copies[0]; + record("d3d12_xs", "cbv_copy", &format!("first unaligned root CBV copy: {} bytes from res {:#x}+{:#x} into ring {:#x}+{:#x} (zero tail {}), list type {ty}, pso {pso:x?}", c.n, c.src, c.src_off, c.dst, c.dst_off, c.zero)); + } + } + if job.copies.len() < job.binds.len() { + REUSED.fetch_add(job.binds.len() - job.copies.len(), Ordering::Relaxed); + } + if !job.detail.is_empty() { + unsafe { trace_target(list, pso, &job) }; + } + for &(side, idx, va) in &job.unresolved { + note(&UNRESOLVED, 8, &|| format!("root CBV param {idx} side {side} va={va:#x} is not inside any known buffer ({}); bound as given, as cbv_raw=off does", describe_miss(va))); + } + for &(side, idx, va) in &job.no_room { + note(&NO_ROOM, 4, &|| format!("root CBV param {idx} side {side} va={va:#x}: the copy ring could not grow (DEFAULT-heap chunk creation failed); bound as given, as cbv_raw=off does")); + } + let timed = !job.copies.is_empty(); + if timed { + unsafe { crate::gpuprof::pass_begin(list, crate::gpuprof::TAG_CBV_COPY) }; + } + unsafe { run(list, &job, zero, ty, pred) }; + if timed { + unsafe { crate::gpuprof::pass_end(list) }; + } + for &(side, idx, va) in job.unresolved.iter().chain(job.no_room.iter()) { + unsafe { bind(list, side, idx, va) }; + } +} + +pub unsafe fn resolve(list: *mut c_void, mask: u8) { + let pso = crate::cl2_state::bound_pso(list); + let pred = crate::cl2_state::predication_of(list); + unsafe { resolve_with(list, mask, pso, pred) }; +} + +pub unsafe fn set_root_cbv(list: *mut c_void, side: u8, idx: u32, va: u64, fwd: &dyn Fn(u64)) { + let bundle = va % SLOT_ALIGN != 0 && unsafe { list_type(list) } == LIST_TYPE_BUNDLE; + if bundle { + note(&BUNDLE_REFUSED, 8, &|| format!("bundle {list:p} sets root CBV param {idx} to unaligned {va:#x}: a bundle cannot record the copy or its barriers, so it is bound as given, as cbv_raw=off does (unsupported)")); + } + match with(|e| e.on_root_cbv(list as usize, side, idx, va, bundle)) { + Action::Forward => fwd(va), + Action::Hold => {} + Action::Provisional(slot) => { + if !crate::dred::removed() { + unsafe { bind(list, side, idx, slot) }; + } + } + } +} + +pub unsafe fn note_executed(queue: *mut c_void, lists: &[*mut c_void]) { + if !crate::cbv_raw::copy_on() { + return; + } + unsafe { stamp_executed(queue, lists) }; +} + +pub unsafe fn stamp_executed(queue: *mut c_void, lists: &[*mut c_void]) { + let held: Vec = with(|e| lists.iter().map(|l| *l as usize).filter(|l| e.holds(*l)).collect()); + let Some(&first) = held.first() else { return }; + match unsafe { crate::cl2_state::signal_queue(queue, first as *mut c_void) } { + Some((f, v)) => with(|e| held.iter().for_each(|&l| e.stamp(l, f, v))), + None => { + note(&NO_FENCE, 4, &|| "no queue fence for lists holding ring slots; their chunks are never reused".to_string()); + with(|e| held.iter().for_each(|&l| e.stamp(l, usize::MAX, u64::MAX))); + } + } +} + +static PREV: [AtomicUsize; 128] = [const { AtomicUsize::new(0) }; 128]; + +fn prev(slot: usize) -> usize { + PREV[slot].load(Ordering::Relaxed) +} + +unsafe extern "system" fn h_compute_root_cbv(this: *mut c_void, i: u32, va: u64) { + let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(prev(X_COMPUTE_ROOT_CBV)) }; + unsafe { set_root_cbv(this, SIDE_COMPUTE, i, va, &|v| f(this, i, v)) } +} + +unsafe extern "system" fn h_graphics_root_cbv(this: *mut c_void, i: u32, va: u64) { + let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(prev(X_GRAPHICS_ROOT_CBV)) }; + unsafe { set_root_cbv(this, SIDE_GRAPHICS, i, va, &|v| f(this, i, v)) } +} + +unsafe extern "system" fn h_compute_rs(this: *mut c_void, rs: *mut c_void) { + with(|e| e.on_root_signature(this as usize, SIDE_COMPUTE, rs as usize)); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(prev(X_SET_COMPUTE_RS)) }; + unsafe { f(this, rs) } +} + +unsafe extern "system" fn h_graphics_rs(this: *mut c_void, rs: *mut c_void) { + with(|e| e.on_root_signature(this as usize, SIDE_GRAPHICS, rs as usize)); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(prev(X_SET_GRAPHICS_RS)) }; + unsafe { f(this, rs) } +} + +static LATE_PREV: [AtomicUsize; 128] = [const { AtomicUsize::new(0) }; 128]; + +unsafe extern "system" fn h_reset(this: *mut c_void, alloc: *mut c_void, pso: *mut c_void) -> i32 { + let chain = crate::list_split::expand(&[this]); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> i32 = unsafe { core::mem::transmute(LATE_PREV[X_RESET].load(Ordering::Relaxed)) }; + let hr = unsafe { f(this, alloc, pso) }; + if hr >= 0 { + with(|e| { + e.forget(this as usize); + for l in &chain { + e.forget(*l as usize); + } + }); + } + hr +} + +pub fn slot_mask(slot: usize) -> u8 { + match slot { + X_DRAW | X_DRAW_INDEXED | X_DRAW_INDEXED_X | X_DISPATCH_MESH_X | X_DISPATCH_MESH => MASK_GRAPHICS, + X_DISPATCH | X_DISPATCH_X => MASK_COMPUTE, + X_EXECUTE_INDIRECT | X_EXEC_BUNDLE => MASK_COMPUTE | MASK_GRAPHICS, + _ => 0, + } +} + +pub fn slot_writes(slot: usize) -> bool { + WRITE_SLOTS.contains(&slot) || matches!(slot, X_DISPATCH | X_DISPATCH_X | X_EXECUTE_INDIRECT) +} + +extern "system" fn hook_pre(list: *mut c_void, slot: usize) { + if slot == X_CLEAR_STATE { + with(|e| e.clear_state(list as usize)); + return; + } + let mask = slot_mask(slot); + if mask != 0 { + unsafe { resolve(list, mask) }; + } + if slot_writes(slot) { + with(|e| e.invalidate(list as usize)); + } +} + +macro_rules! late_thunks { + ($(($name:ident, $slot:literal)),* $(,)?) => { + $( + #[unsafe(naked)] + unsafe extern "system" fn $name() { + core::arch::naked_asm!( + "push rcx", + "push rdx", + "push r8", + "push r9", + "sub rsp, 104", + "movdqu [rsp + 32], xmm0", + "movdqu [rsp + 48], xmm1", + "movdqu [rsp + 64], xmm2", + "movdqu [rsp + 80], xmm3", + "mov edx, {s}", + "call {pre}", + "movdqu xmm0, [rsp + 32]", + "movdqu xmm1, [rsp + 48]", + "movdqu xmm2, [rsp + 64]", + "movdqu xmm3, [rsp + 80]", + "add rsp, 104", + "pop r9", + "pop r8", + "pop rdx", + "pop rcx", + "lea rax, [rip + {tbl}]", + "mov rax, [rax + {off}]", + "jmp rax", + s = const $slot, + off = const $slot * 8, + pre = sym hook_pre, + tbl = sym LATE_PREV, + ); + } + )* + fn late_thunk(slot: usize) -> usize { + match slot { + $( $slot => $name as usize, )* + _ => 0, + } + } + }; +} + +late_thunks!( + (t11, 11), (t12, 12), (t13, 13), (t14, 14), (t15, 15), (t16, 16), (t17, 17), (t26, 26), (t27, 27), + (t53, 53), (t54, 54), (t55, 55), (t59, 59), (t60, 60), (t61, 61), (t62, 62), (t63, 63), (t69, 69), + (t70, 70), (t71, 71), (t72, 72), (t74, 74), (t78, 78), (t81, 81), (t83, 83), (t84, 84), (t88, 88), + (t89, 89), (t90, 90), (t98, 98), (t127, 127), +); + +pub fn install_inner(vt: &[AtomicUsize]) -> usize { + let mut n = 0; + for (slot, f) in [ + (X_COMPUTE_ROOT_CBV, h_compute_root_cbv as usize), + (X_GRAPHICS_ROOT_CBV, h_graphics_root_cbv as usize), + (X_SET_COMPUTE_RS, h_compute_rs as usize), + (X_SET_GRAPHICS_RS, h_graphics_rs as usize), + ] { + let p = vt[slot].load(Ordering::Relaxed); + if p == 0 || p == f { + continue; + } + PREV[slot].store(p, Ordering::Relaxed); + vt[slot].store(f, Ordering::Relaxed); + n += 1; + } + n +} + +pub fn install_late(vt: &[AtomicUsize]) -> usize { + let mut n = 0; + let mut slots: Vec = DRAW_SLOTS.iter().chain(WRITE_SLOTS.iter()).copied().collect(); + slots.push(X_CLEAR_STATE); + slots.sort_unstable(); + slots.dedup(); + for slot in slots { + let f = late_thunk(slot); + if f == 0 || slot >= vt.len() { + continue; + } + let p = vt[slot].load(Ordering::Relaxed); + if p == 0 || p == f { + continue; + } + LATE_PREV[slot].store(p, Ordering::Relaxed); + vt[slot].store(f, Ordering::Relaxed); + n += 1; + } + let p = vt[X_RESET].load(Ordering::Relaxed); + if p != 0 && p != h_reset as usize { + LATE_PREV[X_RESET].store(p, Ordering::Relaxed); + vt[X_RESET].store(h_reset as usize, Ordering::Relaxed); + n += 1; + } + n +} + +pub fn install(vt: &[AtomicUsize], late: bool) { + if !crate::cbv_raw::copy_on() || vt.len() < 128 { + return; + } + let n = if late { install_late(vt) } else { install_inner(vt) }; + record("d3d12_xs", "cbv_copy", &format!("cbv_raw=copy: {} hooks on {n} command-list slots", if late { "draw/dispatch resolve, title-write dedupe invalidation and Reset" } else { "root CBV and root signature" })); +} + +#[cfg(test)] +#[path = "cbv_copy_hw.rs"] +mod hw; + +#[cfg(test)] +mod tests { + use super::*; + + fn src(res: usize, base: u64, len: u64) -> impl Fn(u64) -> Option { + move |va| (va >= base && va < base + len).then(|| Src { res, off: va - base, left: base + len - va, state: 0xac3 }) + } + + #[test] + fn copy_mode_pso_create_reuses_the_translation_metadata_and_never_translates_again() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../input/shader_cache/titles/GbxGame/src/f861c56a34758d84_0200000000000000.xbox"); + let Ok(blob) = std::fs::read(&path) else { + println!("Trackmania PS f861c56a34758d84 not on disk ({}): check not run", path.display()); + return; + }; + let hash = crate::shader_xlat::fnv1a(&blob); + let mode = tombox_xshader::pack_key::Mode { cbv_raw: tombox_xshader::pack_key::CbvRaw::Copy, loop_grad: false, fma: Default::default() }; + let count = || crate::shader_xlat::RUNTIME_SOURCES.with(|c| c.get()); + let n0 = count(); + let _ = crate::shader_xlat::runtime_source(&blob, hash, &[2, 0, 0, 0, 0, 0, 0, 0], &tombox_xshader::hlsl::InputInterp::default(), None, &mode); + assert_eq!(count(), n0 + 1); + let meta = shader_cb(hash).expect("the copy-mode translation records the shader's constant buffer sizes"); + let &(reg, space, bytes) = meta.sizes.first().expect("f861 declares constant buffers"); + let mut desc = vec![0u8; 0x58]; + desc[0x18..0x20].copy_from_slice(&(blob.as_ptr() as u64).to_le_bytes()); + desc[0x20..0x28].copy_from_slice(&(blob.len() as u64).to_le_bytes()); + let (pso, rs) = (0x7f00_c0de_0001usize, 0x7f00_c0de_0002usize); + let mut out = pso as *mut c_void; + let n1 = count(); + unsafe { record_pso(0, desc.as_ptr(), &mut out, &GFX_STAGES) }; + let got = with(|e| { + e.rs_params.insert(rs, vec![(5, reg, space, 0)]); + let ok = e.materialize(pso, &shader_cb); + let r = (ok, e.pso_stages.get(&pso).cloned(), e.declared(Some(pso), rs, 5)); + e.rs_params.remove(&rs); + e.pso_stages.remove(&pso); + e.pso_sizes.remove(&pso); + e.cb_limits.remove(&pso); + r + }); + assert_eq!(count(), n1, "a PSO create in copy mode must not run the translator again"); + assert_eq!(got.0, true); + assert_eq!(got.1, Some(vec![(5, hash)])); + assert_eq!(got.2, Some(bytes)); + } + + #[test] + fn pso_sizes_come_from_the_recorded_translation_metadata() { + let m = ShaderCb { sizes: vec![(13, 0, 0x140), (2, 1, 0x40)], limits: vec![(13, 0, 0x44)] }; + assert_eq!(decode_meta(&encode_meta(&m)), Some(m.clone())); + assert_eq!(decode_meta(b"TBCBM1\x01"), None); + assert_eq!(decode_meta(b"junk"), None); + let mut e = Engine::default(); + e.rs_params.insert(0x77, vec![(3, 13, 0, 0)]); + e.pso_stages.insert(0x99, vec![(1, 0xaaa), (5, 0xbbb)]); + let only_ps = |h: u64| (h == 0xbbb).then(|| m.clone()); + assert!(!e.materialize(0x99, &only_ps)); + assert_eq!(e.declared(Some(0x99), 0x77, 3), None); + let both = |h: u64| match h { + 0xaaa => Some(ShaderCb::default()), + 0xbbb => Some(m.clone()), + _ => None, + }; + assert!(e.materialize(0x99, &both)); + assert_eq!(e.declared(Some(0x99), 0x77, 3), Some(0x140)); + assert_eq!(e.limit(Some(0x99), 0x77, 3), Some(0x44)); + } + + #[test] + fn translator_limits_map_to_register_and_space_and_skip_bindless() { + let mut m = std::collections::BTreeMap::new(); + m.insert(13, 0xffff_ffffu64 * 16); + m.insert((1 << 16) | 2, 0x20); + m.insert(0x8000_0005, 0x40); + assert_eq!(slot_limits(&m), vec![(13, 0, 0xffff_ffff * 16), (2, 1, 0x20)]); + let mut e = Engine::default(); + e.rs_params.insert(0x77, vec![(3, 13, 0, 5), (4, 2, 1, 0)]); + e.pso_sizes.insert(0x99, vec![(5, 13, 0, 0x1000), (5, 2, 1, 0x100), (1, 2, 1, 0x80)]); + e.cb_limits.insert(0x99, vec![(5, 13, 0, 0xffff_ffff * 16), (5, 2, 1, 0x20)]); + assert_eq!(e.limit(Some(0x99), 0x77, 3), Some(0xffff_ffff * 16)); + assert_eq!(e.limit(Some(0x99), 0x77, 4), None); + e.cb_limits.insert(0x99, vec![(5, 13, 0, 0xffff_ffff * 16), (5, 2, 1, 0x20), (1, 2, 1, 0x30)]); + assert_eq!(e.limit(Some(0x99), 0x77, 4), Some(0x30)); + let p = size_plan(e.declared(Some(0x99), 0x77, 3), 0x400, e.limit(Some(0x99), 0x77, 3)).unwrap(); + assert_eq!(p, SizePlan { alloc: 0x1000, copy: 0x400, zero: 0xc00 }); + } + + #[test] + fn size_and_clamp_maths() { + assert_eq!(size_plan(Some(64), 0x1000, None), Some(SizePlan { alloc: 256, copy: 256, zero: 0 })); + assert_eq!(size_plan(Some(336), 100, None), Some(SizePlan { alloc: 512, copy: 100, zero: 412 })); + assert_eq!(size_plan(Some(0), 8, None), Some(SizePlan { alloc: 256, copy: 8, zero: 248 })); + assert_eq!(size_plan(Some(1 << 20), 1 << 20, None), Some(SizePlan { alloc: MAX_CB, copy: MAX_CB, zero: 0 })); + assert_eq!(size_plan(None, 1 << 30, None), Some(SizePlan { alloc: MAX_CB, copy: MAX_CB, zero: 0 })); + assert_eq!(size_plan(None, 0x130, None), Some(SizePlan { alloc: MAX_CB, copy: 0x130, zero: MAX_CB - 0x130 })); + assert_eq!(size_plan(None, 0, None), None); + assert_eq!(size_plan(Some(MAX_CB), 1 << 20, Some(0x340)), Some(SizePlan { alloc: MAX_CB, copy: 0x340, zero: MAX_CB - 0x340 })); + assert_eq!(size_plan(Some(0x200), 0x1000, Some(0)), Some(SizePlan { alloc: 0x200, copy: 0, zero: 0x200 })); + assert_eq!(size_plan(Some(0x200), 0x80, Some(0x100)), Some(SizePlan { alloc: 0x200, copy: 0x80, zero: 0x180 })); + assert_eq!(round_up(257, 256), 512); + assert_eq!(source_barrier(0), None); + assert_eq!(source_barrier(0xac3), None); + assert_eq!(source_barrier(0x800), None); + assert_eq!(source_barrier(0x1), Some((0x1, 0x801))); + assert_eq!(source_barrier(0x8), Some((0x8, 0x800))); + } + + #[test] + fn ring_allocates_aligned_slots_grows_and_reuses_after_the_fence() { + let mut r = Ring::default(); + let never = |_: usize, _: u64| false; + assert_eq!(r.alloc(1, 64, &never), None); + let c0 = r.add_chunk(0xa, 0x10000); + assert_eq!(r.alloc(1, 64, &never), Some((c0, 0))); + assert_eq!(r.alloc(1, 300, &never), Some((c0, 256))); + assert_eq!(r.alloc(1, 256, &never), Some((c0, 768))); + assert_eq!(r.loc(c0, 768), (0xa, 0x10000 + 768)); + assert_eq!(r.alloc(2, 64, &never), None); + let c1 = r.add_chunk(0xb, 0x900000); + assert_eq!(r.alloc(2, 64, &never), Some((c1, 0))); + assert_eq!(r.alloc(1, CHUNK_BYTES, &never), None); + let c2 = r.add_chunk(0xc, 0x400000); + assert_eq!(r.alloc(1, CHUNK_BYTES, &never), Some((c2, 0))); + assert_eq!(r.alloc(1, 1, &never), None); + assert_eq!(r.alloc(1, CHUNK_BYTES + 1, &never), None); + r.set_state(1, c0, ST_VCB); + assert_eq!(r.state(1, c0), ST_VCB); + r.stamp(1, 0xf, 5); + r.stamp(1, 0xf, 7); + r.stamp(1, 0xf, 6); + assert_eq!(r.state(1, c0), ST_COMMON); + r.release(1); + assert_eq!(r.retired_count(), 2); + assert_eq!(r.alloc(3, 64, &|_, v| v <= 6), None); + assert_eq!(r.retired_count(), 2); + let got = r.alloc(3, 64, &|f, v| f == 0xf && v <= 7).unwrap(); + assert!(got.0 == c0 || got.0 == c2); + assert_eq!(got.1, 0); + assert_eq!(r.retired_count(), 0); + r.release(2); + assert!(r.free_count() >= 2); + let back = r.alloc(4, 64, &never).unwrap(); + assert_eq!(back, (c1, 0)); + } + + #[test] + fn unaligned_root_cbvs_pend_and_aligned_ones_forward() { + let mut e = Engine::default(); + assert_eq!(e.on_root_cbv(1, SIDE_GRAPHICS, 3, 0x1000, false), Action::Forward); + assert_eq!(e.on_root_cbv(1, SIDE_GRAPHICS, 3, 0x10b0, false), Action::Hold); + assert_eq!(e.on_root_cbv(1, SIDE_COMPUTE, 0, 0x2030, false), Action::Hold); + assert_eq!(e.on_root_cbv(1, SIDE_GRAPHICS, 4, 0x2030, true), Action::Forward); + assert_eq!(e.pending(1), vec![((0, 0), 0x2030), ((1, 3), 0x10b0)]); + assert_eq!(e.on_root_cbv(1, SIDE_GRAPHICS, 3, 0x2000, false), Action::Forward); + assert_eq!(e.pending(1), vec![((0, 0), 0x2030)]); + e.on_root_signature(1, SIDE_COMPUTE, 0x77); + assert!(e.pending(1).is_empty()); + e.on_root_cbv(1, SIDE_COMPUTE, 0, 0x2030, false); + e.on_root_signature(1, SIDE_COMPUTE, 0x77); + assert_eq!(e.pending(1).len(), 1); + e.on_root_signature(1, SIDE_GRAPHICS, 0x88); + assert_eq!(e.pending(1).len(), 1); + e.clear_state(1); + assert!(e.pending(1).is_empty()); + } + + #[test] + fn draws_copy_once_and_dedupe_until_a_title_write() { + let mut e = Engine::default(); + let look = src(0x5550, 0xbe2_0000, 0x1000); + let mut made = Vec::new(); + let mut mk = || { + made.push(()); + Some((0xc000usize + made.len(), 0x7000_0000u64 * made.len() as u64)) + }; + let done = |_: usize, _: u64| true; + e.rs_params.insert(0x77, vec![(2, 13, 0, 5)]); + e.pso_sizes.insert(0x99, vec![(5, 13, 0, 0x470), (1, 0, 0, 0x40)]); + assert_eq!(e.declared(Some(0x99), 0x77, 2), Some(0x470)); + assert_eq!(e.declared(Some(0x99), 0x77, 3), None); + assert_eq!(e.declared(None, 0x77, 2), None); + e.on_root_signature(1, SIDE_GRAPHICS, 0x77); + e.on_root_cbv(1, SIDE_GRAPHICS, 2, 0xbe2_00b0, false); + let j = e.plan(1, 0xd, 0, MASK_GRAPHICS, Some(0x99), &look, &mut mk, &done); + assert_eq!(j.copies, vec![CopyOp { dst: 0xc001, dst_off: 0, src: 0x5550, src_off: 0xb0, n: 0x500, zero: 0 }]); + assert_eq!(j.chunks, vec![(0xc001, ST_COMMON, ST_VCB)]); + assert_eq!(j.binds, vec![(SIDE_GRAPHICS, 2, 0x7000_0000)]); + assert!(j.sources.is_empty()); + assert!(!e.has_pending(1, MASK_GRAPHICS)); + assert_eq!(e.plan(1, 0xd, 0, MASK_GRAPHICS, Some(0x99), &look, &mut mk, &done), Job::default()); + assert_eq!(e.on_root_cbv(1, SIDE_GRAPHICS, 2, 0xbe2_00b0, false), Action::Provisional(0x7000_0000)); + let j = e.plan(1, 0xd, 0, MASK_GRAPHICS, Some(0x99), &look, &mut mk, &done); + assert!(j.copies.is_empty()); + assert_eq!(j.binds, vec![(SIDE_GRAPHICS, 2, 0x7000_0000)]); + e.invalidate(1); + assert_eq!(e.on_root_cbv(1, SIDE_GRAPHICS, 2, 0xbe2_00b0, false), Action::Hold); + let j = e.plan(1, 0xd, 0, MASK_GRAPHICS, Some(0x99), &look, &mut mk, &done); + assert_eq!(j.copies.len(), 1); + assert_eq!(j.copies[0].dst_off, 0x500); + assert_eq!(j.chunks, vec![(0xc001, ST_VCB, ST_VCB)]); + assert_eq!(j.binds, vec![(SIDE_GRAPHICS, 2, 0x7000_0500)]); + e.on_root_cbv(1, SIDE_GRAPHICS, 2, 0xbe2_0ff0, false); + let j = e.plan(1, 0xd, 0, MASK_GRAPHICS, Some(0x99), &look, &mut mk, &done); + assert_eq!((j.copies[0].n, j.copies[0].zero), (0x10, 0x4f0)); + e.on_root_cbv(1, SIDE_GRAPHICS, 2, 0x4440, false); + let j = e.plan(1, 0xd, 0, MASK_GRAPHICS, Some(0x99), &look, &mut mk, &done); + assert_eq!(j.unresolved, vec![(SIDE_GRAPHICS, 2, 0x4440)]); + e.on_root_cbv(1, SIDE_COMPUTE, 0, 0xbe2_0010, false); + let j = e.plan(1, 0xd, 0, MASK_GRAPHICS, None, &look, &mut mk, &done); + assert_eq!(j, Job::default()); + let j = e.plan(1, 0xd, 0, MASK_COMPUTE, None, &look, &mut mk, &done); + assert_eq!((j.copies[0].n, j.copies[0].zero), (0xff0, MAX_CB - 0xff0)); + assert_eq!(made.len(), 1); + assert!(e.holds(1)); + e.stamp(1, 0xf, 9); + e.forget(1); + assert!(!e.holds(1)); + assert!(e.pending(1).is_empty()); + } + + #[test] + fn default_heap_sources_get_a_copy_source_barrier() { + let mut e = Engine::default(); + let look = |va: u64| Some(Src { res: 0x42, off: va & 0xff, left: 0x100, state: ST_VCB }); + let mut mk = || Some((0xc0, 0x9000u64)); + e.on_root_cbv(1, SIDE_GRAPHICS, 0, 0x30, false); + e.on_root_cbv(1, SIDE_GRAPHICS, 1, 0x50, false); + let j = e.plan(1, 0xd, 0, MASK_GRAPHICS, None, &look, &mut mk, &|_, _| true); + assert_eq!(j.sources, vec![(0x42, ST_VCB, ST_VCB | ST_COPY_SOURCE)]); + assert_eq!(j.copies.len(), 2); + assert_eq!(j.chunks.len(), 1); + } + + #[test] + fn every_hooked_slot_has_a_thunk_and_draws_resolve_the_right_side() { + for s in DRAW_SLOTS.iter().chain(WRITE_SLOTS.iter()).chain([X_CLEAR_STATE].iter()) { + assert_ne!(late_thunk(*s), 0, "slot {s}"); + } + assert_eq!(slot_mask(X_DRAW), MASK_GRAPHICS); + assert_eq!(slot_mask(X_DISPATCH), MASK_COMPUTE); + assert_eq!(slot_mask(X_EXECUTE_INDIRECT), MASK_COMPUTE | MASK_GRAPHICS); + assert_eq!(slot_mask(15), 0); + assert!(slot_writes(15) && slot_writes(26) && slot_writes(X_DISPATCH) && !slot_writes(X_DRAW)); + assert_eq!(crate::cmdlist_wrap::map_slot(X_COMPUTE_ROOT_CBV), Some(PC_SET_COMPUTE_ROOT_CBV)); + assert_eq!(crate::cmdlist_wrap::map_slot(X_GRAPHICS_ROOT_CBV), Some(PC_SET_GRAPHICS_ROOT_CBV)); + assert_eq!(crate::cmdlist_wrap::map_slot(X_SET_GRAPHICS_RS), Some(30)); + } + + static T_PREV: AtomicUsize = AtomicUsize::new(0); + static T_SEEN: Mutex> = Mutex::new(Vec::new()); + + unsafe extern "system" fn t_target(this: *mut c_void, a: u64, b: u32, x: f32, e: u64, f: u64) { + T_SEEN.lock().unwrap().push((this as usize, a, b, x, e, f)); + } + + #[test] + fn late_thunks_forward_every_argument_unchanged() { + T_PREV.store(t_target as usize, Ordering::Relaxed); + LATE_PREV[88].store(t_target as usize, Ordering::Relaxed); + let f: unsafe extern "system" fn(*mut c_void, u64, u32, f32, u64, u64) = unsafe { core::mem::transmute(late_thunk(88)) }; + unsafe { f(0x1234 as *mut c_void, 0xdead_beef_0000_1111, 77, 2.5, 0x5555, 0x6666) }; + assert_eq!(T_SEEN.lock().unwrap().pop(), Some((0x1234, 0xdead_beef_0000_1111, 77, 2.5, 0x5555, 0x6666))); + } +} diff --git a/crates/compat/d3d12_xs/src/cbv_copy_hw.rs b/crates/compat/d3d12_xs/src/cbv_copy_hw.rs new file mode 100644 index 00000000..88f0a6af --- /dev/null +++ b/crates/compat/d3d12_xs/src/cbv_copy_hw.rs @@ -0,0 +1,793 @@ +use super::*; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +const IID_DEV: Guid = Guid { d1: 0x1898_19f1, d2: 0x1db6, d3: 0x4b57, d4: [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7] }; +const IID_RES: Guid = Guid { d1: 0x6964_42be, d2: 0xa72e, d3: 0x4059, d4: [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad] }; +const IID_QUEUE: Guid = Guid { d1: 0x0ec8_70a6, d2: 0x5d7e, d3: 0x4c22, d4: [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed] }; +const IID_ALLOCATOR: Guid = Guid { d1: 0x6102_dee4, d2: 0xaf59, d3: 0x4b09, d4: [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24] }; +const IID_LIST: Guid = Guid { d1: 0x5b16_0d0f, d2: 0xac1b, d3: 0x4185, d4: [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55] }; +const IID_FENCE: Guid = Guid { d1: 0x0a75_3dcf, d2: 0xc4d8, d3: 0x4b91, d4: [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76] }; +const IID_ROOT_SIGNATURE: Guid = Guid { d1: 0xc54a_6b66, d2: 0x72df, d3: 0x4ee8, d4: [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14] }; +const IID_PSO: Guid = Guid { d1: 0x765a_30f3, d2: 0xf624, d3: 0x4c6f, d4: [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45] }; +const IID_DESC_HEAP: Guid = Guid { d1: 0x8efb_471d, d2: 0x616c, d3: 0x4f49, d4: [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51] }; +const IID_FACTORY4: Guid = Guid { d1: 0x1bc6_ea02, d2: 0xef36, d3: 0x464f, d4: [0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a] }; +const IID_ADAPTER: Guid = Guid { d1: 0x2411_e7e1, d2: 0x12ac, d3: 0x4ccf, d4: [0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0] }; +const IID_DEBUG: Guid = Guid { d1: 0x344488b7, d2: 0x6846, d3: 0x474b, d4: [0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0] }; +const IID_INFO_QUEUE: Guid = Guid { d1: 0x0742_a90b, d2: 0xc387, d3: 0x483f, d4: [0xb9, 0x46, 0x30, 0xa7, 0xe4, 0xe6, 0x14, 0x58] }; + +const HEAP_DEFAULT: u32 = 1; +const HEAP_UPLOAD: u32 = 2; +const HEAP_READBACK: u32 = 3; +const ST_RT: u32 = 0x4; +const ST_UAV: u32 = 0x8; +const ST_NPSR: u32 = 0x40; +const ST_GENERIC_READ: u32 = 0xac3; +const FMT_RGBA32_UINT: u32 = 3; +const LIST_DIRECT: u32 = 0; +const LIST_COMPUTE: u32 = 2; +const N: usize = 20; +const CB_BYTES: usize = N * 16; +const PITCH: u64 = 512; + +const P_CLOSE: usize = 9; +const P_RESET: usize = 10; +const P_DRAW: usize = 12; +const P_DISPATCH: usize = 14; +const P_COPY_TEXTURE: usize = 16; +const P_TOPOLOGY: usize = 20; +const P_VIEWPORTS: usize = 21; +const P_SCISSORS: usize = 22; +const P_PSO: usize = 25; +const P_BARRIER: usize = 26; +const P_COMPUTE_RS: usize = 29; +const P_GRAPHICS_RS: usize = 30; +const P_COMPUTE_SRV: usize = 39; +const P_GRAPHICS_SRV: usize = 40; +const P_COMPUTE_UAV: usize = 41; +const P_RTS: usize = 46; + +macro_rules! call { + ($o:expr, $i:expr, ($($t:ty),*) -> $r:ty $(, $a:expr)*) => {{ + let o = $o as *mut c_void; + let f: unsafe extern "system" fn(*mut c_void $(, $t)*) -> $r = core::mem::transmute(vslot(o, $i)); + f(o $(, $a)*) + }}; +} + +extern "system" { + fn LoadLibraryW(p: *const u16) -> *mut c_void; + fn GetProcAddress(h: *mut c_void, n: *const u8) -> *mut c_void; +} + +fn warp() -> bool { + std::env::var("TOMBOX_HW_ADAPTER").map(|v| v.eq_ignore_ascii_case("warp")).unwrap_or(false) +} + +fn locked() -> Option { + for d in ["D:/TomBox/tools/dev", "D:/TomBox/tools/dev/batch_runs"] { + let Ok(rd) = std::fs::read_dir(d) else { continue }; + for e in rd.flatten() { + let n = e.file_name().to_string_lossy().to_ascii_uppercase(); + if n.starts_with("GAME_LOCK") || n.starts_with("USER_PLAYING") { + return Some(format!("{d}/{}", e.file_name().to_string_lossy())); + } + } + } + None +} + +fn skip() -> bool { + if warp() { + return false; + } + match locked() { + Some(p) => { + eprintln!("SKIPPED: {p} exists, so the hardware GPU is in use; rerun with TOMBOX_HW_ADAPTER=warp or once the lock is gone"); + true + } + None => false, + } +} + +struct Gpu { + dev: usize, + gq: usize, + cq: usize, + info: usize, +} + +unsafe impl Send for Gpu {} +unsafe impl Sync for Gpu {} + +unsafe fn warp_adapter() -> *mut c_void { + let name: Vec = "dxgi.dll\0".encode_utf16().collect(); + let h = unsafe { LoadLibraryW(name.as_ptr()) }; + assert!(!h.is_null()); + let p = unsafe { GetProcAddress(h, b"CreateDXGIFactory2\0".as_ptr()) }; + assert!(!p.is_null()); + let create: unsafe extern "system" fn(u32, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(p) }; + let mut f: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { create(0, &IID_FACTORY4, &mut f) } >= 0); + let mut a: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { call!(f, 27, (*const Guid, *mut *mut c_void) -> i32, &IID_ADAPTER, &mut a) } >= 0); + a +} + +unsafe fn make_queue(dev: usize, ty: u32) -> usize { + let desc = [ty, 0, 0, 0]; + let mut q: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { call!(dev, 8, (*const u32, *const Guid, *mut *mut c_void) -> i32, desc.as_ptr(), &IID_QUEUE, &mut q) } >= 0); + q as usize +} + +fn gpu() -> &'static Gpu { + static G: OnceLock = OnceLock::new(); + G.get_or_init(|| unsafe { + crate::enable_experimental_shader_models(); + let debug = std::env::var("TOMBOX_D3D12_DEBUG").is_ok(); + if debug { + let p = crate::host_proc(b"D3D12GetDebugInterface\0"); + let mut dbg: *mut c_void = core::ptr::null_mut(); + let hr = if p == 0 { -1 } else { + let get: unsafe extern "system" fn(*const Guid, *mut *mut c_void) -> i32 = core::mem::transmute(p); + get(&IID_DEBUG, &mut dbg) + }; + if hr >= 0 && !dbg.is_null() { + call!(dbg, 3, () -> ()); + eprintln!("D3D12 debug layer enabled"); + } else { + eprintln!("D3D12 debug layer requested but unavailable (hr={hr:#010x}); running without it"); + } + } + let adapter = if warp() { warp_adapter() } else { core::ptr::null_mut() }; + let p = crate::host_proc(b"D3D12CreateDevice\0"); + let create: extern "system" fn(*mut c_void, u32, *const Guid, *mut *mut c_void) -> i32 = core::mem::transmute(p); + let mut dev: *mut c_void = core::ptr::null_mut(); + let hr = create(adapter, 0xb000, &IID_DEV, &mut dev); + assert!(hr >= 0 && !dev.is_null(), "D3D12CreateDevice ({}) hr={hr:#010x}", if warp() { "WARP" } else { "hardware" }); + let mut info: *mut c_void = core::ptr::null_mut(); + if debug && call!(dev, 0, (*const Guid, *mut *mut c_void) -> i32, &IID_INFO_QUEUE, &mut info) < 0 { + info = core::ptr::null_mut(); + } + let dev = dev as usize; + Gpu { dev, gq: make_queue(dev, LIST_DIRECT), cq: make_queue(dev, LIST_COMPUTE), info: info as usize } + }) +} + +unsafe fn debug_errors(g: &Gpu) -> Vec { + let mut out = Vec::new(); + if g.info == 0 { + return out; + } + let n = unsafe { call!(g.info, 8, () -> u64) }; + for i in 0..n { + let mut len = 0usize; + unsafe { call!(g.info, 5, (u64, *mut u8, *mut usize) -> i32, i, core::ptr::null_mut(), &mut len) }; + if len < 32 { + continue; + } + let mut m = vec![0u64; len.div_ceil(8)]; + if unsafe { call!(g.info, 5, (u64, *mut u8, *mut usize) -> i32, i, m.as_mut_ptr() as *mut u8, &mut len) } < 0 { + continue; + } + let b = m.as_ptr() as *const u8; + let sev = unsafe { *(b.add(4) as *const u32) }; + let text = unsafe { *(b.add(16) as *const *const i8) }; + if sev <= 1 && !text.is_null() { + out.push(unsafe { std::ffi::CStr::from_ptr(text) }.to_string_lossy().into_owned()); + } + } + unsafe { call!(g.info, 4, () -> ()) }; + out +} + +struct Buf { + res: usize, + va: u64, + cpu: *mut u8, +} + +unsafe fn committed(dev: usize, heap: u32, dim: u32, w: u64, fmt: u32, flags: u32, state: u32) -> usize { + let props: [u32; 5] = [heap, 0, 0, 1, 1]; + let mut d = [0u8; 56]; + d[0..4].copy_from_slice(&dim.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&w.to_le_bytes()); + d[0x18..0x1c].copy_from_slice(&1u32.to_le_bytes()); + d[0x1c..0x1e].copy_from_slice(&1u16.to_le_bytes()); + d[0x1e..0x20].copy_from_slice(&1u16.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2c..0x30].copy_from_slice(&(if dim == 1 { 1u32 } else { 0 }).to_le_bytes()); + d[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + let mut r: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { call!(dev, 27, (*const u32, u32, *const u8, u32, *const c_void, *const Guid, *mut *mut c_void) -> i32, + props.as_ptr(), 0, d.as_ptr(), state, core::ptr::null(), &IID_RES, &mut r) }; + assert!(hr >= 0 && !r.is_null(), "CreateCommittedResource dim={dim} heap={heap} hr={hr:#010x}"); + r as usize +} + +unsafe fn buffer(dev: usize, heap: u32, size: u64, flags: u32, state: u32, tracked: Option) -> Buf { + let r = unsafe { committed(dev, heap, 1, size, 0, flags, state) }; + let va = unsafe { call!(r, 11, () -> u64) }; + if let Some(len) = tracked { + crate::gpu_va::insert(crate::gpu_va::Entry { start: va, len, res: r, buffer: true }); + crate::gpu_va::set_state(r, state); + } + let mut cpu: *mut u8 = core::ptr::null_mut(); + if heap != HEAP_DEFAULT { + assert!(unsafe { call!(r, 8, (u32, *const c_void, *mut *mut u8) -> i32, 0, core::ptr::null(), &mut cpu) } >= 0); + } + Buf { res: r, va, cpu } +} + +fn pattern(seed: u32, n: usize) -> Vec { + (0..n / 4).flat_map(|i| ((i as u32).wrapping_mul(0x9e37_79b9) ^ seed ^ 0x0101_0101).to_le_bytes()).collect() +} + +unsafe fn put(b: &Buf, off: usize, data: &[u8]) { + unsafe { core::ptr::copy_nonoverlapping(data.as_ptr(), b.cpu.add(off), data.len()) }; +} + +unsafe fn get(b: &Buf, off: usize, n: usize) -> Vec { + (0..n).map(|i| unsafe { core::ptr::read_volatile(b.cpu.add(off + i)) }).collect() +} + +fn transition_bar(res: usize, before: u32, after: u32) -> [u8; 32] { + let mut b = [0u8; 32]; + b[8..16].copy_from_slice(&(res as u64).to_le_bytes()); + b[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + b[20..24].copy_from_slice(&before.to_le_bytes()); + b[24..28].copy_from_slice(&after.to_le_bytes()); + b +} + +unsafe fn barrier(l: usize, res: usize, before: u32, after: u32) { + let b = transition_bar(res, before, after); + unsafe { call!(l, P_BARRIER, (u32, *const [u8; 32]) -> (), 1, &b) }; +} + +struct Run { + alloc: usize, + list: usize, + queue: usize, + fence: usize, + value: u64, +} + +unsafe fn run_new(g: &Gpu, ty: u32) -> Run { + let mut a: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { call!(g.dev, 9, (u32, *const Guid, *mut *mut c_void) -> i32, ty, &IID_ALLOCATOR, &mut a) } >= 0); + let mut l: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { call!(g.dev, 12, (u32, u32, *mut c_void, *mut c_void, *const Guid, *mut *mut c_void) -> i32, 0, ty, a, core::ptr::null_mut(), &IID_LIST, &mut l) } >= 0); + let mut f: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { call!(g.dev, 36, (u64, u32, *const Guid, *mut *mut c_void) -> i32, 0, 0, &IID_FENCE, &mut f) } >= 0); + Run { alloc: a as usize, list: l as usize, queue: if ty == LIST_COMPUTE { g.cq } else { g.gq }, fence: f as usize, value: 0 } +} + +unsafe fn execute(g: &Gpu, r: &mut Run) { + assert!(unsafe { call!(r.list, P_CLOSE, () -> i32) } >= 0, "Close failed"); + let l = [r.list as *mut c_void]; + unsafe { call!(r.queue, 10, (u32, *const *mut c_void) -> (), 1, l.as_ptr()) }; + unsafe { stamp_executed(r.queue as *mut c_void, &l) }; + r.value += 1; + assert!(unsafe { call!(r.queue, 14, (*mut c_void, u64) -> i32, r.fence as *mut c_void, r.value) } >= 0); + let t = Instant::now(); + while unsafe { call!(r.fence, 8, () -> u64) } < r.value { + assert!(t.elapsed() < Duration::from_secs(60), "GPU never finished (device removed reason {:#010x})", unsafe { call!(g.dev, 37, () -> i32) }); + std::thread::sleep(Duration::from_millis(1)); + } + let errs = unsafe { debug_errors(g) }; + assert!(errs.is_empty(), "D3D12 debug layer errors:\n{}", errs.join("\n")); +} + +unsafe fn restart(r: &mut Run) { + with(|e| e.forget(r.list)); + assert!(unsafe { call!(r.alloc, 8, () -> i32) } >= 0); + assert!(unsafe { call!(r.list, P_RESET, (*mut c_void, *mut c_void) -> i32, r.alloc as *mut c_void, core::ptr::null_mut()) } >= 0); +} + +fn compile(src: &str, profile: &str) -> Vec { + tombox_xshader::dxc::compile(src, profile).unwrap_or_else(|e| panic!("dxc {profile}: {e}\n{src}")) +} + +unsafe fn root_sig(dev: usize, blob: &[u8]) -> usize { + let mut r: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { call!(dev, 16, (u32, *const u8, usize, *const Guid, *mut *mut c_void) -> i32, 0, blob.as_ptr(), blob.len(), &IID_ROOT_SIGNATURE, &mut r) }; + assert!(hr >= 0 && !r.is_null(), "CreateRootSignature hr={hr:#010x}"); + r as usize +} + +struct Sigs { + copy: usize, + raw: usize, +} + +unsafe fn sigs(dev: usize, rs: &str, stage: &str) -> Sigs { + let probe = if stage == "cs_6_0" { + format!("#define RS \"{rs}\"\n[RootSignature(RS)] [numthreads(1, 1, 1)] void main() {{ }}") + } else { + format!("#define RS \"{rs}\"\n[RootSignature(RS)] float4 main() : SV_Position {{ return 0; }}") + }; + let blob = compile(&probe, stage); + let params = crate::cbv_raw::root_cbv_params(&blob); + assert!(!params.is_empty(), "the copy root signature has no root CBV"); + let (raw_blob, patch) = crate::cbv_raw::patch_blob(&blob).expect("patch_blob").expect("raw root signature"); + assert_eq!(patch.root_cbvs, vec![0]); + let copy = unsafe { root_sig(dev, &blob) }; + let raw = unsafe { root_sig(dev, &raw_blob) }; + with(|e| e.rs_params.insert(copy, params)); + Sigs { copy, raw } +} + +fn cb_decl() -> String { + format!("cbuffer CB0 : register(b0) {{ uint4 cb0[{N}]; }};\n") +} + +fn sizes_for(vis: u32, hlsl: &str) -> Vec<(u32, u32, u32, u64)> { + let v: Vec<(u32, u32, u32, u64)> = tombox_xshader::cbv_raw_hlsl::declared_sizes(hlsl).into_iter().map(|(r, s, b)| (vis, r, s, b)).collect(); + assert_eq!(v, vec![(vis, 0, 0, CB_BYTES as u64)]); + v +} + +const VS: &str = "float4 main(uint id : SV_VertexID) : SV_Position { float2 t = float2((id << 1) & 2, id & 2); return float4(t * float2(2, -2) + float2(-1, 1), 0, 1); }"; + +fn ps_src() -> String { + format!("{}uint4 main(float4 p : SV_Position) : SV_Target {{ return cb0[(uint)p.x]; }}\n", cb_decl()) +} + +fn cs_src() -> String { + format!("{}RWByteAddressBuffer o : register(u0);\n[numthreads({N}, 1, 1)] void main(uint i : SV_GroupThreadID) {{ o.Store4(i * 16, cb0[i]); }}\n", cb_decl()) +} + +struct Gfx { + sigs: Sigs, + copy_pso: usize, + raw_pso: usize, + rt: usize, + rtv: usize, + rb: Buf, + _keep: Vec>, +} + +unsafe fn gfx_pso(dev: usize, rs: usize, vs: &[u8], ps: &[u8]) -> usize { + let mut d = vec![0u8; 0x290]; + let mut w = |o: usize, v: &[u8]| d[o..o + v.len()].copy_from_slice(v); + w(0, &(rs as u64).to_le_bytes()); + w(0x08, &(vs.as_ptr() as u64).to_le_bytes()); + w(0x10, &(vs.len() as u64).to_le_bytes()); + w(0x18, &(ps.as_ptr() as u64).to_le_bytes()); + w(0x20, &(ps.len() as u64).to_le_bytes()); + w(0x78, &crate::dbcount::default_blend()); + w(0x1c0, &u32::MAX.to_le_bytes()); + w(0x1c4, &3u32.to_le_bytes()); + w(0x1c8, &1u32.to_le_bytes()); + w(0x1dc, &1u32.to_le_bytes()); + w(0x23c, &3u32.to_le_bytes()); + w(0x240, &1u32.to_le_bytes()); + w(0x244, &FMT_RGBA32_UINT.to_le_bytes()); + w(0x268, &1u32.to_le_bytes()); + let mut p: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { call!(dev, 10, (*const u8, *const Guid, *mut *mut c_void) -> i32, d.as_ptr(), &IID_PSO, &mut p) }; + assert!(hr >= 0 && !p.is_null(), "CreateGraphicsPipelineState hr={hr:#010x}"); + p as usize +} + +unsafe fn compute_pso(dev: usize, rs: usize, cs: &[u8]) -> usize { + let mut d = [0u8; 56]; + d[0..8].copy_from_slice(&(rs as u64).to_le_bytes()); + d[8..16].copy_from_slice(&(cs.as_ptr() as u64).to_le_bytes()); + d[16..24].copy_from_slice(&(cs.len() as u64).to_le_bytes()); + let mut p: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { call!(dev, 11, (*const u8, *const Guid, *mut *mut c_void) -> i32, d.as_ptr(), &IID_PSO, &mut p) }; + assert!(hr >= 0 && !p.is_null(), "CreateComputePipelineState hr={hr:#010x}"); + p as usize +} + +unsafe fn gfx(g: &Gpu) -> Gfx { + let sigs = unsafe { sigs(g.dev, "RootFlags(0), CBV(b0, visibility=SHADER_VISIBILITY_PIXEL)", "vs_6_0") }; + let ps_text = ps_src(); + let raw_text = tombox_xshader::cbv_raw_hlsl::rewrite_hlsl(&ps_text).expect("rewrite_hlsl"); + assert!(raw_text.contains("Load4"), "raw PS was not rewritten:\n{raw_text}"); + let vs = compile(VS, "vs_6_0"); + let ps = compile(&ps_text, "ps_6_0"); + let raw_ps = compile(&raw_text, "ps_6_0"); + let copy_pso = unsafe { gfx_pso(g.dev, sigs.copy, &vs, &ps) }; + let raw_pso = unsafe { gfx_pso(g.dev, sigs.raw, &vs, &raw_ps) }; + with(|e| e.pso_sizes.insert(copy_pso, sizes_for(5, &ps_text))); + let rt = unsafe { committed(g.dev, HEAP_DEFAULT, 3, N as u64, FMT_RGBA32_UINT, 1, ST_RT) }; + let hd = [2u32, 1, 0, 0]; + let mut h: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { call!(g.dev, 14, (*const u32, *const Guid, *mut *mut c_void) -> i32, hd.as_ptr(), &IID_DESC_HEAP, &mut h) } >= 0); + let mut rtv = 0usize; + let ret = unsafe { call!(h, 9, (*mut usize) -> usize, &mut rtv) }; + if ret != &mut rtv as *mut usize as usize { + rtv = ret; + } + unsafe { call!(g.dev, 20, (*mut c_void, *const c_void, usize) -> (), rt as *mut c_void, core::ptr::null(), rtv) }; + let rb = unsafe { buffer(g.dev, HEAP_READBACK, PITCH, 0, ST_COPY_DEST, None) }; + Gfx { sigs, copy_pso, raw_pso, rt, rtv, rb, _keep: vec![vs, ps, raw_ps] } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Via { + Raw, + Copy, +} + +unsafe fn record_draw(f: &Gfx, l: usize, via: Via, va: u64) { + unsafe { + call!(l, P_RTS, (u32, *const usize, i32, *const usize) -> (), 1, &f.rtv, 0, core::ptr::null()); + let vp = [0f32, 0.0, N as f32, 1.0, 0.0, 1.0]; + call!(l, P_VIEWPORTS, (u32, *const f32) -> (), 1, vp.as_ptr()); + let sc = [0i32, 0, N as i32, 1]; + call!(l, P_SCISSORS, (u32, *const i32) -> (), 1, sc.as_ptr()); + call!(l, P_TOPOLOGY, (u32) -> (), 4); + match via { + Via::Raw => { + call!(l, P_GRAPHICS_RS, (usize) -> (), f.sigs.raw); + call!(l, P_PSO, (usize) -> (), f.raw_pso); + call!(l, P_GRAPHICS_SRV, (u32, u64) -> (), 0, va); + } + Via::Copy => { + let lp = l as *mut c_void; + call!(l, P_GRAPHICS_RS, (usize) -> (), f.sigs.copy); + with(|e| e.on_root_signature(l, SIDE_GRAPHICS, f.sigs.copy)); + call!(l, P_PSO, (usize) -> (), f.copy_pso); + set_root_cbv(lp, SIDE_GRAPHICS, 0, va, &|v| bind(lp, SIDE_GRAPHICS, 0, v)); + resolve_with(lp, MASK_GRAPHICS, Some(f.copy_pso), None); + assert!(!with(|e| e.has_pending(l, MASK_GRAPHICS)), "the draw left a root CBV pending"); + } + } + call!(l, P_DRAW, (u32, u32, u32, u32) -> (), 3, 1, 0, 0); + barrier(l, f.rt, ST_RT, ST_COPY_SOURCE); + let mut dst = [0u8; 48]; + dst[0..8].copy_from_slice(&(f.rb.res as u64).to_le_bytes()); + dst[8..12].copy_from_slice(&1u32.to_le_bytes()); + dst[24..28].copy_from_slice(&FMT_RGBA32_UINT.to_le_bytes()); + dst[28..32].copy_from_slice(&(N as u32).to_le_bytes()); + dst[32..36].copy_from_slice(&1u32.to_le_bytes()); + dst[36..40].copy_from_slice(&1u32.to_le_bytes()); + dst[40..44].copy_from_slice(&(PITCH as u32).to_le_bytes()); + let mut src = [0u8; 48]; + src[0..8].copy_from_slice(&(f.rt as u64).to_le_bytes()); + call!(l, P_COPY_TEXTURE, (*const u8, u32, u32, u32, *const u8, *const c_void) -> (), dst.as_ptr(), 0, 0, 0, src.as_ptr(), core::ptr::null()); + barrier(l, f.rt, ST_COPY_SOURCE, ST_RT); + } +} + +fn slots(l: usize) -> Vec { + with(|e| e.lists.get(&l).map(|s| s.dedupe.values().copied().collect()).unwrap_or_default()) +} + +unsafe fn draw_once(g: &Gpu, f: &Gfx, r: &mut Run, via: Via, va: u64) -> (Vec, Vec) { + unsafe { + core::ptr::write_bytes(f.rb.cpu, 0xcd, PITCH as usize); + record_draw(f, r.list, via, va); + let s = slots(r.list); + execute(g, r); + let out = get(&f.rb, 0, CB_BYTES); + restart(r); + (out, s) + } +} + +fn hexdiff(a: &[u8], b: &[u8]) -> String { + a.chunks(16).zip(b.chunks(16)).enumerate().filter(|(_, (x, y))| x != y).take(6) + .map(|(i, (x, y))| format!(" cb0[{i}] got {x:02x?} want {y:02x?}")).collect::>().join("\n") +} + +fn same(what: &str, got: &[u8], want: &[u8]) { + assert_eq!(got.len(), want.len()); + assert!(got == want, "{what} differs:\n{}", hexdiff(got, want)); +} + +struct Gfxs { + f: Gfx, +} + +unsafe impl Send for Gfxs {} +unsafe impl Sync for Gfxs {} + +fn fixture() -> &'static Gfx { + static F: OnceLock = OnceLock::new(); + &F.get_or_init(|| Gfxs { f: unsafe { gfx(gpu()) } }).f +} + +static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +unsafe fn raw_vs_copy(off: usize, tracked_extra: Option, seed: u32) { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let g = gpu(); + let f = fixture(); + let size = 8192usize; + let tracked = tracked_extra.map(|n| (off + n) as u64).unwrap_or(size as u64); + let src = unsafe { buffer(g.dev, HEAP_UPLOAD, size as u64, 0, ST_GENERIC_READ, Some(tracked)) }; + let data = pattern(seed, size); + unsafe { put(&src, 0, &data) }; + let mut want = data[off..off + CB_BYTES].to_vec(); + if let Some(n) = tracked_extra { + want[n..].iter_mut().for_each(|b| *b = 0); + unsafe { put(&src, off + n, &vec![0xa5u8; size - off - n]) }; + } + let va = src.va + off as u64; + let mut r = unsafe { run_new(g, LIST_DIRECT) }; + let (copy, s) = unsafe { draw_once(g, f, &mut r, Via::Copy, va) }; + if va % SLOT_ALIGN == 0 { + assert!(s.is_empty(), "an aligned root CBV was copied: {s:x?}"); + } else { + assert_eq!(s.len(), 1, "an unaligned root CBV was not copied exactly once"); + assert_eq!(s[0] % SLOT_ALIGN, 0); + } + same("cbv_raw=copy output vs the source bytes", ©, &want); + if let Some(n) = tracked_extra { + unsafe { put(&src, off + n, &vec![0u8; size - off - n]) }; + } + let (raw, _) = unsafe { draw_once(g, f, &mut r, Via::Raw, va) }; + same("cbv_raw=copy vs cbv_raw=on (raw SRV) output", ©, &raw); + eprintln!("va={va:#x} (+{:#x} from 256) {} bytes bit-exact raw == copy == source{}", va % SLOT_ALIGN, CB_BYTES, if tracked_extra.is_some() { " with zero tail" } else { "" }); +} + +#[test] +#[ignore = "needs a D3D12 device; run: cargo test -p d3d12_xs --lib hw_cbv_copy -- --ignored --test-threads=1 (TOMBOX_HW_ADAPTER=warp for WARP)"] +fn hw_cbv_copy_aligned_root_cbv_matches_raw() { + if skip() { + return; + } + unsafe { raw_vs_copy(0x200, None, 0x1111_0000) }; +} + +#[test] +#[ignore = "needs a D3D12 device; run: cargo test -p d3d12_xs --lib hw_cbv_copy -- --ignored --test-threads=1 (TOMBOX_HW_ADAPTER=warp for WARP)"] +fn hw_cbv_copy_unaligned_root_cbv_matches_raw() { + if skip() { + return; + } + unsafe { raw_vs_copy(0x2b0, None, 0x2222_0000) }; +} + +#[test] +#[ignore = "needs a D3D12 device; run: cargo test -p d3d12_xs --lib hw_cbv_copy -- --ignored --test-threads=1 (TOMBOX_HW_ADAPTER=warp for WARP)"] +fn hw_cbv_copy_short_source_gets_a_zero_tail_and_matches_raw() { + if skip() { + return; + } + unsafe { raw_vs_copy(0x1e50, Some(100), 0x3333_0000) }; +} + +#[test] +#[ignore = "needs a D3D12 device; run: cargo test -p d3d12_xs --lib hw_cbv_copy -- --ignored --test-threads=1 (TOMBOX_HW_ADAPTER=warp for WARP)"] +fn hw_cbv_copy_two_draws_reuse_a_slot_after_the_fence() { + if skip() { + return; + } + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let g = gpu(); + let f = fixture(); + let a = unsafe { buffer(g.dev, HEAP_UPLOAD, 4096, 0, ST_GENERIC_READ, Some(4096)) }; + let b = unsafe { buffer(g.dev, HEAP_UPLOAD, 4096, 0, ST_GENERIC_READ, Some(4096)) }; + let (da, db) = (pattern(0x4444_0000, 4096), pattern(0x5555_0000, 4096)); + unsafe { put(&a, 0, &da) }; + unsafe { put(&b, 0, &db) }; + let off = 0x150usize; + let hidden = with(|e| { + let ring = e.ring(g.dev); + ring.reclaim(&|f, v| unsafe { crate::cl2_state::fence_passed(f, v) }); + std::mem::take(&mut ring.free) + }); + let mut r = unsafe { run_new(g, LIST_DIRECT) }; + let (c1, s1) = unsafe { draw_once(g, f, &mut r, Via::Copy, a.va + off as u64) }; + same("first copy draw", &c1, &da[off..off + CB_BYTES]); + assert_eq!(s1.len(), 1); + let chunks = with(|e| e.ring(g.dev).chunks.len()); + let retired = with(|e| e.ring(g.dev).retired_count()); + assert!(retired >= 1, "the first list's chunk was not retired behind its fence at Reset"); + let (c2, s2) = unsafe { draw_once(g, f, &mut r, Via::Copy, b.va + off as u64) }; + let grown = with(|e| { + let ring = e.ring(g.dev); + let n = ring.chunks.len(); + ring.free.extend(hidden); + n + }); + same("second copy draw (reused slot)", &c2, &db[off..off + CB_BYTES]); + assert_eq!(s2, s1, "the slot was not reused once its fence passed"); + assert_eq!(grown, chunks, "the ring grew although the old slot was free"); + let mut r2 = unsafe { run_new(g, LIST_DIRECT) }; + let (raw, _) = unsafe { draw_once(g, f, &mut r2, Via::Raw, b.va + off as u64) }; + same("reused-slot copy vs raw", &c2, &raw); + eprintln!("slot {:#x} reused across the fence; both draws bit-exact", s1[0]); +} + +#[test] +#[ignore = "needs a D3D12 device; run: cargo test -p d3d12_xs --lib hw_cbv_copy -- --ignored --test-threads=1 (TOMBOX_HW_ADAPTER=warp for WARP)"] +fn hw_cbv_copy_compute_list_dispatch_matches_raw() { + if skip() { + return; + } + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let g = gpu(); + let sigs = unsafe { sigs(g.dev, "RootFlags(0), CBV(b0), UAV(u0)", "cs_6_0") }; + let cs_text = cs_src(); + let raw_text = tombox_xshader::cbv_raw_hlsl::rewrite_hlsl(&cs_text).expect("rewrite_hlsl"); + let cs = compile(&cs_text, "cs_6_0"); + let raw_cs = compile(&raw_text, "cs_6_0"); + let copy_pso = unsafe { compute_pso(g.dev, sigs.copy, &cs) }; + let raw_pso = unsafe { compute_pso(g.dev, sigs.raw, &raw_cs) }; + with(|e| e.pso_sizes.insert(copy_pso, sizes_for(0, &cs_text))); + let size = 4096u64; + let up = unsafe { buffer(g.dev, HEAP_UPLOAD, size, 0, ST_GENERIC_READ, None) }; + let data = pattern(0x6666_0000, size as usize); + unsafe { put(&up, 0, &data) }; + let src = unsafe { buffer(g.dev, HEAP_DEFAULT, size, 0, ST_COPY_DEST, Some(size)) }; + let uav = unsafe { buffer(g.dev, HEAP_DEFAULT, 1024, 4, ST_UAV, None) }; + let rb = unsafe { buffer(g.dev, HEAP_READBACK, 1024, 0, ST_COPY_DEST, None) }; + let mut setup = unsafe { run_new(g, LIST_DIRECT) }; + unsafe { call!(setup.list, 15, (usize, u64, usize, u64, u64) -> (), src.res, 0, up.res, 0, size) }; + unsafe { execute(g, &mut setup) }; + let off = 0x3d0u64; + let va = src.va + off; + let want = data[off as usize..off as usize + CB_BYTES].to_vec(); + let mut r = unsafe { run_new(g, LIST_COMPUTE) }; + assert_eq!(unsafe { list_type(r.list as *mut c_void) }, LIST_COMPUTE); + let mut outs = Vec::new(); + for via in [Via::Copy, Via::Raw] { + let l = r.list; + let lp = l as *mut c_void; + unsafe { + core::ptr::write_bytes(rb.cpu, 0xcd, 1024); + barrier(l, src.res, ST_COMMON, ST_NPSR); + crate::gpu_va::set_state(src.res, ST_NPSR); + match via { + Via::Raw => { + call!(l, P_COMPUTE_RS, (usize) -> (), sigs.raw); + call!(l, P_PSO, (usize) -> (), raw_pso); + call!(l, P_COMPUTE_SRV, (u32, u64) -> (), 0, va); + call!(l, P_COMPUTE_UAV, (u32, u64) -> (), 1, uav.va); + } + Via::Copy => { + call!(l, P_COMPUTE_RS, (usize) -> (), sigs.copy); + with(|e| e.on_root_signature(l, SIDE_COMPUTE, sigs.copy)); + call!(l, P_PSO, (usize) -> (), copy_pso); + set_root_cbv(lp, SIDE_COMPUTE, 0, va, &|v| bind(lp, SIDE_COMPUTE, 0, v)); + call!(l, P_COMPUTE_UAV, (u32, u64) -> (), 1, uav.va); + resolve_with(lp, MASK_COMPUTE, Some(copy_pso), None); + assert!(!with(|e| e.has_pending(l, MASK_COMPUTE))); + } + } + call!(l, P_DISPATCH, (u32, u32, u32) -> (), 1, 1, 1); + barrier(l, uav.res, ST_UAV, ST_COPY_SOURCE); + call!(l, 15, (usize, u64, usize, u64, u64) -> (), rb.res, 0, uav.res, 0, CB_BYTES as u64); + barrier(l, uav.res, ST_COPY_SOURCE, ST_UAV); + barrier(l, src.res, ST_NPSR, ST_COMMON); + crate::gpu_va::set_state(src.res, ST_COMMON); + let s = slots(l); + if via == Via::Copy { + assert_eq!(s.len(), 1, "the unaligned compute root CBV was not copied"); + } + execute(g, &mut r); + outs.push(get(&rb, 0, CB_BYTES)); + restart(&mut r); + } + } + same("compute cbv_raw=copy output vs source", &outs[0], &want); + same("compute cbv_raw=copy vs cbv_raw=on", &outs[0], &outs[1]); + eprintln!("compute list (type 2) on the compute queue: va={va:#x}, DEFAULT-heap source in NON_PIXEL_SHADER_RESOURCE, {CB_BYTES} bytes bit-exact raw == copy == source"); +} + +#[test] +#[ignore = "needs a D3D12 device; run: cargo test -p d3d12_xs --lib hw_cbv_copy -- --ignored --test-threads=1 (TOMBOX_HW_ADAPTER=warp for WARP)"] +fn hw_cbv_copy_nr_limit_copies_only_nr_bytes_and_zero_fills_the_slot() { + if skip() { + return; + } + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let g = gpu(); + let f = fixture(); + let src = unsafe { buffer(g.dev, HEAP_UPLOAD, 4096, 0, ST_GENERIC_READ, Some(4096)) }; + let data = pattern(0x7777_0000, 4096); + unsafe { put(&src, 0, &data) }; + let off = 0x1b0usize; + let nr = 0x44usize; + let mut want = data[off..off + CB_BYTES].to_vec(); + want[nr..].iter_mut().for_each(|b| *b = 0); + with(|e| e.cb_limits.insert(f.copy_pso, vec![(5, 0, 0, nr as u64)])); + let mut r = unsafe { run_new(g, LIST_DIRECT) }; + let (copy, s) = unsafe { draw_once(g, f, &mut r, Via::Copy, src.va + off as u64) }; + with(|e| e.cb_limits.remove(&f.copy_pso)); + assert_eq!(s.len(), 1); + same("NR-limited copy (data up to NR*stride, zeros after)", ©, &want); + let (full, _) = unsafe { draw_once(g, f, &mut r, Via::Copy, src.va + off as u64) }; + same("copy without a limit", &full, &data[off..off + CB_BYTES]); + eprintln!("NR*stride={nr:#x}: {nr} bytes copied, the remaining {} bytes of the slot read as zero", CB_BYTES - nr); +} + +unsafe fn heap_handles(dev: usize) -> (usize, usize, u64) { + let hd = [0u32, 1, 1, 0]; + let mut h: *mut c_void = core::ptr::null_mut(); + assert!(unsafe { call!(dev, 14, (*const u32, *const Guid, *mut *mut c_void) -> i32, hd.as_ptr(), &IID_DESC_HEAP, &mut h) } >= 0); + let mut cpu = 0usize; + let ret = unsafe { call!(h, 9, (*mut usize) -> usize, &mut cpu) }; + if ret != &mut cpu as *mut usize as usize { + cpu = ret; + } + let mut gpu = 0u64; + let ret = unsafe { call!(h, 10, (*mut u64) -> usize, &mut gpu) }; + if ret != &mut gpu as *mut u64 as usize { + gpu = ret as u64; + } + (h as usize, cpu, gpu) +} + +#[test] +#[ignore = "needs a D3D12 device; run: cargo test -p d3d12_xs --lib hw_cbv_copy -- --ignored --test-threads=1 (TOMBOX_HW_ADAPTER=warp for WARP)"] +fn hw_cbv_copy_unaligned_descriptor_table_cbv_reads_through_a_raw_view_next_to_a_root_cbv() { + if skip() { + return; + } + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let g = gpu(); + let f = fixture(); + let rs_text = "RootFlags(0), CBV(b0, visibility=SHADER_VISIBILITY_PIXEL), DescriptorTable(CBV(b1), visibility=SHADER_VISIBILITY_PIXEL)"; + let probe = format!("#define RS \"{rs_text}\"\n[RootSignature(RS)] float4 main() : SV_Position {{ return 0; }}"); + let blob = compile(&probe, "vs_6_0"); + let parsed = tombox_xshader::parse_root_signature(&blob).expect("parse root signature"); + let tables = table_cbv_ranges(Some(&parsed)); + assert_eq!(tables, vec![(1, 1, 0)]); + let (tbl, p) = crate::cbv_raw::table_blob(&blob).expect("table_blob").expect("a CBV range to rebind"); + assert_eq!((p.ranges, p.root_cbvs.len()), (1, 0)); + assert_eq!(crate::cbv_raw::root_cbv_params(&tbl), crate::cbv_raw::root_cbv_params(&blob), "the root CBV must stay a root CBV"); + let rs = unsafe { root_sig(g.dev, &tbl) }; + let ps_text = format!("cbuffer CB0 : register(b0) {{ uint4 cb0[{N}]; }};\ncbuffer CB1 : register(b1) {{ uint4 cb1[23]; }};\nuint4 main(float4 p : SV_Position) : SV_Target {{ uint i = (uint)p.x; return cb0[i] ^ cb1[i]; }}\n"); + let copy_text = tombox_xshader::cbv_raw_hlsl::rewrite_hlsl_where(&ps_text, &|r, sp| in_table(&tables, r, sp)).expect("rewrite_hlsl_where"); + assert!(copy_text.contains("cbuffer CB0 : register(b0)") && copy_text.contains("tb_cbr1.Load4"), "{copy_text}"); + let vs = compile(VS, "vs_6_0"); + let ps = compile(©_text, "ps_6_0"); + let pso = unsafe { gfx_pso(g.dev, rs, &vs, &ps) }; + let size = 4096usize; + let src = unsafe { buffer(g.dev, HEAP_UPLOAD, size as u64, 0, ST_GENERIC_READ, Some(size as u64)) }; + let data = pattern(0x7777_0000, size); + unsafe { put(&src, 0, &data) }; + let (root_off, table_off) = (0x200usize, 0x4b0usize); + let table_va = src.va + table_off as u64; + assert_ne!(table_va % SLOT_ALIGN, 0); + let (res, d) = crate::cbv_raw::raw_view(table_va, 368, &crate::gpu_va::lookup).expect("raw view of the table CBV"); + assert_eq!(res, src.res); + let (heap, cpu, gpu_h) = unsafe { heap_handles(g.dev) }; + unsafe { call!(g.dev, 18, (*mut c_void, *const u8, usize) -> (), res as *mut c_void, d.as_ptr(), cpu) }; + let want: Vec = (0..CB_BYTES).map(|i| data[root_off + i] ^ data[table_off + i]).collect(); + let mut r = unsafe { run_new(g, LIST_DIRECT) }; + let l = r.list; + unsafe { + core::ptr::write_bytes(f.rb.cpu, 0xcd, PITCH as usize); + call!(l, P_RTS, (u32, *const usize, i32, *const usize) -> (), 1, &f.rtv, 0, core::ptr::null()); + let vp = [0f32, 0.0, N as f32, 1.0, 0.0, 1.0]; + call!(l, P_VIEWPORTS, (u32, *const f32) -> (), 1, vp.as_ptr()); + let sc = [0i32, 0, N as i32, 1]; + call!(l, P_SCISSORS, (u32, *const i32) -> (), 1, sc.as_ptr()); + call!(l, P_TOPOLOGY, (u32) -> (), 4); + let heaps = [heap]; + call!(l, 28, (u32, *const usize) -> (), 1, heaps.as_ptr()); + call!(l, P_GRAPHICS_RS, (usize) -> (), rs); + call!(l, P_PSO, (usize) -> (), pso); + call!(l, 38, (u32, u64) -> (), 0, src.va + root_off as u64); + call!(l, 32, (u32, u64) -> (), 1, gpu_h); + call!(l, P_DRAW, (u32, u32, u32, u32) -> (), 3, 1, 0, 0); + barrier(l, f.rt, ST_RT, ST_COPY_SOURCE); + let mut dst = [0u8; 48]; + dst[0..8].copy_from_slice(&(f.rb.res as u64).to_le_bytes()); + dst[8..12].copy_from_slice(&1u32.to_le_bytes()); + dst[24..28].copy_from_slice(&FMT_RGBA32_UINT.to_le_bytes()); + dst[28..32].copy_from_slice(&(N as u32).to_le_bytes()); + dst[32..36].copy_from_slice(&1u32.to_le_bytes()); + dst[36..40].copy_from_slice(&1u32.to_le_bytes()); + dst[40..44].copy_from_slice(&(PITCH as u32).to_le_bytes()); + let mut s = [0u8; 48]; + s[0..8].copy_from_slice(&(f.rt as u64).to_le_bytes()); + call!(l, P_COPY_TEXTURE, (*const u8, u32, u32, u32, *const u8, *const c_void) -> (), dst.as_ptr(), 0, 0, 0, s.as_ptr(), core::ptr::null()); + barrier(l, f.rt, ST_COPY_SOURCE, ST_RT); + execute(g, &mut r); + let out = get(&f.rb, 0, CB_BYTES); + same("root CBV ^ unaligned table CBV (raw view) output", &out, &want); + } + eprintln!("table CBV at +{:#x} from 256 read through a raw SRV next to a real root CBV: {} bytes bit-exact", table_va % SLOT_ALIGN, CB_BYTES); +} diff --git a/crates/compat/d3d12_xs/src/cbv_raw.rs b/crates/compat/d3d12_xs/src/cbv_raw.rs index a933a118..b6744df3 100644 --- a/crates/compat/d3d12_xs/src/cbv_raw.rs +++ b/crates/compat/d3d12_xs/src/cbv_raw.rs @@ -23,16 +23,94 @@ static PREV_RS: AtomicUsize = AtomicUsize::new(0); static PREV_CBV: AtomicUsize = AtomicUsize::new(0); static REAL_ROOT_SRV: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)]; -pub fn enabled() -> bool { - static E: OnceLock = OnceLock::new(); - *E.get_or_init(|| { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + Auto, + On, + Off, + Copy, +} + +pub fn parse_mode(v: Option<&str>) -> Result { + match v.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + None | Some("") | Some("copy") => Ok(Mode::Copy), + Some("auto") => Ok(Mode::Auto), + Some("1") | Some("on") => Ok(Mode::On), + Some("0") | Some("off") => Ok(Mode::Off), + Some(other) => Err(format!("cbv_raw={other:?} is not one of copy, auto, on, off, 1, 0; using copy")), + } +} + +pub fn mode_setting(cbv_raw: Option, cbraw: Option, cfg: Option) -> Option { + cbv_raw.or(cbraw).or(cfg) +} + +pub fn mode() -> Mode { + static M: OnceLock = OnceLock::new(); + *M.get_or_init(|| { + let raw = mode_setting(std::env::var("TOMBOX_CBV_RAW").ok(), std::env::var("TOMBOX_CBRAW").ok(), compat_common::cfg("cbv_raw")); + parse_mode(raw.as_deref()).unwrap_or_else(|e| { + record("d3d12_xs", "cbv_raw", &e); + Mode::Copy + }) + }) +} + +pub fn copy_on() -> bool { + static C: OnceLock = OnceLock::new(); + *C.get_or_init(|| mode() == Mode::Copy) +} + +pub fn pack_mode(xbox_one: bool) -> tombox_xshader::pack_key::CbvRaw { + pack_mode_of(mode(), enabled(), xbox_one) +} + +pub fn pack_mode_of(mode: Mode, enabled: bool, xbox_one: bool) -> tombox_xshader::pack_key::CbvRaw { + if mode == Mode::Copy { + tombox_xshader::pack_key::CbvRaw::Copy + } else { + tombox_xshader::pack_key::CbvRaw::of(enabled, xbox_one) + } +} + +pub fn xbox_one_title() -> bool { + static X: OnceLock = OnceLock::new(); + *X.get_or_init(|| { extern "system" { fn GetModuleHandleW(n: *const u16) -> *mut c_void; } let name: Vec = "d3d12_x.dll".encode_utf16().chain(Some(0)).collect(); - let on = !unsafe { GetModuleHandleW(name.as_ptr()) }.is_null(); + !unsafe { GetModuleHandleW(name.as_ptr()) }.is_null() + }) +} + +pub fn shader_kind_refusal(xbox_one: bool, durango: bool) -> Option<&'static str> { + (xbox_one && !durango).then_some("Xbox One title shader is not a Durango program") +} + +pub fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| { + let mode = mode(); + let xbox_one = xbox_one_title(); + let on = match mode { + Mode::Auto => xbox_one, + Mode::On => true, + Mode::Off | Mode::Copy => false, + }; + let why = match (mode, xbox_one) { + (Mode::Copy, _) => "cbv_raw=copy", + (Mode::Auto, _) => "Xbox One title (d3d12_x.dll loaded)", + (Mode::On, _) => "cbv_raw=on", + (Mode::Off, true) => "cbv_raw=off on an Xbox One title (d3d12_x.dll loaded)", + (Mode::Off, false) => "cbv_raw=off", + }; if on { - record("d3d12_xs", "cbv_raw", &format!("Xbox One title (d3d12_x.dll loaded): constant buffers are bound as raw SRVs in space {TB_CBRAW_SPACE}+n so a CBV may start at any 16-byte-aligned address like on the console")); + record("d3d12_xs", "cbv_raw", &format!("{why}: constant buffers are bound as raw SRVs in space {}+n so a CBV may start at any 16-byte-aligned address like on the console", tombox_xshader::cbv_raw_hlsl::space_base())); + } else if mode == Mode::Copy { + record("d3d12_xs", "cbv_raw", &format!("{why}: root CBVs stay PC CBVs and one whose address is not 256-byte aligned is copied on the GPU timeline into a 256-aligned emulator ring before each draw or dispatch; descriptor-table CBV ranges are rebound as raw SRVs (space {}+n) so a table CBV may start at any 16-byte-aligned address (xbox_one_title={xbox_one})", tombox_xshader::cbv_raw_hlsl::space_base())); + } else if mode == Mode::Off { + record("d3d12_xs", "cbv_raw", &format!("{why}: constant buffers stay PC CBVs (BufferLocation must be 256-byte aligned)")); } on }) @@ -55,6 +133,10 @@ fn wr(b: &mut [u8], o: usize, v: u32) { pub fn patch_rts0(b: &mut [u8]) -> Result { + patch_rts0_with(b, true) +} + +pub fn patch_rts0_with(b: &mut [u8], roots: bool) -> Result { let version = rd(b, 0)?; let range_size = match version { 1 => 20, @@ -79,7 +161,7 @@ pub fn patch_rts0(b: &mut [u8]) -> Result { } } } - PARAM_CBV => { + PARAM_CBV if roots => { let space = map_space(rd(b, payload + 4)?)?; wr(b, at, PARAM_SRV); wr(b, payload + 4, space); @@ -91,10 +173,35 @@ pub fn patch_rts0(b: &mut [u8]) -> Result { Ok(p) } +pub fn alias_blob(blob: &[u8]) -> Result>, String> { + let (o, n) = crate::console_slots_mesh::rts0_range(blob).ok_or("root signature blob has no RTS0 part")?; + let body = blob.get(o..o + n).ok_or("RTS0 chunk out of bounds")?; + match crate::bl_alias::add_aliases(body)? { + Some(b) => Ok(Some(crate::bl_alias::replace_rts0(blob, &b)?)), + None => Ok(None), + } +} + pub fn patch_blob(blob: &[u8]) -> Result, RsPatch)>, String> { + patch_blob_with(blob, true) +} + +pub fn table_blob(blob: &[u8]) -> Result, RsPatch)>, String> { + patch_blob_with(blob, false) +} + +pub fn copy_mode_blob(blob: &[u8]) -> Result>, String> { + if copy_on() { + table_blob(blob).map(|r| r.map(|(b, _)| b)) + } else { + alias_blob(blob) + } +} + +fn patch_blob_with(blob: &[u8], roots: bool) -> Result, RsPatch)>, String> { let (o, n) = crate::console_slots_mesh::rts0_range(blob).ok_or("root signature blob has no RTS0 part")?; let mut body = blob.get(o..o + n).ok_or("RTS0 chunk out of bounds")?.to_vec(); - let mut p = patch_rts0(&mut body)?; + let mut p = patch_rts0_with(&mut body, roots)?; if let Some(b) = crate::bl_alias::add_aliases(&body)? { body = b; p.aliased = true; @@ -145,9 +252,27 @@ unsafe fn vslot(o: *mut c_void, i: usize) -> usize { unsafe extern "system" fn create_root_signature(this: *mut c_void, mask: u32, blob: *const u8, len: usize, riid: *const c_void, ppv: *mut *mut c_void) -> i32 { let f: unsafe extern "system" fn(*mut c_void, u32, *const u8, usize, *const c_void, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(PREV_RS.load(Ordering::Relaxed)) }; - if blob.is_null() || len == 0 || !enabled() { + if blob.is_null() || len == 0 { return unsafe { f(this, mask, blob, len, riid, ppv) }; } + if !enabled() { + let given = unsafe { core::slice::from_raw_parts(blob, len) }; + return match copy_mode_blob(given) { + Ok(Some(b)) => { + static N: AtomicUsize = AtomicUsize::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 3 { + let what = if copy_on() { "copy root signature: root CBVs kept, descriptor-table CBV ranges rebound as raw SRVs" } else { "off root signature: CBVs kept" }; + record("d3d12_xs", "cbv_raw", &format!("cbv_raw={what}, SRV/UAV ranges aliased for the translator's bindless spaces")); + } + unsafe { f(this, mask, b.as_ptr(), b.len(), riid, ppv) } + } + Ok(None) => unsafe { f(this, mask, blob, len, riid, ppv) }, + Err(e) => { + record("d3d12_xs", "cbv_raw", &format!("root signature (raw patch off) not aliased ({e}); created as given")); + unsafe { f(this, mask, blob, len, riid, ppv) } + } + }; + } if check_on() { log_root_regs(unsafe { core::slice::from_raw_parts(blob, len) }); } @@ -174,7 +299,7 @@ unsafe extern "system" fn create_root_signature(this: *mut c_void, mask: u32, bl } unsafe extern "system" fn create_cbv(this: *mut c_void, pdesc: *const u8, dest: usize) { - if !enabled() { + if !enabled() && !copy_on() { let f: unsafe extern "system" fn(*mut c_void, *const u8, usize) = unsafe { core::mem::transmute(PREV_CBV.load(Ordering::Relaxed)) }; return unsafe { f(this, pdesc, dest) }; } @@ -206,6 +331,7 @@ unsafe extern "system" fn set_compute_root_cbv_x(this: *mut c_void, i: u32, va: if crate::rtcap::enabled() { crate::bindtrace::set_root_cbv(this as usize, true, i, va); } + crate::rootlog::note(this as usize, "cbv_raw:title", 39, i as u64, va, 0, 0); let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(REAL_ROOT_SRV[0].load(Ordering::Relaxed)) }; unsafe { f(this, i, va) } } @@ -227,6 +353,7 @@ unsafe extern "system" fn set_graphics_root_cbv_x(this: *mut c_void, i: u32, va: d.last.entry(this as usize).or_default().insert(i, va); }); } + crate::rootlog::note(this as usize, "cbv_raw:title", 40, i as u64, va, 0, 0); let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(REAL_ROOT_SRV[1].load(Ordering::Relaxed)) }; unsafe { f(this, i, va) } } @@ -254,6 +381,7 @@ fn check_root(i: u32, va: u64, compute: bool) { } pub unsafe fn install_root_cbv_hooks(xbox_vt: &[AtomicUsize], real_vt: *const usize) { + crate::cbv_copy::install(xbox_vt, false); if !enabled() || xbox_vt.len() <= XBOX_SLOT_GRAPHICS_ROOT_CBV { return; } @@ -292,6 +420,53 @@ pub fn parse_clamp(v: &str) -> Option<(u32, u32, Option)> { Some((a.trim().parse().ok()?, lim, only)) } +pub fn hoist_hashes() -> &'static Vec { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| std::env::var("TOMBOX_CBRAW_HOIST").map(|v| v.split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()).unwrap_or_default()) +} + +pub fn hoist_const_loads(h: &str) -> (String, usize) { + let Some(at) = h.find("uint tb_pc = 0u;") else { return (h.to_string(), 0) }; + let ls = h[..at].rfind('\n').map_or(0, |x| x + 1); + let mut seen: Vec<(String, String)> = Vec::new(); + let mut out = String::with_capacity(h.len()); + let mut i = 0; + while i < h.len() { + if h[i..].starts_with("tb_cbr") { + let ns = i + 6; + let ne = ns + h[ns..].bytes().take_while(|c| c.is_ascii_digit()).count(); + let rest = &h[ne..]; + if ne > ns && rest.starts_with(".Load4((") { + let ds = ne + 8; + let de = ds + h[ds..].bytes().take_while(|c| c.is_ascii_digit()).count(); + if de > ds && h[de..].starts_with(") * 16u)") && i >= ls { + let slot = &h[ns..ne]; + let idx = &h[ds..de]; + let name = format!("tb_h{slot}_{idx}"); + if !seen.iter().any(|(n, _)| *n == name) { + seen.push((name.clone(), format!("tb_cbr{slot}.Load4(({idx}) * 16u)"))); + } + out.push_str(&name); + i = de + 8; + continue; + } + } + } + let c = h[i..].chars().next().unwrap(); + out.push(c); + i += c.len_utf8(); + } + if seen.is_empty() { + return (h.to_string(), 0); + } + let decl: String = seen.iter().map(|(n, e)| format!(" uint4 {n} = {e};\n")).collect(); + let mut r = String::with_capacity(out.len() + decl.len()); + r.push_str(&out[..ls]); + r.push_str(&decl); + r.push_str(&out[ls..]); + (r, seen.len()) +} + pub fn clamp_reads(h: &str, slot: u32, lim: u32) -> String { let decl = format!("ByteAddressBuffer tb_cbr{slot} : register("); let Some(at) = h.find(&decl) else { return h.to_string() }; @@ -430,6 +605,7 @@ fn check_draw(list: usize, text: &dyn Fn() -> String) { if !plan.is_empty() { let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(REAL_ROOT_SRV[1].load(Ordering::Relaxed)) }; for (i, va) in &plan { + crate::rootlog::note(list, "cbv_raw:inherit", 40, *i as u64, *va, 0, 0); unsafe { f(list as *mut c_void, *i, *va) }; } let n = INHERITED.fetch_add(plan.len(), Ordering::Relaxed); @@ -445,16 +621,19 @@ fn check_draw(list: usize, text: &dyn Fn() -> String) { unsafe extern "system" fn draw_indexed_checked(this: *mut c_void, a: u32, b: u32, c: u32, d: i32, e: u32) { check_draw(this as usize, &|| format!("DrawIndexedInstanced(idx={a} inst={b} startIdx={c} baseVtx={d} startInst={e})")); let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32) = unsafe { core::mem::transmute(PREV_DRAW_IDX.load(Ordering::Relaxed)) }; - unsafe { f(this, a, b, c, d, e) } + unsafe { f(this, a, b, c, d, e) }; + unsafe { crate::hang_snap::after_draw(this as usize) } } unsafe extern "system" fn draw_checked(this: *mut c_void, a: u32, b: u32, c: u32, d: u32) { check_draw(this as usize, &|| format!("DrawInstanced(vtx={a} inst={b} startVtx={c} startInst={d})")); let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = unsafe { core::mem::transmute(PREV_DRAW.load(Ordering::Relaxed)) }; - unsafe { f(this, a, b, c, d) } + unsafe { f(this, a, b, c, d) }; + unsafe { crate::hang_snap::after_draw(this as usize) } } pub fn install_draw_check(xbox_vt: &[AtomicUsize]) { + crate::cbv_copy::install(xbox_vt, true); if !track_on() || xbox_vt.len() <= XBOX_SLOT_SET_GRAPHICS_RS || REAL_ROOT_SRV[1].load(Ordering::Relaxed) == 0 { return; } @@ -475,6 +654,117 @@ mod tests { use super::*; use crate::gpu_va::Entry; + #[test] + fn hoist_moves_constant_raw_loads_before_the_dispatcher() { + let h = "ByteAddressBuffer tb_cbr13 : register(t13, space4100000); +void main() { + uint a = tb_cbr13.Load4((3) * 16u).x; + uint tb_pc = 0u; uint tb_guard = 0u; + while (tb_pc != 9u) { + uint b = tb_cbr13.Load4((5) * 16u).y + tb_cbr13.Load4((5) * 16u).z; + uint c = tb_cbr13.Load4((t1) * 16u).w; + } +} +"; + let (o, n) = hoist_const_loads(h); + assert_eq!(n, 1, "{o}"); + assert!(o.contains(" uint4 tb_h13_5 = tb_cbr13.Load4((5) * 16u); + uint tb_pc = 0u;"), "{o}"); + assert!(o.contains("uint b = tb_h13_5.y + tb_h13_5.z;"), "{o}"); + assert!(o.contains("uint a = tb_cbr13.Load4((3) * 16u).x;"), "{o}"); + assert!(o.contains("tb_cbr13.Load4((t1) * 16u).w"), "{o}"); + assert_eq!(hoist_const_loads("void f() {} +").1, 0); + } + + #[test] + fn root_signature_built_from_a_shader_gets_the_raw_rebind() { + let body = rts0(2, &[[2, 1, 0, 0]], true); + let plain = crate::device_wrap::shader_root_container(&body, false); + let raw = crate::device_wrap::shader_root_container(&body, true); + let cbvs = |b: &[u8]| root_cbv_params(b).len(); + assert_eq!(cbvs(&plain), 1); + assert_eq!(cbvs(&raw), 0); + let (o, n) = crate::console_slots_mesh::rts0_range(&raw).unwrap(); + let r = &raw[o..o + n]; + let po = u32::from_le_bytes(r[8..12].try_into().unwrap()) as usize; + let last = po + 12; + assert_eq!(u32::from_le_bytes(r[last..last + 4].try_into().unwrap()), PARAM_SRV); + } + + #[test] + fn non_raw_default_shader_root_signature_gets_aliases_and_keeps_cbvs() { + let body = rts0(2, &[[0, u32::MAX, 0, 0]], true); + let plain = crate::device_wrap::shader_root_container(&body, false); + assert!(copy_on() && !enabled()); + let console = crate::device_wrap::wrap_root_signature(&body); + let given = crate::rs_xbox::pc_blob(&console).unwrap_or(console); + assert_eq!(Some(plain.clone()), alias_blob(&given).unwrap()); + assert_eq!(root_cbv_params(&plain), root_cbv_params(&given)); + assert_eq!(root_cbv_params(&plain).len(), 1); + let only_cbv = rts0(2, &[[2, 1, 0, 0]], true); + let c = crate::device_wrap::wrap_root_signature(&only_cbv); + let g = crate::rs_xbox::pc_blob(&c).unwrap_or(c); + let tbl = crate::device_wrap::shader_root_container(&only_cbv, false); + assert_eq!(Some(tbl.clone()), table_blob(&g).unwrap().map(|(b, _)| b)); + assert_ne!(tbl, g, "cbv_raw=copy rebinds the descriptor-table CBV range as a raw SRV range"); + assert_eq!(root_cbv_params(&tbl), root_cbv_params(&g)); + } + + #[test] + fn copy_mode_aliases_unbounded_ranges_but_keeps_root_cbvs() { + let body = rts0(2, &[[0, u32::MAX, 0, 0]], true); + let container = crate::device_wrap::shader_root_container(&body, false); + let console = crate::device_wrap::wrap_root_signature(&body); + let given = crate::rs_xbox::pc_blob(&console).unwrap_or(console); + let raw = patch_blob(&given).unwrap().unwrap().0; + let aliased = alias_blob(&given).unwrap().expect("an unbounded range gets aliases"); + assert!(alias_blob(&aliased).unwrap().is_none(), "aliasing is idempotent"); + assert_eq!(root_cbv_params(&aliased), root_cbv_params(&given)); + assert_eq!(root_cbv_params(&aliased).len(), 1); + let ranges = |b: &[u8]| { + let (o, n) = crate::console_slots_mesh::rts0_range(b).unwrap(); + let r = &b[o..o + n]; + let rd = |x: usize| u32::from_le_bytes(r[x..x + 4].try_into().unwrap()) as usize; + let (np, po) = (rd(4), rd(8)); + (0..np).filter(|i| rd(po + i * 12) == 0).map(|i| rd(rd(po + i * 12 + 8))).sum::() + }; + assert_eq!(ranges(&aliased), ranges(&raw)); + assert!(ranges(&aliased) > ranges(&given)); + assert_eq!(ranges(&container), ranges(&aliased)); + } + + #[test] + fn cbv_raw_mode_setting_is_validated() { + assert_eq!(parse_mode(None), Ok(Mode::Copy)); + assert_eq!(parse_mode(Some("")), Ok(Mode::Copy)); + assert_eq!(parse_mode(Some("copy")), Ok(Mode::Copy)); + assert_eq!(parse_mode(Some("auto")), Ok(Mode::Auto)); + assert_eq!(parse_mode(Some(" ON ")), Ok(Mode::On)); + assert_eq!(parse_mode(Some("1")), Ok(Mode::On)); + assert_eq!(parse_mode(Some("off")), Ok(Mode::Off)); + assert_eq!(parse_mode(Some("0")), Ok(Mode::Off)); + assert_eq!(parse_mode(Some(" Copy ")), Ok(Mode::Copy)); + assert!(parse_mode(Some("yes")).is_err()); + } + + #[test] + fn cbv_raw_wins_over_the_cbraw_alias_then_cfg() { + let s = |x: &str| Some(x.to_string()); + assert_eq!(mode_setting(s("off"), s("1"), s("on")), s("off")); + assert_eq!(mode_setting(None, s("1"), s("off")), s("1")); + assert_eq!(mode_setting(None, None, s("auto")), s("auto")); + assert_eq!(mode_setting(None, None, None), None); + } + + #[test] + fn only_xbox_one_titles_require_durango_programs() { + assert_eq!(shader_kind_refusal(true, true), None); + assert!(shader_kind_refusal(true, false).is_some()); + assert_eq!(shader_kind_refusal(false, false), None); + assert_eq!(shader_kind_refusal(false, true), None); + } + #[test] fn clamp_knob_takes_an_optional_shader_scope() { assert_eq!(parse_clamp("13:z"), Some((13, u32::MAX, None))); diff --git a/crates/compat/d3d12_xs/src/centroid_bind.rs b/crates/compat/d3d12_xs/src/centroid_bind.rs index 3b0863e0..bdac8822 100644 --- a/crates/compat/d3d12_xs/src/centroid_bind.rs +++ b/crates/compat/d3d12_xs/src/centroid_bind.rs @@ -185,7 +185,7 @@ fn constants_of(s: &ListState) -> Constants { unsafe fn push(list: *mut c_void, s: &ListState) { let Some(idx) = root_index(s.rs) else { return }; let c = constants_of(s); - let f: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = unsafe { core::mem::transmute(vslot(list, PC_SET_GRAPHICS_ROOT_CONSTANTS)) }; + let f: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SET_GRAPHICS_ROOT_CONSTANTS)) }; unsafe { f(list, idx, TB_CENTROID_ROOT_DWORDS, c.as_ptr(), 0) }; } diff --git a/crates/compat/d3d12_xs/src/centroid_bind_tests.rs b/crates/compat/d3d12_xs/src/centroid_bind_tests.rs index 512f2016..7067706e 100644 --- a/crates/compat/d3d12_xs/src/centroid_bind_tests.rs +++ b/crates/compat/d3d12_xs/src/centroid_bind_tests.rs @@ -131,6 +131,7 @@ fn ps() -> tombox_xshader::ShaderExtract { has_root_sig: false, input_sig: vec![el("SV_Position", 1, 0, 0xf, 0), el("TEXCOORD_centroid", 0, 1, 0x3, 0x3)], output_sig: vec![el("SV_Target", 64, 0, 0xf, 0xf)], + prim_sig: Vec::new(), resources: Vec::new(), gs_info: None, root_sig: None, diff --git a/crates/compat/d3d12_xs/src/cl2_state.rs b/crates/compat/d3d12_xs/src/cl2_state.rs index e3ff2449..923e6acc 100644 --- a/crates/compat/d3d12_xs/src/cl2_state.rs +++ b/crates/compat/d3d12_xs/src/cl2_state.rs @@ -93,6 +93,10 @@ unsafe fn vslot(obj: *mut c_void, i: usize) -> usize { unsafe { *(*(obj as *const *const usize)).add(i) } } +unsafe fn pc_list_slot(list: *mut c_void, slot: usize) -> usize { + unsafe { crate::cmdlist_wrap::pc_method(list, slot) } +} + unsafe fn release(obj: *mut c_void) { let f: unsafe extern "system" fn(*mut c_void) -> u32 = unsafe { core::mem::transmute(vslot(obj, 2)) }; unsafe { f(obj) }; @@ -439,9 +443,15 @@ macro_rules! fwd { } unsafe extern "system" fn w_topology(this: *mut c_void, t: u32) { + let was = is_rect(this); rec(this, |s| s.topology = Some(t)); crate::present_probe::note_topology(t); - fwd!(X_TOPOLOGY, fn(u32), this, t) + fwd!(X_TOPOLOGY, fn(u32), this, crate::rectlist::forwarded(t)); + if t == crate::rectlist::RECTLIST { + unsafe { apply_rect(this) }; + } else if was { + unsafe { rebind_pso(this) }; + } } unsafe extern "system" fn w_viewports(this: *mut c_void, n: u32, p: *const u8) { @@ -754,13 +764,13 @@ unsafe fn pc_depth_bias(list: *mut c_void, v: (f32, f32, f32)) -> bool { if !unsafe { has_list9(list) } || unsafe { crate::fill::list_type(list) } == LIST_TYPE_BUNDLE { return false; } - let f: unsafe extern "system" fn(*mut c_void, f32, f32, f32) = unsafe { core::mem::transmute(vslot(list, PC_RS_SET_DEPTH_BIAS)) }; + let f: unsafe extern "system" fn(*mut c_void, f32, f32, f32) = unsafe { core::mem::transmute(pc_list_slot(list, PC_RS_SET_DEPTH_BIAS)) }; unsafe { f(list, v.0, v.1, v.2) }; true } unsafe fn pc_set_pso(list: *mut c_void, pso: usize) { - let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(vslot(list, PC_SET_PSO)) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(pc_list_slot(list, PC_SET_PSO)) }; unsafe { f(list, pso as *mut c_void) }; } @@ -775,9 +785,10 @@ pub struct VariantKey { pub clip: bool, pub dynamic: bool, pub bias: Option<(i32, u32, u32)>, + pub rect: bool, } -pub fn variant_desc(d: &mut [u8], k: VariantKey) { +pub fn variant_desc(d: &mut [u8], k: VariantKey) -> bool { d[DESC_DEPTH_CLIP..DESC_DEPTH_CLIP + 4].copy_from_slice(&(k.clip as u32).to_le_bytes()); let f = u32::from_le_bytes(d[DESC_FLAGS..DESC_FLAGS + 4].try_into().unwrap()); let f = if k.dynamic { f | PSO_FLAG_DYNAMIC_DEPTH_BIAS } else { f & !PSO_FLAG_DYNAMIC_DEPTH_BIAS }; @@ -787,11 +798,12 @@ pub fn variant_desc(d: &mut [u8], k: VariantKey) { d[DESC_DEPTH_BIAS + 4..DESC_DEPTH_BIAS + 8].copy_from_slice(&c.to_le_bytes()); d[DESC_DEPTH_BIAS + 8..DESC_DEPTH_BIAS + 12].copy_from_slice(&s.to_le_bytes()); } + !k.rect || crate::rectlist::expand(d) } pub fn static_key(x: DepthBiasX) -> VariantKey { let (_, c, s) = x.pc_values(); - VariantKey { clip: x.clip, dynamic: false, bias: Some((x.bias, c.to_bits(), s.to_bits())) } + VariantKey { clip: x.clip, dynamic: false, bias: Some((x.bias, c.to_bits(), s.to_bits())), rect: false } } pub fn static_matches(pb: &PsoBias, x: DepthBiasX) -> bool { @@ -800,9 +812,13 @@ pub fn static_matches(pb: &PsoBias, x: DepthBiasX) -> bool { } static VARIANTS: Mutex>> = Mutex::new(None); +static RECT_FAILED: Mutex>> = Mutex::new(None); unsafe fn pso_variant(pso: usize, k: VariantKey) -> usize { let id = crate::device_wrap::gfx_pso_identity(pso); + if k.rect && RECT_FAILED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(&(pso, k))) == Some(&id) { + return 0; + } let mut g = VARIANTS.lock().unwrap_or_else(|e| e.into_inner()); let m = g.get_or_insert_with(HashMap::new); if let Some(v) = m.get(&(pso, k)) { @@ -815,11 +831,19 @@ unsafe fn pso_variant(pso: usize, k: VariantKey) -> usize { if dev.is_null() || d.len() < DESC_FLAGS + 4 { return 0; } - variant_desc(&mut d, k); + let fail = |m: &mut HashMap<(usize, VariantKey), usize>| if k.rect { m.insert((pso, k), id); }; + if !variant_desc(&mut d, k) { + fail(RECT_FAILED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); + return 0; + } let f: unsafe extern "system" fn(*mut c_void, *const u8, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(vslot(dev, DEV_CREATE_GFX_PSO)) }; let mut out: *mut c_void = core::ptr::null_mut(); let hr = unsafe { f(dev, d.as_ptr(), &IID_PSO, &mut out) }; if hr < 0 || out.is_null() { + fail(RECT_FAILED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); + if k.rect { + crate::rectlist::refuse_desc(&d, &format!("the expanded pipeline of PSO {pso:#x} was refused by the driver (hr={hr:#010x})")); + } if once(16) { record("d3d12_xs", "cl2_state", &format!("PSO variant {k:?} of {pso:#x} FAILED hr={hr:#010x}")); } @@ -843,7 +867,7 @@ unsafe fn apply_pso_bias(list: *mut c_void, pso: usize) { unsafe { pc_depth_bias(list, (b.bias as f32, b.clamp, b.slope)) }; return; } - let v = unsafe { pso_variant(pso, VariantKey { clip: b.clip, dynamic: false, bias: None }) }; + let v = unsafe { pso_variant(pso, VariantKey { clip: b.clip, dynamic: false, bias: None, rect: false }) }; if v != 0 { unsafe { pc_set_pso(list, v) }; with(list, |s| s.variant_bound = true); @@ -861,6 +885,44 @@ unsafe extern "system" fn w_pso(this: *mut c_void, pso: *mut c_void) { }); fwd!(X_PSO, fn(*mut c_void), this, pso); unsafe { apply_pso_bias(this, pso as usize) }; + unsafe { apply_rect(this) }; +} + +fn is_rect(list: *mut c_void) -> bool { + with(list, |s| s.topology == Some(crate::rectlist::RECTLIST)) +} + +unsafe fn wanted_key(list: *mut c_void, pso: usize) -> Option { + let pb = pso_bias(pso)?; + let x = with(list, |s| s.depth_bias_x); + let dynamic = pb.dynamic && unsafe { dynamic_usable(list) }; + let plain = VariantKey { clip: pb.clip, dynamic: pb.dynamic, bias: None, rect: false }; + let k = match x { + Some(x) if !dynamic => if static_matches(&pb, x) { plain } else { static_key(x) }, + Some(x) => VariantKey { clip: x.clip, dynamic: true, bias: None, rect: false }, + None if pb.dynamic && !dynamic => VariantKey { clip: pb.clip, dynamic: false, bias: None, rect: false }, + None => plain, + }; + Some(VariantKey { rect: is_rect(list), ..k }) +} + +unsafe fn apply_rect(list: *mut c_void) { + if !is_rect(list) { + return; + } + let pso = with(list, |s| s.pso).unwrap_or(0); + if pso == 0 { + return; + } + let Some(k) = (unsafe { wanted_key(list, pso) }) else { + crate::rectlist::refuse(0, pso as u64, &format!("PSO {pso:#x} has no recorded PC description (stream-built or unknown pipeline)")); + return; + }; + let v = unsafe { pso_variant(pso, k) }; + if v != 0 { + unsafe { pc_set_pso(list, v) }; + with(list, |s| s.variant_bound = true); + } } unsafe fn apply_depth_bias_x(this: *mut c_void, x: DepthBiasX) { @@ -888,7 +950,7 @@ unsafe fn apply_depth_bias_x(this: *mut c_void, x: DepthBiasX) { return; } if x.clip != pb.clip { - let v = unsafe { pso_variant(pso, VariantKey { clip: x.clip, dynamic: true, bias: None }) }; + let v = unsafe { pso_variant(pso, VariantKey { clip: x.clip, dynamic: true, bias: None, rect: false }) }; if v != 0 { unsafe { pc_set_pso(this, v) }; with(this, |s| s.variant_bound = true); @@ -904,6 +966,7 @@ unsafe extern "system" fn w_depth_bias_x(this: *mut c_void, bias: i32, clamp: f3 let x = DepthBiasX { bias, clamp, slope, clip: clip != 0 }; rec(this, |s| s.depth_bias_x = Some(x)); unsafe { apply_depth_bias_x(this, x) }; + unsafe { apply_rect(this) }; } pub static QUERY_DXIL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/query_accum.dxil")); @@ -1126,21 +1189,22 @@ unsafe fn uav_barrier(list: *mut c_void, res: usize) { let mut b = [0u8; 32]; b[0..4].copy_from_slice(&2u32.to_le_bytes()); b[8..16].copy_from_slice(&(res as u64).to_le_bytes()); - let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(vslot(list, PC_BARRIER)) }; + let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(pc_list_slot(list, PC_BARRIER)) }; unsafe { f(list, 1, b.as_ptr()) }; } unsafe fn pc_no_predication(list: *mut c_void) { - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, u32) = unsafe { core::mem::transmute(vslot(list, PC_SET_PREDICATION)) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, u32) = unsafe { core::mem::transmute(pc_list_slot(list, PC_SET_PREDICATION)) }; unsafe { f(list, core::ptr::null_mut(), 0, 0) }; } unsafe fn pc_resolve(list: *mut c_void, heap: usize, ty: u32, index: u32, dst: usize, off: u64) { - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u32, u32, *mut c_void, u64) = unsafe { core::mem::transmute(vslot(list, PC_RESOLVE_QUERY)) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u32, u32, *mut c_void, u64) = unsafe { core::mem::transmute(pc_list_slot(list, PC_RESOLVE_QUERY)) }; unsafe { f(list, heap as *mut c_void, ty, index, 1, dst as *mut c_void, off) }; } unsafe fn suspend_queries(list: *mut c_void) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::QUERY) }; let qs = with(list, |s| s.queries.clone()); if qs.is_empty() { return; @@ -1185,6 +1249,7 @@ unsafe fn resume_queries(list: *mut c_void) { } pub(crate) unsafe fn pause_queries(list: *mut c_void, occlusion_only: bool) -> Vec<(usize, u32, u32)> { + let _ij = unsafe { crate::inject::scope(list, crate::inject::QUERY) }; let qs: Vec = with(list, |s| if s.suspended { Vec::new() } else { s.queries.iter().filter(|q| !occlusion_only || q.ty <= 1).cloned().collect() }); if qs.is_empty() { return Vec::new(); @@ -1217,7 +1282,7 @@ pub(crate) unsafe fn pause_queries(list: *mut c_void, occlusion_only: bool) -> V } } if let Some((r, o, op)) = pred { - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, u32) = unsafe { core::mem::transmute(vslot(list, PC_SET_PREDICATION)) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, u32) = unsafe { core::mem::transmute(pc_list_slot(list, PC_SET_PREDICATION)) }; unsafe { f(list, r as *mut c_void, o, op) }; } qs.iter().map(|q| (q.heap, q.ty, q.index)).collect() @@ -1240,10 +1305,12 @@ pub(crate) unsafe fn bound_variant_key(list: *mut c_void) -> Option } let pb = pso_bias(pso)?; let dynamic = pb.dynamic && unsafe { dynamic_usable(list) }; + let rect = is_rect(list); Some(match x { - Some(x) if !dynamic => static_key(x), - Some(x) => VariantKey { clip: x.clip, dynamic: true, bias: None }, - None => VariantKey { clip: pb.clip, dynamic: false, bias: None }, + Some(x) if !dynamic => VariantKey { rect, ..static_key(x) }, + Some(x) => VariantKey { clip: x.clip, dynamic: true, bias: None, rect }, + None if rect => return unsafe { wanted_key(list, pso) }, + None => VariantKey { clip: pb.clip, dynamic: false, bias: None, rect }, }) } @@ -1256,6 +1323,7 @@ pub(crate) unsafe fn rebind_pso(list: *mut c_void) { if let Some(x) = x { unsafe { apply_depth_bias_x(list, x) }; } + unsafe { apply_rect(list) }; } #[cfg(test)] @@ -1276,13 +1344,14 @@ pub(crate) fn test_restore(saved: Vec) { } unsafe fn accumulate(list: *mut c_void, heap: usize, ty: u32, dst: *mut c_void, plan: &[(u32, u64, u32, u32, Vec)]) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::QUERY) }; let Some(p) = (unsafe { query_pipe(list) }) else { return }; let key = crate::list_split::origin_of(list); - let cp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = unsafe { core::mem::transmute(vslot(list, PC_COPY_BUFFER)) }; - let srs: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(vslot(list, PC_SET_CROOT)) }; - let sc: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = unsafe { core::mem::transmute(vslot(list, PC_SET_CCONSTS)) }; - let su: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(vslot(list, PC_SET_CUAV)) }; - let d: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = unsafe { core::mem::transmute(vslot(list, PC_DISPATCH)) }; + let cp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = unsafe { core::mem::transmute(pc_list_slot(list, PC_COPY_BUFFER)) }; + let srs: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(pc_list_slot(list, PC_SET_CROOT)) }; + let sc: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = unsafe { core::mem::transmute(pc_list_slot(list, PC_SET_CCONSTS)) }; + let su: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(pc_list_slot(list, PC_SET_CUAV)) }; + let d: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = unsafe { core::mem::transmute(pc_list_slot(list, PC_DISPATCH)) }; unsafe { pc_no_predication(list); for (index, off, words, mode, parts) in plan { @@ -1387,6 +1456,7 @@ pub(crate) unsafe fn reapply_so(list: *mut c_void) { } pub unsafe fn note_executed(queue: *mut c_void, lists: &[*mut c_void]) { + unsafe { crate::cbv_copy::note_executed(queue, lists) }; unsafe { crate::dbcount::note_executed(queue, lists) }; let Some(&first) = lists.first() else { return }; let keys: Vec = lists.iter().map(|&l| crate::list_split::origin_of(l)).collect(); @@ -1421,12 +1491,17 @@ pub unsafe fn after_bundle(this: *mut c_void, bundle: *mut c_void) { } let bundle = crate::cmdlist_wrap::unwrap(bundle); let b = with(bundle, |s| s.clone()); + let was = is_rect(this); rec(this, |s| s.merge_bundle(&b)); if b.pso.is_none() { if let Some(x) = b.depth_bias_x { unsafe { apply_depth_bias_x(this, x) }; } + if was && !is_rect(this) { + unsafe { rebind_pso(this) }; + } } + unsafe { apply_rect(this) }; } unsafe extern "system" fn w_z_order(this: *mut c_void, enable: u32) { @@ -1479,6 +1554,7 @@ pub(crate) fn query_parts(list: *mut c_void) -> Vec> { } pub(crate) unsafe fn close_part_into(list: *mut c_void, slots: &[Option]) -> i32 { + let _ij = unsafe { crate::inject::scope(list, crate::inject::QUERY) }; let qs = with(list, |s| if s.open { s.queries.clone() } else { Vec::new() }); if !qs.is_empty() { for q in &qs { @@ -1696,11 +1772,14 @@ pub(crate) unsafe fn submit_part(list: *mut c_void, queue: *mut c_void) { let l = [list]; unsafe { crate::title_heap::sync_for_execute(&l) }; crate::title_shadow::before_execute(); + let sig = if crate::gpu_wait::signal_fn() != 0 { crate::gpu_wait::signal_fn() } else { unsafe { vslot(queue, 14) } }; + unsafe { crate::placed_offset::before_submit(queue, &l, exec as usize, sig) }; if crate::gpu_wait::has_queue_fns() { unsafe { crate::gpu_wait::submit(queue, &l, exec, crate::gpu_wait::signal_fn(), crate::gpu_wait::wait_fn()) }; } else { unsafe { exec(queue, 1, l.as_ptr()) }; } + unsafe { crate::placed_offset::after_submit(queue, &l, exec as usize, sig) }; unsafe { crate::title_shadow::after_execute(queue, crate::gpu_wait::signal_fn(), crate::gpu_wait::wait_fn()) }; unsafe { crate::list_split::after_submit(queue, &l) }; unsafe { note_executed(queue, &l) }; @@ -2172,14 +2251,14 @@ mod tests { d[DESC_DEPTH_CLIP..DESC_DEPTH_CLIP + 4].copy_from_slice(&1u32.to_le_bytes()); let x = DepthBiasX { bias: -5, clamp: 1.0, slope: 0.25, clip: false }; let k = static_key(x); - assert_eq!(k, VariantKey { clip: false, dynamic: false, bias: Some((-5, 0, 0.25f32.to_bits())) }); + assert_eq!(k, VariantKey { clip: false, dynamic: false, bias: Some((-5, 0, 0.25f32.to_bits())), rect: false }); variant_desc(&mut d, k); let pb = pso_bias_from_desc(&d).unwrap(); assert_eq!(pb, PsoBias { dynamic: false, bias: -5, clamp: 0.0, slope: 0.25, clip: false }); assert_eq!(u32::from_le_bytes(d[DESC_FLAGS..DESC_FLAGS + 4].try_into().unwrap()), 0x1); assert!(static_matches(&pb, x)); assert!(!static_matches(&pb, DepthBiasX { clip: true, ..x })); - variant_desc(&mut d, VariantKey { clip: true, dynamic: true, bias: None }); + variant_desc(&mut d, VariantKey { clip: true, dynamic: true, bias: None, rect: false }); assert_eq!(pso_bias_from_desc(&d).unwrap(), PsoBias { dynamic: true, bias: -5, clamp: 0.0, slope: 0.25, clip: true }); assert!(chunk_fits(120, 8, 128) && !chunk_fits(121, 8, 128) && !chunk_fits(u32::MAX, 8, 128)); } @@ -2322,4 +2401,36 @@ mod tests { assert_eq!(vt[43].load(Ordering::Relaxed), w_v43 as usize); assert_eq!(vt[12].load(Ordering::Relaxed), 3012); } + + #[test] + fn pc_list_slot_resolves_real_pc_methods_on_wrapped_xbox_command_list() { + let dev = unsafe { real_device() }; + if dev.is_null() { + return; + } + unsafe { + let mut alloc = core::ptr::null_mut(); + if vc!(dev, DEV_CREATE_ALLOCATOR, fn(u32, *const Guid, *mut *mut c_void) -> i32, 0, &IID_ALLOCATOR, &mut alloc) < 0 { + return; + } + let mut list = core::ptr::null_mut(); + if vc!(dev, 12, fn(u32, u32, *mut c_void, *mut c_void, *const Guid, *mut *mut c_void) -> i32, 0, 0, alloc, core::ptr::null_mut(), &IID_LIST, &mut list) < 0 { + release(alloc); + return; + } + let expected_croot = vslot(list, PC_SET_CROOT); + let expected_cconsts = vslot(list, PC_SET_CCONSTS); + let expected_cuav = vslot(list, PC_SET_CUAV); + let expected_resolve = vslot(list, PC_RESOLVE_QUERY); + let expected_pred = vslot(list, PC_SET_PREDICATION); + crate::cmdlist_wrap::apply(list); + assert_eq!(pc_list_slot(list, PC_SET_CROOT), expected_croot); + assert_eq!(pc_list_slot(list, PC_SET_CCONSTS), expected_cconsts); + assert_eq!(pc_list_slot(list, PC_SET_CUAV), expected_cuav); + assert_eq!(pc_list_slot(list, PC_RESOLVE_QUERY), expected_resolve); + assert_eq!(pc_list_slot(list, PC_SET_PREDICATION), expected_pred); + release(list); + release(alloc); + } + } } diff --git a/crates/compat/d3d12_xs/src/cl_console_fix.rs b/crates/compat/d3d12_xs/src/cl_console_fix.rs index 5b6a8444..3898a3e1 100644 --- a/crates/compat/d3d12_xs/src/cl_console_fix.rs +++ b/crates/compat/d3d12_xs/src/cl_console_fix.rs @@ -85,6 +85,7 @@ pub fn flush_records(list_type: u32) -> bool { } unsafe extern "system" fn flush_pipeline_x(this: *mut c_void, flags: u32, start: u64, size: u64) { + let _ij = unsafe { crate::inject::scope(this, crate::inject::BARRIER) }; let ty = unsafe { crate::fill::list_type(this) }; if let Some(e) = flush_error(flags, start, size, ty) { if once(16) { @@ -175,6 +176,7 @@ unsafe fn scratch_for(list: *mut c_void, need: u64) -> Option { } unsafe fn copy_within(list: *mut c_void, res: usize, dst_off: u64, src_off: u64, len: u64) -> Result<(), &'static str> { + let _ij = unsafe { crate::inject::scope(list, crate::inject::COPY) }; let state = crate::gpu_va::state(res); let Some(plan) = within_plan(state) else { return Err("the buffer is in an upload heap, which the GPU cannot write on PC") }; let ty = unsafe { crate::fill::list_type(list) }; diff --git a/crates/compat/d3d12_xs/src/cl_ext.rs b/crates/compat/d3d12_xs/src/cl_ext.rs index 8133f2fe..f1180f21 100644 --- a/crates/compat/d3d12_xs/src/cl_ext.rs +++ b/crates/compat/d3d12_xs/src/cl_ext.rs @@ -162,6 +162,7 @@ pub fn bop64_route(va: u64, flags: u32) -> Result { } unsafe fn stall_list(list: *mut c_void) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::BARRIER) }; let mut b = [0u8; 32]; b[0..4].copy_from_slice(&2u32.to_le_bytes()); let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(pc_fn(list, PC_SLOT_RESOURCE_BARRIER)) }; diff --git a/crates/compat/d3d12_xs/src/cl_fw.rs b/crates/compat/d3d12_xs/src/cl_fw.rs index 91d94deb..60d622be 100644 --- a/crates/compat/d3d12_xs/src/cl_fw.rs +++ b/crates/compat/d3d12_xs/src/cl_fw.rs @@ -99,10 +99,19 @@ unsafe fn pc_set_predication(list: *mut c_void, res: usize, offset: u64, op: u32 unsafe { f(list, res as *mut c_void, offset, op) }; } +static FIRST_SET: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); +static FIRST_ADVANCE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); + unsafe fn apply(list: *mut c_void, c: Cursor, what: &str) { let addr = c.address(); + let first = if what == "AdvancePredicationX" { &FIRST_ADVANCE } else { &FIRST_SET }; match resolve(addr) { - Target::Buffer { res, offset } => unsafe { pc_set_predication(list, res, offset, PREDICATION_OP_EQUAL_ZERO) }, + Target::Buffer { res, offset } => { + unsafe { pc_set_predication(list, res, offset, PREDICATION_OP_EQUAL_ZERO) }; + if !first.swap(true, Ordering::Relaxed) { + record("d3d12_xs", "cl_fw", &format!("first call {what} on list {list:p}: predicate {addr:#x} (buffer {:#x} + offset {:#x}) -> PC SetPredication(res {res:#x}, offset {offset:#x}, EQUAL_ZERO)", c.va, c.offset)); + } + } t => { unsafe { pc_set_predication(list, 0, 0, 0) }; if once() { @@ -125,6 +134,9 @@ pub unsafe fn set_predication_buffer(list: *mut c_void, desc: *const Predication if desc.is_null() { store(key, None); unsafe { pc_set_predication(list, 0, 0, 0) }; + if !FIRST_SET.swap(true, Ordering::Relaxed) { + record("d3d12_xs", "cl_fw", &format!("first call {W}(NULL) on list {list:p}: predication cleared")); + } return; } let d = unsafe { *desc }; diff --git a/crates/compat/d3d12_xs/src/cmdlist_wrap.rs b/crates/compat/d3d12_xs/src/cmdlist_wrap.rs index 4ece9c15..ea9c645d 100644 --- a/crates/compat/d3d12_xs/src/cmdlist_wrap.rs +++ b/crates/compat/d3d12_xs/src/cmdlist_wrap.rs @@ -1,538 +1,554 @@ -//! Xbox D3D12.x `ID3D12GraphicsCommandList` vtable translation. -//! -//! Reverse-engineered from the Fortnite RHI call sites, the Xbox command-list -//! vtable differs from PC by **4 methods inserted after PC slot 27** -//! (ExecuteBundle). Confirmed slot mapping (Xbox slot -> PC method): -//! * 0..=26 identical (IUnknown, Close=9, Reset=10, DrawInstanced=12, -//! DrawIndexedInstanced=13, Dispatch=14, SetPipelineState=25, -//! ResourceBarrier=26 — all verified unshifted at their call sites) -//! * 27..=31 ExecuteBundle (PC27) + 4 Xbox-specific inserted methods -//! * 32.. PC method (slot - 4): SetDescriptorHeaps(PC28)=Xbox32, -//! SetGraphicsRootSignature(PC30)=Xbox34, SetGraphicsRootDescriptorTable -//! (PC32)=Xbox36, OMSetRenderTargets(PC46)=Xbox50 — all verified. -//! -//! Fix: build an "Xbox-layout" vtable whose slot i holds the *real PC method -//! pointer* for the mapped PC slot, then point each real command-list object at -//! it. Because the object IS the real list, no forwarding thunk is needed — the -//! real method is called with the real `this` directly. Slots 0..=26 stay -//! identical so the D3D12 runtime's own calls (QueryInterface, GetType, AddRef, -//! Release) still work when the list is handed to ExecuteCommandLists. - -use core::ffi::c_void; -use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -#[allow(unused_imports)] use core::sync::atomic::AtomicU64; -use compat_common::record; - -extern "system" { - fn VirtualProtect(addr: *mut c_void, size: usize, new_protect: u32, old_protect: *mut u32) -> i32; -} -const PAGE_READWRITE: u32 = 0x04; - -/// Number of Xbox vtable slots we materialize. Max observed call is Xbox slot 50 -/// (OMSetRenderTargets); 128 leaves generous headroom. -const N: usize = 128; -static XBOX_VT: [AtomicUsize; N] = [const { AtomicUsize::new(0) }; N]; -static BUILT: AtomicBool = AtomicBool::new(false); -static mut REAL_VT_PTR: *const usize = core::ptr::null(); -static INSERTED_HITS: AtomicUsize = AtomicUsize::new(0); -pub(crate) const CONSOLE_NULL_SLOT: usize = 66; - -pub(crate) unsafe fn real_method(slot: usize) -> usize { - unsafe { *REAL_VT_PTR.add(slot) } -} - -pub(crate) unsafe fn pc_method(list: *mut c_void, slot: usize) -> usize { - let vt = unsafe { *(list as *const *const usize) }; - let xbox = XBOX_VT.as_ptr() as *const usize; - if vt == xbox && !unsafe { REAL_VT_PTR }.is_null() { - unsafe { *REAL_VT_PTR.add(slot) } - } else { - unsafe { *vt.add(slot) } - } -} - -pub(crate) fn vt_get(i: usize) -> usize { - XBOX_VT[i].load(Ordering::Relaxed) -} - -pub(crate) fn vt_set(i: usize, f: usize) { - XBOX_VT[i].store(f, Ordering::Relaxed); -} - -pub(crate) fn map_slot(i: usize) -> Option { - match i { - 0..=27 => Some(i), - 28..=31 => Some(i + 24), - 32..=55 => Some(i - 4), - 56..=59 => Some(i), - _ => None, - } -} - -/// Fail-loud-ish stub for an Xbox-inserted slot of unknown signature. Returns 0 -/// in rax (valid for both void- and HRESULT(S_OK)-returning methods) so a stray -/// call doesn't corrupt state; logs the first few so we learn if the game needs one. -#[unsafe(naked)] -unsafe extern "system" fn inserted_stub() { - core::arch::naked_asm!( - "lea rax, [rip + {counter}]", - "lock inc qword ptr [rax]", - "xor eax, eax", - "ret", - counter = sym INSERTED_HITS, - ) -} - -// High-slot diagnostic: the +4 shift is only valid through PC slot 46 (Xbox 50). -// Past that the Xbox command list has its own extension methods, so our naive map -// sends calls to the wrong PC method (e.g. a texture-copy landed on DispatchMesh -> -// device removal). Install logging no-op probes across the high range to capture, -// for every high slot the game actually calls, the slot + first arg + caller RVA, -// so we can reconstruct the true mapping. No-op avoids recording invalid GPU work. -static EXE_BASE: AtomicUsize = AtomicUsize::new(0); -static PROBE_HITS: AtomicUsize = AtomicUsize::new(0); - -unsafe extern "system" fn probe_impl(_this: *mut c_void, a: u64, caller: usize, slot: u64) { - let h = PROBE_HITS.fetch_add(1, Ordering::Relaxed); - static PER: [AtomicUsize; 128] = [const { AtomicUsize::new(0) }; 128]; - let _ = h; - if PER[(slot as usize).min(127)].fetch_add(1, Ordering::Relaxed) < 4 { - let base = EXE_BASE.load(Ordering::Relaxed); - record("d3d12_xs", "cmdlist.hi", - &format!("slot={slot} arg1={a:#x} caller={:#x}", caller.wrapping_sub(base))); - } -} - -macro_rules! make_probes { - ($(($name:ident, $slot:literal)),* $(,)?) => { - $( - #[unsafe(naked)] - unsafe extern "system" fn $name() { - core::arch::naked_asm!( - "mov r8, [rsp]", // caller return address -> 3rd arg - "mov r9d, {s}", // slot -> 4th arg - "jmp {i}", - s = const $slot, i = sym probe_impl, - ); - } - )* - fn is_probe(p: usize) -> bool { - false $( || p == $name as usize )* - } - #[allow(dead_code)] - unsafe fn install_all_probes() { - $( XBOX_VT[$slot].store($name as usize, Ordering::Relaxed); )* - } - /// The high-slot scan showed the game only calls slot 83 (an Xbox texture-copy - /// command our +4 map misrouted to DispatchMesh). No-op just that slot for now. - unsafe fn install_probes() { - // The +4 shift is verified only through Xbox slot 50. Everything above is an - // unverified/Xbox-only method: log-and-ignore until mapped from evidence - // (e.g. slot 67 = FlushTextureCache-style flush, slot 83 = texture copy). - install_all_probes(); - for i in 47..=49 { XBOX_VT[i].store(*REAL_VT_PTR.add(i - 4), Ordering::Relaxed); } - // Verified from FD3D12CommandContext::RHIClearMRTImpl call sites: - // Xbox 51 = ClearDepthStencilView (PC 47), Xbox 52 = ClearRenderTargetView (PC 48). - for i in 51..=52 { XBOX_VT[i].store(*REAL_VT_PTR.add(i - 4), Ordering::Relaxed); } - for i in 53..=58 { - if let Some(pc) = map_slot(i) { - XBOX_VT[i].store(*REAL_VT_PTR.add(pc), Ordering::Relaxed); - } - } - XBOX_VT[84].store(copy_resource_x as usize, Ordering::Relaxed); - XBOX_VT[67].store(flush_texture_cache_x as usize, Ordering::Relaxed); - // Xbox 68 = OMSetDepthBounds (PC ID3D12GraphicsCommandList1 slot 62): called from - // FD3D12StateCacheBase::ApplyState (EXE+0x4e0480) with the two cached depth-bound - // floats in xmm1/xmm2 when its depth-bounds dirty flag is set. - XBOX_VT[68].store(*REAL_VT_PTR.add(62), Ordering::Relaxed); - XBOX_VT[83].store(copy_texture_region_x as usize, Ordering::Relaxed); - XBOX_VT[16].store(copy_texture_region_owned as usize, Ordering::Relaxed); - XBOX_VT[17].store(copy_resource_owned as usize, Ordering::Relaxed); - // Xbox 59 = ExecuteIndirect, same slot and argument order as PC: - // FD3D12CommandContext::RHIDispatchIndirectComputeShader (EXE+0x85145b) calls it as - // (pCommandSignature, 1, pArgumentBuffer, ArgumentBufferOffset, null, 0). Leaving it - // a no-op silently dropped every indirect dispatch/draw. - XBOX_VT[59].store(*REAL_VT_PTR.add(59), Ordering::Relaxed); - if crate::rtcap::enabled() { - XBOX_VT[26].store(resource_barrier_traced as usize, Ordering::Relaxed); - XBOX_VT[25].store(set_pso_traced as usize, Ordering::Relaxed); - XBOX_VT[50].store(om_set_targets_traced as usize, Ordering::Relaxed); - XBOX_VT[12].store(draw_traced as usize, Ordering::Relaxed); - XBOX_VT[13].store(draw_indexed_traced as usize, Ordering::Relaxed); - XBOX_VT[14].store(dispatch_traced as usize, Ordering::Relaxed); - XBOX_VT[59].store(indirect_traced as usize, Ordering::Relaxed); - XBOX_VT[48].store(ia_set_vbs_traced as usize, Ordering::Relaxed); - XBOX_VT[35].store(set_compute_table_traced as usize, Ordering::Relaxed); - XBOX_VT[36].store(set_gfx_table_traced as usize, Ordering::Relaxed); - } - crate::blendclamp::install(); - crate::gpuprof::install(); - } - }; -} -make_probes!( - (p47,47),(p48,48),(p49,49),(p51,51),(p52,52),(p53,53),(p54,54),(p55,55),(p56,56),(p57,57), - (p58,58),(p59,59),(p60,60),(p61,61),(p62,62),(p63,63),(p64,64),(p65,65),(p66,66),(p67,67), - (p68,68),(p69,69),(p70,70),(p71,71),(p72,72),(p73,73),(p74,74),(p75,75),(p76,76),(p77,77), - (p78,78),(p79,79),(p80,80),(p81,81),(p82,82),(p83,83),(p84,84),(p85,85),(p86,86),(p87,87), - (p88,88),(p89,89),(p90,90),(p91,91),(p92,92),(p93,93),(p94,94),(p95,95),(p96,96),(p97,97), - (p98,98),(p99,99),(p100,100),(p101,101),(p102,102),(p103,103),(p104,104),(p105,105),(p106,106), - (p107,107),(p108,108),(p109,109),(p110,110),(p111,111),(p112,112),(p113,113),(p114,114),(p115,115), - (p116,116),(p117,117),(p118,118),(p119,119),(p120,120),(p121,121),(p122,122),(p123,123),(p124,124), - (p125,125),(p126,126),(p127,127), -); - -/// ResourceBarrier (slot 26, identical on Xbox and PC) with state tracking for the -/// diagnostic render-target capture; installed only when the capture is enabled. -unsafe extern "system" fn resource_barrier_traced(this: *mut c_void, n: u32, barriers: *const u8) { - crate::rtcap::note_barriers(n, barriers); - let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = core::mem::transmute(*REAL_VT_PTR.add(26)); - f(this, n, barriers) -} - -// Draw-trace hooks (installed only with the diagnostic capture): note, then forward. -unsafe extern "system" fn set_pso_traced(this: *mut c_void, pso: *mut c_void) { - crate::rtcap::on_set_pso(this as usize, pso as usize); - let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = core::mem::transmute(*REAL_VT_PTR.add(25)); - f(this, pso) -} -unsafe extern "system" fn om_set_targets_traced(this: *mut c_void, n: u32, handles: *const usize, single: i32, dsv: *const usize) { - crate::rtcap::on_set_targets(this as usize, n, handles, single != 0, dsv); - let f: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = core::mem::transmute(*REAL_VT_PTR.add(46)); - f(this, n, handles, single, dsv) -} -/// SetCompute/GraphicsRootDescriptorTable (PC 31/32 = Xbox 35/36): (RootParameterIndex, -/// D3D12_GPU_DESCRIPTOR_HANDLE by value). Recorded for the binding trace. -unsafe extern "system" fn set_compute_table_traced(this: *mut c_void, index: u32, handle: u64) { - crate::bindtrace::set_table(this as usize, true, index, handle); - let f: unsafe extern "system" fn(*mut c_void, u32, u64) = core::mem::transmute(*REAL_VT_PTR.add(31)); - f(this, index, handle) -} -unsafe extern "system" fn set_gfx_table_traced(this: *mut c_void, index: u32, handle: u64) { - crate::bindtrace::set_table(this as usize, false, index, handle); - let f: unsafe extern "system" fn(*mut c_void, u32, u64) = core::mem::transmute(*REAL_VT_PTR.add(32)); - f(this, index, handle) -} -unsafe extern "system" fn draw_traced(this: *mut c_void, a: u32, b: u32, c: u32, d: u32) { - crate::rtcap::trace_draw(this as usize, false, &format!("DrawInstanced(vtx={a} inst={b} startVtx={c} startInst={d})")); - if !crate::rtcap::on_draw(this as usize, 0) { - return; - } - let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = core::mem::transmute(*REAL_VT_PTR.add(12)); - f(this, a, b, c, d) -} -/// IASetVertexBuffers (PC 44 = Xbox 48): (StartSlot, NumViews, pViews); views are 16 bytes. -unsafe extern "system" fn ia_set_vbs_traced(this: *mut c_void, start: u32, n: u32, views: *const u8) { - crate::rtcap::on_set_vbs(this as usize, start, n, views); - let f: unsafe extern "system" fn(*mut c_void, u32, u32, *const u8) = core::mem::transmute(*REAL_VT_PTR.add(44)); - f(this, start, n, views) -} -unsafe extern "system" fn draw_indexed_traced(this: *mut c_void, a: u32, b: u32, c: u32, d: i32, e: u32) { - crate::rtcap::trace_draw(this as usize, false, &format!("DrawIndexedInstanced(idx={a} inst={b} startIdx={c} baseVtx={d} startInst={e})")); - if !crate::rtcap::on_draw(this as usize, 1) { - return; - } - let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32) = core::mem::transmute(*REAL_VT_PTR.add(13)); - f(this, a, b, c, d, e) -} -unsafe extern "system" fn dispatch_traced(this: *mut c_void, a: u32, b: u32, c: u32) { - crate::rtcap::trace_draw(this as usize, true, &format!("Dispatch({a},{b},{c})")); - if !crate::rtcap::on_draw(this as usize, 2) { - return; - } - let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = core::mem::transmute(*REAL_VT_PTR.add(14)); - f(this, a, b, c) -} -unsafe extern "system" fn indirect_traced(this: *mut c_void, sig: *mut c_void, n: u32, buf: *mut c_void, off: u64, cbuf: *mut c_void, coff: u64) { - if !crate::rtcap::on_draw(this as usize, 3) { - return; - } - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64) = core::mem::transmute(*REAL_VT_PTR.add(59)); - f(this, sig, n, buf, off, cbuf, coff) -} - -/// Xbox slot 67: reached (by tail call) from `FD3D12CommandContext::FlushTextureCacheIfNeeded` -/// (EXE+0x4e0718). The console GPU's texture cache has no PC counterpart, so there is -/// nothing to do; this is a deliberate no-op, not a placeholder. -static FLUSH_HITS: AtomicUsize = AtomicUsize::new(0); - -unsafe extern "system" fn flush_texture_cache_x(this: *mut c_void) { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - let on = *ON.get_or_init(|| std::env::var("TOMBOX_FLUSH_UAV").map(|v| v != "0").unwrap_or(true)); - if FLUSH_HITS.fetch_add(1, Ordering::Relaxed) == 0 { - record("d3d12_xs", "FlushTextureCacheX", &format!("first call; mapped to a global UAV barrier = {on}")); - } - if !on || this.is_null() { - return; - } - let b: [u64; 4] = [2, 0, 0, 0]; - let f: unsafe extern "system" fn(*mut c_void, u32, *const [u64; 4]) = core::mem::transmute(*REAL_VT_PTR.add(26)); - f(this, 1, &b) -} - -pub fn flush_hits() -> usize { - FLUSH_HITS.load(Ordering::Relaxed) -} - -unsafe extern "system" fn copy_texture_region_owned(this: *mut c_void, dst: *const u8, x: u32, y: u32, z: u32, src: *const u8, src_box: *const c_void) { - if !dst.is_null() { - crate::placed::note_gpu_write(core::ptr::read_unaligned(dst as *const u64) as *mut c_void); - let d = core::ptr::read_unaligned(dst as *const u64) as usize; - if crate::res3d::is_3d(d) { - let s = if src.is_null() { 0 } else { core::ptr::read_unaligned(src as *const u64) as usize }; - crate::res3d::note(d, "CopyTextureRegion", &format!("at ({x},{y},{z}) src={s:#x} srcType={}", if src.is_null() { 9 } else { core::ptr::read_unaligned(src.add(8) as *const u32) })); - } - } - let f: unsafe extern "system" fn(*mut c_void, *const u8, u32, u32, u32, *const u8, *const c_void) = - core::mem::transmute(*REAL_VT_PTR.add(16)); - f(this, dst, x, y, z, src, src_box) -} - -unsafe extern "system" fn copy_resource_owned(this: *mut c_void, dst: *mut c_void, src: *mut c_void) { - crate::placed::note_gpu_write(dst); - crate::res3d::note(dst as usize, "CopyResource", &format!("src={src:p}")); - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) = core::mem::transmute(*REAL_VT_PTR.add(17)); - f(this, dst, src) -} - -/// Xbox slot 83 = CopyTextureRegion with one extra trailing argument. -/// -/// Evidence: `FD3D12TextureBase::UpdateTexture` (EXE+0xc7cc5f) and -/// `FD3D12RHICommandInitializeTexture::ExecuteNoCmdList` (EXE+0x13e7da9) call it as -/// (this, pDst, DstX, DstY, DstZ, pSrc, pSrcBox, 0) with 48-byte copy locations laid out as -/// on PC (resource, type, 32-byte placed footprint / subresource index). The eighth argument -/// is always 0 at both sites (probably Xbox copy flags) and is dropped. -unsafe extern "system" fn copy_texture_region_x( - this: *mut c_void, dst: *const u8, x: u32, y: u32, z: u32, src: *const u8, src_box: *const c_void, flags: u32, -) { - static CALLS: AtomicUsize = AtomicUsize::new(0); - let n = CALLS.fetch_add(1, Ordering::Relaxed); - if dst.is_null() || src.is_null() { - record("d3d12_xs", "CopyTextureRegionX", "null copy location - ignored"); - return; - } - let q = |p: *const u8, o: usize| core::ptr::read_unaligned(p.add(o) as *const u64); - let d = |p: *const u8, o: usize| core::ptr::read_unaligned(p.add(o) as *const u32); - if n < 6 || flags != 0 { - record("d3d12_xs", "CopyTextureRegionX", &format!( - "#{n} dst{{res={:#x} type={} sub={}}} at ({x},{y},{z}) src{{res={:#x} type={} off={:#x} fmt={} {}x{}x{} pitch={}}} box={src_box:p} flags={flags:#x}", - q(dst, 0), d(dst, 8), d(dst, 16), q(src, 0), d(src, 8), q(src, 16), d(src, 24), d(src, 28), d(src, 32), d(src, 36), d(src, 40))); - } - if q(dst, 0) == 0 || q(src, 0) == 0 { - record("d3d12_xs", "CopyTextureRegionX", "null resource in copy location - ignored"); - return; - } - crate::placed::note_gpu_write(q(dst, 0) as *mut c_void); - crate::res3d::scan_grid_upload(q(dst, 0) as usize, q(src, 0) as *mut c_void, q(src, 16), d(src, 24), d(src, 28), d(src, 32), d(src, 36), d(src, 40)); - crate::res3d::note(q(dst, 0) as usize, "CopyTextureRegionX", &format!("at ({x},{y},{z}) src={:#x} type={} off={:#x} fmt={} {}x{}x{} pitch={}", q(src, 0), d(src, 8), q(src, 16), d(src, 24), d(src, 28), d(src, 32), d(src, 36), d(src, 40))); - let f: unsafe extern "system" fn(*mut c_void, *const u8, u32, u32, u32, *const u8, *const c_void) = - core::mem::transmute(*REAL_VT_PTR.add(16)); - f(this, dst, x, y, z, src, src_box); -} - -unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: *mut c_void, src: *mut c_void, flags: u32) { - static CALLS: AtomicUsize = AtomicUsize::new(0); - if CALLS.fetch_add(1, Ordering::Relaxed) < 4 || flags != 0 { - record("d3d12_xs", "CopyResourceX", &format!("dst={dst:p} src={src:p} flags={flags:#x}")); - } - if dst.is_null() || src.is_null() { - return; - } - crate::placed::note_gpu_write(dst); - crate::res3d::note(dst as usize, "CopyResourceX", &format!("src={src:p} flags={flags:#x}")); - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) = core::mem::transmute(*REAL_VT_PTR.add(17)); - f(this, dst, src); -} - -#[cfg(test)] -mod tests { - use super::map_slot; - - #[test] - fn xbox_cmdlist_slot_map() { - for i in 0..=27 { assert_eq!(map_slot(i), Some(i)); } - assert_eq!(map_slot(28), Some(52)); - assert_eq!(map_slot(29), Some(53)); - assert_eq!(map_slot(30), Some(54)); - assert_eq!(map_slot(31), Some(55)); - assert_eq!(map_slot(32), Some(28)); - assert_eq!(map_slot(36), Some(32)); - assert_eq!(map_slot(50), Some(46)); - assert_eq!(map_slot(53), Some(49)); - assert_eq!(map_slot(55), Some(51)); - for i in 56..=59 { assert_eq!(map_slot(i), Some(i)); } - assert_eq!(map_slot(60), None); - assert_eq!(map_slot(83), None); - let mut seen = std::collections::HashSet::new(); - for i in 0..=59 { assert!(seen.insert(map_slot(i).unwrap())); } - assert_eq!(seen.len(), 60); - assert!((0..60).all(|p| seen.contains(&p))); - } -} - -/// Point a freshly created real command list at the Xbox-layout vtable. -pub fn apply(real_list: *mut c_void) { - if real_list.is_null() { - return; - } - unsafe { - let real_vt = *(real_list as *const *const usize); - if !BUILT.swap(true, Ordering::SeqCst) { - for i in 0..N { - let p = match map_slot(i) { - Some(src) => *real_vt.add(src), - None => inserted_stub as usize, - }; - XBOX_VT[i].store(p, Ordering::Relaxed); - } - extern "system" { fn GetModuleHandleW(n: *const u16) -> *mut c_void; } - EXE_BASE.store(GetModuleHandleW(core::ptr::null()) as usize, Ordering::Relaxed); - REAL_VT_PTR = real_vt; - install_probes(); // high-slot logging no-op probes (47..95, except 50) - let console_defaults = crate::console_slots::snapshot(&XBOX_VT); - crate::cl_console_fix::install_console_bodies(&XBOX_VT); - crate::cmdlist_x::install(&XBOX_VT, real_vt); - crate::query_x::install(&XBOX_VT, real_vt); - crate::bindtrace::install_root_cbv_hooks(&XBOX_VT, real_vt); - crate::cbv_raw::install_root_cbv_hooks(&XBOX_VT, real_vt); - crate::replay::install(&XBOX_VT); - crate::replay_ext::install(&XBOX_VT); - crate::hot_reload::install(&XBOX_VT); - crate::cmd_spy::install(&XBOX_VT); - crate::cmdlist_validate::install(); - crate::console_slots::install_cmdlist(&XBOX_VT, real_vt, &console_defaults); - crate::console_slots_cl2::install_cmdlist(&XBOX_VT, &console_defaults); - crate::cl2_state::install(&XBOX_VT, &console_defaults); - crate::placed_offset::install_cmdlist(&XBOX_VT); - crate::list_split::install(&XBOX_VT); - crate::title_heap::install(&XBOX_VT); - crate::console_slots_mesh::install_cmdlist(&XBOX_VT); - crate::perfctr_cl::install(&XBOX_VT); - crate::cl_console_fix::install_copy_memory(&XBOX_VT); - crate::dbcount::install(&XBOX_VT); - crate::cl_console_fix::install_family_tail(&XBOX_VT); - crate::resolve_x::install(&XBOX_VT); - crate::dred_marks::install(&XBOX_VT); - crate::depth_uav::install_cmdlist(&XBOX_VT); - crate::pso_async::install(&XBOX_VT); - crate::cbv_raw::install_draw_check(&XBOX_VT); - XBOX_VT[CONSOLE_NULL_SLOT].store(0, Ordering::Relaxed); - record("d3d12_xs", "cmdlist.vtable", - &format!("built Xbox-layout cmdlist vtable from real {real_vt:p} (+4 shift at PC28)")); - // Diagnostic: RVAs of the real PC methods inside D3D12Core, to attribute crash frames. - let core = GetModuleHandleW("D3D12Core.dll".encode_utf16().collect::>().as_ptr()) as usize; - let mut s = String::new(); - for i in 0..86 { s.push_str(&format!("{i}:{:x} ", (*real_vt.add(i)).wrapping_sub(core))); } - record("d3d12_xs", "cmdlist.vtable", &format!("XBOX_VT at {:p}, slot98={:#x} stub={:#x}", XBOX_VT.as_ptr(), XBOX_VT[98].load(Ordering::Relaxed), inserted_stub as usize)); - record("d3d12_xs", "cmdlist.vtable", &format!("PC cmdlist method RVAs in D3D12Core: {s}")); - } - // The real object keeps its PC vtable; the title only ever sees a shim (below). - let _ = (VirtualProtect as usize, PAGE_READWRITE); - } -} - -// ---- command-list shim object ------------------------------------------------------------ -// -// On Xbox the command list is a public struct with an inline GPU command buffer: the title -// writes raw command packets straight into it for hot state changes, e.g. in -// FD3D12StateCacheBase::ApplyState (EXE+0x4e0433): -// -// mov rcx,[list+18h] ; current write pointer -// cmp rcx,[list+30h] ; end of buffer -> jae slow path -// mov dword ptr [rcx],0C000B600h ; mov [rcx+4],eax ; lea rax,[rcx+8] ; mov [list+18h],rax -// -// and only when the buffer is full does it call the method (slow path = vtable slot 20, -// IASetPrimitiveTopology). Handing the title the real PC object therefore lets it read -// D3D12-internal fields as buffer pointers and scribble through them. Instead the title -// gets this shim: our own zeroed block whose write pointer == end pointer (both 0), so -// every inline fast path of that form falls back to the API call, with a vtable of thunks -// that swap the shim for the real list and jump through the Xbox-layout table. -// -// Status: the layout fact (+0x18 write ptr, +0x30 end ptr) is observed at one call site; -// other inline fields the title may read are served zeros (unverified). - -/// Offset of the real ID3D12GraphicsCommandList pointer inside the shim. -const SHIM_REAL_OFF: usize = 0x38; -/// Shim size: generous and zero-filled, for any other inline field the title reads. -const SHIM_SIZE: usize = 0x4000; -static SHIM_VT: [AtomicUsize; N] = [const { AtomicUsize::new(0) }; N]; -static SHIM_BUILT: std::sync::Once = std::sync::Once::new(); - -unsafe fn build_shim_thunks() { - extern "system" { - fn VirtualAlloc(addr: *mut c_void, size: usize, ty: u32, protect: u32) -> *mut c_void; - } - let code = VirtualAlloc(core::ptr::null_mut(), N * 32, 0x3000, 0x40) as *mut u8; - assert!(!code.is_null(), "d3d12_xs: cannot allocate command-list shim thunks"); - let timed = crate::slowcall::enabled(); - if timed { - crate::slowcall::calibrate(); - crate::slowcall::CL_TABLE.store(XBOX_VT.as_ptr() as usize, Ordering::SeqCst); - } - for i in 0..N { - let p = code.add(i * 32); - let mut b: Vec = vec![0x48, 0x8B, 0x49, SHIM_REAL_OFF as u8]; - if timed && !is_probe(XBOX_VT[i].load(Ordering::Relaxed)) { - b.extend_from_slice(&[0x41, 0xBA]); - b.extend_from_slice(&(i as u32).to_le_bytes()); - b.extend_from_slice(&[0x48, 0xB8]); - b.extend_from_slice(&(crate::slowcall::cl_timed as usize as u64).to_le_bytes()); - b.extend_from_slice(&[0xFF, 0xE0]); - } else { - b.extend_from_slice(&[0x48, 0xB8]); - b.extend_from_slice(&(XBOX_VT.as_ptr().add(i) as u64).to_le_bytes()); - b.extend_from_slice(&[0xFF, 0x20]); - } - core::ptr::copy_nonoverlapping(b.as_ptr(), p, b.len()); - SHIM_VT[i].store(p as usize, Ordering::Relaxed); - } -} - -/// Wrap a freshly created real command list in a shim object for the title. -pub fn wrap(real_list: *mut c_void) -> *mut c_void { - if real_list.is_null() { - return real_list; - } - apply(real_list); // builds the Xbox-layout table on first use - crate::cl2_state::on_new_list(real_list); - unsafe { - SHIM_BUILT.call_once(|| build_shim_thunks()); - let layout = std::alloc::Layout::from_size_align(SHIM_SIZE, 16).unwrap(); - let p = std::alloc::alloc_zeroed(layout); - assert!(!p.is_null(), "d3d12_xs: cannot allocate command-list shim"); - *(p as *mut usize) = SHIM_VT.as_ptr() as usize; - *(p.add(SHIM_REAL_OFF) as *mut usize) = real_list as usize; - crate::cmdlist_x::note_shim(real_list, p as *mut c_void); - static N_WRAPPED: AtomicUsize = AtomicUsize::new(0); - if N_WRAPPED.fetch_add(1, Ordering::Relaxed) < 3 { - record("d3d12_xs", "cmdlist.shim", &format!("real {real_list:p} wrapped as shim {p:p}")); - } - p as *mut c_void - } -} - -pub unsafe fn set_real(shim: *mut c_void, real: *mut c_void) { - unsafe { *((shim as *mut u8).add(SHIM_REAL_OFF) as *mut usize) = real as usize }; -} - -/// If `p` is one of our shims return the real command list, else `p` unchanged. -pub fn unwrap(p: *mut c_void) -> *mut c_void { - if p.is_null() { - return p; - } - unsafe { - if *(p as *const usize) == SHIM_VT.as_ptr() as usize { - *((p as *const u8).add(SHIM_REAL_OFF) as *const usize) as *mut c_void - } else if let Some(real) = crate::dma_list::unwrap(p) { - real - } else { - p - } - } -} - -/// How many times an Xbox-inserted (unmapped) slot was called — a nonzero value -/// means the game needs one of those 4 methods implemented. -pub fn inserted_hits() -> usize { - INSERTED_HITS.load(Ordering::Relaxed) -} +//! Xbox D3D12.x `ID3D12GraphicsCommandList` vtable translation. +//! +//! Reverse-engineered from the Fortnite RHI call sites, the Xbox command-list +//! vtable differs from PC by **4 methods inserted after PC slot 27** +//! (ExecuteBundle). Confirmed slot mapping (Xbox slot -> PC method): +//! * 0..=26 identical (IUnknown, Close=9, Reset=10, DrawInstanced=12, +//! DrawIndexedInstanced=13, Dispatch=14, SetPipelineState=25, +//! ResourceBarrier=26 — all verified unshifted at their call sites) +//! * 27..=31 ExecuteBundle (PC27) + 4 Xbox-specific inserted methods +//! * 32.. PC method (slot - 4): SetDescriptorHeaps(PC28)=Xbox32, +//! SetGraphicsRootSignature(PC30)=Xbox34, SetGraphicsRootDescriptorTable +//! (PC32)=Xbox36, OMSetRenderTargets(PC46)=Xbox50 — all verified. +//! +//! Fix: build an "Xbox-layout" vtable whose slot i holds the *real PC method +//! pointer* for the mapped PC slot, then point each real command-list object at +//! it. Because the object IS the real list, no forwarding thunk is needed — the +//! real method is called with the real `this` directly. Slots 0..=26 stay +//! identical so the D3D12 runtime's own calls (QueryInterface, GetType, AddRef, +//! Release) still work when the list is handed to ExecuteCommandLists. + +use core::ffi::c_void; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +#[allow(unused_imports)] use core::sync::atomic::AtomicU64; +use compat_common::record; + +extern "system" { + fn VirtualProtect(addr: *mut c_void, size: usize, new_protect: u32, old_protect: *mut u32) -> i32; +} +const PAGE_READWRITE: u32 = 0x04; + +/// Number of Xbox vtable slots we materialize. Max observed call is Xbox slot 50 +/// (OMSetRenderTargets); 128 leaves generous headroom. +const N: usize = 128; +static XBOX_VT: [AtomicUsize; N] = [const { AtomicUsize::new(0) }; N]; +static BUILT: AtomicBool = AtomicBool::new(false); +static mut REAL_VT_PTR: *const usize = core::ptr::null(); +pub(crate) unsafe fn real_list_slot(slot: usize) -> usize { + let p = unsafe { REAL_VT_PTR }; + if p.is_null() { 0 } else { unsafe { *p.add(slot) } } +} +static INSERTED_HITS: AtomicUsize = AtomicUsize::new(0); +pub(crate) const CONSOLE_NULL_SLOT: usize = 66; + +pub(crate) unsafe fn real_slot_ptr(slot: usize) -> *mut usize { + let p = unsafe { REAL_VT_PTR }; + if p.is_null() { core::ptr::null_mut() } else { unsafe { p.add(slot) as *mut usize } } +} + +pub(crate) unsafe fn real_method(slot: usize) -> usize { + unsafe { *REAL_VT_PTR.add(slot) } +} + +#[track_caller] +pub(crate) unsafe fn pc_method(list: *mut c_void, slot: usize) -> usize { + let vt = unsafe { *(list as *const *const usize) }; + let xbox = XBOX_VT.as_ptr() as *const usize; + if vt == xbox && !unsafe { REAL_VT_PTR }.is_null() { + if let Some(t) = crate::rootlog::route(slot, core::panic::Location::caller().file()) { + return t; + } + unsafe { *REAL_VT_PTR.add(slot) } + } else { + unsafe { *vt.add(slot) } + } +} + +pub(crate) fn vt_get(i: usize) -> usize { + XBOX_VT[i].load(Ordering::Relaxed) +} + +pub(crate) fn vt_set(i: usize, f: usize) { + XBOX_VT[i].store(f, Ordering::Relaxed); +} + +pub(crate) fn map_slot(i: usize) -> Option { + match i { + 0..=27 => Some(i), + 28..=31 => Some(i + 24), + 32..=55 => Some(i - 4), + 56..=59 => Some(i), + _ => None, + } +} + +/// Fail-loud-ish stub for an Xbox-inserted slot of unknown signature. Returns 0 +/// in rax (valid for both void- and HRESULT(S_OK)-returning methods) so a stray +/// call doesn't corrupt state; logs the first few so we learn if the game needs one. +#[unsafe(naked)] +unsafe extern "system" fn inserted_stub() { + core::arch::naked_asm!( + "lea rax, [rip + {counter}]", + "lock inc qword ptr [rax]", + "xor eax, eax", + "ret", + counter = sym INSERTED_HITS, + ) +} + +// High-slot diagnostic: the +4 shift is only valid through PC slot 46 (Xbox 50). +// Past that the Xbox command list has its own extension methods, so our naive map +// sends calls to the wrong PC method (e.g. a texture-copy landed on DispatchMesh -> +// device removal). Install logging no-op probes across the high range to capture, +// for every high slot the game actually calls, the slot + first arg + caller RVA, +// so we can reconstruct the true mapping. No-op avoids recording invalid GPU work. +static EXE_BASE: AtomicUsize = AtomicUsize::new(0); +static PROBE_HITS: AtomicUsize = AtomicUsize::new(0); + +unsafe extern "system" fn probe_impl(_this: *mut c_void, a: u64, caller: usize, slot: u64) { + let h = PROBE_HITS.fetch_add(1, Ordering::Relaxed); + static PER: [AtomicUsize; 128] = [const { AtomicUsize::new(0) }; 128]; + let _ = h; + if PER[(slot as usize).min(127)].fetch_add(1, Ordering::Relaxed) < 4 { + let base = EXE_BASE.load(Ordering::Relaxed); + record("d3d12_xs", "cmdlist.hi", + &format!("slot={slot} arg1={a:#x} caller={:#x}", caller.wrapping_sub(base))); + } +} + +macro_rules! make_probes { + ($(($name:ident, $slot:literal)),* $(,)?) => { + $( + #[unsafe(naked)] + unsafe extern "system" fn $name() { + core::arch::naked_asm!( + "mov r8, [rsp]", // caller return address -> 3rd arg + "mov r9d, {s}", // slot -> 4th arg + "jmp {i}", + s = const $slot, i = sym probe_impl, + ); + } + )* + fn is_probe(p: usize) -> bool { + false $( || p == $name as usize )* + } + #[allow(dead_code)] + unsafe fn install_all_probes() { + $( XBOX_VT[$slot].store($name as usize, Ordering::Relaxed); )* + } + /// The high-slot scan showed the game only calls slot 83 (an Xbox texture-copy + /// command our +4 map misrouted to DispatchMesh). No-op just that slot for now. + unsafe fn install_probes() { + // The +4 shift is verified only through Xbox slot 50. Everything above is an + // unverified/Xbox-only method: log-and-ignore until mapped from evidence + // (e.g. slot 67 = FlushTextureCache-style flush, slot 83 = texture copy). + install_all_probes(); + for i in 47..=49 { XBOX_VT[i].store(*REAL_VT_PTR.add(i - 4), Ordering::Relaxed); } + // Verified from FD3D12CommandContext::RHIClearMRTImpl call sites: + // Xbox 51 = ClearDepthStencilView (PC 47), Xbox 52 = ClearRenderTargetView (PC 48). + for i in 51..=52 { XBOX_VT[i].store(*REAL_VT_PTR.add(i - 4), Ordering::Relaxed); } + for i in 53..=58 { + if let Some(pc) = map_slot(i) { + XBOX_VT[i].store(*REAL_VT_PTR.add(pc), Ordering::Relaxed); + } + } + XBOX_VT[84].store(copy_resource_x as usize, Ordering::Relaxed); + XBOX_VT[67].store(flush_texture_cache_x as usize, Ordering::Relaxed); + // Xbox 68 = OMSetDepthBounds (PC ID3D12GraphicsCommandList1 slot 62): called from + // FD3D12StateCacheBase::ApplyState (EXE+0x4e0480) with the two cached depth-bound + // floats in xmm1/xmm2 when its depth-bounds dirty flag is set. + XBOX_VT[68].store(*REAL_VT_PTR.add(62), Ordering::Relaxed); + XBOX_VT[83].store(copy_texture_region_x as usize, Ordering::Relaxed); + XBOX_VT[16].store(copy_texture_region_owned as usize, Ordering::Relaxed); + XBOX_VT[17].store(copy_resource_owned as usize, Ordering::Relaxed); + // Xbox 59 = ExecuteIndirect, same slot and argument order as PC: + // FD3D12CommandContext::RHIDispatchIndirectComputeShader (EXE+0x85145b) calls it as + // (pCommandSignature, 1, pArgumentBuffer, ArgumentBufferOffset, null, 0). Leaving it + // a no-op silently dropped every indirect dispatch/draw. + XBOX_VT[59].store(*REAL_VT_PTR.add(59), Ordering::Relaxed); + if crate::rtcap::enabled() { + XBOX_VT[26].store(resource_barrier_traced as usize, Ordering::Relaxed); + XBOX_VT[25].store(set_pso_traced as usize, Ordering::Relaxed); + XBOX_VT[50].store(om_set_targets_traced as usize, Ordering::Relaxed); + XBOX_VT[12].store(draw_traced as usize, Ordering::Relaxed); + XBOX_VT[13].store(draw_indexed_traced as usize, Ordering::Relaxed); + XBOX_VT[14].store(dispatch_traced as usize, Ordering::Relaxed); + XBOX_VT[59].store(indirect_traced as usize, Ordering::Relaxed); + XBOX_VT[48].store(ia_set_vbs_traced as usize, Ordering::Relaxed); + XBOX_VT[35].store(set_compute_table_traced as usize, Ordering::Relaxed); + XBOX_VT[36].store(set_gfx_table_traced as usize, Ordering::Relaxed); + } + crate::blendclamp::install(); + crate::gpuprof::install(); + } + }; +} +make_probes!( + (p47,47),(p48,48),(p49,49),(p51,51),(p52,52),(p53,53),(p54,54),(p55,55),(p56,56),(p57,57), + (p58,58),(p59,59),(p60,60),(p61,61),(p62,62),(p63,63),(p64,64),(p65,65),(p66,66),(p67,67), + (p68,68),(p69,69),(p70,70),(p71,71),(p72,72),(p73,73),(p74,74),(p75,75),(p76,76),(p77,77), + (p78,78),(p79,79),(p80,80),(p81,81),(p82,82),(p83,83),(p84,84),(p85,85),(p86,86),(p87,87), + (p88,88),(p89,89),(p90,90),(p91,91),(p92,92),(p93,93),(p94,94),(p95,95),(p96,96),(p97,97), + (p98,98),(p99,99),(p100,100),(p101,101),(p102,102),(p103,103),(p104,104),(p105,105),(p106,106), + (p107,107),(p108,108),(p109,109),(p110,110),(p111,111),(p112,112),(p113,113),(p114,114),(p115,115), + (p116,116),(p117,117),(p118,118),(p119,119),(p120,120),(p121,121),(p122,122),(p123,123),(p124,124), + (p125,125),(p126,126),(p127,127), +); + +/// ResourceBarrier (slot 26, identical on Xbox and PC) with state tracking for the +/// diagnostic render-target capture; installed only when the capture is enabled. +unsafe extern "system" fn resource_barrier_traced(this: *mut c_void, n: u32, barriers: *const u8) { + crate::rtcap::note_barriers(n, barriers); + let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = core::mem::transmute(*REAL_VT_PTR.add(26)); + f(this, n, barriers) +} + +// Draw-trace hooks (installed only with the diagnostic capture): note, then forward. +unsafe extern "system" fn set_pso_traced(this: *mut c_void, pso: *mut c_void) { + crate::rtcap::on_set_pso(this as usize, pso as usize); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = core::mem::transmute(*REAL_VT_PTR.add(25)); + f(this, pso) +} +unsafe extern "system" fn om_set_targets_traced(this: *mut c_void, n: u32, handles: *const usize, single: i32, dsv: *const usize) { + crate::rtcap::on_set_targets(this as usize, n, handles, single != 0, dsv); + let f: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = core::mem::transmute(*REAL_VT_PTR.add(46)); + f(this, n, handles, single, dsv) +} +/// SetCompute/GraphicsRootDescriptorTable (PC 31/32 = Xbox 35/36): (RootParameterIndex, +/// D3D12_GPU_DESCRIPTOR_HANDLE by value). Recorded for the binding trace. +unsafe extern "system" fn set_compute_table_traced(this: *mut c_void, index: u32, handle: u64) { + crate::bindtrace::set_table(this as usize, true, index, handle); + let f: unsafe extern "system" fn(*mut c_void, u32, u64) = core::mem::transmute(*REAL_VT_PTR.add(31)); + f(this, index, handle) +} +unsafe extern "system" fn set_gfx_table_traced(this: *mut c_void, index: u32, handle: u64) { + crate::bindtrace::set_table(this as usize, false, index, handle); + let f: unsafe extern "system" fn(*mut c_void, u32, u64) = core::mem::transmute(*REAL_VT_PTR.add(32)); + f(this, index, handle) +} +unsafe extern "system" fn draw_traced(this: *mut c_void, a: u32, b: u32, c: u32, d: u32) { + crate::rtcap::trace_draw(this as usize, false, &format!("DrawInstanced(vtx={a} inst={b} startVtx={c} startInst={d})")); + if !crate::rtcap::on_draw(this as usize, 0) { + return; + } + let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = core::mem::transmute(*REAL_VT_PTR.add(12)); + f(this, a, b, c, d) +} +/// IASetVertexBuffers (PC 44 = Xbox 48): (StartSlot, NumViews, pViews); views are 16 bytes. +unsafe extern "system" fn ia_set_vbs_traced(this: *mut c_void, start: u32, n: u32, views: *const u8) { + crate::rtcap::on_set_vbs(this as usize, start, n, views); + let f: unsafe extern "system" fn(*mut c_void, u32, u32, *const u8) = core::mem::transmute(*REAL_VT_PTR.add(44)); + f(this, start, n, views) +} +unsafe extern "system" fn draw_indexed_traced(this: *mut c_void, a: u32, b: u32, c: u32, d: i32, e: u32) { + crate::rtcap::trace_draw(this as usize, false, &format!("DrawIndexedInstanced(idx={a} inst={b} startIdx={c} baseVtx={d} startInst={e})")); + if !crate::rtcap::on_draw(this as usize, 1) { + return; + } + let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32) = core::mem::transmute(*REAL_VT_PTR.add(13)); + f(this, a, b, c, d, e) +} +unsafe extern "system" fn dispatch_traced(this: *mut c_void, a: u32, b: u32, c: u32) { + crate::rtcap::trace_draw(this as usize, true, &format!("Dispatch({a},{b},{c})")); + if !crate::rtcap::on_draw(this as usize, 2) { + return; + } + let f: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = core::mem::transmute(*REAL_VT_PTR.add(14)); + f(this, a, b, c) +} +unsafe extern "system" fn indirect_traced(this: *mut c_void, sig: *mut c_void, n: u32, buf: *mut c_void, off: u64, cbuf: *mut c_void, coff: u64) { + if !crate::rtcap::on_draw(this as usize, 3) { + return; + } + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64) = core::mem::transmute(*REAL_VT_PTR.add(59)); + f(this, sig, n, buf, off, cbuf, coff) +} + +/// Xbox slot 67: reached (by tail call) from `FD3D12CommandContext::FlushTextureCacheIfNeeded` +/// (EXE+0x4e0718). The console GPU's texture cache has no PC counterpart, so there is +/// nothing to do; this is a deliberate no-op, not a placeholder. +static FLUSH_HITS: AtomicUsize = AtomicUsize::new(0); + +unsafe extern "system" fn flush_texture_cache_x(this: *mut c_void) { + let _ij = unsafe { crate::inject::scope(this, crate::inject::BARRIER) }; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| std::env::var("TOMBOX_FLUSH_UAV").map(|v| v != "0").unwrap_or(true)); + if FLUSH_HITS.fetch_add(1, Ordering::Relaxed) == 0 { + record("d3d12_xs", "FlushTextureCacheX", &format!("first call; mapped to a global UAV barrier = {on}")); + } + if !on || this.is_null() { + return; + } + let b: [u64; 4] = [2, 0, 0, 0]; + let f: unsafe extern "system" fn(*mut c_void, u32, *const [u64; 4]) = core::mem::transmute(*REAL_VT_PTR.add(26)); + f(this, 1, &b) +} + +pub fn flush_hits() -> usize { + FLUSH_HITS.load(Ordering::Relaxed) +} + +unsafe extern "system" fn copy_texture_region_owned(this: *mut c_void, dst: *const u8, x: u32, y: u32, z: u32, src: *const u8, src_box: *const c_void) { + if !dst.is_null() { + crate::placed::note_gpu_write(core::ptr::read_unaligned(dst as *const u64) as *mut c_void); + let d = core::ptr::read_unaligned(dst as *const u64) as usize; + if crate::res3d::is_3d(d) { + let s = if src.is_null() { 0 } else { core::ptr::read_unaligned(src as *const u64) as usize }; + crate::res3d::note(d, "CopyTextureRegion", &format!("at ({x},{y},{z}) src={s:#x} srcType={}", if src.is_null() { 9 } else { core::ptr::read_unaligned(src.add(8) as *const u32) })); + } + } + let f: unsafe extern "system" fn(*mut c_void, *const u8, u32, u32, u32, *const u8, *const c_void) = + core::mem::transmute(*REAL_VT_PTR.add(16)); + f(this, dst, x, y, z, src, src_box) +} + +unsafe extern "system" fn copy_resource_owned(this: *mut c_void, dst: *mut c_void, src: *mut c_void) { + crate::placed::note_gpu_write(dst); + crate::res3d::note(dst as usize, "CopyResource", &format!("src={src:p}")); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) = core::mem::transmute(*REAL_VT_PTR.add(17)); + f(this, dst, src) +} + +/// Xbox slot 83 = CopyTextureRegion with one extra trailing argument. +/// +/// Evidence: `FD3D12TextureBase::UpdateTexture` (EXE+0xc7cc5f) and +/// `FD3D12RHICommandInitializeTexture::ExecuteNoCmdList` (EXE+0x13e7da9) call it as +/// (this, pDst, DstX, DstY, DstZ, pSrc, pSrcBox, 0) with 48-byte copy locations laid out as +/// on PC (resource, type, 32-byte placed footprint / subresource index). The eighth argument +/// is always 0 at both sites (probably Xbox copy flags) and is dropped. +unsafe extern "system" fn copy_texture_region_x( + this: *mut c_void, dst: *const u8, x: u32, y: u32, z: u32, src: *const u8, src_box: *const c_void, flags: u32, +) { + static CALLS: AtomicUsize = AtomicUsize::new(0); + let n = CALLS.fetch_add(1, Ordering::Relaxed); + if dst.is_null() || src.is_null() { + record("d3d12_xs", "CopyTextureRegionX", "null copy location - ignored"); + return; + } + let q = |p: *const u8, o: usize| core::ptr::read_unaligned(p.add(o) as *const u64); + let d = |p: *const u8, o: usize| core::ptr::read_unaligned(p.add(o) as *const u32); + if n < 6 || flags != 0 { + record("d3d12_xs", "CopyTextureRegionX", &format!( + "#{n} dst{{res={:#x} type={} sub={}}} at ({x},{y},{z}) src{{res={:#x} type={} off={:#x} fmt={} {}x{}x{} pitch={}}} box={src_box:p} flags={flags:#x}", + q(dst, 0), d(dst, 8), d(dst, 16), q(src, 0), d(src, 8), q(src, 16), d(src, 24), d(src, 28), d(src, 32), d(src, 36), d(src, 40))); + } + if q(dst, 0) == 0 || q(src, 0) == 0 { + record("d3d12_xs", "CopyTextureRegionX", "null resource in copy location - ignored"); + return; + } + crate::placed::note_gpu_write(q(dst, 0) as *mut c_void); + crate::res3d::scan_grid_upload(q(dst, 0) as usize, q(src, 0) as *mut c_void, q(src, 16), d(src, 24), d(src, 28), d(src, 32), d(src, 36), d(src, 40)); + crate::res3d::note(q(dst, 0) as usize, "CopyTextureRegionX", &format!("at ({x},{y},{z}) src={:#x} type={} off={:#x} fmt={} {}x{}x{} pitch={}", q(src, 0), d(src, 8), q(src, 16), d(src, 24), d(src, 28), d(src, 32), d(src, 36), d(src, 40))); + let f: unsafe extern "system" fn(*mut c_void, *const u8, u32, u32, u32, *const u8, *const c_void) = + core::mem::transmute(*REAL_VT_PTR.add(16)); + f(this, dst, x, y, z, src, src_box); +} + +unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: *mut c_void, src: *mut c_void, flags: u32) { + static CALLS: AtomicUsize = AtomicUsize::new(0); + if CALLS.fetch_add(1, Ordering::Relaxed) < 4 || flags != 0 { + record("d3d12_xs", "CopyResourceX", &format!("dst={dst:p} src={src:p} flags={flags:#x}")); + } + if dst.is_null() || src.is_null() { + return; + } + crate::placed::note_gpu_write(dst); + crate::res3d::note(dst as usize, "CopyResourceX", &format!("src={src:p} flags={flags:#x}")); + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) = core::mem::transmute(*REAL_VT_PTR.add(17)); + f(this, dst, src); +} + +#[cfg(test)] +mod tests { + use super::map_slot; + + #[test] + fn xbox_cmdlist_slot_map() { + for i in 0..=27 { assert_eq!(map_slot(i), Some(i)); } + assert_eq!(map_slot(28), Some(52)); + assert_eq!(map_slot(29), Some(53)); + assert_eq!(map_slot(30), Some(54)); + assert_eq!(map_slot(31), Some(55)); + assert_eq!(map_slot(32), Some(28)); + assert_eq!(map_slot(36), Some(32)); + assert_eq!(map_slot(50), Some(46)); + assert_eq!(map_slot(53), Some(49)); + assert_eq!(map_slot(55), Some(51)); + for i in 56..=59 { assert_eq!(map_slot(i), Some(i)); } + assert_eq!(map_slot(60), None); + assert_eq!(map_slot(83), None); + let mut seen = std::collections::HashSet::new(); + for i in 0..=59 { assert!(seen.insert(map_slot(i).unwrap())); } + assert_eq!(seen.len(), 60); + assert!((0..60).all(|p| seen.contains(&p))); + } +} + +/// Point a freshly created real command list at the Xbox-layout vtable. +pub fn apply(real_list: *mut c_void) { + if real_list.is_null() { + return; + } + unsafe { + let real_vt = *(real_list as *const *const usize); + if !BUILT.swap(true, Ordering::SeqCst) { + for i in 0..N { + let p = match map_slot(i) { + Some(src) => *real_vt.add(src), + None => inserted_stub as usize, + }; + XBOX_VT[i].store(p, Ordering::Relaxed); + } + extern "system" { fn GetModuleHandleW(n: *const u16) -> *mut c_void; } + EXE_BASE.store(GetModuleHandleW(core::ptr::null()) as usize, Ordering::Relaxed); + REAL_VT_PTR = real_vt; + install_probes(); // high-slot logging no-op probes (47..95, except 50) + let console_defaults = crate::console_slots::snapshot(&XBOX_VT); + crate::cl_console_fix::install_console_bodies(&XBOX_VT); + crate::cmdlist_x::install(&XBOX_VT, real_vt); + crate::query_x::install(&XBOX_VT, real_vt); + crate::bindtrace::install_root_cbv_hooks(&XBOX_VT, real_vt); + crate::cbv_raw::install_root_cbv_hooks(&XBOX_VT, real_vt); + crate::replay::install(&XBOX_VT); + crate::replay_ext::install(&XBOX_VT); + crate::hot_reload::install(&XBOX_VT); + crate::cmd_spy::install(&XBOX_VT); + crate::cmdlist_validate::install(); + crate::console_slots::install_cmdlist(&XBOX_VT, real_vt, &console_defaults); + crate::console_slots_cl2::install_cmdlist(&XBOX_VT, &console_defaults); + crate::cl2_state::install(&XBOX_VT, &console_defaults); + crate::placed_offset::install_cmdlist(&XBOX_VT); + crate::list_split::install(&XBOX_VT); + crate::title_heap::install(&XBOX_VT); + crate::console_slots_mesh::install_cmdlist(&XBOX_VT); + crate::perfctr_cl::install(&XBOX_VT); + crate::cl_console_fix::install_copy_memory(&XBOX_VT); + crate::dbcount::install(&XBOX_VT); + crate::cl_console_fix::install_family_tail(&XBOX_VT); + crate::resolve_x::install(&XBOX_VT); + crate::dred_marks::install(&XBOX_VT); + crate::depth_uav::install_cmdlist(&XBOX_VT); + crate::pso_async::install(&XBOX_VT); + crate::cbv_raw::install_draw_check(&XBOX_VT); + crate::passcap::install(&XBOX_VT); + crate::gpuprof::install_ops(&XBOX_VT); + XBOX_VT[CONSOLE_NULL_SLOT].store(0, Ordering::Relaxed); + record("d3d12_xs", "cmdlist.vtable", + &format!("built Xbox-layout cmdlist vtable from real {real_vt:p} (+4 shift at PC28)")); + // Diagnostic: RVAs of the real PC methods inside D3D12Core, to attribute crash frames. + let core = GetModuleHandleW("D3D12Core.dll".encode_utf16().collect::>().as_ptr()) as usize; + let mut s = String::new(); + for i in 0..86 { s.push_str(&format!("{i}:{:x} ", (*real_vt.add(i)).wrapping_sub(core))); } + record("d3d12_xs", "cmdlist.vtable", &format!("XBOX_VT at {:p}, slot98={:#x} stub={:#x}", XBOX_VT.as_ptr(), XBOX_VT[98].load(Ordering::Relaxed), inserted_stub as usize)); + record("d3d12_xs", "cmdlist.vtable", &format!("PC cmdlist method RVAs in D3D12Core: {s}")); + } + // The real object keeps its PC vtable; the title only ever sees a shim (below). + let _ = (VirtualProtect as usize, PAGE_READWRITE); + } +} + +// ---- command-list shim object ------------------------------------------------------------ +// +// On Xbox the command list is a public struct with an inline GPU command buffer: the title +// writes raw command packets straight into it for hot state changes, e.g. in +// FD3D12StateCacheBase::ApplyState (EXE+0x4e0433): +// +// mov rcx,[list+18h] ; current write pointer +// cmp rcx,[list+30h] ; end of buffer -> jae slow path +// mov dword ptr [rcx],0C000B600h ; mov [rcx+4],eax ; lea rax,[rcx+8] ; mov [list+18h],rax +// +// and only when the buffer is full does it call the method (slow path = vtable slot 20, +// IASetPrimitiveTopology). Handing the title the real PC object therefore lets it read +// D3D12-internal fields as buffer pointers and scribble through them. Instead the title +// gets this shim: our own zeroed block whose write pointer == end pointer (both 0), so +// every inline fast path of that form falls back to the API call, with a vtable of thunks +// that swap the shim for the real list and jump through the Xbox-layout table. +// +// Status: the layout fact (+0x18 write ptr, +0x30 end ptr) is observed at one call site; +// other inline fields the title may read are served zeros (unverified). + +/// Offset of the real ID3D12GraphicsCommandList pointer inside the shim. +const SHIM_REAL_OFF: usize = 0x38; +/// Shim size: generous and zero-filled, for any other inline field the title reads. +const SHIM_SIZE: usize = 0x4000; +static SHIM_VT: [AtomicUsize; N] = [const { AtomicUsize::new(0) }; N]; +static SHIM_BUILT: std::sync::Once = std::sync::Once::new(); + +unsafe fn build_shim_thunks() { + extern "system" { + fn VirtualAlloc(addr: *mut c_void, size: usize, ty: u32, protect: u32) -> *mut c_void; + } + let code = VirtualAlloc(core::ptr::null_mut(), N * 32, 0x3000, 0x40) as *mut u8; + assert!(!code.is_null(), "d3d12_xs: cannot allocate command-list shim thunks"); + let timed = crate::slowcall::enabled(); + if timed { + crate::slowcall::calibrate(); + crate::slowcall::CL_TABLE.store(XBOX_VT.as_ptr() as usize, Ordering::SeqCst); + } + for i in 0..N { + let p = code.add(i * 32); + let mut b: Vec = vec![0x48, 0x8B, 0x49, SHIM_REAL_OFF as u8]; + if timed && !is_probe(XBOX_VT[i].load(Ordering::Relaxed)) { + b.extend_from_slice(&[0x41, 0xBA]); + b.extend_from_slice(&(i as u32).to_le_bytes()); + b.extend_from_slice(&[0x48, 0xB8]); + b.extend_from_slice(&(crate::slowcall::cl_timed as usize as u64).to_le_bytes()); + b.extend_from_slice(&[0xFF, 0xE0]); + } else { + b.extend_from_slice(&[0x48, 0xB8]); + b.extend_from_slice(&(XBOX_VT.as_ptr().add(i) as u64).to_le_bytes()); + b.extend_from_slice(&[0xFF, 0x20]); + } + core::ptr::copy_nonoverlapping(b.as_ptr(), p, b.len()); + SHIM_VT[i].store(p as usize, Ordering::Relaxed); + } +} + +/// Wrap a freshly created real command list in a shim object for the title. +pub fn wrap(real_list: *mut c_void) -> *mut c_void { + if real_list.is_null() { + return real_list; + } + apply(real_list); // builds the Xbox-layout table on first use + crate::cl2_state::on_new_list(real_list); + unsafe { + SHIM_BUILT.call_once(|| build_shim_thunks()); + let layout = std::alloc::Layout::from_size_align(SHIM_SIZE, 16).unwrap(); + let p = std::alloc::alloc_zeroed(layout); + assert!(!p.is_null(), "d3d12_xs: cannot allocate command-list shim"); + *(p as *mut usize) = SHIM_VT.as_ptr() as usize; + *(p.add(SHIM_REAL_OFF) as *mut usize) = real_list as usize; + crate::cmdlist_x::note_shim(real_list, p as *mut c_void); + static N_WRAPPED: AtomicUsize = AtomicUsize::new(0); + if N_WRAPPED.fetch_add(1, Ordering::Relaxed) < 3 { + record("d3d12_xs", "cmdlist.shim", &format!("real {real_list:p} wrapped as shim {p:p}")); + } + p as *mut c_void + } +} + +pub unsafe fn set_real(shim: *mut c_void, real: *mut c_void) { + unsafe { *((shim as *mut u8).add(SHIM_REAL_OFF) as *mut usize) = real as usize }; +} + +/// If `p` is one of our shims return the real command list, else `p` unchanged. +pub fn unwrap(p: *mut c_void) -> *mut c_void { + if p.is_null() { + return p; + } + unsafe { + if *(p as *const usize) == SHIM_VT.as_ptr() as usize { + *((p as *const u8).add(SHIM_REAL_OFF) as *const usize) as *mut c_void + } else if let Some(real) = crate::dma_list::unwrap(p) { + real + } else { + p + } + } +} + +/// How many times an Xbox-inserted (unmapped) slot was called — a nonzero value +/// means the game needs one of those 4 methods implemented. +pub fn inserted_hits() -> usize { + INSERTED_HITS.load(Ordering::Relaxed) +} diff --git a/crates/compat/d3d12_xs/src/cmdlist_x.rs b/crates/compat/d3d12_xs/src/cmdlist_x.rs index f096f12c..026e7fb7 100644 --- a/crates/compat/d3d12_xs/src/cmdlist_x.rs +++ b/crates/compat/d3d12_xs/src/cmdlist_x.rs @@ -137,10 +137,10 @@ unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers } let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = core::mem::transmute(REAL_BARRIER.load(Ordering::Relaxed)); - if crate::depth_uav::barriers(this, n, barriers, f) { - return; + if !crate::depth_uav::barriers(this, n, barriers, f) { + f(this, n, barriers); } - f(this, n, barriers) + crate::placed_offset::after_barrier(this, n, barriers) } pub fn note_shim(real: *mut c_void, shim: *mut c_void) { diff --git a/crates/compat/d3d12_xs/src/console_slots.rs b/crates/compat/d3d12_xs/src/console_slots.rs index a0deb9ad..a71a5902 100644 --- a/crates/compat/d3d12_xs/src/console_slots.rs +++ b/crates/compat/d3d12_xs/src/console_slots.rs @@ -123,6 +123,7 @@ pub fn copy_plan(dst_state: u32, src_state: u32, dst_upload: bool) -> Option<(Op } unsafe extern "system" fn cl_copy_memory(this: *mut c_void, dst: u64, src: u64, size: u64, flags: u32) { + let _ij = unsafe { crate::inject::scope(this, crate::inject::COPY) }; if size == 0 || size % 4 != 0 { if once(©_LOG, 8) { record("d3d12_xs", "console_slots", &format!("CopyMemoryToMemoryX: size {size:#x} must be a non-zero multiple of 4 (console validation)")); @@ -303,6 +304,7 @@ pub fn wbi_params(va: u64, words: &[u32]) -> Vec { static WBI_LOG: AtomicUsize = AtomicUsize::new(0); pub(crate) unsafe fn write_immediate(list: *mut c_void, va: u64, words: &[u32], mode: u32, what: &str) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::COPY) }; let align = 4 * words.len() as u64; if va == 0 || va & GRAPHICS_VA_HIGH_MASK != 0 || va % align != 0 { if once(&WBI_LOG, 8) { diff --git a/crates/compat/d3d12_xs/src/cpu_watch.rs b/crates/compat/d3d12_xs/src/cpu_watch.rs new file mode 100644 index 00000000..3c2cede3 --- /dev/null +++ b/crates/compat/d3d12_xs/src/cpu_watch.rs @@ -0,0 +1,343 @@ +use core::ffi::c_void; +use core::sync::atomic::{AtomicUsize, Ordering}; + +pub const PAGE: usize = 0x1000; +const WRITE_WATCH_FLAG_RESET: u32 = 1; +const ABSENT: usize = 1; +pub const OWNER_NONE: u32 = 0; +pub const OWNER_EMULATOR: u32 = 1; +pub const OWNER_TITLE: u32 = 2; + +extern "system" { + fn GetWriteWatch(flags: u32, base: *mut c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; + fn GetModuleHandleA(name: *const u8) -> *mut c_void; + fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void; + fn GetLastError() -> u32; + fn VirtualQuery(addr: *const c_void, mbi: *mut Mbi, len: usize) -> usize; +} + +#[repr(C)] +#[derive(Default)] +struct Mbi { + base: usize, + alloc_base: usize, + alloc_protect: u32, + partition: u16, + pad0: u16, + size: usize, + state: u32, + protect: u32, + ty: u32, + pad1: u32, +} + +pub fn watched_ranges(lo: usize, len: usize) -> Option> { + if !enabled() || len == 0 { + return None; + } + let hi = lo + len; + let mut out: Vec<(usize, usize, usize)> = Vec::new(); + let mut a = lo; + while a < hi { + let mut m = Mbi::default(); + if unsafe { VirtualQuery(a as *const c_void, &mut m, core::mem::size_of::()) } == 0 { + return None; + } + let mut end = (m.base + m.size).min(hi); + if end <= a { + return None; + } + if m.state == 0x1000 { + let (o, b, n) = owner(a); + if o != OWNER_EMULATOR { + return None; + } + end = end.min(b + n); + if end <= a { + return None; + } + let mut one: *mut c_void = core::ptr::null_mut(); + let mut count = 1usize; + let mut gran = 0u32; + if unsafe { GetWriteWatch(0, (a & !(PAGE - 1)) as *mut c_void, PAGE, &mut one, &mut count, &mut gran) } != 0 { + return None; + } + match out.last_mut() { + Some(l) if l.1 == a && l.2 == b => l.1 = end, + _ => out.push((a, end, b)), + } + } + a = end; + } + Some(out) +} + +pub fn committed(lo: usize, len: usize) -> bool { + let probe = |a: usize| { + let mut m = Mbi::default(); + unsafe { VirtualQuery(a as *const c_void, &mut m, core::mem::size_of::()) != 0 && m.state == 0x1000 } + }; + len > 0 && probe(lo) && probe(lo + len - 1) +} + +pub fn region(addr: usize) -> String { + let mut m = Mbi::default(); + let n = unsafe { VirtualQuery(addr as *const c_void, &mut m, core::mem::size_of::()) }; + if n == 0 { + return format!("VirtualQuery({addr:#x}) failed (error {})", unsafe { GetLastError() }); + } + let ty = match m.ty { + 0x2_0000 => "private", + 0x4_0000 => "mapped", + 0x100_0000 => "image", + _ => "none", + }; + let st = match m.state { + 0x1000 => "commit", + 0x2000 => "reserve", + 0x1_0000 => "free", + _ => "?", + }; + format!("type={ty} state={st} protect={:#x} alloc_base={:#x} alloc_protect={:#x} region={:#x}+{:#x} va-alloc_base={:#x}", m.protect, m.alloc_base, m.alloc_protect, m.base, m.size, addr.wrapping_sub(m.alloc_base)) +} + +type OwnerFn = unsafe extern "system" fn(usize, *mut usize, *mut usize) -> u32; + +static OWNER_FN: AtomicUsize = AtomicUsize::new(0); +static OWNER_TRIES: AtomicUsize = AtomicUsize::new(0); +static OWNER_LAST_TRY: std::sync::Mutex> = std::sync::Mutex::new(None); +static TEST_OWNER: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("TOMBOX_WRITE_WATCH").map(|v| v.trim() != "0").unwrap_or(true)) +} + +fn owner_fn() -> Option { + let f = OWNER_FN.load(Ordering::Acquire); + if f > ABSENT { + return Some(unsafe { core::mem::transmute::(f) }); + } + let now = std::time::Instant::now(); + { + let mut last = OWNER_LAST_TRY.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(t) = *last { + if now.duration_since(t) < std::time::Duration::from_millis(250) { + return None; + } + } + *last = Some(now); + } + for m in [&b"xmem.dll\0"[..], b"xmem_x.dll\0", b"xmem_xs.dll\0"] { + let h = unsafe { GetModuleHandleA(m.as_ptr()) }; + if h.is_null() { + continue; + } + let p = unsafe { GetProcAddress(h, b"TomboxWriteWatchOwner\0".as_ptr()) } as usize; + if p > ABSENT { + OWNER_FN.store(p, Ordering::Release); + return Some(unsafe { core::mem::transmute::(p) }); + } + } + OWNER_TRIES.fetch_add(1, Ordering::Relaxed); + None +} + +pub fn register_test_region(base: usize, len: usize) { + let mut r = TEST_OWNER.lock().unwrap_or_else(|e| e.into_inner()); + r.retain(|&(b, n)| b + n <= base || base + len <= b); + r.push((base, len)); +} + +pub fn owner(addr: usize) -> (u32, usize, usize) { + if let Some(&(b, n)) = TEST_OWNER.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|&&(b, n)| addr >= b && addr < b + n) { + return (OWNER_EMULATOR, b, n); + } + let Some(f) = owner_fn() else { return (OWNER_NONE, 0, 0) }; + let (mut b, mut n) = (0usize, 0usize); + let o = unsafe { f(addr, &mut b, &mut n) }; + (o, b, n) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Class { + Watched, + Disabled, + NoOwnerApi, + TitleOwned, + NotWatched, + SpansRegions, +} + +impl Class { + pub fn why(self) -> &'static str { + match self { + Class::Watched => "watched", + Class::Disabled => "TOMBOX_WRITE_WATCH=0", + Class::NoOwnerApi => "xmem exports no TomboxWriteWatchOwner, so a watched range could be the title's own", + Class::TitleOwned => "the title allocated this memory with MEM_WRITE_WATCH itself; resetting would corrupt its XMemGetWriteWatch", + Class::NotWatched => "the backing memory has no write watch (heap block, physical or file-mapped view, or a reservation made before write watch)", + Class::SpansRegions => "the resource spans more than one watched reservation", + } + } +} + +pub fn classify(lo: usize, len: usize) -> Class { + if !enabled() { + return Class::Disabled; + } + if len == 0 { + return Class::NotWatched; + } + let (o, b, n) = owner(lo); + match o { + OWNER_EMULATOR => {} + OWNER_TITLE => return Class::TitleOwned, + _ => { + return if owner_fn().is_none() && TEST_OWNER.lock().unwrap_or_else(|e| e.into_inner()).is_empty() { Class::NoOwnerApi } else { Class::NotWatched }; + } + } + if lo + len > b + n { + return Class::SpansRegions; + } + let mut one: *mut c_void = core::ptr::null_mut(); + let mut count = 1usize; + let mut gran = 0u32; + let first = lo & !(PAGE - 1); + let r = unsafe { GetWriteWatch(0, first as *mut c_void, PAGE, &mut one, &mut count, &mut gran) }; + if r != 0 { + return Class::NotWatched; + } + Class::Watched +} + +pub fn take_dirty(lo: usize, hi: usize, buf: &mut Vec) -> Result, u32> { + let a = lo & !(PAGE - 1); + let b = (hi + PAGE - 1) & !(PAGE - 1); + if a >= b { + return Ok(Vec::new()); + } + let pages = (b - a) / PAGE; + if buf.len() < pages { + buf.resize(pages, 0); + } + let mut count = pages; + let mut gran = 0u32; + let r = unsafe { GetWriteWatch(WRITE_WATCH_FLAG_RESET, a as *mut c_void, b - a, buf.as_mut_ptr() as *mut *mut c_void, &mut count, &mut gran) }; + if r != 0 { + return Err(unsafe { GetLastError() }); + } + let g = if gran == 0 { PAGE } else { gran as usize }; + Ok(runs(&buf[..count.min(pages)], g)) +} + +pub fn runs(pages: &[usize], gran: usize) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = Vec::new(); + let mut v: Vec = pages.to_vec(); + v.sort_unstable(); + for p in v { + match out.last_mut() { + Some(last) if last.1 >= p => last.1 = last.1.max(p + gran), + _ => out.push((p, p + gran)), + } + } + out +} + +pub fn merge_extents(mut ext: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ext.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::new(); + for (a, b) in ext { + let (a, b) = (a & !(PAGE - 1), (b + PAGE - 1) & !(PAGE - 1)); + match out.last_mut() { + Some(last) if last.1 >= a => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + out +} + +pub fn row_extents(offs: &[u32], w_e: usize, h_e: usize, bpe: usize) -> Vec<(u32, u32)> { + (0..h_e) + .map(|y| { + let row = &offs[y * w_e..(y + 1) * w_e]; + let lo = row.iter().copied().min().unwrap_or(0); + let hi = row.iter().copied().max().unwrap_or(0) + bpe as u32; + (lo, hi) + }) + .collect() +} + +pub fn dirty_bands(rows: &[(u32, u32)], base: usize, dirty: &[(usize, usize)], gap: usize) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = Vec::new(); + for (y, &(lo, hi)) in rows.iter().enumerate() { + let (a, b) = (base + lo as usize, base + hi as usize); + let hit = dirty.iter().any(|&(da, db)| da < b && a < db); + if !hit { + continue; + } + match out.last_mut() { + Some(last) if y <= last.1 + gap => last.1 = y + 1, + _ => out.push((y, y + 1)), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + extern "system" { + fn VirtualAlloc(addr: *mut c_void, len: usize, ty: u32, protect: u32) -> *mut c_void; + fn VirtualFree(addr: *mut c_void, len: usize, ty: u32) -> i32; + } + + const MEM_COMMIT_RESERVE: u32 = 0x3000; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + #[test] + fn dirty_pages_coalesce_into_runs() { + assert_eq!(runs(&[0x3000, 0x1000, 0x2000, 0x6000], PAGE), vec![(0x1000, 0x4000), (0x6000, 0x7000)]); + assert_eq!(merge_extents(vec![(0x2010, 0x2020), (0x1000, 0x2001), (0x9000, 0x9001)]), vec![(0x1000, 0x3000), (0x9000, 0xa000)]); + } + + #[test] + fn a_partial_page_write_marks_only_the_rows_on_that_page() { + let (w, h, bpe) = (256usize, 64usize, 4usize); + let offs: Vec = (0..h).flat_map(|y| (0..w).map(move |x| ((y * w + x) * bpe) as u32)).collect(); + let rows = row_extents(&offs, w, h, bpe); + assert_eq!(rows[1], (1024, 2048)); + let base = 0x10_0000; + let bands = dirty_bands(&rows, base, &[(base + 0x3000, base + 0x4000)], 0); + assert_eq!(bands, vec![(12, 16)]); + let bands = dirty_bands(&rows, base, &[(base, base + 0x1000), (base + 0x2000, base + 0x3000)], 0); + assert_eq!(bands, vec![(0, 4), (8, 12)]); + assert_eq!(dirty_bands(&rows, base, &[(base, base + 0x1000), (base + 0x2000, base + 0x3000)], 4), vec![(0, 12)]); + assert!(dirty_bands(&rows, base, &[(base + 0x40000, base + 0x41000)], 0).is_empty()); + } + + #[test] + fn get_write_watch_reports_writes_after_a_reset() { + unsafe { + let n = 8 * PAGE; + let p = VirtualAlloc(core::ptr::null_mut(), n, MEM_COMMIT_RESERVE | MEM_WRITE_WATCH, 0x04) as usize; + assert_ne!(p, 0); + register_test_region(p, n); + if enabled() { + assert_eq!(classify(p + 16, 3 * PAGE), Class::Watched); + } + let mut buf = Vec::new(); + let _ = take_dirty(p, p + n, &mut buf).unwrap(); + *((p + 2 * PAGE + 100) as *mut u8) = 7; + *((p + 3 * PAGE) as *mut u8) = 7; + *((p + 6 * PAGE + 5) as *mut u8) = 7; + assert_eq!(take_dirty(p, p + n, &mut buf).unwrap(), vec![(p + 2 * PAGE, p + 4 * PAGE), (p + 6 * PAGE, p + 7 * PAGE)]); + assert!(take_dirty(p, p + n, &mut buf).unwrap().is_empty(), "RESET clears what was reported"); + let q = VirtualAlloc(core::ptr::null_mut(), n, MEM_COMMIT_RESERVE, 0x04) as usize; + assert!(take_dirty(q, q + n, &mut buf).is_err(), "memory without MEM_WRITE_WATCH is refused, not reported clean"); + VirtualFree(p as *mut c_void, 0, 0x8000); + VirtualFree(q as *mut c_void, 0, 0x8000); + } + } +} diff --git a/crates/compat/d3d12_xs/src/dbcount.rs b/crates/compat/d3d12_xs/src/dbcount.rs index f891aaf2..eef0c62e 100644 --- a/crates/compat/d3d12_xs/src/dbcount.rs +++ b/crates/compat/d3d12_xs/src/dbcount.rs @@ -1194,17 +1194,17 @@ unsafe fn pass_pso(list: *mut c_void, pso: usize, src: &Src, pass: Pass, vk: Opt } unsafe fn pc_set_pso(list: *mut c_void, pso: usize) { - let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(vslot(list, PC_SET_PSO)) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SET_PSO)) }; unsafe { f(list, pso as *mut c_void) }; } unsafe fn pc_null_so(list: *mut c_void) { - let f: unsafe extern "system" fn(*mut c_void, u32, u32, *const u8) = unsafe { core::mem::transmute(vslot(list, PC_SO_TARGETS)) }; + let f: unsafe extern "system" fn(*mut c_void, u32, u32, *const u8) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SO_TARGETS)) }; unsafe { f(list, 0, 4, core::ptr::null()) }; } unsafe fn aux_query(list: *mut c_void, heap: usize, begin: bool, index: u32) { - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u32) = unsafe { core::mem::transmute(vslot(list, if begin { PC_BEGIN_QUERY } else { PC_END_QUERY })) }; + let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u32) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, if begin { PC_BEGIN_QUERY } else { PC_END_QUERY })) }; unsafe { f(list, heap as *mut c_void, QUERY_OCCLUSION, index) }; } @@ -1226,7 +1226,8 @@ impl Draw { } unsafe fn issue(list: *mut c_void, d: Draw, replay: bool) { - let pc = |i: usize| unsafe { vslot(list, i) }; + let _ij = if replay { Some(unsafe { crate::inject::scope(list, crate::inject::DRAW) }) } else { None }; + let pc = |i: usize| unsafe { crate::cmdlist_wrap::pc_method(list, i) }; match d { Draw::Instanced(a, b, c, e) => { let p = if replay { pc(PC_DRAW) } else { prev(X_DRAW) }; @@ -1591,7 +1592,7 @@ unsafe fn uav_barrier(list: *mut c_void, res: usize) { let mut b = [0u8; 32]; b[0..4].copy_from_slice(&2u32.to_le_bytes()); b[8..16].copy_from_slice(&(res as u64).to_le_bytes()); - let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(vslot(list, PC_BARRIER)) }; + let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_BARRIER)) }; unsafe { f(list, 1, b.as_ptr()) }; } @@ -1601,12 +1602,12 @@ unsafe fn combine(list: *mut c_void, g: &Gpu, heap: *mut c_void, ty: u32, index: pools(|p| group_slots(groups).for_each(|s| p.aux.hold(k, s))); let t = base; let acc = base + 8; - let cp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = unsafe { core::mem::transmute(vslot(list, PC_COPY_BUFFER)) }; - let rq: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u32, u32, *mut c_void, u64) = unsafe { core::mem::transmute(vslot(list, PC_RESOLVE_QUERY)) }; - let srs: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(vslot(list, PC_SET_CROOT)) }; - let sc: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = unsafe { core::mem::transmute(vslot(list, PC_SET_CCONSTS)) }; - let su: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(vslot(list, PC_SET_CUAV)) }; - let dp: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = unsafe { core::mem::transmute(vslot(list, PC_DISPATCH)) }; + let cp: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_COPY_BUFFER)) }; + let rq: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u32, u32, *mut c_void, u64) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_RESOLVE_QUERY)) }; + let srs: unsafe extern "system" fn(*mut c_void, *mut c_void) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SET_CROOT)) }; + let sc: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SET_CCONSTS)) }; + let su: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SET_CUAV)) }; + let dp: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_DISPATCH)) }; let s = res as *mut c_void; unsafe { crate::fill::barrier_pub(list, res, ST_COMMON, ST_COPY_DEST) }; fwd!(X_RESOLVE_QUERY, fn(*mut c_void, u32, u32, u32, *mut c_void, u64) -> (), list, heap, ty, index, 1, s, t as u64); diff --git a/crates/compat/d3d12_xs/src/depth_uav.rs b/crates/compat/d3d12_xs/src/depth_uav.rs index 8c7114e9..35a50eea 100644 --- a/crates/compat/d3d12_xs/src/depth_uav.rs +++ b/crates/compat/d3d12_xs/src/depth_uav.rs @@ -673,6 +673,7 @@ pub unsafe fn barriers(list: *mut c_void, n: u32, barriers: *const u8, real: uns } unsafe fn run_pass(list: *mut c_void, p: &Pair, copy_in: bool) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::DETILE) }; let Some(ps) = PASS.get().and_then(|r| r.as_ref().ok()) else { return }; static LOG: AtomicUsize = AtomicUsize::new(0); if crate::cl2_state::active_queries(list) > 0 && LOG.fetch_add(1, Ordering::Relaxed) < 4 { diff --git a/crates/compat/d3d12_xs/src/device_console_fix.rs b/crates/compat/d3d12_xs/src/device_console_fix.rs index dfb6f9c5..d9bb48a0 100644 --- a/crates/compat/d3d12_xs/src/device_console_fix.rs +++ b/crates/compat/d3d12_xs/src/device_console_fix.rs @@ -210,6 +210,16 @@ pub const HEAP_FLAG_XBOX_CPU_ATTR: u32 = 0x2; const E_INVALIDARG: i32 = 0x8007_0057u32 as i32; const PC_HEAP_MIN: u64 = 0x10000; const PC_HEAP_ALIGN_MSAA: u64 = 0x40_0000; +pub const HEAP_DENY_CATEGORIES: u32 = 0x4 | 0x40 | 0x80; + +pub fn pc_heap_deny_flags(flags: u32) -> u32 { + let deny = flags & HEAP_DENY_CATEGORIES; + if deny.count_ones() == 1 { + flags & !HEAP_DENY_CATEGORIES + } else { + flags + } +} pub fn heap_desc_for_pc(x: &[u8]) -> Result<[u8; HEAP_DESC_SIZE], i32> { let mut d: [u8; HEAP_DESC_SIZE] = x[..HEAP_DESC_SIZE].try_into().unwrap(); @@ -217,7 +227,7 @@ pub fn heap_desc_for_pc(x: &[u8]) -> Result<[u8; HEAP_DESC_SIZE], i32> { if flags & HEAP_FLAG_ALLOW_DISPLAY != 0 { return Err(E_INVALIDARG); } - d[0x28..0x2c].copy_from_slice(&(flags & !HEAP_FLAG_XBOX_CPU_ATTR).to_le_bytes()); + d[0x28..0x2c].copy_from_slice(&pc_heap_deny_flags(flags & !HEAP_FLAG_XBOX_CPU_ATTR).to_le_bytes()); pc_heap_words_at(&mut d, 8); let size = u64::from_le_bytes(d[0..8].try_into().unwrap()); let size = ((size + 0xff) & !0xff).max(PC_HEAP_MIN); @@ -559,7 +569,7 @@ mod tests { let d = heap_desc_for_pc(&heap(0x12345, 1, 0x100, 0x2 | 0x4)).unwrap(); assert_eq!(u64::from_le_bytes(d[0..8].try_into().unwrap()), 0x12400); assert_eq!(u64::from_le_bytes(d[0x20..0x28].try_into().unwrap()), 0); - assert_eq!(xs_u32(&d, 0x28), 0x4); + assert_eq!(xs_u32(&d, 0x28), 0); assert_eq!(xs_u32(&d, 8), 1); let z = heap_desc_for_pc(&heap(0, 2, 0x20_0000, 0)).unwrap(); assert_eq!(u64::from_le_bytes(z[0..8].try_into().unwrap()), PC_HEAP_MIN); @@ -568,6 +578,14 @@ mod tests { assert_eq!(u64::from_le_bytes(big[0x20..0x28].try_into().unwrap()), 1 << 23); } + #[test] + fn single_category_deny_heaps_become_valid_pc_heaps() { + for (x, pc) in [(0u32, 0u32), (0x4, 0), (0x40, 0), (0x80, 0), (0x44, 0x44), (0x84, 0x84), (0xc0, 0xc0), (0x4 | 0x1, 0x1), (0x40 | 0x100, 0x100), (0x44 | 0x1, 0x45)] { + assert_eq!(pc_heap_deny_flags(x), pc, "flags {x:#x}"); + assert_eq!(xs_u32(&heap_desc_for_pc(&heap(0x10000, 1, 0, x)).unwrap(), 0x28), pc, "flags {x:#x}"); + } + } + #[test] fn null_sampler_desc_uses_the_release_driver_default_0x12d600() { let x = default_xsamp(); diff --git a/crates/compat/d3d12_xs/src/device_ext_a.rs b/crates/compat/d3d12_xs/src/device_ext_a.rs index 621ebd1f..92115d75 100644 --- a/crates/compat/d3d12_xs/src/device_ext_a.rs +++ b/crates/compat/d3d12_xs/src/device_ext_a.rs @@ -249,6 +249,14 @@ pub unsafe fn plan_placed_view(res: *mut c_void, pdesc: *const u8, uav: bool, lo if fit_texture_view(&mut pc, &rdesc, uav) && once(&FIT_LOG, 16) { record("d3d12_xs", "PlacedViewX", &format!("texture view (resource fmt={} samples={}) given view fmt={} dim={}: PC texture views need a typed format and an MSAA dimension for multisampled resources, so they are taken from the resource",rd32(&rdesc, 0x20), rd32(&rdesc, 0x24), rd32(&pc, 0), rd32(&pc, 4))); } + if !uav && rd32(&rdesc, 0x24) > 1 { + crate::fmask_check::note_view(res as usize, rd32(&pc, 8), rd32(&x, 0x34)); + } + static MS_LOG: AtomicUsize = AtomicUsize::new(0); + if !uav && rd32(&rdesc, 0x24) > 1 && (crate::rtcap::enabled() || crate::passcap::on()) && once(&MS_LOG, 64) { + let hex: Vec = x.chunks(4).map(|c| format!("{:08x}", u32::from_le_bytes([c[0], c[1], c[2], c[3]]))).collect(); + record("d3d12_xs", "PlacedViewX", &format!("MS SRV on res {:#x} (fmt={} samples={}): raw Xbox desc dwords [{}] -> PC fmt={} dim={} map={:#x}", res as usize, rd32(&rdesc, 0x20), rd32(&rdesc, 0x24), hex.join(" "), rd32(&pc, 0), rd32(&pc, 4), rd32(&pc, 8))); + } let extras: Vec<(usize, u32)> = if uav { vec![(0x38, rd32(&x, 0x38))] } else { diff --git a/crates/compat/d3d12_xs/src/device_wrap.rs b/crates/compat/d3d12_xs/src/device_wrap.rs index 442c031a..08d686b3 100644 --- a/crates/compat/d3d12_xs/src/device_wrap.rs +++ b/crates/compat/d3d12_xs/src/device_wrap.rs @@ -41,6 +41,8 @@ const DEVICE_IIDS: [Guid; 9] = [ Guid { d1: 0x9218_e6bb, d2: 0xf944, d3: 0x4f7e, d4: [0xa7, 0x5c, 0xb1, 0xb2, 0xc7, 0xb7, 0x01, 0xf3] }, // Device8 ]; +const IID_XSX_DEVICE8: Guid = Guid { d1: 0x728f1fa2, d2: 0xea11, d3: 0x4a9f, d4: [0x9b, 0x52, 0x9b, 0x42, 0xa4, 0x84, 0xd5, 0xc9] }; + fn is_device_iid(g: &Guid) -> bool { DEVICE_IIDS.iter().any(|d| d == g) } @@ -69,7 +71,7 @@ unsafe extern "system" fn qi(this: *mut DeviceWrapper, riid: *const Guid, ppv: * } unsafe { *ppv = core::ptr::null_mut() }; let g = unsafe { &*riid }; - if is_device_iid(g) || *g == IID_IUNKNOWN { + if is_device_iid(g) || *g == IID_IUNKNOWN || *g == IID_XSX_DEVICE8 { unsafe { *ppv = this as *mut c_void; (*this).refs.fetch_add(1, Ordering::SeqCst); @@ -167,7 +169,7 @@ unsafe extern "system" fn create_descriptor_heap( // Keep the heap REAL (so it works when passed to SetDescriptorHeaps etc.); // patch the shared heap vtable once to fix the handle-getter ABI. crate::heap_wrap::ensure_patched(unsafe { *ppv }); - if crate::rtcap::enabled() && !pdesc.is_null() { + if (crate::rtcap::enabled() || crate::passcap::tables_on()) && !pdesc.is_null() { // Binding trace: remember shader-visible heaps (GPU handle -> CPU handle). let d = pdesc as *const u32; let (htype, numd, flags) = unsafe { (*d.add(0), *d.add(1), *d.add(2)) }; @@ -558,7 +560,11 @@ unsafe extern "system" fn create_committed_resource( desc_copy[..0x38].copy_from_slice(&d); crate::depth_uav::d_real(init_state) }; - let hr = unsafe { f(real, pheap, heap_flags, desc_ptr, init_state, pclear, use_riid, ppv) }; + let pooled = if depth_uav == crate::depth_uav::Plan::None { unsafe { crate::res_pool::try_create(real, pheap, heap_flags, desc_ptr, init_state, pclear, ppv) } } else { None }; + let hr = match pooled { + Some(hr) => hr, + None => unsafe { f(real, pheap, heap_flags, desc_ptr, init_state, pclear, use_riid, ppv) }, + }; if hr >= 0 && !ppv.is_null() { crate::map_x::ensure_patched(unsafe { *ppv }); let res = unsafe { *ppv }; @@ -579,6 +585,9 @@ unsafe extern "system" fn create_committed_resource( let xdesc: [u8; 0x38] = unsafe { core::ptr::read_unaligned(pdesc as *const [u8; 0x38]) }; let backing = if heap_type == 1 { unsafe { crate::gpu_va::back_committed_texture(&xdesc) } } else { None }; unsafe { crate::gpu_va::note_resource(real, *ppv, &desc_copy[..0x38], init_state, backing) }; + if crate::va_census::on() { + crate::va_census::note_how(unsafe { *ppv } as usize, match backing { Some(v) => format!("CreateCommittedResource with title backing {v:#x}"), None => "CreateCommittedResource".to_string() }); + } let res = unsafe { *ppv }; match backing { Some(va) => unsafe { crate::gpu_va::adopt_backing(res, va, xdesc, init_state) }, @@ -587,10 +596,13 @@ unsafe extern "system" fn create_committed_resource( } unsafe { crate::rtcap::register(*ppv, &desc_copy[..0x38], init_state) }; crate::res3d::note_create(unsafe { *ppv }, &desc_copy[..0x38], &format!("committed heapType={heap_type} heapFlags={heap_flags:#x} state={init_state:#x} backing={backing:x?}")); - if crate::rtcap::enabled() && desc_copy[0] == 1 && !pheap.is_null() { + if (crate::rtcap::enabled() || crate::passcap::tables_on()) && desc_copy[0] == 1 && !pheap.is_null() { let width = u64::from_le_bytes(desc_copy[0x10..0x18].try_into().unwrap()); unsafe { crate::bindtrace::note_buffer(*ppv, width, *pheap) }; } + if pooled.is_none() { + unsafe { crate::title_gpu::committed(*ppv, &xdesc) }; + } } static N: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); if hr < 0 && !pdesc.is_null() { @@ -686,6 +698,8 @@ unsafe fn bisect_gfx_pso(real: *mut c_void, desc: &[u8], riid: *const Guid) -> S ("default_blend", Box::new(|d: &mut Vec| { d[0x78..0x1c0].fill(0); for i in 0..8 { let o = 0x80 + i * 40; d[o + 8..o + 12].copy_from_slice(&2u32.to_le_bytes()); d[o + 12..o + 16].copy_from_slice(&1u32.to_le_bytes()); d[o + 16..o + 20].copy_from_slice(&1u32.to_le_bytes()); d[o + 20..o + 24].copy_from_slice(&2u32.to_le_bytes()); d[o + 24..o + 28].copy_from_slice(&1u32.to_le_bytes()); d[o + 28..o + 32].copy_from_slice(&1u32.to_le_bytes()); d[o + 32..o + 36].copy_from_slice(&4u32.to_le_bytes()); d[o + 36] = 15; } })), ("no_flags", Box::new(move |d: &mut Vec| put(d, 0x288, 0))), ("no_stream_out", Box::new(|d: &mut Vec| d[0x58..0x78].fill(0))), + ("rtv_fill", Box::new(move |d: &mut Vec| { let rt0 = u32::from_le_bytes(d[0x244..0x248].try_into().unwrap()); let num = u32::from_le_bytes(d[0x240..0x244].try_into().unwrap()).min(8) as usize; for i in 0..num { let o = 0x244 + 4 * i; if d[o..o + 4] == [0u8; 4] { put(d, o, rt0); } } })), + ("single_sample", Box::new(move |d: &mut Vec| { put(d, 0x268, 1); put(d, 0x26c, 0); })), ]; let mut out = String::new(); for (name, m) in variants { @@ -800,14 +814,47 @@ unsafe extern "system" fn create_gfx_pso_x( this: *mut DeviceWrapper, pdesc: *const u8, num_ext: u32, pext: *const u8, riid: *const Guid, ppv: *mut *mut c_void, ) -> i32 { + unsafe { crate::pso_xrec::note(crate::pso_xrec::GFX, pdesc, num_ext) }; let mut ev = crate::frame_ev::begin(crate::frame_ev::PSO_SYNC); if let Some(hr) = unsafe { crate::pso_async::create_gfx(this, (*this).real, pdesc, num_ext, pext, riid, ppv, create_gfx_pso_sync) } { if let Some(s) = ev.as_mut() { s.set_kind(if crate::frame_ev::take_async_mark() { crate::frame_ev::PSO_ASYNC } else { crate::frame_ev::PSO_INLINE }); } - return hr; + return crate::cbv_copy::after_gfx_pso(hr, pdesc, ppv); + } + let t0 = std::time::Instant::now(); + let _ = crate::pso_lib::take_lock_wait_us(); + let hr = unsafe { create_gfx_pso_sync(this, pdesc, num_ext, pext, riid, ppv) }; + note_sync_pso("graphics (CreateGraphicsPipelineState_X)", unsafe { crate::pso_async::sync_reason(pdesc, riid, false) }, t0, hr); + crate::cbv_copy::after_gfx_pso(hr, pdesc, ppv) +} + +pub(crate) unsafe fn replay_create(wrapper: *mut c_void, gfx: bool, desc: *const u8, riid: *const Guid, out: *mut usize) -> i32 { + let this = wrapper as *mut DeviceWrapper; + let ppv = out as *mut *mut c_void; + if gfx { + unsafe { create_gfx_pso_sync(this, desc, 0, core::ptr::null(), riid, ppv) } + } else { + unsafe { create_compute_pso_sync(this, desc, 0, core::ptr::null(), riid, ppv) } + } +} + +pub(crate) fn forget_pso(pso: usize) { + crate::frame_ev::lock(pso_registry()).remove(&pso); +} + +fn note_sync_pso(kind: &str, why: &str, t0: std::time::Instant, hr: i32) { + static N: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + let lock_ms = crate::pso_lib::take_lock_wait_us() as f64 / 1000.0; + if ms < 50.0 { + return; + } + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 40 || n % 100 == 0 { + let name = std::thread::current().name().map(str::to_owned).unwrap_or_else(|| format!("{:?}", std::thread::current().id())); + record("d3d12_xs", "pso_sync", &format!("#{} {kind} took {ms:.1} ms on {name} (sync because: {why}; of that {lock_ms:.1} ms waiting for the pipeline library lock) hr={hr:#010x}", n + 1)); } - unsafe { create_gfx_pso_sync(this, pdesc, num_ext, pext, riid, ppv) } } unsafe extern "system" fn create_gfx_pso_sync( @@ -866,6 +913,7 @@ unsafe extern "system" fn create_gfx_pso_sync( }; let ps_opts = if _pext.is_null() || _num_ext == 0 { None } else { crate::pso_ext::ps::options_in_entries(unsafe { core::slice::from_raw_parts(_pext, _num_ext as usize * crate::pso_ext::EXT_STRIDE) }, _num_ext as usize) }; let mut ps_origin: Option = None; + let mut edits: Vec<&'static str> = Vec::new(); let stages = [("VS", 0x08usize), ("PS", 0x18), ("DS", 0x28), ("HS", 0x38), ("GS", 0x48)]; let present = |o: usize| rd(&desc, o) != 0 && rd(&desc, o + 8) != 0; let feeder = if present(0x48) { 0x48 } else if present(0x28) { 0x28 } else { 0x08 }; @@ -891,12 +939,24 @@ unsafe extern "system" fn create_gfx_pso_sync( let code = if stage == "PS" { ps_origin = crate::pso_ext::ps::origin_from_blob(p, n, rtfmt, ps_opts.unwrap_or_default()); match (ps_opts, &ps_origin) { - (Some(_), Some(o)) => crate::pso_ext::ps::variant(o, crate::pso_ext::ps::depth_stencil_writes(&desc)).unwrap_or(code), + (Some(_), Some(o)) => match crate::pso_ext::ps::variant(o, crate::pso_ext::ps::depth_stencil_writes(&desc)) { + Some(v) => { + edits.push("ps:pso_ext_variant"); + v + } + None => code, + }, _ => code, } } else if stage == "VS" { let sems = unsafe { snorm10_semantics(&desc) }; - unsafe { crate::vs_snorm::variant(p, n, &sems) }.unwrap_or(code) + match unsafe { crate::vs_snorm::variant(p, n, &sems, &link(off)) } { + Some(v) => { + edits.push("vs:vs_snorm"); + v + } + None => code, + } } else { code }; @@ -976,8 +1036,18 @@ unsafe extern "system" fn create_gfx_pso_sync( unsafe { core::mem::transmute(*real_vtbl(real).add(10)) }; unsafe { crate::cl2_state::patch_gfx_pso_desc(real, &mut desc) }; let t0 = std::time::Instant::now(); - let hr = crate::perf::timed(crate::perf::PSO, || unsafe { crate::pso_ext::create(real, &desc, _num_ext, _pext, riid, ppv).unwrap_or_else(|| f(real, desc.as_ptr(), riid, ppv)) }); + let mut via_ext = false; + let hr = crate::perf::timed(crate::perf::PSO, || unsafe { + match crate::pso_ext::create(real, &desc, _num_ext, _pext, riid, ppv) { + Some(h) => { + via_ext = true; + h + } + None => crate::pso_lib::gfx(real, &desc, riid, ppv, &|d| f(real, d, riid, ppv)), + } + }); if hr >= 0 && !ppv.is_null() { + crate::hang_cap::note_origin(unsafe { *ppv } as usize, || format!("original edits=[{}] numExt={_num_ext} created_via={}", edits.join(","), if via_ext { "pso_ext::create (Xbox ext entries applied)" } else { "CreateGraphicsPipelineState(desc)" })); unsafe { crate::pso_ext::note(*ppv, _num_ext, _pext) }; crate::pso_ext::ps::note_pso(unsafe { *ppv }, ps_origin.clone()); } @@ -1119,6 +1189,16 @@ unsafe fn own_semantic_names(layout: &mut [u8]) -> Vec> { names } +pub(crate) fn pso_record_bytes(pso: usize) -> Option<(Vec, Vec, Vec, Vec, Vec>)> { + let rec = crate::frame_ev::lock(pso_registry()).get(&pso).cloned()?; + let rd = |o: usize| u64::from_le_bytes(rec.desc[o..o + 8].try_into().unwrap()); + let blob = |o: usize| { + let (p, n) = (rd(o) as *const u8, rd(o + 8) as usize); + if p.is_null() || n == 0 || n > 0x100_0000 { Vec::new() } else { unsafe { core::slice::from_raw_parts(p, n).to_vec() } } + }; + Some((rec.desc.clone(), blob(0x08), blob(0x18), rec._layout.clone(), rec._names.clone())) +} + pub(crate) unsafe fn register_gfx_pso(pso: *mut c_void, desc: Vec, shaders: Vec>>) { unsafe { register_pso(pso, desc, shaders) } } @@ -1181,7 +1261,7 @@ pub fn pso_summary(pso: usize) -> Option<(usize, usize, String)> { // method table rather than installed on the wrapper, because the title also reaches the // real device directly (ID3D12DeviceChild::GetDevice on a resource or command list returns // it) and views created that way would otherwise go unrecorded. -static REAL_ORIG: [core::sync::atomic::AtomicUsize; 32] = [const { core::sync::atomic::AtomicUsize::new(0) }; 32]; +static REAL_ORIG: [core::sync::atomic::AtomicUsize; 40] = [const { core::sync::atomic::AtomicUsize::new(0) }; 40]; fn real_orig(slot: usize) -> usize { REAL_ORIG[slot].load(Ordering::Relaxed) } @@ -1192,19 +1272,41 @@ unsafe extern "system" fn real_create_root_signature(real: *mut c_void, mask: u3 let f: unsafe extern "system" fn(*mut c_void, u32, *const u8, usize, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(real_orig(16)) }; let stripped = unsafe { crate::rs_xbox::pc_blob_raw(blob, len) }; let (blob, len) = stripped.as_ref().map_or((blob, len), |b| (b.as_ptr(), b.len())); + let aliased = if blob.is_null() || len == 0 { None } else { crate::cbv_raw::alias_blob(unsafe { core::slice::from_raw_parts(blob, len) }).ok().flatten() }; + let (blob, len) = aliased.as_ref().map_or((blob, len), |b| (b.as_ptr(), b.len())); + let copy = |b: *const u8, l: usize| if b.is_null() || l == 0 { Vec::new() } else { unsafe { core::slice::from_raw_parts(b, l) }.to_vec() }; + let sent = core::cell::RefCell::new(Vec::::new()); let mut gds = unsafe { crate::gds::patch_root_signature(blob, len) }; let (gb, gl) = gds.as_ref().map_or((blob, len), |(b, _)| (b.as_ptr(), b.len())); - let cen = unsafe { crate::centroid_bind::create(gb, gl, &|b, l| f(real, mask, b, l, riid, ppv), ppv) }; + let cen = unsafe { + crate::centroid_bind::create(gb, gl, &|b, l| { + *sent.borrow_mut() = copy(b, l); + f(real, mask, b, l, riid, ppv) + }, ppv) + }; let mut hr = match (&cen, &gds) { (Some(hr), _) => *hr, - (None, Some((b, _))) => unsafe { f(real, mask, b.as_ptr(), b.len(), riid, ppv) }, - (None, None) => unsafe { f(real, mask, blob, len, riid, ppv) }, + (None, Some((b, _))) => { + *sent.borrow_mut() = b.clone(); + unsafe { f(real, mask, b.as_ptr(), b.len(), riid, ppv) } + } + (None, None) => { + *sent.borrow_mut() = copy(blob, len); + unsafe { f(real, mask, blob, len, riid, ppv) } + } }; if hr < 0 && gds.is_some() { record("d3d12_xs", "gds", &format!("root signature with the GDS parameter rejected hr={hr:#010x}; created without GDS")); gds = None; + *sent.borrow_mut() = copy(blob, len); hr = unsafe { f(real, mask, blob, len, riid, ppv) }; } + if hr >= 0 && !ppv.is_null() && unsafe { !(*ppv).is_null() } { + let s = sent.borrow(); + if !s.is_empty() { + crate::pso_lib::note_real_root(unsafe { *ppv } as usize, &s); + } + } if hr >= 0 && !ppv.is_null() { if let Some((_, idx)) = gds { crate::gds::note_root_signature(unsafe { *ppv }, idx) } if cen.is_none() { crate::centroid_bind::forget(unsafe { *ppv }) } @@ -1281,6 +1383,16 @@ unsafe extern "system" fn real_copy_descriptors_simple(real: *mut c_void, n: u32 let f: unsafe extern "system" fn(*mut c_void, u32, usize, usize, u32) = unsafe { core::mem::transmute(real_orig(24)) }; unsafe { f(real, n, dest, src, heap_type) } } +unsafe extern "system" fn real_make_resident(real: *mut c_void, n: u32, objs: *const *mut c_void) -> i32 { + unsafe { crate::hang_cap::note_residency(false, n, objs) }; + let f: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) -> i32 = unsafe { core::mem::transmute(real_orig(34)) }; + unsafe { f(real, n, objs) } +} +unsafe extern "system" fn real_evict(real: *mut c_void, n: u32, objs: *const *mut c_void) -> i32 { + unsafe { crate::hang_cap::note_residency(true, n, objs) }; + let f: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) -> i32 = unsafe { core::mem::transmute(real_orig(35)) }; + unsafe { f(real, n, objs) } +} /// Patch the real device's method table (shared by every interface version of the device). unsafe fn patch_real_device(real: *mut c_void) { extern "system" { @@ -1299,20 +1411,37 @@ unsafe fn patch_real_device(real: *mut c_void) { record("d3d12_xs", "bindtrace", "could not unprotect the device method table - descriptor trace disabled"); return; } + let full = crate::rtcap::enabled(); for (slot, f) in hooks { + if slot == 16 && !full { + continue; + } REAL_ORIG[slot].store(*vt.add(slot), Ordering::Relaxed); *vt.add(slot) = f; } let mut tmp = 0u32; VirtualProtect(vt.add(16) as *mut c_void, 9 * 8, old, &mut tmp); record("d3d12_xs", "bindtrace", "descriptor hooks installed on the real device method table"); + if crate::hang_cap::on() { + let mut old2 = 0u32; + if VirtualProtect(vt.add(34) as *mut c_void, 2 * 8, 0x04, &mut old2) != 0 { + for (slot, f) in [(34usize, real_make_resident as usize), (35, real_evict as usize)] { + REAL_ORIG[slot].store(*vt.add(slot), Ordering::Relaxed); + *vt.add(slot) = f; + } + VirtualProtect(vt.add(34) as *mut c_void, 2 * 8, old2, &mut tmp); + record("d3d12_xs", "hang_cap", "MakeResident/Evict hooks installed on the real device method table"); + } + } }); } unsafe extern "system" fn create_rtv_traced(this: *mut DeviceWrapper, res: *mut c_void, pdesc: *const u8, dest: usize) { let real = unsafe { (*this).real }; let inc: unsafe extern "system" fn(*mut c_void, u32) -> u32 = unsafe { core::mem::transmute(*real_vtbl(real).add(15)) }; + crate::firstuse::note(res as usize, crate::firstuse::RTV); crate::rtcap::note_view(dest, res as usize, unsafe { inc(real, 2) } as usize); + unsafe { crate::blendclamp::note_rtv(dest, res as usize, pdesc) }; unsafe { crate::rtcap::register_view_target(res, 4) }; crate::replay::note_view(dest, 'r', res as usize, if pdesc.is_null() { None } else { Some(unsafe { core::slice::from_raw_parts(pdesc, 24) }) }); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const u8, usize) = unsafe { core::mem::transmute(*real_vtbl(real).add(20)) }; @@ -1320,6 +1449,7 @@ unsafe extern "system" fn create_rtv_traced(this: *mut DeviceWrapper, res: *mut } unsafe extern "system" fn create_dsv_traced(this: *mut DeviceWrapper, res: *mut c_void, pdesc: *const u8, dest: usize) { let real = unsafe { (*this).real }; + crate::firstuse::note(res as usize, crate::firstuse::DSV); crate::rtcap::note_view(dest, res as usize, 0); unsafe { crate::rtcap::register_view_target(res, 0x10) }; crate::replay::note_view(dest, 'd', res as usize, if pdesc.is_null() { None } else { Some(unsafe { core::slice::from_raw_parts(pdesc, 24) }) }); @@ -1338,6 +1468,17 @@ unsafe extern "system" fn create_derived_pso_x( riid: *const Guid, ppv: *mut *mut c_void, ) -> i32 { let _ev = crate::frame_ev::begin(crate::frame_ev::PSO_SYNC); + let t0 = std::time::Instant::now(); + let _ = crate::pso_lib::take_lock_wait_us(); + let hr = unsafe { create_derived_pso_inner(this, base, num, patches, riid, ppv) }; + note_sync_pso("derived graphics (CreateDerivedPipelineState_X)", "derived PSOs are always created on the calling thread", t0, hr); + hr +} + +unsafe fn create_derived_pso_inner( + this: *mut DeviceWrapper, base: *mut c_void, num: u32, patches: *const u8, + riid: *const Guid, ppv: *mut *mut c_void, +) -> i32 { const E_FAIL: i32 = 0x8000_4005u32 as i32; const STRIDE: usize = 0x14C; static OK: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); @@ -1413,8 +1554,18 @@ unsafe extern "system" fn create_derived_pso_x( let f: unsafe extern "system" fn(*mut c_void, *const u8, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(*real_vtbl(real).add(10)) }; let ext_ptr = ds_ext.as_ref().map_or(core::ptr::null(), |e| e.as_ptr()); - let hr = unsafe { crate::pso_ext::create(real, &desc, ds_ext.is_some() as u32, ext_ptr, riid, ppv).unwrap_or_else(|| f(real, desc.as_ptr(), riid, ppv)) }; + let mut via_ext = false; + let hr = unsafe { + match crate::pso_ext::create(real, &desc, ds_ext.is_some() as u32, ext_ptr, riid, ppv) { + Some(h) => { + via_ext = true; + h + } + None => crate::pso_lib::gfx(real, &desc, riid, ppv, &|d| f(real, d, riid, ppv)), + } + }; if hr >= 0 && !ppv.is_null() { + crate::hang_cap::note_origin(unsafe { *ppv } as usize, || format!("derived from base {base:p} patch tags [{}] ds_ext={} created_via={}", tags.trim(), ds_ext.is_some(), if via_ext { "pso_ext::create" } else { "CreateGraphicsPipelineState(desc)" })); unsafe { crate::pso_ext::note(*ppv, ds_ext.is_some() as u32, ext_ptr) }; crate::pso_ext::ps::note_pso(unsafe { *ppv }, ps_origin.clone()); } @@ -1476,6 +1627,29 @@ pub fn wrap_root_signature(rts: &[u8]) -> Vec { static ROOT_FROM_SHADER: std::sync::Mutex>> = std::sync::Mutex::new(None); +pub(crate) fn shader_root_container(rts: &[u8], raw: bool) -> Vec { + let console = wrap_root_signature(rts); + let container = crate::rs_xbox::pc_blob(&console).unwrap_or(console); + if !raw { + return match crate::cbv_raw::copy_mode_blob(&container) { + Ok(Some(b)) => b, + Ok(None) => container, + Err(e) => { + record("d3d12_xs", "PSO.rootFromShader", &format!("bindless alias failed ({e}); root signature left as the shader gives it")); + container + } + }; + } + match crate::cbv_raw::patch_blob(&container) { + Ok(Some((b, _))) => b, + Ok(None) => container, + Err(e) => { + record("d3d12_xs", "PSO.rootFromShader", &format!("cbv_raw patch failed ({e}); root signature left as the shader gives it")); + container + } + } +} + unsafe fn root_from_shaders(real: *mut c_void, desc: &[u8], stages: &[usize]) -> usize { static N: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); for &o in stages { @@ -1495,8 +1669,7 @@ unsafe fn root_from_shaders(real: *mut c_void, desc: &[u8], stages: &[usize]) -> let f: unsafe extern "system" fn(*mut c_void, u32, *const u8, usize, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(*real_vtbl(real).add(16)) }; let mut rs: *mut c_void = core::ptr::null_mut(); - let console = wrap_root_signature(rts); - let container = crate::rs_xbox::pc_blob(&console).unwrap_or(console); + let container = shader_root_container(rts, crate::cbv_raw::enabled()); let hr = unsafe { f(real, 0, container.as_ptr(), container.len(), &IID_ROOT_SIGNATURE, &mut rs) }; if N.fetch_add(1, Ordering::Relaxed) < 6 { record("d3d12_xs", "PSO.rootFromShader", &format!("null pRootSignature; built root signature from the shader's RTS0 part ({} bytes, header {:x?}) -> hr={hr:#010x}", rts.len(), rts.chunks_exact(4).take(6).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect::>())); @@ -1504,6 +1677,7 @@ unsafe fn root_from_shaders(real: *mut c_void, desc: &[u8], stages: &[usize]) -> let _ = std::fs::write(std::env::temp_dir().join("tombox").join("psodump").join(format!("rts0_{key:016x}.bin")), rts); } if hr >= 0 && !rs.is_null() { + crate::pso_lib::note_root(rs as usize, 0, &container, true); m.insert(key, rs as usize); return rs as usize; } @@ -1537,14 +1711,19 @@ unsafe extern "system" fn create_compute_pso_x( this: *mut DeviceWrapper, pdesc: *const u8, num_ext: u32, pext: *const u8, riid: *const Guid, ppv: *mut *mut c_void, ) -> i32 { + unsafe { crate::pso_xrec::note(crate::pso_xrec::CS, pdesc, num_ext) }; let mut ev = crate::frame_ev::begin(crate::frame_ev::PSO_SYNC); if let Some(hr) = unsafe { crate::pso_async::create_compute(this, (*this).real, pdesc, num_ext, pext, riid, ppv, create_compute_pso_sync) } { if let Some(s) = ev.as_mut() { s.set_kind(if crate::frame_ev::take_async_mark() { crate::frame_ev::PSO_ASYNC } else { crate::frame_ev::PSO_INLINE }); } - return hr; + return crate::cbv_copy::after_compute_pso(hr, pdesc, ppv); } - unsafe { create_compute_pso_sync(this, pdesc, num_ext, pext, riid, ppv) } + let t0 = std::time::Instant::now(); + let _ = crate::pso_lib::take_lock_wait_us(); + let hr = unsafe { create_compute_pso_sync(this, pdesc, num_ext, pext, riid, ppv) }; + note_sync_pso("compute (CreateComputePipelineState_X)", unsafe { crate::pso_async::sync_reason(pdesc, riid, true) }, t0, hr); + crate::cbv_copy::after_compute_pso(hr, pdesc, ppv) } unsafe extern "system" fn create_compute_pso_sync( @@ -1580,7 +1759,7 @@ unsafe extern "system" fn create_compute_pso_sync( desc[16..24].copy_from_slice(&(code.len() as u64).to_le_bytes()); let f: unsafe extern "system" fn(*mut c_void, *const u8, *const Guid, *mut *mut c_void) -> i32 = unsafe { core::mem::transmute(*real_vtbl(real).add(11)) }; // PC CreateComputePipelineState - let hr = unsafe { f(real, desc.as_ptr(), riid, ppv) }; + let hr = unsafe { crate::pso_lib::compute(real, &desc, riid, ppv, &|d| f(real, d, riid, ppv)) }; if hr == 0 && !ppv.is_null() && crate::rtcap::enabled() { crate::rtcap::note_compute_pso(unsafe { *ppv } as usize, code.as_ptr() as usize); } @@ -1663,6 +1842,9 @@ unsafe extern "system" fn create_heap( } }; let hr = unsafe { f(real, d.as_ptr(), riid, ppv) }; + if hr >= 0 && !ppv.is_null() { + unsafe { crate::title_gpu::heap(*ppv, size) }; + } let note = format!(" | pc size={:#x} align={:#x} flags={:#x}", u64at(&d, 0), u64at(&d, 0x20), u32at(&d, 0x28)); if hr >= 0 && crate::rtcap::enabled() && !ppv.is_null() { crate::bindtrace::note_heap_type(unsafe { *ppv } as usize, htype); @@ -1789,7 +1971,7 @@ unsafe extern "system" fn create_placed_resource_x( }; static N: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); - if hr < 0 || n < 12 { + if hr < 0 || n < 12 || (crate::passcap::tables_on() && n < 20000) { let how = match &made { Some(m) => format!("aliased {:?} heap {:#x}+{:#x}", m.kind, m.heap, m.offset), None => "separate committed resource".to_string(), @@ -1805,6 +1987,10 @@ unsafe extern "system" fn create_placed_resource_x( let addref: unsafe extern "system" fn(*mut c_void) -> u32 = unsafe { core::mem::transmute(*real_vtbl(res).add(1)) }; unsafe { addref(res) }; unsafe { crate::gpu_va::note_resource(real, res, &d, init_state, Some(va)) }; + if crate::va_census::on() { + crate::va_census::set_len(res as usize, xbox_size); + crate::va_census::note_how(res as usize, match &made { Some(m) => format!("CreatePlacedResourceX aliased {:?} heap {:#x}+{:#x}", m.kind, m.heap, m.offset), None => "CreatePlacedResourceX separate committed".to_string() }); + } crate::placed::register(res, crate::placed::Placed { va, desc: orig, init_state }); crate::res3d::note_create(res, &orig, &format!("placedX va={va:#x} {}", match &made { Some(m) => format!("aliased {:?} heap {:#x}+{:#x}", m.kind, m.heap, m.offset), None => "separate committed".to_string() })); if flags & 0x7 != 0 { @@ -1943,7 +2129,7 @@ pub(crate) fn vtable() -> *const usize { v[75] = crate::device_x::unregister_page_pool_x as usize; v[87] = crate::device_x::device87_release_x as usize; crate::device_ext_a::install(&mut v); - if crate::rtcap::enabled() { + if crate::rtcap::enabled() || crate::passcap::on() || crate::blendclamp::lazy() { v[20] = create_rtv_traced as usize; v[21] = create_dsv_traced as usize; } @@ -1958,17 +2144,23 @@ pub(crate) fn vtable() -> *const usize { crate::depth_uav::hook_device(&mut v); crate::ecl_probe::install_device(&mut v); crate::cbv_raw::hook_device(&mut v); + crate::pso_lib::hook_device(&mut v); Box::leak(v.into_boxed_slice()).as_ptr() as usize }) as *const usize } /// Wrap a real `ID3D12Device` so we can intercept QueryInterface. pub fn wrap_device(real: *mut c_void) -> *mut c_void { - if crate::rtcap::enabled() && !real.is_null() { + if !real.is_null() { + unsafe { crate::shader_xlat::probe_typed_atomic64(real) }; + crate::blend_probe::note_device(real); + } + if (crate::rtcap::enabled() || crate::passcap::tables_on()) && !real.is_null() { unsafe { patch_real_device(real) }; } let w = Box::new(DeviceWrapper { vtable: vtable(), real, refs: AtomicU32::new(1) }); let p = Box::into_raw(w) as *mut c_void; + crate::pso_lib::warm(real, p); WRAPPED.lock().unwrap_or_else(|e| e.into_inner()).push((real as usize, p as usize)); p } @@ -1988,3 +2180,19 @@ pub(crate) fn wrapper_qi(real: *mut c_void, riid: *const Guid, ppv: *mut *mut c_ fn unregister_wrapper(w: usize) { WRAPPED.lock().unwrap_or_else(|e| e.into_inner()).retain(|e| e.1 != w); } + +#[cfg(test)] +mod xsx_device8_tests { + use super::*; + + #[test] + fn qi_answers_the_scarlett_device8_iid_with_the_wrapper() { + let mut w = DeviceWrapper { vtable: core::ptr::null(), real: core::ptr::null_mut(), refs: AtomicU32::new(1) }; + let mut out: *mut c_void = core::ptr::null_mut(); + let hr = unsafe { qi(&mut w, &IID_XSX_DEVICE8, &mut out) }; + assert_eq!(hr, S_OK); + assert_eq!(out, &mut w as *mut DeviceWrapper as *mut c_void); + assert_eq!(w.refs.load(Ordering::SeqCst), 2); + assert_eq!(guid_str(&IID_XSX_DEVICE8), "{728f1fa2-ea11-4a9f-9b52-9b42a484d5c9}"); + } +} diff --git a/crates/compat/d3d12_xs/src/dred.rs b/crates/compat/d3d12_xs/src/dred.rs index 19f886be..1a0fc067 100644 --- a/crates/compat/d3d12_xs/src/dred.rs +++ b/crates/compat/d3d12_xs/src/dred.rs @@ -49,18 +49,51 @@ pub fn requested() -> bool { static DEVICE: AtomicUsize = AtomicUsize::new(0); static DRED: AtomicUsize = AtomicUsize::new(0); static REPORTED: AtomicBool = AtomicBool::new(false); +static REMOVED: AtomicBool = AtomicBool::new(false); pub fn is_removal(hr: i32) -> bool { matches!(hr as u32, 0x887A_0005 | 0x887A_0006 | 0x887A_0007 | 0x887A_0020) } +#[cfg(test)] +thread_local! { + static T_REMOVED: core::cell::Cell = const { core::cell::Cell::new(false) }; +} + +#[cfg(not(test))] +pub fn removed() -> bool { + REMOVED.load(Ordering::Acquire) +} + +#[cfg(test)] +pub fn removed() -> bool { + T_REMOVED.with(|c| c.get()) +} + +#[cfg(not(test))] +pub fn mark_removed() { + REMOVED.store(true, Ordering::Release); +} + +#[cfg(test)] +pub fn mark_removed() { + T_REMOVED.with(|c| c.set(true)); +} + +#[cfg(test)] +pub fn clear_removed_for_test() { + T_REMOVED.with(|c| c.set(false)); +} + pub fn on_failure(hr: i32, site: &str) { if is_removal(hr) { + mark_removed(); report_once(site, Some(hr)); } } pub fn report_once(site: &str, hr: Option) -> bool { + mark_removed(); let dev = DEVICE.load(Ordering::Acquire) as *mut c_void; if dev.is_null() || REPORTED.swap(true, Ordering::AcqRel) { return false; @@ -69,9 +102,53 @@ pub fn report_once(site: &str, hr: Option) -> bool { record(M, "dred.removed", &format!("first device-removal sign: {site}{what}")); unsafe { report(dev, DRED.load(Ordering::Acquire) as *mut c_void) }; crate::hang_cap::dump_on_removal(); + schedule_exit(hr); true } +extern "system" { + fn ExitProcess(code: u32) -> !; +} + +pub fn exit_delay_ms(v: Option<&str>) -> Option { + match v.map(str::trim) { + None | Some("") => Some(3000), + Some("off") | Some("0") => None, + Some(s) => s.parse().ok().or(Some(3000)), + } +} + +pub fn exit_code(hr: Option) -> u32 { + hr.filter(|h| is_removal(*h)).map_or(0x887A_0006, |h| h as u32) +} + +#[cfg(test)] +static TEST_EXIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +fn schedule_exit(hr: Option) { + let Some(ms) = exit_delay_ms(std::env::var("TOMBOX_REMOVED_EXIT_MS").ok().as_deref()) else { return }; + let code = exit_code(hr); + #[cfg(test)] + { + let _ = ms; + TEST_EXIT.store(code, Ordering::Release); + record(M, "dred.removed", &format!("test build: would exit with code {code:#010x}; the test process keeps running")); + } + #[cfg(not(test))] + exit_after(ms, code); +} + +#[cfg(not(test))] +fn exit_after(ms: u64, code: u32) { + let log = std::env::var("TOMBOX_LOG").unwrap_or_else(|_| "tombox_compat.log".into()); + record(M, "dred.removed", &format!("the GPU device is lost ({}); the process exits with code {code:#010x} in {ms} ms instead of letting the title run on a dead device. DRED summary: dred.* lines in {log}; hang captures in {}", removed_reason_name(code as i32), crate::hang_cap::dump_dir().display())); + let _ = std::thread::Builder::new().name("tombox-removed-exit".into()).spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(ms)); + record(M, "dred.removed", &format!("exiting now with code {code:#010x} (device removed)")); + unsafe { ExitProcess(code) } + }); +} + unsafe fn slot(obj: *mut c_void, i: usize) -> usize { *(*(obj as *const *const usize)).add(i) } @@ -437,6 +514,28 @@ pub unsafe fn format_page_fault(pf: *const u8) -> Vec { mod tests { use super::*; + #[test] + fn removed_exit_delay_and_code() { + assert_eq!(exit_delay_ms(None), Some(3000)); + assert_eq!(exit_delay_ms(Some("off")), None); + assert_eq!(exit_delay_ms(Some("0")), None); + assert_eq!(exit_delay_ms(Some("750")), Some(750)); + assert_eq!(exit_code(Some(0x887A_0006u32 as i32)), 0x887A_0006); + assert_eq!(exit_code(Some(0x887A_0005u32 as i32)), 0x887A_0005); + assert_eq!(exit_code(None), 0x887A_0006); + assert_eq!(exit_code(Some(0x8007_0057u32 as i32)), 0x887A_0006); + } + + #[test] + fn removed_flag_is_set_by_a_removal_failure_only() { + clear_removed_for_test(); + on_failure(0x8007_0057u32 as i32, "test"); + assert!(!removed()); + on_failure(0x887A_0006u32 as i32, "test"); + assert!(removed()); + clear_removed_for_test(); + } + #[repr(C)] struct Node { la: *const u8, @@ -576,8 +675,11 @@ mod tests { #[test] fn report_is_one_shot_and_needs_an_armed_device() { - let _ = report_once("test", None); + let first = report_once("test", None); assert!(!report_once("test", None)); + if first { + assert_eq!(TEST_EXIT.load(Ordering::Acquire), 0x887A_0006, "a report arms the exit, which a test build records instead of exiting"); + } } #[test] diff --git a/crates/compat/d3d12_xs/src/dred_marks.rs b/crates/compat/d3d12_xs/src/dred_marks.rs index fe9d5000..e02df51d 100644 --- a/crates/compat/d3d12_xs/src/dred_marks.rs +++ b/crates/compat/d3d12_xs/src/dred_marks.rs @@ -180,7 +180,7 @@ pub unsafe fn mark(list: *mut c_void, pso: *mut c_void) { let t = text(pso as usize, entry); let w: Vec = t.encode_utf16().chain(Some(0)).collect(); note_marker(list as usize, t); - let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, u32) = unsafe { core::mem::transmute(vslot(list, PC_SET_MARKER)) }; + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, u32) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_SET_MARKER)) }; unsafe { f(list, 0, w.as_ptr() as *const c_void, (w.len() * 2) as u32) }; MARKS.fetch_add(1, Ordering::Relaxed); } diff --git a/crates/compat/d3d12_xs/src/fill.rs b/crates/compat/d3d12_xs/src/fill.rs index 8b23a3cc..e542ab6e 100644 --- a/crates/compat/d3d12_xs/src/fill.rs +++ b/crates/compat/d3d12_xs/src/fill.rs @@ -139,6 +139,7 @@ unsafe fn pattern(dev: *mut c_void, pat: &[u8; 16], need: u64) -> Option } unsafe fn barrier(list: *mut c_void, b: &[u8; 32]) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::BARRIER) }; let f: unsafe extern "system" fn(*mut c_void, u32, *const u8) = unsafe { core::mem::transmute(*vt(list).add(26)) }; unsafe { f(list, 1, b.as_ptr()) }; } @@ -175,6 +176,7 @@ pub unsafe fn fill(list: *mut c_void, copy_list: bool, va: u64, size: u32, value } pub unsafe fn fill_pattern(list: *mut c_void, copy_list: bool, va: u64, size: u64, pat: &[u8; 16], flags: u32) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::COPY) }; let value = u32::from_le_bytes([pat[0], pat[1], pat[2], pat[3]]); static LOG: AtomicUsize = AtomicUsize::new(0); static MISS: AtomicUsize = AtomicUsize::new(0); diff --git a/crates/compat/d3d12_xs/src/firstuse.rs b/crates/compat/d3d12_xs/src/firstuse.rs new file mode 100644 index 00000000..84ff864f --- /dev/null +++ b/crates/compat/d3d12_xs/src/firstuse.rs @@ -0,0 +1,180 @@ +use core::sync::atomic::{AtomicU64, Ordering}; +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; +use compat_common::record; + +pub const CREATE: u8 = 0; +pub const UPLOAD: u8 = 1; +pub const DETILE: u8 = 2; +pub const SRV: u8 = 3; +pub const UAV: u8 = 4; +pub const RTV: u8 = 5; +pub const DSV: u8 = 6; +const KINDS: usize = 7; +const NAMES: [&str; KINDS] = ["create", "upload", "detile", "srv", "uav", "rtv", "dsv"]; +const MAX_LINES: u64 = 4000; +const MAX_FRAME_LINES: u64 = 20000; + +static PRESENT: AtomicU64 = AtomicU64::new(0); +static START: OnceLock = OnceLock::new(); + +#[derive(Default)] +struct S { + first: HashMap, + frame: [u64; KINDS], + bytes: [u64; KINDS], + top: Vec<(u64, usize, u8)>, + lines: u64, + frame_lines: u64, +} + +static ST: Mutex> = Mutex::new(None); + +fn with(f: impl FnOnce(&mut S) -> R) -> R { + let mut g = ST.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(S::default)) +} + +pub fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("TOMBOX_FIRSTUSE").map(|v| v.trim() == "1").unwrap_or(false)) +} + +pub fn kind_name(k: u8) -> &'static str { + NAMES.get(k as usize).copied().unwrap_or("?") +} + +fn t_ms() -> f64 { + START.get().map_or(0.0, |s| s.elapsed().as_secs_f64() * 1000.0) +} + +pub fn present() -> u64 { + PRESENT.load(Ordering::Relaxed) +} + +pub fn on_present() { + if !on() { + return; + } + START.get_or_init(Instant::now); + let p = PRESENT.fetch_add(1, Ordering::Relaxed); + let inj = crate::inject::take(); + let line = with(|s| { + let f = core::mem::take(&mut s.frame); + let b = core::mem::take(&mut s.bytes); + let top = core::mem::take(&mut s.top); + if (f.iter().all(|&n| n == 0) && inj.iter().all(|&n| n == 0)) || s.frame_lines >= MAX_FRAME_LINES { + return None; + } + s.frame_lines += 1; + Some((f, b, top)) + }); + if let Some((f, b, top)) = line { + record("d3d12_xs", "firstuse", &format!("frame present #{p} t={:.0} ms: first uses {}{}{} | injected {}", t_ms(), summary(&f), bytes_text(&b), top_text(&top), crate::inject::summary(&inj))); + } +} + +pub fn bytes_text(b: &[u64; KINDS]) -> String { + let v: Vec = b.iter().enumerate().filter(|(_, n)| **n > 0).map(|(k, n)| format!("{} {:.2} MiB", NAMES[k], *n as f64 / 1048576.0)).collect(); + if v.is_empty() { String::new() } else { format!(" | bytes {}", v.join(", ")) } +} + +pub fn top_text(top: &[(u64, usize, u8)]) -> String { + let v: Vec = top.iter().map(|(b, r, k)| format!("{r:#x} {} {:.2} MiB", kind_name(*k), *b as f64 / 1048576.0)).collect(); + if v.is_empty() { String::new() } else { format!(" | top {}", v.join(", ")) } +} + +fn push_top(top: &mut Vec<(u64, usize, u8)>, e: (u64, usize, u8)) { + top.push(e); + top.sort_by(|a, b| b.0.cmp(&a.0)); + top.truncate(5); +} + +pub fn note_bytes(res: usize, kind: u8, bytes: u64) { + if !on() || res == 0 || kind as usize >= KINDS { + return; + } + with(|s| { + s.bytes[kind as usize] += bytes; + push_top(&mut s.top, (bytes, res, kind)); + }); + note(res, kind); +} + +pub fn summary(f: &[u64; KINDS]) -> String { + let v: Vec = f.iter().enumerate().filter(|(_, n)| **n > 0).map(|(k, n)| format!("{} {n}", NAMES[k])).collect(); + v.join(", ") +} + +pub fn note(res: usize, kind: u8) { + if !on() || res == 0 || kind as usize >= KINDS { + return; + } + let p = present() + 1; + let log = with(|s| { + let e = s.first.entry(res).or_insert([0; KINDS]); + if kind == CREATE { + *e = [0; KINDS]; + } + if e[kind as usize] != 0 { + return false; + } + e[kind as usize] = p; + s.frame[kind as usize] += 1; + if s.lines < MAX_LINES { + s.lines += 1; + return true; + } + false + }); + if log { + record("d3d12_xs", "firstuse", &format!("res {res:#x} first {} in frame #{p} t={:.0} ms", kind_name(kind), t_ms())); + } +} + +pub fn describe_at(e: &[u64; KINDS], now: u64) -> String { + let v: Vec = e.iter().enumerate().filter(|(_, p)| **p != 0) + .map(|(k, p)| format!("{} #{p}{}", NAMES[k], if *p == now { " (THIS FRAME)" } else { "" })).collect(); + if v.is_empty() { " first-use: none recorded".to_string() } else { format!(" first-use: {}", v.join(", ")) } +} + +pub fn describe(res: usize) -> String { + if !on() || res == 0 { + return String::new(); + } + let now = present() + 1; + match with(|s| s.first.get(&res).copied()) { + Some(e) => describe_at(&e, now), + None => " first-use: none recorded".to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn describe_marks_this_frame_and_summary_skips_zero_kinds() { + let mut e = [0u64; KINDS]; + e[CREATE as usize] = 3; + e[UPLOAD as usize] = 9; + e[SRV as usize] = 4; + assert_eq!(describe_at(&e, 9), " first-use: create #3, upload #9 (THIS FRAME), srv #4"); + assert_eq!(describe_at(&[0; KINDS], 1), " first-use: none recorded"); + let mut f = [0u64; KINDS]; + f[DETILE as usize] = 2; + f[RTV as usize] = 1; + assert_eq!(summary(&f), "detile 2, rtv 1"); + let mut b = [0u64; KINDS]; + b[UPLOAD as usize] = 3 * 1048576; + assert_eq!(bytes_text(&b), " | bytes upload 3.00 MiB"); + let mut top = Vec::new(); + for i in 0..7u64 { + push_top(&mut top, (i * 1048576, i as usize + 1, UPLOAD)); + } + assert_eq!(top.len(), 5); + assert_eq!(top[0], (6 * 1048576, 7, UPLOAD)); + assert!(top_text(&top[..1]).starts_with(" | top 0x7 upload 6.00 MiB")); + } +} diff --git a/crates/compat/d3d12_xs/src/fmask_check.rs b/crates/compat/d3d12_xs/src/fmask_check.rs new file mode 100644 index 00000000..1b441713 --- /dev/null +++ b/crates/compat/d3d12_xs/src/fmask_check.rs @@ -0,0 +1,124 @@ +use crate::record; +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; + +pub const FMASK_MAP: u32 = 0x1920; +pub const FMASK_SEL: u32 = 4; + +#[derive(Default)] +struct S { + shaders: HashMap>, + views: HashMap>, + checks: HashMap, + xlat: HashMap, + reported: HashSet<(u64, bool)>, + pso_hash: HashMap, +} + +static ARMED: AtomicBool = AtomicBool::new(false); +static NO_TRACE: AtomicBool = AtomicBool::new(false); +static ST: Mutex> = Mutex::new(None); + +fn with(f: impl FnOnce(&mut S) -> R) -> R { + f(ST.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(S::default)) +} + +pub fn armed() -> bool { + ARMED.load(Ordering::Relaxed) +} + +pub fn note_translation(hash: u64, hlsl: &str, pairs: &[(u32, u32, u32)]) { + let ms = hlsl.contains("Texture2DMS<"); + let ident = hlsl.contains("0x88888810u"); + with(|s| s.xlat.insert(hash, (ms, ident, pairs.len()))); + note_shader(hash, pairs); +} + +pub fn translation_text(hash: u64) -> String { + let gate = tombox_xshader::hlsl::msaa_dim_on(); + match with(|s| s.xlat.get(&hash).copied()) { + Some((ms, ident, n)) => format!("translated live in this process (TOMBOX_XS_MSAA_DIM={}, so xlat_index is bypassed): Texture2DMS declared={ms}, identity FMASK emitted={ident}, FMASK pairs={n}", gate as u8), + None => format!("NOT translated live in this process: served from the shader pack/xlat_index or translated before tracking (TOMBOX_XS_MSAA_DIM={})", gate as u8), + } +} + +pub fn note_shader(hash: u64, pairs: &[(u32, u32, u32)]) { + if pairs.is_empty() { + return; + } + with(|s| s.shaders.insert(hash, pairs.to_vec())); + ARMED.store(true, Ordering::Relaxed); + if !crate::rtcap::enabled() && !NO_TRACE.swap(true, Ordering::Relaxed) { + record("d3d12_xs", "fmask_check", &format!("shader {hash:016x} reads FMASK through the layout rule (table param, FMASK index, MS index) {pairs:?}; the bind-time descriptor cross-check needs TOMBOX_RTCAP=1 descriptor tracking and is NOT verified in this run")); + } +} + +pub fn note_view(res: usize, map: u32, sel: u32) { + if !tombox_xshader::hlsl::msaa_dim_on() { + return; + } + with(|s| { + if s.views.len() < 4096 { + s.views.entry(res).or_default().insert((map, sel)); + } + }); +} + +fn ps_hash(pso: usize) -> u64 { + let real = crate::pso_async::real_of(pso); + crate::device_wrap::pso_summary(pso) + .or_else(|| if real != 0 { crate::device_wrap::pso_summary(real) } else { None }) + .and_then(|(_, p, _)| if p == 0 { None } else { crate::shader_xlat::origin_hash(p) }) + .unwrap_or(0) +} + +pub fn verdict(fm: Option<(usize, u32, u32)>, ms: Option<(usize, u32, u32)>, sels: &HashSet<(u32, u32)>) -> Result { + let show = |e: Option<(usize, u32, u32)>| e.map(|(r, d, m)| format!("res {r:#x} dim={d} map={m:#x}")).unwrap_or_else(|| "no SRV recorded".into()); + let (Some((fr, fd, fmap)), Some((mr, md, _))) = (fm, ms) else { + return Err(format!("FMASK slot {} / MS slot {}", show(fm), show(ms))); + }; + let sel_ok = sels.contains(&(fmap, FMASK_SEL)); + if fr != 0 && fr == mr && md == 6 && fd == 6 && fmap == FMASK_MAP && sel_ok { + return Ok(format!("FMASK slot is a map {FMASK_MAP:#x} desc+0x34={FMASK_SEL} view of the bound MS resource {fr:#x}")); + } + Err(format!("FMASK slot {} (desc+0x34 values seen for that resource and map: {:?}) / MS slot {}; expected the same MS resource, dim 6, map {FMASK_MAP:#x}, desc+0x34={FMASK_SEL}", + show(fm), sels.iter().filter(|v| v.0 == fmap).map(|v| v.1).collect::>(), show(ms))) +} + +pub fn on_draw(list: usize, pso: usize) { + if pso == 0 { + return; + } + let known = with(|s| s.pso_hash.get(&pso).copied()); + let h = match known { + Some(h) => h, + None => { + let h = ps_hash(pso); + with(|s| s.pso_hash.insert(pso, h)); + h + } + }; + let Some(pairs) = with(|s| { + let p = s.shaders.get(&h)?.clone(); + let c = s.checks.entry(h).or_default(); + if *c >= 4 { + return None; + } + *c += 1; + Some(p) + }) else { return }; + for (param, fi, mi) in pairs { + let fm = crate::bindtrace::table_srv(list, false, param, fi); + let ms = crate::bindtrace::table_srv(list, false, param, mi); + let sels = with(|s| fm.and_then(|f| s.views.get(&f.0).cloned()).unwrap_or_default()); + let v = verdict(fm, ms, &sels); + let ok = v.is_ok(); + if with(|s| s.reported.insert((h, ok))) { + match v { + Ok(m) => record("d3d12_xs", "fmask_check", &format!("shader {h:016x} param {param} [{fi}] vs [{mi}]: OK, {m}")), + Err(m) => record("d3d12_xs", "fmask_check", &format!("MISMATCH shader {h:016x} param {param} [{fi}] vs [{mi}]: the layout rule reads [{fi}] as FMASK (identity) but {m}; see docs/BLOCKERS.md FMASK entry")), + } + } + } +} diff --git a/crates/compat/d3d12_xs/src/frame_csv.rs b/crates/compat/d3d12_xs/src/frame_csv.rs index 10160713..c60f2758 100644 --- a/crates/compat/d3d12_xs/src/frame_csv.rs +++ b/crates/compat/d3d12_xs/src/frame_csv.rs @@ -50,9 +50,29 @@ struct Csv { wait_ticks: i64, snap: [(u64, u64); 2], qpc_last: i64, + last_flush: i64, } unsafe impl Send for Csv {} +impl Csv { + fn wrote_row(&mut self, now: i64) { + self.rows += 1; + if self.rows % 240 == 0 || self.rows <= 2 || now - self.last_flush >= qpf() / 4 { + let _ = self.out.flush(); + self.last_flush = now; + } + } +} + +fn open_file(p: &std::path::Path) -> Result { + let f = std::fs::File::create(p).map_err(|e| format!("create {}: {e}", p.display()))?; + let mut out = std::io::BufWriter::with_capacity(64 * 1024, f); + let _ = writeln!(out, "frame,t_ms,present_interval_ms,present_cpu_ms,fence_wait_ms,gpu_frame_ms,gpu_present_list_us{}", crate::frame_ev::header()); + let _ = out.flush(); + let now = qpc(); + Ok(Csv { out, path: p.display().to_string(), qheap: 0, rb: 0, map: core::ptr::null(), freq: 0, pending: [Pending::default(); 2], last_gpu_start: 0, start_qpc: now, last_present: 0, rows: 0, wait_ticks: 0, snap: [(0, 0); 2], qpc_last: 0, last_flush: now }) +} + static CSV: Mutex> = Mutex::new(None); static FAILED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); @@ -63,9 +83,7 @@ fn path() -> std::path::PathBuf { unsafe fn open(device: usize, freq: u64) -> Result { let p = path(); - let f = std::fs::File::create(&p).map_err(|e| format!("create {}: {e}", p.display()))?; - let mut out = std::io::BufWriter::with_capacity(64 * 1024, f); - let _ = writeln!(out, "frame,t_ms,present_interval_ms,present_cpu_ms,fence_wait_ms,gpu_frame_ms,gpu_present_list_us{}", crate::frame_ev::header()); + let mut c = open_file(&p)?; let qd: [u32; 3] = [1, 4, 0]; let mut qheap = 0usize; let mut rb = 0usize; @@ -92,9 +110,9 @@ unsafe fn open(device: usize, freq: u64) -> Result { } } record("d3d12_xs", "[frame_csv]", &format!("writing {} (gpu timestamps {})", p.display(), if qheap != 0 { "on" } else { "off" })); - let now = qpc(); crate::frame_ev::set_active(true); - Ok(Csv { out, path: p.display().to_string(), qheap, rb, map, freq, pending: [Pending::default(); 2], last_gpu_start: 0, start_qpc: now, last_present: 0, rows: 0, wait_ticks: 0, snap: [(0, 0); 2], qpc_last: 0 }) + (c.qheap, c.rb, c.map, c.freq) = (qheap, rb, map, freq); + Ok(c) } pub fn on() -> bool { @@ -129,7 +147,7 @@ pub unsafe fn list_begin(device: *mut c_void, list: *mut c_void, frame: u64, fre } } let c = g.as_mut().unwrap(); - if c.qheap != 0 { + if c.qheap != 0 && !crate::dred::removed() { let slot = (frame % 2) as u32; let i = slot as usize; c.snap[i] = unsafe { (core::ptr::read_volatile(c.map.add(i * 2)), core::ptr::read_volatile(c.map.add(i * 2 + 1))) }; @@ -140,7 +158,7 @@ pub unsafe fn list_begin(device: *mut c_void, list: *mut c_void, frame: u64, fre pub unsafe fn list_end(list: *mut c_void, frame: u64) { let g = CSV.lock().unwrap(); let Some(c) = g.as_ref() else { return }; - if c.qheap != 0 { + if c.qheap != 0 && !crate::dred::removed() { let slot = (frame % 2) as u32; unsafe { vc!(list, 53, fn(usize, u32, u32) -> (), c.qheap, 2, slot * 2 + 1); @@ -157,6 +175,28 @@ pub fn add_wait(ticks: i64) { } } +pub fn present_skipped(entry: i64) { + let mut g = CSV.lock().unwrap_or_else(|e| e.into_inner()); + let Some(c) = g.as_mut() else { return }; + let now = qpc(); + let f = qpf() as f64; + let ms = |t: i64| t as f64 * 1000.0 / f; + if c.last_present == 0 { + c.start_qpc = entry; + } + let interval = if c.last_present != 0 { ms(entry - c.last_present) } else { 0.0 }; + c.last_present = entry; + crate::frame_ev::note_present_thread(); + let ev = crate::frame_ev::take(); + let game_dt = crate::frame_ev::game_dt_ms(c.qpc_last, &ev); + if ev.qpc_last != 0 { + c.qpc_last = ev.qpc_last; + } + let _ = writeln!(c.out, "0,{:.3},{interval:.3},{:.3},{:.3},,{}", ms(entry - c.start_qpc), ms(now - entry), ms(c.wait_ticks), crate::frame_ev::row(&ev, game_dt)); + c.wait_ticks = 0; + c.wrote_row(now); +} + pub fn present_done(frame: u64, entry: i64) { let mut g = CSV.lock().unwrap(); let Some(c) = g.as_mut() else { return }; @@ -166,7 +206,7 @@ pub fn present_done(frame: u64, entry: i64) { let slot = (frame % 2) as usize; let old = c.pending[slot]; let (mut gpu_frame, mut gpu_list) = (String::new(), String::new()); - if old.valid && c.qheap != 0 { + if old.valid && c.qheap != 0 && !crate::dred::removed() { let (a, z) = c.snap[slot]; if z >= a && a != 0 { gpu_list = format!("{:.1}", (z - a) as f64 * 1e6 / c.freq as f64); @@ -178,10 +218,7 @@ pub fn present_done(frame: u64, entry: i64) { } if old.valid { let _ = writeln!(c.out, "{},{:.3},{:.3},{:.3},{:.3},{gpu_frame},{gpu_list}{}", old.frame, old.t_ms, old.interval_ms, old.cpu_ms, old.wait_ms, crate::frame_ev::row(&old.ev, old.game_dt)); - c.rows += 1; - if c.rows % 240 == 0 { - let _ = c.out.flush(); - } + c.wrote_row(now); } if c.last_present == 0 { c.start_qpc = entry; @@ -197,3 +234,33 @@ pub fn present_done(frame: u64, entry: i64) { c.pending[slot] = Pending { frame, t_ms: ms(entry - c.start_qpc), interval_ms: interval, cpu_ms: ms(now - entry), wait_ms: ms(c.wait_ticks), valid: true, ev, game_dt }; c.wait_ticks = 0; } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_title_present_reaches_the_file_without_a_clean_exit() { + let p = std::env::temp_dir().join(format!("tombox_frames_test_{}.csv", std::process::id())); + *CSV.lock().unwrap() = Some(open_file(&p).unwrap()); + let header = std::fs::read_to_string(&p).unwrap(); + assert!(header.starts_with("frame,t_ms,present_interval_ms") && header.ends_with('\n')); + let t = qpc(); + present_done(1, t); + present_done(2, t + 10); + assert_eq!(CSV.lock().unwrap().as_ref().unwrap().rows, 0); + present_done(3, t + 20); + present_skipped(t + 30); + let rows = CSV.lock().unwrap().as_ref().unwrap().rows; + let body = std::fs::read_to_string(&p).unwrap(); + *CSV.lock().unwrap() = None; + let _ = std::fs::remove_file(&p); + assert_eq!(rows, 2); + let lines: Vec<&str> = body.lines().collect(); + assert_eq!(lines.len(), 3, "{body}"); + assert!(lines[1].starts_with("1,")); + assert!(lines[2].starts_with("0,")); + assert_eq!(lines[1].split(',').count(), lines[0].split(',').count()); + assert_eq!(lines[2].split(',').count(), lines[0].split(',').count()); + } +} diff --git a/crates/compat/d3d12_xs/src/frame_ev.rs b/crates/compat/d3d12_xs/src/frame_ev.rs index 5a83793e..5be66581 100644 --- a/crates/compat/d3d12_xs/src/frame_ev.rs +++ b/crates/compat/d3d12_xs/src/frame_ev.rs @@ -18,8 +18,15 @@ pub const IO: usize = 10; pub const IO_BG: usize = 11; pub const LOCK: usize = 12; pub const FRAME_WAIT: usize = 13; -pub const N: usize = 14; -pub const NAMES: [&str; N] = ["pso_sync", "pso_inline", "pso_async", "pso_bind_wait", "xlat", "dxc", "committed", "placed", "heap", "upload", "io_read", "io_read_bg", "lock_wait", "frame_wait"]; +pub const PSO_LIB_HIT: usize = 14; +pub const PSO_LIB_MISS: usize = 15; +pub const PREWARM_HIT: usize = 16; +pub const PREWARM_LATE: usize = 17; +pub const PREWARM_UNUSED: usize = 18; +pub const TITLE_WAIT: usize = 19; +pub const TITLE_SLEEP: usize = 20; +pub const N: usize = 21; +pub const NAMES: [&str; N] = ["pso_sync", "pso_inline", "pso_async", "pso_bind_wait", "xlat", "dxc", "committed", "placed", "heap", "upload", "io_read", "io_read_bg", "lock_wait", "frame_wait", "pso_lib_hit", "pso_lib_miss", "prewarm_hit", "prewarm_late", "prewarm_unused", "title_wait", "title_sleep"]; static ACTIVE: AtomicBool = AtomicBool::new(false); static CNT: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; @@ -28,6 +35,8 @@ static BG: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; static BG_TICKS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; static QPC_LAST: AtomicI64 = AtomicI64::new(0); static QPC_CALLS: AtomicU64 = AtomicU64::new(0); +static UP_BYTES: AtomicU64 = AtomicU64::new(0); +static UP_COPIES: AtomicU64 = AtomicU64::new(0); static GTC_CALLS: AtomicU64 = AtomicU64::new(0); static PRESENT_TID: AtomicU32 = AtomicU32::new(0); static ORIG_QPC: AtomicUsize = AtomicUsize::new(0); @@ -35,6 +44,13 @@ static ORIG_GTC: AtomicUsize = AtomicUsize::new(0); static ORIG_GTC64: AtomicUsize = AtomicUsize::new(0); static ORIG_RF: AtomicUsize = AtomicUsize::new(0); static ORIG_RFX: AtomicUsize = AtomicUsize::new(0); +static ORIG_WSO: AtomicUsize = AtomicUsize::new(0); +static ORIG_WSOX: AtomicUsize = AtomicUsize::new(0); +static ORIG_WMO: AtomicUsize = AtomicUsize::new(0); +static ORIG_WMOX: AtomicUsize = AtomicUsize::new(0); +static ORIG_SLEEP: AtomicUsize = AtomicUsize::new(0); +static ORIG_SLEEPX: AtomicUsize = AtomicUsize::new(0); +static ORIG_STT: AtomicUsize = AtomicUsize::new(0); static HOOKED: std::sync::Once = std::sync::Once::new(); thread_local! { @@ -48,8 +64,18 @@ extern "system" { fn GetModuleHandleW(name: *const u16) -> *mut u8; } +#[cfg(test)] +thread_local! { + static T_ON: Cell = const { Cell::new(false) }; + static T_ACC: core::cell::RefCell = core::cell::RefCell::new(Snap::default()); +} + #[inline] pub fn active() -> bool { + #[cfg(test)] + if T_ON.with(|c| c.get()) { + return true; + } ACTIVE.load(Relaxed) } @@ -71,8 +97,33 @@ fn worker() -> bool { }) } +pub fn counts_on_title_frame(k: usize) -> bool { + matches!(k, PSO_LIB_HIT | PSO_LIB_MISS | PREWARM_HIT | PREWARM_LATE | PREWARM_UNUSED) +} + +pub fn note(k: usize, ticks: i64) { + if active() { + add(k, ticks, worker()); + } +} + fn add(k: usize, ticks: i64, bg: bool) { let t = ticks.max(0) as u64; + let bg = bg && !counts_on_title_frame(k); + #[cfg(test)] + if T_ON.with(|c| c.get()) { + T_ACC.with(|a| { + let mut a = a.borrow_mut(); + if bg { + a.bg_n[k] += 1; + a.bg_ticks[k] += t; + } else { + a.n[k] += 1; + a.ticks[k] += t; + } + }); + return; + } if bg { BG[k].fetch_add(1, Relaxed); BG_TICKS[k].fetch_add(t, Relaxed); @@ -132,6 +183,22 @@ fn on_dxc(us: u64) { note_nested(DXC, (us as i128 * qpf() as i128 / 1_000_000) as i64); } +pub fn note_upload(bytes: u64, copies: u64) { + #[cfg(test)] + if T_ON.with(|c| c.get()) { + T_ACC.with(|a| { + let mut a = a.borrow_mut(); + a.upload_bytes += bytes; + a.upload_copies += copies; + }); + return; + } + if active() { + UP_BYTES.fetch_add(bytes, Relaxed); + UP_COPIES.fetch_add(copies, Relaxed); + } +} + pub fn note_frame_wait(ticks: i64) { if active() { add(FRAME_WAIT, ticks, worker()); @@ -171,6 +238,8 @@ pub struct Snap { pub qpc_last: i64, pub qpc_calls: u64, pub gtc_calls: u64, + pub upload_bytes: u64, + pub upload_copies: u64, } pub fn take() -> Snap { @@ -184,6 +253,8 @@ pub fn take() -> Snap { s.qpc_last = QPC_LAST.load(Relaxed); s.qpc_calls = QPC_CALLS.swap(0, Relaxed); s.gtc_calls = GTC_CALLS.swap(0, Relaxed); + s.upload_bytes = UP_BYTES.swap(0, Relaxed); + s.upload_copies = UP_COPIES.swap(0, Relaxed); s } @@ -196,7 +267,7 @@ pub fn header() -> String { for name in NAMES { h.push_str(&format!(",{name}_n,{name}_ms")); } - h.push_str(",bg_pso_n,bg_xlat_n,bg_xlat_ms,bg_dxc_n,bg_dxc_ms,qpc_calls,gtc_calls,game_dt_ms"); + h.push_str(",bg_pso_n,bg_xlat_n,bg_xlat_ms,bg_dxc_n,bg_dxc_ms,qpc_calls,gtc_calls,game_dt_ms,upload_bytes,upload_copies"); h } @@ -216,6 +287,7 @@ pub fn row(s: &Snap, game_dt_ms: Option) -> String { if let Some(g) = game_dt_ms { r.push_str(&format!("{g:.3}")); } + r.push_str(&format!(",{},{}", s.upload_bytes, s.upload_copies)); r } @@ -252,6 +324,56 @@ unsafe extern "system" fn gtc64_hook() -> u64 { unsafe { f() } } +fn on_present_thread() -> bool { + let t = PRESENT_TID.load(Relaxed); + t != 0 && unsafe { GetCurrentThreadId() } == t +} + +fn timed(k: usize, f: impl FnOnce() -> R) -> R { + if !active() || !on_present_thread() { + return f(); + } + let t0 = qpc(); + let r = f(); + add(k, qpc() - t0, false); + r +} + +unsafe extern "system" fn wso_hook(h: *mut c_void, ms: u32) -> u32 { + let f: unsafe extern "system" fn(*mut c_void, u32) -> u32 = unsafe { core::mem::transmute(ORIG_WSO.load(Relaxed)) }; + timed(TITLE_WAIT, || unsafe { f(h, ms) }) +} + +unsafe extern "system" fn wsox_hook(h: *mut c_void, ms: u32, alert: i32) -> u32 { + let f: unsafe extern "system" fn(*mut c_void, u32, i32) -> u32 = unsafe { core::mem::transmute(ORIG_WSOX.load(Relaxed)) }; + timed(TITLE_WAIT, || unsafe { f(h, ms, alert) }) +} + +unsafe extern "system" fn wmo_hook(n: u32, hs: *const *mut c_void, all: i32, ms: u32) -> u32 { + let f: unsafe extern "system" fn(u32, *const *mut c_void, i32, u32) -> u32 = unsafe { core::mem::transmute(ORIG_WMO.load(Relaxed)) }; + timed(TITLE_WAIT, || unsafe { f(n, hs, all, ms) }) +} + +unsafe extern "system" fn wmox_hook(n: u32, hs: *const *mut c_void, all: i32, ms: u32, alert: i32) -> u32 { + let f: unsafe extern "system" fn(u32, *const *mut c_void, i32, u32, i32) -> u32 = unsafe { core::mem::transmute(ORIG_WMOX.load(Relaxed)) }; + timed(TITLE_WAIT, || unsafe { f(n, hs, all, ms, alert) }) +} + +unsafe extern "system" fn sleep_hook(ms: u32) { + let f: unsafe extern "system" fn(u32) = unsafe { core::mem::transmute(ORIG_SLEEP.load(Relaxed)) }; + timed(TITLE_SLEEP, || unsafe { f(ms) }) +} + +unsafe extern "system" fn sleepx_hook(ms: u32, alert: i32) -> u32 { + let f: unsafe extern "system" fn(u32, i32) -> u32 = unsafe { core::mem::transmute(ORIG_SLEEPX.load(Relaxed)) }; + timed(TITLE_SLEEP, || unsafe { f(ms, alert) }) +} + +unsafe extern "system" fn stt_hook() -> i32 { + let f: unsafe extern "system" fn() -> i32 = unsafe { core::mem::transmute(ORIG_STT.load(Relaxed)) }; + timed(TITLE_SLEEP, || unsafe { f() }) +} + fn io_kind() -> usize { if unsafe { GetCurrentThreadId() } == PRESENT_TID.load(Relaxed) { IO } else { IO_BG } } @@ -281,15 +403,22 @@ unsafe extern "system" fn read_file_ex_hook(h: *mut c_void, buf: *mut c_void, n: fn install_title_hooks() { HOOKED.call_once(|| { tombox_xshader::shader_cache::COMPILE_HOOK.store(on_dxc as fn(u64) as usize, Relaxed); - let targets: [(&str, usize, &AtomicUsize); 5] = [ + let targets: [(&str, usize, &AtomicUsize); 12] = [ ("QueryPerformanceCounter", qpc_hook as usize, &ORIG_QPC), ("GetTickCount", gtc_hook as usize, &ORIG_GTC), ("GetTickCount64", gtc64_hook as usize, &ORIG_GTC64), ("ReadFile", read_file_hook as usize, &ORIG_RF), ("ReadFileEx", read_file_ex_hook as usize, &ORIG_RFX), + ("WaitForSingleObject", wso_hook as usize, &ORIG_WSO), + ("WaitForSingleObjectEx", wsox_hook as usize, &ORIG_WSOX), + ("WaitForMultipleObjects", wmo_hook as usize, &ORIG_WMO), + ("WaitForMultipleObjectsEx", wmox_hook as usize, &ORIG_WMOX), + ("Sleep", sleep_hook as usize, &ORIG_SLEEP), + ("SleepEx", sleepx_hook as usize, &ORIG_SLEEPX), + ("SwitchToThread", stt_hook as usize, &ORIG_STT), ]; let n = unsafe { compat_common::gdk::hook::patch_module(GetModuleHandleW(core::ptr::null()), &targets) }; - compat_common::record("d3d12_xs", "[frame_csv]", &format!("frame event counters on; title clock/file probes patched {n} import slots in the title exe (QueryPerformanceCounter, GetTickCount[64], ReadFile[Ex])")); + compat_common::record("d3d12_xs", "[frame_csv]", &format!("frame event counters on; title clock/file/wait probes patched {n} import slots in the title exe (QueryPerformanceCounter, GetTickCount[64], ReadFile[Ex], WaitForSingle/MultipleObjects[Ex] -> title_wait, Sleep[Ex]/SwitchToThread -> title_sleep; waits count only on the title's present thread)")); }); } @@ -297,35 +426,113 @@ fn install_title_hooks() { mod tests { use super::*; + fn local(on: bool) -> Snap { + T_ON.with(|c| c.set(on)); + T_ACC.with(|a| core::mem::take(&mut *a.borrow_mut())) + } + #[test] - fn scopes_record_exclusive_time_and_reset_per_take() { - ACTIVE.store(true, Relaxed); - KIND.with(|k| k.set(1)); - let _ = take(); + fn title_wait_and_sleep_columns_follow_the_present_thread_only() { + let h = header(); + assert!(h.contains(",title_wait_n,title_wait_ms,title_sleep_n,title_sleep_ms,bg_pso_n")); + let _ = local(true); + PRESENT_TID.store(0, Relaxed); + assert_eq!(timed(TITLE_WAIT, || 7), 7); + assert_eq!(local(true).n[TITLE_WAIT], 0); + note_present_thread(); + timed(TITLE_WAIT, || ()); + timed(TITLE_SLEEP, || ()); + timed(TITLE_SLEEP, || ()); + let s = local(false); + assert_eq!((s.n[TITLE_WAIT], s.n[TITLE_SLEEP]), (1, 2)); + assert_eq!(s.bg_n[TITLE_WAIT] + s.bg_n[TITLE_SLEEP], 0); + let other = std::thread::spawn(|| { + T_ON.with(|c| c.set(true)); + timed(TITLE_WAIT, || ()); + T_ACC.with(|a| a.borrow().n[TITLE_WAIT]) + }).join().unwrap(); + assert_eq!(other, 0); + PRESENT_TID.store(0, Relaxed); + } + + #[test] + fn pipeline_library_events_from_pso_workers_land_in_the_frame_columns() { + let _ = local(true); + add(PSO_LIB_HIT, 10, true); + add(PSO_LIB_MISS, 20, true); + add(PSO_SYNC, 30, true); + let s = local(false); + assert_eq!((s.n[PSO_LIB_HIT], s.ticks[PSO_LIB_HIT]), (1, 10)); + assert_eq!((s.n[PSO_LIB_MISS], s.ticks[PSO_LIB_MISS]), (1, 20)); + assert_eq!(s.bg_n[PSO_LIB_HIT] + s.bg_n[PSO_LIB_MISS], 0); + assert_eq!((s.n[PSO_SYNC], s.bg_n[PSO_SYNC], s.bg_ticks[PSO_SYNC]), (0, 1, 30)); + let r = row(&s, None); + let cols: Vec<&str> = r.split(',').collect(); + assert_eq!(cols[1 + 2 * PSO_LIB_HIT], "1"); + assert_eq!(cols[1 + 2 * PSO_LIB_MISS], "1"); + } + + #[test] + fn scopes_attribute_counts_and_exclusive_time_to_the_right_class() { + let _ = local(true); { let _outer = begin(XLAT); note_nested(DXC, 1000); let mut inner = begin(PSO_SYNC).unwrap(); inner.set_kind(PSO_INLINE); + mark_async(); } - let s = take(); + let s = local(false); assert_eq!(s.n[XLAT], 1); - assert_eq!(s.n[DXC], 1); - assert_eq!(s.ticks[DXC], 1000); + assert_eq!((s.n[DXC], s.ticks[DXC]), (1, 1000)); assert_eq!(s.n[PSO_INLINE], 1); assert_eq!(s.n[PSO_SYNC], 0); - let s2 = take(); - assert_eq!(s2.n, [0; N]); + assert_eq!(s.n.iter().sum::(), 3); + assert_eq!(s.bg_n, [0; N]); + assert_eq!(local(false).n, [0; N]); let m = Mutex::new(5); assert_eq!(*lock(&m), 5); - mark_async(); assert!(take_async_mark()); assert!(!take_async_mark()); - ACTIVE.store(false, Relaxed); - assert!(begin(XLAT).is_none()); let row = row(&s, Some(1.5)); assert_eq!(row.split(',').count(), header().split(',').count()); - assert!(row.ends_with("1.500")); + assert!(row.ends_with("1.500,0,0")); + } + + #[test] + fn upload_bytes_and_copies_are_the_last_two_columns() { + let _ = local(true); + note_upload(0x4000, 3); + note_upload(0x1000, 2); + let s = local(false); + assert_eq!((s.upload_bytes, s.upload_copies), (0x5000, 5)); + let h = header(); + assert!(h.ends_with(",game_dt_ms,upload_bytes,upload_copies")); + let r = row(&s, None); + assert_eq!(r.split(',').count(), h.split(',').count()); + assert!(r.ends_with(",20480,5"), "{r}"); + } + + #[test] + fn nested_time_is_never_charged_to_the_outer_scope() { + let _ = local(true); + { + let _outer = begin(XLAT); + note_nested(DXC, i64::MAX / 4); + } + let s = local(false); + assert_eq!(s.n[XLAT], 1); + assert_eq!(s.ticks[XLAT], 0); + assert_eq!(s.ticks[DXC], (i64::MAX / 4) as u64); + } + + #[test] + fn inactive_threads_record_nothing_locally() { + let _ = local(false); + if !ACTIVE.load(Relaxed) { + assert!(begin(XLAT).is_none()); + } + T_ACC.with(|a| assert_eq!(a.borrow().n, [0; N])); } #[test] diff --git a/crates/compat/d3d12_xs/src/gds.rs b/crates/compat/d3d12_xs/src/gds.rs index 1dc594c1..f96270f6 100644 --- a/crates/compat/d3d12_xs/src/gds.rs +++ b/crates/compat/d3d12_xs/src/gds.rs @@ -219,7 +219,7 @@ unsafe fn bind(list: *mut c_void, rs: *mut c_void, slot: usize) { if barriers_allowed(unsafe { crate::fill::list_type(list) }) { unsafe { transition(list, res, STATE_UAV) }; } - let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(vslot(list, slot)) }; + let f: unsafe extern "system" fn(*mut c_void, u32, u64) = unsafe { core::mem::transmute(crate::cmdlist_wrap::pc_method(list, slot)) }; unsafe { f(list, idx, va) }; } @@ -275,6 +275,7 @@ pub fn gds_copy_plan(to_gds: bool, dword: u32, count: u32, mem_state: u32, mem_u } pub unsafe fn copy(list: *mut c_void, to_gds: bool, dword: u32, count: u32, va: u64, what: &str) { + let _ij = unsafe { crate::inject::scope(list, crate::inject::COPY) }; if count == 0 { return; } @@ -306,7 +307,7 @@ pub unsafe fn copy(list: *mut c_void, to_gds: bool, dword: u32, count: u32, va: unsafe { transition(list, gres, plan.gds_state); if let Some((a, b)) = plan.mem_before { crate::fill::barrier_pub(list, e.res, a, b); } - let f: unsafe extern "system" fn(*mut c_void, usize, u64, usize, u64, u64) = core::mem::transmute(vslot(list, PC_COPY_BUFFER_REGION)); + let f: unsafe extern "system" fn(*mut c_void, usize, u64, usize, u64, u64) = core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_COPY_BUFFER_REGION)); if to_gds { f(list, gres, plan.gds_off, e.res, off, plan.bytes); } else { @@ -351,7 +352,7 @@ pub unsafe fn write_ordered_append(list: *mut c_void, counter: u32, gds_dword: u let back = STATES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(&(list as usize)).copied()); unsafe { transition(list, gres, STATE_COPY_DEST); - let f: unsafe extern "system" fn(*mut c_void, u32, *const WbiParam, *const u32) = core::mem::transmute(vslot(list, PC_WRITE_BUFFER_IMMEDIATE)); + let f: unsafe extern "system" fn(*mut c_void, u32, *const WbiParam, *const u32) = core::mem::transmute(crate::cmdlist_wrap::pc_method(list, PC_WRITE_BUFFER_IMMEDIATE)); f(list, params.len() as u32, params.as_ptr(), modes.as_ptr()); if let Some(s) = back.filter(|&s| s == STATE_UAV) { transition(list, gres, s); diff --git a/crates/compat/d3d12_xs/src/gpu_va.rs b/crates/compat/d3d12_xs/src/gpu_va.rs index a71b413e..cc042d88 100644 --- a/crates/compat/d3d12_xs/src/gpu_va.rs +++ b/crates/compat/d3d12_xs/src/gpu_va.rs @@ -15,8 +15,8 @@ pub struct Entry { } struct Tables { - ranges: BTreeMap, - cpu: BTreeMap, + ranges: Vec>, + cpu: Vec>, texture_va: HashMap, state: HashMap, width: HashMap, @@ -27,24 +27,45 @@ static NEXT_SYNTH: AtomicU64 = AtomicU64::new(SYNTHETIC_TEXTURE_BASE); fn with(f: impl FnOnce(&mut Tables) -> R) -> R { let mut g = T.lock().unwrap_or_else(|e| e.into_inner()); - let t = g.get_or_insert_with(|| Tables { ranges: BTreeMap::new(), cpu: BTreeMap::new(), texture_va: HashMap::new(), state: HashMap::new(), width: HashMap::new() }); + let t = g.get_or_insert_with(|| Tables { ranges: Vec::new(), cpu: Vec::new(), texture_va: HashMap::new(), state: HashMap::new(), width: HashMap::new() }); f(t) } -fn insert_into(m: &mut BTreeMap, e: Entry) { +const MAX_LEVELS: usize = 8; + +fn overlapping(m: &BTreeMap, e: &Entry) -> Vec { let end = e.start.saturating_add(e.len); - let stale: Vec = m.range(..end).rev() + m.range(..end).rev() .take_while(|(_, x)| x.start.saturating_add(x.len) > e.start) - .map(|(k, _)| *k).collect(); - for k in stale { - m.remove(&k); + .map(|(_, x)| *x).collect() +} + +fn insert_into(levels: &mut Vec>, e: Entry) { + let mut l = 0; + loop { + if levels.len() <= l { + levels.push(BTreeMap::new()); + } + let mut larger = false; + for old in overlapping(&levels[l], &e) { + if old.res != e.res && old.len > e.len && l + 1 < MAX_LEVELS { + larger = true; + } else if let Some(old) = levels[l].remove(&old.start) { + crate::hang_cap::note_evict(&old, &e); + } + } + if !larger { + levels[l].insert(e.start, e); + return; + } + l += 1; } - m.insert(e.start, e); } -fn find_in(m: &BTreeMap, a: u64) -> Option<(Entry, u64)> { - m.range(..=a).next_back().map(|(_, e)| *e) - .filter(|e| a < e.start.saturating_add(e.len)) +fn find_in(levels: &[BTreeMap], a: u64) -> Option<(Entry, u64)> { + levels.iter() + .filter_map(|m| m.range(..=a).next_back().map(|(_, e)| *e).filter(|e| a < e.start.saturating_add(e.len))) + .min_by_key(|e| e.len) .map(|e| crate::placed_offset::true_entry(e, a)) } @@ -72,7 +93,22 @@ pub fn near_in(m: &BTreeMap, va: u64, n: usize) -> Vec { } pub fn near(va: u64, n: usize) -> Vec { - with(|t| near_in(&t.ranges, va, n)) + with(|t| { + let mut all: BTreeMap = BTreeMap::new(); + for m in t.ranges.iter().rev() { + all.extend(m.iter().map(|(k, e)| (*k, *e))); + } + near_in(&all, va, n) + }) +} + +pub fn lookup_buffer(va: u64) -> Option<(Entry, u64)> { + with(|t| { + t.ranges.iter() + .filter_map(|m| m.range(..=va).next_back().map(|(_, e)| *e).filter(|e| e.buffer && va < e.start.saturating_add(e.len))) + .min_by_key(|e| e.len) + .map(|e| crate::placed_offset::true_entry(e, va)) + }) } pub fn lookup_gpu(va: u64) -> Option<(Entry, u64)> { @@ -319,10 +355,15 @@ pub unsafe fn note_resource(real_device: *mut c_void, res: *mut c_void, desc: &[ if let Some(x) = placed_va { insert(Entry { start: x, len: width, res: res as usize, buffer: true }); } + crate::va_census::note(res as usize, desc, placed_va.unwrap_or(pc_va), width, placed_va.is_some()); + crate::firstuse::note(res as usize, crate::firstuse::CREATE); return; } unsafe { ensure_patched(res) }; - assign_texture_va(res as usize, xbox_texture_size(desc).max(1), placed_va); + let len = xbox_texture_size(desc).max(1); + let va = assign_texture_va(res as usize, len, placed_va); + crate::va_census::note(res as usize, desc, va, len, va < SYNTHETIC_TEXTURE_BASE); + crate::firstuse::note(res as usize, crate::firstuse::CREATE); } #[cfg(test)] @@ -341,6 +382,40 @@ mod tests { assert_eq!(lookup(0x1_0000_2f00), None); } + #[test] + fn buffer_lookup_sees_through_a_texture_registered_inside_a_buffer_range() { + let base = 0x5_0800_0000u64; + insert(Entry { start: base, len: 0x600_0000, res: 0x30, buffer: true }); + insert(Entry { start: base + 0x544_0000, len: 0x2_0000, res: 0x31, buffer: false }); + assert_eq!(lookup(base + 0x544_c9c0).map(|(e, _)| e.res), Some(0x31)); + assert_eq!(lookup_buffer(base + 0x544_c9c0).map(|(e, o)| (e.res, o)), Some((0x30, 0x544_c9c0))); + assert_eq!(lookup_buffer(base + 0x600_0000), None); + } + + #[test] + fn a_smaller_resource_never_evicts_the_larger_range_it_sits_in() { + let base = 0x3_0800_0000u64; + insert(Entry { start: base, len: 0x600_0000, res: 0x10, buffer: true }); + insert(Entry { start: base + 0x4f4_0000, len: 0x1_0000, res: 0x11, buffer: false }); + assert_eq!(lookup(base + 0x5_6830).map(|(e, o)| (e.res, o)), Some((0x10, 0x5_6830))); + assert_eq!(lookup(base + 0x4f4_0100).map(|(e, o)| (e.res, o)), Some((0x11, 0x100))); + assert_eq!(lookup(base + 0x5ff_fff0).map(|(e, _)| e.res), Some(0x10)); + insert(Entry { start: base + 0x4f4_8000, len: 0x1_0000, res: 0x12, buffer: false }); + assert_eq!(lookup(base + 0x4f4_0100).map(|(e, _)| e.res), Some(0x10)); + assert_eq!(lookup(base + 0x4f4_9000).map(|(e, _)| e.res), Some(0x12)); + insert(Entry { start: base + 0x100_0000, len: 0x800, res: 0x13, buffer: false }); + insert(Entry { start: base + 0x100_0200, len: 0x100, res: 0x14, buffer: false }); + assert_eq!(lookup(base + 0x100_0250).map(|(e, _)| e.res), Some(0x14)); + assert_eq!(lookup(base + 0x100_0400).map(|(e, _)| e.res), Some(0x13)); + assert_eq!(lookup(base + 0x100_0900).map(|(e, _)| e.res), Some(0x10)); + insert(Entry { start: base, len: 0x600_0000, res: 0x15, buffer: true }); + assert_eq!(lookup(base + 0x5_6830).map(|(e, _)| e.res), Some(0x15)); + assert_eq!(lookup(base + 0x100_0250).map(|(e, _)| e.res), Some(0x14)); + insert(Entry { start: base, len: 0x800_0000, res: 0x16, buffer: true }); + assert_eq!(lookup(base + 0x700_0000).map(|(e, _)| e.res), Some(0x16)); + assert_eq!(lookup(base + 0x5_6830).map(|(e, _)| e.res), Some(0x16)); + } + #[test] fn synthetic_texture_ranges_do_not_collide() { let a = assign_texture_va(0x5000, 0x30000, None); diff --git a/crates/compat/d3d12_xs/src/gpuprof.rs b/crates/compat/d3d12_xs/src/gpuprof.rs index f6aea919..7203cc2f 100644 --- a/crates/compat/d3d12_xs/src/gpuprof.rs +++ b/crates/compat/d3d12_xs/src/gpuprof.rs @@ -31,22 +31,86 @@ struct Ev { slot: u32, label: Label, kind: u8, + count: bool, + frame: u32, } #[derive(Default)] struct ListRec { label: Option