From 51fc8e0b13acad07cd05032d9d0cf2abe75f4e1f Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:28:44 +0200 Subject: [PATCH 01/29] shader: add offset, short-read, and regular-file guards in sgd5_effects with CLI suite (#2608) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/sgd5_effects_cli_check.py | 447 ++++++++++++++++++++++++++++++++ tools/sgd5_effects.py | 16 +- 3 files changed, 463 insertions(+), 3 deletions(-) create mode 100644 tests/sgd5_effects_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 5a367699d..f04ee8e85 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8891,6 +8891,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/awc_metadata_cli_check.py") add_test(NAME sgd5_effect_candidates COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_check.py") + add_test(NAME shader_sgd5_effects_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_cli_check.py") + set_tests_properties(shader_sgd5_effects_cli_check PROPERTIES TIMEOUT 60) add_test(NAME rdna2_tools_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/rdna2_tools_check.py") add_test(NAME rdna2_cli_checks COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/sgd5_effects_cli_check.py b/tests/sgd5_effects_cli_check.py new file mode 100644 index 000000000..297c69e9c --- /dev/null +++ b/tests/sgd5_effects_cli_check.py @@ -0,0 +1,447 @@ +"""CLI, path-guard, short-read, error-handling, and mutation suite for tools/sgd5_effects.py.""" + +import argparse +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "sgd5_effects.py" +sys.path.insert(0, str(ROOT / "tools")) + +import sgd5_effects # noqa: E402 + + +def _word(value: int) -> bytes: + return struct.pack(" bytes: + encoded = text.encode("ascii") + b"\0" + return bytes([len(encoded)]) + encoded + + +def _deflate_raw(blob: bytes, mode: int = zlib.Z_FINISH) -> bytes: + compressor = zlib.compressobj(wbits=-15) + return compressor.compress(blob) + compressor.flush(mode) + + +def _program_record(label: str, kind: int, identity: int, *, pack=_deflate_raw) -> tuple[bytes, str]: + dxil = struct.pack(" bytes: + lists = b"".join(_word(len(group)) + b"".join(map(_word, group)) for group in (vs, ps, [], [], [], [])) + strings = b"\0entry\0" + return _len_name(label) + _word(0) + lists + b"\xff\xff" + _word(len(strings)) + strings + + +def _build_archive(prefix_len: int = 0) -> tuple[bytes, int, int, int, int, int, str, str]: + vs0, vs_digest = _program_record("vs_main", 1, 101) + ps0, ps_digest = _program_record("ps_main", 0, 202) + arrays = _word(1) + vs0 + _word(1) + ps0 + _word(0) * 4 + first = _effect_record("idle", [], []) + second = _effect_record("draw", [0], [0]) + header = bytes(prefix_len) + b"SGD5" + bytes(28) + arrays_start = len(header) + first_start = arrays_start + len(arrays) + 4 + second_start = first_start + len(first) + archive = header + arrays + _word(2) + first + second + return archive, prefix_len, len(archive), arrays_start, second_start, len(archive), vs_digest, ps_digest + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = sgd5_effects.main(argv) + except SystemExit as exc: + raw = exc.code + code = 0 if raw is None else (int(raw) if isinstance(raw, int) else 2) + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class Sgd5EffectsCliPositiveTests(unittest.TestCase): + def test_cli_zero_and_hex_offsets_exact_json_schema(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, prefix_len, fmt_offset in ( + ("zero_group_start", 0, str), + ("hex_offsets", 16, hex), + ): + with self.subTest(label=label): + data, grp_start, grp_end, arrays, rec_start, rec_end, vs_digest, ps_digest = _build_archive( + prefix_len + ) + archive = root / f"{label}.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + fmt_offset(grp_start), + fmt_offset(grp_end), + "--arrays", + fmt_offset(arrays), + "--record", + fmt_offset(rec_start), + fmt_offset(rec_end), + ] + expected = { + "effect": "draw", + "candidates": [ + { + "group": "VS", + "index": 0, + "name": "vs_main", + "dxil_kind": 1, + "container_sha256": vs_digest, + }, + { + "group": "PS", + "index": 0, + "name": "ps_main", + "dxil_kind": 0, + "container_sha256": ps_digest, + }, + ], + } + + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(set(doc), {"effect", "candidates"}) + self.assertEqual(doc, expected) + for item in doc["candidates"]: + self.assertEqual(set(item), {"group", "index", "name", "dxil_kind", "container_sha256"}) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), expected) + + self.assertEqual(sorted(p.name for p in root.iterdir()), ["hex_offsets.bin", "zero_group_start.bin"]) + + def test_main_sys_argv_and_script_entrypoint(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "entry.bin" + archive.write_bytes(data) + cli_argv = [ + str(TOOL), + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(json.loads(out)["candidates"]), 2) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(len(json.loads(stdout.getvalue())["candidates"]), 2) + + +class Sgd5EffectsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragment: str, + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment.lower(), proc.stderr.lower()) + + def test_py314_safe_argparse_errors_exit_nonzero_without_traceback(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "valid.bin" + archive.write_bytes(data) + base_argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + for label, argv, frag in ( + ("missing_all_args", [], "usage:"), + ("missing_required_flags", [str(archive), "draw"], "required"), + ("non_integer_arrays", [str(archive), "draw", "--group", "0", "1", "--arrays", "bad", "--record", "0", "1"], "invalid"), + ("unknown_flag", [*base_argv, "--unknown-flag"], "unrecognized"), + ): + with self.subTest(case=label): + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + sgd5_effects.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self._assert_clean_failure(argv, expected_code=2, expected_fragment=frag) + + def test_negative_offsets_rejected_by_offset_parser_before_opening_archive(self) -> None: + self.assertEqual(sgd5_effects.offset("0"), 0) + self.assertEqual(sgd5_effects.offset("0x20"), 32) + for raw in ("-1", "-0x1", "-16"): + with self.subTest(raw=raw): + with self.assertRaises(argparse.ArgumentTypeError): + sgd5_effects.offset(raw) + + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + existing = Path(tmp) / "existing.bin" + existing.write_bytes(data) + missing = Path(tmp) / "missing.bin" + + for archive in (existing, missing): + for label, bad_argv in ( + ("neg_group_start", [str(archive), "draw", "--group", "-1", str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), + ("neg_group_end", [str(archive), "draw", "--group", str(grp_start), "-1", "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), + ("neg_arrays", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays=-0x1", "--record", str(rec_start), str(rec_end)]), + ("neg_record_start", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", "-1", str(rec_end)]), + ("neg_record_end", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), "-0x10"]), + ): + with self.subTest(archive=archive.name, case=label): + with mock.patch.object( + sgd5_effects, + "candidates", + side_effect=AssertionError("candidates called for negative offset"), + ): + self._assert_clean_failure( + bad_argv, + expected_code=2, + expected_fragment="non-negative", + ) + + def test_non_file_and_missing_archive_rejected_upfront_before_candidates(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + dir_path = root / "archive_dir" + dir_path.mkdir() + missing_path = root / "missing.bin" + + for label, bad_archive in ( + ("directory", str(dir_path)), + ("empty_cwd_dir", ""), + ("missing_file", str(missing_path)), + ): + with self.subTest(case=label): + argv = [ + bad_archive, + "draw", + "--group", + "0", + "64", + "--arrays", + "32", + "--record", + "48", + "64", + ] + with mock.patch.object( + sgd5_effects, + "candidates", + side_effect=AssertionError(f"candidates called for invalid archive {label}"), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment="regular file", + check_subprocess=bool(bad_archive), + ) + + def test_cursor_short_and_overlong_reads_and_negative_skip_rejected(self) -> None: + class _FakeView: + def __init__(self, payload: bytes) -> None: + self._payload = payload + + def read(self, offset: int, length: int) -> bytes: + return self._payload + + for label, payload, request in ( + ("empty_short_read", b"", 4), + ("partial_short_read", b"abc", 4), + ("overlong_read", b"abcde", 4), + ): + with self.subTest(case=label): + cursor = sgd5_effects.Cursor(_FakeView(payload), 0, 16) + with self.assertRaisesRegex(ValueError, "Truncated"): + cursor.read(request) + + neg_cursor = sgd5_effects.Cursor(_FakeView(b"abcd"), 4, 16) + with self.assertRaisesRegex(ValueError, "Negative"): + neg_cursor.skip(-1) + self.assertEqual(neg_cursor.pos, 4) + + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "short_read.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + with mock.patch.object(sgd5_effects.PagedResource, "read", side_effect=[b"SGD5", b"SG"]): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment="Truncated", + check_subprocess=False, + ) + + def test_os_value_struct_and_zlib_errors_caught_without_traceback(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "probe.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + + # Real corrupt archive checks via both in-process main() and subprocess. + bad_magic = bytearray(data) + bad_magic[0:4] = b"BAD!" + bad_magic_path = Path(tmp) / "bad_magic.bin" + bad_magic_path.write_bytes(bad_magic) + self._assert_clean_failure( + [str(bad_magic_path), *argv[1:]], + expected_code=1, + expected_fragment="Missing SGD5 group header", + ) + + vs_bad, _ = _program_record("vs_main", 1, 101, pack=lambda blob: b"\xff" * len(_deflate_raw(blob))) + ps0, _ = _program_record("ps_main", 0, 202) + bad_arrays = _word(1) + vs_bad + _word(1) + ps0 + _word(0) * 4 + draw_effect = _effect_record("draw", [0], [0]) + bad_zlib_bytes = ( + b"SGD5" + + bytes(28) + + bad_arrays + + _word(2) + + _effect_record("idle", [], []) + + draw_effect + ) + bad_zlib_path = Path(tmp) / "bad_zlib.bin" + bad_zlib_path.write_bytes(bad_zlib_bytes) + self._assert_clean_failure( + [ + str(bad_zlib_path), + "draw", + "--group", + "0", + str(len(bad_zlib_bytes)), + "--arrays", + "32", + "--record", + str(len(bad_zlib_bytes) - len(draw_effect)), + str(len(bad_zlib_bytes)), + ], + expected_code=1, + expected_fragment="Invalid compressed SGD5 candidate", + ) + + # Direct error-tuple mutation controls for (OSError, ValueError, struct.error, zlib.error). + for exc in ( + OSError("simulated read error"), + ValueError("simulated validation error"), + struct.error("unpack requires a buffer of 12 bytes"), + zlib.error("Error -3 while decompressing data"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(sgd5_effects, "candidates", side_effect=exc): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment=str(exc), + check_subprocess=False, + ) + + self.assertEqual( + sorted(p.name for p in Path(tmp).iterdir()), + ["bad_magic.bin", "bad_zlib.bin", "probe.bin"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/sgd5_effects.py b/tools/sgd5_effects.py index c485ec52f..f0c851ec1 100644 --- a/tools/sgd5_effects.py +++ b/tools/sgd5_effects.py @@ -23,6 +23,8 @@ def __init__(self, view: PagedResource, start: int, end: int): self.end = end def skip(self, size: int) -> int: + if size < 0: + raise ValueError("Negative SGD5 field size") start = self.pos if size > self.end - start: raise ValueError("SGD5 field exceeds supplied range") @@ -30,7 +32,10 @@ def skip(self, size: int) -> int: return start def read(self, size: int) -> bytes: - return self.view.read(self.skip(size), size) + data = self.view.read(self.skip(size), size) + if len(data) != size: + raise ValueError("Truncated SGD5 field") + return data def word(self) -> int: return int.from_bytes(self.read(4), "little") @@ -158,7 +163,10 @@ def candidates(stream: BinaryIO, name: str, group_start: int, group_end: int, ar def offset(value: str) -> int: - return int(value, 0) + parsed = int(value, 0) + if parsed < 0: + raise argparse.ArgumentTypeError(f"Expected non-negative offset, got {value}") + return parsed def main(argv: Sequence[str] | None = None) -> int: @@ -172,10 +180,12 @@ def main(argv: Sequence[str] | None = None) -> int: help="Physical bounds of the selected effect, including its final name block") args = parser.parse_args(argv) try: + if not args.archive.is_file(): + raise ValueError(f"Expected an existing regular file: {args.archive}") with args.archive.open("rb") as stream: found = candidates(stream, args.effect, *args.group, args.arrays, *args.record) print(json.dumps({"effect": args.effect, "candidates": [asdict(item) for item in found]}, indent=2)) - except (OSError, ValueError) as exc: + except (OSError, ValueError, struct.error, zlib.error) as exc: sys.stderr.write(f"{args.archive}: {exc}\n") return 1 return 0 From 0858991042594da908c6f039c8be866855d0eaad Mon Sep 17 00:00:00 2001 From: JVProg <100954822+JVProg@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:29:12 +0100 Subject: [PATCH 02/29] startup: count new view records by slot behind an opt-in census (#2613) X2W_D3D12_VIEW_CENSUS=1 counts new distinct view records by device slot and logs the record vector capacity and hash bucket count before an insertion that is expected to grow either. Record identity, ids and descriptor binding do not change. Refs #1199 Co-authored-by: Claude Sonnet 5.5 --- CMakeLists.txt | 28 +++ docs/startup-runtime.md | 43 ++++ src/startup_stubs/d3d12_capture.inl | 54 +++++ src/startup_stubs/d3d12_xs_device.cpp | 22 ++ tests/startup_view_census.cpp | 288 ++++++++++++++++++++++++++ 5 files changed, 435 insertions(+) create mode 100644 tests/startup_view_census.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f04ee8e85..23e414ed9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1371,6 +1371,34 @@ foreach(backend IN ITEMS warp hardware) endforeach() +# X2W_D3D12_VIEW_CENSUS=1 counts new distinct view records by slot and logs capacity and buckets before they grow. +# `off` runs without the switch (nothing reported); `vary` is the negative control: the repeated stream is made distinct, +# and the fixture must say so. +add_executable(startup_view_census tests/startup_view_census.cpp) +target_compile_features(startup_view_census PRIVATE cxx_std_17) +target_link_libraries(startup_view_census PRIVATE d3d12_xs_shim d3d12 dxgi psapi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS on off vary) + set(census_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + list(APPEND census_env "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/startup_view_census_${mode}_${backend}.log") + if(NOT mode STREQUAL "off") + list(APPEND census_env "X2W_D3D12_VIEW_CENSUS=1") + endif() + if(mode STREQUAL "on") + set(census_test startup_view_census_${backend}) + add_test(NAME ${census_test} COMMAND startup_view_census ${backend}) + else() + set(census_test startup_view_census_${mode}_${backend}) + add_test(NAME ${census_test} COMMAND startup_view_census ${backend} ${mode}) + endif() + set_tests_properties(${census_test} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "${census_env}") + if(mode STREQUAL "vary") + set_tests_properties(${census_test} PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: the repeated stream added records") + endif() + endforeach() +endforeach() + add_executable(startup_resource_retire_title tests/startup_resource_retire_title.cpp) target_include_directories(startup_resource_retire_title PRIVATE src) target_compile_features(startup_resource_retire_title PRIVATE cxx_std_17) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 1353b96e3..e38af186e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1349,6 +1349,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | +| `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | @@ -1534,6 +1535,48 @@ FALSE without the switch, like `x2w_d3d12_budget_snapshot`. `startup_resource_re runs the same steps without the switch. The hardware cases report 77 without a physical adapter, and the debug-layer cases report 77 where the debug layer is not installed. +## D3D12 view census + +The stand-in keeps one record per distinct view: slot, resource, counter, +description bytes and whether the desktop view was created. Records are not +removed. `X2W_D3D12_VIEW_CENSUS=1` shows which slot adds them. It changes no +record, id or descriptor binding. + +The heartbeat adds a line: + +`x2w-view-census distinct by slot: cbv= srv= uav= rtv= dsv= sampler= records= capacity= ids= buckets= grows-records= grows-ids= missed=` + +- `cbv` to `sampler`: new records from device slots 17 to 22. +- `records`, `capacity`: size and capacity of the record vector. +- `ids`, `buckets`: size and bucket count of the hash map from content to id. + +Before an insertion that is expected to grow either container, the same fields +are logged as `x2w-view-census before growth of `, +with the slot of the new record. The values are those before the growth. The line +is written before the allocation, so it is in the log when that allocation fails, +also when no further heartbeat follows. The growth is predicted: from the +vector's capacity, and for the map from the MSVC rehash rule (the new size over +the bucket count exceeds the maximum load factor). `missed` counts capacity or +bucket changes that no line announced. + +The census counts distinct byte contents, not distinct views. It does not say +why two records differ (for example a changing address, or description bytes +that the view type does not use), and it does not measure the size of the +containers in bytes or reduce it. + +`startup_view_census_` calls slots 17, 18 and 22 of the device. +A repeated descriptor must add no record and grow nothing. A stream of 200,000 +distinct constant buffer views, 3,000 buffer SRVs and 100 samplers must be +counted by slot, with one log line per announced growth. Both streams run under +a job commit limit 256 MiB above the commit held after setup. `off` checks that +nothing is reported without the switch; in `vary` the repeated stream changes +every call, and the fixture must fail. Slots 19 to 21 are not exercised. + +```powershell +cmake --build --preset dev --target startup_view_census +ctest --preset dev --no-tests=error -R "^startup_view_census" -V +``` + ## Input script `X2W_INPUT_SCRIPT` (`run.ps1 -InputScript`) drives the virtual gamepad of the `GameInput.dll` diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6f92733f0..2b51942e8 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -61,6 +61,33 @@ std::vector& view_materialized() { static std::vector& view_ids() { static std::unordered_map m; return m; } // content hash -> view id LONG64 views_noted, views_distinct, descriptors_copied; +// X2W_D3D12_VIEW_CENSUS=1 (diagnostic only, docs/startup-runtime.md): new distinct view records by slot, and one line +// before an insertion that is expected to grow view_records or the view_ids buckets. All fields: note_lock held. +bool view_census_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_VIEW_CENSUS"); + return on; +} +struct ViewCensus { + u64 distinct[6]; // slots 17..22 + u64 grows_records, grows_ids; // growths announced + u64 missed; // capacity or bucket count changed without an announcement +}; +ViewCensus view_census{}; + +std::size_t view_census_format(char* out, std::size_t capacity, const char* what) +{ + const ViewCensus& c = view_census; + const int n = std::snprintf(out, capacity, + "x2w-view-census %s: cbv=%llu srv=%llu uav=%llu rtv=%llu dsv=%llu sampler=%llu records=%llu capacity=%llu " + "ids=%llu buckets=%llu grows-records=%llu grows-ids=%llu missed=%llu", + what, c.distinct[0], c.distinct[1], c.distinct[2], c.distinct[3], c.distinct[4], c.distinct[5], + static_cast(view_records().size()), static_cast(view_records().capacity()), + static_cast(view_ids().size()), static_cast(view_ids().bucket_count()), + c.grows_records, c.grows_ids, c.missed); + return n < 0 ? 0 : (std::min)(static_cast(n), capacity - 1); +} + // The shadow entry for a desktop CPU descriptor handle (note_lock held), or null. std::uint32_t* shadow_slot(u64 desktop_handle, std::uint32_t* room = nullptr) { @@ -306,10 +333,37 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ record.id = found->second; } else { record.id = static_cast(view_records().size()); + const bool census = view_census_enabled(); + std::size_t capacity_before = 0, buckets_before = 0; + bool records_full = false, ids_full = false; + if (census) { + capacity_before = view_records().capacity(); + buckets_before = view_ids().bucket_count(); + records_full = view_records().size() == capacity_before; + // MSVC's rule: unordered_map rehashes when the new size would exceed the maximum load factor. + ids_full = static_cast(view_ids().size() + 1) / static_cast(buckets_before) > + view_ids().max_load_factor(); + // Logged before the allocation, so the last line survives an allocation that fails. + if (records_full || ids_full) { + view_census.grows_records += records_full; + view_census.grows_ids += ids_full; + char line[640]; + view_census_format(line, sizeof(line), + records_full && ids_full ? "before growth of records and ids" + : records_full ? "before growth of records" + : "before growth of ids"); + log("%s (new slot %u)", line, record.slot); + } + } view_records().push_back(record); view_materialized().push_back(created); view_ids()[hash] = record.id; ++views_distinct; + if (census) { + if (record.slot >= 17 && record.slot <= 22) ++view_census.distinct[record.slot - 17]; + view_census.missed += !records_full && view_records().capacity() != capacity_before; + view_census.missed += !ids_full && view_ids().bucket_count() != buckets_before; + } } if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { const std::uint32_t prev = *slot_ptr; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f92272d09..50a37c5aa 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -5288,6 +5288,24 @@ extern "C" __declspec(dllexport) std::size_t x2w_d3d12_retire_reasons_line(char* return retire_reasons_line(out, capacity); } +// The census heartbeat line, or an empty string when X2W_D3D12_VIEW_CENSUS is not set. +std::size_t view_census_line(char* out, std::size_t capacity) +{ + if (!out || !capacity) return 0; + out[0] = 0; + if (!view_census_enabled()) return 0; + AcquireSRWLockShared(¬e_lock); + const std::size_t used = view_census_format(out, capacity, "distinct by slot"); + ReleaseSRWLockShared(¬e_lock); + return used; +} + +// Fixture export (startup_view_census): the line the heartbeat logs, now. +extern "C" __declspec(dllexport) std::size_t x2w_d3d12_view_census_line(char* out, std::size_t capacity) +{ + return view_census_line(out, capacity); +} + // Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many // resources the open recording of a list moved out of COMMON, and how many it holds. Counts entries only. struct RetireProbe { @@ -6070,6 +6088,10 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa "(region-information proofs %lld, region queries %lld)", views_noted, views_distinct, descriptors_copied, static_cast(heap_infos().size()), static_cast(placed_buffer_calls), static_cast(placed_buffer_region_info), static_cast(placed_buffer_queries)); + { + char line[640]; + if (view_census_line(line, sizeof(line))) log("%s", line); + } { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); diff --git a/tests/startup_view_census.cpp b/tests/startup_view_census.cpp new file mode 100644 index 000000000..d11b99cfd --- /dev/null +++ b/tests/startup_view_census.cpp @@ -0,0 +1,288 @@ +// X2W_D3D12_VIEW_CENSUS=1 (docs/startup-runtime.md#d3d12-view-census): the stand-in counts new distinct view records +// by slot and logs the vector capacity and hash bucket count before an insertion that grows either. The fixture compares +// a stream of one repeated descriptor with a stream of distinct descriptors, both through the real device view slots +// and both under a job commit limit set above what the process holds after setup. +// +// startup_view_census [off|vary] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1 X2W_D3D12_VIEW_CENSUS=1 X2W_TRAP_LOG=) +// "off" runs without X2W_D3D12_VIEW_CENSUS: nothing may be reported or logged. "vary" is the negative control: +// the stream meant to repeat one descriptor changes it every call, which the fixture must report as a failure. +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) std::size_t x2w_d3d12_view_census_line(char*, std::size_t); + +namespace { + +constexpr unsigned long long headroom = 256ull << 20; // job commit limit above the commit held after setup +constexpr UINT repeated_calls = 200000; +constexpr UINT distinct_buffers = 200000; // slot 17 +constexpr UINT distinct_views = 3000; // slot 18 +constexpr UINT distinct_samplers = 100; // slot 22 + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +unsigned long long process_commit() +{ + PROCESS_MEMORY_COUNTERS_EX counters{}; + if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&counters), sizeof(counters))) + return 0; + return counters.PrivateUsage; +} + +// Puts this process in its own job with a commit limit. The job lives until the process ends. +bool limit_commit(unsigned long long limit) +{ + const HANDLE job = CreateJobObjectW(nullptr, nullptr); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY; + info.JobMemoryLimit = static_cast(limit); + return job && SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info)) && + AssignProcessToJobObject(job, GetCurrentProcess()); +} + +struct Census { + unsigned long long cbv, srv, uav, rtv, dsv, sampler, records, capacity, ids, buckets, grows_records, grows_ids, missed; +}; + +bool read_census(Census& c, const char* stage) +{ + char line[1024]{}; + if (!x2w_d3d12_view_census_line(line, sizeof(line))) { + std::printf("FAIL: %s: the census line is empty although the switch is on\n", stage); + return false; + } + const int fields = std::sscanf(line, + "x2w-view-census distinct by slot: cbv=%llu srv=%llu uav=%llu rtv=%llu dsv=%llu sampler=%llu records=%llu " + "capacity=%llu ids=%llu buckets=%llu grows-records=%llu grows-ids=%llu missed=%llu", + &c.cbv, &c.srv, &c.uav, &c.rtv, &c.dsv, &c.sampler, &c.records, &c.capacity, &c.ids, &c.buckets, + &c.grows_records, &c.grows_ids, &c.missed); + std::printf("%s: %s\n", stage, line); + if (fields != 13) std::printf("FAIL: %s: unreadable census line (%d fields)\n", stage, fields); + return fields == 13; +} + +bool check(bool ok, const char* what) +{ + if (!ok) std::printf("FAIL: %s\n", what); + return ok; +} + +std::string read_log() +{ + wchar_t path[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", path, MAX_PATH); + std::string text; + if (!length || length >= MAX_PATH) return text; + const HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return text; + char chunk[4096]; + DWORD got = 0; + while (ReadFile(file, chunk, sizeof(chunk), &got, nullptr) && got) text.append(chunk, got); + CloseHandle(file); + return text; +} + +unsigned long long occurrences(const std::string& text, const char* needle) +{ + unsigned long long count = 0; + for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count; + return count; +} + +struct Streams { + IUnknown* guest; + UINT64 view_handle, sampler_handle; + + void constant_buffer(UINT index) const + { + const D3D12_CONSTANT_BUFFER_VIEW_DESC desc{0x100000ull + 256ull * index, 256}; + invoke(guest, 17, &desc, view_handle); + } + void buffer_view(UINT index) const + { + D3D12_SHADER_RESOURCE_VIEW_DESC desc; + std::memset(&desc, 0, sizeof(desc)); // padding is part of the record's content + desc.Format = DXGI_FORMAT_R32_FLOAT; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = index; + desc.Buffer.NumElements = 1; + invoke(guest, 18, static_cast(nullptr), &desc, view_handle); + } + void sampler(UINT index) const + { + D3D12_SAMPLER_DESC desc{}; + desc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + desc.AddressU = desc.AddressV = desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + desc.MipLODBias = static_cast(index) / 16.0f; + desc.MaxAnisotropy = 1; + desc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + desc.MaxLOD = D3D12_FLOAT32_MAX; + invoke(guest, 22, &desc, sampler_handle); + } +}; + +bool scenario(const Streams& s, bool vary) +{ + // One of each first, so the repeated stream starts from records that already exist. + s.constant_buffer(0); + s.buffer_view(0); + s.sampler(0); + Census start{}, repeated{}, distinct{}; + if (!read_census(start, "start")) return false; + + const unsigned long long before_repeated = process_commit(); + for (UINT i = 0; i < repeated_calls; ++i) s.constant_buffer(vary ? i : 0); + for (UINT i = 0; i < distinct_views; ++i) s.buffer_view(0); + const unsigned long long after_repeated = process_commit(); + if (!read_census(repeated, "repeated")) return false; + if (!check(repeated.records == start.records && repeated.cbv == start.cbv && repeated.srv == start.srv && + repeated.sampler == start.sampler, + "the repeated stream added records")) + return false; + if (!check(repeated.capacity == start.capacity && repeated.buckets == start.buckets && + repeated.grows_records == start.grows_records && repeated.grows_ids == start.grows_ids, + "the repeated stream grew a container")) + return false; + + for (UINT i = 1; i <= distinct_buffers; ++i) s.constant_buffer(i); + for (UINT i = 1; i <= distinct_views; ++i) s.buffer_view(i); + for (UINT i = 1; i <= distinct_samplers; ++i) s.sampler(i); + const unsigned long long after_distinct = process_commit(); + if (!read_census(distinct, "distinct")) return false; + std::printf("commit bytes: repeated stream %+lld, distinct stream %+lld\n", + static_cast(after_repeated - before_repeated), + static_cast(after_distinct - after_repeated)); + if (!check(distinct.cbv - repeated.cbv == distinct_buffers, "slot 17 count") || + !check(distinct.srv - repeated.srv == distinct_views, "slot 18 count") || + !check(distinct.sampler - repeated.sampler == distinct_samplers, "slot 22 count") || + !check(!distinct.uav && !distinct.rtv && !distinct.dsv, "a slot without calls has records") || + !check(distinct.records - repeated.records == distinct_buffers + distinct_views + distinct_samplers, + "record total") || + !check(distinct.ids == distinct.records, "ids and records differ") || + !check(distinct.capacity >= distinct.records, "capacity below size") || + !check(distinct.grows_records > repeated.grows_records, "no vector growth announced") || + !check(distinct.grows_ids > repeated.grows_ids, "no bucket growth announced") || + !check(!distinct.missed, "a container grew without an announcement")) + return false; + + // Every announced growth has its log line. + const std::string log = read_log(); + const unsigned long long both = occurrences(log, "x2w-view-census before growth of records and ids:"); + const unsigned long long records = occurrences(log, "x2w-view-census before growth of records:") + both; + const unsigned long long ids = occurrences(log, "x2w-view-census before growth of ids:") + both; + std::printf("growth lines in the log: records %llu, ids %llu\n", records, ids); + return check(records == distinct.grows_records && ids == distinct.grows_ids, "growth lines and counters differ"); +} + +// With the switch off the same calls report nothing. +bool nothing_reported(const Streams& s) +{ + for (UINT i = 0; i < 1000; ++i) s.constant_buffer(i); + char line[256]; + std::memset(line, 'x', sizeof(line)); + const std::size_t length = x2w_d3d12_view_census_line(line, sizeof(line)); + return check(!length && !line[0], "the census reported without its switch") && + check(!occurrences(read_log(), "x2w-view-census"), "the census logged without its switch"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "vary"))) + return 2; + const bool off = argc == 3 && !std::strcmp(argv[2], "off"); + const bool vary = argc == 3 && !std::strcmp(argv[2], "vary"); + char value[2]{}; + const bool census_on = GetEnvironmentVariableA("X2W_D3D12_VIEW_CENSUS", value, sizeof(value)) == 1 && value[0] == '1'; + wchar_t log_path[MAX_PATH]; + const DWORD log_length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path, MAX_PATH); + if (census_on == off || !log_length || log_length >= MAX_PATH) { + std::puts("FAIL: the environment does not match the requested mode"); + return 2; + } + DeleteFileW(log_path); // before the stand-in writes its first line + + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr guest, views, samplers; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device")) + return 3; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } view_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}, sampler_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1}, 0, 0}; + if (!require(invoke(guest.Get(), 14, &view_heap, &__uuidof(ID3D12DescriptorHeap), views.GetAddressOf()), "view heap") || + !require(invoke(guest.Get(), 14, &sampler_heap, &__uuidof(ID3D12DescriptorHeap), samplers.GetAddressOf()), "sampler heap")) + return 3; + const Streams streams{guest.Get(), invoke(views.Get(), 9), invoke(samplers.Get(), 9)}; + + const unsigned long long held = process_commit(); + if (!held || !limit_commit(held + headroom)) { + std::printf("FAIL: could not set the job commit limit (error %lu)\n", GetLastError()); + return 4; + } + // The limit is real: a commit larger than the room under it is refused. + if (void* too_much = VirtualAlloc(nullptr, static_cast(headroom + held), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) { + VirtualFree(too_much, 0, MEM_RELEASE); + std::puts("FAIL: the job commit limit did not refuse an allocation above it"); + return 4; + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) std::printf("adapter=%ls\n", adapter_desc.Description); + std::printf("mode=%s, commit after setup %llu bytes, job limit %llu bytes\n", off ? "off" : vary ? "vary" : "on", held, + held + headroom); + if (!(off ? nothing_reported(streams) : scenario(streams, vary))) return 5; + std::puts(off ? "view-census off checks passed" : "view-census checks passed"); + return 0; +} From 99ed51fd998a3e7a5546288fed414beabd1d4815 Mon Sep 17 00:00:00 2001 From: dnn <55638248+denn0x@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:30:04 +0000 Subject: [PATCH 03/29] startup: lower v_pack_b32_f16 with op_sel and neg/abs in gfx2hlsl (#2475) * startup: lower v_pack_b32_f16 with op_sel and neg/abs in gfx2hlsl D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA, VOP3 V_PACK_B32_F16). op_sel[i] selects the high half of source i (LLVM 15: VOP3_OPSEL); neg and abs act on bit 15 of the selected half, abs first. The halves are copied as bits, as pixel_aot lowers the same instruction; no binary16 denormal flush or NaN quieting is modelled (assumed). Register sources only: an inline float constant on a binary16 operand is a binary16 value. A destination op_sel bit and clamp are refused. Test: tests/startup_gfx2hlsl_pack_b32_f16_check.py evaluates the emitted expression for every op_sel x abs x neg combination over sample register pairs against a bit reference (2304 cases), plus an SGPR source. Negative controls: swapped halves and neg-before-abs are caught by the reference; without the handler the instruction is refused, as on main. * gfx2hlsl: explain the low/high half reads and the strict op_sel spelling in v_pack_b32_f16 (comments only) * tests: verify packed binary16 output words on D3D12 --------- Co-authored-by: Royoo <3230853833@qq.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 9 ++ tests/startup_gfx2hlsl_pack_b32_f16_check.py | 141 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 38 +++++ 5 files changed, 190 insertions(+) create mode 100644 tests/startup_gfx2hlsl_pack_b32_f16_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 71eb71905..ef7f3e5e6 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -308,6 +308,7 @@ jobs: tests/startup_gfx2hlsl_mul_hi_check.py \ tests/startup_gfx2hlsl_sad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ + tests/startup_gfx2hlsl_pack_b32_f16_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ tests/startup_buffer_format_word3_table_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 89516ec2a..f9a68ef8d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -249,6 +249,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_signext_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_b32_f16_check.py ./out/pe-env/bin/python -B tests/run_checks_parallel_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 23e414ed9..522a02a4a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3250,6 +3250,9 @@ if(EXISTS "${INTAKE_PYTHON}") # s_brev_b32 of a known constant folds to a known word (a sampler built from it is a constant descriptor). add_test(NAME startup_gfx2hlsl_scalar_brev_fold COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_brev_fold_check.py") + # v_pack_b32_f16 with op_sel and the neg/abs source modifiers, evaluated against a bit reference. + add_test(NAME startup_gfx2hlsl_pack_b32_f16 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py") # Scalar sign-extends and conditional moves (batch 3 #2). add_test(NAME startup_gfx2hlsl_s_sext_cmov COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_sext_cmov_check.py") @@ -3420,6 +3423,12 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_u8_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_pack_b32_f16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_pack_b32_f16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 (#1723): VOP3A saturating 16-bit integer packs, encoding/refusal # controls, and WARP/hardware draws (FXC 5_1 and DXC 6_0) with four mutations per opcode. add_test(NAME startup_gfx2hlsl_cvt_pk_int16_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_gfx2hlsl_pack_b32_f16_check.py b/tests/startup_gfx2hlsl_pack_b32_f16_check.py new file mode 100644 index 000000000..071eddee7 --- /dev/null +++ b/tests/startup_gfx2hlsl_pack_b32_f16_check.py @@ -0,0 +1,141 @@ +"""v_pack_b32_f16 (VOP3) in tools/startup/gfx2hlsl.py: D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA). + +Synthetic VOP3 words (gfx10 opcode 0x311; op_sel in word 0 bits 14:11, abs in bits 10:8, clamp in bit 15, neg in +word 1 bits 31:29). The decoder reads each word back, and the test asserts the printed op_sel and modifier forms. +The emitted expression is evaluated in Python for every op_sel[0..1] x abs x neg combination over sample register +pairs. The reference written here selects the half (op_sel[i] = high half of source i), then applies abs (clear +bit 15) and then neg (flip bit 15). An SGPR source is accepted. +Controls (refused): a destination op_sel bit, clamp, an inline float constant and an inline integer source. +Negative controls: an expression with the halves swapped, or with neg applied before abs, is caught by the +reference; without op_v_pack_b32_f16 the instruction is refused, as on main. +The draw mode checks raw integer readback under DXC and FXC and rejects a lowering that omits negation. +""" +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vop3(vdst, s0, s1, opsel=0, absm=0, neg=0, clamp=0): + """s0 and s1 are 9-bit source fields: 256 + n is vN, n < 106 is sN, 128..208 and 240..248 inline constants.""" + return [0xd4000000 | 0x311 << 16 | clamp << 15 | opsel << 11 | absm << 8 | vdst, s0 | s1 << 9 | neg << 29] + + +def one(words): + s = G.Stage(Pipe(), 'vs', b'') + s.lines, s.pc = [], 0 + _, _, name, text = G.decode(struct.pack('<2I', *words))[0] + s.one(name, text) + return text, s.lines + + +def ev(expr, env): + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', expr) + return eval(py, {}, env) & 0xffffffff + + +def ref(a, b, sel, absm, neg, neg_first=False): + out = [] + for i, x in enumerate((a, b)): + h = (x >> 16) & 0xffff if sel >> i & 1 else x & 0xffff + if neg_first and neg >> i & 1: + h ^= 0x8000 + if absm >> i & 1: + h &= 0x7fff + if not neg_first and neg >> i & 1: + h ^= 0x8000 + out.append(h) + return out[0] | out[1] << 16 + + +VALUES = [0x00000000, 0x3c00bc00, 0x80017fff, 0xfc007e00, 0x12345678, 0xffff0001] + + +def refused(words, why): + try: + one(words) + except G.Unsupported as error: + assert why in str(error), str(error) + else: + raise AssertionError('accepted: %s' % why) + + +def main(): + cases = 0 + for sel in range(4): + for absm in range(4): + for neg in range(4): + text, lines = one(vop3(3, 257, 258, sel, absm, neg)) + assert text.startswith('v_pack_b32_f16 v3, '), text + assert ('op_sel:[%d,%d,0]' % (sel & 1, sel >> 1) in text) == bool(sel), text + m = re.fullmatch(r'v3 = (.*);', lines[0]) + assert m and len(lines) == 1, lines + for a in VALUES: + for b in VALUES: + got = ev(m.group(1), {'v1': a, 'v2': b}) + assert got == ref(a, b, sel, absm, neg), (text, hex(a), hex(b), hex(got)) + cases += 1 + if absm and neg & absm: + # The modifier order matters only where both act: the wrong order must be caught. + assert any(ev(m.group(1), {'v1': a, 'v2': b}) != ref(a, b, sel, absm, neg, neg_first=True) + for a in VALUES for b in VALUES), text + text, lines = one(vop3(3, 5, 258, 1)) # SGPR source, high half + assert text == 'v_pack_b32_f16 v3, s5, v2 op_sel:[1,0,0]', text + assert all(ev(lines[0][len('v3 = '):-1], {'s5': a, 'v2': b}) == ref(a, b, 1, 0, 0) + for a in VALUES for b in VALUES), lines + _, lines = one(vop3(3, 257, 258, 1)) + swapped = re.fullmatch(r'v3 = (.*) \| \((.*) << 16\);', lines[0]) + wrong = '%s | (%s << 16)' % (swapped.group(2), swapped.group(1)) + assert any(ev(wrong, {'v1': a, 'v2': b}) != ref(a, b, 1, 0, 0) for a in VALUES for b in VALUES) + refused(vop3(3, 257, 258, 4), 'v_pack_b32_f16 form') + refused(vop3(3, 257, 258, clamp=1), 'v_pack_b32_f16 modifier clamp') + refused(vop3(3, 242, 258), 'v_pack_b32_f16 source 1.0') + refused(vop3(3, 129, 258), 'v_pack_b32_f16 source 1') + saved = G.Stage.op_v_pack_b32_f16 + del G.Stage.op_v_pack_b32_f16 + try: + refused(vop3(3, 257, 258), 'v_pack_b32_f16') + finally: + G.Stage.op_v_pack_b32_f16 = saved + print('pack_b32_f16: %d (op_sel, abs, neg, value) cases match the reference; SGPR source accepted; swapped ' + 'halves and neg-before-abs caught; destination op_sel, clamp and constants refused; refused without the ' + 'handler' % cases) + + +def draw_cases(dxc, renderer, adapter, fxc=None): + from startup_gfx2hlsl_lane_alu import check_draw + + op = 'v_pack_b32_f16' + # The selected halves cover zeros, subnormals, infinities and NaN payloads as integer bits. + values = [ + (0x0000bc00, 0xa5a58000, 0), (0x80017e00, 0xf0f00001, 0), + (0xfc008001, 0xabcd7d55, 0), (0x7d337c00, 0xdcba7c00, 0), + ] + body = b''.join(struct.pack('<2I', *vop3(12 + lane, 256 + lane, 260 + lane, 1, 1, 1)) + for lane in range(4)) + family = { + 'ops': {op: (2, lambda a, b: ref(a, b, 1, 1, 1), False)}, + 'draw': {op: values}, + 'body': {op: body}, + 'mutations': {op: (r' \^ 0x8000u', '', lambda a, b: ref(a, b, 1, 1, 0))}, + 'accepted': [], + 'refused': [], + } + check_draw(family, dxc, renderer, adapter, fxc) + + +if __name__ == '__main__': + if len(sys.argv) > 1 and sys.argv[1] == 'draw': + draw_cases(*sys.argv[2:]) + else: + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a19e68b69..11a1552af 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5289,6 +5289,44 @@ def op_v_cvt_i32_f32(self, ops, mods): dst = reg_range(ops[0])[1] self.set_v(dst, 'uint(int(F(%s)))' % self.u(ops[1])) + def op_v_pack_b32_f16(self, ops, mods): + """D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA, VOP3 V_PACK_B32_F16). + + op_sel[i] selects the high half of source i (LLVM 15 VOP3Instructions.td: V_PACK_B32_F16 is VOP3_OPSEL). + The neg and abs source modifiers act on the sign bit (bit 15) of the selected half, abs first. The halves + are copied as bits, like pixel_aot's lowering of the same instruction: no binary16 denormal flush and no + NaN quieting is modelled (an assumption, not measured). Register sources only: an inline float constant + on a binary16 operand is a binary16 value, not the binary32 word u() would give. A destination op_sel bit + and clamp are refused, and so is any modifier other than the one op_sel:[a,b,c] spelling the decoder + prints.""" + sel = [0, 0, 0] + for m in mods: + match = re.fullmatch(r'op_sel:\[([01]),([01]),([01])\]', m) + if not match: + raise Unsupported('v_pack_b32_f16 modifier %s' % m) + sel = [int(x) for x in match.groups()] + dst = reg_range(ops[0]) if ops else None + if sel[2] or len(ops) != 3 or not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('v_pack_b32_f16 form %s %s' % (', '.join(ops), ' '.join(mods))) + halves = [] + for i, tok in enumerate(ops[1:3]): + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + tok = tok[1:] if neg else tok + absolute = tok.startswith('|') and tok.endswith('|') + tok = tok[1:-1] if absolute else tok + reg = reg_range(tok) + if not reg or reg[1] != reg[2] or reg[0] not in ('v', 's'): + raise Unsupported('v_pack_b32_f16 source %s' % ops[1 + i]) + # The high half needs the whole word; the low half reads only bits 15:0, so a register whose high half + # is undefined (after an odd-count d16 load) stays readable here. + half = '(%s >> 16)' % self.u(tok) if sel[i] else '(%s & 0xffffu)' % self.u(tok, low16_only=True) + if absolute: + half = '(%s & 0x7fffu)' % half + if neg: + half = '(%s ^ 0x8000u)' % half + halves.append(half) + self.set_v(dst[1], '%s | (%s << 16)' % (halves[0], halves[1])) + def op_v_cvt_pk_u8_f32(self, ops, mods): # VOP3A opcode 350 of the RDNA 1.0 and RDNA 2 ISA guides: # D = (S2 & ~(0xff << 8 * S1[1:0])) | ((flt32_to_uint8(S0) & 0xff) << 8 * S1[1:0]) From d371ce46c57bf972f225616d462f99486f323f77 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:31:05 +0200 Subject: [PATCH 04/29] cpu: lower 16 VEX.256 AVX2 cross-lane extend and dword/qword unpack forms (#2614) --- CMakeLists.txt | 23 ++ tests/cpu/avx_int_regs_check.py | 15 +- tests/cpu/avx_int_ymm_abs_sign_shuf_check.py | 4 +- tests/cpu/avx_int_ymm_widen_unpack.asm | 301 +++++++++++++++ tests/cpu/avx_int_ymm_widen_unpack.def | 25 ++ tests/cpu/avx_int_ymm_widen_unpack_check.py | 383 +++++++++++++++++++ tools/cpu_avx_int_aot.py | 136 +++++-- 7 files changed, 838 insertions(+), 49 deletions(-) create mode 100644 tests/cpu/avx_int_ymm_widen_unpack.asm create mode 100644 tests/cpu/avx_int_ymm_widen_unpack.def create mode 100644 tests/cpu/avx_int_ymm_widen_unpack_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 522a02a4a..a0ad7738b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5329,6 +5329,29 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_avx_int_ymm_pack PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_pack.txt") + # cpu_avx_int_ymm_widen_unpack_checks + set(cpu_avx_int_ymm_widen_unpack_exports + "op_vpmovsxbw_ymm,op_vpmovsxbd_ymm,op_vpmovsxbq_ymm,op_vpmovsxwd_ymm,op_vpmovsxwq_ymm,op_vpmovsxdq_ymm," + "op_vpmovzxbw_ymm,op_vpmovzxbd_ymm,op_vpmovzxbq_ymm,op_vpmovzxwd_ymm,op_vpmovzxwq_ymm,op_vpmovzxdq_ymm," + "op_vpunpckldq_ymm,op_vpunpckhdq_ymm,op_vpunpcklqdq_ymm,op_vpunpckhqdq_ymm," + "op_vpmovsxbd_ymm_stale_dst,op_vpmovsxbw_ymm_alias,op_vpmovzxdq_ymm_alias," + "op_vpunpckldq_ymm_dst_src1,op_vpunpckhqdq_ymm_dst_src2,op_vpunpckhdq_ymm_all," + "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq,op_chain_ymm_widen_unpack") + string(CONCAT cpu_avx_int_ymm_widen_unpack_exports ${cpu_avx_int_ymm_widen_unpack_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_int_ymm_widen_unpack_${variant} avx_int_ymm_widen_unpack) + cpu_translation(cpu_avx_int_ymm_widen_unpack_${variant} cpu_avx_int_aot "${cpu_avx_int_ymm_widen_unpack_exports}") + endforeach() + target_compile_definitions(cpu_avx_int_ymm_widen_unpack_altered PRIVATE ALTER_YMM) + add_test(NAME cpu_aot_avx_int_ymm_widen_unpack COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_int_ymm_widen_unpack_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_int_ymm_widen_unpack PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_widen_unpack.txt") set(cpu_avx_move_exports "op_andpd_xmm,op_andpd_ymm,op_andps_xmm,op_andps_ymm,op_andnpd_xmm,op_andnpd_ymm," "op_andnps_xmm,op_andnps_ymm,op_orpd_xmm,op_orpd_ymm,op_orps_xmm,op_orps_ymm," diff --git a/tests/cpu/avx_int_regs_check.py b/tests/cpu/avx_int_regs_check.py index c683c53ab..3a0d0d098 100644 --- a/tests/cpu/avx_int_regs_check.py +++ b/tests/cpu/avx_int_regs_check.py @@ -707,21 +707,22 @@ def check_rejections(original_path): # 1) VEX.L=1 (256-bit) packed-integer encodings of surviving forms must be rejected explicitly (AVX2, not AVX1). # The 256-bit add, subtract, saturating add and subtract, compare, minimum, maximum, absolute value, - # sign, word shuffle, horizontal, and pack forms are lowered and are covered by avx_int_ymm_addsub_check.py, - # avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, avx_int_ymm_abs_sign_shuf_check.py, - # avx_int_ymm_horizontal_check.py, and avx_int_ymm_pack_check.py. + # sign, word shuffle, horizontal, pack, cross-lane extend, and dword/qword unpack forms are lowered and + # covered by avx_int_ymm_addsub_check.py, avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, + # avx_int_ymm_abs_sign_shuf_check.py, avx_int_ymm_horizontal_check.py, avx_int_ymm_pack_check.py, + # and avx_int_ymm_widen_unpack_check.py. vex256_int_cases = [ ("vpmulhuw_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMULHUW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), - ("vpunpckhdq_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpsrld_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSRLD_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), ("vpalignr_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPALIGNR_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 4)), ("vpblendvb_ymm", Instruction.create_reg_reg_reg_reg(Code.VEX_VPBLENDVB_YMM_YMM_YMMM256_YMM, R.YMM0, R.YMM1, R.YMM2, R.YMM3)), ("vpblendw_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPBLENDW_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0xAA)), ("vpmaddwd_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMADDWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), ("vpmulld_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMULLD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), ("vmpsadbw_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VMPSADBW_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0)), - ("vpmovsxbw_ymm", Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM1)), - ("vpmovzxdq_ymm", Instruction.create_reg_reg(Code.VEX_VPMOVZXDQ_YMM_XMMM128, R.YMM0, R.XMM1)), - ("vpunpckldq_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpsrld_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSRLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), + ("vpsllq_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSLLQ_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), + ("vpsrlq_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSRLQ_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), ("vpslld_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSLLD_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), ("vpslld_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSLLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), ("vpsrlq_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSRLQ_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), diff --git a/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py b/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py index 07ae0dc61..f69a5589e 100644 --- a/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py +++ b/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py @@ -243,8 +243,8 @@ def check_translator(): "unsupported EVEX instruction"), ("vpshufhw_evex", (loads[0], Instruction.create_reg_reg_u32( Code.EVEX_VPSHUFHW_YMM_K1Z_YMMM256_IMM8, R.YMM0, R.YMM1, 0x1B), ret), "unsupported EVEX instruction"), - ("vpmovsxbw_ymm_xmm_source", (loads[0], Instruction.create_reg_reg( - Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM1), ret), "unsupported VEX.256 (L=1) packed-integer encoding"), + ("vpsrld_ymm_xmm_source", (*loads, Instruction.create_reg_reg_reg( + Code.VEX_VPSRLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2), ret), "unsupported VEX.256 (L=1) packed-integer encoding"), ("vpshufb_ymm_other_form", (*loads, Instruction.create_reg_reg_reg( Code.VEX_VPSHUFB_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported instruction"), ("vpalignr_ymm_other_form", (*loads, Instruction.create_reg_reg_reg_u32( diff --git a/tests/cpu/avx_int_ymm_widen_unpack.asm b/tests/cpu/avx_int_ymm_widen_unpack.asm new file mode 100644 index 000000000..6a4404912 --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack.asm @@ -0,0 +1,301 @@ +; coverage: source cpu_aot_avx_int_ymm_widen_unpack +; Source-owned differential fixture for 256-bit (VEX.L=1, AVX2) packed-integer +; cross-lane extend moves (VPMOVSX*/VPMOVZX*) and in-lane unpacks (VPUNPCK{L,H}{DQ,QDQ}). +; RCX = const void* input_a (32 bytes) +; RDX = const void* input_b (32 bytes) +; R8 = void* output (32 bytes) +.code + +op_vpmovsxbw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbw ymm0, xmm1 +ELSE + vpmovsxbw ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbw_ymm ENDP + +op_vpmovsxbd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbd ymm0, xmm1 +ELSE + vpmovsxbd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbd_ymm ENDP + +op_vpmovsxbq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbq ymm0, xmm1 +ELSE + vpmovsxbq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbq_ymm ENDP + +op_vpmovsxwd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxwd ymm0, xmm1 +ELSE + vpmovsxwd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwd_ymm ENDP + +op_vpmovsxwq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxwq ymm0, xmm1 +ELSE + vpmovsxwq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwq_ymm ENDP + +op_vpmovsxdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxdq ymm0, xmm1 +ELSE + vpmovsxdq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxdq_ymm ENDP + +op_vpmovzxbw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbw ymm0, xmm1 +ELSE + vpmovzxbw ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbw_ymm ENDP + +op_vpmovzxbd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbd ymm0, xmm1 +ELSE + vpmovzxbd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbd_ymm ENDP + +op_vpmovzxbq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbq ymm0, xmm1 +ELSE + vpmovzxbq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbq_ymm ENDP + +op_vpmovzxwd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxwd ymm0, xmm1 +ELSE + vpmovzxwd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxwd_ymm ENDP + +op_vpmovzxwq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxwq ymm0, xmm1 +ELSE + vpmovzxwq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxwq_ymm ENDP + +op_vpmovzxdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxdq ymm0, xmm1 +ELSE + vpmovzxdq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxdq_ymm ENDP + +op_vpunpckldq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckhdq ymm0, ymm1, ymm2 +ELSE + vpunpckldq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckldq_ymm ENDP + +op_vpunpckhdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckldq ymm0, ymm1, ymm2 +ELSE + vpunpckhdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckhdq_ymm ENDP + +op_vpunpcklqdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckhqdq ymm0, ymm1, ymm2 +ELSE + vpunpcklqdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpcklqdq_ymm ENDP + +op_vpunpckhqdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpcklqdq ymm0, ymm1, ymm2 +ELSE + vpunpckhqdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckhqdq_ymm ENDP + +op_vpmovsxbd_ymm_stale_dst PROC FRAME + .endprolog + vmovdqu ymm0, YMMWORD PTR [rdx] + vmovdqu ymm1, YMMWORD PTR [rcx] + vpmovsxbd ymm0, xmm1 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbd_ymm_stale_dst ENDP + +op_vpmovsxbw_ymm_alias PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vpmovsxbw ymm1, xmm1 + vmovdqu YMMWORD PTR [r8], ymm1 + vzeroupper + ret +op_vpmovsxbw_ymm_alias ENDP + +op_vpmovzxdq_ymm_alias PROC FRAME + .endprolog + vmovdqu ymm2, YMMWORD PTR [rcx] + vpmovzxdq ymm2, xmm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpmovzxdq_ymm_alias ENDP + +op_vpunpckldq_ymm_dst_src1 PROC FRAME + .endprolog + vmovdqu ymm3, YMMWORD PTR [rcx] + vmovdqu ymm4, YMMWORD PTR [rdx] + vpunpckldq ymm3, ymm3, ymm4 + vmovdqu YMMWORD PTR [r8], ymm3 + vzeroupper + ret +op_vpunpckldq_ymm_dst_src1 ENDP + +op_vpunpckhqdq_ymm_dst_src2 PROC FRAME + .endprolog + vmovdqu ymm4, YMMWORD PTR [rcx] + vmovdqu ymm5, YMMWORD PTR [rdx] + vpunpckhqdq ymm5, ymm4, ymm5 + vmovdqu YMMWORD PTR [r8], ymm5 + vzeroupper + ret +op_vpunpckhqdq_ymm_dst_src2 ENDP + +op_vpunpckhdq_ymm_all PROC FRAME + .endprolog + vmovdqu ymm2, YMMWORD PTR [rcx] + vpunpckhdq ymm2, ymm2, ymm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpunpckhdq_ymm_all ENDP + +op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpmovsxwd ymm0, xmm1 + vpunpcklqdq xmm0, xmm0, xmm2 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq ENDP + +op_chain_ymm_widen_unpack PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpmovsxwd ymm3, xmm1 + vpmovzxbd ymm4, xmm2 + vpunpckldq ymm0, ymm3, ymm4 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_chain_ymm_widen_unpack ENDP + +END diff --git a/tests/cpu/avx_int_ymm_widen_unpack.def b/tests/cpu/avx_int_ymm_widen_unpack.def new file mode 100644 index 000000000..3935ba5a4 --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack.def @@ -0,0 +1,25 @@ +EXPORTS + op_vpmovsxbw_ymm + op_vpmovsxbd_ymm + op_vpmovsxbq_ymm + op_vpmovsxwd_ymm + op_vpmovsxwq_ymm + op_vpmovsxdq_ymm + op_vpmovzxbw_ymm + op_vpmovzxbd_ymm + op_vpmovzxbq_ymm + op_vpmovzxwd_ymm + op_vpmovzxwq_ymm + op_vpmovzxdq_ymm + op_vpunpckldq_ymm + op_vpunpckhdq_ymm + op_vpunpcklqdq_ymm + op_vpunpckhqdq_ymm + op_vpmovsxbd_ymm_stale_dst + op_vpmovsxbw_ymm_alias + op_vpmovzxdq_ymm_alias + op_vpunpckldq_ymm_dst_src1 + op_vpunpckhqdq_ymm_dst_src2 + op_vpunpckhdq_ymm_all + op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq + op_chain_ymm_widen_unpack diff --git a/tests/cpu/avx_int_ymm_widen_unpack_check.py b/tests/cpu/avx_int_ymm_widen_unpack_check.py new file mode 100644 index 000000000..e1d10328a --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack_check.py @@ -0,0 +1,383 @@ +"""Differential, boundary, mutation, and rejection checks for 256-bit AVX2 extend and unpack ops.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import sys + +from iced_x86 import Code, Decoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from avx_int_ymm_minmax_check import encode_seq, first_bad_word, invoke, load # noqa: E402 +from avx_int_ymm_pack_check import host_has_avx2 # noqa: E402 +from cpu_avx_int_aot import lift_code # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXTEND_SPECS = { + # export: (signed, src_width_bytes, dst_width_bytes) + "op_vpmovsxbw_ymm": (True, 1, 2), + "op_vpmovsxbd_ymm": (True, 1, 4), + "op_vpmovsxbq_ymm": (True, 1, 8), + "op_vpmovsxwd_ymm": (True, 2, 4), + "op_vpmovsxwq_ymm": (True, 2, 8), + "op_vpmovsxdq_ymm": (True, 4, 8), + "op_vpmovzxbw_ymm": (False, 1, 2), + "op_vpmovzxbd_ymm": (False, 1, 4), + "op_vpmovzxbq_ymm": (False, 1, 8), + "op_vpmovzxwd_ymm": (False, 2, 4), + "op_vpmovzxwq_ymm": (False, 2, 8), + "op_vpmovzxdq_ymm": (False, 4, 8), +} +UNPACK_EXPORTS = ( + "op_vpunpckldq_ymm", + "op_vpunpckhdq_ymm", + "op_vpunpcklqdq_ymm", + "op_vpunpckhqdq_ymm", +) +BASE_EXPORTS = tuple(EXTEND_SPECS) + UNPACK_EXPORTS +SPECIAL_EXPORTS = ( + "op_vpmovsxbd_ymm_stale_dst", + "op_vpmovsxbw_ymm_alias", + "op_vpmovzxdq_ymm_alias", + "op_vpunpckldq_ymm_dst_src1", + "op_vpunpckhqdq_ymm_dst_src2", + "op_vpunpckhdq_ymm_all", + "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", + "op_chain_ymm_widen_unpack", +) +EXPORTS = BASE_EXPORTS + SPECIAL_EXPORTS + +_FMT_SIGNED = {1: "b", 2: "h", 4: "i", 8: "q"} +_FMT_UNSIGNED = {1: "B", 2: "H", 4: "I", 8: "Q"} + + +# --- Independent Python reference: cross-lane XMM->YMM extend & per-128-bit-lane unpack --- + +def _ref_extend(is_signed, src_w, dst_w, a): + count = 32 // dst_w + in_fmt = (_FMT_SIGNED if is_signed else _FMT_UNSIGNED)[src_w] + out_fmt = (_FMT_SIGNED if is_signed else _FMT_UNSIGNED)[dst_w] + vals = struct.unpack(f"<{count}{in_fmt}", a[:count * src_w]) + return struct.pack(f"<{count}{out_fmt}", *vals) + + +def _unpack_half(kind, a16, b16): + if kind in ("ldq", "hdq"): + xs = struct.unpack("<4I", a16) + ys = struct.unpack("<4I", b16) + off = 0 if kind == "ldq" else 2 + return struct.pack("<4I", xs[off], ys[off], xs[off + 1], ys[off + 1]) + if kind in ("lqdq", "hqdq"): + xs = struct.unpack("<2Q", a16) + ys = struct.unpack("<2Q", b16) + idx = 0 if kind == "lqdq" else 1 + return struct.pack("<2Q", xs[idx], ys[idx]) + raise ValueError(kind) + + +def _ref_unpack(kind, a, b): + return _unpack_half(kind, a[:16], b[:16]) + _unpack_half(kind, a[16:32], b[16:32]) + + +def reference(name, a, b): + if name in EXTEND_SPECS: + return _ref_extend(*EXTEND_SPECS[name], a) + if name == "op_vpmovsxbd_ymm_stale_dst": + return _ref_extend(True, 1, 4, a) + if name == "op_vpmovsxbw_ymm_alias": + return _ref_extend(True, 1, 2, a) + if name == "op_vpmovzxdq_ymm_alias": + return _ref_extend(False, 4, 8, a) + if name in ("op_vpunpckldq_ymm", "op_vpunpckldq_ymm_dst_src1"): + return _ref_unpack("ldq", a, b) + if name == "op_vpunpckhdq_ymm": + return _ref_unpack("hdq", a, b) + if name == "op_vpunpckhdq_ymm_all": + return _ref_unpack("hdq", a, a) + if name == "op_vpunpcklqdq_ymm": + return _ref_unpack("lqdq", a, b) + if name in ("op_vpunpckhqdq_ymm", "op_vpunpckhqdq_ymm_dst_src2"): + return _ref_unpack("hqdq", a, b) + if name == "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq": + t = _ref_extend(True, 2, 4, a) + return _unpack_half("lqdq", t[:16], b[:16]) + b"\x00" * 16 + if name == "op_chain_ymm_widen_unpack": + t3 = _ref_extend(True, 2, 4, a) + t4 = _ref_extend(False, 1, 4, b) + return _ref_unpack("ldq", t3, t4) + raise KeyError(name) + + +def all_pairs(): + """Construct sign-boundary vectors with non-zero ignored XMM/YMM upper bytes plus random.""" + pairs = [] + b_edges = (0x00, 0x01, 0x7F, 0x80, 0x81, 0xFE, 0xFF) + w_edges = (0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF) + d_edges = (0x00000000, 0x00000001, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF) + + for shift in range(len(b_edges)): + a = bytes(b_edges[(i + shift) % len(b_edges)] for i in range(32)) + b = bytes(b_edges[(3 * i + shift + 1) % len(b_edges)] for i in range(32)) + pairs.append((a, b)) + for shift in range(len(w_edges)): + a = struct.pack("<16H", *(w_edges[(i + shift) % len(w_edges)] for i in range(16))) + b = struct.pack("<16H", *(w_edges[(3 * i + shift + 2) % len(w_edges)] for i in range(16))) + pairs.append((a, b)) + for shift in range(len(d_edges)): + a = struct.pack("<8I", *(d_edges[(i + shift) % len(d_edges)] for i in range(8))) + b = struct.pack("<8I", *(d_edges[(3 * i + shift + 2) % len(d_edges)] for i in range(8))) + pairs.append((a, b)) + + # Distinct non-zero high bytes in xmm (bytes 4..15) and upper ymm lane (bytes 16..31). + pairs.append((bytes(range(0x10, 0x30)), bytes(range(0xA0, 0xC0)))) + pairs.append((bytes(0x80 + i for i in range(32)), bytes(0x7F - i for i in range(32)))) + pairs.append((bytes(32), bytes(32))) + pairs.append((b"\xff" * 32, b"\xff" * 32)) + pairs.append((b"\x80" * 16 + b"\x55" * 16, b"\x7f" * 16 + b"\xaa" * 16)) + + rng = random.Random(0x57DE9) + pairs += [(rng.randbytes(32), rng.randbytes(32)) for _ in range(160)] + return pairs + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def check_translator(): + ret = Instruction.create(Code.RETNQ) + ymm_loads = (load(R.YMM1, R.RCX), load(R.YMM2, R.RDX)) + xmm_loads = ( + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)), + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)), + ) + + extend_codes = { + "VPMOVSXBW": Code.VEX_VPMOVSXBW_YMM_XMMM128, + "VPMOVSXBD": Code.VEX_VPMOVSXBD_YMM_XMMM64, + "VPMOVSXBQ": Code.VEX_VPMOVSXBQ_YMM_XMMM32, + "VPMOVSXWD": Code.VEX_VPMOVSXWD_YMM_XMMM128, + "VPMOVSXWQ": Code.VEX_VPMOVSXWQ_YMM_XMMM64, + "VPMOVSXDQ": Code.VEX_VPMOVSXDQ_YMM_XMMM128, + "VPMOVZXBW": Code.VEX_VPMOVZXBW_YMM_XMMM128, + "VPMOVZXBD": Code.VEX_VPMOVZXBD_YMM_XMMM64, + "VPMOVZXBQ": Code.VEX_VPMOVZXBQ_YMM_XMMM32, + "VPMOVZXWD": Code.VEX_VPMOVZXWD_YMM_XMMM128, + "VPMOVZXWQ": Code.VEX_VPMOVZXWQ_YMM_XMMM64, + "VPMOVZXDQ": Code.VEX_VPMOVZXDQ_YMM_XMMM128, + } + accepted = 0 + for name, code in extend_codes.items(): + source, _ = lift_code( + name, 0x1000, encode_seq(xmm_loads[0], Instruction.create_reg_reg(code, R.YMM0, R.XMM1), ret)) + assert f"ymm0 = op_{name.lower()}_ymm(ymm1);" in source, name + # Aliased dst == src with YMM source loaded must also lift cleanly. + alias_src, _ = lift_code( + f"{name}_alias", 0x1000, encode_seq(ymm_loads[0], Instruction.create_reg_reg(code, R.YMM1, R.XMM1), ret)) + assert f"ymm1 = op_{name.lower()}_ymm(ymm1);" in alias_src, name + accepted += 1 + + for name in ("VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ"): + code = getattr(Code, f"VEX_{name}_YMM_YMM_YMMM256") + source, _ = lift_code( + name, 0x1000, encode_seq(*ymm_loads, Instruction.create_reg_reg_reg(code, R.YMM0, R.YMM1, R.YMM2), ret)) + assert f"wide128(op_{name.lower()}, ymm1, ymm2)" in source, name + accepted += 1 + + # 128-bit forms keep their 128-bit single-helper path. + src_ext128, _ = lift_code( + "xmm_vpmovsxbw", 0x1000, + encode_seq(xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_XMM_XMMM64, R.XMM0, R.XMM1), ret)) + assert "ymm0 = op_vpmovsxbw(ymm1);" in src_ext128 and "_ymm" not in src_ext128 + src_unpck128, _ = lift_code( + "xmm_vpunpckldq", 0x1000, + encode_seq(*xmm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret)) + assert "ymm0 = op_vpunpckldq(ymm1, ymm2);" in src_unpck128 and "wide128" not in src_unpck128 + + mem_err = "unsupported memory operand for register-domain AVX integer instruction" + mem = MemoryOperand(R.RDX) + cases = [] + for name, code in extend_codes.items(): + cases.append((f"{name.lower()}_mem", (Instruction.create_reg_mem(code, R.YMM0, mem), ret), mem_err)) + for name in ("VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ"): + code = getattr(Code, f"VEX_{name}_YMM_YMM_YMMM256") + cases.append((f"{name.lower()}_mem", (ymm_loads[0], Instruction.create_reg_reg_mem(code, R.YMM0, R.YMM1, mem), ret), mem_err)) + + cases += [ + # EVEX variants + ("vpmovsxbw_evex", (xmm_loads[0], Instruction.create_reg_reg(Code.EVEX_VPMOVSXBW_YMM_K1Z_XMMM128, R.YMM0, R.XMM1), ret), + "unsupported EVEX instruction"), + ("vpmovzxdq_evex", (xmm_loads[0], Instruction.create_reg_reg(Code.EVEX_VPMOVZXDQ_YMM_K1Z_XMMM128, R.YMM0, R.XMM1), ret), + "unsupported EVEX instruction"), + ("vpunpckldq_evex", (*ymm_loads, Instruction.create_reg_reg_reg(Code.EVEX_VPUNPCKLDQ_YMM_K1Z_YMM_YMMM256B32, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + ("vpunpckhqdq_evex", (*ymm_loads, Instruction.create_reg_reg_reg(Code.EVEX_VPUNPCKHQDQ_YMM_K1Z_YMM_YMMM256B64, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + # Nonvolatile YMM6..15 / XMM6..15 + ("vpmovsxbd_nonvol_dst", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVSXBD_YMM_XMMM64, R.YMM6, R.XMM1), ret), + "nonvolatile vector register"), + ("vpmovzxwq_nonvol_src", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVZXWQ_YMM_XMMM64, R.YMM0, R.XMM7), ret), + "nonvolatile vector register"), + ("vpunpckldq_nonvol_dst", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_YMM_YMM_YMMM256, R.YMM8, R.YMM1, R.YMM2), ret), + "nonvolatile vector register"), + ("vpunpcklqdq_nonvol_src2", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLQDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM15), ret), + "nonvolatile vector register"), + # Unlowered YMM unpack forms whose 128-bit encodings are carved out to cpu_vex_aot.py + ("vpunpcklbw_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLBW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpckhbw_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHBW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpcklwd_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpckhwd_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + # Undefined sources + ("vpmovsxbw_undef_src", (Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM3), ret), + "undefined vector register ymm3"), + ("vpunpckhdq_undef_src2", (ymm_loads[0], Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM3), ret), + "undefined vector register ymm3"), + # Missing terminal ret + ("vpmovzxdq_missing_ret", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVZXDQ_YMM_XMMM128, R.YMM0, R.XMM1)), + "missing terminal ret"), + ] + for label, seq, reason in cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted a rejected control") + return accepted, len(cases) + + +def check_differential(native, lifted, altered, altered_lifted): + pairs = all_pairs() + total = 0 + for name in EXPORTS: + for index, (a, b) in enumerate(pairs): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b) + if got != want: + raise AssertionError( + f"{label} {name} case {index} word {first_bad_word(got, want)}: " + f"got {got.hex()} expected {want.hex()}") + total += 1 + + # Unaligned input and output buffers; guard bytes must remain intact. + a, b = pairs[len(pairs) // 2] + for name in EXPORTS: + for a_offset, out_offset in ((1, 0), (0, 3), (7, 5)): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b, a_offset, out_offset) + if got != want: + raise AssertionError(f"{label} {name} offsets {a_offset}/{out_offset}") + total += 1 + + # Altered build checks: swapped ops match altered native and diverge from original. + for name in BASE_EXPORTS: + changed = 0 + for a, b in pairs: + alt_nat = invoke(altered[name], a, b) + alt_lif = invoke(altered_lifted[name], a, b) + if alt_lif != alt_nat: + raise AssertionError(f"altered {name}: lifted differs from native") + changed += alt_nat != invoke(native[name], a, b) + if not changed: + raise AssertionError(f"altered build did not diverge on {name}") + + # Mutant Python models: must fail against lifted in the expected 64-bit words. + zero16 = b"\x00" * 16 + mutants = [ + # Upper 128-bit half dropped on extend and unpack + ("op_vpmovsxbw_ymm", lambda x, _y: reference("op_vpmovsxbw_ymm", x, _y)[:16] + zero16, {2, 3}), + ("op_vpunpckldq_ymm", lambda x, y: reference("op_vpunpckldq_ymm", x, y)[:16] + zero16, {2, 3}), + # Lower 128-bit extend duplicated into upper 128-bit lane instead of cross-lane slicing + ("op_vpmovsxbw_ymm", lambda x, _y: reference("op_vpmovsxbw_ymm", x, _y)[:16] * 2, {2, 3}), + ("op_vpmovzxbd_ymm", lambda x, _y: reference("op_vpmovzxbd_ymm", x, _y)[:16] * 2, {2, 3}), + ("op_vpmovsxdq_ymm", lambda x, _y: reference("op_vpmovsxdq_ymm", x, _y)[:16] * 2, {2, 3}), + # Stale upper YMM bits (bytes 16..31) erroneously read for upper half + ("op_vpmovsxbw_ymm", lambda x, _y: _ref_extend(True, 1, 2, x)[:16] + _ref_extend(True, 1, 2, x[16:])[:16], {2, 3}), + # Wrong sign/zero extension + ("op_vpmovsxbd_ymm", lambda x, y: reference("op_vpmovzxbd_ymm", x, y), {0, 1, 2, 3}), + ("op_vpmovzxwq_ymm", lambda x, y: reference("op_vpmovsxwq_ymm", x, y), {0, 1, 2, 3}), + # Ignored upper XMM bytes (bytes 8..15) erroneously read for *BD + ("op_vpmovsxbd_ymm", lambda x, _y: _ref_extend(True, 1, 4, x[8:]), {0, 1, 2, 3}), + # Cross-lane or swapped unpacks + ("op_vpunpckldq_ymm", lambda x, y: reference("op_vpunpckhdq_ymm", x, y), {0, 1, 2, 3}), + ("op_vpunpcklqdq_ymm", lambda x, y: reference("op_vpunpckhqdq_ymm", x, y), {0, 1, 2, 3}), + ("op_vpunpckldq_ymm", + lambda x, y: _unpack_half("ldq", x[:16], y[:16]) + _unpack_half("ldq", x[:16], y[:16]), {2, 3}), + # Missing VEX.128 upper-half zeroing after YMM extend + ("op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", + lambda x, y: reference("op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", x, y)[:16] + _ref_extend(True, 2, 4, x)[16:], + {2, 3}), + ] + for name, wrong, allowed_words in mutants: + bad_words = set() + for x, y in pairs: + w = first_bad_word(invoke(lifted[name], x, y), wrong(x, y)) + if w is not None: + bad_words.add(w) + if not bad_words or not bad_words <= allowed_words: + raise AssertionError( + f"mutant on {name}: bad words {sorted(bad_words)}, expected subset of {sorted(allowed_words)}") + + return total, len(mutants), len(BASE_EXPORTS) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + + accepted, rejected = check_translator() + print(f"{accepted} 256-bit extend/unpack forms accepted; {rejected} rejection controls passed") + + lifted_lib, lifted = bind(lifted_path, "lifted_") + if not host_has_avx2(lifted_lib): + print("Host lacks CPUID.01H:ECX[28] + XGETBV + CPUID.07H:EBX[5] AVX2; skipping native differential check") + sys.exit(77) + + _, native = bind(original_path, "") + _, altered = bind(altered_path, "") + _, altered_lifted = bind(altered_lifted_path, "lifted_") + total, caught, altered_count = check_differential(native, lifted, altered, altered_lifted) + print(f"{total} native/lifted/reference cases across {len(EXPORTS)} exports matched bit for bit; " + f"{caught} mutant controls + {altered_count} altered-build controls caught") + + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_avx_int_aot.py b/tools/cpu_avx_int_aot.py index 0e67cda33..7f1d4b03b 100644 --- a/tools/cpu_avx_int_aot.py +++ b/tools/cpu_avx_int_aot.py @@ -40,6 +40,9 @@ - 256-bit (VEX.L=1, AVX2, register operands only) pack with saturation: vpacksswb, vpackssdw, vpackusdw. Each 128-bit lane is computed independently (128-bit vpackuswb stays with cpu_vex_aot.py). + - 256-bit (VEX.L=1, AVX2, register operands only) cross-lane extend: vpmovsxbw/bd/bq/wd/wq/dq, + vpmovzxbw/bd/bq/wd/wq/dq (XMM low 128 bits -> YMM 256 bits; upper source bits ignored). + - 256-bit (VEX.L=1, AVX2, register operands only) in-lane unpack: vpunpckldq/hdq/lqdq/hqdq. Transport/ABI glue: vmovdqu (128/256-bit flat load, store and register copy), flat 32/64-bit GPR load/store mov for scratch GPRs, and terminal ret. @@ -95,6 +98,7 @@ "vphaddw", "vphaddd", "vphaddsw", "vphsubw", "vphsubd", "vphsubsw", "vpmuldq", "vpmuludq", "vpmulhrsw", "vpsadbw", "vpacksswb", "vpackssdw", "vpackusdw", + "vpunpckldq", "vpunpckhdq", "vpunpcklqdq", "vpunpckhqdq", ) } WIDE_BINARY_CODES = { @@ -112,6 +116,7 @@ "VPHADDW", "VPHADDD", "VPHADDSW", "VPHSUBW", "VPHSUBD", "VPHSUBSW", "VPMULDQ", "VPMULUDQ", "VPMULHRSW", "VPSADBW", "VPACKSSWB", "VPACKSSDW", "VPACKUSDW", + "VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ", ) } # 256-bit one-source forms: the 128-bit helper runs on each half. vpshufhw/vpshuflw use the @@ -128,6 +133,28 @@ WIDE_UNARY_IMM_CODES = { getattr(Code, f"VEX_{name}_YMM_YMMM256_IMM8") for name in ("VPSHUFHW", "VPSHUFLW") } +# 256-bit cross-lane sign/zero-extend moves (XMM low 128 bits -> YMM 256 bits). +WIDE_EXTEND_HELPERS = { + getattr(M, name.upper()): f"op_{name}_ymm" + for name in ( + "vpmovsxbw", "vpmovsxbd", "vpmovsxbq", "vpmovsxwd", "vpmovsxwq", "vpmovsxdq", + "vpmovzxbw", "vpmovzxbd", "vpmovzxbq", "vpmovzxwd", "vpmovzxwq", "vpmovzxdq", + ) +} +WIDE_EXTEND_CODES = { + Code.VEX_VPMOVSXBW_YMM_XMMM128, + Code.VEX_VPMOVSXBD_YMM_XMMM64, + Code.VEX_VPMOVSXBQ_YMM_XMMM32, + Code.VEX_VPMOVSXWD_YMM_XMMM128, + Code.VEX_VPMOVSXWQ_YMM_XMMM64, + Code.VEX_VPMOVSXDQ_YMM_XMMM128, + Code.VEX_VPMOVZXBW_YMM_XMMM128, + Code.VEX_VPMOVZXBD_YMM_XMMM64, + Code.VEX_VPMOVZXBQ_YMM_XMMM32, + Code.VEX_VPMOVZXWD_YMM_XMMM128, + Code.VEX_VPMOVZXWQ_YMM_XMMM64, + Code.VEX_VPMOVZXDQ_YMM_XMMM128, +} # Unary: dst = helper(src) UNARY_HELPERS = { @@ -379,7 +406,7 @@ } -ALLOWED_CODES |= WIDE_BINARY_CODES | WIDE_UNARY_CODES | WIDE_UNARY_IMM_CODES +ALLOWED_CODES |= WIDE_BINARY_CODES | WIDE_UNARY_CODES | WIDE_UNARY_IMM_CODES | WIDE_EXTEND_CODES PRELUDE = """#include @@ -1092,68 +1119,91 @@ // --- Sign-extend and zero-extend moves --- -static Vec256 op_vpmovsxbw(const Vec256& a) { +static Vec256 extend_bw(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 8u; ++i) set_lane16(out, i, static_cast(static_cast(s8(lane8(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + set_lane16(out, i, sign_ext ? static_cast(static_cast(s8(u))) + : static_cast(u)); + } return out; } -static Vec256 op_vpmovsxbd(const Vec256& a) { +static Vec256 extend_bd(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, static_cast(static_cast(s8(lane8(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + set_lane32(out, i, sign_ext ? static_cast(static_cast(s8(u))) + : static_cast(u)); + } return out; } -static Vec256 op_vpmovsxbq(const Vec256& a) { - return {{static_cast(static_cast(s8(lane8(a, 0u)))), - static_cast(static_cast(s8(lane8(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovsxwd(const Vec256& a) { +static Vec256 extend_bq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, static_cast(static_cast(s16(lane16(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + out.q[i] = sign_ext ? static_cast(static_cast(s8(u))) + : static_cast(u); + } return out; } -static Vec256 op_vpmovsxwq(const Vec256& a) { - return {{static_cast(static_cast(s16(lane16(a, 0u)))), - static_cast(static_cast(s16(lane16(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovsxdq(const Vec256& a) { - return {{static_cast(static_cast(s32(lane32(a, 0u)))), - static_cast(static_cast(s32(lane32(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxbw(const Vec256& a) { +static Vec256 extend_wd(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 8u; ++i) set_lane16(out, i, lane8(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint16_t u = lane16(a, i); + set_lane32(out, i, sign_ext ? static_cast(static_cast(s16(u))) + : static_cast(u)); + } return out; } -static Vec256 op_vpmovzxbd(const Vec256& a) { +static Vec256 extend_wq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, lane8(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint16_t u = lane16(a, i); + out.q[i] = sign_ext ? static_cast(static_cast(s16(u))) + : static_cast(u); + } return out; } -static Vec256 op_vpmovzxbq(const Vec256& a) { - return {{lane8(a, 0u), lane8(a, 1u), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxwd(const Vec256& a) { +static Vec256 extend_dq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, lane16(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint32_t u = lane32(a, i); + out.q[i] = sign_ext ? static_cast(static_cast(s32(u))) + : static_cast(u); + } return out; } -static Vec256 op_vpmovzxwq(const Vec256& a) { - return {{lane16(a, 0u), lane16(a, 1u), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxdq(const Vec256& a) { - return {{lane32(a, 0u), lane32(a, 1u), 0ull, 0ull}}; -} +static Vec256 op_vpmovsxbw(const Vec256& a) { return extend_bw(a, 8u, true); } +static Vec256 op_vpmovsxbd(const Vec256& a) { return extend_bd(a, 4u, true); } +static Vec256 op_vpmovsxbq(const Vec256& a) { return extend_bq(a, 2u, true); } +static Vec256 op_vpmovsxwd(const Vec256& a) { return extend_wd(a, 4u, true); } +static Vec256 op_vpmovsxwq(const Vec256& a) { return extend_wq(a, 2u, true); } +static Vec256 op_vpmovsxdq(const Vec256& a) { return extend_dq(a, 2u, true); } +static Vec256 op_vpmovzxbw(const Vec256& a) { return extend_bw(a, 8u, false); } +static Vec256 op_vpmovzxbd(const Vec256& a) { return extend_bd(a, 4u, false); } +static Vec256 op_vpmovzxbq(const Vec256& a) { return extend_bq(a, 2u, false); } +static Vec256 op_vpmovzxwd(const Vec256& a) { return extend_wd(a, 4u, false); } +static Vec256 op_vpmovzxwq(const Vec256& a) { return extend_wq(a, 2u, false); } +static Vec256 op_vpmovzxdq(const Vec256& a) { return extend_dq(a, 2u, false); } + +static Vec256 op_vpmovsxbw_ymm(const Vec256& a) { return extend_bw(a, 16u, true); } +static Vec256 op_vpmovsxbd_ymm(const Vec256& a) { return extend_bd(a, 8u, true); } +static Vec256 op_vpmovsxbq_ymm(const Vec256& a) { return extend_bq(a, 4u, true); } +static Vec256 op_vpmovsxwd_ymm(const Vec256& a) { return extend_wd(a, 8u, true); } +static Vec256 op_vpmovsxwq_ymm(const Vec256& a) { return extend_wq(a, 4u, true); } +static Vec256 op_vpmovsxdq_ymm(const Vec256& a) { return extend_dq(a, 4u, true); } +static Vec256 op_vpmovzxbw_ymm(const Vec256& a) { return extend_bw(a, 16u, false); } +static Vec256 op_vpmovzxbd_ymm(const Vec256& a) { return extend_bd(a, 8u, false); } +static Vec256 op_vpmovzxbq_ymm(const Vec256& a) { return extend_bq(a, 4u, false); } +static Vec256 op_vpmovzxwd_ymm(const Vec256& a) { return extend_wd(a, 8u, false); } +static Vec256 op_vpmovzxwq_ymm(const Vec256& a) { return extend_wq(a, 4u, false); } +static Vec256 op_vpmovzxdq_ymm(const Vec256& a) { return extend_dq(a, 4u, false); } // --- Unpack / interleave --- @@ -1379,7 +1429,8 @@ def write_gpr(op_index, ins): wide_unary = ins.code in WIDE_UNARY_CODES wide_unary_imm = ins.code in WIDE_UNARY_IMM_CODES wide_binary = ins.code in WIDE_BINARY_CODES - wide_any = wide_unary or wide_unary_imm or wide_binary + wide_extend = ins.code in WIDE_EXTEND_CODES + wide_any = wide_unary or wide_unary_imm or wide_binary or wide_extend if (mnemonic in AVX_INT_128_ONLY_MNEMONICS and not wide_any and op_code.encoding == EncodingKind.VEX and op_code.l == 1): raise ValueError(f"unsupported VEX.256 (L=1) packed-integer encoding at RVA {ins.ip:#x}: {ins}") @@ -1445,6 +1496,11 @@ def write_gpr(op_index, ins): statements.append( f"{dst} = wide128_unary_imm({WIDE_UNARY_IMM_HELPERS[mnemonic]}, {src}, {imm:#x}u);") defined_vec.add(dst_idx) + elif wide_extend: + src, _ = read_vec(1, ins) + dst_idx, dst, _ = write_vec(0, ins, allow_ymm=True) + statements.append(f"{dst} = {WIDE_EXTEND_HELPERS[mnemonic]}({src});") + defined_vec.add(dst_idx) elif mnemonic in UNARY_HELPERS: src, _ = read_vec(1, ins) dst_idx, dst, _ = write_vec(0, ins) From 780c0bc492b21a9853af7fdde6e200ee0437ad7e Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:33:06 +0200 Subject: [PATCH 05/29] cpu: lower 32/64-bit BMI2 BZHI, MULX, PDEP, and PEXT in cpu_bmi2_bit_aot (#2621) --- CMakeLists.txt | 26 + tests/cpu/bmi2_bit_aot.asm | 303 +++++++++++ tests/cpu/bmi2_bit_aot.def | 27 + tests/cpu/bmi2_bit_aot_check.py | 854 ++++++++++++++++++++++++++++++++ tools/cpu_bmi2_bit_aot.py | 688 +++++++++++++++++++++++++ 5 files changed, 1898 insertions(+) create mode 100644 tests/cpu/bmi2_bit_aot.asm create mode 100644 tests/cpu/bmi2_bit_aot.def create mode 100644 tests/cpu/bmi2_bit_aot_check.py create mode 100644 tools/cpu_bmi2_bit_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a0ad7738b..fb058175c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6542,6 +6542,32 @@ if(EXISTS "${INTAKE_PYTHON}") SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_shift.txt") + # cpu_aot_bmi2_bit + set(cpu_bmi2_bit_exports + "op_bzhi32,op_bzhi64,op_mulx32,op_mulx64,op_mulx32_alias,op_mulx64_alias," + "op_pdep32,op_pdep64,op_pext32,op_pext64," + "op_bzhi32_mem,op_bzhi64_mem,op_mulx32_mem,op_mulx64_mem," + "op_pdep32_mem,op_pdep64_mem,op_pext32_mem,op_pext64_mem," + "op_mem_r8_source,op_bzhi32_flags,op_bzhi64_flags," + "op_flags_preserve32,op_flags_preserve64,op_flags_preserve_pf," + "op_flags_preserve_mem,op_bmi2_bit_discarded_read") + string(CONCAT cpu_bmi2_bit_exports ${cpu_bmi2_bit_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_bmi2_bit_${variant} bmi2_bit_aot) + cpu_translation(cpu_bmi2_bit_${variant} cpu_bmi2_bit_aot "${cpu_bmi2_bit_exports}") + endforeach() + target_compile_definitions(cpu_bmi2_bit_altered PRIVATE ALTER_BMI2_BIT) + add_test(NAME cpu_aot_bmi2_bit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/bmi2_bit_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_bmi2_bit PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_bit.txt") + # cpu_aot_bmi1_bit set(cpu_bmi1_aot_exports "op_blsi32,op_blsi64,op_blsmsk32,op_blsmsk64,op_blsr32,op_blsr64," diff --git a/tests/cpu/bmi2_bit_aot.asm b/tests/cpu/bmi2_bit_aot.asm new file mode 100644 index 000000000..6c6ab04a4 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot.asm @@ -0,0 +1,303 @@ +; coverage: record cpu_aot_bmi2_bit +; Source-built MASM fixture for the four BMI2 bit-manipulation forms from +; docs/coverage/x64_zen2.tsv group BMI/ADX: BZHI, MULX, PDEP, and PEXT in 32-bit +; and 64-bit register and flat zero-displacement [rcx|rdx|r8] memory forms, plus +; BZHI CF/ZF/SF/OF flag checks, CMP -> PDEP/PEXT/MULX -> SETcc flag preservation +; (CF, ZF, SF, OF, PF), MULX op0==op1 aliasing, 32-bit zero-extension, [r8] +; source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8] + movzx r9d, r9b + movzx r10d, r10b + mov eax, 2 + pdep r10d, r10d, eax + or r9d, r10d + movzx r11d, r11b + mov eax, 4 + pdep r11d, r11d, eax + or r9d, r11d + movzx r10d, byte ptr [r8] + mov eax, 8 + pdep r10d, r10d, eax + or r9d, r10d + mov eax, r9d + mov dword ptr [r8], eax +ENDM + +; --- Register forms (mov rax,-1 / r9,-1 / r10,-1 before 32-bit ops checks [63:32] zero-ext) --- + +op_bzhi32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pext eax, ecx, edx +ELSE + bzhi eax, ecx, edx +ENDIF + ret +op_bzhi32 ENDP + +op_bzhi64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pext rax, rcx, rdx +ELSE + bzhi rax, rcx, rdx +ENDIF + ret +op_bzhi64 ENDP + +op_mulx32 PROC FRAME + .endprolog + mov r9, -1 + mov r10, -1 +IFDEF ALTER_BMI2_BIT + mulx r10d, r9d, ecx +ELSE + mulx r9d, r10d, ecx +ENDIF + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx32 ENDP + +op_mulx64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + mulx r10, r9, rcx +ELSE + mulx r9, r10, rcx +ENDIF + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx64 ENDP + +op_mulx32_alias PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + mulx r9d, eax, ecx +ELSE + mulx eax, eax, ecx +ENDIF + ret +op_mulx32_alias ENDP + +op_mulx64_alias PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + mulx r9, rax, rcx +ELSE + mulx rax, rax, rcx +ENDIF + ret +op_mulx64_alias ENDP + +op_pdep32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pext eax, ecx, edx +ELSE + pdep eax, ecx, edx +ENDIF + ret +op_pdep32 ENDP + +op_pdep64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pext rax, rcx, rdx +ELSE + pdep rax, rcx, rdx +ENDIF + ret +op_pdep64 ENDP + +op_pext32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pdep eax, ecx, edx +ELSE + pext eax, ecx, edx +ENDIF + ret +op_pext32 ENDP + +op_pext64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pdep rax, rcx, rdx +ELSE + pext rax, rcx, rdx +ENDIF + ret +op_pext64 ENDP + +; --- Flat zero-displacement [rcx|rdx] m32 / m64 source forms --- + +op_bzhi32_mem PROC FRAME + .endprolog + mov rax, -1 + mov r9d, dword ptr [rdx] + bzhi eax, dword ptr [rcx], r9d + ret +op_bzhi32_mem ENDP + +op_bzhi64_mem PROC FRAME + .endprolog + mov r9, qword ptr [rdx] + bzhi rax, qword ptr [rcx], r9 + ret +op_bzhi64_mem ENDP + +op_mulx32_mem PROC FRAME + .endprolog + mov r9, -1 + mov r10, -1 + mulx r9d, r10d, dword ptr [rcx] + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx32_mem ENDP + +op_mulx64_mem PROC FRAME + .endprolog + mulx r9, r10, qword ptr [rcx] + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx64_mem ENDP + +op_pdep32_mem PROC FRAME + .endprolog + mov rax, -1 + pdep eax, ecx, dword ptr [rdx] + ret +op_pdep32_mem ENDP + +op_pdep64_mem PROC FRAME + .endprolog + pdep rax, rcx, qword ptr [rdx] + ret +op_pdep64_mem ENDP + +op_pext32_mem PROC FRAME + .endprolog + mov rax, -1 + pext eax, ecx, dword ptr [rdx] + ret +op_pext32_mem ENDP + +op_pext64_mem PROC FRAME + .endprolog + pext rax, rcx, qword ptr [rdx] + ret +op_pext64_mem ENDP + +; --- [r8] source-then-store and program order --- + +op_mem_r8_source PROC FRAME + .endprolog + mov r9, qword ptr [rcx] + pdep r10, r9, qword ptr [r8] + pext r11, r10, qword ptr [rdx] + mulx r9, rax, qword ptr [r8] + xor rax, r11 + mov qword ptr [r8], r10 + ret +op_mem_r8_source ENDP + +; --- BZHI flags: (CF << 0) | (ZF << 1) | (SF << 2) | (OF << 3) --- + +op_bzhi32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + bzhi eax, ecx, edx + PACK_CF_ZF_SF_OF + ret +op_bzhi32_flags ENDP + +op_bzhi64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + bzhi rax, rcx, rdx + PACK_CF_ZF_SF_OF + ret +op_bzhi64_flags ENDP + +; --- Flag preservation across CMP -> PDEP/PEXT/MULX -> SETcc (CF/ZF/SF/OF and PF) --- + +op_flags_preserve32 PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + cmp ecx, edx + pdep r9d, ecx, edx + pext r10d, r9d, edx + mulx r11d, eax, ecx + PACK_CF_ZF_SF_OF + ret +op_flags_preserve32 ENDP + +op_flags_preserve64 PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + cmp rcx, rdx + pdep r9, rcx, rdx + pext r10, r9, rdx + mulx r11, rax, rcx + PACK_CF_ZF_SF_OF + ret +op_flags_preserve64 ENDP + +op_flags_preserve_pf PROC FRAME + .endprolog + cmp rcx, rdx + pdep r9, rcx, rdx + pext r10, r9, rdx + mulx r11, rax, rcx + setp byte ptr [r8] + ret +op_flags_preserve_pf ENDP + +op_flags_preserve_mem PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov r9, qword ptr [rcx] + mov r10, qword ptr [rdx] + cmp r9, r10 + pdep r11, r9, qword ptr [rdx] + pext r9, r11, qword ptr [rcx] + mulx r10, rax, qword ptr [rcx] + PACK_CF_ZF_SF_OF + ret +op_flags_preserve_mem ENDP + +; --- Discarded memory read must still fault on NULL rdx even under /O2 --- + +op_bmi2_bit_discarded_read PROC FRAME + .endprolog + pext r9, rcx, qword ptr [rdx] + mov rax, rcx + ret +op_bmi2_bit_discarded_read ENDP + +END diff --git a/tests/cpu/bmi2_bit_aot.def b/tests/cpu/bmi2_bit_aot.def new file mode 100644 index 000000000..a8e7c1060 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot.def @@ -0,0 +1,27 @@ +EXPORTS + op_bzhi32 + op_bzhi64 + op_mulx32 + op_mulx64 + op_mulx32_alias + op_mulx64_alias + op_pdep32 + op_pdep64 + op_pext32 + op_pext64 + op_bzhi32_mem + op_bzhi64_mem + op_mulx32_mem + op_mulx64_mem + op_pdep32_mem + op_pdep64_mem + op_pext32_mem + op_pext64_mem + op_mem_r8_source + op_bzhi32_flags + op_bzhi64_flags + op_flags_preserve32 + op_flags_preserve64 + op_flags_preserve_pf + op_flags_preserve_mem + op_bmi2_bit_discarded_read diff --git a/tests/cpu/bmi2_bit_aot_check.py b/tests/cpu/bmi2_bit_aot_check.py new file mode 100644 index 000000000..cf2f0ae67 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot_check.py @@ -0,0 +1,854 @@ +"""Differential, /O2, flag-preservation, mutant, and rejection checks for cpu_bmi2_bit_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_bmi2_bit_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_bzhi32", + "op_bzhi64", + "op_mulx32", + "op_mulx64", + "op_mulx32_alias", + "op_mulx64_alias", + "op_pdep32", + "op_pdep64", + "op_pext32", + "op_pext64", + "op_bzhi32_mem", + "op_bzhi64_mem", + "op_mulx32_mem", + "op_mulx64_mem", + "op_pdep32_mem", + "op_pdep64_mem", + "op_pext32_mem", + "op_pext64_mem", + "op_mem_r8_source", + "op_bzhi32_flags", + "op_bzhi64_flags", + "op_flags_preserve32", + "op_flags_preserve64", + "op_flags_preserve_pf", + "op_flags_preserve_mem", + "op_bmi2_bit_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_bzhi32", + "op_bzhi64", + "op_mulx32", + "op_mulx64", + "op_mulx32_alias", + "op_mulx64_alias", + "op_pdep32", + "op_pdep64", + "op_pext32", + "op_pext64", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) +OUT_FILL = b"\x5A" * 16 + + +# --- Independent Python reference model --- + +def ref_bzhi(val, idx, bits, *, bad_mask=False): + mask = (1 << bits) - 1 + s = val & mask + n = (idx & (bits - 1)) if bad_mask else (idx & 0xFF) + if n >= bits: + d = s + cf = 1 + else: + d = s & ((1 << n) - 1) + cf = 0 + zf = 1 if d == 0 else 0 + sf = 1 if (d & (1 << (bits - 1))) else 0 + of = 0 + packed = (cf << 0) | (zf << 1) | (sf << 2) | (of << 3) + return d, packed + + +def ref_mulx(src1, src2, bits): + mask = (1 << bits) - 1 + prod = (src1 & mask) * (src2 & mask) + lo = prod & mask + hi = (prod >> bits) & mask + return hi, lo + + +def ref_pdep(src, msk, bits): + mask = (1 << bits) - 1 + s = src & mask + m = msk & mask + d = 0 + k = 0 + for i in range(bits): + if (m >> i) & 1: + if (s >> k) & 1: + d |= 1 << i + k += 1 + return d + + +def ref_pext(src, msk, bits): + mask = (1 << bits) - 1 + s = src & mask + m = msk & mask + d = 0 + k = 0 + for i in range(bits): + if (m >> i) & 1: + if (s >> i) & 1: + d |= 1 << k + k += 1 + return d + + +def ref_cmp_flags(a, b, bits): + mask = (1 << bits) - 1 + sign = 1 << (bits - 1) + ua, ub = a & mask, b & mask + r = (ua - ub) & mask + cf = 1 if ua < ub else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r & sign) else 0 + of = 1 if (((ua ^ ub) & (ua ^ r)) & sign) else 0 + pf = 1 if (bin(r & 0xFF).count("1") % 2 == 0) else 0 + packed4 = (cf << 0) | (zf << 1) | (sf << 2) | (of << 3) + return (cf, zf, sf, of, pf), packed4 + + +VALUES = ( + 0x0000000000000000, + 0x0000000000000001, + 0x0000000000000003, + 0x0000000055AA55AA, + 0x000000007FFFFFFF, + 0x0000000080000000, + 0x0000000080000001, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, + 0xDEADBEEF80000001, + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, + 0x8000000000000001, + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, +) +BZHI_INDICES = ( + 0, 1, 7, 15, 31, 32, 33, 63, 64, 65, 255, + 0x100, 0x101, 0x120, 0x13F, 0x140, 0xFFFFFFFF, 0x8000000000000000, +) +BIT_MASKS = ( + 0x0000000000000000, + 0x0000000000000001, + 0x0000000080000000, + 0x0000000055555555, + 0x00000000AAAAAAAA, + 0x00000000FFFFFFFF, + 0x8000000000000001, + 0x0F0F0F0F0F0F0F0F, + 0x5555555555555555, + 0xAAAAAAAAAAAAAAAA, + 0xFFFFFFFFFFFFFFFF, +) + + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + """Verify shifts, BMI1, EVEX/XOP, ABI, addressing, PF/AF, prefix, and state rejections.""" + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + mov_r9_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R9, R.RCX) + cmp_rcx_rdx = Instruction.create_reg_reg(Code.CMP_R64_RM64, R.RCX, R.RDX) + bzhi_rax = Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.RDX) + + alt_accept = [ + ("bzhi64_r11_r8_rcx", ( + Instruction.create_reg_mem_reg(Code.VEX_BZHI_R64_RM64_R64, R.R11, MemoryOperand(R.R8), R.RCX), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), + ret, + ), "r11 = op_bzhi64(ld_1000_1, rcx, flags);"), + ("bzhi32_self_alias", ( + mov_r9_rcx, + Instruction.create_reg_reg_reg(Code.VEX_BZHI_R32_RM32_R32, R.R9D, R.R9D, R.EDX), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R9D), + ret, + ), "r9 = op_bzhi32((r9 & 0xFFFFFFFFull), (rdx & 0xFFFFFFFFull), flags);"), + ("mulx64_alias_mem", ( + Instruction.create_reg_reg_mem(Code.VEX_MULX_R64_R64_RM64, R.R9, R.R9, MemoryOperand(R.RCX)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), + ret, + ), "r9 = mulx_hi_1000;"), + ("pdep64_r9_r10_rcx", ( + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R10, R.RDX), + Instruction.create_reg_reg_mem(Code.VEX_PDEP_R64_R64_RM64, R.R9, R.R10, MemoryOperand(R.RCX)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), + ret, + ), "r9 = op_pdep64(r10, ld_1003_2);"), + ("pext32_r11_r9_r8", ( + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.R9D, R.ECX), + Instruction.create_reg_reg_mem(Code.VEX_PEXT_R32_R32_RM32, R.R11D, R.R9D, MemoryOperand(R.R8)), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R11D), + ret, + ), "r11 = op_pext32((r9 & 0xFFFFFFFFull), ld_1003_2);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r} in:\n{src}") + + seg_pext = Instruction.create_reg_reg_mem(Code.VEX_PEXT_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RDX)) + seg_pext.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # EVEX / XOP + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_bextr", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R32_RM32_IMM32, R.EAX, R.ECX, 0x0804), ret), + "unsupported XOP instruction"), + # BMI2 shifts & legacy shifts (ALL shifts refused) + ("bmi2_rorx", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, R.RCX, 5), ret), + "unsupported VEX instruction"), + ("bmi2_shlx", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi2_shrx", (Instruction.create_reg_reg_reg(Code.VEX_SHRX_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_sarx", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("legacy_shl_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM32_IMM8, R.EAX, 1), ret), + "unsupported instruction"), + ("legacy_shl_1", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM64_1, R.RAX, 1), ret), + "unsupported instruction"), + ("legacy_shr_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHR_RM32_IMM8, R.EAX, 3), ret), + "unsupported instruction"), + ("legacy_sar_cl", (mov_rax_rcx, Instruction.create_reg_reg(Code.SAR_RM32_CL, R.EAX, R.CL), ret), + "unsupported instruction"), + ("legacy_ror_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.ROR_RM32_IMM8, R.EAX, 2), ret), + "unsupported instruction"), + # BMI1 instructions + ("bmi1_andn", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R32_R32_RM32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi1_bextr", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi1_blsi", (Instruction.create_reg_reg(Code.VEX_BLSI_R32_RM32, R.EAX, R.ECX), ret), + "unsupported VEX instruction"), + ("bmi1_blsmsk", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_blsr", (Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_tzcnt", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + # Nonvolatile GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RBX, R.RCX, R.RDX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RSI, R.RDX), ret), + "nonvolatile GPR"), + ("nonvol_r12_idx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.R12), ret), + "nonvolatile GPR"), + ("nonvol_rsp_lo", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R64_R64_RM64, R.RAX, R.RSP, R.RCX), ret), + "nonvolatile GPR"), + # Writes to argument GPRs (rcx/rdx/r8) including MULX op0 & op1 + ("write_arg_rcx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RCX, R.RDX, R.R8), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_mulx_hi_edx", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R32_R32_RM32, R.EDX, R.EAX, R.ECX), ret), + "cannot write argument GPR rdx"), + ("write_arg_mulx_lo_r8", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R64_R64_RM64, R.RAX, R.R8, R.RCX), ret), + "cannot write argument GPR r8"), + ("write_arg_pext_r8", (Instruction.create_reg_reg_reg(Code.VEX_PEXT_R64_R64_RM64, R.R8, R.RCX, R.RDX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + # High-byte GPRs + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_reg(Code.MOV_R8_RM8, R.AL, R.AH), ret), + "unsupported high-byte GPR"), + ("high_byte_ch_dst", (Instruction.create_reg_reg(Code.MOV_R8_RM8, R.CH, R.DL), mov_rax_rcx, ret), + "unsupported high-byte GPR"), + # Displaced memory operands (must be refused!) + ("disp_mem_bzhi", (Instruction.create_reg_mem_reg( + Code.VEX_BZHI_R64_RM64_R64, R.RAX, MemoryOperand(R.RCX, displ=8, displ_size=1), R.RDX), ret), + "displaced memory operand"), + ("disp_mem_mulx", (Instruction.create_reg_reg_mem( + Code.VEX_MULX_R32_R32_RM32, R.R9D, R.EAX, MemoryOperand(R.RDX, displ=4, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_pdep", (Instruction.create_reg_reg_mem( + Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.R8, displ=8, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_pext", (Instruction.create_reg_reg_mem( + Code.VEX_PEXT_R32_R32_RM32, R.EAX, R.ECX, MemoryOperand(R.RCX, displ=-4, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_store_mov", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=8, displ_size=1), R.RAX), ret), + "displaced memory operand"), + ("disp_mem_store_setcc", (cmp_rcx_rdx, mov_rax_rcx, Instruction.create_mem( + Code.SETB_RM8, MemoryOperand(R.R8, displ=1, displ_size=1)), ret), + "displaced memory operand"), + # RIP-relative, SIB-indexed, bad base, non-[r8] stores + ("rip_rel_pdep", (Instruction.create_reg_reg_mem( + Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("sib_idx_pext", (Instruction.create_reg_reg_mem( + Code.VEX_PEXT_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RCX, R.RDX, 8)), ret), + "SIB index memory operand"), + ("bad_base_rbx", (Instruction.create_reg_reg_mem( + Code.VEX_MULX_R64_R64_RM64, R.R9, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem_reg( + Code.VEX_BZHI_R32_RM32_R32, R.EAX, MemoryOperand(R.RSP), R.EDX), ret), + "bad base register in memory operand"), + ("non_r8_store_mov", (mov_rax_rcx, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "non-r8 store memory operand"), + ("non_r8_store_setcc", (cmp_rcx_rdx, mov_rax_rcx, Instruction.create_mem(Code.SETE_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Undefined GPR / undefined flag / PF & AF readers after BZHI + ("undef_gpr_src", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.R9, R.RDX), ret), + "undefined GPR r9"), + ("undef_gpr_idx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.R10), ret), + "undefined GPR r10"), + ("undef_rax_ret", (Instruction.create_reg_reg_reg(Code.VEX_PEXT_R64_R64_RM64, R.R9, R.RCX, R.RDX), ret), + "return with undefined RAX"), + ("undef_flags_setb", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("undef_flags_after_pdep", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, R.RDX), + Instruction.create_mem(Code.SETE_RM8, MemoryOperand(R.R8)), ret), "undefined flags read"), + ("undef_pf_setp_after_bzhi", (cmp_rcx_rdx, bzhi_rax, Instruction.create_mem(Code.SETP_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("undef_pf_setnp_after_bzhi", (cmp_rcx_rdx, bzhi_rax, Instruction.create_mem(Code.SETNP_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("af_reader_lahf_after_bzhi", (bzhi_rax, Instruction.create(Code.LAHF), ret), + "unsupported instruction"), + ("af_reader_pushfq_after_bzhi", (bzhi_rax, Instruction.create(Code.PUSHFQ), ret), + "unsupported instruction"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_pext", (seg_pext, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (mov_rax_rcx,), "missing terminal ret"), + ("after_ret", (mov_rax_rcx, ret, mov_r9_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE patching and CLI non-traceback rejection controls. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_flags_preserve64") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off : file_off + len(patch)] = patch + struct.pack_into("> bit_idx) & 1 for p in seen_bzhi} != {0, 1}: + raise AssertionError(f"{name} did not exercise both 0 and 1 for {fname}") + if {(p >> 3) & 1 for p in seen_bzhi} != {0}: + raise AssertionError(f"{name} observed non-zero OF") + + # 4) Flag preservation across CMP -> PDEP/PEXT/MULX -> SETcc (CF, ZF, SF, OF, PF) + flag_pairs = [ + (0x0000000000000000, 0x0000000000000000), + (0x0000000000000000, 0x0000000000000001), + (0x0000000000000003, 0x0000000000000002), + (0x0000000080000000, 0x0000000000000001), + (0x000000007FFFFFFF, 0x00000000FFFFFFFF), + (0x8000000000000000, 0x0000000000000001), + (0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF), + ] + [(rng.getrandbits(64), rng.getrandbits(64)) for _ in range(24)] + + for bits, name in ((32, "op_flags_preserve32"), (64, "op_flags_preserve64")): + seen = set() + for a, b in flag_pairs: + f_tuple, packed4 = ref_cmp_flags(a, b, bits) + seen.add(f_tuple[:4]) + exp_buf = struct.pack("(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported BMI2 bit-manipulation instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - BZHI r32, r/m32, r32 | BZHI r64, r/m64, r64 (index = src2[7:0]; CF=1 if index>=width) + - MULX r32, r32, r/m32 | MULX r64, r64, r/m64 (implicit EDX/RDX src1; op0==op1 -> hi) + - PDEP r32, r32, r/m32 | PDEP r64, r64, r/m64 (parallel bit deposit, flagless) + - PEXT r32, r32, r/m32 | PEXT r64, r64, r/m64 (parallel bit extract, flagless) + +Exact SDM semantics: + - 32-bit destinations zero-extend into bits [63:32]. + - BZHI masks index to low 8 bits (index >= width preserves src and sets CF=1; index == 0 + yields 0 with CF=0; updates CF, ZF, SF, clears OF, and leaves PF/AF undefined). + - MULX reads implicit EDX/RDX and src2 before writing dst_lo then dst_hi (so op0==op1 + writes the high half) and leaves all flags unmodified. + - PDEP and PEXT leave all flags unmodified. + - Memory operands are flat zero-displacement [rcx|rdx|r8] loads read unconditionally via + load_always() so /O2 cannot eliminate faulting reads. + +Transport / flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, movzx, cmp, xor, or, setcc (reg or [r8]), + flat zero-displacement [r8] stores, and terminal ret. + +EVEX/XOP encodings, shifts/rotates (legacy SHL/SHR/SAR/ROR/ROL and BMI2 RORX/SARX/SHLX/SHRX), +BMI1 (ANDN/BEXTR/BLSI/BLSMSK/BLSR/TZCNT), nonvolatile GPRs, writes to argument GPRs +(rcx/rdx/r8), high-byte GPRs, undefined GPR or flag reads (including PF/AF after BZHI), +RIP-relative/SIB-indexed/displaced/non-argument memory operands, stores outside [r8], +instruction prefixes, branches/calls, and missing or trailing instructions after ret are +rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", + R.RCX: "rcx", + R.RDX: "rdx", + R.R8: "r8", + R.R9: "r9", + R.R10: "r10", + R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", + R.ECX: "rcx", + R.EDX: "rdx", + R.R8D: "r8", + R.R9D: "r9", + R.R10D: "r10", + R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", + R.CX: "rcx", + R.DX: "rdx", + R.R8W: "r8", + R.R9W: "r9", + R.R10W: "r10", + R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", + R.CL: "rcx", + R.DL: "rdx", + R.R8L: "r8", + R.R9L: "r9", + R.R10L: "r10", + R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +BMI2_BIT_SPECS = { + Code.VEX_BZHI_R32_RM32_R32: ("bzhi", 32), + Code.VEX_BZHI_R64_RM64_R64: ("bzhi", 64), + Code.VEX_MULX_R32_R32_RM32: ("mulx", 32), + Code.VEX_MULX_R64_R64_RM64: ("mulx", 64), + Code.VEX_PDEP_R32_R32_RM32: ("pdep", 32), + Code.VEX_PDEP_R64_R64_RM64: ("pdep", 64), + Code.VEX_PEXT_R32_R32_RM32: ("pext", 32), + Code.VEX_PEXT_R64_R64_RM64: ("pext", 64), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +CMP_WIDTHS = { + Code.CMP_R32_RM32: 32, + Code.CMP_RM32_R32: 32, + Code.CMP_RM32_IMM8: 32, + Code.CMP_RM32_IMM32: 32, + Code.CMP_EAX_IMM32: 32, + Code.CMP_R64_RM64: 64, + Code.CMP_RM64_R64: 64, + Code.CMP_RM64_IMM8: 64, + Code.CMP_RM64_IMM32: 64, + Code.CMP_RAX_IMM32: 64, +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + # PF is tracked solely to validate flag preservation and reject reads after BZHI. + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_cmp32(word lhs_w, word rhs_w, Flags& flags) { + const std::uint32_t a = static_cast(lhs_w); + const std::uint32_t b = static_cast(rhs_w); + const std::uint32_t r = a - b; + flags.cf = a < b; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((a ^ b) & (a ^ r)) & 0x80000000u) != 0u; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_cmp64(word a, word b, Flags& flags) { + const word r = a - b; + flags.cf = a < b; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((a ^ b) & (a ^ r)) >> 63) != 0ull; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast(masked)); +} + +// --- BMI2 BZHI / MULX / PDEP / PEXT helpers --- + +static inline word op_bzhi32(word src_w, word idx_w, Flags& flags) { + const std::uint32_t s = static_cast(src_w); + const unsigned idx = static_cast(idx_w & 0xFFull); + std::uint32_t d = 0u; + if (idx >= 32u) { + d = s; + flags.cf = true; + } else { + d = (idx == 0u) ? 0u : (s & ((1u << idx) - 1u)); + flags.cf = false; + } + flags.zf = (d == 0u); + flags.sf = (d & 0x80000000u) != 0u; + flags.of = false; + return static_cast(d); +} + +static inline word op_bzhi64(word s, word idx_w, Flags& flags) { + const unsigned idx = static_cast(idx_w & 0xFFull); + word d = 0ull; + if (idx >= 64u) { + d = s; + flags.cf = true; + } else { + d = (idx == 0u) ? 0ull : (s & ((1ull << idx) - 1ull)); + flags.cf = false; + } + flags.zf = (d == 0ull); + flags.sf = (d >> 63) != 0ull; + flags.of = false; + return d; +} + +static inline void op_mulx32(word src1_w, word src2_w, word& hi, word& lo) { + const std::uint64_t prod = static_cast(static_cast(src1_w)) + * static_cast(static_cast(src2_w)); + lo = prod & 0xFFFFFFFFull; + hi = prod >> 32; +} + +static inline void op_mulx64(word src1, word src2, word& hi, word& lo) { +#if defined(_MSC_VER) + word high = 0ull; + lo = _umul128(src1, src2, &high); + hi = high; +#else + const unsigned __int128 prod = static_cast(src1) * static_cast(src2); + lo = static_cast(prod); + hi = static_cast(prod >> 64); +#endif +} + +static inline word op_pdep32(word src_w, word mask_w) { + std::uint32_t s = static_cast(src_w); + std::uint32_t m = static_cast(mask_w); + std::uint32_t d = 0u; + while (m != 0u) { + const std::uint32_t lowest = m & (~m + 1u); + if ((s & 1u) != 0u) { + d |= lowest; + } + s >>= 1; + m &= ~lowest; + } + return static_cast(d); +} + +static inline word op_pdep64(word s, word m) { + word d = 0ull; + while (m != 0ull) { + const word lowest = m & (~m + 1ull); + if ((s & 1ull) != 0ull) { + d |= lowest; + } + s >>= 1; + m &= ~lowest; + } + return d; +} + +static inline word op_pext32(word src_w, word mask_w) { + const std::uint32_t s = static_cast(src_w); + std::uint32_t m = static_cast(mask_w); + std::uint32_t d = 0u; + std::uint32_t out_bit = 1u; + while (m != 0u) { + const std::uint32_t lowest = m & (~m + 1u); + if ((s & lowest) != 0u) { + d |= out_bit; + } + out_bit <<= 1; + m &= ~lowest; + } + return static_cast(d); +} + +static inline word op_pext64(word s, word m) { + word d = 0ull; + word out_bit = 1ull; + while (m != 0ull) { + const word lowest = m & (~m + 1ull); + if ((s & lowest) != 0ull) { + d |= out_bit; + } + out_bit <<= 1; + m &= ~lowest; + } + return d; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_bmi2() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast(info[1]) & (1u << 8)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line BMI2 BZHI/MULX/PDEP/PEXT leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in BMI2_BIT_SPECS: + if encoding != EncodingKind.VEX: + raise ValueError(f"expected VEX encoding for BMI2 op at RVA {ins.ip:#x}: {ins}") + mnemonic, width = BMI2_BIT_SPECS[code] + if mnemonic == "bzhi": + src_expr = read_rm(1, ins, width) + idx_expr = read_reg(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_bzhi{width}({src_expr}, {idx_expr}, flags);") + defined_gpr.add(dst) + # BZHI defines CF, ZF, SF, OF and leaves PF/AF undefined. + defined_flags = {"cf", "zf", "sf", "of"} + elif mnemonic == "mulx": + src1_expr = "(rdx & 0xFFFFFFFFull)" if width == 32 else "rdx" + src2_expr = read_rm(2, ins, width) + dst_hi = check_dst_reg(0, ins, width, require_defined=False) + dst_lo = check_dst_reg(1, ins, width, require_defined=False) + hi_var = f"mulx_hi_{ins.ip:x}" + lo_var = f"mulx_lo_{ins.ip:x}" + statements.append(f"word {hi_var} = 0ull;") + statements.append(f"word {lo_var} = 0ull;") + statements.append(f"op_mulx{width}({src1_expr}, {src2_expr}, {hi_var}, {lo_var});") + # Write dst_lo first, then dst_hi so op0 == op1 receives the high half per Intel SDM. + statements.append(f"{dst_lo} = {lo_var};") + statements.append(f"{dst_hi} = {hi_var};") + defined_gpr.add(dst_lo) + defined_gpr.add(dst_hi) + else: + src_expr = read_reg(1, ins, width) + mask_expr = read_rm(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_{mnemonic}{width}({src_expr}, {mask_expr});") + defined_gpr.add(dst) + elif encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in CMP_WIDTHS: + width = CMP_WIDTHS[code] + lhs_expr = read_rm(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"compute_cmp{width}({lhs_expr}, {rhs_expr}, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flags read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always({addr}, static_cast(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, [n for n in args.exports.split(",") if n]) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From cf22fa995c86bd55d75a64c341a7710270ae5862 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:33:56 +0200 Subject: [PATCH 06/29] pe: sort package scan and harden CLI path guards in pe_package_preflight with CLI suite (#2609) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/pe_package_preflight_cli_check.py | 582 ++++++++++++++++++++++++ tools/pe_package_preflight.py | 32 +- 3 files changed, 612 insertions(+), 5 deletions(-) create mode 100644 tests/pe_package_preflight_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fb058175c..88aad3b10 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10273,6 +10273,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/dependency_paths_cli_check.py") add_test(NAME pe_package_import_closure COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_check.py") + add_test(NAME pe_package_preflight_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_cli_check.py") + set_tests_properties(pe_package_preflight_cli_check PROPERTIES TIMEOUT 60) add_test(NAME pe_inventory_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_inventory_cli_check.py") add_test(NAME call_evidence_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/pe_package_preflight_cli_check.py b/tests/pe_package_preflight_cli_check.py new file mode 100644 index 000000000..18f488a2c --- /dev/null +++ b/tests/pe_package_preflight_cli_check.py @@ -0,0 +1,582 @@ +#!/usr/bin/env python3 +"""Synthetic PE32+ CLI, deterministic scan, and error-handling suite for tools/pe_package_preflight.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "pe_package_preflight.py" +sys.path.insert(0, str(TOOLS_DIR)) +import pe_package_preflight # noqa: E402 + + +IMAGE_BASE = 0x180000000 +RAW_OFFSET = 0x200 +SECTION_RVA = 0x1000 +SECTION_SIZE = 0x1000 + + +def _build_pe32_plus( + *, + imports: tuple[tuple[str, str, str | int], ...] = (), + exports: tuple[tuple[str | None, str | None], ...] = (), + machine: int = 0x8664, +) -> bytes: + """Build a minimal synthetic PE32+ image with optional exports and normal/delay imports.""" + rdata = bytearray(SECTION_SIZE) + cursor = 0 + + def alloc(size: int, align: int = 4) -> int: + nonlocal cursor + cursor = (cursor + align - 1) & ~(align - 1) + rva = SECTION_RVA + cursor + if cursor + size > len(rdata): + raise AssertionError("synthetic .rdata overflow") + cursor += size + return rva + + def put(rva: int, blob: bytes) -> None: + offset = rva - SECTION_RVA + rdata[offset:offset + len(blob)] = blob + + export_rva = export_size = 0 + if exports: + code_rva = alloc(4, 4) + put(code_rva, b"\xC3\x90\x90\x90") + functions = [] + named_entries = [] + for idx, (symbol, forwarder) in enumerate(exports): + if forwarder is not None: + fwd_blob = forwarder.encode("ascii") + b"\0" + fwd_rva = alloc(len(fwd_blob), 2) + put(fwd_rva, fwd_blob) + functions.append(fwd_rva) + else: + functions.append(code_rva) + if symbol is not None: + name_blob = symbol.encode("ascii") + b"\0" + name_rva = alloc(len(name_blob), 2) + put(name_rva, name_blob) + named_entries.append((symbol, idx, name_rva)) + named_entries.sort(key=lambda item: item[0]) + + eat_rva = alloc(4 * len(functions), 4) + put(eat_rva, b"".join(struct.pack(" tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = pe_package_preflight.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _make_synthetic_package(pkg: Path) -> None: + sub = pkg / "sub" + sub.mkdir() + (pkg / "app.exe").write_bytes( + _build_pe32_plus( + imports=( + ("normal", "helper.dll", "HelperInit"), + ("delay", "helper.dll", 2), + ("normal", "kernel32.dll", "ExitProcess"), + ) + ) + ) + (sub / "helper.dll").write_bytes( + _build_pe32_plus( + imports=(("normal", "core.dll", "CoreTick"),), + exports=(("HelperInit", None), (None, None)), + ) + ) + (sub / "core.dll").write_bytes( + _build_pe32_plus(exports=(("CoreTick", None),)) + ) + + +class PePackagePreflightCliPositiveTests(unittest.TestCase): + def test_stdout_and_atomic_output_with_zero_leftover_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + # 1) Stdout mode (in-process + subprocess). + code, out, err = _run_main([str(pkg), "app.exe"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + report = json.loads(out) + self.assertEqual(report["schema"], 1) + self.assertEqual(report["entry"], "app.exe") + self.assertEqual(report["summary"]["images_scanned"], 3) + self.assertEqual(report["summary"]["images_reachable"], 3) + self.assertEqual(report["summary"]["static_imports"], 4) + self.assertEqual(report["summary"]["bundled_failures"], 0) + self.assertEqual(report["summary"]["external_unverified"], 1) + self.assertEqual(report["ignored_images"], []) + self.assertFalse(report["reachable"]["sub/helper.dll"]["conditional"]) + self.assertEqual( + report["reachable"]["sub/core.dll"]["path"], + ["app.exe", "sub/helper.dll", "sub/core.dll"], + ) + + proc = _run_subprocess(str(pkg), "app.exe") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), report) + + # 2) Atomic --output creation into nested non-existent directory, 0 leftover temps. + nested_out = base / "reports" / "nested" / "preflight.json" + proc_out = _run_subprocess(str(pkg), "app.exe", "--output", str(nested_out)) + self.assertEqual(proc_out.returncode, 0, proc_out.stderr) + self.assertEqual(proc_out.stdout, "") + self.assertEqual(proc_out.stderr, "") + self.assertEqual(json.loads(nested_out.read_text(encoding="utf-8")), report) + self.assertEqual( + sorted(p.name for p in nested_out.parent.iterdir()), + ["preflight.json"], + ) + + # 3) Atomic replacement of pre-existing output file, 0 leftover temps. + nested_out.write_text("stale content", encoding="utf-8") + code_rep, out_rep, err_rep = _run_main([str(pkg), "app.exe", "--output", str(nested_out)]) + self.assertEqual(code_rep, 0, err_rep) + self.assertEqual(out_rep, "") + self.assertEqual(err_rep, "") + self.assertEqual(json.loads(nested_out.read_text(encoding="utf-8")), report) + self.assertEqual( + sorted(p.name for p in nested_out.parent.iterdir()), + ["preflight.json"], + ) + + # 4) sys.argv forwarding when argv=None and __main__ entrypoint. + cli_argv = [str(TOOL), str(pkg), "app.exe"] + with mock.patch.object(sys, "argv", cli_argv): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(json.loads(out_none), report) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue()), report) + + def test_unsorted_rglob_deterministic_order_and_cutoff(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + a_dir = root / "a_dir" + b_dir = root / "B_dir" + a_dir.mkdir() + b_dir.mkdir() + + entry = a_dir / "first.exe" + second = a_dir / "second.dll" + huge = b_dir / "huge.dll" + entry.write_bytes(b"a" * 100) + second.write_bytes(b"b" * 100) + huge.write_bytes(b"z" * 500) + + # Unsorted rglob puts B_dir/huge.dll first (and ASCII sort puts 'B' < 'a'); + # deterministic casefold sort visits a_dir/first.exe, a_dir/second.dll before B_dir/huge.dll. + unsorted_paths = [huge, second, entry] + with ( + mock.patch.object(Path, "rglob", return_value=iter(unsorted_paths)), + mock.patch.object(pe_package_preflight, "MAX_IMAGE_BYTES", 300), + mock.patch.object(pe_package_preflight, "MAX_IMAGES", 1), + ): + with self.assertRaisesRegex(ValueError, "1024 PE image inspection limit"): + pe_package_preflight._paths(root.resolve()) + + with ( + mock.patch.object(Path, "rglob", return_value=iter(unsorted_paths)), + mock.patch.object(pe_package_preflight, "MAX_IMAGE_BYTES", 300), + mock.patch.object(pe_package_preflight, "MAX_TOTAL_BYTES", 150), + ): + with self.assertRaisesRegex(ValueError, "2 GiB PE inspection limit"): + pe_package_preflight._paths(root.resolve()) + + with tempfile.TemporaryDirectory() as tmp: + pkg = Path(tmp) + _make_synthetic_package(pkg) + forward = [pkg / "app.exe", pkg / "sub" / "core.dll", pkg / "sub" / "helper.dll"] + reversed_order = list(reversed(forward)) + with mock.patch.object(Path, "rglob", return_value=iter(forward)): + code_a, out_a, err_a = _run_main([str(pkg), "app.exe"]) + with mock.patch.object(Path, "rglob", return_value=iter(reversed_order)): + code_b, out_b, err_b = _run_main([str(pkg), "app.exe"]) + self.assertEqual(code_a, 0, err_a) + self.assertEqual(code_b, 0, err_b) + self.assertEqual(out_a, out_b) + + +class PePackagePreflightCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_root_is_dir_and_non_empty_entry_validated_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + not_a_dir = base / "regular.txt" + not_a_dir.write_text("not a directory", encoding="utf-8") + + with mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError("inspect called for invalid package/entry"), + ): + self._assert_clean_failure( + [str(base / "missing_pkg"), "app.exe"], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self._assert_clean_failure( + [str(not_a_dir), "app.exe"], + expected_code=1, + fragments=("pe_package_preflight:", "Package root must be a directory"), + ) + for blank_entry in ("", " "): + with self.subTest(entry=blank_entry): + self._assert_clean_failure( + [str(pkg), blank_entry], + expected_code=1, + fragments=("pe_package_preflight:", "Entry must be"), + ) + + for blank_entry in ("", " "): + with self.subTest(direct_entry=blank_entry): + with self.assertRaisesRegex(ValueError, "Entry must be"): + pe_package_preflight.inspect(pkg, blank_entry) + + def test_output_collision_dir_inside_pkg_rejected_before_temp_staging(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + file_parent = base / "collision.txt" + file_parent.write_text("keep-me", encoding="utf-8") + out_dir = base / "existing_dir" + out_dir.mkdir() + + cases = ( + ("parent_regular_file", file_parent / "report.json", ("not a directory",)), + ("ancestor_regular_file", file_parent / "nested" / "report.json", ("not a directory",)), + ("output_is_dir", out_dir, ("directory",)), + ("output_empty_string", Path(""), ("directory",)), + ("output_inside_pkg_root", pkg, ("outside the inspected package",)), + ("output_inside_pkg_file", pkg / "report.json", ("outside the inspected package",)), + ("output_inside_pkg_nested", pkg / "new_sub" / "report.json", ("outside the inspected package",)), + ) + for label, target, frags in cases: + with self.subTest(case=label): + with ( + mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError(f"inspect called for {label}"), + ), + mock.patch.object( + pe_package_preflight.tempfile, + "TemporaryDirectory", + side_effect=AssertionError(f"temp staging called for {label}"), + ), + ): + argv = [str(pkg), "app.exe", "--output", "" if label == "output_empty_string" else str(target)] + self._assert_clean_failure( + argv, + expected_code=1, + fragments=("pe_package_preflight:", *frags), + ) + + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-me") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertFalse((pkg / "report.json").exists()) + self.assertFalse((pkg / "new_sub").exists()) + + def test_output_symlink_rejected_before_temp_staging(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.json" + real_target.write_text("untouched", encoding="utf-8") + live_link = out_dir / "live_link.json" + dangling_link = out_dir / "dangling_link.json" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "nonexistent.json") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + for label, target in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + with ( + mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError(f"inspect called for {label}"), + ), + mock.patch.object( + pe_package_preflight.tempfile, + "TemporaryDirectory", + side_effect=AssertionError(f"temp staging called for {label}"), + ), + ): + self._assert_clean_failure( + [str(pkg), "app.exe", "--output", str(target)], + expected_code=1, + fragments=("pe_package_preflight:", "symlink"), + ) + + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.json", "live_link.json", "real.json"], + ) + + def test_temp_staging_replace_failure_leaves_zero_leftover_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + out_dir = base / "out_dir" + out_dir.mkdir() + out_file = out_dir / "report.json" + out_file.write_text("original", encoding="utf-8") + + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(pkg), "app.exe", "--output", str(out_file)], + expected_code=1, + fragments=("pe_package_preflight:", "simulated replace failure"), + check_subprocess=False, + ) + + self.assertEqual(out_file.read_text(encoding="utf-8"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json"]) + + def test_invalid_pe_and_missing_entry_do_not_create_output_dir_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + (pkg / "bad.exe").write_bytes(b"not a valid PE") + absent_out = base / "should_not_exist" / "report.json" + + self._assert_clean_failure( + [str(pkg), "bad.exe", "--output", str(absent_out)], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self.assertFalse(absent_out.parent.exists()) + + _make_synthetic_package(pkg) + self._assert_clean_failure( + [str(pkg), "missing.exe", "--output", str(absent_out)], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self.assertFalse(absent_out.parent.exists()) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + pkg = Path(tmp) + _make_synthetic_package(pkg) + cases = ( + ([], ("required",)), + ([str(pkg)], ("required",)), + ([str(pkg), "app.exe", "--bogus-flag"], ("unrecognized",)), + ([str(pkg), "app.exe", "--output"], ("expected one argument",)), + ) + for argv, frags in cases: + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/pe_package_preflight.py b/tools/pe_package_preflight.py index 4af2e57a5..89c3dd462 100644 --- a/tools/pe_package_preflight.py +++ b/tools/pe_package_preflight.py @@ -9,6 +9,7 @@ import heapq import json from pathlib import Path +import struct import sys import tempfile @@ -35,7 +36,7 @@ def _relative(root, path): def _paths(root): result = {} total_bytes = 0 - for path in root.rglob("*"): + for path in sorted(root.rglob("*"), key=lambda p: (p.as_posix().casefold(), p.as_posix())): if path.suffix.casefold() not in (".dll", ".exe"): continue if path.is_symlink(): @@ -160,7 +161,25 @@ def packaged(module): ignored_images=sorted(set(images) - set(reached))) +def _validate_entry(entry): + if not isinstance(entry, str) or not entry.strip(): + raise ValueError("Entry must be a non-empty relative path to an .exe inside the package") + + +def _validate_output(output, root): + if output.is_symlink(): + raise ValueError(f"Output path must not be a symlink: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"Output parent is not a directory: {parent}") + if output.resolve().is_relative_to(root): + raise ValueError("Write reports outside the inspected package") + if output.is_dir(): + raise IsADirectoryError(f"Output path is a directory: {output}") + + def inspect(root, entry): + _validate_entry(entry) root = Path(root).resolve(strict=True) if not root.is_dir(): raise ValueError("Package root must be a directory") @@ -183,11 +202,14 @@ def main(argv=None): args = parser.parse_args(argv) try: root = args.package.resolve(strict=True) - if args.output and args.output.resolve().is_relative_to(root): - raise ValueError("Write reports outside the inspected package") + if not root.is_dir(): + raise ValueError("Package root must be a directory") + _validate_entry(args.entry) + if args.output is not None: + _validate_output(args.output, root) report = inspect(root, args.entry) output = json.dumps(report, indent=2, sort_keys=True, ensure_ascii=True) + "\n" - if args.output: + if args.output is not None: args.output.parent.mkdir(parents=True, exist_ok=True) # Replace the directory entry instead of writing through a possible hard link. with tempfile.TemporaryDirectory(dir=args.output.parent) as directory: @@ -196,7 +218,7 @@ def main(argv=None): report_path.replace(args.output) else: print(output, end="") - except (OSError, ValueError, KeyError, pefile.PEFormatError) as exc: + except (OSError, ValueError, KeyError, struct.error, pefile.PEFormatError) as exc: parser.exit(1, f"pe_package_preflight: {exc}\n") return 0 From b97bb64d250f5d5ce04290860de1fe4c7b4c918a Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:34:49 +0200 Subject: [PATCH 07/29] shader: harden rdna_cvt_pk_u8 CLI validation and atomic writes with CLI suite (#2619) --- CMakeLists.txt | 3 + tests/rdna_cvt_pk_u8_cli_check.py | 505 ++++++++++++++++++++++++++++++ tools/rdna_cvt_pk_u8.py | 230 ++++++++++---- 3 files changed, 680 insertions(+), 58 deletions(-) create mode 100644 tests/rdna_cvt_pk_u8_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 88aad3b10..d9cd0bdbc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10202,6 +10202,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_BINARY_DIR}/triangle_vs.cso" "${DXC_BIN_DIR}/dxil.dll") set_tests_properties(shader_metadata_probe PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME shader_metadata_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_probe_check.py") + add_test(NAME shader_rdna_cvt_pk_u8_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/rdna_cvt_pk_u8_cli_check.py") + set_tests_properties(shader_rdna_cvt_pk_u8_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_metadata_census COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_census_check.py") add_test(NAME shader_profile_audit_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/rdna_cvt_pk_u8_cli_check.py b/tests/rdna_cvt_pk_u8_cli_check.py new file mode 100644 index 000000000..8194c9f35 --- /dev/null +++ b/tests/rdna_cvt_pk_u8_cli_check.py @@ -0,0 +1,505 @@ +"""Pure-Python CLI, atomic-write, path-collision, error-guard, and mutation suite for tools/rdna_cvt_pk_u8.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "rdna_cvt_pk_u8.py" +MEASURED_TSV = ROOT / "tests" / "data" / "rdna_cvt_pk_u8_measured.tsv" +sys.path.insert(0, str(ROOT / "tools")) + +import rdna_cvt_pk_u8 # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = rdna_cvt_pk_u8.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + cwd=str(cwd) if cwd is not None else None, + timeout=30, + ) + + +class _FakeHip: + device = 0 + + def __init__(self) -> None: + self.calls: list[tuple[str, int]] = [] + + def count(self) -> int: + return 2 + + def arch(self, device: int | None = None) -> str: + idx = self.device if device is None else device + return "gfx1030:sramecc-:xnack-" if idx == 0 else "gfx1036" + + def run_kernel(self, hsaco: bytes, kname: str, words: list[tuple[int, int]]) -> list[int]: + self.calls.append((kname, len(words))) + model = "trunc_sat_nan0" if kname.endswith("_rtz") else "rne_sat_nan0" + return [rdna_cvt_pk_u8.model_word(model, b, s) for b, s in words] + + +def _fake_build(arch: str, variant: str, workdir: str, args) -> tuple[bytes, str]: + out = Path(workdir) / f"{variant}_{arch}.hsaco" + out.write_bytes(b"HSACO_" + variant.encode("ascii")) + return out.read_bytes(), str(out) + + +class RdnaCvtPkU8CliPositiveTests(unittest.TestCase): + def test_self_test_direct_argv_and_subprocess(self) -> None: + code, out, err = _run_main(["--self-test"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("self-test OK", out) + + with mock.patch.object(sys, "argv", [str(TOOL), "--self-test"]): + code_default, out_default, err_default = _run_main(None) + self.assertIs(type(code_default), int) + self.assertEqual(code_default, 0, err_default) + self.assertIn("self-test OK", out_default) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), "--self-test"]), + redirect_stdout(stdout), + redirect_stderr(stderr), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertIn("self-test OK", stdout.getvalue()) + self.assertEqual(stderr.getvalue(), "") + + proc = _run_subprocess("--self-test") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("self-test OK", proc.stdout) + + def test_mocked_hip_writes_tsv_and_json_atomically_and_matches_measured(self) -> None: + expected_rows = [ + line.rstrip("\n") + for line in MEASURED_TSV.read_text(encoding="utf-8").splitlines() + if not line.startswith("#") + ] + self.assertEqual(len(expected_rows), 5432) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_tsv = root / "tsv_dir" / "rdna_cvt_pk_u8.tsv" + out_json = root / "json_dir" / "rdna_cvt_pk_u8.json" + seen_replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + created_workdirs: list[Path] = [] + real_mkdtemp = rdna_cvt_pk_u8.tempfile.mkdtemp + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + seen_replaces.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + return real_replace(src, dst) + + def tracking_mkdtemp(**kwargs): + d = Path(real_mkdtemp(**kwargs)) + created_workdirs.append(d) + return str(d) + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=tracking_replace), + mock.patch.object(rdna_cvt_pk_u8.tempfile, "mkdtemp", side_effect=tracking_mkdtemp), + ): + code, out, err = _run_main([ + "--out", str(out_tsv), + "--json", str(out_json), + "--show", "0", + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("HIP device 0: gfx1030:sramecc-:xnack- <- used", out) + self.assertIn("HIP device 1: gfx1036", out) + self.assertIn("rows identical to", out) + self.assertIn("results written to", out) + self.assertIn("verbose JSON written to", out) + + self.assertEqual(len(created_workdirs), 1) + self.assertFalse(created_workdirs[0].exists()) + + self.assertEqual(len(seen_replaces), 2) + self.assertEqual( + {dst.resolve() for _, dst in seen_replaces}, + {out_tsv.resolve(), out_json.resolve()}, + ) + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], [out_tsv.name]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], [out_json.name]) + + tsv_lines = out_tsv.read_text(encoding="utf-8").splitlines() + self.assertIn("# device gfx1030", tsv_lines) + tsv_rows = [line for line in tsv_lines if not line.startswith("#")] + self.assertEqual(tsv_rows, expected_rows) + + doc = json.loads(out_json.read_text(encoding="utf-8")) + self.assertEqual(doc["arch"], "gfx1030") + self.assertEqual(doc["sentinel"], rdna_cvt_pk_u8.SENTINEL) + self.assertEqual(len(doc["rows"]), 5432) + self.assertEqual(doc["summary"]["default"]["matching_models"], ["rne_sat_nan0"]) + self.assertEqual(doc["summary"]["rtz"]["matching_models"], ["trunc_sat_nan0"]) + self.assertEqual(doc["summary"]["flush"]["matching_models"], ["rne_sat_nan0"]) + + def test_asm_only_with_keep_and_compare_diff_report(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + keep_dir = root / "keep_artifacts" + with mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build): + code, out, err = _run_main(["--asm-only", "--arch", "gfx1030", "--keep", str(keep_dir)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("built default", out) + self.assertTrue((keep_dir / "default_gfx1030.hsaco").is_file()) + + # Compare with a modified TSV triggers the DIFFER summary line without failing. + ref_lines = MEASURED_TSV.read_text(encoding="utf-8").splitlines() + for idx, line in enumerate(ref_lines): + if not line.startswith("#"): + parts = line.split("\t") + parts[3] = "00000000" + ref_lines[idx] = "\t".join(parts) + break + diff_ref = root / "diff_ref.tsv" + diff_ref.write_text("\n".join(ref_lines) + "\n", encoding="utf-8") + out_tsv = root / "out.tsv" + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + code2, out2, err2 = _run_main([ + "--out", str(out_tsv), + "--compare", str(diff_ref), + ]) + self.assertEqual(code2, 0, err2) + self.assertEqual(err2, "") + self.assertIn("rows DIFFER from", out2) + self.assertIn("(1 of 5432 rows)", out2) + + +class RdnaCvtPkU8CliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + allow_stdout: bool = False, + cwd: Path | None = None, + ) -> str: + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, expected_code, err) + if not allow_stdout: + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv, cwd=cwd) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + if not allow_stdout: + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + return err + + def test_asm_only_needs_arch_and_hip_runtime_errors(self) -> None: + # --asm-only without --arch -> stderr + return 2 (not SystemExit). + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")): + self._assert_clean_failure( + ["--asm-only"], + expected_code=2, + expected_fragments=("error: --asm-only needs --arch",), + ) + + with TemporaryDirectory() as tmp: + out_tsv = Path(tmp) / "out.tsv" + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=RuntimeError("no HIP dll")): + self._assert_clean_failure( + ["--out", str(out_tsv)], + expected_code=2, + expected_fragments=("error: no HIP dll",), + check_subprocess=False, + ) + + class _FailingKernelHip(_FakeHip): + def run_kernel(self, hsaco, kname, words): + raise RuntimeError("kernel launch failed") + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FailingKernelHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + self._assert_clean_failure( + ["--out", str(out_tsv)], + expected_code=3, + expected_fragments=("error: kernel launch failed",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertFalse(out_tsv.exists()) + + def test_flag_and_path_type_validation_guards(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + reg_file = root / "regular.txt" + reg_file.write_text("keep-me", encoding="utf-8") + existing_dir = root / "existing_dir" + existing_dir.mkdir() + valid_out = root / "ok.tsv" + + cases = [ + (["--show", "-1", "--out", str(valid_out)], "--show must be >= 0", True), + (["--keep", "", "--out", str(valid_out)], "--keep path must not be empty", True), + (["--keep", str(reg_file), "--out", str(valid_out)], "--keep path is not a directory", True), + (["--keep", str(reg_file / "sub"), "--out", str(valid_out)], "--keep parent path is not a directory", True), + (["--compare", str(existing_dir), "--out", str(valid_out)], "--compare path is a directory", True), + (["--out", ""], "--out path must not be empty", True), + (["--out", str(existing_dir) + os.sep], "--out path is a directory path", True), + (["--out", str(existing_dir)], "--out path is a directory", True), + (["--out", str(reg_file / "child.tsv")], "--out parent path is not a directory", True), + (["--out", str(reg_file / "sub" / "child.tsv")], "--out parent path is not a directory", True), + (["--out", str(valid_out), "--json", ""], "--json path must not be empty", True), + (["--out", str(valid_out), "--json", str(existing_dir) + "/"], "--json path is a directory path", True), + (["--out", str(valid_out), "--json", str(existing_dir)], "--json path is a directory", True), + (["--out", str(valid_out), "--json", str(reg_file / "child.json")], "--json parent path is not a directory", True), + ] + for argv, fragment, subproc in cases: + with self.subTest(argv=argv): + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=AssertionError("build() must not run")), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", fragment), + check_subprocess=subproc, + ) + self.assertEqual(reg_file.read_text(encoding="utf-8"), "keep-me") + self.assertEqual(list(existing_dir.iterdir()), []) + + def test_symlink_output_guards_kill_mutations(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "target.txt" + target.write_text("do-not-clobber", encoding="utf-8") + valid_out = root / "valid.tsv" + + for flag, name in (("--out", "out_link.tsv"), ("--json", "json_link.json")): + link = root / name + try: + link.symlink_to(target) + created_real = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_real = False + + argv = [flag, str(link)] if flag == "--out" else ["--out", str(valid_out), flag, str(link)] + if created_real: + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", f"{flag} path must not be a symlink"), + ) + link.unlink() + else: + with ( + mock.patch.object( + Path, + "is_symlink", + autospec=True, + side_effect=lambda p, expected=link: os.path.normcase(str(p.resolve())) + == os.path.normcase(str(expected.resolve())), + ), + mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", f"{flag} path must not be a symlink"), + check_subprocess=False, + ) + self.assertEqual(target.read_text(encoding="utf-8"), "do-not-clobber") + + def test_collision_guards_alias_nonexistent_and_hardlink(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + ref = root / "ref.tsv" + ref.write_text("# ref\n", encoding="utf-8") + ref_hardlink = root / "ref_hardlink.tsv" + os.link(ref, ref_hardlink) + self.assertNotEqual(ref.resolve(), ref_hardlink.resolve()) + self.assertTrue(ref.samefile(ref_hardlink)) + + ghost_a = root / "ghost.txt" + ghost_b = sub / ".." / "ghost.txt" + other_out = root / "other_out.tsv" + + collision_cases = [ + (["--out", str(ref), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(sub / ".." / "ref.tsv"), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(ref_hardlink), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(ghost_a), "--compare", str(ghost_b)], "--out path collides with --compare"), + (["--out", str(other_out), "--json", str(ref), "--compare", str(ref)], "--json path collides with --compare"), + (["--out", str(other_out), "--json", str(ref_hardlink), "--compare", str(ref)], "--json path collides with --compare"), + (["--out", str(ghost_a), "--json", str(ghost_b)], "--out and --json paths must not collide"), + (["--out", str(ref), "--json", str(ref_hardlink)], "--out and --json paths must not collide"), + (["--keep", str(ghost_a), "--out", str(ghost_b)], "--keep and --out paths must not collide"), + ] + for argv, fragment in collision_cases: + with self.subTest(argv=argv): + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", fragment), + ) + self.assertEqual(ref.read_text(encoding="utf-8"), "# ref\n") + + def test_atomic_write_and_compare_failures_leave_zero_temps(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_tsv = root / "out_dir" / "res.tsv" + out_json = root / "json_dir" / "res.json" + out_tsv.parent.mkdir() + out_json.parent.mkdir() + out_tsv.write_text("PRIOR_TSV", encoding="utf-8") + out_json.write_text("PRIOR_JSON", encoding="utf-8") + + # 1) os.replace fails on --out: prior files preserved, zero sibling .tmp leftovers. + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=OSError("simulated tsv replace fail")), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error: simulated tsv replace fail",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertEqual(out_tsv.read_text(encoding="utf-8"), "PRIOR_TSV") + self.assertEqual(out_json.read_text(encoding="utf-8"), "PRIOR_JSON") + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], ["res.tsv"]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], ["res.json"]) + + # 2) os.replace fails on --json after --out: prior --json preserved, zero sibling .tmp leftovers. + real_replace = os.replace + calls = [] + + def fail_second_replace(src, dst): + calls.append(Path(dst)) + if len(calls) == 2: + raise OSError("simulated json replace fail") + return real_replace(src, dst) + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=fail_second_replace), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error: simulated json replace fail",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertEqual(out_json.read_text(encoding="utf-8"), "PRIOR_JSON") + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], ["res.tsv"]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], ["res.json"]) + + # 3) Corrupt UTF-8 --compare file -> ValueError/UnicodeDecodeError caught -> clean exit 1. + bad_cmp = root / "bad_utf8.tsv" + bad_cmp.write_bytes(b"\xff\xfe\xfd") + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--compare", str(bad_cmp)], + expected_code=1, + expected_fragments=("error:",), + check_subprocess=False, + allow_stdout=True, + ) + + # 4) json.JSONDecodeError caught cleanly if raised during main flow. + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object( + rdna_cvt_pk_u8.json, + "dumps", + side_effect=json.JSONDecodeError("bad json", "x", 0), + ), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error:", "bad json"), + check_subprocess=False, + allow_stdout=True, + ) + + def test_argparse_usage_errors_compatible_with_py314(self) -> None: + for bad_argv, fragment in ( + (["--unknown-flag"], "--unknown-flag"), + (["--arch"], "--arch"), + (["--show", "not-an-int"], "--show"), + (["--cov", "9"], "--cov"), + (["--build", "bogus"], "--build"), + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure( + bad_argv, + expected_code=2, + expected_fragments=("usage:", fragment), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna_cvt_pk_u8.py b/tools/rdna_cvt_pk_u8.py index d7dccdc75..09a533e23 100644 --- a/tools/rdna_cvt_pk_u8.py +++ b/tools/rdna_cvt_pk_u8.py @@ -28,6 +28,7 @@ import json import math import os +from pathlib import Path import re import shutil import struct @@ -526,7 +527,103 @@ def check(name, got, want): # ---------------------------------------------------------------- main -def main(): +def _same_path(left, right): + left_p = Path(left) + right_p = Path(right) + if os.path.normcase(str(left_p.resolve())) == os.path.normcase(str(right_p.resolve())): + return True + return left_p.exists() and right_p.exists() and left_p.samefile(right_p) + + +def _validate_output_path(flag, raw_path): + if not raw_path or not raw_path.strip(): + raise ValueError('%s path must not be empty' % flag) + if raw_path.endswith(('/', '\\')): + raise ValueError('%s path is a directory path: %s' % (flag, raw_path)) + p = Path(raw_path) + if p.is_symlink(): + raise ValueError('%s path must not be a symlink: %s' % (flag, raw_path)) + if p.is_dir(): + raise ValueError('%s path is a directory: %s' % (flag, raw_path)) + if p.exists() and not p.is_file(): + raise ValueError('%s path is not a regular file: %s' % (flag, raw_path)) + for parent in p.parents: + if parent.is_symlink() and not parent.is_dir(): + raise ValueError('%s parent path is a symlink to non-directory: %s' % (flag, parent)) + if parent.exists() and not parent.is_dir(): + raise ValueError('%s parent path is not a directory: %s' % (flag, parent)) + return p + + +def _validate_args(args): + if args.show < 0: + raise ValueError('--show must be >= 0, got %d' % args.show) + + keep_path = None + if args.keep is not None: + if not args.keep.strip(): + raise ValueError('--keep path must not be empty') + keep_path = Path(args.keep) + if keep_path.exists() and not keep_path.is_dir(): + raise ValueError('--keep path is not a directory: %s' % args.keep) + if keep_path.is_symlink() and not keep_path.is_dir(): + raise ValueError('--keep path is a broken symlink: %s' % args.keep) + for parent in keep_path.parents: + if parent.exists() and not parent.is_dir(): + raise ValueError('--keep parent path is not a directory: %s' % parent) + + cmp_path = None + if args.compare: + cmp_path = Path(args.compare) + if cmp_path.is_dir(): + raise ValueError('--compare path is a directory: %s' % args.compare) + + out_path = _validate_output_path('--out', args.out) + json_path = _validate_output_path('--json', args.json) if args.json is not None else None + + if cmp_path is not None and _same_path(out_path, cmp_path): + raise ValueError('--out path collides with --compare: %s' % args.out) + if json_path is not None and cmp_path is not None and _same_path(json_path, cmp_path): + raise ValueError('--json path collides with --compare: %s' % args.json) + if json_path is not None and _same_path(out_path, json_path): + raise ValueError('--out and --json paths must not collide: %s' % args.out) + if keep_path is not None: + if _same_path(keep_path, out_path): + raise ValueError('--keep and --out paths must not collide: %s' % args.out) + if json_path is not None and _same_path(keep_path, json_path): + raise ValueError('--keep and --json paths must not collide: %s' % args.json) + if cmp_path is not None and _same_path(keep_path, cmp_path): + raise ValueError('--keep and --compare paths must not collide: %s' % args.compare) + + +def _write_atomic(path, content): + """Write content to a sibling temp file and atomically replace path, cleaning up on failure.""" + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode='w', + encoding='utf-8', + newline='\n', + dir=target.parent, + prefix='.%s.' % target.name, + suffix='.tmp', + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, target) + except BaseException: + if tmp_path is not None: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + raise + + +def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--device', type=int, default=0, help='HIP device index (default 0; every device is listed)') ap.add_argument('--arch', help='target, e.g. gfx1030, gfx1032, gfx1100 (default: from the HIP device)') @@ -543,72 +640,89 @@ def main(): ap.add_argument('--clang', help='clang executable (--build hip)') ap.add_argument('--llvm-mc', help='llvm-mc executable (--build asm)') ap.add_argument('--lld', help='ld.lld executable (--build asm)') - args = ap.parse_args() + args = ap.parse_args(argv) if args.self_test: return self_test() - hip, arch = None, args.arch - if not args.asm_only: + temp_workdir = None + try: + _validate_args(args) + + hip, arch = None, args.arch + if not args.asm_only: + try: + hip = Hip() + hip.device = args.device + for i in range(hip.count()): + print('HIP device %d: %s%s' % (i, hip.arch(i), ' <- used' if i == args.device else '')) + if not arch: + arch = hip.arch() + except RuntimeError as e: + print('error: %s' % e, file=sys.stderr) + return 2 + if not arch: + print('error: --asm-only needs --arch', file=sys.stderr) + return 2 + arch = arch.split(':')[0] + + if args.keep: + workdir = args.keep + os.makedirs(workdir, exist_ok=True) + else: + temp_workdir = tempfile.mkdtemp(prefix='cvt_pk_u8_') + workdir = temp_workdir + + images = {} + for var in VARIANTS: + images[var] = build(arch, var, workdir, args) + print('built %s (%d bytes): %s' % (var, len(images[var][0]), images[var][1])) + if args.asm_only: + return 0 + + rows = build_rows() + words = [(r[1], r[2]) for r in rows] + results = {} try: - hip = Hip() - hip.device = args.device - for i in range(hip.count()): - print('HIP device %d: %s%s' % (i, hip.arch(i), ' <- used' if i == args.device else '')) - if not arch: - arch = hip.arch() + for var in VARIANTS: + results[var] = hip.run_kernel(images[var][0], 'cvt_pk_u8_' + var, words) except RuntimeError as e: print('error: %s' % e, file=sys.stderr) - return 2 - if not arch: - sys.exit('error: --asm-only needs --arch') - arch = arch.split(':')[0] - - workdir = args.keep or tempfile.mkdtemp(prefix='cvt_pk_u8_') - os.makedirs(workdir, exist_ok=True) - images = {} - for var in VARIANTS: - images[var] = build(arch, var, workdir, args) - print('built %s (%d bytes): %s' % (var, len(images[var][0]), images[var][1])) - if args.asm_only: + return 3 + summary = analyse(rows, results, args.show) + print_report(rows, results, summary, arch, args.show) + header = ['# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py', + '# sentinel (S2) %08x' % SENTINEL, '# device %s' % arch, + '# columns (tab separated, words in hex): label in sel default rtz flush', + '# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0'] + lines = ['\t'.join([r[0], '%08x' % r[1], '%08x' % r[2]] + ['%08x' % results[v][i] for v in VARIANTS]) + for i, r in enumerate(rows)] + _write_atomic(args.out, '\n'.join(header + lines) + '\n') + print('\nresults written to %s' % os.path.abspath(args.out)) + if args.json: + payload = json.dumps( + {'arch': arch, 'sentinel': SENTINEL, + 'rows': [{'label': r[0], 'in': '%08x' % r[1], 'sel': '%08x' % r[2], + **{v: '%08x' % results[v][i] for v in results}} for i, r in enumerate(rows)], + 'summary': summary}, + indent=1, + ) + _write_atomic(args.json, payload) + print('verbose JSON written to %s' % os.path.abspath(args.json)) + if args.compare and os.path.exists(args.compare): + with open(args.compare, encoding='utf-8') as f: + stored = [l.rstrip('\n') for l in f if not l.startswith('#')] + if stored == lines: + print('rows identical to %s' % args.compare) + else: + print('rows DIFFER from %s (%d of %d rows)' % (args.compare, sum(a != b for a, b in zip(stored, lines)), len(lines))) return 0 - - rows = build_rows() - words = [(r[1], r[2]) for r in rows] - results = {} - try: - for var in VARIANTS: - results[var] = hip.run_kernel(images[var][0], 'cvt_pk_u8_' + var, words) - except RuntimeError as e: + except (OSError, ValueError, json.JSONDecodeError) as e: print('error: %s' % e, file=sys.stderr) - return 3 - summary = analyse(rows, results, args.show) - print_report(rows, results, summary, arch, args.show) - header = ['# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py', - '# sentinel (S2) %08x' % SENTINEL, '# device %s' % arch, - '# columns (tab separated, words in hex): label in sel default rtz flush', - '# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0'] - lines = ['\t'.join([r[0], '%08x' % r[1], '%08x' % r[2]] + ['%08x' % results[v][i] for v in VARIANTS]) - for i, r in enumerate(rows)] - os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) - with open(args.out, 'w', newline='\n') as f: - f.write('\n'.join(header + lines) + '\n') - print('\nresults written to %s' % os.path.abspath(args.out)) - if args.json: - with open(args.json, 'w') as f: - json.dump({'arch': arch, 'sentinel': SENTINEL, - 'rows': [{'label': r[0], 'in': '%08x' % r[1], 'sel': '%08x' % r[2], - **{v: '%08x' % results[v][i] for v in results}} for i, r in enumerate(rows)], - 'summary': summary}, f, indent=1) - print('verbose JSON written to %s' % os.path.abspath(args.json)) - if args.compare and os.path.exists(args.compare): - with open(args.compare) as f: - stored = [l.rstrip('\n') for l in f if not l.startswith('#')] - if stored == lines: - print('rows identical to %s' % args.compare) - else: - print('rows DIFFER from %s (%d of %d rows)' % (args.compare, sum(a != b for a, b in zip(stored, lines)), len(lines))) - return 0 + return 1 + finally: + if temp_workdir is not None: + shutil.rmtree(temp_workdir, ignore_errors=True) if __name__ == '__main__': From 51fdbbce9099ef1b185ca4305790e00da2edf736 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:35:09 +0200 Subject: [PATCH 08/29] ffx: add upfront path guards and atomic writes to ffx_working_set_delta with CLI suite (#2616) --- CMakeLists.txt | 3 + tests/ffx_working_set_delta_cli_check.py | 322 +++++++++++++++++++++++ tools/ffx_working_set_delta.py | 50 +++- 3 files changed, 371 insertions(+), 4 deletions(-) create mode 100644 tests/ffx_working_set_delta_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d9cd0bdbc..b701049bc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10335,6 +10335,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/probe_root_devices_check.py") add_test(NAME ffx_working_set_delta_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/ffx_working_set_delta_check.py") + add_test(NAME ffx_working_set_delta_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/ffx_working_set_delta_cli_check.py") + set_tests_properties(ffx_working_set_delta_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_descriptors_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_descriptors_aot_check.py") add_test(NAME range_manifest_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/ffx_working_set_delta_cli_check.py b/tests/ffx_working_set_delta_cli_check.py new file mode 100644 index 000000000..d076e34ea --- /dev/null +++ b/tests/ffx_working_set_delta_cli_check.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and error-handling suite for tools/ffx_working_set_delta.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "ffx_working_set_delta.py" +sys.path.insert(0, str(TOOLS_DIR)) +import ffx_working_set_delta # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include \n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) word create_delta(word input, word counters) { return input + counters; }\n' +) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = ffx_working_set_delta.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FfxWorkingSetDeltaCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_new_dir_and_overwrite(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "delta.cpp" + + # 1) Create missing parent directories and write atomically with 0 .tmp files. + with mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP) as gen: + code, out, err = _run_main([str(image), str(nested_out)]) + gen.assert_called_once_with(image, False) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["delta.cpp"]) + + # 2) Forward --package flag and atomically replace pre-existing file with 0 .tmp files. + nested_out.write_text("stale content", encoding="ascii") + pkg_cpp = SYNTHETIC_CPP + "// package-mode\n" + with mock.patch.object(ffx_working_set_delta, "generate", return_value=pkg_cpp) as gen_pkg: + code_pkg, out_pkg, err_pkg = _run_main([str(image), str(nested_out), "--package"]) + gen_pkg.assert_called_once_with(image, True) + self.assertEqual(code_pkg, 0, err_pkg) + self.assertEqual(out_pkg, "") + self.assertEqual(err_pkg, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), pkg_cpp) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["delta.cpp"]) + + # 3) Verify sys.argv forwarding when argv=None. + cli_argv = [str(TOOL), str(image), str(nested_out)] + with ( + mock.patch.object(sys, "argv", cli_argv), + mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # 4) Verify __main__ entrypoint propagates SystemExit cleanly. + bad_pe = base / "bad_main.dll" + bad_pe.write_bytes(b"not a PE") + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(bad_pe), str(base / "unused.cpp")]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout.getvalue(), "") + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertTrue(stderr.getvalue().strip()) + + +class FfxWorkingSetDeltaCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "should_not_exist" / "delta.cpp" + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + self.assertFalse(absent_out.parent.exists()) + + def test_invalid_pe_bytes_exit_1_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + bad_pe = base / "bad.dll" + bad_pe.write_bytes(b"not a valid PE32+ image") + absent_out = base / "absent_dir" / "delta.cpp" + + self._assert_clean_failure( + [str(bad_pe), str(absent_out)], + expected_code=1, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_reject_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "delta.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "delta.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_atomic_write_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "delta.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["delta.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "delta.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ffx_working_set_delta.py b/tools/ffx_working_set_delta.py index 6ed27189a..cf9184fc4 100644 --- a/tools/ffx_working_set_delta.py +++ b/tools/ffx_working_set_delta.py @@ -1,6 +1,8 @@ """Translate the counter updates following two upscaler working-set queries.""" import argparse from pathlib import Path +import struct +import tempfile import pefile @@ -31,6 +33,47 @@ def generate(image: Path, package: bool) -> str: return "\n".join(source) +def _validate_paths(image: Path, output: Path, parser: argparse.ArgumentParser) -> None: + if image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {image}") + if not image.is_file(): + raise FileNotFoundError(f"image file not found: {image}") + if output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if output.resolve() == image.resolve() or (output.exists() and image.samefile(output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) @@ -38,10 +81,9 @@ def main(argv=None) -> int: parser.add_argument("--package", action="store_true") args = parser.parse_args(argv) try: - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") - args.output.write_text(generate(args.image, args.package), encoding="ascii") - except (OSError, ValueError, pefile.PEFormatError) as error: + _validate_paths(args.image, args.output, parser) + _write_atomic(args.output, generate(args.image, args.package)) + except (OSError, ValueError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") return 0 From e5d8251b736c097c9c967296d11568501e1e3dd4 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:36:22 +0100 Subject: [PATCH 09/29] startup: refuse a lane mask read as data by v_mov_b32 and v_cndmask_b32 (#2623) A lane-mask register (a compare result, vcc_lo, exec_lo, a saved EXEC copy) holds only the current lane's bit in the one-lane model, while RDNA 2 reads the whole mask word when the register is a data operand. v_cndmask_b32 (both data operands) and v_mov_b32 (plain, e64 and SDWA DWORD) took such a register through u()/u_src and emitted the lane bit. They now refuse it, after stripping the source modifiers; the lane select of v_cndmask is unchanged. Tests that moved a mask with v_mov_b32 first now expect the new refusal, or read the mask as a lane select instead so they still reach the refusal they test. The SDWA check that accepted a whole-mask move now expects a refusal. AI-assisted. --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 11 +++- tests/startup_gfx2hlsl_add_sub_co_check.py | 12 ++-- tests/startup_gfx2hlsl_compute_check.py | 27 ++++---- tests/startup_gfx2hlsl_join_symbols_check.py | 20 ++++-- tests/startup_gfx2hlsl_mask_data_check.py | 65 +++++++++++++++++++ ...up_gfx2hlsl_readfirstlane_uniform_check.py | 12 +++- tests/startup_gfx2hlsl_sdwa_check.py | 5 +- tools/startup/gfx2hlsl.py | 23 ++++++- 11 files changed, 148 insertions(+), 32 deletions(-) create mode 100644 tests/startup_gfx2hlsl_mask_data_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ef7f3e5e6..6ac6935fd 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -249,6 +249,7 @@ jobs: tests/startup_gfx2hlsl_int_med3_check.py \ tests/startup_gfx2hlsl_cselect_mask_check.py \ tests/startup_gfx2hlsl_mask_overwrite_check.py \ + tests/startup_gfx2hlsl_mask_data_check.py \ tests/startup_gfx2hlsl_image_get_lod_check.py \ tests/startup_gfx2hlsl_add_sub_co_check.py \ tests/startup_gfx2hlsl_add_sub_co_ci_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f9a68ef8d..92208393f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -202,6 +202,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_int_med3_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cselect_mask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_overwrite_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_data_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_get_lod_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_ci_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b701049bc..ed89ff2ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3386,6 +3386,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: a scalar load or select into a former lane-mask SGPR clears its mask mark. add_test(NAME startup_gfx2hlsl_mask_overwrite_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mask_overwrite_check.py") + # Startup shader translator: lane masks cannot be used as vector data words. + add_test(NAME startup_gfx2hlsl_mask_data_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mask_data_check.py") # Startup shader translator: image_get_lod on a 2D texture (CalculateLevelOfDetail / Unclamped). add_test(NAME startup_gfx2hlsl_image_get_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_get_lod_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index c84ebab6c..2a1cfa310 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14153,11 +14153,20 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cselect_mask_controls$ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mask_overwrite_controls$' -V ``` +## Startup translator: lane masks used as vector data + +The one-lane model stores a mask as the current lane's bit. RDNA 2 reads the whole mask word when the register is +a data source. For example, after `v_cmp_eq_u32_e64 s[30:31], 0, v0`, reading s30 as data gives +`0xffffffff` if all 32 lanes pass. The translator refuses lane masks in either data operand of +`v_cndmask_b32` and in the source of `v_mov_b32`, including SDWA DWORD. Source modifiers still identify the +underlying mask register. Lane masks remain valid as selectors, and ordinary scalar words remain valid as data. +The synthetic controls run under `startup_gfx2hlsl_mask_data_controls`. + ## Startup translator: 32-bit add and subtract with a carry out `tools/startup/gfx2hlsl.py` refused the VOP3b forms `v_add_co_u32`, `v_sub_co_u32` and `v_subrev_co_u32` as unknown instructions. It now lowers them from the AMD RDNA 2 ISA description: `D = S0 + S1` with the carry out of bit 31, `D = S0 - S1` with a borrow when `S1 > S0`, and `SUBREV` with the sources swapped. These forms take no carry-in. The carry goes to the lane's bit of VCC or of the SGPR destination, which becomes a lane mask and is never a uniform source. The result and the carry are computed into the scratch registers `a` and `w` before either destination is written, so a destination may overlap a source. When `exec` is not known, an inactive lane keeps D and writes a 0 carry, as the compare lowering does. `clamp`, other modifiers, an EXEC carry-out and a wrong operand count are refused. -`tests/startup_gfx2hlsl_add_sub_co_check.py` decodes synthetic VOP3b words for the three forms with an SGPR and a VCC carry-out, evaluates the emitted lines with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py` on a grid of edge values, and compares them with Python references written from the ISA description. It also checks that the carry-out SGPR is a lane mask, that a readfirstlane of a copy of it is refused, the exec-masked form, an overlapping destination and the refusals. Negative control: a borrow with the comparison reversed disagrees with the reference on the grid. On the translator before this change every form is refused. Test: `startup_gfx2hlsl_add_sub_co_controls`. Not covered: DXC compilation and a draw through a translated pipeline; the check evaluates the emitted HLSL text only. +`tests/startup_gfx2hlsl_add_sub_co_check.py` decodes synthetic VOP3b words for the three forms with an SGPR and a VCC carry-out, evaluates the emitted lines with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py` on a grid of edge values, and compares them with Python references written from the ISA description. It also checks that the carry-out SGPR is a lane mask, that moving it as vector data is refused, the exec-masked form, an overlapping destination and the refusals. Negative control: a borrow with the comparison reversed disagrees with the reference on the grid. On the translator before this change every form is refused. Test: `startup_gfx2hlsl_add_sub_co_controls`. Not covered: DXC compilation and a draw through a translated pipeline; the check evaluates the emitted HLSL text only. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_add_sub_co_controls$' -V diff --git a/tests/startup_gfx2hlsl_add_sub_co_check.py b/tests/startup_gfx2hlsl_add_sub_co_check.py index 7fa75429f..0a80e6ea1 100644 --- a/tests/startup_gfx2hlsl_add_sub_co_check.py +++ b/tests/startup_gfx2hlsl_add_sub_co_check.py @@ -8,8 +8,8 @@ The emitted lines are evaluated with the restricted evaluator of startup_gfx2hlsl_bit_alu_check on a grid of edge values and compared with Python references written from the ISA description, for an SGPR and a VCC carry-out. Also -checked: the carry-out SGPR becomes a lane mask that is not a uniform source, a readfirstlane of a copy of it is -refused, inactive lanes keep D and get a 0 carry when exec is not known, a destination that overlaps a source reads +checked: the carry-out SGPR becomes a lane mask that is refused as vector move data, inactive lanes keep D +and get a 0 carry when exec is not known, a destination that overlaps a source reads the source first, and clamp, a wrong operand count and an EXEC carry-out are refused. Negative control: a borrow written as S0 > S1 differs from the reference on the grid. """ @@ -117,15 +117,15 @@ def main(): count += 1 check('%s matches the ISA reference on the grid' % text, bad is None, bad) - # The carry-out is per lane: a readfirstlane of a VGPR copied from it must not be proven uniform. + # The carry-out holds only this lane's bit and cannot be moved as a data word. s, text, _ = translate(vop3b(0x30f, 2, 18, V4, V3)) try: s.one('v_mov_b32', 'v_mov_b32 v5, s18') - s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s20, v5') except G.Unsupported as error: - check('%s: readfirstlane of a copy of the carry-out is refused' % text, 'uniform' in str(error), str(error)) + check('%s: moving the carry-out as data is refused' % text, + str(error) == 'v_mov_b32 data operand s18 is a lane mask', str(error)) else: - check('%s: readfirstlane of a copy of the carry-out is refused' % text, False, s.lines) + check('%s: moving the carry-out as data is refused' % text, False, s.lines) # D of varying sources is not proven uniform either. s, text, _ = translate(vop3b(0x30f, 2, 18, V4, V3)) try: diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 5cc703fd8..fd4c3bd58 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -412,6 +412,7 @@ def saveexec_fixture(): # Single instructions the controls splice into case A before its store, recorded from llvm-mc 15. STORE_A = WORDS_A.index(bytes.fromhex('001070e004050480')) +SCC_LANE_SELECT = 'v_cndmask_b32_e64 v5, 0, 1, s20' SPLICE = { 's_cmp_lt_u32 s7, 4': '07840abf', 's_and_b32 s13, s13, 0xc000ffff': '0dff0d87ffff00c0', @@ -422,7 +423,7 @@ def saveexec_fixture(): 's_cmov_b32 s20, 1': '810594be', 's_cmov_b64 s[20:21], s[4:5]': '040694be', 's_cmovk_i32 s20, 3': '030014b1', - 's_cbranch_scc0 1': '010084bf', + 's_cbranch_scc0 2': '020084bf', 's_cbranch_scc1 1': '010085bf', 's_cbranch_vccz 1': '010086bf', 'v_mov_b32 v3, 0': '8002067e', @@ -441,6 +442,7 @@ def saveexec_fixture(): 's_add_u32 s20, s7, 1': '07811480', 's_or_b32 exec_lo, exec_lo, s0': '7e007e88', 'v_mov_b32 v5, s20': '14020a7e', + SCC_LANE_SELECT: '050001d580025100', 's_mov_b32 s21, exec_lo': '7e0395be', 's_mov_b32 exec_lo, vcc_lo': '6a03febe', 's_mov_b32 exec_lo, s21': '1503febe', @@ -694,11 +696,10 @@ def check_mbcnt(): def check_descriptor_scc(): # Case A loads the input descriptor into s[12:15] and stores through s[16:19]. - # Put the condition into the stored value, or let the branch skip the move. + # Read s20's lane bit into the stored value. The SCC branches skip both dwords of the lane select. compare = 's_cmp_lt_u32 s7, 4' mask = 's_and_b32 s13, s13, 0xc000ffff' select = 's_cselect_b32 s20, 1, 0' - move = 'v_mov_b32 v5, s20' def pipeline(*lines): return translate('A', code=splice(*lines)) @@ -707,20 +708,20 @@ def rejected(*lines): refused('scc from descriptor data', lambda: pipeline(*lines)) for reader in (select, 's_cselect_b64 s[20:21], 1, 0', 's_cmov_b32 s20, 1', 's_cmov_b64 s[20:21], s[4:5]', - 's_cmovk_i32 s20, 3', 's_cbranch_scc0 1', 's_cbranch_scc1 1'): - rejected(compare, mask, reader, move) - assert 'uav 0 table 1 16' in pipeline(mask, compare, reader, move).manifest() - rejected(compare, 's_add_u32 s13, s13, 1', select, move) - assert 's20 = scc ?' in pipeline(compare, 's_mov_b32 s13, s13', select, move).hlsl_cs() - assert 's20 = scc ?' in pipeline(mask, 's_and_b32 s22, s7, 1', select, move).hlsl_cs() - assert 's20 = scc ?' in pipeline(mask, 's_and_saveexec_b32 s0, vcc_lo', select, move).hlsl_cs() + 's_cmovk_i32 s20, 3', 's_cbranch_scc0 2', 's_cbranch_scc1 2'): + rejected(compare, mask, reader, SCC_LANE_SELECT) + assert 'uav 0 table 1 16' in pipeline(mask, compare, reader, SCC_LANE_SELECT).manifest() + rejected(compare, 's_add_u32 s13, s13, 1', select, SCC_LANE_SELECT) + assert 's20 = scc ?' in pipeline(compare, 's_mov_b32 s13, s13', select, SCC_LANE_SELECT).hlsl_cs() + assert 's20 = scc ?' in pipeline(mask, 's_and_b32 s22, s7, 1', select, SCC_LANE_SELECT).hlsl_cs() + assert 's20 = scc ?' in pipeline(mask, 's_and_saveexec_b32 s0, vcc_lo', select, SCC_LANE_SELECT).hlsl_cs() # A conditional edge can bypass the fresh comparison. A back edge can carry # the descriptor-derived flag to a read that comes first in program order. - rejected(mask, 's_cbranch_vccz 1', compare, select, move) + rejected(mask, 's_cbranch_vccz 1', compare, select, SCC_LANE_SELECT) rejected(compare, 'v_mov_b32 v3, 0', select, mask, 'v_add_nc_u32 v3, 1, v3', - 'v_cmp_gt_u32 vcc_lo, 2, v3', 's_cbranch_vccnz 65530', move) - assert 's20 = scc ?' in pipeline(compare, 's_branch 2', mask, select, move).hlsl_cs() + 'v_cmp_gt_u32 vcc_lo, 2, v3', 's_cbranch_vccnz 65530', SCC_LANE_SELECT) + assert 's20 = scc ?' in pipeline(compare, 's_branch 2', mask, select, SCC_LANE_SELECT).hlsl_cs() def check_lds(): diff --git a/tests/startup_gfx2hlsl_join_symbols_check.py b/tests/startup_gfx2hlsl_join_symbols_check.py index 8d72a634d..cda6bc966 100644 --- a/tests/startup_gfx2hlsl_join_symbols_check.py +++ b/tests/startup_gfx2hlsl_join_symbols_check.py @@ -274,13 +274,18 @@ def cmp_ne(sdst, v): # v_cmp_ne_i32_e64 sdst, 0, v return struct.pack('> 0u) & 0xffu);') check('v_mov UNUSED_SEXT with a DWORD destination has no unused bits', mov('v2', 'DWORD', 'UNUSED_SEXT', 'WORD_0') == 'v1 = ((v2 >> 0u) & 0xffffu);') -check('v_mov whole lane mask is the plain move', mov('exec_lo', 'DWORD', 'UNUSED_PAD', 'DWORD') == 'v1 = exec;') +check('v_mov whole lane mask refused', + mov('exec_lo', 'DWORD', 'UNUSED_PAD', 'DWORD') == 'refused: v_mov_b32 data operand exec_lo is a lane mask') check('v_mov UNUSED_SEXT with a sub-dword destination refused', refused_as('v_mov_b32_sdwa v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:DWORD', 'SDWA UNUSED_SEXT')) check('v_mov clamp refused', refused_as('v_mov_b32_sdwa v1, v2 clamp dst_sel:DWORD dst_unused:UNUSED_PAD ' @@ -172,4 +173,4 @@ def mov(source, dst_sel, unused, src_sel): for text in failures: print(' ' + text) sys.exit(1) -print('PASS') \ No newline at end of file +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 11a1552af..3b4af0c56 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1871,6 +1871,22 @@ def split_neg(tok): return True, tok[1:] return False, tok + def reject_lane_mask_data(self, op, tok): + """The lane bit cannot represent a mask's word when it is read as data.""" + source = tok + while True: + neg, operand = self.split_neg(source) + if neg: + source = operand + elif source.startswith('|') and source.endswith('|') and len(source) >= 2: + source = source[1:-1] + elif source.startswith(('abs(', 'sext(')) and source.endswith(')'): + source = source[source.index('(') + 1:-1] + else: + break + if self.is_lane_mask(source): + raise Unsupported('%s data operand %s is a lane mask' % (op, tok)) + def u_src(self, tok): """uint expression for an integer-context source that the disassembler may print negated.""" # In an integer instruction the `-` modifier is the source's sign bit flipped: the same bit @@ -3341,7 +3357,9 @@ def sdwa(self, base, ops, mods): elif base == 'v_mov_b32': arity, text = 1, '{0}' # A lane mask is one bit per lane here, so a byte or word of it is not the hardware's field. - if fields.get('src0_sel') != 'DWORD' and self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): + if fields.get('src0_sel') == 'DWORD': + self.reject_lane_mask_data(base, ops[1]) + elif self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): raise Unsupported('v_mov_b32 SDWA %s of lane mask %s' % (fields.get('src0_sel'), ops[1])) else: raise Unsupported('SDWA form of %s' % base) @@ -5545,6 +5563,7 @@ def op_v_readlane_b32(self, ops, mods): def op_v_mov_b32(self, ops, mods): if len(ops) != 2: raise Unsupported('v_mov_b32 with %d operands, expected 2' % len(ops)) + self.reject_lane_mask_data('v_mov_b32', ops[1]) self.set_v(reg_range(ops[0])[1], self.u(ops[1])) def op_v_swap_b32(self, ops, mods): @@ -5579,6 +5598,8 @@ def op_v_cndmask_b32(self, ops, mods): raise Unsupported('v_cndmask_b32 with %s' % mods) if len(ops) not in (3, 4): raise Unsupported('v_cndmask_b32 with %d operands, expected 3 or 4' % len(ops)) + for source in ops[1:3]: + self.reject_lane_mask_data('v_cndmask_b32', source) mask = self.u(ops[3]) if len(ops) > 3 else 'vcc' self.set_v(reg_range(ops[0])[1], '(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1]))) From 0a3a2653e2cf3bb3e41ddf4aa1fc64be88194b89 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 07:37:16 +0800 Subject: [PATCH 10/29] tests: reuse the compute pipeline across descriptor-format references (#2615) * tests: run compute store references on a shared renderer device * tests: compare the descriptor fixture using one device for its reference cases * tests: use one root signature and compute pipeline for the reference batch * tests: retain case labels and 320-word diagnostics in the shared compute run --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 6 ++ tests/compute_check.cpp | 164 ++++++++++++++++------------- tests/compute_load_format_check.py | 104 ++++++++++-------- tests/desktop_gpu.h | 13 ++- tests/offscreen_check.cpp | 35 +++--- 5 files changed, 194 insertions(+), 128 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 2a1cfa310..f593934ce 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6199,6 +6199,12 @@ On the invalid runs, these mutated sources must fail: Dropping only the -1 clamp is not observable: long division of 32768 by 32767 also gives 1.0. With the lowering removed, or with its channel count changed, the translation controls fail. LLVM 15 assembles the fixture, and `lower` of the disassembly and the CLI output both match `lower` of the source. +The seven matching and fourteen intentionally wrong references use the same shader. The fixture passes +them to `offscreen_check --compute-store-batch ...` in order. They share +one D3D12 device, root signature and pipeline. Each case gets fresh buffers, submits its own dispatch and +compares all 320 words after the fence. The renderer reports `pass`, `mismatch` or `error` for each case +and exits with status 1 if any case fails. The eleven shader mutations still compile and dispatch separately. + ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_descriptor_load_format_|load_format_controls$)' -V diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 4b6ada2a5..ee4fb50d1 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -250,8 +250,21 @@ struct StoreCase { } }; -static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE shader, - D3D12_SHADER_BYTECODE rootBytes, bool conversion_pair = false, +static ComputeReadbackProgram create_compute_program(ID3D12Device* device, D3D12_SHADER_BYTECODE shader, + D3D12_SHADER_BYTECODE rootBytes) +{ + ComputeReadbackProgram program; + check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&program.signature)), + "Create compute root signature"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = program.signature.Get(); + pso.CS = shader; + check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&program.pipeline)), "Create compute pipeline"); + return program; +} + +static void run_compute(ID3D12Device* device, bool tables, const ComputeReadbackProgram& program, + bool conversion_pair = false, const StoreCase* store = nullptr, const std::vector* texels = nullptr, DXGI_FORMAT texture_format = DXGI_FORMAT_UNKNOWN, ID3D12Resource* rendered_texture = nullptr, bool dpp_case = false, bool sized_views = false, UINT texture_first_mip = 0, @@ -259,14 +272,6 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE { if ((texels || rendered_texture) && !tables) throw std::runtime_error("An image load needs the descriptor-table signature"); if (uav_words == 0 || uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); - ComPtr signature; - check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&signature)), - "Create compute root signature"); - D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; - pso.pRootSignature = signature.Get(); - pso.CS = shader; - ComPtr pipeline; - check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipeline)), "Create compute pipeline"); auto input = make_buffer(device, constants_offset + 4 * alignment, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); auto output = make_buffer(device, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, @@ -275,14 +280,14 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr, store && store->has_initial ? &store->initial : nullptr, store ? &store->root_constants : nullptr); - ComputeCommands commands(device, pipeline.Get()); + ComputeCommands commands(device, program.pipeline.Get()); auto& list = commands.list; ComPtr texture_upload, texture; if (texels) texture = upload_texture(device, list.Get(), *texels, texture_format, texture_upload); transition(list.Get(), output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); list->CopyBufferRegion(output.Get(), 0, input.Get(), bytes, bytes); transition(list.Get(), output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - list->SetComputeRootSignature(signature.Get()); + list->SetComputeRootSignature(program.signature.Get()); ComPtr heap; if (tables) { // An image-load case binds its output at u0 and the source texture at t0; the table @@ -346,21 +351,18 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE store->axis(2), capacity, mismatches); else std::printf("layout=%s output_words=%u guard_words=%u mismatches=%u\n", tables ? "tables" : "root", active, capacity - active, mismatches); - if (mismatches) throw std::runtime_error("Compute readback differs from CPU reference"); + if (mismatches) throw ReadbackMismatch("Compute readback differs from CPU reference"); } void check_compute(ID3D12Device* device, bool tables) { const D3D12_SHADER_BYTECODE shader = tables ? D3D12_SHADER_BYTECODE{compute_tables, sizeof(compute_tables)} : D3D12_SHADER_BYTECODE{compute_root, sizeof(compute_root)}; - run_compute(device, tables, shader, shader); + run_compute(device, tables, create_compute_program(device, shader, shader)); } -void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, - bool dpp_case, bool sized_views, UINT uav_words) +static std::vector read_compute_shader(const char* path) { - if (sized_views && uav_words > capacity) - throw std::runtime_error("Invalid compute UAV word count"); std::ifstream file(path, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); const auto size = file.tellg(); @@ -369,70 +371,86 @@ void check_compute_file(ID3D12Device* device, const char* path, bool conversion_ file.seekg(0); if (!file.read(bytes.data(), static_cast(bytes.size()))) throw std::runtime_error(std::string("Could not read compute shader: ") + path); - const D3D12_SHADER_BYTECODE shader{bytes.data(), bytes.size()}; - if (reference) { - StoreCase store{}; - std::ifstream file(reference, std::ios::binary); - file.read(reinterpret_cast(&store.groups), sizeof(store.groups)); - file.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); - // Bit 31 declares the trailing initial output segment; no other bit above the - // group counts is known, so an unflagged case keeps its historic bounds check. - constexpr UINT initial_data_flag = 1u << 31; - store.has_initial = (store.groups & initial_data_flag) != 0; - store.groups &= ~initial_data_flag; - if (!file || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || - store.axis(2) > 5) - throw std::runtime_error("Invalid compute store reference"); - if (dpp_case && store.groups != 1) - throw std::runtime_error("Invalid compute DPP reference dispatch"); - if (store.has_initial) { - file.read(reinterpret_cast(store.initial.data()), sizeof(store.initial)); - if (!file) - throw std::runtime_error("Invalid compute store initial words"); - } + return bytes; +} + +static StoreCase read_store_reference(const char* reference, bool dpp_case) +{ + StoreCase store{}; + std::ifstream file(reference, std::ios::binary); + file.read(reinterpret_cast(&store.groups), sizeof(store.groups)); + file.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); + // Bit 31 declares the trailing initial output segment; no other bit above the + // group counts is known, so an unflagged case keeps its historic bounds check. + constexpr UINT initial_data_flag = 1u << 31; + store.has_initial = (store.groups & initial_data_flag) != 0; + store.groups &= ~initial_data_flag; + if (!file || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || + store.axis(2) > 5) + throw std::runtime_error("Invalid compute store reference"); + if (dpp_case && store.groups != 1) + throw std::runtime_error("Invalid compute DPP reference dispatch"); + if (store.has_initial) { + file.read(reinterpret_cast(store.initial.data()), sizeof(store.initial)); + if (!file) + throw std::runtime_error("Invalid compute store initial words"); + } + if (file.peek() != std::char_traits::eof()) { + file.read(reinterpret_cast(store.root_constants.data()), sizeof(store.root_constants)); + if (!file) + throw std::runtime_error("Invalid compute store constants"); if (file.peek() != std::char_traits::eof()) { - file.read(reinterpret_cast(store.root_constants.data()), sizeof(store.root_constants)); - if (!file) - throw std::runtime_error("Invalid compute store constants"); - if (file.peek() != std::char_traits::eof()) { - file.read(reinterpret_cast(store.source.data()), sizeof(store.source)); - if (!file || file.peek() != std::char_traits::eof()) - throw std::runtime_error("Invalid compute store source words"); - store.has_source = true; - } + file.read(reinterpret_cast(store.source.data()), sizeof(store.source)); + if (!file || file.peek() != std::char_traits::eof()) + throw std::runtime_error("Invalid compute store source words"); + store.has_source = true; } + } + return store; +} + +ComputeReadbackProgram load_compute_store_program(ID3D12Device* device, const char* shader) +{ + const auto code = read_compute_shader(shader); + return create_compute_program(device, {code.data(), code.size()}, {compute_root, sizeof(compute_root)}); +} + +void check_compute_store_reference(ID3D12Device* device, const ComputeReadbackProgram& program, const char* reference) +{ + const StoreCase store = read_store_reference(reference, false); + run_compute(device, false, program, false, &store); +} + +void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, + bool dpp_case, bool sized_views, UINT uav_words) +{ + if (sized_views && uav_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); + const auto bytes = read_compute_shader(path); + const D3D12_SHADER_BYTECODE shader{bytes.data(), bytes.size()}; + if (reference) { + const StoreCase store = read_store_reference(reference, dpp_case); if (sized_views) { const UINT effective_uav_words = uav_words ? uav_words : capacity; if (effective_uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); - run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, nullptr, + const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case, true, 0, effective_uav_words); } else { - run_compute(device, false, shader, {compute_root, sizeof(compute_root)}, false, &store, nullptr, + const auto program = create_compute_program(device, shader, {compute_root, sizeof(compute_root)}); + run_compute(device, false, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case); } } else { - run_compute(device, false, shader, shader, conversion_pair); + run_compute(device, false, create_compute_program(device, shader, shader), conversion_pair); } } -static std::vector read_texture_shader(const char* path) -{ - std::ifstream file(path, std::ios::binary | std::ios::ate); - if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); - const auto size = file.tellg(); - if (size <= 0) throw std::runtime_error(std::string("Empty compute shader: ") + path); - std::vector bytes(static_cast(size)); - file.seekg(0); - if (!file.read(bytes.data(), static_cast(bytes.size()))) - throw std::runtime_error(std::string("Could not read compute shader: ") + path); - return bytes; -} - // The image load uses a descriptor-table signature. Its case file appends the source texels. void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference) { - const auto code = read_texture_shader(path); + const auto code = read_compute_shader(path); const D3D12_SHADER_BYTECODE shader{code.data(), code.size()}; StoreCase store{}; std::ifstream source(reference, std::ios::binary); @@ -458,7 +476,8 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch throw std::runtime_error("Invalid compute image load reference"); const auto format = rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; - run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, &texels, format, + const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, &texels, format, nullptr, false, false, view_mip1 ? 1 : 0); } @@ -540,12 +559,12 @@ bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, con source.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); if (!source || source.peek() != std::char_traits::eof() || store.groups != 1) throw std::runtime_error("Invalid compute MSAA load reference"); - const auto code = read_texture_shader(path); - const auto vs = read_texture_shader(vs_path), ps = read_texture_shader(ps_path); + const auto code = read_compute_shader(path); + const auto vs = read_compute_shader(vs_path), ps = read_compute_shader(ps_path); auto texture = render_msaa_texture(device, {vs.data(), vs.size()}, {ps.data(), ps.size()}); if (!texture) return false; - run_compute(device, true, {code.data(), code.size()}, {compute_tables, sizeof(compute_tables)}, - false, &store, nullptr, DXGI_FORMAT_UNKNOWN, texture.Get()); + const auto program = create_compute_program(device, {code.data(), code.size()}, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, texture.Get()); return true; } @@ -650,7 +669,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co return false; } - const auto code = read_texture_shader(path); + const auto code = read_compute_shader(path); ComPtr signature; check(device->CreateRootSignature(0, compute_tables, sizeof(compute_tables), IID_PPV_ARGS(&signature)), "Create image store root signature"); @@ -761,6 +780,7 @@ void check_bvh_root_roundtrip(ID3D12Device* device) if (roundtrip->GetBufferSize() != control->GetBufferSize() || std::memcmp(roundtrip->GetBufferPointer(), control->GetBufferPointer(), control->GetBufferSize()) != 0) throw std::runtime_error("Normalized signature differs from independent control serialization"); - run_compute(device, false, shader, {roundtrip->GetBufferPointer(), roundtrip->GetBufferSize()}); + const auto program = create_compute_program(device, shader, {roundtrip->GetBufferPointer(), roundtrip->GetBufferSize()}); + run_compute(device, false, program); std::puts("normalized_signature=matched_control root_creation=passed pipeline_creation=passed dispatch=passed"); } diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index bdaa9eca3..bc98b779b 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -7,6 +7,7 @@ from fractions import Fraction import os from pathlib import Path +import re import struct import subprocess import sys @@ -311,38 +312,70 @@ def binary(directory, assembler, objcopy, library): return 0 +def check_references(renderer, backend, shader, cases): + paths = [path for path, _label, _diagnostic in cases] + result = subprocess.run([renderer, backend, "--compute-store-batch", shader, *paths], + capture_output=True, text=True) + statuses = [line for line in result.stdout.splitlines() if line.startswith("case=")] + messages = re.split(r"(?=^case=\d+ path=)", result.stderr, flags=re.MULTILINE)[1:] + summaries = [line for line in result.stdout.splitlines() if line.startswith("groups=")] + for i, (path, label, diagnostic) in enumerate(cases): + status = "mismatch" if diagnostic else "pass" + if (i >= len(statuses) or statuses[i] != f"case={i} status={status}" + or i >= len(messages) or not messages[i].startswith(f"case={i} path={path}\n") + or (diagnostic and diagnostic not in messages[i])): + raise AssertionError(f"{NAME}: {label} expected {status}\n{result.stdout}{result.stderr}") + summary = summaries[i] if i < len(summaries) else "" + counts = re.fullmatch(r"groups=\d+ compared_words=320 mismatches=(\d+)", summary) + if not counts or (int(counts[1]) > 0) != bool(diagnostic): + raise AssertionError(f"{NAME}: {label} unexpected readback\n{result.stdout}{result.stderr}") + expected_exit = int(any(diagnostic for _, _, diagnostic in cases)) + if not (len(cases) == len(statuses) == len(messages) == len(summaries)) or result.returncode != expected_exit: + raise AssertionError(f"{NAME}: unexpected batch result ({result.returncode})\n{result.stdout}{result.stderr}") + labels = iter(label for _path, label, _diagnostic in cases) + for line in result.stdout.splitlines(): + if line.startswith("groups="): + print(f"{NAME}: {next(labels)}") + print(line) + + def draw(directory, compiler, renderer, backend): """Dispatch with chosen t0 words; wrong references and mutated sources must fail. - Every case owns its case and cso files, so the launches run on a small thread pool. Results are - checked afterwards in the original order with the original messages. + The reference cases share one device and compute pipeline. Each independently compiled mutation keeps its own + renderer process so compilation and readback can overlap with the reference checks. """ src, cso = directory / "load.hlsl", directory / "load.cso" source = lower() src.write_text(source, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) words = source_words() - jobs = [] # (check, label, extra, case bytes, shader, mutated source or None) + references = [] + mutations = [] - def add(check, label, groups, reference, formats=None, extra=None, mutated=None): + def write_case(number, groups, reference, formats): + case = directory / f"case{number}.bin" data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or constants())) + struct.pack("<320I", *words)) - jobs.append((check, label, extra, data, mutated)) - - def run(number, job): - _check, _label, _extra, data, mutated = job - case, shader = directory / f"case{number}.bin", cso case.write_bytes(data) - if mutated is not None: - shader = directory / f"mutated{number}.cso" - bad_src = directory / f"mutated{number}.hlsl" - bad_src.write_text(mutated, encoding="ascii") - subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", shader, bad_src], check=True) - return subprocess.run([renderer, backend, "--compute-store-case", shader, case], - capture_output=True, text=True) + return case + + def add_reference(label, groups, reference, formats=None, diagnostic=None): + case = write_case(len(references), groups, reference, formats) + references.append((case, label, diagnostic)) + + def run_mutation(number, label, case, mutated): + shader = directory / f"mutated{number}.cso" + bad_src = directory / f"mutated{number}.hlsl" + bad_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", shader, bad_src], check=True) + result = subprocess.run([renderer, backend, "--compute-store-case", shader, case], + capture_output=True, text=True) + if result.returncode != 1 or "Compute readback differs" not in result.stderr: + raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") for groups in (1, 2): - add("pass", "dispatch", groups, expected_words(groups)) + add_reference("dispatch", groups, expected_words(groups)) def invalid_formats(number): formats = constants() @@ -354,48 +387,37 @@ def invalid_formats(number): unwritten = [base.SENTINEL] * 320 zeros = (lambda channels: (lambda words: [0] * channels)) for number, (label, index, _word) in enumerate(INVALID): - add("pass", f"refused {label}", 2, unwritten, invalid_formats(number)) + add_reference(f"refused {label}", 2, unwritten, invalid_formats(number)) channels = len(LOADS[index][0]) placeholders = [("published as zeros", zeros(channels))] if number == 2: placeholders.append(("published with the (0, 0, 0, 1) fill", lambda words: [words[0], 0])) for what, values in placeholders: published = expected_words(2, placeholder=(index, values)) - add("placeholder", f"{label} {what}", 2, published, invalid_formats(number), - extra=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") + add_reference(f"{label} {what}", 2, published, invalid_formats(number), + diagnostic=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") expected = expected_words(2) for label, wrong in WRONG: reference = expected_words(2, wrong=wrong) word = next((i for i, (a, b) in enumerate(zip(expected, reference)) if a != b), None) if word is None: raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") - add("wrong", label, 2, reference, extra=f"word={word} expected=") + add_reference(f"reference '{label}'", 2, reference, diagnostic=f"word={word} expected=") for label, old, new, run_index in MUTATIONS: mutated = source.replace(old, new, 1) if mutated == source: raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") - if run_index is None: - add("mutation", label, 2, expected, mutated=mutated) - else: - add("mutation", label, 2, unwritten, invalid_formats(run_index), mutated=mutated) + number = len(references) + len(mutations) + reference, formats = (expected, None) if run_index is None else (unwritten, invalid_formats(run_index)) + case = write_case(number, 2, reference, formats) + mutations.append((number, label, case, mutated)) with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: - results = list(pool.map(lambda item: run(*item), enumerate(jobs))) - for (check, label, extra, _data, _mutated), result in zip(jobs, results): - if check == "pass": - print(f"{NAME}: {label}", flush=True) - sys.stdout.write(result.stdout) - if result.returncode: - sys.stderr.write(result.stderr) - return 1 - elif check == "placeholder": - if result.returncode != 1 or extra not in result.stderr: - raise AssertionError(f"{NAME}: {label} escaped detection\n{result.stderr}") - elif check == "wrong": - if result.returncode != 1 or extra not in result.stderr: - raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{result.stderr}") - elif result.returncode != 1 or "Compute readback differs" not in result.stderr: - raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") + batch = pool.submit(check_references, renderer, backend, cso, references) + mutants = [pool.submit(run_mutation, *mutation) for mutation in mutations] + batch.result() + for future in mutants: + future.result() print(f"{NAME}: {2 + len(INVALID)} dispatches, {len(WRONG) + len(INVALID) + 1} wrong references and " f"{len(MUTATIONS)} mutated sources checked") return 0 diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 84ff8c3f5..b09835fa1 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -46,6 +46,12 @@ void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr, bool dpp_case = false, bool sized_views = false, UINT uav_words = 0); +struct ComputeReadbackProgram { + Microsoft::WRL::ComPtr signature; + Microsoft::WRL::ComPtr pipeline; +}; +ComputeReadbackProgram load_compute_store_program(ID3D12Device* device, const char* shader); +void check_compute_store_reference(ID3D12Device* device, const ComputeReadbackProgram& program, const char* reference); void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference); bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, const char* reference, const char* vs_path, const char* ps_path); @@ -80,8 +86,11 @@ void check_texture_mips(ID3D12Device* device); void check_depth_mask_draw(ID3D12Device*, const char*, const char*, const char*, bool); void check_sampled_coverage(ID3D12Device*, const char*, const char*); void check_dual_pixel(ID3D12Device*, const char*, const char*, bool); -struct PixelMismatch : std::runtime_error { - PixelMismatch() : std::runtime_error("AOT color export differs from CPU reference") {} +struct ReadbackMismatch : std::runtime_error { + using std::runtime_error::runtime_error; +}; +struct PixelMismatch : ReadbackMismatch { + PixelMismatch() : ReadbackMismatch("AOT color export differs from CPU reference") {} }; void check_translated_pixel(ID3D12Device* device, const char* path, bool swapRB, const char* reference = nullptr, diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index d3973cdd1..963f442ca 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -459,11 +459,14 @@ bool validate_compute_mesh_texture_fallback_args(int argc, char** argv) (argc != 10 || std::string_view(argv[9]) == "--stale"); } -template -OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_draw) +template +OperationResult run_readback_batch(const OperationContext& ctx, AfterCase after_case) { - const bool pairs = std::string_view(ctx.argv[2]) == "--check-pixel-pairs"; + const std::string_view operation(ctx.argv[2]); + const bool pairs = operation == "--check-pixel-pairs"; + const bool compute = operation == "--compute-store-batch"; const int stride = pairs ? 2 : 1; + ComputeReadbackProgram program; bool failed = false; for (int i = 4, index = 0; i < ctx.argc; i += stride, ++index) { const char* shader = ctx.argv[pairs ? i - 1 : 3]; @@ -471,10 +474,15 @@ OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_dra std::fprintf(stderr, "case=%d path=%s\n", index, ctx.argv[i]); if (pairs) std::fprintf(stderr, "shader=%s\n", shader); try { - check(ctx.device->GetDeviceRemovedReason(), "Pixel batch device"); - check_translated_pixel(ctx.device, shader, false, ctx.argv[i]); - after_draw(index); - } catch (const PixelMismatch& e) { + check(ctx.device->GetDeviceRemovedReason(), compute ? "Compute batch device" : "Pixel batch device"); + if (compute) { + if (!program.pipeline) program = load_compute_store_program(ctx.device, shader); + check_compute_store_reference(ctx.device, program, ctx.argv[i]); + } else { + check_translated_pixel(ctx.device, shader, false, ctx.argv[i]); + } + after_case(index); + } catch (const ReadbackMismatch& e) { std::fprintf(stderr, "%s\n", e.what()); status = "mismatch"; } catch (const std::exception& e) { @@ -490,15 +498,15 @@ OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_dra return failed ? OperationResult{OutcomeKind::fail, nullptr} : OperationResult{OutcomeKind::pass, nullptr}; } -OperationResult run_check_pixel_batch(const OperationContext& ctx) +OperationResult run_check_batch(const OperationContext& ctx) { - return run_pixel_batch(ctx, [](int) {}); + return run_readback_batch(ctx, [](int) {}); } OperationResult run_pixel_batch_debug_control(const OperationContext& ctx) { if (!ctx.messages) return {OutcomeKind::skip, "skip: pixel batch control requires the D3D12 debug layer"}; - return run_pixel_batch(ctx, [&](int index) { + return run_readback_batch(ctx, [&](int index) { if (index == 1) check(ctx.messages->AddApplicationMessage(D3D12_MESSAGE_SEVERITY_ERROR, "pixel batch control error"), "Add pixel batch control message"); @@ -511,7 +519,7 @@ OperationResult run_pixel_batch_removal_control(const OperationContext& ctx) const HRESULT hr = ctx.device->QueryInterface(IID_PPV_ARGS(&device)); if (hr == E_NOINTERFACE) return {OutcomeKind::skip, "skip: pixel batch control requires ID3D12Device5"}; check(hr, "Query pixel batch control device"); - return run_pixel_batch(ctx, [&](int index) { + return run_readback_batch(ctx, [&](int index) { if (index == 1) device->RemoveDevice(); }); } @@ -1620,8 +1628,8 @@ constexpr CapabilityGate kGateSm66MinLod{ // Scenario-dependent capability checks (such as DXR tier, mesh tier, or existing-heap support) // remain inside the handlers and report OutcomeKind::skip. const OperationSpec kOperations[] = { - {"--check-pixel-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_pixel_batch}, - {"--check-pixel-pairs", 5, kUnboundedArgc, validate_pixel_pairs_args, kNoGate, run_check_pixel_batch}, + {"--check-pixel-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_batch}, + {"--check-pixel-pairs", 5, kUnboundedArgc, validate_pixel_pairs_args, kNoGate, run_check_batch}, {"--pixel-batch-debug-control", 7, 7, nullptr, kNoGate, run_pixel_batch_debug_control}, {"--pixel-batch-removal-control", 7, 7, nullptr, kNoGate, run_pixel_batch_removal_control}, {"--compute-root", 3, 3, nullptr, kNoGate, run_compute_root}, @@ -1629,6 +1637,7 @@ const OperationSpec kOperations[] = { {"--compute-root-file", 4, 4, nullptr, kNoGate, run_compute_root_file}, {"--ffx-immediate-conversion", 4, 4, nullptr, kNoGate, run_ffx_immediate_conversion}, {"--compute-store-case", 5, 5, nullptr, kNoGate, run_compute_store_case}, + {"--compute-store-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_batch}, {"--compute-store-sized-case", 5, 6, nullptr, kNoGate, run_compute_store_sized_case}, {"--compute-store-dpp-case", 5, 5, nullptr, kGateShaderWave, run_compute_store_dpp_case}, {"--compute-store-case-atomic64", 5, 5, nullptr, kGateComputeAtomic64, run_compute_store_case}, From 35e0a5d92dbe08ee541f17da23eb4a968463d455 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:38:17 +0200 Subject: [PATCH 11/29] runtime: add upfront CLI guards and atomic writes to bink_heap_aot with CLI suite (#2627) --- CMakeLists.txt | 3 + tests/bink_heap_aot_cli_check.py | 363 +++++++++++++++++++++++++++++++ tools/bink_heap_aot.py | 59 ++++- 3 files changed, 419 insertions(+), 6 deletions(-) create mode 100644 tests/bink_heap_aot_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ed89ff2ac..08f0f7f5a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10308,6 +10308,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(pe_run_package_trap_missing PROPERTIES TIMEOUT 60) add_test(NAME bink_heap_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_heap_aot_check.py") + add_test(NAME runtime_bink_heap_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bink_heap_aot_cli_check.py") + set_tests_properties(runtime_bink_heap_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_frame_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_frame_aot_check.py") add_test(NAME cpu_stdio_exe_aot_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/bink_heap_aot_cli_check.py b/tests/bink_heap_aot_cli_check.py new file mode 100644 index 000000000..49bc5af44 --- /dev/null +++ b/tests/bink_heap_aot_cli_check.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and error-handling suite for tools/bink_heap_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "bink_heap_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) +import bink_heap_aot # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include \n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) void* heap_request(word bytes) { return nullptr; }\n' +) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = bink_heap_aot.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class BinkHeapAotCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_new_dir_and_overwrite(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "heap_aot.cpp" + + # 1) Create missing parent directories and write atomically with 0 .tmp files. + with mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP) as gen: + code, out, err = _run_main([str(image), str(nested_out)]) + gen.assert_called_once_with(image, None, None) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["heap_aot.cpp"]) + + # 2) Forward --entries and --group-entry, and atomically overwrite existing file with 0 .tmp files. + nested_out.write_text("stale content", encoding="ascii") + entries_cpp = SYNTHETIC_CPP + "// entries-mode\n" + with mock.patch.object(bink_heap_aot, "generate", return_value=entries_cpp) as gen_entries: + code_ent, out_ent, err_ent = _run_main([ + str(image), + str(nested_out), + "--entries", + "0x1000", + "0x2000", + "--group-entry", + "heap_group", + ]) + gen_entries.assert_called_once_with(image, [0x1000, 0x2000], "heap_group") + self.assertEqual(code_ent, 0, err_ent) + self.assertEqual(out_ent, "") + self.assertEqual(err_ent, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), entries_cpp) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["heap_aot.cpp"]) + + # 3) Verify sys.argv forwarding when argv=None. + cli_argv = [str(TOOL), str(image), str(nested_out)] + with ( + mock.patch.object(sys, "argv", cli_argv), + mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # 4) Verify __main__ entrypoint propagates SystemExit cleanly on invalid PE. + bad_pe = base / "bad_main.dll" + bad_pe.write_bytes(b"not a PE") + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(bad_pe), str(base / "unused.cpp")]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout.getvalue(), "") + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertTrue(stderr.getvalue().strip()) + + +class BinkHeapAotCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "should_not_exist" / "heap_aot.cpp" + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + self.assertFalse(absent_out.parent.exists()) + + def test_invalid_pe_bytes_exit_1_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + bad_pe = base / "bad.dll" + bad_pe.write_bytes(b"not a valid PE32+ image") + absent_out = base / "absent_dir" / "heap_aot.cpp" + + self._assert_clean_failure( + [str(bad_pe), str(absent_out)], + expected_code=1, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_negative_entries_and_empty_group_entry_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_cpp = base / "absent_dir" / "heap_aot.cpp" + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid entries/group-entry"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid entries/group-entry"), + ), + ): + for label, argv, frags in ( + ("neg_alloc_rva", [str(image), str(out_cpp), "--entries", "-1", "0x2000"], ("non-negative",)), + ("neg_free_rva", [str(image), str(out_cpp), "--entries", "0x1000", "-4"], ("non-negative",)), + ("both_neg_rva", [str(image), str(out_cpp), "--entries", "-1", "-4"], ("non-negative",)), + ("empty_group_entry", [str(image), str(out_cpp), "--group-entry", ""], ("--group-entry",)), + ("blank_group_entry", [str(image), str(out_cpp), "--group-entry", " "], ("--group-entry",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags) + + self.assertFalse(out_cpp.parent.exists()) + + def test_output_guards_reject_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "heap_aot.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "heap_aot.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_atomic_write_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "heap_aot.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["heap_aot.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "heap_aot.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--entries", "0x1000"], ("expected 2 arguments",)), + ([str(image), str(out_cpp), "--entries", "bad", "0x2000"], ("invalid",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bink_heap_aot.py b/tools/bink_heap_aot.py index 430f39223..49455a304 100644 --- a/tools/bink_heap_aot.py +++ b/tools/bink_heap_aot.py @@ -1,6 +1,8 @@ """Lower the Bink callback setter and heap callers to a Windows DLL.""" import argparse from pathlib import Path +import struct +import tempfile import pefile from iced_x86 import Decoder, MemorySizeExt, Mnemonic as M, OpKind as K, Register as R @@ -208,7 +210,52 @@ def generate(image, entries, group_entry=None): """ + group -def main(argv=None): +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + if args.image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {args.image}") + if not args.image.is_file(): + raise FileNotFoundError(f"image file not found: {args.image}") + if args.entries is not None and any(rva < 0 for rva in args.entries): + raise ValueError("--entries RVAs must be non-negative") + if args.group_entry is not None and not args.group_entry.strip(): + raise ValueError("--group-entry must be non-empty") + if args.output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("output", type=Path) @@ -216,13 +263,13 @@ def main(argv=None): metavar=("ALLOC_RVA", "FREE_RVA")) parser.add_argument("--group-entry", help="Grouped allocation caller RVA or the fixture export heap_group") args = parser.parse_args(argv) - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") try: - args.output.write_text(generate(args.image, args.entries, args.group_entry), encoding="ascii") - except (ValueError, OSError, pefile.PEFormatError) as error: + _validate_args(args, parser) + _write_atomic(args.output, generate(args.image, args.entries, args.group_entry)) + except (ValueError, OSError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 0236873794ac49a0154a623fdbaa3c0b46fc7035 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:39:12 +0200 Subject: [PATCH 12/29] ci: harden coverage_svg validation and atomic writes with CLI suite (#2617) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/coverage_svg_cli_check.py | 448 ++++++++++++++++++++++++++++++++ tools/coverage_svg.py | 56 +++- 3 files changed, 501 insertions(+), 6 deletions(-) create mode 100644 tests/coverage_svg_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 08f0f7f5a..ad93d3a12 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4280,6 +4280,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/emit_variants_cli_check.py") add_test(NAME coverage_svg COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/coverage_svg_check.py") + add_test(NAME ci_coverage_svg_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/coverage_svg_cli_check.py") + set_tests_properties(ci_coverage_svg_cli_check PROPERTIES TIMEOUT 60) # Compile-only: outcome classification and GVN pass shares, no wall-time threshold (#775). add_test(NAME dxc_compile_time_gvn COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dxc_compile_time_check.py" "${DXC_EXECUTABLE}") diff --git a/tests/coverage_svg_cli_check.py b/tests/coverage_svg_cli_check.py new file mode 100644 index 000000000..149ad4628 --- /dev/null +++ b/tests/coverage_svg_cli_check.py @@ -0,0 +1,448 @@ +#!/usr/bin/env python3 +"""CLI, validation, collision, atomic-write, and mutation suite for tools/coverage_svg.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "coverage_svg.py" +sys.path.insert(0, str(ROOT / "tools")) + +import coverage_svg as cs # noqa: E402 + + +def _sample_coverage(): + return { + "x64_zen2": { + "covered": 4, + "total": 1007, + "blocked_by_skip": ["SSE movss"], + "groups": { + "Integer": {"covered": 3, "total": 1000}, + "SSE": {"covered": 1, "total": 6}, + "Tiny": {"covered": 0, "total": 1}, + "Zero": {"covered": 0, "total": 0}, + }, + }, + "gfx1013": { + "covered": 0, + "total": 0, + "blocked_by_skip": [], + "groups": { + "ZeroOnly": {"covered": 0, "total": 0}, + }, + }, + "gfx1030": { + "covered": 2, + "total": 5, + "blocked_by_skip": ["VOP3 v_add3_u32"], + "groups": { + "SOP1": {"covered": 2, "total": 3}, + "VOP3": {"covered": 0, "total": 2}, + }, + }, + } + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = cs.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class CoverageSvgCliPositiveTests(unittest.TestCase): + def test_direct_main_writes_svg_creates_parents_and_leaves_zero_tmp(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "nested" / "sub" / "dashboard.svg" + self.assertFalse(out_svg.parent.exists()) + + code, out, err = _run_main([str(cov), str(out_svg), "--source", "test-commit, test-os, warp"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertTrue(out_svg.is_file()) + self.assertEqual( + out_svg.read_text(encoding="utf-8"), + cs.render(data, "test-commit, test-os, warp"), + ) + self.assertEqual([p.name for p in out_svg.parent.iterdir()], ["dashboard.svg"]) + + def test_sys_argv_and_script_entrypoint(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "out" / "entry.svg" + cli_argv = [str(TOOL), str(cov), str(out_svg), "--source", "entry-banner"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertIn("Measured on entry-banner.", out_svg.read_text(encoding="utf-8")) + + out_svg.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(out_svg.is_file()) + + def test_subprocess_end_to_end_positive(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "sub.svg" + + proc = _run_subprocess(str(cov), str(out_svg), "--source", "sub-banner") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual(out_svg.read_text(encoding="utf-8"), cs.render(data, "sub-banner")) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + +class CoverageSvgCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure(self, argv, *, expected_fragment, expected_code=1, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + if expected_code == 1: + self.assertIn("coverage_svg:", err) + else: + self.assertIn("usage:", err.lower()) + if expected_fragment: + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + if expected_code == 1: + self.assertIn("coverage_svg:", proc.stderr) + else: + self.assertIn("usage:", proc.stderr.lower()) + if expected_fragment: + self.assertIn(expected_fragment, proc.stderr) + + def test_empty_and_whitespace_source_rejected_upfront_and_in_render(self): + data = _sample_coverage() + for bad_source in ("", " ", "\t\n", None): + with self.subTest(bad_source=bad_source): + with self.assertRaisesRegex(ValueError, "source"): + cs.render(data, bad_source) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "never_created" / "out.svg" + + for bad_source in ("", " ", "\t\n"): + with self.subTest(cli_source=bad_source): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(out_svg), "--source", bad_source], + expected_fragment="--source must not be empty", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + def test_render_rejects_bool_negative_and_covered_gt_total_counts(self): + def _mutated(mutator): + sample = _sample_coverage() + mutator(sample) + return sample + + cases = ( + ("area_bool_covered", lambda d: d["x64_zen2"].__setitem__("covered", True), TypeError, "integers"), + ("area_bool_total", lambda d: d["x64_zen2"].__setitem__("total", False), TypeError, "integers"), + ("area_float_covered", lambda d: d["x64_zen2"].__setitem__("covered", 1.5), TypeError, "integers"), + ("area_neg_covered", lambda d: d["x64_zen2"].__setitem__("covered", -1), ValueError, "non-negative"), + ("area_neg_total", lambda d: d["x64_zen2"].__setitem__("total", -1), ValueError, "non-negative"), + ( + "area_covered_gt_total", + lambda d: d["x64_zen2"].__setitem__("covered", d["x64_zen2"]["total"] + 1), + ValueError, + "exceed total", + ), + ("group_bool_covered", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("covered", True), TypeError, "integers"), + ("group_bool_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", True), TypeError, "integers"), + ("group_float_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", 2.5), TypeError, "integers"), + ("group_neg_covered", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("covered", -1), ValueError, "non-negative"), + ("group_neg_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", -1), ValueError, "non-negative"), + ( + "group_covered_gt_total", + lambda d: d["x64_zen2"]["groups"]["SSE"].__setitem__("covered", 7), + ValueError, + "exceed total", + ), + ) + for name, mutator, exc_type, fragment in cases: + with self.subTest(case=name): + with self.assertRaisesRegex(exc_type, fragment): + cs.render(_mutated(mutator), "banner") + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_svg = root / "never" / "out.svg" + for name, mutator, _, fragment in cases: + with self.subTest(cli_case=name): + cov = root / f"{name}.json" + cov.write_text(json.dumps(_mutated(mutator)), encoding="utf-8") + self._assert_clean_failure( + [str(cov), str(out_svg), "--source", "banner"], + expected_fragment=fragment, + ) + self.assertFalse(out_svg.parent.exists()) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + def test_coverage_input_missing_dir_and_non_regular_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.json" + dir_in = root / "dir_in" + dir_in.mkdir() + reg_in = root / "coverage.json" + reg_in.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + out_svg = root / "never" / "out.svg" + + for path, frag in ( + (missing, "coverage file not found"), + (dir_in, "coverage path is a directory"), + ): + with self.subTest(path=path): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(path), str(out_svg), "--source", "banner"], + expected_fragment=frag, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + with ( + mock.patch.object(Path, "is_file", return_value=False), + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(reg_in), str(out_svg), "--source", "banner"], + expected_fragment="regular file", + check_subprocess=False, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + def test_output_dir_symlink_file_parent_and_samefile_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + cov_bytes = cov.read_bytes() + + # 1) Existing directory output rejected upfront. + out_dir = root / "existing_dir" + out_dir.mkdir() + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(out_dir), "--source", "banner"], + expected_fragment="existing directory", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(list(out_dir.iterdir()), []) + + # 2) Output symlink rejected upfront (real symlink if permitted, else mocked). + target = root / "keep_target.svg" + target.write_text("keep-target", encoding="utf-8") + sym_out = root / "link.svg" + try: + sym_out.symlink_to(target) + created_real = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_real = False + + if created_real: + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(sym_out), "--source", "banner"], + expected_fragment="symbolic link", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + sym_out.unlink() + else: + with ( + mock.patch.object( + Path, + "is_symlink", + autospec=True, + side_effect=lambda p, expected=sym_out: p.resolve() == expected.resolve(), + ), + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(sym_out), "--source", "banner"], + expected_fragment="symbolic link", + check_subprocess=False, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(target.read_text(encoding="utf-8"), "keep-target") + + # 3) File-parent output (direct and nested under regular file) rejected upfront. + file_parent = root / "regular_parent" + file_parent.write_text("keep-parent", encoding="utf-8") + for bad_out in (file_parent / "out.svg", file_parent / "nested" / "out.svg"): + with self.subTest(file_parent_out=bad_out): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(bad_out), "--source", "banner"], + expected_fragment="parent path is not a directory", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-parent") + + # 4) Output colliding with input via exact path, resolve() alias, and hardlink samefile(). + alias_out = sub / ".." / "coverage.json" + hardlink_out = sub / "hardlink.svg" + os.link(cov, hardlink_out) + self.assertNotEqual(cov.resolve(), hardlink_out.resolve()) + self.assertTrue(cov.samefile(hardlink_out)) + + for label, bad_out in (("exact", cov), ("alias", alias_out), ("samefile", hardlink_out)): + with self.subTest(collision=label): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(bad_out), "--source", "banner"], + expected_fragment="must not match input", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(cov.read_bytes(), cov_bytes) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + self.assertFalse(any(p.name.endswith(".tmp") for p in sub.iterdir())) + + def test_bad_json_and_atomic_write_failure_leave_zero_tmp_files(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + bad_json = root / "bad.json" + bad_json.write_text("{not json", encoding="utf-8") + never_out = root / "never" / "out.svg" + self._assert_clean_failure( + [str(bad_json), str(never_out), "--source", "banner"], + expected_fragment="Expecting", + ) + self.assertFalse(never_out.parent.exists()) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + sentinel_dir = root / "sentinel_dir" + sentinel_dir.mkdir() + sentinel = sentinel_dir / "keep.svg" + sentinel.write_text("prior-svg", encoding="utf-8") + + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(cov), str(sentinel), "--source", "banner"], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(sentinel.read_text(encoding="utf-8"), "prior-svg") + self.assertEqual([p.name for p in sentinel_dir.iterdir()], ["keep.svg"]) + + def test_argparse_errors_py314_compatible_exit_2_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + out_svg = root / "out.svg" + + for bad_argv in ( + [], + [str(cov)], + [str(cov), str(out_svg)], + [str(cov), str(out_svg), "--source"], + [str(cov), str(out_svg), "--source", "ok", "--unknown-flag"], + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure( + bad_argv, + expected_fragment="", + expected_code=2, + ) + self.assertFalse(out_svg.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/coverage_svg.py b/tools/coverage_svg.py index cf3dbeb55..e90a51e0f 100644 --- a/tools/coverage_svg.py +++ b/tools/coverage_svg.py @@ -104,7 +104,23 @@ def group(name, counts, x, y, w, h): return "".join(parts) + "", labelled +def _validate_counts(covered, total, scope: str) -> None: + if ( + isinstance(covered, bool) + or not isinstance(covered, int) + or isinstance(total, bool) + or not isinstance(total, int) + ): + raise TypeError(f"{scope} counts must be integers") + if total < 0 or covered < 0: + raise ValueError(f"{scope} counts must be non-negative") + if covered > total: + raise ValueError(f"{scope} covered count ({covered}) must not exceed total ({total})") + + def render(m, source): + if not isinstance(source, str) or not source.strip(): + raise ValueError("--source must not be empty") if not isinstance(m, dict): raise TypeError("coverage root must be a JSON object") rows = [text(20, 34, "Instruction-form coverage", 20, bold=True), text(20, 56, NOTE, 12, MUTED), @@ -119,6 +135,7 @@ def render(m, source): groups = r["groups"] if not isinstance(blocked, list) or not isinstance(groups, dict): raise TypeError(f"{key} entry has invalid blocked_by_skip or groups") + _validate_counts(r["covered"], r["total"], key) held = {} for form in blocked: if not isinstance(form, str): @@ -137,8 +154,7 @@ def render(m, source): raise TypeError(f"{key}.{g} must be a JSON object") total = v["total"] covered = v["covered"] - if total < 0 or covered < 0: - raise ValueError(f"{key}.{g} counts must be non-negative") + _validate_counts(covered, total, f"{key}.{g}") if total > 0: items.append((g, total)) items.sort(key=lambda kv: -kv[1]) @@ -180,6 +196,35 @@ def _write_atomic(path: Path, content: str) -> None: raise +def _same_path(left: Path, right: Path) -> bool: + if left == right: + return True + if left.exists() and right.exists() and left.samefile(right): + return True + try: + return left.resolve() == right.resolve() + except OSError: + return False + + +def _validate_paths(coverage: Path, output: Path) -> None: + if not coverage.exists(): + raise FileNotFoundError(f"coverage file not found: {coverage}") + if coverage.is_dir(): + raise IsADirectoryError(f"coverage path is a directory: {coverage}") + if not coverage.is_file(): + raise ValueError(f"coverage path must be a regular file: {coverage}") + if output.is_symlink(): + raise ValueError(f"output path must not be a symbolic link: {output}") + if output.exists() and output.is_dir(): + raise IsADirectoryError(f"output path is an existing directory: {output}") + for parent in output.parents: + if (parent.exists() or parent.is_symlink()) and not parent.is_dir(): + raise ValueError(f"output parent path is not a directory: {parent}") + if _same_path(output, coverage): + raise ValueError(f"output path must not match input path: {output}") + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("coverage", type=Path, help="JSON written by form_coverage.py --json") @@ -187,10 +232,9 @@ def main(argv=None) -> int: parser.add_argument("--source", required=True, help="commit, OS build and adapter of the measured run") args = parser.parse_args(argv) try: - coverage_path = args.coverage.resolve() - output_path = args.output.resolve() - if output_path == coverage_path: - raise ValueError(f"output path must not match input path: {args.output}") + if not args.source.strip(): + raise ValueError("--source must not be empty") + _validate_paths(args.coverage, args.output) svg = render(json.loads(args.coverage.read_text(encoding="utf-8")), args.source) _write_atomic(args.output, svg) except (OSError, ValueError, KeyError, TypeError) as exc: From 0f09473fa6f42e0049b47f28f6364aafafd826eb Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Wed, 25 Nov 2026 17:41:04 -0600 Subject: [PATCH 13/29] shader: classify RDNA2 permlane operations as cross-lane (#2628) - Preserve ordinary vector ALU classification and translator refusal. - Exercise the authored encodings and dashboard categories. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 10 +++++++ tests/rdna2_tools_check.py | 48 +++++++++++++++++++++++++++++++ tools/scan_unsupported_shaders.py | 10 ++++++- 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index f593934ce..27e29d30e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13994,6 +13994,16 @@ python3 -B tests/rdna2_tools_check.py Scope: recognition only. No translator lowers these forms through this change, and no hardware or Windows run backs them. +## RDNA2 lane permutations in the unsupported-shader report + +`tools/scan_unsupported_shaders.py` reports `v_permlane16_b32` and +`v_permlanex16_b32` as `VALU (Cross-lane)` in `unsupported_details`. +The former can gather a value from another lane in the same 16-lane row. +The latter selects from the paired row. Both remain unsupported by the +pixel translator with either a declared wave32 or wave64 layout. The +lane-local byte-selection instruction `v_perm_b32` retains its ordinary +VALU classification. [AMD RDNA 2 ISA, §12.12](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) + ## gfx1013 VOP1 rounding, frexp and operand-free opcodes `tools/disasm_rdna2.py` named only part of the VOP1 table; eleven opcodes in two contiguous gaps printed as `v_vop1_NN` diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 1b197796d..2aaaf9789 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -4309,6 +4309,54 @@ def test_decoded_scalar_control_forms_are_recognized(self): ) self.assertEqual(missing, []) + def test_permlane_cross_lane_census_preserves_lowering_refusal(self): + # gfx1013 VOP3 bytes use the same valid VGPR/SGPR operands in all three forms. + encodings = ( + ("000077d701050c00", "v_permlane16_b32", "VALU (Cross-lane)"), + ("000078d701050c00", "v_permlanex16_b32", "VALU (Cross-lane)"), + ("000044d701050c00", "v_perm_b32", "VALU (Vector ALU)"), + ) + results = [] + for wave_size in (32, 64): + for encoding, opcode, category in encodings: + with self.subTest(wave_size=wave_size, opcode=opcode): + instruction = disasm_rdna2(bytes.fromhex(encoding))[0]["assembly"] + self.assertEqual(instruction, f"{opcode} v0, v1, s2, s3") + shader = [ + "v_mov_b32_e32 v1, 1", + "s_mov_b32 s2, 0", + "s_mov_b32 s3, 0", + instruction, + "v_cvt_pkrtz_f16_f32_e32 v16, v0, v0", + "exp mrt0 v16, v16, v16, v16 done compr vm", + "s_endpgm", + ] + record = analyze_shader_instructions( + f"ps_{opcode}_wave{wave_size}", shader, wave_size=wave_size + ) + self.assertTrue(record["opcodes_recognized"]) + self.assertFalse(record["translator_accepted"]) + self.assertEqual(record["compatibility_category"], "opcode_recognized_translator_rejected") + self.assertEqual(record["lower_error_kind"], "translator_rejection") + self.assertEqual(record["lower_error"], f"Unsupported instruction 3: {instruction}") + self.assertEqual(record["unsupported_details"], [ + {"line_number": 4, "raw": instruction, "opcode": opcode, "category": category}, + ]) + results.append(record) + + with tempfile.TemporaryDirectory() as tmp: + json_file, _ = generate_progress_dashboard(results, Path(tmp)) + report = json.loads(json_file.read_text(encoding="utf-8")) + cross_lane = report["subsystems"]["VALU (Cross-lane)"] + self.assertEqual(cross_lane["total_instructions"], 4) + self.assertEqual(cross_lane["distinct_opcodes"], 2) + self.assertCountEqual(cross_lane["top_opcodes"], ["v_permlane16_b32", "v_permlanex16_b32"]) + missing = {row["opcode"]: row for row in report["missing_opcodes_ranked"]} + for _, opcode, category in encodings: + self.assertEqual(missing[opcode]["category"], category) + self.assertEqual(missing[opcode]["occurrences"], 2) + + def test_accepted_full_shader(self): """Canonical straight-line pixel shader accepted by pixel_aot translator.""" canonical_shader = [ diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 6e32ee9f6..b81d26544 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -482,11 +482,15 @@ def lower_rejection_causes(results: list[dict]) -> dict: } ) +OPCODE_ENCODING_SUFFIX = re.compile(r"_(?:e32|e64|sdwa|dpp.*)$") +CROSS_LANE_VALU_OPCODES = {"v_permlane16_b32", "v_permlanex16_b32"} +CROSS_LANE_VALU_CATEGORY = "VALU (Cross-lane)" + def is_opcode_recognized(opcode: str) -> bool: """Check if opcode belongs to recognized AMD RDNA 2 ISA instructions.""" clean = opcode.strip().lower() - base = re.sub(r"_(?:e32|e64|sdwa|dpp.*)$", "", clean) + base = OPCODE_ENCODING_SUFFIX.sub("", clean) if base in KNOWN_RDNA2_BASE_OPCODES or clean in KNOWN_RDNA2_BASE_OPCODES: return True if base.startswith(("v_cmp_", "v_cmpx_")) or clean.startswith(("v_cmp_", "v_cmpx_")): @@ -501,6 +505,8 @@ def is_opcode_recognized(opcode: str) -> bool: def classify_isa_category(opcode: str) -> str: """Classify instruction into RDNA 2 ISA category according to the AMD manual.""" op = opcode.lower() + if OPCODE_ENCODING_SUFFIX.sub("", op.strip()) in CROSS_LANE_VALU_OPCODES: + return CROSS_LANE_VALU_CATEGORY if op.startswith("v_interp"): return "VINTRP (Parameter Interpolation)" if op.startswith("v_"): @@ -899,6 +905,8 @@ def make_progress_bar(percentage: float, width: int = 24, unicode_blocks: bool = def get_implementation_target(opcode: str, category: str) -> str: """Identify target file and subsystem in Xbox2Windows for an opcode.""" op = opcode.lower() + if category == CROSS_LANE_VALU_CATEGORY: + return "`tools/pixel_aot.py` (Wave lane layout, active lanes and bound control)" if "VALU" in category or "Vector ALU" in category: if any(x in op for x in ["_f32", "_f16", "_i32", "_u32"]): return "`tools/pixel_aot.py` (ALU dictionary / table)" From aa1b512cdb2330226e6d40f20c69d50fcac5d8e0 Mon Sep 17 00:00:00 2001 From: lukaslw-lab Date: Thu, 26 Nov 2026 00:42:28 +0100 Subject: [PATCH 14/29] d3d12: do not wrap large allocations for unplaced memory SRVs (#2611) An unplaced buffer memory SRV (device slot 70, #2395) wrapped the whole allocation holding the view with OpenExistingHeapFromAddress. A 6 KiB view in a ~2.15 GiB title startup block wrapped the block; afterwards each VirtualQuery over it took seconds and DirectStorage requests stalled for ~120 s. Wrap only allocations up to the existing 256 MiB span limit (size from one region-information call); larger ones take the upload copy. Co-authored-by: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- CMakeLists.txt | 2 +- src/startup_stubs/d3d12_memory_srv.inl | 5 +++-- src/startup_stubs/memory_srv_buffer.h | 13 ++++++++++++- src/startup_stubs/placed_buffer_range.h | 12 ++++++++++++ tests/startup_address_buffer_srv_check.py | 4 ++-- tests/startup_address_srv.cpp | 10 ++++++++++ tests/startup_memory_srv_buffer_check.cpp | 15 +++++++++++++-- tests/startup_placed_buffer_range_check.cpp | 19 +++++++++++++++++++ 8 files changed, 72 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ad93d3a12..6a8cf15c5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1982,7 +1982,7 @@ add_executable(startup_memory_srv_buffer_check tests/startup_memory_srv_buffer_c target_include_directories(startup_memory_srv_buffer_check PRIVATE src) target_compile_features(startup_memory_srv_buffer_check PRIVATE cxx_std_17) add_test(NAME startup_memory_srv_buffer COMMAND startup_memory_srv_buffer_check) -foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-covers) +foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-covers unplaced-heap-limit) add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 673084c38..f57e607db 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -258,7 +258,8 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) } // Backing for unplaced buffer memory SRVs: 64 KiB page-aligned placed resource on an existing heap -// (OpenExistingHeapFromAddress zero-copy aliasing on hardware) or committed UPLOAD buffer (fallback). +// (OpenExistingHeapFromAddress zero-copy aliasing on hardware, allocations up to 256 MiB) or committed UPLOAD +// buffer (fallback). struct UnplacedBufferEntry { Wrapper* device = nullptr; void* allocation_base = nullptr; @@ -350,7 +351,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co break; } } - if (!heap) { + if (!heap && x2w_startup::unplaced_existing_heap_allowed(x2w_startup::allocation_bytes(memory.base))) { ID3D12Device3* device3 = nullptr; if (SUCCEEDED(desktop->QueryInterface(IID_PPV_ARGS(&device3)))) { if (SUCCEEDED(device3->OpenExistingHeapFromAddress(memory.base, IID_PPV_ARGS(&heap)))) { diff --git a/src/startup_stubs/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h index 4031efe12..b24be40d5 100644 --- a/src/startup_stubs/memory_srv_buffer.h +++ b/src/startup_stubs/memory_srv_buffer.h @@ -127,6 +127,17 @@ inline bool resolve_buffer_srv_desc(std::uint64_t buffer_title_base, std::uint64 return true; } +// Largest unplaced buffer span, and largest allocation an unplaced buffer may wrap as an existing heap. +constexpr std::uint64_t unplaced_max_span = 256ull << 20; + +// OpenExistingHeapFromAddress wraps the whole allocation holding the view, not just the view's pages. A few KiB +// view in a multi-GiB title block must not wrap the block (afterwards each VirtualQuery over the block took +// seconds), so allocations of unknown size (0) or above the span limit take the upload copy instead. +inline bool unplaced_existing_heap_allowed(std::uint64_t allocation_bytes) +{ + return allocation_bytes && allocation_bytes <= unplaced_max_span; +} + // Calculates 64 KiB page-aligned extent and byte span for unplaced buffer memory SRVs. // Returns false on zero address/bytes, arithmetic overflow, or when the span exceeds the maximum allowable limit (256 MiB). inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_bytes, @@ -134,7 +145,7 @@ inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_byt { constexpr std::uint64_t alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; constexpr std::uint64_t mask = alignment - 1; - constexpr std::uint64_t max_span = 256ull << 20; + constexpr std::uint64_t max_span = unplaced_max_span; if (!address || !span_bytes || span_bytes > ~std::uint64_t{0} - address) return false; page_start = address & ~mask; const std::uint64_t end = address + span_bytes; diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index 456cdfe6b..6e8bc3c4c 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -58,6 +58,18 @@ inline QueryRegion query_region() } } // namespace placed_detail +// Size of the whole allocation holding address, from one region-information call (no page-table scan); +// 0 when the call is missing or fails. +inline std::uint64_t allocation_bytes(const void* address) +{ + placed_detail::RegionInformation info{}; + SIZE_T returned = 0; + const placed_detail::QueryRegion query = placed_detail::query_region(); + if (!address || !query || !query(GetCurrentProcess(), address, 0 /* MemoryRegionInfo */, &info, sizeof(info), &returned)) + return 0; + return info.RegionSize; +} + // False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is // exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the // full walk measures. diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 44c6304f0..c8ebc7c8f 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -50,13 +50,13 @@ def check(directory, consumer, backend): ) if actual is None: return 77 - values = (17, 63, 141, 141, 99, 17, 17, 17) + values = (17, 63, 141, 141, 99, 17, 17, 77) row = b"".join(bytes((v, 0, 0, 255)) for v in values) expected = row * 4 if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") check_refusal_lines(trap_log.read_text(errors="replace")) - print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view) exact") + print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view, unplaced buffer in a large allocation copied) exact") return 0 diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index d2a72fc2d..1dab72a30 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -533,6 +533,16 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(5); draw(6); + + // An unplaced buffer in an allocation above the 256 MiB limit is not wrapped as an existing heap; its + // upload copy must still publish the bytes at the address. + static auto* const large = static_cast( + VirtualAlloc(nullptr, (256ull << 20) + 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!large) return 53; + large[4] = 77; + raw.address = ptr(large); + raw.view.Buffer.FirstElement = 4; + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(7); return 0; } diff --git a/tests/startup_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp index abc4c7005..cced3c949 100644 --- a/tests/startup_memory_srv_buffer_check.cpp +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -5,6 +5,7 @@ // --mutate first-32: expect a resolved FirstElement above 4 Gi elements to be cut to 32 bits. // --mutate unplaced-extent: expect page span calculation crossing a 64 KiB boundary to return a single page. // --mutate unplaced-covers: expect a buffer range past the end of the cached page to be accepted as covered. +// --mutate unplaced-heap-limit: expect a 2 GiB allocation to be wrapped as an existing heap for an unplaced buffer. // Each mutated run is a negative control and must fail. #include "startup_stubs/memory_srv_buffer.h" @@ -84,10 +85,11 @@ int main(int argc, char** argv) if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && (std::strcmp(argv[2], "height") == 0 || std::strcmp(argv[2], "exact-fit") == 0 || std::strcmp(argv[2], "first-32") == 0 || - std::strcmp(argv[2], "unplaced-extent") == 0 || std::strcmp(argv[2], "unplaced-covers") == 0)) { + std::strcmp(argv[2], "unplaced-extent") == 0 || std::strcmp(argv[2], "unplaced-covers") == 0 || + std::strcmp(argv[2], "unplaced-heap-limit") == 0)) { mutation = argv[2]; } else if (argc != 1) { - std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32|unplaced-extent|unplaced-covers]\n"); + std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32|unplaced-extent|unplaced-covers|unplaced-heap-limit]\n"); return 2; } const auto buf = buffer_desc(1024); @@ -301,6 +303,15 @@ int main(int argc, char** argv) check("unplaced covers zero cached span", !x2w_startup::unplaced_buffer_covers(0x10000, 0, 0x10000, 48)); check("unplaced covers zero requested span", !x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x10000, 0)); + // Existing-heap wrap of the allocation holding an unplaced buffer: up to the 256 MiB span limit only. + check("unplaced heap 64 KiB allocation", x2w_startup::unplaced_existing_heap_allowed(65536)); + check("unplaced heap 256 MiB allocation", x2w_startup::unplaced_existing_heap_allowed(256ull << 20)); + check("unplaced heap 256 MiB + 64 KiB allocation", + !x2w_startup::unplaced_existing_heap_allowed((256ull << 20) + 65536)); + check("unplaced heap 2 GiB allocation", + x2w_startup::unplaced_existing_heap_allowed(2ull << 30) == mutated("unplaced-heap-limit")); + check("unplaced heap unknown allocation size", !x2w_startup::unplaced_existing_heap_allowed(0)); + if (failures) return 1; std::printf("slot 70 buffer memory SRV validation: all checks passed\n"); return 0; diff --git a/tests/startup_placed_buffer_range_check.cpp b/tests/startup_placed_buffer_range_check.cpp index 2b395c945..b5806b6cf 100644 --- a/tests/startup_placed_buffer_range_check.cpp +++ b/tests/startup_placed_buffer_range_check.cpp @@ -27,6 +27,8 @@ // it. Decisions as above; in addition every placement must be proven without VirtualQuery (a call // count, not a time). The time per placement of the full walk, the bounded walk and the exact // proof is printed. +// 10. allocation_bytes (the unplaced slot 70 path's existing-heap limit): 64 KiB and 256 MiB + 64 KiB +// reservations with only their first page committed, asked at the base and at the last byte. // // --mutate region-only trusts the allocation size without checking that every page is committed: it // passes (exits 0) only if decisions differ in the partly committed cases and nowhere else. @@ -411,6 +413,23 @@ int main(int argc, char** argv) } } + // Case 10: allocation_bytes reports the whole allocation from any address in it, committed or not. + { + const SIZE_T sizes[] = {page, (SIZE_T{256} << 20) + page}; + for (const SIZE_T bytes : sizes) { + auto* block = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS)); + if (!block || !VirtualAlloc(block, page, MEM_COMMIT, PAGE_READWRITE)) { + setup_fail("cannot reserve the allocation-size block", block); + if (block) VirtualFree(block, 0, MEM_RELEASE); + continue; + } + if (x2w_startup::allocation_bytes(block) != bytes) fail("allocation_bytes at the base", block); + if (x2w_startup::allocation_bytes(block + bytes - 1) != bytes) fail("allocation_bytes at the last byte", block); + VirtualFree(block, 0, MEM_RELEASE); + } + if (x2w_startup::allocation_bytes(nullptr) != 0) fail("allocation_bytes of a null address", nullptr); + } + std::printf("all %llu placements: VirtualQuery calls full walk %llu, measured %llu\n", placements, full_queries, exact_queries); const int total = failures[other] + failures[partial] + failures[cost]; From bb1addf295f5c42b8ca5f4748ea4266fcc8ce72b Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:43:35 +0200 Subject: [PATCH 15/29] cpu: lower VEX.128/256 AVX horizontal and addsub FP ops in cpu_avx_horiz_fp_aot (#2629) --- CMakeLists.txt | 29 ++ tests/cpu/avx_horiz_fp_aot.asm | 329 ++++++++++++++++++++++ tests/cpu/avx_horiz_fp_aot.def | 32 +++ tests/cpu/avx_horiz_fp_aot_check.py | 419 ++++++++++++++++++++++++++++ tools/cpu_avx_horiz_fp_aot.py | 403 ++++++++++++++++++++++++++ 5 files changed, 1212 insertions(+) create mode 100644 tests/cpu/avx_horiz_fp_aot.asm create mode 100644 tests/cpu/avx_horiz_fp_aot.def create mode 100644 tests/cpu/avx_horiz_fp_aot_check.py create mode 100644 tools/cpu_avx_horiz_fp_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a8cf15c5..fb6084cec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6976,6 +6976,35 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_avx_horiz_fp PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_avx_horiz_fp_dedicated + set(cpu_avx_horiz_fp_aot_exports + "op_vhaddps_xmm_reg,op_vhaddpd_xmm_reg,op_vhsubps_xmm_reg,op_vhsubpd_xmm_reg," + "op_vaddsubps_xmm_reg,op_vaddsubpd_xmm_reg," + "op_vhaddps_xmm_mem,op_vhaddpd_xmm_mem,op_vhsubps_xmm_mem,op_vhsubpd_xmm_mem," + "op_vaddsubps_xmm_mem,op_vaddsubpd_xmm_mem," + "op_vhaddps_ymm_reg,op_vhaddpd_ymm_reg,op_vhsubps_ymm_reg,op_vhsubpd_ymm_reg," + "op_vaddsubps_ymm_reg,op_vaddsubpd_ymm_reg," + "op_vhaddps_ymm_mem,op_vhaddpd_ymm_mem,op_vhsubps_ymm_mem,op_vhsubpd_ymm_mem," + "op_vaddsubps_ymm_mem,op_vaddsubpd_ymm_mem," + "op_vhaddps_ymm_mem_rcx,op_vaddsubpd_ymm_mem_r8," + "op_vhaddps_ymm_alias_dst_src1,op_vhaddpd_ymm_alias_dst_src2," + "op_vhsubps_ymm_alias_src1_src2,op_vaddsubps_ymm_alias_all,op_vaddsubpd_xmm_alias_dst_src2") + string(CONCAT cpu_avx_horiz_fp_aot_exports ${cpu_avx_horiz_fp_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_horiz_fp_aot_${variant} avx_horiz_fp_aot) + cpu_translation(cpu_avx_horiz_fp_aot_${variant} cpu_avx_horiz_fp_aot "${cpu_avx_horiz_fp_aot_exports}") + endforeach() + target_compile_definitions(cpu_avx_horiz_fp_aot_altered PRIVATE ALTER_AVX_HORIZ_FP) + add_test(NAME cpu_aot_avx_horiz_fp_dedicated COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_horiz_fp_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_horiz_fp_dedicated PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_horiz_fp_dedicated.txt") + cpu_asm_fixture(cpu_avx_addsub_fp avx_addsub_fp) set(avx_addsub_fp_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_avx_addsub_fp_lifted.cpp") add_custom_command(OUTPUT "${avx_addsub_fp_fixture}" diff --git a/tests/cpu/avx_horiz_fp_aot.asm b/tests/cpu/avx_horiz_fp_aot.asm new file mode 100644 index 000000000..7678a4a82 --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot.asm @@ -0,0 +1,329 @@ +; coverage: record cpu_aot_avx_horiz_fp_dedicated +; Source-owned MASM fixture for VEX.128 and VEX.256 AVX horizontal and alternating +; floating-point add/sub ops (vhaddps, vhaddpd, vhsubps, vhsubpd, vaddsubps, vaddsubpd). +; ABI: void fn(const void* rcx, const void* rdx, void* r8). +.code + +op_vhaddps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vhaddps xmm0, xmm1, xmm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_xmm_reg ENDP + +op_vhaddpd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhaddpd ymm0, ymm1, ymm2 +ELSE + vhaddpd xmm0, xmm1, xmm2 +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_xmm_reg ENDP + +op_vhsubps_xmm_reg PROC FRAME + .endprolog + vmovaps ymm0, YMMWORD PTR [r8] + vmovaps ymm1, YMMWORD PTR [rcx] + vmovaps ymm2, YMMWORD PTR [rdx] + vhsubps xmm0, xmm1, xmm2 + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_xmm_reg ENDP + +op_vhsubpd_xmm_reg PROC FRAME + .endprolog + vmovapd ymm0, YMMWORD PTR [r8] + vmovapd ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vhsubpd xmm0, xmm1, xmm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_xmm_reg ENDP + +op_vaddsubps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vaddsubps xmm0, xmm1, xmm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_xmm_reg ENDP + +op_vaddsubpd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vaddsubpd xmm0, xmm1, xmm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_reg ENDP + +op_vhaddps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vhaddps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_xmm_mem ENDP + +op_vhaddpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vhaddpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_xmm_mem ENDP + +op_vhsubps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_xmm_mem ENDP + +op_vhsubpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vhsubpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_xmm_mem ENDP + +op_vaddsubps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vaddsubps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_xmm_mem ENDP + +op_vaddsubpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vaddsubpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_mem ENDP + +op_vhaddps_ymm_reg PROC FRAME + .endprolog + vmovaps ymm1, YMMWORD PTR [rcx] + vmovaps ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhsubps ymm0, ymm1, ymm2 +ELSE + vhaddps ymm0, ymm1, ymm2 +ENDIF + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_reg ENDP + +op_vhaddpd_ymm_reg PROC FRAME + .endprolog + vmovapd ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vhaddpd ymm0, ymm1, ymm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_reg ENDP + +op_vhsubps_ymm_reg PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vhsubps ymm0, ymm1, ymm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_reg ENDP + +op_vhsubpd_ymm_reg PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vhsubpd ymm0, ymm1, ymm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_ymm_reg ENDP + +op_vaddsubps_ymm_reg PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhaddps ymm0, ymm1, ymm2 +ELSE + vaddsubps ymm0, ymm1, ymm2 +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_reg ENDP + +op_vaddsubpd_ymm_reg PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vaddsubpd ymm0, ymm1, ymm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_reg ENDP + +op_vhaddps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhaddps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_mem ENDP + +op_vhaddpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vhaddpd ymm0, ymm1, YMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_mem ENDP + +op_vhsubps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_mem ENDP + +op_vhsubpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vhsubpd ymm0, ymm1, YMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_ymm_mem ENDP + +op_vaddsubps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vaddsubps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_mem ENDP + +op_vaddsubpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_AVX_HORIZ_FP + vhsubpd ymm0, ymm1, YMMWORD PTR [rdx] +ELSE + vaddsubpd ymm0, ymm1, YMMWORD PTR [rdx] +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_mem ENDP + +op_vhaddps_ymm_mem_rcx PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rdx] + vhaddps ymm0, ymm1, YMMWORD PTR [rcx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_mem_rcx ENDP + +op_vaddsubpd_ymm_mem_r8 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vaddsubpd ymm0, ymm1, YMMWORD PTR [r8] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_mem_r8 ENDP + +op_vhaddps_ymm_alias_dst_src1 PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vmovups ymm1, YMMWORD PTR [rdx] + vhaddps ymm0, ymm0, ymm1 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_alias_dst_src1 ENDP + +op_vhaddpd_ymm_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vhaddpd ymm0, ymm1, ymm0 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_alias_dst_src2 ENDP + +op_vhsubps_ymm_alias_src1_src2 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps ymm0, ymm1, ymm1 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_alias_src1_src2 ENDP + +op_vaddsubps_ymm_alias_all PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vaddsubps ymm0, ymm0, ymm0 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_alias_all ENDP + +op_vaddsubpd_xmm_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vaddsubpd xmm0, xmm1, xmm0 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_alias_dst_src2 ENDP + +END diff --git a/tests/cpu/avx_horiz_fp_aot.def b/tests/cpu/avx_horiz_fp_aot.def new file mode 100644 index 000000000..b0a2748a6 --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot.def @@ -0,0 +1,32 @@ +EXPORTS + op_vhaddps_xmm_reg + op_vhaddpd_xmm_reg + op_vhsubps_xmm_reg + op_vhsubpd_xmm_reg + op_vaddsubps_xmm_reg + op_vaddsubpd_xmm_reg + op_vhaddps_xmm_mem + op_vhaddpd_xmm_mem + op_vhsubps_xmm_mem + op_vhsubpd_xmm_mem + op_vaddsubps_xmm_mem + op_vaddsubpd_xmm_mem + op_vhaddps_ymm_reg + op_vhaddpd_ymm_reg + op_vhsubps_ymm_reg + op_vhsubpd_ymm_reg + op_vaddsubps_ymm_reg + op_vaddsubpd_ymm_reg + op_vhaddps_ymm_mem + op_vhaddpd_ymm_mem + op_vhsubps_ymm_mem + op_vhsubpd_ymm_mem + op_vaddsubps_ymm_mem + op_vaddsubpd_ymm_mem + op_vhaddps_ymm_mem_rcx + op_vaddsubpd_ymm_mem_r8 + op_vhaddps_ymm_alias_dst_src1 + op_vhaddpd_ymm_alias_dst_src2 + op_vhsubps_ymm_alias_src1_src2 + op_vaddsubps_ymm_alias_all + op_vaddsubpd_xmm_alias_dst_src2 diff --git a/tests/cpu/avx_horiz_fp_aot_check.py b/tests/cpu/avx_horiz_fp_aot_check.py new file mode 100644 index 000000000..bbfa86d5d --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot_check.py @@ -0,0 +1,419 @@ +"""Differential, boundary, mutation, refusal, and coverage-record checks for dedicated AVX horizontal/addsub FP AOT.""" + +import ctypes +import os +from pathlib import Path +import struct +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +THIS_DIR = Path(__file__).resolve().parent +TOOLS_DIR = THIS_DIR.parents[1] / "tools" +sys.path.insert(0, str(THIS_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) + +from avx_horiz_fp import F32, F64, _guarded_buf # noqa: E402 +from cpu_avx_horiz_fp_aot import lift_code, main as tool_main, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + + +EXPORTS = ( + "op_vhaddps_xmm_reg", + "op_vhaddpd_xmm_reg", + "op_vhsubps_xmm_reg", + "op_vhsubpd_xmm_reg", + "op_vaddsubps_xmm_reg", + "op_vaddsubpd_xmm_reg", + "op_vhaddps_xmm_mem", + "op_vhaddpd_xmm_mem", + "op_vhsubps_xmm_mem", + "op_vhsubpd_xmm_mem", + "op_vaddsubps_xmm_mem", + "op_vaddsubpd_xmm_mem", + "op_vhaddps_ymm_reg", + "op_vhaddpd_ymm_reg", + "op_vhsubps_ymm_reg", + "op_vhsubpd_ymm_reg", + "op_vaddsubps_ymm_reg", + "op_vaddsubpd_ymm_reg", + "op_vhaddps_ymm_mem", + "op_vhaddpd_ymm_mem", + "op_vhsubps_ymm_mem", + "op_vhsubpd_ymm_mem", + "op_vaddsubps_ymm_mem", + "op_vaddsubpd_ymm_mem", + "op_vhaddps_ymm_mem_rcx", + "op_vaddsubpd_ymm_mem_r8", + "op_vhaddps_ymm_alias_dst_src1", + "op_vhaddpd_ymm_alias_dst_src2", + "op_vhsubps_ymm_alias_src1_src2", + "op_vaddsubps_ymm_alias_all", + "op_vaddsubpd_xmm_alias_dst_src2", +) + +ALTERED_CASES = ( + ("op_vhaddps_ymm_reg", "op_vhsubps_ymm_reg"), + ("op_vaddsubps_ymm_reg", "op_vhaddps_ymm_reg"), + ("op_vaddsubpd_ymm_mem", "op_vhsubpd_ymm_mem"), +) + + +def encode_seq(*instructions): + encoder = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += encoder.encode(ins, rip) + return encoder.take_buffer() + + +def _lane_ps(kind: str, lane_a: bytes, lane_b: bytes, mxcsr: int) -> bytes: + xa = struct.unpack("<4I", lane_a) + xb = struct.unpack("<4I", lane_b) + if kind == "vhadd": + vals = ( + F32.add(xa[0], xa[1], mxcsr), + F32.add(xa[2], xa[3], mxcsr), + F32.add(xb[0], xb[1], mxcsr), + F32.add(xb[2], xb[3], mxcsr), + ) + elif kind == "vhsub": + vals = ( + F32.sub(xa[0], xa[1], mxcsr), + F32.sub(xa[2], xa[3], mxcsr), + F32.sub(xb[0], xb[1], mxcsr), + F32.sub(xb[2], xb[3], mxcsr), + ) + elif kind == "vaddsub": + vals = ( + F32.sub(xa[0], xb[0], mxcsr), + F32.add(xa[1], xb[1], mxcsr), + F32.sub(xa[2], xb[2], mxcsr), + F32.add(xa[3], xb[3], mxcsr), + ) + else: + raise ValueError(kind) + return struct.pack("<4I", *vals) + + +def _lane_pd(kind: str, lane_a: bytes, lane_b: bytes, mxcsr: int) -> bytes: + xa = struct.unpack("<2Q", lane_a) + xb = struct.unpack("<2Q", lane_b) + if kind == "vhadd": + vals = (F64.add(xa[0], xa[1], mxcsr), F64.add(xb[0], xb[1], mxcsr)) + elif kind == "vhsub": + vals = (F64.sub(xa[0], xa[1], mxcsr), F64.sub(xb[0], xb[1], mxcsr)) + elif kind == "vaddsub": + vals = (F64.sub(xa[0], xb[0], mxcsr), F64.add(xa[1], xb[1], mxcsr)) + else: + raise ValueError(kind) + return struct.pack("<2Q", *vals) + + +def ref_op(name: str, a: bytes, b: bytes, mxcsr: int) -> bytes: + if name == "op_vhaddps_ymm_mem_rcx": + a, b = b, a + elif name in ("op_vhsubps_ymm_alias_src1_src2", "op_vaddsubps_ymm_alias_all"): + b = a + is_xmm = "_xmm_" in name + is_pd = "pd_" in name + if "vhadd" in name: + kind = "vhadd" + elif "vhsub" in name: + kind = "vhsub" + elif "vaddsub" in name: + kind = "vaddsub" + else: + raise KeyError(name) + lane_fn = _lane_pd if is_pd else _lane_ps + lo = lane_fn(kind, a[0:16], b[0:16], mxcsr) + if is_xmm: + return lo + b"\x00" * 16 + return lo + lane_fn(kind, a[16:32], b[16:32], mxcsr) + + +def check_translator(original_path: Path): + source_cpp, meta = translate(original_path, EXPORTS) + assert len(meta) == len(EXPORTS) and "host_has_avx" in source_cpp, meta + + ld_ymm0 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_YMM_YMMM256, R.YMM0, MemoryOperand(R.RCX)) + ld_ymm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM1, MemoryOperand(R.RCX)) + ld_ymm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPD_YMM_YMMM256, R.YMM2, MemoryOperand(R.RDX)) + ld_xmm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPD_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)) + ld_xmm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)) + ret_ins = Instruction.create(Code.RETNQ) + vzero = Instruction.create(Code.VEX_VZEROUPPER) + + # All 12 horizontal/addsub codes (6 mnemonics x XMM/YMM) in reg & flat [rcx|rdx|r8] mem-src forms. + accepted = 0 + for code, is_ymm, helper in ( + (Code.VEX_VHADDPS_XMM_XMM_XMMM128, False, "op_vhaddps"), + (Code.VEX_VHADDPS_YMM_YMM_YMMM256, True, "op_vhaddps"), + (Code.VEX_VHADDPD_XMM_XMM_XMMM128, False, "op_vhaddpd"), + (Code.VEX_VHADDPD_YMM_YMM_YMMM256, True, "op_vhaddpd"), + (Code.VEX_VHSUBPS_XMM_XMM_XMMM128, False, "op_vhsubps"), + (Code.VEX_VHSUBPS_YMM_YMM_YMMM256, True, "op_vhsubps"), + (Code.VEX_VHSUBPD_XMM_XMM_XMMM128, False, "op_vhsubpd"), + (Code.VEX_VHSUBPD_YMM_YMM_YMMM256, True, "op_vhsubpd"), + (Code.VEX_VADDSUBPS_XMM_XMM_XMMM128, False, "op_vaddsubps"), + (Code.VEX_VADDSUBPS_YMM_YMM_YMMM256, True, "op_vaddsubps"), + (Code.VEX_VADDSUBPD_XMM_XMM_XMMM128, False, "op_vaddsubpd"), + (Code.VEX_VADDSUBPD_YMM_YMM_YMMM256, True, "op_vaddsubpd"), + ): + dst, s1, s2 = (R.YMM0, R.YMM1, R.YMM2) if is_ymm else (R.XMM0, R.XMM1, R.XMM2) + loads = (ld_ymm1, ld_ymm2) if is_ymm else (ld_xmm1, ld_xmm2) + st_code = Code.VEX_VMOVUPS_YMMM256_YMM if is_ymm else Code.VEX_VMOVUPS_XMMM128_XMM + reg_src, _ = lift_code( + f"{helper}_reg", + 0x1000, + encode_seq( + *loads, + Instruction.create_reg_reg_reg(code, dst, s1, s2), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + vzero, + ret_ins, + ), + ) + assert f"{helper}(ymm1, ymm2, {'true' if is_ymm else 'false'})" in reg_src, reg_src + accepted += 1 + + for base in (R.RCX, R.RDX, R.R8): + mem_src, _ = lift_code( + f"{helper}_mem_{base}", + 0x1000, + encode_seq( + loads[0], + Instruction.create_reg_reg_mem(code, dst, s1, MemoryOperand(base)), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + ret_ins, + ), + ) + loader = "load256" if is_ymm else "load128" + assert f"{helper}(ymm1, {loader}(" in mem_src, mem_src + accepted += 1 + + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VADDPS_YMM_K1Z_YMM_YMMM256B32, R.YMM0, R.YMM1, R.YMM2) + evex_ins.op_mask = R.K1 + seg_mem = MemoryOperand(R.RDX) + seg_prefix_ins = Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, seg_mem) + seg_prefix_ins.segment_prefix = R.FS + + rejects = [ + ("evex", (ld_ymm1, ld_ymm2, evex_ins, ret_ins), "unsupported EVEX instruction"), + ("legacy_sse", (ld_xmm1, ld_xmm2, Instruction.create_reg_mem(Code.HADDPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX)), ret_ins), "unsupported instruction"), + ("nonvol_ymm6_dst", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM6, R.YMM1, R.YMM2), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm15_src", (ld_xmm1, Instruction.create_reg_reg_reg(Code.VEX_VHSUBPD_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM15), ret_ins), "nonvolatile vector register"), + ("nonvol_ymm7_move", (Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM7, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("undef_ymm3", (ld_ymm1, Instruction.create_reg_reg_reg(Code.VEX_VHADDPD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM3), ret_ins), "undefined vector register ymm3"), + ("undef_alias_dst", (ld_ymm1, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM0, R.YMM1), ret_ins), "undefined vector register ymm0"), + ("disp_mem_rcx", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RCX, displ=32, displ_size=1)), ret_ins), "unsupported memory operand"), + ("disp_mem_rdx", (ld_xmm1, Instruction.create_reg_reg_mem(Code.VEX_VADDSUBPS_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.RDX, displ=16, displ_size=1)), ret_ins), "unsupported memory operand"), + ("disp_store_r8", (ld_ymm0, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8, displ=32, displ_size=1), R.YMM0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rcx", (ld_ymm0, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.RCX), R.YMM0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rdx", (ld_xmm1, Instruction.create_mem_reg(Code.VEX_VMOVAPD_XMMM128_XMM, MemoryOperand(R.RDX), R.XMM1), ret_ins), "unsupported memory operand"), + ("indexed_mem", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHSUBPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RDX, R.RCX, 1)), ret_ins), "unsupported memory operand"), + ("rip_rel_mem", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VADDSUBPD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RIP, displ=0x1040, displ_size=4)), ret_ins), "unsupported memory operand"), + ("non_arg_base_rax", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RAX)), ret_ins), "unsupported memory operand"), + ("addr32_ecx", (ld_xmm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.ECX)), ret_ins), "unsupported memory operand"), + ("seg_prefix", (ld_ymm1, seg_prefix_ins, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), "missing terminal ret"), + ("after_ret", (ld_ymm1, ret_ins, ld_ymm2), "unreachable instruction after ret"), + ] + for label, seq, reason in rejects: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted invalid sequence") + + # Verify CLI failure exit code 1 without traceback and zero temp files. + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_cpp = root / "out.cpp" + try: + tool_main([str(root / "missing.dll"), "op_vhaddps_ymm_reg", str(out_cpp)]) + except SystemExit as exc: + assert exc.code == 1, exc.code + else: + raise AssertionError("missing DLL did not exit") + assert not out_cpp.exists() and list(root.iterdir()) == [] + + print(f"translator validated: {accepted} forms accepted, {len(rejects)} refusal controls passed") + + +def host_has_avx(lifted_lib) -> bool: + if hasattr(lifted_lib, "host_has_avx"): + lifted_lib.host_has_avx.argtypes = [] + lifted_lib.host_has_avx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_avx()) + return False + + +def check_differential(native_path: Path, lifted_path: Path, altered_path: Path, altered_lifted_path: Path) -> None: + native = ctypes.CDLL(str(native_path.resolve())) + lifted = ctypes.CDLL(str(lifted_path.resolve())) + altered_native = ctypes.CDLL(str(altered_path.resolve())) + altered_lifted = ctypes.CDLL(str(altered_lifted_path.resolve())) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes, exchange.restype = [ctypes.c_uint32], ctypes.c_uint32 + + def _f32(*vals): + words = [v if isinstance(v, int) else struct.unpack(" bytes: + _ra, pa = _guarded_buf(a_bytes, align if name == "op_vhaddps_ymm_mem_rcx" else 0) + _rb, pb = _guarded_buf(b_bytes, 0 if name in ("op_vhaddps_ymm_mem_rcx", "op_vaddsubpd_ymm_mem_r8") else align) + seed = b_bytes if name == "op_vaddsubpd_ymm_mem_r8" else b"\xCC" * 32 + _rc, pc = _guarded_buf(seed, align if name == "op_vaddsubpd_ymm_mem_r8" else 0) + fn = getattr(dll, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = None + previous = exchange(mxcsr) + try: + fn(pa, pb, pc) + finally: + exchange(previous) + return ctypes.string_at(pc, 32) + + for name in EXPORTS: + pairs = f64_pairs if "pd_" in name else f32_pairs + for mxcsr in mxcsr_modes: + for a_bytes, b_bytes in pairs: + want = ref_op(name, a_bytes, b_bytes, mxcsr) + got_n = invoke(native, "", name, a_bytes, b_bytes, mxcsr, 0) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, mxcsr, 0) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} mxcsr={mxcsr:#x}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + if "_mem" in name: + a_bytes, b_bytes = pairs[0] + for off in (1, 3, 7): + want = ref_op(name, a_bytes, b_bytes, 0x1F80) + got_n = invoke(native, "", name, a_bytes, b_bytes, 0x1F80, off) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, off) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} align={off}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + + # Altered controls must diverge from original and match altered native DLL. + for name, alt_ref_name in ALTERED_CASES: + pairs = f64_pairs if "pd_" in name else f32_pairs + a_bytes, b_bytes = pairs[0] + want_orig = ref_op(name, a_bytes, b_bytes, 0x1F80) + want_alt = ref_op(alt_ref_name, a_bytes, b_bytes, 0x1F80) + got_alt_n = invoke(altered_native, "", name, a_bytes, b_bytes, 0x1F80, 0) + got_alt_l = invoke(altered_lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, 0) + assert got_alt_n == want_alt and got_alt_l == want_alt, (name, got_alt_n.hex(), got_alt_l.hex(), want_alt.hex()) + assert got_alt_l != want_orig, f"altered {name} failed to diverge from original" + + # Altered XMM zeroing control: vhaddpd ymm0 instead of xmm0 leaves bits [255:128] non-zero. + a64, b64 = f64_pairs[0] + want_xmm_orig = ref_op("op_vhaddpd_xmm_reg", a64, b64, 0x1F80) + got_xmm_alt_n = invoke(altered_native, "", "op_vhaddpd_xmm_reg", a64, b64, 0x1F80, 0) + got_xmm_alt_l = invoke(altered_lifted, "lifted_", "op_vhaddpd_xmm_reg", a64, b64, 0x1F80, 0) + assert got_xmm_alt_n == got_xmm_alt_l, (got_xmm_alt_n.hex(), got_xmm_alt_l.hex()) + assert got_xmm_alt_l[:16] == want_xmm_orig[:16] and got_xmm_alt_l[16:] != b"\x00" * 16, got_xmm_alt_l.hex() + + print( + f"{cases} AVX horizontal/addsub FP cases across {len(EXPORTS)} exports and {len(mxcsr_modes)} MXCSR modes " + f"matched native DLL and IEEE-754 reference; {len(ALTERED_CASES) + 1} altered controls diverged" + ) + + +def record_covered_forms(original_path: Path) -> None: + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main() -> None: + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + check_translator(original_path) + + lifted_lib = ctypes.CDLL(str(lifted_path.resolve())) + if not host_has_avx(lifted_lib): + print("Host lacks CPUID.01H:ECX[27:28] + XGETBV[2:1]; skipping native differential check") + sys.exit(77) + + check_differential(original_path, lifted_path, altered_path, altered_lifted_path) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_avx_horiz_fp_aot.py b/tools/cpu_avx_horiz_fp_aot.py new file mode 100644 index 000000000..e84bfbbcc --- /dev/null +++ b/tools/cpu_avx_horiz_fp_aot.py @@ -0,0 +1,403 @@ +"""Lift bounded Windows x64 leaf functions with AVX horizontal and add/sub FP ops to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned buffers. YMM0..YMM5 +are modeled as portable 256-bit value structs (four 64-bit lanes); every VEX.128 +write to an XMM destination zeroes bits [255:128] of the corresponding YMM register. + +Supported AVX horizontal / alternating FP forms (docs/coverage/x64_zen2.tsv group AVX): + - VHADDPS, VHADDPD, VHSUBPS, VHSUBPD, VADDSUBPS, VADDSUBPD + in VEX.128 (xmm, xmm, xmm/m128) and VEX.256 (ymm, ymm, ymm/m256) forms. + +Transport / ABI glue: + - VMOVAPS, VMOVAPD, VMOVUPS, VMOVUPD (reg-reg, flat [rcx|rdx|r8] loads, flat [r8] stores) + - VZEROUPPER and terminal RET. + +EVEX encodings, legacy SSE forms, nonvolatile vector registers (XMM6..15/YMM6..15), +undefined vector reads, displaced or non-flat memory operands, non-[r8] stores, +instruction prefixes, branches, and trailing or missing ret are rejected. +""" + +import argparse +from pathlib import Path +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +VOLATILE_YMM = {getattr(R, f"YMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(6, 32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) + +# (helper_name, is_ymm) +HORIZ_FP_CODES = { + Code.VEX_VHADDPS_XMM_XMM_XMMM128: ("op_vhaddps", False), + Code.VEX_VHADDPS_YMM_YMM_YMMM256: ("op_vhaddps", True), + Code.VEX_VHADDPD_XMM_XMM_XMMM128: ("op_vhaddpd", False), + Code.VEX_VHADDPD_YMM_YMM_YMMM256: ("op_vhaddpd", True), + Code.VEX_VHSUBPS_XMM_XMM_XMMM128: ("op_vhsubps", False), + Code.VEX_VHSUBPS_YMM_YMM_YMMM256: ("op_vhsubps", True), + Code.VEX_VHSUBPD_XMM_XMM_XMMM128: ("op_vhsubpd", False), + Code.VEX_VHSUBPD_YMM_YMM_YMMM256: ("op_vhsubpd", True), + Code.VEX_VADDSUBPS_XMM_XMM_XMMM128: ("op_vaddsubps", False), + Code.VEX_VADDSUBPS_YMM_YMM_YMMM256: ("op_vaddsubps", True), + Code.VEX_VADDSUBPD_XMM_XMM_XMMM128: ("op_vaddsubpd", False), + Code.VEX_VADDSUBPD_YMM_YMM_YMMM256: ("op_vaddsubpd", True), +} + +# is_ymm for full-width VEX FP moves +VEC_MOVE_CODES = { + Code.VEX_VMOVAPS_XMM_XMMM128: False, + Code.VEX_VMOVAPS_XMMM128_XMM: False, + Code.VEX_VMOVAPS_YMM_YMMM256: True, + Code.VEX_VMOVAPS_YMMM256_YMM: True, + Code.VEX_VMOVAPD_XMM_XMMM128: False, + Code.VEX_VMOVAPD_XMMM128_XMM: False, + Code.VEX_VMOVAPD_YMM_YMMM256: True, + Code.VEX_VMOVAPD_YMMM256_YMM: True, + Code.VEX_VMOVUPS_XMM_XMMM128: False, + Code.VEX_VMOVUPS_XMMM128_XMM: False, + Code.VEX_VMOVUPS_YMM_YMMM256: True, + Code.VEX_VMOVUPS_YMMM256_YMM: True, + Code.VEX_VMOVUPD_XMM_XMMM128: False, + Code.VEX_VMOVUPD_XMMM128_XMM: False, + Code.VEX_VMOVUPD_YMM_YMMM256: True, + Code.VEX_VMOVUPD_YMMM256_YMM: True, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.VEX_VZEROUPPER, + *HORIZ_FP_CODES, + *VEC_MOVE_CODES, +} + +PRELUDE = """#include +#include +#include +#include +#if defined(_MSC_VER) +#include +#define X2W_UNALIGNED __unaligned +#else +#define X2W_UNALIGNED +#endif + +using word = std::uint64_t; + +struct Vec256 { + std::uint64_t q[4]; +}; + +static inline Vec256 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, 0ull, 0ull}}; +} + +static inline Vec256 load256(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + const std::uint64_t q2 = p[2]; + const std::uint64_t q3 = p[3]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, q2, q3}}; +} + +static inline void store128(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, 16); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store256(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.q, 32); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline Vec256 copy128(const Vec256& v) { + return {{v.q[0], v.q[1], 0ull, 0ull}}; +} + +template +static inline Vec256 apply_sse3_lanes(const Vec256& a, const Vec256& b, bool wide, Fn fn) { + Vec256 out{}; + const unsigned lanes = wide ? 2u : 1u; + for (unsigned lane = 0; lane < lanes; ++lane) { + LaneVec va; + LaneVec vb; + std::memcpy(&va, &a.q[lane * 2u], 16); + std::memcpy(&vb, &b.q[lane * 2u], 16); + const LaneVec vr = fn(va, vb); + std::memcpy(&out.q[lane * 2u], &vr, 16); + } + return out; +} + +static inline Vec256 op_vhaddps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_hadd_ps(x, y); }); +} + +static inline Vec256 op_vhaddpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_hadd_pd(x, y); }); +} + +static inline Vec256 op_vhsubps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_hsub_ps(x, y); }); +} + +static inline Vec256 op_vhsubpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_hsub_pd(x, y); }); +} + +static inline Vec256 op_vaddsubps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_addsub_ps(x, y); }); +} + +static inline Vec256 op_vaddsubpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_addsub_pd(x, y); }); +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif +""" + + +def vec_index(register, ins, *, expected_wide): + """Map XMM0..XMM5 or YMM0..YMM5 to register index, enforcing width and rejecting nonvolatile/other.""" + if register in VOLATILE_XMM: + if expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_XMM[register] + if register in VOLATILE_YMM: + if not expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_YMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, store=False, expected_size=None): + """Lower a flat zero-displacement [rcx|rdx|r8] pointer operand (stores restricted to [r8]).""" + base = ins.memory_base + allowed = {R.R8} if store else ARGUMENTS + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or ins.memory_displacement != 0 + or not RegisterExt.is_gpr64(base) + or base not in allowed + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if expected_size is not None and MemorySizeExt.size(ins.memory_size) != expected_size: + raise ValueError(f"unsupported memory size at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AVX horizontal/addsub FP leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + if idx not in defined: + raise ValueError(f"undefined vector register ymm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"ymm{idx}" + + def write_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + used.add(idx) + return idx, f"ymm{idx}" + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ( + ins.op_code().encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code == Code.VEX_VZEROUPPER: + for idx in sorted(defined): + statements.append(f"ymm{idx}.q[2] = 0ull; ymm{idx}.q[3] = 0ull;") + elif ins.code in HORIZ_FP_CODES: + helper, wide = HORIZ_FP_CODES[ins.code] + if ins.op_count != 3 or ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported AVX horizontal FP operands at RVA {ins.ip:#x}: {ins}") + src1 = read_vec(1, ins, expected_wide=wide) + if ins.op2_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=32 if wide else 16) + src2 = f"{'load256' if wide else 'load128'}({addr})" + elif ins.op2_kind == OpKind.REGISTER: + src2 = read_vec(2, ins, expected_wide=wide) + else: + raise ValueError(f"unsupported AVX horizontal FP operands at RVA {ins.ip:#x}: {ins}") + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {helper}({src1}, {src2}, {'true' if wide else 'false'});") + defined.add(dst_idx) + elif ins.code in VEC_MOVE_CODES: + wide = VEC_MOVE_CODES[ins.code] + expected_size = 32 if wide else 16 + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=expected_size) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {'load256' if wide else 'load128'}({addr});") + defined.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + addr = flat_address(ins, store=True, expected_size=expected_size) + statements.append(f"{'store256' if wide else 'store128'}({addr}, {src});") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {src};" if wide else f"{dst} = copy128({src});") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported vector move operands at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec256 ymm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _write_atomic(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image must be a regular file: {args.image}") + exports = [name for name in args.exports.split(",") if name] + if not exports: + raise ValueError("exports list must not be empty") + source, meta = translate(args.image, exports) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"cpu_avx_horiz_fp_aot: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 815ac65fb5719dc3e955bfbfec3ff9a0a3a8d4ec Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:46:07 +0200 Subject: [PATCH 16/29] script: add archive file and ASCII state guards to script_state_probe with CLI suite (#2620) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/script_state_probe_cli_check.py | 377 ++++++++++++++++++++++++++ tools/script_state_probe.py | 34 ++- 3 files changed, 411 insertions(+), 3 deletions(-) create mode 100644 tests/script_state_probe_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fb6084cec..f62ff89dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8973,6 +8973,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$") add_test(NAME script_state_probe_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_state_probe_check.py") + add_test(NAME script_state_probe_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/script_state_probe_cli_check.py") + set_tests_properties(script_state_probe_cli_check PROPERTIES TIMEOUT 60) add_test(NAME script_typed_path_dispatch COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$" TypedScriptPathTests) add_test(NAME bcpack_prefix_and_mip_tail COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/script_state_probe_cli_check.py b/tests/script_state_probe_cli_check.py new file mode 100644 index 000000000..b0e3a75bf --- /dev/null +++ b/tests/script_state_probe_cli_check.py @@ -0,0 +1,377 @@ +"""Pure-Python CLI and synthetic RPF9 validation suite for tools/script_state_probe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import mmap +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "script_state_probe.py" +sys.path.insert(0, str(ROOT / "tools")) + +import script_state_probe as probe # noqa: E402 + + +def _attr(name: str, spelling: str, raw: int, kind: int) -> bytes: + return struct.pack(" list[bytes]: + return [ + _attr("priority", str(priority), priority, 3), + _attr("blendduration", "25", 25, 3), + _attr("orbitdistance", "2.500000", 0x40200000, 2), + _attr("pitchlimits", "-0.500000,0.500000,0.000000", 0, 1), + _attr("headinglimits", "-1.500000,1.500000,0.000000", 1, 1), + ] + + +def _synth_record( + *, + priorities: tuple[int, ...] = (7,), + state_label: str = "cli_synthetic_state", + truncate_schema_by: int = 0, + corrupt_zlib: bool = False, + truncate_zlib: bool = False, +) -> bytes: + """Build one zlib-compressed PSIN/LSCH/LENM/LSNS/LGID/LRSC/CHKS record payload.""" + attrs = bytearray() + nodes = bytearray() + + def add_node(name: str, parent: int, row_list: list[bytes]) -> int: + idx = len(nodes) // 16 + nodes.extend( + struct.pack( + " 1: + root_parent = add_node("root", root_parent, []) + for prio in priorities: + state_idx = add_node("state", root_parent, [_attr("id", state_label, 0, 5)]) + add_node("camera", state_idx, _camera_rows(prio)) + + vecs = struct.pack("<6f", -0.5, 0.5, 0.0, -1.5, 1.5, 0.0) + arrays = ((len(attrs) // 16, 2), (0, 0), (2, 4), (0, 0), (len(nodes) // 16, 3)) + root_blob = b"".join(struct.pack("4sI", tag, len(part) + 8)) + body.extend(part) + + chks_size = 20 + total_len = len(body) + chks_size + body.extend(struct.pack(">4sIIQ", b"CHKS", chks_size, total_len, 0)) + + compressed = zlib.compress(bytes(body)) + if corrupt_zlib: + return compressed[:4] + b"\xff\x00\xff\x00" + compressed[8:] + if truncate_zlib: + return compressed[:6] + return compressed + + +def _build_rpf9(*payloads: bytes) -> bytes: + archive = bytearray(b"9FPR") + for payload in payloads: + archive.extend(bytes(-len(archive) % 16)) + archive.extend(payload) + return bytes(archive) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = probe.main(argv) + except SystemExit as exc: + rc = exc.code if isinstance(exc.code, int) else 2 + return rc, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + env = dict(os.environ, PYTHONUTF8="1") + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + encoding="utf-8", + env=env, + timeout=30, + ) + + +class ScriptStateProbeCliPositiveTests(unittest.TestCase): + def test_direct_main_default_and_state_schema(self): + single_bytes = _build_rpf9(_synth_record(priorities=(7,), state_label="orbit_one")) + ambig_bytes = _build_rpf9(_synth_record(priorities=(7, 11), state_label="orbit_dup")) + with TemporaryDirectory() as tmp: + root = Path(tmp) + single = root / "single.rpf" + single.write_bytes(single_bytes) + ambig = root / "ambig.rpf" + ambig.write_bytes(ambig_bytes) + + # Default mode without --state. + rc, out, err = _run_main([str(single)]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + default_json = json.loads(out) + self.assertEqual( + set(default_json), + {"counts", "requested_state", "first_verified_example"}, + ) + self.assertIsNone(default_json["requested_state"]) + self.assertIsNone(default_json["first_verified_example"]) + self.assertEqual( + default_json["counts"], + { + "section_records": 1, + "node_trees": 1, + "state_nodes": 1, + "camera_parameter_sets": 1, + "all_five_literals_verified": 1, + }, + ) + self.assertEqual(single.read_bytes(), single_bytes) + + # Matching --state mode. + rc, out, err = _run_main([str(single), "--state", "orbit_one"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + matched_json = json.loads(out) + self.assertEqual(matched_json["requested_state"], "orbit_one") + self.assertEqual( + matched_json["first_verified_example"], + { + "priority": "7", + "blendduration": "25", + "orbitdistance": "2.500000", + "pitchlimits": "-0.500000,0.500000,0.000000", + "headinglimits": "-1.500000,1.500000,0.000000", + }, + ) + self.assertNotIn("ambiguous_state_candidates", matched_json) + + # Unmatched --state mode. + rc, out, err = _run_main([str(single), "--state", "absent_state"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + missed_json = json.loads(out) + self.assertEqual(missed_json["requested_state"], "absent_state") + self.assertIsNone(missed_json["first_verified_example"]) + + # Ambiguous --state mode. + rc, out, err = _run_main([str(ambig), "--state", "orbit_dup"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + ambig_json = json.loads(out) + self.assertIsNone(ambig_json["first_verified_example"]) + self.assertEqual( + [c["node_path"] for c in ambig_json["ambiguous_state_candidates"]], + [[0, 1], [0, 3]], + ) + + # Subprocess parity and sys.argv/runpy entrypoint. + proc = _run_subprocess(str(single), "--state", "orbit_one") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), matched_json) + + with mock.patch.object(sys, "argv", [str(TOOL), str(single), "--state", "orbit_one"]): + rc_none, out_none, err_none = _run_main(None) + self.assertEqual(rc_none, 0, err_none) + self.assertEqual(json.loads(out_none), matched_json) + + out_runpy, err_runpy = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(single)]), + redirect_stdout(out_runpy), + redirect_stderr(err_runpy), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(err_runpy.getvalue(), "") + self.assertEqual(json.loads(out_runpy.getvalue()), default_json) + + def test_corrupt_or_truncated_zlib_yields_zero_node_trees_without_crash(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, kw in ( + ("corrupt_zlib", {"corrupt_zlib": True}), + ("truncated_zlib", {"truncate_zlib": True}), + ): + with self.subTest(case=label): + archive = root / f"{label}.rpf" + archive.write_bytes(_build_rpf9(_synth_record(**kw))) + rc, out, err = _run_main([str(archive)]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + payload = json.loads(out) + self.assertEqual(payload["counts"].get("node_trees", 0), 0) + self.assertEqual(payload["counts"], {}) + + +class ScriptStateProbeCliNegativeTests(unittest.TestCase): + def _assert_cli_failure( + self, + argv: list[str], + *, + expected_code: int, + fragment: str, + check_subprocess: bool = True, + ) -> None: + rc, out, err = _run_main(argv) + self.assertEqual(rc, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(fragment, proc.stderr) + + def test_upfront_is_file_and_archive_validation_controls(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.rpf" + folder = root / "dir_archive" + folder.mkdir() + empty = root / "empty.rpf" + empty.write_bytes(b"") + short_header = root / "short.rpf" + short_header.write_bytes(b"9FP") + bad_magic = root / "bad_magic.rpf" + bad_magic.write_bytes(b"NOPE" + b"\x00" * 16) + truncated_schema = root / "truncated_schema.rpf" + truncated_schema.write_bytes(_build_rpf9(_synth_record(truncate_schema_by=8))) + + # Missing and directory must reject upfront before open/mmap. + with ( + mock.patch.object(Path, "open", side_effect=AssertionError("open must not run")), + mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")), + ): + with self.assertRaises(FileNotFoundError): + probe.inspect(missing) + with self.assertRaisesRegex(ValueError, "directory"): + probe.inspect(folder) + + self._assert_cli_failure([str(missing)], expected_code=1, fragment="not found") + self._assert_cli_failure([str(folder)], expected_code=1, fragment="directory") + + # 0-byte archive must fail cleanly before mmap.mmap. + with mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")): + with self.assertRaisesRegex(ValueError, "Empty archive"): + probe.inspect(empty) + self._assert_cli_failure([str(empty)], expected_code=1, fragment="Empty archive") + + # Truncated header, bad magic, and truncated inner schema. + self._assert_cli_failure([str(short_header)], expected_code=1, fragment="Expected an RPF9 archive") + self._assert_cli_failure([str(bad_magic)], expected_code=1, fragment="Expected an RPF9 archive") + self._assert_cli_failure([str(truncated_schema)], expected_code=1, fragment="Truncated schema members") + + def test_empty_and_non_ascii_state_validation(self): + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "valid.rpf" + archive.write_bytes(_build_rpf9(_synth_record())) + + # Upfront state validation rejects before open/mmap. + with ( + mock.patch.object(Path, "open", side_effect=AssertionError("open must not run")), + mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")), + ): + with self.assertRaisesRegex(ValueError, "non-empty ASCII"): + probe.inspect(archive, "") + with self.assertRaisesRegex(ValueError, "ASCII"): + probe.inspect(archive, "café") + with self.assertRaisesRegex(ValueError, "non-empty ASCII"): + probe.joaat("", allow_empty=False) + + # Empty and non-ASCII --state via main(argv) and subprocess. + self._assert_cli_failure([str(archive), "--state", ""], expected_code=1, fragment="non-empty ASCII") + self._assert_cli_failure([str(archive), "--state", "café"], expected_code=1, fragment="ASCII") + + def test_argparse_errors_and_help_py314_compatible(self): + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "valid.rpf" + archive.write_bytes(_build_rpf9(_synth_record())) + + for argv, fragment in ( + ([], "usage:"), + ([str(archive), "--unknown-flag"], "unrecognized"), + ([str(archive), "--state"], "--state"), + ): + with self.subTest(argv=argv): + self._assert_cli_failure(argv, expected_code=2, fragment=fragment) + + rc, out, err = _run_main(["--help"]) + self.assertEqual(rc, 0) + self.assertIn("usage:", out) + self.assertEqual(err, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/script_state_probe.py b/tools/script_state_probe.py index cf741652b..8b13d6d5b 100644 --- a/tools/script_state_probe.py +++ b/tools/script_state_probe.py @@ -13,7 +13,11 @@ from section_probe import sections -def joaat(text): +def joaat(text, *, allow_empty=True): + if not isinstance(text, str): + raise ValueError("State label must be an ASCII string") + if not allow_empty and not text: + raise ValueError("State label must be non-empty ASCII") value = 0 for byte in text.encode("ascii"): value = (value + byte) & 0xffffffff @@ -24,6 +28,26 @@ def joaat(text): return (value + (value << 15)) & 0xffffffff +def _validate_state(state): + if not isinstance(state, str) or not state: + raise ValueError("State label must be non-empty ASCII") + try: + return joaat(state, allow_empty=False) + except UnicodeEncodeError as exc: + raise ValueError(f"State label must be ASCII: {state!r}") from exc + + +def _require_archive_file(path): + path = Path(path) + if not path.is_file(): + if path.is_dir(): + raise ValueError(f"archive path is a directory, not a file: {path}") + if not path.exists(): + raise FileNotFoundError(f"archive file not found: {path}") + raise ValueError(f"archive path is not a regular file: {path}") + return path + + CAMERA = {joaat(s): s for s in ("blendduration", "orbitdistance", "priority", "pitchlimits", "headinglimits")} NODE = struct.Struct(" int: parser.add_argument("--state", help="Report at most one hash-verified example for this state label") args = parser.parse_args(argv) try: - result = inspect(args.archive, args.state) + if args.state is not None: + _validate_state(args.state) + archive = _require_archive_file(args.archive) + result = inspect(archive, args.state) except (OSError, ValueError, struct.error, zlib.error) as exc: parser.exit(1, f"{args.archive}: {exc}\n") print(json.dumps(result, indent=2)) From 5b368706e6161181d55c24140ae00aa99dc29b42 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 07:48:22 +0800 Subject: [PATCH 17/29] tests: use a portable negative record offset in the SGD5 CLI fixture (#2632) --- tests/sgd5_effects_cli_check.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/sgd5_effects_cli_check.py b/tests/sgd5_effects_cli_check.py index 297c69e9c..903bbb7cb 100644 --- a/tests/sgd5_effects_cli_check.py +++ b/tests/sgd5_effects_cli_check.py @@ -263,7 +263,8 @@ def test_negative_offsets_rejected_by_offset_parser_before_opening_archive(self) ("neg_group_end", [str(archive), "draw", "--group", str(grp_start), "-1", "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), ("neg_arrays", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays=-0x1", "--record", str(rec_start), str(rec_end)]), ("neg_record_start", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", "-1", str(rec_end)]), - ("neg_record_end", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), "-0x10"]), + # Older argparse versions treat a separate negative hex token as an option, not as an offset. + ("neg_record_end", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), "-16"]), ): with self.subTest(archive=archive.name, case=label): with mock.patch.object( From 52bccd9012e029ab766c485ce3c2ca4006cf4c18 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:49:33 +0100 Subject: [PATCH 18/29] shader: lower image_sample_d and document image_sample_c_d refusal in gfx2hlsl (Part of #1723) (#2082) * feat: lower image_sample_d to SampleGrad in gfx2hlsl Part of #1723. 2D, 2D array and 3D gradient samples; image_sample_c_d is refused by name (needs SM 6.8). * test: register startup_image_sample_d in CMake Part of #1723. * startup: keep the guest LOD cap for image_sample_d and document the form in gfx2hlsl * test: WARP and hardware readback for image_sample_d against a CPU reference * tests: build the implicit Sample negative control with two arguments --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 11 ++ docs/experiments.md | 17 ++ tests/startup_image_sample_d_check.py | 133 ++++++++++++++ tests/startup_image_sample_d_draw_check.py | 203 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 37 +++- 5 files changed, 398 insertions(+), 3 deletions(-) create mode 100644 tests/startup_image_sample_d_check.py create mode 100644 tests/startup_image_sample_d_draw_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index f62ff89dd..c6788297b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3134,6 +3134,17 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_ngg_slice_check.py") add_test(NAME startup_image_sample_l COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_l_check.py") + add_test(NAME startup_image_sample_d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_d_check.py") + # image_sample_d drawn on D3D12 (FXC 5_1 and DXC 6_0): GPU readback of the mip chosen by explicit gradients. + add_test(NAME startup_image_sample_d_draw_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_d_draw_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_d_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_d_draw_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_sample_d_draw_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_image_gather_lz COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_gather_lz_check.py") add_test(NAME startup_compute_gather_lz COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 27e29d30e..8a03f32b7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15712,6 +15712,23 @@ The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequenc Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. +## Startup translator: explicit-gradient image_sample_d + +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_d` form in a pixel stage to `tex.SampleGrad(smp, uv, ddx, ddy)`. The address dwords are ddx, then ddy (one register per coordinate axis each), then the coordinates: six registers for 2D, seven for a 2D array (slice last), nine for a volume (a contiguous nine-dword volume address encoded as a sixteen-register range is trimmed to nine). Only `dim:`, `dmask:` and the cache-policy bits `dlc`, `glc`, `slc` are accepted. + +Refused with a named reason: `image_sample_c_d` (it would need `SampleCmpGrad`, shader model 6.8; only `image_sample_c` and `_c_lz` are lowered), `image_sample_d_o` and every other offset, bias, clamp, `a16`, `tfe` or `lwe` form, an empty `dmask`, a 1D image, and an address count that does not match the dimension. + +The guest sampler LOD range is kept: a constant sampler carries MIN_LOD and MAX_LOD to the static sampler through the same `smpl` line as `image_sample`, `_l` and `_lz` (sampler words `(0, 0, 0x04000000, 0)` stay capped at mip 0), with the same refusals for a LOD bias and for MIN_LOD above MAX_LOD. A mip filter of 0 keeps the ordinary sampler, and a heap sampler is not validated and is logged once per module. + +Verified: the Python translation checks (address order, refusals, the LOD cap, fixture words against `llvm-mc`) and a D3D12 draw on WARP and hardware (`tests/startup_image_sample_d_draw_check.py`): four `SampleGrad` probes on a three-mip, two-slice fixture read back against a CPU reference, with a MAX_LOD 0 sampler and an implicit `Sample` as negative controls. + +```bash +./out/pe-env/bin/python -B tests/startup_image_sample_d_check.py +./out/pe-env/bin/python -B tests/startup_image_sample_d_check.py binary +ctest --preset dev --no-tests=error -R "^startup_image_sample_d" -V +ctest --preset dev --no-tests=error -R "^startup_image_sample_d_draw_(warp|hardware)$" -V +``` + ### Startup 24-bit multiplies, v_xnor_b32 and the funnel shifts `tools/startup/gfx2hlsl.py` translates `v_mul_i32_i24`, `v_mad_i32_i24`, `v_mul_hi_i32_i24`, `v_xnor_b32`, `v_alignbit_b32` and `v_alignbyte_b32` (VOP2 and VOP3 spellings) in 32-bit integer arithmetic, with no 64-bit type. The signed forms sign-extend the low 24 bits of each source with a left shift of 8 and an arithmetic right shift; the high product is assembled from 12-bit halves so that it stays inside 32 bits. diff --git a/tests/startup_image_sample_d_check.py b/tests/startup_image_sample_d_check.py new file mode 100644 index 000000000..5e7ac7d48 --- /dev/null +++ b/tests/startup_image_sample_d_check.py @@ -0,0 +1,133 @@ +"""Explicit-gradient image_sample_d in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary reassemble every fixture source and compare it with the recorded words + +The address dwords of image_sample_d are ddx, then ddy (one register per coordinate axis each), then the coordinates. +The lowering must pass those registers to SampleGrad in that order: a 2D sample has six, a 2D array seven (the slice +last) and a volume nine. image_sample_c_d would need SampleCmpGrad (shader model 6.8) and is refused by name instead +of being sampled without its gradients. +""" +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_sample_l_check import POST, PRE # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, assemble, root_blob # noqa: E402 + +TAIL = 's[16:23], s[24:27] dmask:0xf dim:' +IMAGE = { + 'd2': 'image_sample_d v[4:7], v[0:5], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'd2nsa': 'image_sample_d v[4:7], [v0, v1, v2, v3, v1, v0], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'd3': 'image_sample_d v[4:7], v[0:8], ' + TAIL + 'SQ_RSRC_IMG_3D', + 'd2a': 'image_sample_d v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D_ARRAY', + 'd1': 'image_sample_d v[4:7], [v0, v1, v2], ' + TAIL + 'SQ_RSRC_IMG_1D', + 'cd': 'image_sample_c_d v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'do': 'image_sample_d_o v[4:7], v[0:6], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'dtfe': 'image_sample_d v[4:5], v[0:5], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D tfe', + 'dglc': 'image_sample_d v[4:7], v[0:5], ' + TAIL + 'SQ_RSRC_IMG_2D glc', +} +WORDS = { + 'd2': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd2nsa': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf0c0f88f00004c4000102030100000000703f8cbf0f1800f804050607000081bf'), + 'd3': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf100f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd2a': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf280f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd1': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf020f88f00004c40001020000703f8cbf0f1800f804050607000081bf'), + 'cd': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080fa8f00004c400703f8cbf0f1800f804050607000081bf'), + 'do': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080fc8f00004c400703f8cbf0f1800f804050607000081bf'), + 'dtfe': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080189f00004c400703f8cbf0f1800f804050607000081bf'), + 'dglc': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf082f88f00004c400703f8cbf0f1800f804050607000081bf'), +} + + +def stage(name): + return G.Pipeline(VS_WORDS, WORDS[name], root_blob(flags=0)).hlsl_ps() + + +def grad_call(name): + """(location, ddx, ddy) register lists of the SampleGrad call.""" + call = re.search(r'SampleGrad\(([^;]*)\);', stage(name)) + assert call, name + parts = call.group(1).split('float')[1:] + assert len(parts) == 3, call.group(1) + return [re.findall(r'F\((v\d+)\)', part) for part in parts] + + +def refused(name, text): + try: + stage(name) + except G.Unsupported as error: + assert text in str(error), (name, str(error)) + else: + raise AssertionError('%s was accepted' % name) + + +def check_address_count(): + """A count that does not match the dimension is refused before any register is read.""" + for coords, count in (('[v0, v1, v2, v3, v1]', 5), ('[v0, v1, v2, v3, v1, v0, v2]', 7)): + bare = G.Stage.__new__(G.Stage) + try: + bare.image(['v5', coords, 's0'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x1'], 'd') + except G.Unsupported as error: + assert str(error) == 'image_sample_d with %d address registers' % count, (coords, error) + else: + raise AssertionError('image_sample_d accepted %d address registers' % count) + + +def check_lod_cap(): + """A guest sampler capped to MAX_LOD 0 keeps its cap: the static sampler carries it, so SampleGrad cannot reach mip 2. + + The cap fixture is the 2D program with `s_mov_b32 s26, 0` (80039abe) widened to the literal 0x04000000, mip filter + point (word 2 bits 27:26 = 1), words (0, 0, 0x04000000, 0). A mip filter of 0 keeps the ordinary sampler.""" + words = WORDS['d2'] + assert words.count(bytes.fromhex('80039abe')) == 1 + capped = words.replace(bytes.fromhex('80039abe'), bytes.fromhex('ff039abe') + (0x04000000).to_bytes(4, 'little')) + pipe = G.Pipeline(VS_WORDS, capped, root_blob(flags=0)) + assert 'SampleGrad(' in pipe.hlsl_ps() + lines = pipe.manifest().splitlines() + assert 'smpl 0 0x0 0x0 0x4000000 0x0' in lines and 'smp ' not in pipe.manifest(), pipe.manifest() + plain = G.Pipeline(VS_WORDS, words, root_blob(flags=0)) + plain.hlsl_ps() + assert 'smp 0 0x0 0x0 0x0 0x0' in plain.manifest().splitlines() and 'smpl' not in plain.manifest(), plain.manifest() + print('a capped constant sampler is carried to the static sampler; mip filter 0 keeps the ordinary one') + + +def controls(): + check_address_count() + check_lod_cap() + assert grad_call('d2') == [['v4', 'v5'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2') + assert grad_call('d2nsa') == [['v1', 'v0'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2nsa') + assert grad_call('d3') == [['v6', 'v7', 'v8'], ['v0', 'v1', 'v2'], ['v3', 'v4', 'v5']], grad_call('d3') + assert grad_call('d2a') == [['v4', 'v5', 'v6'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2a') + assert 'Texture2DArray' in stage('d2a') and 'Texture3D' in stage('d3') + print('2D, NSA 2D, 3D and 2D array pass ddx, ddy and the coordinates to SampleGrad in address order') + + refused('cd', 'image_sample_c_d') + refused('do', 'image_sample_d_o') + refused('d1', 'unverified 1D image sample address or modifiers') + refused('dtfe', 'image_sample_d modifier tfe') + print('refused: compare, offset, 1D, tfe') + + assert grad_call('dglc') == grad_call('d2') # cache-policy bits do not change the sampled value + print('glc is accepted') + + +def check_binary(llvm_mc): + for name, line in IMAGE.items(): + built = assemble(llvm_mc, PRE + line + '\n' + POST) + if built != WORDS[name]: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), WORDS[name].hex())) + print('fixture words match llvm-mc') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + else: + sys.exit(__doc__) diff --git a/tests/startup_image_sample_d_draw_check.py b/tests/startup_image_sample_d_draw_check.py new file mode 100644 index 000000000..409aeca02 --- /dev/null +++ b/tests/startup_image_sample_d_draw_check.py @@ -0,0 +1,203 @@ +"""image_sample_d drawn on D3D12 (WARP and hardware), GPU readback against a CPU reference (Part of #1723). + + (no arguments) build the programs, translate them, check the CPU reference + draw [fxc] + compile (DXC ps_6_0, and FXC ps_5_1 when given) and draw against the + 4x4 two-slice, three-mip R32G32B32A32_FLOAT fixture of startup_image_3d.cpp + +One pixel stage samples four times with explicit gradients. The gradients, not the coordinates, pick the mip level: +rho = largest gradient component * 4 texels, so 0.25 -> mip 0, 0.5 -> mip 1, 1.0 -> mip 2 (exact powers of two, no +rounding ambiguity). Probes use ddx only, ddy only, a gradient on the second axis and the second array slice. +The expected colours come from the fixture formula red = (1 + x + 4y + 16s + 32m) / 128 evaluated here with +exact fractions. Mutants: a sampler capped to MAX_LOD 0 and SampleGrad replaced by an implicit Sample must both +return mip 0 on every probe, which the same draw must report as different from the expected colours. +""" +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import ( # noqa: E402 + FULLSCREEN_VS, + VS_WORDS, + CompileQueue, + compile_hlsl, + root_blob, +) +from startup_image_sample_c_border_check import ( # noqa: E402 + DIM_2D_ARRAY, + EXP_MRT0_V4_V7, + INLINE_FLOATS, + S_ENDPGM, + S_LOAD_DWORDX8, + S_WAIT_LGKM, + S_WAIT_VM, + f32_hex, + manifest_sampler, + mimg_seq, + s_mov_b32, + v_mov_inline, + v_mov_lit, +) + +IMG_SAMPLE_D = 0x22 +SIZE = 4 +LEVELS = 3 +# Point filters, mip filter point (word 2 bits 27:26 = 1), MIN_LOD 0 and MAX_LOD 2.0 (u4.8, word 1 bits 23:12). +SAMPLER_WORDS = (0, 2 * 256 << 12, 0x04000000, 0) +CAPPED_WORDS = (0, 0, 0x04000000, 0) +ADDR = 10 # v10..v16: ddx, ddy, coordinates, slice; v4..v7 receive the four probes + +# (u, v, slice, ddx, ddy) +PROBES = ( + (Fraction(5, 8), Fraction(3, 8), 0, (Fraction(1, 4), 0), (0, Fraction(1, 4))), + (Fraction(5, 8), Fraction(3, 8), 0, (Fraction(1, 2), 0), (0, 0)), + (Fraction(1, 8), Fraction(7, 8), 0, (0, 0), (0, 1)), + (Fraction(7, 8), Fraction(5, 8), 1, (0, Fraction(1, 2)), (0, 0)), +) + + +def bits(value): + return struct.unpack('> m + out.append(texel_red(int(u * dim), int(v * dim), s, m)) + return out + + +def pipeline(code): + return G.Pipeline(VS_WORDS, code, root_blob()) + + +def check_disassembly(code): + off, decoded = 0, [] + while off < len(code): + size, mnemonic, asm, _ = D.decode_instruction(code, off) + assert size > 0 and 'unknown' not in mnemonic, (off, mnemonic, asm) + decoded.append(asm) + off += size + assert off == len(code) and decoded[-1] == 's_endpgm' + assert sum(a.startswith('image_sample_d') for a in decoded) == len(PROBES), decoded + + +def controls(): + _src, code = build_program(SAMPLER_WORDS) + check_disassembly(code) + hlsl = pipeline(code).hlsl_ps() + assert hlsl.count('SampleGrad(') == len(PROBES), hlsl + expected = reference() + # Mip 1 and 2 are reached, and every probe differs from its mip 0 value: the draw can tell the levels apart. + assert expected == [Fraction(7, 128), Fraction(34, 128), Fraction(65, 128), Fraction(54, 128)], expected + assert all(a != b for a, b in list(zip(expected, reference(0)))[1:]) and expected[0] == reference(0)[0] + assert 'smpl ' in pipeline(code).manifest() + print('four SampleGrad probes translate; reference reaches mips 0, 1, 2 and slice 1') + + +def run_draw(renderer, adapter, vs, ps, expected, sampler): + cmd = [renderer, adapter, '--startup-image-2d-array-mips', str(vs), str(ps), '0', expected, sampler] + return subprocess.run(cmd, capture_output=True, text=True) + + +def check_draw(dxc, renderer, adapter, fxc=None): + _src, code = build_program(SAMPLER_WORDS) + pipe = pipeline(code) + sampler = manifest_sampler(pipe) + capped = manifest_sampler(pipeline(build_program(CAPPED_WORDS)[1])) + hlsl = pipe.hlsl_ps() + # Sample takes (sampler, uv) only: drop the two gradient arguments of each call. + gradient = r'float2\(F\(v\d+\), F\(v\d+\)\)' + implicit, changed = re.subn(rf', {gradient}, {gradient}(?=\);)', '', hlsl) + assert changed == hlsl.count('.SampleGrad(') == 4 + implicit = implicit.replace('.SampleGrad(', '.Sample(') + want = ','.join(f32_hex(float(r)) for r in reference()) + mip0 = ','.join(f32_hex(float(r)) for r in reference(0)) + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + with tempfile.TemporaryDirectory() as tmp, CompileQueue() as queue: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = queue.call(compile_hlsl, compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + grad = queue.call(compile_hlsl, compiler, kind, hlsl, 'grad_%s' % kind, ps_profile, directory) + run = run_draw(renderer, adapter, vs, grad, want, sampler) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if run.returncode != 0: + raise AssertionError('%s image_sample_d draw failed:\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s image_sample_d: %s' % (kind, want), flush=True) + + capped_run = run_draw(renderer, adapter, vs, grad, want, capped) + if capped_run.returncode == 0 or ('actual=' + mip0) not in capped_run.stderr: + raise AssertionError('%s capped-sampler mutant did not produce mip 0:\n%s\n%s' + % (kind, capped_run.stdout, capped_run.stderr)) + print('%s mutant MAX_LOD 0 caught' % kind, flush=True) + + flat = queue.call(compile_hlsl, compiler, kind, implicit, 'flat_%s' % kind, ps_profile, directory) + flat_run = run_draw(renderer, adapter, vs, flat, want, sampler) + if flat_run.returncode == 0 or ('actual=' + mip0) not in flat_run.stderr: + raise AssertionError('%s implicit-Sample mutant did not produce mip 0:\n%s\n%s' + % (kind, flat_run.stdout, flat_run.stderr)) + print('%s mutant implicit Sample caught' % kind, flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3b4af0c56..9e3cde9cb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4833,6 +4833,27 @@ def image(self, ops, mods, how): if one and (how != 'sample' or len(cs) != 1 or not dmask or any(not m.startswith(('dim:', 'dmask:')) for m in mods)): raise Unsupported('unverified 1D image sample address or modifiers') lod = bias = None + grads = None + if how == 'd': + # Address dwords are ddx then ddy (one per coordinate axis each) and then the coordinates, so a 2D + # sample is six registers, a 2D array seven and a volume nine. Offsets, bias, clamp, a16 and the + # other layout-changing modifiers are refused; only cache-policy bits are accepted. + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('image_sample_d modifier %s' % m) + if dmask == 0: + raise Unsupported('image_sample_d with an empty dmask') + if one: + raise Unsupported('image_sample_d on a 1D image') + axes = 3 if dim == 'SQ_RSRC_IMG_3D' else 2 + want = 3 * axes + (1 if dim == 'SQ_RSRC_IMG_2D_ARRAY' else 0) + if want == 9 and len(cs) == 16 and not ops[1].startswith('['): + # A contiguous nine-dword volume address is encoded as a sixteen-register range; the rest is padding. + cs = cs[:9] + if len(cs) != want: + raise Unsupported('image_sample_d with %d address registers' % len(cs)) + grads = (cs[:axes], cs[axes:2 * axes]) + cs = cs[2 * axes:] if how in ('l', 'b'): # image_sample_l: the address dwords are the coordinates and then the explicit level. image_sample_b: # the RDNA 2 ISA (section 8.2.5, "{ offset } { bias } { z-compare } { derivative } { body }") puts one @@ -4934,12 +4955,12 @@ def image(self, ops, mods, how): if heap or not words or self.default_sampler_words(words): raise Unsupported('image_get_lod with a sampler that is not constant (LOD limits and bias unknown)') smp = self.pipe.sampler(tuple(self.lod_sampler_words('image_get_lod', words)), lod_limits=True) - elif how in ('sample', 'l', 'lz') and (heap or (words and self.default_sampler_words(words))): + elif how in ('sample', 'l', 'lz', 'd') and (heap or (words and self.default_sampler_words(words))): # A heap sampler, or the fixed default that stands in for one, keeps its unbounded static LOD range: the # descriptor is read at run time, so its MIN_LOD, MAX_LOD and bias are not validated here (#2221). self.pipe.lod_unvalidated.add(name) smp = heap or self.pipe.sampler(tuple(words)) - elif how in ('sample', 'l', 'lz') and words: + elif how in ('sample', 'l', 'lz', 'd') and words: # A constant descriptor carries its LOD limits like image_sample_b, under the same bias and range # validation. A mip filter of 0 (base level only) keeps the ordinary sampler, as before: refusing it # would drop every pipeline with an all-zero inline sampler, and only the bias form needs it refused. @@ -4959,7 +4980,11 @@ def image(self, ops, mods, how): if how == 'sample' and self.kind == 'cs': # A compute lane has no pixel quad to supply derivatives; level 0 would be a guess. raise Unsupported('image_sample with implicit LOD in a compute program') - if how == 'l': + if how == 'd': + axes = len(grads[0]) + dx, dy = ['float%d(%s)' % (axes, ', '.join(self.f(r) for r in g)) for g in grads] + call = '%s.SampleGrad(%s, %s, %s, %s)' % (tex, smp, uv, dx, dy) + elif how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'b': # SampleBias adds the bias to the implicit LOD, like the ISA's _B suffix ("Add this BIAS to the LOD @@ -5111,6 +5136,12 @@ def lod_sampler_words(self, name, words, mip_filter_none_ok=False): def op_image_sample_b(self, ops, mods): self.image(ops, mods, 'b') + def op_image_sample_d(self, ops, mods): + self.image(ops, mods, 'd') + + def op_image_sample_c_d(self, ops, mods): + raise Unsupported('image_sample_c_d: SampleCmpGrad needs shader model 6.8; only c and c_lz are lowered') + def op_image_get_lod(self, ops, mods): self.image(ops, mods, 'get_lod') From c461c847539e74244a59bd517cf9863a568ea0d4 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:50:18 +0100 Subject: [PATCH 19/29] tests: add source-built mesh57 loop refusal fixture (#2413 T6) (#2622) Prove tip translate_mesh57 refuses a back-edge outside the accepted group-memory exchanges by the named loop reason, with a mutant that drops the back-edge and an exact-string oracle. Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 10 ++ tests/startup_mesh57_loop_refusal.s | 74 ++++++++++++ tests/startup_mesh57_loop_refusal_check.py | 128 +++++++++++++++++++++ 6 files changed, 218 insertions(+) create mode 100644 tests/startup_mesh57_loop_refusal.s create mode 100644 tests/startup_mesh57_loop_refusal_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6ac6935fd..09345a2f4 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -86,6 +86,7 @@ jobs: (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_loop_refusal_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), @@ -268,6 +269,7 @@ jobs: tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ tests/startup_mesh57_skeleton_check.py \ + tests/startup_mesh57_loop_refusal_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 92208393f..cd477f204 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,6 +191,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_loop_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c6788297b..bae96dbe6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3334,6 +3334,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Slot 57 mesh requests (#2413): the one accepted group-memory shape translates; each mutation is refused. add_test(NAME startup_mesh57_skeleton COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py") + # Slot 57 mesh loop refusal outside the accepted exchanges (#2413 T6); mutant drops the back-edge. + add_test(NAME startup_mesh57_loop_refusal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_refusal_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 8a03f32b7..c5e36d0f3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9514,6 +9514,16 @@ and unproven wave masks remain unsupported. Use Append `draw ` for CPU-reference readback of the SCC paths and lane-masked if/else. +The `startup_mesh57_loop_refusal` check is a source-built program with the same +exchanges plus one deliberate back-edge after the count exchange +(`tests/startup_mesh57_loop_refusal.s`). Tip refuses it with +`slot 57 mesh: a loop outside the group-memory exchanges is not covered`. The +mutant replaces that back-edge with a second `s_nop` and must not stop on that +loop message. The oracle is an exact string match; a stub that only checks for +any `unsupported:` result would accept a wrong reason and is rejected by the +check. Host-only (no WARP/hardware draw). Run +`python -B tests/startup_mesh57_loop_refusal_check.py`, or the matching CTest. + A forward `s_cbranch_vccz` or `s_cbranch_vccnz` can also branch on the lane's VCC bit when EXEC is full and every incoming path last wrote VCC with a full-EXEC `v_cmp_*` from wave-uniform SGPRs or constants. A compare with a diff --git a/tests/startup_mesh57_loop_refusal.s b/tests/startup_mesh57_loop_refusal.s new file mode 100644 index 000000000..4303b7941 --- /dev/null +++ b/tests/startup_mesh57_loop_refusal.s @@ -0,0 +1,74 @@ +// Source-built slot 57 mesh fixture for #2413 item T6: the accepted group-memory exchanges plus one +// deliberate back-edge outside them. Tip translate_mesh57 must refuse that loop by name. +// Entry and buffer layout match tests/startup_mesh57_skeleton.s. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +// Back-edge outside both modelled exchanges: s_branch -2 retargets the preceding s_nop. +s_nop 0 +s_branch -2 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192 +s_waitcnt vmcnt(0) +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tests/startup_mesh57_loop_refusal_check.py b/tests/startup_mesh57_loop_refusal_check.py new file mode 100644 index 000000000..83f8da976 --- /dev/null +++ b/tests/startup_mesh57_loop_refusal_check.py @@ -0,0 +1,128 @@ +"""Slot 57 mesh loop refusal outside the accepted group-memory exchanges (#2413 T6). + +usage: startup_mesh57_loop_refusal_check.py + startup_mesh57_loop_refusal_check.py binary + +The source-built fixture (tests/startup_mesh57_loop_refusal.s) keeps the skeleton exchanges and inserts one +back-edge after the count exchange. Tip translate_mesh57 must refuse it with the named loop message. The mutant +replaces that back-edge with a second s_nop so the request no longer stops on the loop refusal (it translates +through the source-only path). A stubbed comparator that ignores the refusal string would accept a different +unsupported reason; this check uses an exact match so that stub fails. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LOOP_REASON = 'slot 57 mesh: a loop outside the group-memory exchanges is not covered' +# Skeleton words through the count-exchange join (s_mov_b64 exec, -1), then s_nop; s_branch -2; then the body. +MESH = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 bf800000 bf82fffe 7d28000e 3608008f 34080884 e0381000 80041004' + ' e03810c0 80041404 bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f' + ' 34080882 e0301180 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +# Mutant: the same program with the back-edge replaced by a second s_nop. +MUTANT = MESH[: MESH.index('bf82fffe')] + ['bf800000'] + MESH[MESH.index('bf82fffe') + 1:] +PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() + +FAILED = [] + + +def expect(what, got, want): + if got != want: + FAILED.append(what) + print('FAIL %s: got %r, want %r' % (what, got, want)) + + +def code(words): + return b''.join(struct.pack(' Date: Thu, 26 Nov 2026 00:55:12 +0100 Subject: [PATCH 20/29] shader: propagate descriptor pointers through s_add_u32/s_addc_u32 in gfx2hlsl (Part of #1723) (#2069) * fix: carry descriptor pointers through s_add_u32/s_addc_u32 in gfx2hlsl A table or root pointer advanced by a literal offset now keeps its source and byte offset, so a following s_load reads the advanced descriptor. A register addend on a pointer is refused instead of silently keeping the old pointer. Part of #1723 * shader: refuse descriptor pointer advances across branches and detached s_addc_u32 in gfx2hlsl (Part of #1723) * shader: keep the pointer-advance bookkeeping safe for stages without branch state (Part of #1723) * fix: keep the branch-join refusal for pointer adds in branching shaders * fix: require the matching high-word add before folding an advanced descriptor pointer * fix: advance 32-bit table pointers without a high word and judge the high operand by content * fix: keep descriptor pointer pair open until its matching s_addc_u32 * fix: let the descriptor pointer pair pass translate's SCC check, add WARP readback case * fix: refuse an untracked-offset pointer as a descriptor, run the pointer check in Linux CI * fix: refuse a root pointer load whose high word was overwritten * Revert "fix: refuse a root pointer load whose high word was overwritten" This reverts commit 0f226c5cb04d401951ef0dded42ce9f8c4f528f5. --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 4 + tests/startup_gfx2hlsl_desc_ptr_prop_check.py | 225 ++++++++++++++++++ tests/startup_smem_address_check.py | 43 ++++ tools/startup/gfx2hlsl.py | 92 ++++++- 5 files changed, 362 insertions(+), 3 deletions(-) create mode 100644 tests/startup_gfx2hlsl_desc_ptr_prop_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 09345a2f4..4cb608731 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -332,6 +332,7 @@ jobs: tests/startup_gfx2hlsl_getpc_refusal_check.py \ tests/startup_gfx2hlsl_image_arity_check.py \ tests/startup_compute_lds_dual_atomics_check.py \ + tests/startup_gfx2hlsl_desc_ptr_prop_check.py \ tests/run_checks_parallel_check.py build-and-test: name: Build and test on Windows diff --git a/CMakeLists.txt b/CMakeLists.txt index bae96dbe6..1c36f54b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3196,6 +3196,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_op_refusals COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_op_refusals_check.py") set_tests_properties(startup_gfx2hlsl_op_refusals PROPERTIES TIMEOUT 60) + # gfx2hlsl carries a descriptor pointer through s_add_u32 / s_addc_u32 with a literal offset (#1723). + add_test(NAME startup_gfx2hlsl_desc_ptr_prop COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_ptr_prop_check.py") + set_tests_properties(startup_gfx2hlsl_desc_ptr_prop PROPERTIES TIMEOUT 60) # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") diff --git a/tests/startup_gfx2hlsl_desc_ptr_prop_check.py b/tests/startup_gfx2hlsl_desc_ptr_prop_check.py new file mode 100644 index 000000000..96b082b72 --- /dev/null +++ b/tests/startup_gfx2hlsl_desc_ptr_prop_check.py @@ -0,0 +1,225 @@ +"""Check descriptor pointer propagation through s_add_u32 / s_addc_u32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_desc_ptr_prop_check.py + +A shader advances a descriptor table or root pointer with `s_add_u32 sD, sP, ` and +`s_addc_u32 sD+1, sP+1, 0`, into the same or another register pair, then loads descriptors through +the result. The load must read at the advanced byte offset. A non-literal addend must be refused, +never silently treated as the unchanged pointer. +""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +class Pipe: + sampler_heap = False + + def __init__(self): + self.keys = [] + self.modified = set() + + def ud(self, key): + return 'ud_%s' % '_'.join(map(str, key)) + + def resource(self, key, kind): + if (key, kind) not in self.keys: + self.keys.append((key, kind)) + return 'r%d' % self.keys.index((key, kind)) + + +def stage(symbols): + s = G.Stage.__new__(G.Stage) + s.pipe, s.sym, s.lines = Pipe(), dict(symbols), [] + s.used_s, s.used_v, s.uniform_v, s.exec_known = set(), set(), set(), True + s.masks, s.varying_s = set(), set() + s.scc_uniform = True + return s + + +def run(symbols, program, branches=False): + """Symbols after the (op, operands) steps, or the Unsupported message.""" + s = stage(symbols) + s.has_branches = branches + s.ins = [(4 * i, 4, op, '') for i, (op, _operands) in enumerate(program)] + try: + for i, (op, operands) in enumerate(program): + s.pc = 4 * i + if op == 's_load_dwordx4': + s.op_s_load_dwordx4(operands.split(', '), []) + else: + s.lower(op, '%s %s' % (op, operands), operands.split(', '), []) + except G.Unsupported as error: + return 'refused: %s' % error + return s + + +TABLE = {8: ('ptr', ('table', 0))} # a table pointer is 32 bits wide: no high word +ROOT = {8: ('ptr', ('root', 1)), 9: ('ptrhi', ('root', 1))} +ADVANCE = [('s_add_u32', 's20, s8, 0x40'), ('s_addc_u32', 's21, s9, 0')] +TABLE_ADVANCE = [('s_add_u32', 's20, s8, 0x40')] +LOAD = [('s_load_dwordx4', 's[4:7], s[20:21], 0x10')] + +s = run(TABLE, TABLE_ADVANCE + LOAD) +check('table pointer advanced into another pair, descriptor read at pointer + 0x40 + 0x10', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s if isinstance(s, str) else s.sym)) + +same = [('s_add_u32', 's8, s8, 0x20')] +s = run(TABLE, same + [('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('table pointer advanced in place', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x20, 0), str(s if isinstance(s, str) else s.sym)) + +twice = [('s_add_u32', 's20, s8, 0x40'), ('s_add_u32', 's22, s20, 0x10')] +s = run(TABLE, twice + [('s_load_dwordx4', 's[4:7], s[22:23], 0x4')]) +check('two advances add up', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x54, 0), str(s if isinstance(s, str) else s.sym)) + +s = run(ROOT, ADVANCE + LOAD) +check('root constant-buffer pointer advanced, buffer read at the advanced offset', + not isinstance(s, str) and any('Load(80)' in line for line in s.lines), str(s if isinstance(s, str) else s.lines)) + +s = run(TABLE, [('s_add_u32', 's8, s8, s2')]) +check('a register addend on a pointer is refused', isinstance(s, str) and 'non-literal' in s, str(s)) + +s = run(ROOT, ADVANCE + [('s_load_dwordx4', 's[4:7], s[20:21], s2')]) +check('a register offset through an advanced pointer is still refused', isinstance(s, str), str(s)) + +# The untracked-offset mark of a branchy program must be refused here too, never a TypeError. +s = stage({8: ('ptr', ('root', 1), 'added'), 9: ('ptrhi', ('root', 1))}) +try: + s.descriptor('s[8:9]') + check('an untracked-offset pointer used whole as a descriptor is refused', False, 'accepted') +except G.Unsupported: + check('an untracked-offset pointer used whole as a descriptor is refused', True) + +s = run(ROOT, ADVANCE) +try: + s.descriptor('s[20:21]') + check('an advanced pointer used whole as a descriptor is refused', False, 'accepted') +except G.Unsupported: + check('an advanced pointer used whole as a descriptor is refused', True) + +s = run(ROOT, ADVANCE, branches=True) +check('a pointer advance in a program with branches is refused', isinstance(s, str), str(s)) + +# The high-word add is the carry of the low-word add right before it, never of an unrelated carry in SCC. +s = run(ROOT, [('s_cmp_eq_u32', '0, 0'), ('s_addc_u32', 's9, s9, 0')]) +check('s_addc_u32 without the low-word add is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [ADVANCE[0], ('s_cmp_eq_u32', '0, 0'), ADVANCE[1]]) +check('s_addc_u32 separated from its low-word add is refused', isinstance(s, str), str(s)) + +# A fold needs the complete matching pair: the load must not trust the low word alone. +LOW = ADVANCE[0] +s = run(ROOT, [LOW] + LOAD) +check('missing high-word add is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('missing high-word add in place is refused', isinstance(s, str), str(s)) + +s = run(ROOT, ADVANCE + [('s_mov_b32', 's21, 0')] + LOAD) +check('overwritten high word is refused', isinstance(s, str), str(s)) + +mixed = dict(ROOT) +mixed[10], mixed[11] = ('ptr', ('root', 2)), ('ptrhi', ('root', 2)) +s = run(mixed, [LOW, ('s_addc_u32', 's21, s11, 0')] + LOAD) +check('high word from another pointer is refused', isinstance(s, str), str(s)) + +s = run(mixed, [LOW, ('s_addc_u32', 's21, s10, 0')] + LOAD) +check('high word from a different register pair is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [('s_add_u32', 's20, s8, 0xfffff'), ('s_addc_u32', 's21, s9, 0')] + LOAD) +check('complete pair with a large low-word add is folded', + not isinstance(s, str) and any('Load(%d)' % (0xfffff + 0x10) in line for line in s.lines), str(s)) + +# The high word is bound to the accumulated offset: the original word never stands in for an advanced one. +s = run(ROOT, ADVANCE + [('s_mov_b32', 's21, s9')] + LOAD) +check('completed high word overwritten by the original one is refused', isinstance(s, str), str(s)) + +SECOND = [('s_add_u32', 's22, s20, 0x20')] +s = run(ROOT, ADVANCE + SECOND + [('s_addc_u32', 's23, s9, 0'), ('s_load_dwordx4', 's[4:7], s[22:23], 0x10')]) +check('second advance with the original high word is refused', isinstance(s, str), str(s)) + +s = run(ROOT, ADVANCE + SECOND + [('s_addc_u32', 's23, s21, 0'), ('s_load_dwordx4', 's[4:7], s[22:23], 0x10')]) +check('second advance with the completed high word of the first pair is folded', + not isinstance(s, str) and any('Load(%d)' % (0x40 + 0x20 + 0x10) in line for line in s.lines), str(s)) + +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_addc_u32', 's9, s9, 0'), ('s_add_u32', 's8, s8, 0x20'), + ('s_addc_u32', 's9, s9, 0'), ('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('in-place advance twice with each completed high word is folded', + not isinstance(s, str) and any('Load(64)' in line for line in s.lines), str(s)) + +# Real entry state: a table pointer is one 32-bit register with no high word, so it advances with +# the low add alone and its neighbour register stays untouched. +def entry(params, kind='vs'): + s = stage({}) + s.kind, s.pipe.root = kind, {'params': params, 'flags': 0} + s.setup_entry() + return s.sym + + +REAL = entry([{'type': 0}, {'type': 2}]) +s = run(REAL, [('s_add_u32', 's20, s8, 0x40')] + LOAD) +check('real table pointer advanced by the low add alone, descriptor read at +0x50', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s)) + +s = run(REAL, [('s_add_u32', 's8, s8, 0x40'), ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')]) +check('real table pointer advanced in place keeps the next register symbol', + not isinstance(s, str) and s.sym.get(9) == REAL[9] and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s)) + +s = run(REAL, [('s_add_u32', 's20, s9, 0x40'), ('s_addc_u32', 's21, s10, 0')] + LOAD) +check('real root pointer pair advanced through the load', + not isinstance(s, str) and any('Load(80)' in line for line in s.lines), str(s)) + +s = run(REAL, [('s_add_u32', 's20, s9, 0x40')] + LOAD) +check('real root pointer without its high add is refused', isinstance(s, str), str(s)) + +copied = dict(ROOT) +copied[30] = ('ptrhi', ('root', 1)) +s = run(copied, [LOW, ('s_addc_u32', 's21, s30, 0')] + LOAD) +check('a copied high word completes the pair', not isinstance(s, str), str(s)) + +viam0 = dict(ROOT) +viam0['m0'] = ('ptr', ('root', 1)) +s = run(viam0, [('s_add_u32', 's20, m0, 0x40'), ('s_addc_u32', 's21, s9, 0')] + LOAD) +check('a low word held in m0 completes the pair', not isinstance(s, str), str(s)) + +# A program with branches does not track the added offset: the load through the advanced pointer is a refusal +# (never a crash), and the same straight-line shape keeps folding. +IN_PLACE = [('s_add_u32', 's8, s8, 0x40'), ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')] +s = run(TABLE, IN_PLACE, branches=True) +check('in-place pointer advance then load in a program with branches is refused, not a crash', + isinstance(s, str) and 'untracked offset' in s, str(s)) + +s = run(TABLE, IN_PLACE) +check('the same in-place advance without branches still folds to +0x50', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s if isinstance(s, str) else s.sym)) + +# The pair is complete only after its s_addc_u32: an in-place pair folds, and a high word that was only +# copied (never advanced) must not stand in for it. +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_addc_u32', 's9, s9, 0'), + ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')]) +check('complete in-place pair folds to +0x30', + not isinstance(s, str) and any('Load(%d)' % 0x30 in line for line in s.lines), str(s if isinstance(s, str) else s.lines)) + +s = run(ROOT, [ADVANCE[0], ('s_mov_b32', 's21, s9')] + LOAD) +check('out-of-place low add with a copied, unadvanced high word is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [ADVANCE[0], ADVANCE[1]] + LOAD) +check('complete out-of-place pair leaves the original high source untouched', + not isinstance(s, str) and s.sym.get(9) == ('ptrhi', ('root', 1)), str(s if isinstance(s, str) else s.sym)) + +if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) +print('startup_gfx2hlsl_desc_ptr_prop: ok') diff --git a/tests/startup_smem_address_check.py b/tests/startup_smem_address_check.py index e2d53f0f3..ba169a9e8 100644 --- a/tests/startup_smem_address_check.py +++ b/tests/startup_smem_address_check.py @@ -291,6 +291,22 @@ def controls(): for word in words[:64]: assert 0 < ((word >> 23) & 0xff) < 0xff, hex(word) + # 10. A complete s_add_u32/s_addc_u32 table-pointer pair goes through the full translate() (with its SCC + # check) and reads the same bytes as the single load at the summed offset; any other SCC reader is refused. + assert build_smem_pointer_pair_pipeline().hlsl_vs() == build_smem_dwordx4_pipeline().hlsl_vs() + vs_scc = b''.join(( + encode_sop2(0x00, 20, 0, 128 + 8), + encode_sop2(0x04, 21, 1, 128 + 0), + encode_sop2(0x0a, 30, 129, 128), # s_cselect_b32 s30, 1, 0 reads the carry + encode_smem(SMEM_LOAD_DWORDX4, 16, 20, soffset=125, imm=0x8), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + try: + G.Pipeline(vs_scc, struct.pack('<3I', 0xf800180f, 0, 0xbf810000), root_with_one_constant()).hlsl_vs() + raise AssertionError('an independent SCC read after the pointer pair was accepted') + except G.Unsupported as error: + assert 'scc' in str(error), error + # ---- D3D12 GPU readback cases ------------------------------------------------------------------------- @@ -309,6 +325,24 @@ def build_smem_dwordx4_pipeline(): return G.Pipeline(vs, ps, root_with_one_constant()) +def build_smem_pointer_pair_pipeline(): + """Same loads as build_smem_dwordx4_pipeline, but the vertex-buffer table pointer s[0:1] is advanced by a complete + s_add_u32 s20, s0, 8 / s_addc_u32 s21, s1, 0 pair and the load adds offset:0x8 (total 0x10).""" + vs = b''.join(( + encode_sop2(0x00, 20, 0, 128 + 8), # s_add_u32 s20, s0, 8 + encode_sop2(0x04, 21, 1, 128 + 0), # s_addc_u32 s21, s1, 0 + encode_smem(SMEM_LOAD_DWORDX4, 16, 20, soffset=125, imm=0x8), + encode_smem(SMEM_BUFFER_LOAD_DWORDX4, 20, 16, soffset=8, imm=0x18, glc=1), + encode_vop1(0x01, 4, 20), + encode_vop1(0x01, 5, 21), + encode_vop1(0x01, 6, 22), + encode_vop1(0x01, 7, 23), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + ps = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) + return G.Pipeline(vs, ps, root_with_one_constant()) + + def build_smem_m0_and_overlap_pipeline(): """VS: m0 + offset:0x14 dlc, const SGPR + offset:0x08, and overlapping runtime SGPR s[20:21] + offset:0x1c glc.""" vs = b''.join(( @@ -416,6 +450,15 @@ def check_gpu(directory, compiler, consumer, adapter, fxc=None): print(f's_buffer_load_dwordx4 (soffset={soffset}, offset:0x18):', [l for l in res.stdout.splitlines() if 'mismatches=' in l][0]) + # 1b. Vertex-buffer table pointer advanced by a complete s_add_u32/s_addc_u32 pair must read the same bytes as case 1. + p_pair = build_smem_pointer_pair_pipeline() + res_pair = run_buffer_case(directory, compiler, consumer, adapter, p_pair, p_pair.hlsl_vs(), + expected_smem_dwordx4(soffset=32), soffset=32) + if res_pair.returncode: + raise RuntimeError('advanced vertex-buffer table pointer pair:\n' + res_pair.stdout + res_pair.stderr) + print('advanced vertex-buffer table pointer (s_add_u32 + s_addc_u32, offset:0x8):', + [l for l in res_pair.stdout.splitlines() if 'mismatches=' in l][0]) + # 2. m0 + offset:0x14 dlc and destination-overlapping runtime SGPR s[20:21] + offset:0x1c glc. p_m0 = build_smem_m0_and_overlap_pipeline() src_m0 = p_m0.hlsl_vs() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9e3cde9cb..eb0d6f7b9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -620,6 +620,16 @@ def fbits(x): return struct.unpack(' ('s', 8, 11); 's8' -> ('s', 8, 8); 'v[1:3]' -> ('v', 1, 3); 'exec'/'vcc' pairs too.""" @@ -2110,6 +2120,8 @@ def descriptor(self, tok): # descriptors): its offset is the load's offset plus the first register's dword index. return s[1], (None if s[2] is None else s[2] + 4 * s[3]) if s and s[0] == 'ptr': + if len(s) > 2 and s[2]: + raise Unsupported('descriptor operand %s is a pointer with offset %s' % (tok, hex(s[2]) if isinstance(s[2], int) else s[2])) return s[1], None raise Unsupported('descriptor operand %s holds %s' % (tok, s)) @@ -2754,7 +2766,8 @@ def descriptor_scc_reads(self, branches, effects): continue seen.add((off, stale)) size, name, asm = instructions[off] - if stale and off not in self.calculated_pc and reads_scc(name, asm): + if (stale and off not in self.calculated_pc and off not in getattr(self, 'ptr_addc_pcs', ()) + and reads_scc(name, asm)): yield stale, name if off in effects: stale = effects[off] if effects[off] != 'emitted' else None @@ -3141,6 +3154,14 @@ def lower(self, base, asm, ops, mods): return self.set_v(reg_range(ops[0])[1], text.format(*args)) if base in SCA: return self.scalar(base, ops) + if base == 's_addc_u32': + # Only the high word of an advanced descriptor pointer; the carry is not modelled. + hi = reg_range(ops[1]) if len(ops) == 3 else None + if hasattr(self, 'scc_uniform') and self.tracks_uniformity(): + self.scc_uniform = False + if hi and hi[0] == 's' and self.pointer_add(base, ops[0], ops[1:], [self.sym.get(hi[1]), None]): + return None + raise Unsupported(base) if base == 's_getpc_b64': # RDNA 2 GETPC returns the address of its successor: the shader's load address plus a known byte # offset, which is not an integer this model can emit. It is elided only when the program also @@ -3392,6 +3413,54 @@ def sdwa(self, base, ops, mods): destination in self.low16_only_v) self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) + def pointer_add(self, base, dname, srcs, syms): + """Propagate a descriptor pointer through s_add_u32 sD, sP, / s_addc_u32 sD+1, sP+1, 0. + + The pair advances a table or root pointer by a literal byte offset, into the same or + another register pair. The offset rides in the low word as ('ptr', source, offset); the + high word keeps ('ptrhi', source). The low-word carry is taken as zero: the base is a + table or root address and the offset is below 1 MiB. Anything else returns False. + """ + if base not in ('s_add_u32', 's_addc_u32') or len(srcs) != 2 or not syms[0]: + return False + if getattr(self, 'has_branches', False): + # The symbolic update runs once in disassembly order; a branch could skip it or repeat it at run time. + return False + reg = reg_range(dname) + if not reg or reg[0] != 's' or reg[1] != reg[2] or reg[1] > 105: + return False + d = reg[1] + if base == 's_add_u32': + if syms[0][0] != 'ptr' or not re.fullmatch(r'(?:0[xX][0-9a-fA-F]+|\d+)', srcs[1]): + return False + added = int(srcs[1], 0) + if added > 0xfffff: + raise Unsupported('descriptor pointer offset %s' % srcs[1]) + before = syms[0][2] if len(syms[0]) > 2 else 0 + self.sym[d] = ('ptr', syms[0][1], before + added) + if syms[0][1][0] in PTR64_SOURCES and d + 1 <= 105: + # The carry-in of an s_addc_u32 is only the carry of this very add: remember where the next + # instruction starts so that the high-word add is accepted right behind it and nowhere else. + size = next((n for off, n, _name, _asm in getattr(self, 'ins', ()) if off == self.pc), 0) + self.ptr_low_add = (d, self.pc + size, syms[0][1], before, before + added) + # The pair stays open until the matching s_addc_u32 completes it. The high register is left as it + # is (in place it is still the original high source); a load through an open pair is refused. + self.__dict__.setdefault('ptr_open_pairs', set()).add(d) + return True + low = self.sym.get(d - 1) + mark = getattr(self, 'ptr_low_add', None) + hi = reg_range(srcs[0]) + # The high operand is judged by what it holds, not by where it sits: a copied high word still counts. + if (not mark or srcs[1] != '0' or not low or low[0] != 'ptr' or not hi or hi[0] != 's' + or mark[:2] != (d - 1, getattr(self, 'pc', 0)) or low[1] != mark[2] + or self.sym.get(hi[1]) != ptr_high_symbol(mark[2], mark[3])): + return False + self.sym[d] = ptr_high_symbol(mark[2], mark[4]) + getattr(self, 'ptr_open_pairs', set()).discard(d - 1) + # This s_addc_u32 is the only reader of the low add's elided carry; any other SCC reader stays refused. + self.__dict__.setdefault('ptr_addc_pcs', set()).add(self.pc) + return True + # scalar ALU with descriptor-word bookkeeping def exec_absorbed_source(self, base, srcs): """Index of a joined source of the instruction at a branch target whose stale value cannot reach bit 0 of @@ -3483,6 +3552,8 @@ def src_sym(t): raise Unsupported('scc from descriptor data') if word_pack: raise Unsupported('%s on descriptor data' % base) + if self.pointer_add(base, dname, srcs, syms): + return None if dname == 'm0': if scc: raise Unsupported('scc from descriptor data') @@ -3509,6 +3580,10 @@ def src_sym(t): self.sym[d + 1] = hi elif self.tracks_uniformity(): self.varying_s.add(d + 1) + elif (own and own[0] == 'ptr' and base in ('s_add_u32', 's_addc_u32') + and not getattr(self, 'has_branches', False)): + # With branches the offset is not tracked: the 'added' mark below stays, and the join refuses it. + raise Unsupported('%s adds a non-literal to a descriptor pointer' % base) elif raw is not None: self.sym[d] = raw if raw[0] == 'desc': @@ -3853,6 +3928,15 @@ def op_s_load_dwordx4(self, ops, mods, count=4): p = self.sym.get(base[1]) if not p or p[0] != 'ptr': raise Unsupported('s_load through s%d holding %s' % (base[1], p)) + if len(p) > 2 and not isinstance(p[2], int): + # The 'added' mark (an add whose offset is not tracked, as in a program with branches): no byte offset. + raise Unsupported('s_load through s%d: the pointer was advanced by an untracked offset' % base[1]) + base_off = p[2] if len(p) > 2 else 0 # literal bytes added by s_add_u32 on the pointer + if (base_off or len(p) > 2) and p[1][0] in PTR64_SOURCES: + # An advanced 64-bit pointer needs its high word completed by the matching s_addc_u32; + # a table pointer is 32 bits wide and has no high word. + if base[1] in getattr(self, 'ptr_open_pairs', ()) or self.sym.get(base[1] + 1) != ptr_high_symbol(p[1], base_off): + raise Unsupported('s_load through s%d: its high word is not the matching advanced pair' % base[1]) # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. token = smem_offset(ops[2]) known = self.const_soffset(token) if p[1] != ('smpheap',) else None @@ -3874,7 +3958,7 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) buf = self.pipe.resource((p[1], None), 'buf') for i in range(count): - self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) + self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, base_off + off + 4 * i)) return # The pointer symbol does not record an addend or a rewritten high word, so two loads through such a # pointer may read different words under the same (source, offset). In a compute or vertex stage (the @@ -3890,7 +3974,7 @@ def op_s_load_dwordx4(self, ops, mods, count=4): else: load = (self.pc,) for i in range(count): - self.sym[dst[1] + i] = ('desc', p[1], off, i) + load + self.sym[dst[1] + i] = ('desc', p[1], base_off + off, i) + load if into_vcc: self.vcc_lost = True self.vcc_descriptor_overwritten = False @@ -3900,6 +3984,8 @@ def op_s_load_dwordx4(self, ops, mods, count=4): return if into_vcc: raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) + if base_off: + raise Unsupported('s_load through %s advanced by %#x' % (p[1], base_off)) if p[1] == ('smpheap',): if self.pipe.sampler_heap and count == 4: # A sampler picked at run time from the sampler heap: keep the byte offset in the From d01afa7bef34afaea966ce559001c71c7cd13749 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:56:42 +0100 Subject: [PATCH 21/29] startup: re-key slot 57 mesh requests in shader_cache_rekey.py (#2634) shader_cache_rekey.py re-keyed graphics, RTV and slot 67 compute requests and only counted slot 57 mesh requests. mesh57_key hashes the request files under a versioned prefix, so after a revision that changes it a kept cache lost every slot 57 request. The tool now recomputes that key with mesh57_key and copies .ps57, .root and the .m57 ready marker under the new name, with the rules the other kinds follow: everything read first, nothing written on a missing or unreadable part, temporary name then rename, an existing target left alone. Slot 86 is still only counted. AI-assisted. --- docs/startup-runtime.md | 6 +- tests/startup_shader_cache_rekey_check.py | 57 +++++++++++++------ tests/startup_shader_cache_rekey_cli_check.py | 4 +- tools/startup/shader_cache_rekey.py | 30 +++++----- 4 files changed, 63 insertions(+), 34 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index e38af186e..d2bf02406 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1105,7 +1105,7 @@ Archive each run's logs together with a copy of `shader_cache/`, and leave the c When the translator handles more, the next `--pending` pass retries the waiting requests from the same cache. This holds only while the pipeline key is unchanged. The key hashes a translation revision string (`x2w-startup-shader-N`, in `pipeline_key` in `gfx2hlsl.py` and in the runtime). After a revision change the runtime asks for new keys, and the old requests stay in the cache. -**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies the graphics, RTV variant and slot 67 compute requests of the old cache under the keys of the current revision, computed with `pipeline_key` and `compute_key` of the `gfx2hlsl.py` next to it. Stop the title and any `--pending` loop first; nothing else may write the cache. Then: +**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies graphics, RTV variant, slot 67 compute and slot 57 mesh requests under their current keys. It uses `pipeline_key`, `compute_key` and `mesh57_key` from the adjacent `gfx2hlsl.py` and updates each RTV variant with its new graphics key. Stop the title and any `--pending` loop first; nothing else may write the cache. Then: ```powershell .\out\pe-env\Scripts\python.exe -B tools\startup\shader_cache_rekey.py out\startup\shader_cache out\startup\shader_cache_rekeyed @@ -1113,11 +1113,11 @@ When the translator handles more, the next `--pending` pass retries the waiting robocopy out\startup\shader_cache_rekeyed out\startup\shader_cache /XC /XN /XO ``` -1. The re-key step only reads the old cache and writes request files (`req_*`) only, never results or `.fail`. A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes: if a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. Slot 57 and slot 86 mesh requests have their own key strings and are not re-keyed. `X2W_TRANSLATE_JOBS` sets the number of hashing processes. +1. The re-key step reads the old cache and writes only request files (`req_*`). A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes. If a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. A slot 57 request requires `.ps57`, `.root` and the `.m57` ready marker. The `.ps57` file is empty when there is no pixel stage. Slot 86 mesh requests are only counted. `X2W_TRANSLATE_JOBS` sets the number of hashing processes. 2. `--pending` translates the re-keyed requests offline, as it does for a running title's cache. 3. The `robocopy` switches skip every file that already exists in the cache, so results the runtime or a later pass wrote are kept. A `robocopy` exit code below 8 means success: 1 is set when files were copied, and 2 is set because the cache holds files that the new directory does not. A code of 8 or more is a failure. On Linux, run the same steps with `./out/pe-env/bin/python` and merge with `cp -rn out/startup/shader_cache_rekeyed/. out/startup/shader_cache/`, which also keeps existing files. -`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer revision gives other names, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs. +`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer graphics and compute revision gives other names for those requests, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs. When `fxc` is available, a request that later translates loses its `.fail`. In manifest-only mode (`X2W_FXC` empty) the old `.fail` stays, so on a kept cache the `.fail` categories in `triage.md` can include pipelines that now have a `.txt`. That table counts category tokens over all `.fail` files, up to `--max-items`. diff --git a/tests/startup_shader_cache_rekey_check.py b/tests/startup_shader_cache_rekey_check.py index fc9a5ffa1..978639b90 100644 --- a/tests/startup_shader_cache_rekey_check.py +++ b/tests/startup_shader_cache_rekey_check.py @@ -6,11 +6,11 @@ - An old cache holds requests of the older revision (two graphics requests, one with an input layout, one compute request, an RTV variant of the first graphics request), one current-revision graphics request, the same - pipeline as the first at the current revision, a mesh request, a result and a .fail. Their old names differ - from pipeline_key / compute_key of the current revision. + pipeline as the first at the current revision, an old and a current slot 57 mesh request, a slot 86 marker, + a result and a .fail. Old request names differ from the current pipeline_key, compute_key or mesh57_key. - The tool, run as a script with two hashing processes, writes exactly the current names with the same bytes (the RTV variant re-keyed to its new base), no results or .fail, and gfx2hlsl.pending_keys lists them. -- With the newer revision the same requests get other names again. +- With the newer graphics and compute revision those requests and the RTV variant get other names again. - A second run writes nothing; re-keying a current cache keeps every name. - A missing request part, a truncated RTV variant or an RTV variant whose base request is missing exits with 1 and creates nothing. @@ -75,12 +75,19 @@ def gkey(module, parts): COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20, '.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root', '.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)} +MESH_OLD = {'.ps57': b'', '.root': b'RTS0 synthetic mesh root', '.m57': b'synthetic mesh'} +MESH_CURRENT = {'.ps57': b'synthetic pixel stage', '.root': b'RTS0 synthetic mesh root', + '.m57': b'another synthetic mesh'} def ckey(module, parts): return module.compute_key(parts['.c67'], parts['.data'], parts['.root'], parts['.desc'], parts['.sa'], parts['.sb']) +def mkey(module, parts): + return module.mesh57_key(parts['.m57'], parts['.ps57'], parts['.root']) + + def rtv_text(base): return 'rtv1 %d 28 87' % base @@ -108,7 +115,7 @@ def run(src, dst, jobs='2'): env=env, timeout=120) -def expected_files(module, requests, computes, rtv_bases): +def expected_files(module, requests, computes, rtv_bases, meshes): """{name: bytes} of the requests named under module's revision.""" files = {} for parts in requests: @@ -120,6 +127,9 @@ def expected_files(module, requests, computes, rtv_bases): for parts in rtv_bases: text = rtv_text(gkey(module, parts)).encode('ascii') files['req_%016x.rtv' % G.fnv(text)] = text + for parts in meshes: + for ext, data in parts.items(): + files['req_%016x%s' % (mkey(module, parts), ext)] = data return files @@ -143,7 +153,12 @@ def main(): old_rtv = write_rtv(src, gkey(older, g1)) write_request(src, gkey(G, g1), g1) # the same pipeline at the current revision write_request(src, gkey(G, g3), g3) # current only - write_request(src, 0x123456789abcdef0, {'.ps57': b'', '.root': b'RTS0 mesh', '.m57': b'\x01' * 8}) + meshes = (MESH_OLD, MESH_CURRENT) + old_mesh = mkey(G, MESH_OLD) ^ 1 + mesh_keys = {mkey(G, parts) for parts in meshes} + write_request(src, old_mesh, MESH_OLD) + write_request(src, mkey(G, MESH_CURRENT), MESH_CURRENT) + write_request(src, 0x123456789abcdef0, {'.m86': b'synthetic slot 86 marker'}) (src / ('%016x.txt' % gkey(older, g1))).write_text('synthetic result\n') (src / ('%016x.fail' % gkey(older, g2))).write_text('synthetic refusal\n') before = snapshot(src) @@ -152,22 +167,26 @@ def main(): current_names = {gkey(G, g1), gkey(G, g2), ckey(G, COMPUTE)} check('older-revision names differ from the current keys', not old_names & current_names) - # (a) re-keyed names are pipeline_key / compute_key of the current revision, with the same bytes. + # (a) re-keyed names use the current key functions, with the same bytes. dst = tmp / 'rekeyed' first = run(src, dst) check('re-key exits 0', first.returncode == 0, first.stderr.strip()) - want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,)) + want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,), meshes) got = contents(dst) if dst.is_dir() else {} check('re-keyed files are exactly the current requests', got == want, 'extra %s missing %s' % (sorted(set(got) - set(want)), sorted(set(want) - set(got)))) check('no results or .fail written', all(name.startswith('req_') for name in got)) check('graphics summary counts the duplicate and the current request', 'graphics: 4 requests, 2 already current -> 3 keys' in first.stdout, first.stdout) - check('mesh request counted, not re-keyed', 'm57 1, m86 0' in first.stdout, first.stdout) + check('mesh summary counts the old and current slot 57 requests', + 'm57: 2 requests, 1 already current -> 2 keys' in first.stdout, first.stdout) + check('slot 86 marker is only counted', 'not re-keyed (own key strings): m86 1' in first.stdout, + first.stdout) pending = G.pending_keys(str(dst), False) rtv_new = G.fnv(rtv_text(gkey(G, g1)).encode('ascii')) check('gfx2hlsl.pending_keys lists the re-keyed requests', - pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new}), pending) + pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new} | mesh_keys), + pending) # (e) the RTV variant names the new base and is named by the hash of its new text. rtv_file = dst / ('req_%016x.rtv' % rtv_new) @@ -186,7 +205,8 @@ def main(): third = run(dst, again, jobs='1') check('current requests keep their names', third.returncode == 0 and contents(again) == want and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout - and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout, third.stdout + third.stderr) + and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout + and 'm57: 2 requests, 2 already current -> 2 keys' in third.stdout, third.stdout + third.stderr) # (b) under a newer revision the same requests get other names (in process: one job keeps the patch). R.g, saved = newer, R.g @@ -198,18 +218,23 @@ def main(): R.g = saved got_newer = contents(newest) if newest.is_dir() else {} check('newer revision re-keys to its own names', code == 0 - and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,))) - check('newer names differ from the current names', not set(got_newer) & set(want)) + and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,), meshes)) + check('only mesh names are shared between the graphics and compute revisions', + set(got_newer) & set(want) == set(expected_files(G, (), (), (), meshes))) # (f) negative controls: an incomplete request, a truncated RTV variant or an RTV variant without its base - # request writes nothing. Without the base's ready marker (.a) there is one graphics request less: 5, not 6. + # request writes nothing. Without the base's ready marker (.a), the request count drops from 8 to 7. for label, total, reason, damage in ( - ('missing .root', 6, 'unreadable req_%016x.root' % gkey(older, g2), + ('missing .root', 8, 'unreadable req_%016x.root' % gkey(older, g2), lambda d: (d / ('req_%016x.root' % gkey(older, g2))).unlink()), - ('truncated RTV variant', 6, '.rtv text does not hash to its name', + ('missing slot 57 .root', 8, 'unreadable req_%016x.root' % old_mesh, + lambda d: (d / ('req_%016x.root' % old_mesh)).unlink()), + ('missing slot 57 .ps57', 8, 'unreadable req_%016x.ps57' % old_mesh, + lambda d: (d / ('req_%016x.ps57' % old_mesh)).unlink()), + ('truncated RTV variant', 8, '.rtv text does not hash to its name', lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes( rtv_text(gkey(older, g1)).encode('ascii')[:-3])), - ('missing RTV base', 5, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1), + ('missing RTV base', 7, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1), lambda d: (d / ('req_%016x.a' % gkey(older, g1))).unlink())): bad = tmp / ('bad_' + label.replace(' ', '_')) shutil.copytree(src, bad) diff --git a/tests/startup_shader_cache_rekey_cli_check.py b/tests/startup_shader_cache_rekey_cli_check.py index c8bee38eb..39a3f850a 100644 --- a/tests/startup_shader_cache_rekey_cli_check.py +++ b/tests/startup_shader_cache_rekey_cli_check.py @@ -80,7 +80,7 @@ def test_positive_main_argv_none_and_subprocess(self): rc, stdout, stderr = _run_main([str(src), str(dst_argv)]) self.assertEqual(rc, 0, stderr) self.assertEqual(stderr, "") - self.assertIn("m57 0, m86 1", stdout) + self.assertIn("not re-keyed (own key strings): m86 1", stdout) expected_names = sorted([ f"req_{keys['g']:016x}.a", f"req_{keys['g']:016x}.b", @@ -116,7 +116,7 @@ def test_positive_main_argv_none_and_subprocess(self): ) self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual(proc.stderr, "") - self.assertIn("m57 0, m86 1", proc.stdout) + self.assertIn("not re-keyed (own key strings): m86 1", proc.stdout) self.assertEqual(sorted(p.name for p in dst_sub.iterdir()), expected_names) def test_usage_and_path_guards(self): diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index 2e49127a8..64db2d903 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -3,16 +3,16 @@ usage: shader_cache_rekey.py -The key of a graphics request (req_.a), of an RTV variant (req_.rtv) and of a device slot 67 compute -request (req_.c67) hashes the translation revision string (pipeline_key and compute_key in gfx2hlsl.py). +Graphics (req_.a), slot 67 compute (req_.c67) and slot 57 mesh (req_.m57) request keys hash their +translation revision strings (pipeline_key, compute_key and mesh57_key in gfx2hlsl.py). RTV variants +(req_.rtv) hash text containing the graphics key. After a revision change the runtime asks for new keys, so a kept cache is cold again. This tool recomputes the key of every such request with the gfx2hlsl.py next to it and copies the request files under the new names into . `gfx2hlsl.py --pending ` can then translate them without a running title. The old cache is only read. Only request files (req_*) are written; results and .fail files are not, and a file that already exists in is left as it is. Each file is written to a temporary name and renamed; -the ready marker (.a, .c67) goes last, as the runtime writes it. Slot 57 and slot 86 mesh requests have their own -key strings and are only counted. +the ready marker (.a, .c67, .m57) goes last, as the runtime writes it. Slot 86 mesh requests are only counted. All requests are read before anything is written. When a request part is missing or unreadable, or an RTV variant is malformed, does not match its own name or names a base request that is not in the cache, the tool @@ -29,7 +29,8 @@ REQUEST = re.compile(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57|m86)') # Request files of each kind; the ready marker is last. -PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67')} +PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), + 'm57': ('.ps57', '.root', '.m57')} OPTIONAL = {'.ia'} # a graphics request without an input layout has no .ia @@ -61,6 +62,8 @@ def current_key(job): return kind, key, None, 'unreadable %s: %s' % (os.path.basename(error.filename or ''), error.strerror) if kind == 'g': return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b'')), None + if kind == 'm57': + return kind, key, g.mesh57_key(p['.m57'], p['.ps57'], p['.root']), None return kind, key, g.compute_key(p['.c67'], p['.data'], p['.root'], p['.desc'], p['.sa'], p['.sb']), None @@ -111,7 +114,8 @@ def rekey(src, dst, jobs=None, out=None): if os.path.exists(dst) and os.path.samefile(src, dst): print('error: the new request dir must not be the old cache', file=sys.stderr) return 2 - found = {'g': [], 'c': [], 'rtv': [], 'm57': 0, 'm86': 0} + found = {kind: [] for kind in (*PARTS, 'rtv')} + m86 = 0 try: entries = sorted(os.listdir(src)) except OSError as error: @@ -122,12 +126,12 @@ def rekey(src, dst, jobs=None, out=None): if not m: continue key, ext = int(m.group(1), 16), m.group(2) - if ext in ('m57', 'm86'): - found[ext] += 1 + if ext == 'm86': + m86 += 1 else: - found[{'a': 'g', 'c67': 'c', 'rtv': 'rtv'}[ext]].append(key) + found[{'a': 'g', 'c67': 'c'}.get(ext, ext)].append(key) - work = [(src, kind, key) for kind in ('g', 'c') for key in found[kind]] + work = [(src, kind, key) for kind in PARTS for key in found[kind]] jobs = min(jobs or g.translation_jobs(), len(work)) if jobs < 2: results = [current_key(job) for job in work] @@ -136,7 +140,7 @@ def rekey(src, dst, jobs=None, out=None): with ProcessPoolExecutor(max_workers=jobs) as pool: results = list(pool.map(current_key, work, chunksize=max(1, len(work) // (jobs * 4)))) - new = {'g': {}, 'c': {}} + new = {kind: {} for kind in PARTS} bad = [] for kind, old, key, reason in results: if reason: @@ -165,7 +169,7 @@ def rekey(src, dst, jobs=None, out=None): return 1 stats = {'written': 0, 'kept': 0} try: - for kind, label in (('g', 'graphics'), ('c', 'compute')): + for kind, label in (('g', 'graphics'), ('c', 'compute'), ('m57', 'm57')): done = set() for old, key in sorted(new[kind].items()): if key in done: # requests of the same pipeline from several revisions @@ -182,7 +186,7 @@ def rekey(src, dst, jobs=None, out=None): print('error: failed writing %s: %s' % (dst, error), file=sys.stderr) return 1 print('rtv variants: %d requests -> %d keys' % (len(found['rtv']), len(rtv)), file=out) - print('not re-keyed (own key strings): m57 %d, m86 %d' % (found['m57'], found['m86']), file=out) + print('not re-keyed (own key strings): m86 %d' % m86, file=out) print('files: %d written, %d already present in %s' % (stats['written'], stats['kept'], dst), file=out) return 0 From 4f6a3f45ba6b69c7cb78ab7b34249276a384121c Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Thu, 26 Nov 2026 01:57:56 +0200 Subject: [PATCH 22/29] shader: extract main(argv), bounds checks, and struct/zlib guards in shader_census with CLI suite (#2437) * shader: extract main(argv), bounds checks, and struct/zlib guards in shader_census with CLI suite * tests: accept Python 3.14+ argparse message in shader_census_cli_check --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/shader_census_cli_check.py | 296 +++++++++++++++++++++++++++++++ tools/shader_census.py | 33 ++-- 3 files changed, 319 insertions(+), 12 deletions(-) create mode 100644 tests/shader_census_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1c36f54b3..cf4f5ec41 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10263,6 +10263,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(shader_rdna_cvt_pk_u8_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_metadata_census COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_census_check.py") + add_test(NAME shader_census_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_census_cli_check.py") add_test(NAME shader_profile_audit_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_profile_audit_check.py") add_test(NAME shader_profile_audit_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/shader_census_cli_check.py b/tests/shader_census_cli_check.py new file mode 100644 index 000000000..d02e8fbd4 --- /dev/null +++ b/tests/shader_census_cli_check.py @@ -0,0 +1,296 @@ +"""Pure-Python CLI, boundary, error-guard, and mutation suite for tools/shader_census.py.""" +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "shader_census.py" +sys.path.insert(0, str(ROOT / "tools")) + +import shader_census as sc # noqa: E402 + + +def _make_dxbc(digest_byte: int, word: int, stage: int = 0) -> bytes: + program = struct.pack(" bytes: + encoder = zlib.compressobj(wbits=-15) + payload = encoder.compress(blob) + encoder.flush() + return ( + name.encode("ascii") + + b"\0\0" + + struct.pack("<4I", len(payload), 0, len(payload), len(blob)) + + payload + ) + + +def _make_archive() -> bytes: + a = _make_dxbc(1, 17, stage=0) + b = _make_dxbc(1, 18, stage=0) + c = _make_dxbc(2, 19, stage=5) + return _make_record(a) + _make_record(a) + _make_record(b) + _make_record(c) + + +def _make_ps9_cache(entries: list[tuple[int, int]] | None = None) -> tuple[bytes, int]: + entries = entries if entries is not None else [(0, 16), (16, 16), (0, 16), (32, 32)] + index_start = 128 + 0x70 + 2 * 0x18 + 3 * 8 + code_base = index_start + len(entries) * 8 + data = bytearray(code_base + 96) + data[:4] = b"PS\x00\x09" + struct.pack_into("<4I", data, 80, 1, 2, 3, len(entries)) + for i, (offset, size) in enumerate(entries): + struct.pack_into("<2I", data, index_start + i * 8, offset, size) + return bytes(data), code_base + + +class ShaderCensusCliTests(unittest.TestCase): + def _run_main(self, argv: list[str]) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + code = 0 + with redirect_stdout(out), redirect_stderr(err): + try: + ret = sc.main(argv) + code = 0 if ret is None else ret + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, out.getvalue(), err.getvalue() + + def _assert_main_fails(self, argv: list[str], *, expected_code: int, fragment: str | tuple[str, ...]) -> str: + code, stdout, stderr = self._run_main(argv) + self.assertEqual(code, expected_code, f"argv={argv!r} stderr={stderr!r}") + self.assertEqual(stdout, "") + self.assertNotIn("Traceback", stderr) + fragments = (fragment,) if isinstance(fragment, str) else fragment + self.assertTrue( + any(f in stderr for f in fragments), + f"none of {fragments!r} found in {stderr!r}", + ) + return stderr + + def test_main_argv_forwarding_and_json_schema(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + cache_bytes, base = _make_ps9_cache() + cache.write_bytes(cache_bytes) + + # Mutating sys.argv ensures main(argv) forwards its explicit argv parameter. + with mock.patch.object(sys, "argv", ["shader_census.py", "--bogus-global-flag"]): + for base_arg in (str(base), hex(base)): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + rc = sc.main([str(archive), "--cache-blob", str(cache), "--code-base", base_arg]) + self.assertEqual(rc, 0) + self.assertEqual(err.getvalue(), "") + doc = json.loads(out.getvalue()) + self.assertEqual( + set(doc), + { + "archive_records", + "dxbc_header_digests", + "classification_cache", + "cache_index", + "candidate_rejections", + }, + ) + self.assertEqual(doc["archive_records"]["count"], 4) + self.assertEqual(doc["archive_records"]["stages"], {"pixel": 3, "compute": 1}) + self.assertTrue(doc["archive_records"]["coverage_denominator"]) + self.assertEqual(doc["dxbc_header_digests"]["count"], 2) + self.assertFalse(doc["dxbc_header_digests"]["integrity_verified"]) + self.assertEqual(doc["classification_cache"]["count"], 3) + self.assertEqual(doc["cache_index"]["count"], 4) + self.assertEqual(doc["cache_index"]["distinct_spans"], 3) + self.assertEqual(doc["cache_index"]["aliased_entries"], 1) + self.assertEqual(doc["cache_index"]["code_base"], base) + self.assertEqual(doc["cache_index"]["index_offset"], 312) + self.assertEqual(doc["cache_index"]["program_validation"], "not performed") + + # Archive-only subprocess CLI check. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(archive)], + capture_output=True, + text=True, + check=True, + ) + sub_doc = json.loads(proc.stdout) + self.assertEqual(sub_doc["archive_records"]["count"], 4) + self.assertIsNone(sub_doc["cache_index"]) + + def test_zero_byte_archive_and_cache_blob(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + empty_archive = root / "empty.archive" + empty_cache = root / "empty.cache" + empty_archive.write_bytes(b"") + empty_cache.write_bytes(b"") + + # 0-byte archive succeeds cleanly without mmap ValueError. + code, out, err = self._run_main([str(empty_archive)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(doc["archive_records"]["count"], 0) + self.assertIsNone(doc["cache_index"]) + + # 0-byte --cache-blob exits 1 with 'Shader census:' (never mmap ValueError traceback). + stderr = self._assert_main_fails( + [str(empty_archive), "--cache-blob", str(empty_cache), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + self.assertIn("128-byte header", stderr) + + def test_directory_and_missing_path_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + archive.write_bytes(_make_archive()) + subdir = root / "a_dir" + subdir.mkdir() + + # Directory passed as archive -> exit 1 with 'Shader census:' and 'directory'. + err_arch = self._assert_main_fails([str(subdir)], expected_code=1, fragment="Shader census:") + self.assertIn("directory", err_arch.lower()) + + # Directory passed as --cache-blob -> exit 1 with 'Shader census:' and 'directory'. + err_blob = self._assert_main_fails( + [str(archive), "--cache-blob", str(subdir), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + self.assertIn("directory", err_blob.lower()) + + # Missing archive and missing --cache-blob -> exit 1 with 'Shader census:'. + self._assert_main_fails([str(root / "missing.archive")], expected_code=1, fragment="Shader census:") + self._assert_main_fails( + [str(archive), "--cache-blob", str(root / "missing.cache"), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + + def test_mismatched_and_negative_code_base_exit_2(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + cache_bytes, base = _make_ps9_cache() + cache.write_bytes(cache_bytes) + + # Mismatched --cache-blob / --code-base -> argparse exit 2. + self._assert_main_fails([str(archive), "--cache-blob", str(cache)], expected_code=2, fragment="supplied together") + self._assert_main_fails([str(archive), "--code-base", hex(base)], expected_code=2, fragment="supplied together") + + # Negative --code-base (decimal and hex) -> parser.error exit 2. + for args_extra in (["--code-base", "-1"], ["--code-base=-1"], ["--code-base=-0x10"]): + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), *args_extra], + expected_code=2, + fragment="non-negative", + ) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "-0x10"], + expected_code=2, + fragment=("expected one argument", "non-negative"), + ) + + # Non-integer --code-base -> exit 2. + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "not_an_int"], + expected_code=2, + fragment="invalid", + ) + + def test_malformed_truncated_inputs_and_struct_zlib_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + + # Truncated PS/9 cache (<128 bytes) -> exit 1 with 'Shader census:'. + cache.write_bytes(b"PS\x00\x09" + b"\x00" * 123) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + + # Out-of-bounds code_base or overlapping allocations -> exit 1 with 'Shader census:'. + bad_cache, bad_base = _make_ps9_cache([(0, 32), (16, 16)]) + cache.write_bytes(bad_cache) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(bad_base)], + expected_code=1, + fragment="Shader census:", + ) + good_cache, good_base = _make_ps9_cache() + cache.write_bytes(good_cache) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(len(good_cache) + 1)], + expected_code=1, + fragment="Shader census:", + ) + + # Corrupt deflate payload and truncated span in archive -> cleanly counted in candidate_rejections. + corrupt_deflate = b"bad_rec\0\0" + struct.pack("<4I", 20, 0, 20, 64) + b"\xff" * 20 + truncated_span = b"trunc_rec\0\0" + struct.pack("<4I", 64, 0, 64, 64) + b"\x00" * 8 + archive.write_bytes(_make_archive() + corrupt_deflate + truncated_span) + code, out, err = self._run_main([str(archive)]) + self.assertEqual(code, 0, err) + doc = json.loads(out) + self.assertEqual(doc["archive_records"]["count"], 4) + self.assertEqual(doc["candidate_rejections"]["deflate_error"], 1) + self.assertEqual(doc["candidate_rejections"]["truncated_span"], 1) + + # Direct struct.error and zlib.error propagation -> guarded to exit 1 with 'Shader census:'. + archive.write_bytes(_make_archive()) + for err_obj in (struct.error("truncated header"), zlib.error("corrupt deflate stream")): + with mock.patch.object(sc, "scene_records", side_effect=err_obj): + self._assert_main_fails( + [str(archive)], + expected_code=1, + fragment=f"Shader census: {err_obj}", + ) + with mock.patch.object(sc, "cache_index", side_effect=err_obj): + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(good_base)], + expected_code=1, + fragment=f"Shader census: {err_obj}", + ) + + # Subprocess end-to-end negative check verifying zero raw traceback on stderr. + sub_fail = subprocess.run( + [sys.executable, "-B", str(TOOL), str(archive), "--cache-blob", str(cache), "--code-base=-4"], + capture_output=True, + text=True, + ) + self.assertEqual(sub_fail.returncode, 2) + self.assertNotIn("Traceback", sub_fail.stderr) + self.assertIn("non-negative", sub_fail.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/shader_census.py b/tools/shader_census.py index 4f6d17b49..cff1f672a 100644 --- a/tools/shader_census.py +++ b/tools/shader_census.py @@ -1,4 +1,6 @@ """Report shader populations separately; do not classify or execute programs.""" +from __future__ import annotations + import argparse from contextlib import ExitStack import hashlib @@ -6,6 +8,7 @@ import mmap from pathlib import Path import struct +import zlib from resource_inventory import scene_records @@ -64,30 +67,36 @@ def observe(stage, blob, sections): ) -def main(): +def _map_input(stack: ExitStack, path: Path): + if path.is_dir(): + raise ValueError(f"Expected a file, not a directory: {path}") + stream = stack.enter_context(path.open("rb")) + if stream.seek(0, 2) == 0: + return b"" + return stack.enter_context(mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)) + + +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("--cache-blob", type=Path, help="Already decoded PS/9 cache from the same build") parser.add_argument("--code-base", type=lambda value: int(value, 0), help="Independently established code-area base in that cache (decimal or hex)") - args = parser.parse_args() + args = parser.parse_args(argv) if (args.cache_blob is None) != (args.code_base is None): parser.error("--cache-blob and --code-base must be supplied together") + if args.code_base is not None and args.code_base < 0: + parser.error("--code-base must be non-negative") try: with ExitStack() as stack: - def mapped(path): - stream = stack.enter_context(path.open("rb")) - if stream.seek(0, 2) == 0: - return b"" - return stack.enter_context(mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)) - - archive = mapped(args.archive) - blob = mapped(args.cache_blob) if args.cache_blob is not None else None + archive = _map_input(stack, args.archive) + blob = _map_input(stack, args.cache_blob) if args.cache_blob is not None else None result = census(archive, cache_blob=blob, code_base=args.code_base) - except (OSError, ValueError) as error: + except (OSError, ValueError, struct.error, zlib.error) as error: parser.exit(1, f"Shader census: {error}\n") print(json.dumps(result, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 1cd73d3a7d8ca53ab635b7059b1e2cf281f1eb39 Mon Sep 17 00:00:00 2001 From: chasegrindy Date: Thu, 26 Nov 2026 01:01:52 +0100 Subject: [PATCH 23/29] startup: invalidate slot 35 tables when the compute view heap changes (#2636) Track ordinary and oversized compute view heaps separately from the graphics lookup. Keep the table when the same heap is rebound and clear it on changes or unset. Cover the recorder in the CPU checks. Co-authored-by: chasegrindy <302242206+chasegrindy@users.noreply.github.com> --- src/startup_stubs/d3d12_draw.inl | 14 +++++------- src/startup_stubs/list_compute_root.h | 24 ++++++++++++++++++-- tests/startup_compute_root.cpp | 32 +++++++++++++++++++++++++-- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 16aa47bd0..ecd416690 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2385,15 +2385,14 @@ const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* sign void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heaps) { x2w_startup::SamplerSource source; - u64 view_heap = 0; + x2w_startup::ViewHeapSelection view_heaps; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); for (UINT i = 0; i < count; ++i) { for (const HeapInfo& heap : heap_infos()) { if (heap.wrapper == reinterpret_cast(heaps[i]) && - heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && - heap.logical_count > heap.count) - view_heap = heap.wrapper; + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); if (heap.wrapper == reinterpret_cast(heaps[i]) && heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) source = {static_cast(heap.title_sampler_cpu), heap.count}; @@ -2402,12 +2401,11 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* ReleaseSRWLockShared(¬e_lock); } auto& pass = pass_of(self); - if (pass.source_view_heap != view_heap) - { + if (pass.source_view_heap != view_heaps.graphics) { for (auto& table : pass.view_tables) table = {}; - pass.compute_tables.clear(); } - pass.source_view_heap = view_heap; + pass.compute_tables.set_view_heap(view_heaps.compute); + pass.source_view_heap = view_heaps.graphics; pass.title_samplers = source; } diff --git a/src/startup_stubs/list_compute_root.h b/src/startup_stubs/list_compute_root.h index 6e5d89c46..a47b3477d 100644 --- a/src/startup_stubs/list_compute_root.h +++ b/src/startup_stubs/list_compute_root.h @@ -14,6 +14,19 @@ namespace x2w_startup { +// Slot 32 builds this selection afresh for each call. The graphics lookup still singles out +// oversized logical heaps; compute table invalidation also needs ordinary shader-visible heaps. +struct ViewHeapSelection { + std::uint64_t graphics = 0; + std::uint64_t compute = 0; + + void note(std::uint64_t wrapper, bool shader_visible, unsigned logical_count, unsigned desktop_count) + { + if (shader_visible) compute = wrapper; + if (logical_count > desktop_count) graphics = wrapper; + } +}; + class ComputeTables { public: static constexpr unsigned max_parameters = 16; // same range as the graphics tables @@ -26,9 +39,10 @@ class ComputeTables { } // Slot 32 with another view heap: the recorded addresses belong to the old one. - void clear() + void set_view_heap(std::uint64_t heap) { - for (auto& table : tables_) table = {}; + if (heap != view_heap_) clear(); + view_heap_ = heap; } // False when the parameter is out of range (counted). @@ -47,7 +61,13 @@ class ComputeTables { std::uint32_t out_of_range_count() const { return out_of_range_; } private: + void clear() + { + for (auto& table : tables_) table = {}; + } + const void* signature_ = nullptr; + std::uint64_t view_heap_ = 0; ViewTable tables_[max_parameters] = {}; std::uint32_t out_of_range_ = 0; }; diff --git a/tests/startup_compute_root.cpp b/tests/startup_compute_root.cpp index b31cd9bcc..d8c065d48 100644 --- a/tests/startup_compute_root.cpp +++ b/tests/startup_compute_root.cpp @@ -7,6 +7,7 @@ namespace { using x2w_startup::ComputeTables; +using x2w_startup::ViewHeapSelection; using x2w_startup::ViewTable; using x2w_startup::resolve_view_table; int failures; @@ -65,9 +66,36 @@ int main() { ComputeTables s; s.set_signature(&root_a); + const auto select = [&](std::uint64_t heap, bool visible, unsigned logical, unsigned desktop) { + ViewHeapSelection selection; + selection.note(heap, visible, logical, desktop); + s.set_view_heap(selection.compute); + return selection; + }; + auto selection = select(1, true, 8, 8); + check(selection.compute == 1 && !selection.graphics, "ordinary heap is selected only for compute invalidation"); s.set_table(7, at(6)); - s.clear(); - check(s.table(7).address == 0 && s.signature() == &root_a, "a view heap change clears the tables and keeps the signature"); + select(1, true, 8, 8); + check(s.table(7).address == at(6).address, "same ordinary heap keeps the table"); + select(2, true, 8, 8); + check(!s.table(7).address, "different ordinary heap clears the table"); + s.set_table(7, at(6)); + selection = select(3, true, 16, 8); + check(selection.compute == 3 && selection.graphics == 3, "oversized heap remains visible to graphics lookup"); + check(!s.table(7).address, "ordinary to oversized clears the table"); + s.set_table(7, at(6)); + select(3, true, 16, 8); + check(s.table(7).address == at(6).address, "same oversized heap keeps the table"); + select(4, true, 16, 8); + check(!s.table(7).address, "different oversized heap clears the table"); + s.set_table(7, at(6)); + select(1, true, 8, 8); + check(!s.table(7).address, "oversized to ordinary clears the table"); + s.set_table(7, at(6)); + s.set_view_heap(ViewHeapSelection{}.compute); + check(!s.table(7).address && s.signature() == &root_a, "unsetting the heap clears the table and keeps the signature"); + selection = select(5, false, 8, 8); + check(!selection.compute && !selection.graphics, "CPU-only heap does not select a view heap"); } { ComputeTables s; From 01de48e9b9299e92700c596dc45ea8cc84cb1e77 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:03:39 +0000 Subject: [PATCH 24/29] shader: lower s_abs_i32 in gfx2hlsl (#1723) Port the pixel_aot signed absolute SOP1 so ordinary pipelines that only need |S0| stop refusing. SCC is the nonzero test of the result; INT_MIN stays. Lane masks and descriptor words are refused. CPU fixture with a negative control. Co-authored-by: SimSalabimse --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 8 ++ tests/startup_gfx2hlsl_s_abs_check.py | 158 ++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 36 ++++++ 6 files changed, 207 insertions(+) create mode 100644 tests/startup_gfx2hlsl_s_abs_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4cb608731..94c9df3c7 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -293,6 +293,7 @@ jobs: tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_s_abs_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ diff --git a/AGENTS.md b/AGENTS.md index cd477f204..730e97774 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,6 +173,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cf4f5ec41..ea4cdbaab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3215,6 +3215,9 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test. add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py") + # gfx2hlsl lowers s_abs_i32 (SOP1, #1723): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_abs COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_abs_check.py") # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index c5e36d0f3..58544ab29 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7993,6 +7993,14 @@ one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked as lane masks are refused because their per-lane projections lose the other bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitcmp$' -V`. +**Scalar absolute value.** Startup translation lowers `s_abs_i32` to +`(asint(S0) < 0 ? (0u - S0) : S0)` with `SCC = (D != 0)`, matching `pixel_aot` +(INT_MIN stays). Lane masks and descriptor-bearing sources are refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_abs_check.py`). The fixture is +CPU-only; Windows WARP/hardware draws are left for an independent retest. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + **Scalar immediate comparisons.** The startup translator sign-extends the 16-bit field of `s_movk_i32` and `s_cmpk_*_i32`, and zero-extends the field of `s_cmpk_*_u32`. The source-built check covers all six relations against diff --git a/tests/startup_gfx2hlsl_s_abs_check.py b/tests/startup_gfx2hlsl_s_abs_check.py new file mode 100644 index 000000000..b3a83dc68 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_abs_check.py @@ -0,0 +1,158 @@ +"""s_abs_i32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_abs_check.py + +RDNA 2 ISA SOP1: S_ABS_I32 sets D to the absolute value of S0 as a signed 32-bit word +(INT_MIN stays 0x80000000) and SCC = (D != 0). Matches pixel_aot. Lane masks and +descriptor sources are refused. The reference is plain Python; the translated text is +evaluated on the CPU. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0x00000001, 0xffffffff, 0x80000000, 0x7fffffff, 0xfffffff1, 0x12345678) +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack(' 105: + raise Unsupported('s_abs_i32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_abs_i32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + src_sym = None + if imm: + value = int(ops[1], 0) & 0xffffffff + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_abs_i32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_abs_i32 on a lane mask') + src_sym = self.sym.get(src[1]) + if src_sym and src_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_abs_i32 on %s data' % src_sym[0]) + value = src_sym[1] & 0xffffffff if src_sym and src_sym[0] == 'const' else None + if value is not None: + folded = (-value if value & 0x80000000 else value) & 0xffffffff + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + return None + expr = '(asint(%s) < 0 ? (0u - %s) : %s)' % ((self.u(ops[1]),) * 3) + self.set_s(dst[1], expr, scc='$ != 0') + return None + # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- def op_x2w_mesh_lane0(self, ops, mods): # `s_mov_b64 exec, 1` leaves lane 0 of each wave running. The saved copy of that mask is not modelled. From 8ecaa8ec992cf6ac404d9b7f3f044f62778f4796 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 08:04:21 +0800 Subject: [PATCH 25/29] tests: run heap-view load references in one batch per compute shader (#2635) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 4 +++ tests/compute_heap_view_check.py | 58 +++++++++++++++--------------- tests/compute_load_format_check.py | 12 +++---- 3 files changed, 38 insertions(+), 36 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c5e36d0f3..0292a18ef 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6277,6 +6277,10 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_|heap_view_controls$)' -V ``` +The 56 matching references and seven wrong references run in two shader batches, one for XY and one for +XYZW. Each dispatch still checks all 320 words. Each wrong reference must report its first differing +word, including the expected and actual values. The fourteen recompiled mutations run individually. + ```sh python3 -B tests/compute_heap_view_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` diff --git a/tests/compute_heap_view_check.py b/tests/compute_heap_view_check.py index 6555ec680..68156df83 100644 --- a/tests/compute_heap_view_check.py +++ b/tests/compute_heap_view_check.py @@ -259,58 +259,56 @@ def draw(directory, compiler, renderer, backend): src.write_text(lower(suffix), encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) shaders[suffix] = cso - case = directory / "heap.case" - dispatches = 0 + sources = {suffix: source_words(views) for suffix, views in SUFFIXES.items()} + cases = {suffix: [] for suffix in SUFFIXES} - def write(suffix, slot, groups, reference): - words = source_words(SUFFIXES[suffix]) + def write(case, suffix, slot, groups, reference): case.write_bytes(struct.pack("<321I", groups, *reference) + struct.pack("<16I", *constants(slot)) - + struct.pack("<320I", *words)) - return words + + struct.pack("<320I", *sources[suffix])) + + def add(suffix, slot, groups, reference, label, actual=None): + diagnostic = None + if actual is not None: + word = next((i for i, (a, b) in enumerate(zip(reference, actual)) if a != b), None) + if word is None: + raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") + diagnostic = f"word={word} expected={reference[word]:08x} actual={actual[word]:08x}" + path = directory / f"heap_{suffix}_{len(cases[suffix])}.case" + write(path, suffix, slot, groups, reference) + cases[suffix].append((path, f"{suffix} slot {slot} {label} (groups={groups})", diagnostic)) for suffix, views in SUFFIXES.items(): for slot in range(len(views) + 1): - words = source_words(views) - for groups in (1, 2): - write(suffix, slot, groups, expected_words(suffix, slot, groups, words)) - if subprocess.run([*cmd, shaders[suffix], case]).returncode: - return 1 - dispatches += 1 label = views[slot]["label"] if slot < len(views) else "no record" - print(f"{NAME}: {suffix} slot {slot} {'refused' if slot in REFUSED[suffix] or slot >= len(views) else 'read'}" - f" ({label})", flush=True) + action = "refused" if slot in REFUSED[suffix] or slot >= len(views) else "read" + for groups in (1, 2): + add(suffix, slot, groups, expected_words(suffix, slot, groups, sources[suffix]), f"{action} ({label})") + dispatches = sum(map(len, cases.values())) # A refusal must stay distinguishable from a published zero read: zeros against a refused slot must fail. for suffix, slot in (("xy", 4), ("xy", 10), ("xy", 11), ("xyzw", 3)): - words = source_words(SUFFIXES[suffix]) - zeros = [0] * WORDS - write(suffix, slot, 2, zeros) - bad = subprocess.run([*cmd, shaders[suffix], case], capture_output=True, text=True) - if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: - raise AssertionError(f"{NAME}: zeros published for {suffix} slot {slot} escaped detection\n{bad.stderr}") + add(suffix, slot, 2, [0] * WORDS, "zeros published", expected_words(suffix, slot, 2, sources[suffix])) for label, wrong, (suffix, slot) in WRONG: - words = source_words(SUFFIXES[suffix]) + words = sources[suffix] good = expected_words(suffix, slot, 2, words) wrong_words = expected_words(suffix, slot, 2, words, wrong=wrong) - if good == wrong_words: - raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") - write(suffix, slot, 2, wrong_words) - bad = subprocess.run([*cmd, shaders[suffix], case], capture_output=True, text=True) - if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: - raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{bad.stderr}") + add(suffix, slot, 2, wrong_words, label, good) + for suffix, references in cases.items(): + fmt.check_references(NAME, renderer, backend, shaders[suffix], references) + wrong_count = sum(map(len, cases.values())) - dispatches original = {suffix: lower(suffix) for suffix in SUFFIXES} + case = directory / "mutated.case" for label, old, new, (suffix, slot) in MUTATIONS: mutated = original[suffix].replace(old, new, 1) if mutated == original[suffix]: raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") - words = source_words(SUFFIXES[suffix]) - write(suffix, slot, 2, expected_words(suffix, slot, 2, words)) + write(case, suffix, slot, 2, expected_words(suffix, slot, 2, sources[suffix])) bad_src, bad_cso = directory / "mutated.hlsl", directory / "mutated.cso" bad_src.write_text(mutated, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", bad_cso, bad_src], check=True) bad = subprocess.run([*cmd, bad_cso, case], capture_output=True, text=True) if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{bad.stderr}") - print(f"{NAME}: {dispatches} dispatches, {3 + len(WRONG)} wrong references and " + print(f"{NAME}: {dispatches} dispatches, {wrong_count} wrong references and " f"{len(MUTATIONS)} mutated sources checked") return 0 diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index bc98b779b..2539cc006 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -312,7 +312,7 @@ def binary(directory, assembler, objcopy, library): return 0 -def check_references(renderer, backend, shader, cases): +def check_references(name, renderer, backend, shader, cases): paths = [path for path, _label, _diagnostic in cases] result = subprocess.run([renderer, backend, "--compute-store-batch", shader, *paths], capture_output=True, text=True) @@ -324,18 +324,18 @@ def check_references(renderer, backend, shader, cases): if (i >= len(statuses) or statuses[i] != f"case={i} status={status}" or i >= len(messages) or not messages[i].startswith(f"case={i} path={path}\n") or (diagnostic and diagnostic not in messages[i])): - raise AssertionError(f"{NAME}: {label} expected {status}\n{result.stdout}{result.stderr}") + raise AssertionError(f"{name}: {label} expected {status}\n{result.stdout}{result.stderr}") summary = summaries[i] if i < len(summaries) else "" counts = re.fullmatch(r"groups=\d+ compared_words=320 mismatches=(\d+)", summary) if not counts or (int(counts[1]) > 0) != bool(diagnostic): - raise AssertionError(f"{NAME}: {label} unexpected readback\n{result.stdout}{result.stderr}") + raise AssertionError(f"{name}: {label} unexpected readback\n{result.stdout}{result.stderr}") expected_exit = int(any(diagnostic for _, _, diagnostic in cases)) if not (len(cases) == len(statuses) == len(messages) == len(summaries)) or result.returncode != expected_exit: - raise AssertionError(f"{NAME}: unexpected batch result ({result.returncode})\n{result.stdout}{result.stderr}") + raise AssertionError(f"{name}: unexpected batch result ({result.returncode})\n{result.stdout}{result.stderr}") labels = iter(label for _path, label, _diagnostic in cases) for line in result.stdout.splitlines(): if line.startswith("groups="): - print(f"{NAME}: {next(labels)}") + print(f"{name}: {next(labels)}") print(line) @@ -413,7 +413,7 @@ def invalid_formats(number): mutations.append((number, label, case, mutated)) with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: - batch = pool.submit(check_references, renderer, backend, cso, references) + batch = pool.submit(check_references, NAME, renderer, backend, cso, references) mutants = [pool.submit(run_mutation, *mutation) for mutation in mutations] batch.result() for future in mutants: From 48236d4dc297ca4d374c94f0d6ccca5d8762762a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:05:56 +0000 Subject: [PATCH 26/29] test: pin sopk descriptor-refusal mutation to sopk-only raise s_bitset0/1_b32 reused the plain-scalar sym allow-list line, so the sopk_accum mutant needle was no longer unique. Match the sopk raise that formats with `base` instead. Co-authored-by: SimSalabimse --- tests/startup_gfx2hlsl_sopk_accum_check.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/startup_gfx2hlsl_sopk_accum_check.py b/tests/startup_gfx2hlsl_sopk_accum_check.py index 4f92dd352..bc689e701 100644 --- a/tests/startup_gfx2hlsl_sopk_accum_check.py +++ b/tests/startup_gfx2hlsl_sopk_accum_check.py @@ -290,7 +290,11 @@ def load_mutant(old, new): ('no mask refusal', "if d in self.masks or self.sym.get(d, ('',))[0] == 'execcopy':", 'if False:'), ('no descriptor refusal', - "if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'):", 'if False:'), + # Pin the sopk-only raise (uses `base`); other SOP1 ports share the same sym allow-list line. + "if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'):\n" + " raise Unsupported('%s on %s data' % (base, sym[0]))", + "if False:\n" + " raise Unsupported('%s on %s data' % (base, sym[0]))"), ('lowering removed', 'def op_s_addk_i32(self, ops, mods):', 'def op_unused_addk(self, ops, mods):'), ] From 46313981d58bd82d0e65774126f64da1477555a2 Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:17:02 +0100 Subject: [PATCH 27/29] shader: lower s_bitset0/1_b32 in gfx2hlsl (#2023 Item J) (#2638) * shader: lower s_bitset0/1_b32 in gfx2hlsl (#2023 Item J) Port the pixel_aot bit set/clear SOP1 forms so ordinary vertex and pixel pipelines that only need an in-place scalar bit update stop refusing at s_bitset1_b32. SCC stays unchanged; lane masks and descriptor SGPRs refuse. Co-authored-by: SimSalabimse * test: pin sopk descriptor-refusal mutation to sopk-only raise s_bitset0/1_b32 reused the plain-scalar sym allow-list line, so the sopk_accum mutant needle was no longer unique. Match the sopk raise that formats with `base` instead. Co-authored-by: SimSalabimse --------- Co-authored-by: Cursor Agent Co-authored-by: SimSalabimse --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 9 ++ tests/startup_gfx2hlsl_s_bitset_check.py | 155 +++++++++++++++++++++ tests/startup_gfx2hlsl_sopk_accum_check.py | 6 +- tools/startup/gfx2hlsl.py | 52 +++++++ 7 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_s_bitset_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4cb608731..5d86ad940 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -293,6 +293,7 @@ jobs: tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_s_bitset_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ diff --git a/AGENTS.md b/AGENTS.md index cd477f204..84cb9183a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,6 +173,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cf4f5ec41..52c80c494 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3215,6 +3215,9 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test. add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py") + # gfx2hlsl lowers s_bitset0_b32 and s_bitset1_b32 (SOP1, #2023 Item J): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_bitset COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset_check.py") # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 0292a18ef..6088bc218 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7997,6 +7997,15 @@ one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked as lane masks are refused because their per-lane projections lose the other bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitcmp$' -V`. +**Scalar bit set and clear.** Startup translation lowers `s_bitset0_b32` and +`s_bitset1_b32` in place: bit `S0[4:0]` of the destination is cleared or set, +and SCC is unchanged (same form as `pixel_aot` / #1579; Refs #2023 Item J). +Lane masks and descriptor-bearing SGPRs are refused. A known constant +destination with a known bit index folds. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitset$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_bitset_check.py`). The fixture is +CPU-only; Windows WARP/hardware draws are left for an independent retest. + **Scalar immediate comparisons.** The startup translator sign-extends the 16-bit field of `s_movk_i32` and `s_cmpk_*_i32`, and zero-extends the field of `s_cmpk_*_u32`. The source-built check covers all six relations against diff --git a/tests/startup_gfx2hlsl_s_bitset_check.py b/tests/startup_gfx2hlsl_s_bitset_check.py new file mode 100644 index 000000000..baa873e0c --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitset_check.py @@ -0,0 +1,155 @@ +"""s_bitset0_b32 and s_bitset1_b32 in tools/startup/gfx2hlsl.py (#2023 Item J). + +usage: startup_gfx2hlsl_s_bitset_check.py + +RDNA 2 ISA SOP1: S_BITSET0_B32 clears bit S0[4:0] of D in place; S_BITSET1_B32 sets that bit. +SCC is unchanged. The reference is plain Python integer arithmetic; the translated text is evaluated +on the CPU. Lane-mask and descriptor-bearing destinations or sources are refused. A mutation that +drops the bit update must disagree with the reference. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0xffffffff, 0x80000001, 0x00010020, 0x55555555, 0xaaaaaaaa, 0x12345678) +INDEXES = (0, 1, 5, 16, 31, 32, 33, 0x21, 0xffffffe5) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack(' 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + d = dst[1] + if self.is_lane_mask(ops[0]) or d in self.masks: + raise Unsupported('%s on a lane mask' % name) + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + bit_sym = None + if imm: + index_imm = int(ops[1], 0) & 31 + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('%s source %s' % (name, ops[1])) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('%s on a lane mask' % name) + bit_sym = self.sym.get(src[1]) + if bit_sym and bit_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, bit_sym[0])) + index_imm = bit_sym[1] & 31 if bit_sym and bit_sym[0] == 'const' else None + sym = self.sym.get(d) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, sym[0])) + prev = self.S(d) + bit = self.u(ops[1]) + mask = '(1u << (%s & 31))' % bit + result = '(%s & ~%s)' % (prev, mask) if clear else '(%s | %s)' % (prev, mask) + if sym and sym[0] == 'const' and index_imm is not None: + value = ((sym[1] & ~(1 << index_imm)) if clear else (sym[1] | (1 << index_imm))) & 0xffffffff + self.set_s(d, '0x%08xu' % value, ('const', value)) + else: + self.set_s(d, result) + self.masks.discard(d) + return None + def scalar_cmov(self, ops, mods, pair, name=None): """D = SCC ? S0 : D on plain SGPR destinations; SCC is unchanged.""" name = name or 's_cmov_b%d' % (64 if pair else 32) From 6afdbd927ea721d3ec37f8b71f1190a362e9ec70 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:21:43 +0000 Subject: [PATCH 28/29] test: add D3D12 WARP dispatch readback for s_abs_i32 Mirror the #2639 / pack_absdiff UAV dump pattern. Cover INT_MIN, -1, 0, a positive word, SCC, and an SCC-dependent branch on the adapter. Co-authored-by: SimSalabimse --- docs/experiments.md | 7 +- tests/startup_gfx2hlsl_s_abs_check.py | 244 ++++++++++++++++++-------- 2 files changed, 175 insertions(+), 76 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 509007930..518f024f5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8001,8 +8001,11 @@ bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitcmp$' `(asint(S0) < 0 ? (0u - S0) : S0)` with `SCC = (D != 0)`, matching `pixel_aot` (INT_MIN stays). Lane masks and descriptor-bearing sources are refused. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs$' -V` -(or `python3 -B tests/startup_gfx2hlsl_s_abs_check.py`). The fixture is -CPU-only; Windows WARP/hardware draws are left for an independent retest. +(or `python3 -B tests/startup_gfx2hlsl_s_abs_check.py`). The `_dispatch_warp` +/ `_dispatch_hardware` variants compile the translated expression into a +compute shader and compare UAV readback for INT_MIN, -1, 0 and a positive +word (plus an SCC-dependent branch token) against the same reference: +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs_dispatch_warp$' -V`. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). **Scalar bit set and clear.** Startup translation lowers `s_bitset0_b32` and diff --git a/tests/startup_gfx2hlsl_s_abs_check.py b/tests/startup_gfx2hlsl_s_abs_check.py index b3a83dc68..306731689 100644 --- a/tests/startup_gfx2hlsl_s_abs_check.py +++ b/tests/startup_gfx2hlsl_s_abs_check.py @@ -1,15 +1,23 @@ """s_abs_i32 in tools/startup/gfx2hlsl.py (#1723). usage: startup_gfx2hlsl_s_abs_check.py + startup_gfx2hlsl_s_abs_check.py dispatch RDNA 2 ISA SOP1: S_ABS_I32 sets D to the absolute value of S0 as a signed 32-bit word (INT_MIN stays 0x80000000) and SCC = (D != 0). Matches pixel_aot. Lane masks and descriptor sources are refused. The reference is plain Python; the translated text is evaluated on the CPU. + +With `dispatch`, the lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_s_ff1_check / +startup_gfx2hlsl_pack_absdiff_check). Each case stores D, SCC, and an SCC-dependent +branch token so `asint` / `0u - x` and the nonzero SCC test are exercised on device. """ import re import struct +import subprocess import sys +import tempfile from pathlib import Path HERE = Path(__file__).resolve().parent @@ -23,6 +31,10 @@ MASK = 0xffffffff SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} WORDS = (0x00000000, 0x00000001, 0xffffffff, 0x80000000, 0x7fffffff, 0xfffffff1, 0x12345678) +# GPU cases from review: INT_MIN, -1, 0, a positive value (SCC follows D != 0). +DRAW = (0x80000000, 0xffffffff, 0x00000000, 0x12345678) +SCC_BRANCH_TAKEN = 0x00a11ced +SCC_BRANCH_NOT = 0x00dead00 VCC_LO, EXEC_LO = 106, 126 failures = [] @@ -76,83 +88,167 @@ def run(lines, env): return env -bad = None -lines, _ = translate(sop1('s_abs_i32', 3, 1)) -assert lines and not lines[0].startswith('refused'), lines -for word in WORDS: - out = run(lines, {'s1': word, 'scc': 0}) - want = (ref_abs(word), int(ref_abs(word) != 0)) - if (out['s3'], int(bool(out['scc']))) != want: - bad = (hex(word), (out['s3'], out['scc']), want) - break -check('s_abs_i32 SGPR source', bad is None, str(bad)) +def controls(): + bad = None + lines, _ = translate(sop1('s_abs_i32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': 0}) + want = (ref_abs(word), int(ref_abs(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_abs_i32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_abs_i32', 's_abs_i32 s3, %d' % (word if word < 0x80000000 else word - (1 << 32))) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': 0}) + want = (ref_abs(word), int(ref_abs(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), stage.lines, (out['s3'], out['scc']), want) + break + check('s_abs_i32 immediate source', bad is None, str(bad)) + + lines, sym = translate(sop1('s_abs_i32', 3, 1), sym={1: ('const', 0xfffffff1)}) + # 0xfffffff1 = -15; abs = 15 + check('s_abs_i32 folds a constant source', + lines[0].startswith('s3 = 0x0000000fu;') and sym.get(3) == ('const', 15) + and any(l.startswith('scc = ') for l in lines), + str((lines, sym.get(3)))) + + # INT_MIN stays. + lines, sym = translate(sop1('s_abs_i32', 3, 1), sym={1: ('const', 0x80000000)}) + check('s_abs_i32 keeps INT_MIN', + lines[0].startswith('s3 = 0x80000000u;') and sym.get(3) == ('const', 0x80000000), + str((lines, sym.get(3)))) + + refused = [translate(sop1('s_abs_i32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_abs_i32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) -bad = None -for word in WORDS: stage = Probe() + stage.masks.add(1) try: - stage.one('s_abs_i32', 's_abs_i32 s3, %d' % (word if word < 0x80000000 else word - (1 << 32))) + stage.one('s_abs_i32', 's_abs_i32 s3, s1') + check('s_abs_i32 refuses a tracked lane-mask source', False, stage.lines) except G.Unsupported as error: - bad = ('refused %s' % error,) - break - out = run(stage.lines, {'scc': 0}) - want = (ref_abs(word), int(ref_abs(word) != 0)) - # Constant fold emits a hex literal and SCC from the folded value. - if 's3 = 0x' in stage.lines[0]: - if (out['s3'], int(bool(out['scc']))) != want: - bad = (hex(word), stage.lines, (out['s3'], out['scc']), want) - break - elif (out['s3'], int(bool(out['scc']))) != want: - bad = (hex(word), stage.lines, (out['s3'], out['scc']), want) - break -check('s_abs_i32 immediate source', bad is None, str(bad)) - -lines, sym = translate(sop1('s_abs_i32', 3, 1), sym={1: ('const', 0xfffffff1)}) -# 0xfffffff1 = -15; abs = 15 -check('s_abs_i32 folds a constant source', - lines[0].startswith('s3 = 0x0000000fu;') and sym.get(3) == ('const', 15) - and any(l.startswith('scc = ') for l in lines), - str((lines, sym.get(3)))) - -# INT_MIN stays. -lines, sym = translate(sop1('s_abs_i32', 3, 1), sym={1: ('const', 0x80000000)}) -check('s_abs_i32 keeps INT_MIN', - lines[0].startswith('s3 = 0x80000000u;') and sym.get(3) == ('const', 0x80000000), - str((lines, sym.get(3)))) - -refused = [translate(sop1('s_abs_i32', d, s))[0][0] for d, s in ( - (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] -check('s_abs_i32 refuses lane-mask destinations/sources', - all(r.startswith('refused: ') for r in refused), str(refused)) - -stage = Probe() -stage.masks.add(1) -try: - stage.one('s_abs_i32', 's_abs_i32 s3, s1') - check('s_abs_i32 refuses a tracked lane-mask source', False, stage.lines) -except G.Unsupported as error: - check('s_abs_i32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + check('s_abs_i32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_abs_i32', 's_abs_i32 s3, s1') + check('s_abs_i32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_abs_i32 refuses a descriptor source', 'desc' in str(error), str(error)) -stage = Probe() -stage.sym[1] = ('desc', ('root', 0), 0, 0) -try: + # Negative control: drop the abs; evaluation must diverge on a negative word. + stage = Probe() stage.one('s_abs_i32', 's_abs_i32 s3, s1') - check('s_abs_i32 refuses a descriptor source', False, stage.lines) -except G.Unsupported as error: - check('s_abs_i32 refuses a descriptor source', 'desc' in str(error), str(error)) - -# Negative control: drop the abs; evaluation must diverge on a negative word. -stage = Probe() -stage.one('s_abs_i32', 's_abs_i32 s3, s1') -mutated = [re.sub(r'\(asint\(s1\) < 0 \? \(0u - s1\) : s1\)', 's1', stage.lines[0])] -assert mutated != stage.lines, stage.lines -out_ok = run(stage.lines, {'s1': 0xfffffff1, 'scc': 0}) -out_bad = run(mutated + stage.lines[1:], {'s1': 0xfffffff1, 'scc': 0}) -check('mutation that drops abs diverges', - out_ok['s3'] == 15 and out_bad['s3'] == 0xfffffff1, - str((out_ok['s3'], out_bad['s3']))) - -if failures: - print('FAILED: %s' % ', '.join(failures)) - sys.exit(1) -print('all ok') + mutated = [re.sub(r'\(asint\(s1\) < 0 \? \(0u - s1\) : s1\)', 's1', stage.lines[0])] + assert mutated != stage.lines, stage.lines + out_ok = run(stage.lines, {'s1': 0xfffffff1, 'scc': 0}) + out_bad = run(mutated + stage.lines[1:], {'s1': 0xfffffff1, 'scc': 0}) + check('mutation that drops abs diverges', + out_ok['s3'] == 15 and out_bad['s3'] == 0xfffffff1, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +def dispatch_abs(dxc, runner, adapter, cases, directory): + """Translate s_abs_i32 once; feed each case through a UAV and read D, SCC, and a branch token.""" + lines, _ = translate(sop1('s_abs_i32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(len(cases))) + # Per case: abs result, SCC as uint, SCC-dependent branch token. + result_width = 3 + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + dst_byte = 4 * (len(fill) + result_width * i) + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %s;' % (4 * i, '%#010xu' % (fill[i] ^ word)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % dst_byte) + hlsl.append(' data.Store(%d, uint(scc));' % (dst_byte + 4)) + # Prove SCC drives a real branch on the device (not only a stored bool). + hlsl.append(' if (scc) {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_TAKEN)) + hlsl.append(' } else {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_NOT)) + hlsl.append(' }') + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_abs_i32' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + result_width * len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def check_dispatch(dxc, runner, adapter): + controls() + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + got = dispatch_abs(dxc, runner, adapter, DRAW, Path(tmp)) + for i, word in enumerate(DRAW): + abs_v = ref_abs(word) + scc_v = int(abs_v != 0) + branch = SCC_BRANCH_TAKEN if scc_v else SCC_BRANCH_NOT + base = 3 * i + label = 'dispatch s_abs_i32 %#010x' % word + check('%s result' % label, got[base] == abs_v, + 'got %#x want %#x' % (got[base], abs_v)) + check('%s SCC' % label, got[base + 1] == scc_v, + 'got %#x want %#x' % (got[base + 1], scc_v)) + check('%s SCC branch' % label, got[base + 2] == branch, + 'got %#x want %#x' % (got[base + 2], branch)) + # Explicit INT_MIN / zero controls called out in the review. + check('dispatch keeps INT_MIN as 0x80000000', got[0] == 0x80000000, hex(got[0])) + check('dispatch SCC of 0 is false (branch not-taken)', + got[3 * 2 + 1] == 0 and got[3 * 2 + 2] == SCC_BRANCH_NOT, + str((got[3 * 2 + 1], got[3 * 2 + 2]))) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) From a0b791b2f61be62f686d6abcb7e4b95dc01ac0b3 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 00:21:49 +0000 Subject: [PATCH 29/29] build: register s_abs_i32 WARP/hardware dispatch ctests Wire startup_gfx2hlsl_s_abs_dispatch_{warp,hardware} to the new UAV-readback mode so Windows CI and Sander can run the fixture. Co-authored-by: SimSalabimse --- CMakeLists.txt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8b777cecd..62027e206 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3215,9 +3215,16 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test. add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py") - # gfx2hlsl lowers s_abs_i32 (SOP1, #1723): CPU evaluation and refusals. + # gfx2hlsl lowers s_abs_i32 (SOP1, #1723): CPU evaluation, then a D3D12 UAV readback on + # WARP/hardware (same dispatch pattern as startup_gfx2hlsl_s_ff1 / pack_absdiff). add_test(NAME startup_gfx2hlsl_s_abs COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_abs_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_abs_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_abs_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_abs_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers s_bitset0_b32 and s_bitset1_b32 (SOP1, #2023 Item J): CPU evaluation and refusals. add_test(NAME startup_gfx2hlsl_s_bitset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset_check.py")