Files
mandy/tools/image_fuzz.py
2026-11-22 07:08:03 -05:00

382 lines
17 KiB
Python

r"""Differential fuzzer for the translator's image path, starting with `image_load` (standard library only).
Each case is a hand-written RDNA2 pixel shader that reads one texel with `image_load` and exports it to
`mrt0`. It runs on the GPU through `runtime/test/vk_image_fuzz.cpp` against a synthetic texture of a chosen
format, and every RGBA32F pixel is compared with an independent CPU oracle that models the RDNA2 texel fetch
for that T# format. A texel fetch is a memory read: no filtering, no borders, no LOD selection.
What this covers today: 2D `image_load`, nonzero `dmask` values, `R8G8B8A8_UNORM`, `R16G16B16A16_SFLOAT`,
`R32G32B32A32_SFLOAT` and `R32_SFLOAT`, at sizes that divide the 64x64 draw (8/16/32/64), every texel read
at least once.
Integer coverage uses 8-bit UINT/SINT sampled images (the translator reads them through uint/sint aliases of the
sampled array) and converts loaded integers to exactly representable floats.
Not covered yet: wider integer formats, mips, 1D/2D-array/3D/cube, `image_sample`/`gather` with filters and borders, and texel
offsets with `VK_KHR_maintenance8`.
Usage:
python -I tools/image_fuzz.py [--programs N] [--seed S] [--build DIR] [--work DIR] [--show]
python -I tools/image_fuzz.py --self-test
Exit code: 0 when every case matches, 1 on a mismatch, 2 on a setup or harness error. Nothing here reads
game files.
"""
import argparse
import os
import random
import re
import signal
import struct
import subprocess
import sys
import tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS = os.path.join(ROOT, "tools")
SHADERS = os.path.join(ROOT, "runtime", "test", "shaders")
TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py")
sys.path.insert(0, TOOLS)
sys.path.insert(0, SHADERS)
import mc_command # noqa: E402
from compute_fixture import find_test_program # noqa: E402
HARNESS = "vk_image_fuzz"
DRAW = 64 # the harness draws a 64x64 full-screen triangle
# name -> (Vulkan format for the spec and the image, GFX10 FORMAT code for T# word 1, bytes per texel, model)
FORMATS = {
"R8G8B8A8_UNORM": ("R8G8B8A8_UNORM", 56, 4, "unorm8"),
"R16G16B16A16_SFLOAT": ("R16G16B16A16_SFLOAT", 71, 8, "half4"),
"R32G32B32A32_SFLOAT": ("R32G32B32A32_SFLOAT", 77, 16, "float4"),
"R32_SFLOAT": ("R32_SFLOAT", 22, 4, "float1"),
"R8G8B8A8_UINT": ("R8G8B8A8_UINT", 60, 4, "uint8"),
"R8G8B8A8_SINT": ("R8G8B8A8_SINT", 61, 4, "sint8"),
}
SIZES = (8, 16, 32, 64)
DMASKS = (0xf, *range(1, 0xf))
STDERR_TAIL = 20 # lines of the harness's output a failure prints
# Windows reports a crash as an NTSTATUS exit code (unsigned); the ones a driver crash tends to end with
NTSTATUS = {
0xC0000005: "access violation",
0xC000001D: "illegal instruction",
0xC0000094: "integer divide by zero",
0xC00000FD: "stack overflow",
0xC0000374: "heap corruption",
0xC0000409: "stack buffer overrun",
}
def assemble(asm: str, name: str, work: str) -> None:
"""Assemble with llvm-mc like runtime/test/shaders/build.py, into work/disasm/<name>.s."""
cmd = mc_command.mc_command() + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"]
r = mc_command.run(cmd, input=asm, capture_output=True, text=True)
if r.returncode or "error:" in r.stderr:
raise SystemExit(f"llvm-mc rejected {name}:\n{r.stderr}")
code = "".join(line for line in r.stdout.splitlines(keepends=True)
if not line.lstrip().startswith("."))
disasm = os.path.join(work, "disasm")
os.makedirs(disasm, exist_ok=True)
with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8") as f:
f.write(f"; {name} generated by tools/image_fuzz.py\n{code}")
with open(os.path.join(work, name + ".dxbc"), "wb") as f:
f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name
def translate(work: str) -> str:
"""Translate work/disasm into work/spirv and return that directory."""
spirv = os.path.join(work, "spirv")
r = subprocess.run([sys.executable, "-I", TRANSLATOR, os.path.join(work, "disasm"), "--out", spirv],
capture_output=True, text=True)
if r.returncode:
raise SystemExit(f"translator failed:\n{r.stdout}\n{r.stderr}")
return spirv
SENTINELS = (1.0, 2.0, 3.0, 4.0)
def masked_components(rgba, dmask):
"""Selected R/G/B/A components occupy consecutive VGPRs; remaining VGPRs keep their sentinels."""
selected = [rgba[c] for c in range(4) if dmask & (1 << c)]
return selected + list(SENTINELS[len(selected):])
def pixel_shader(width: int, height: int, dmask: int = 0xf, model: str = "") -> str:
"""image_load of a 2D texture at the texel under each pixel, exported to mrt0."""
count = dmask.bit_count()
dst = "v4" if count == 1 else f"v[4:{3 + count}]"
init = "".join(f"\tv_mov_b32_e32 v{reg}, {value}\n" for reg, value in enumerate(SENTINELS, 4))
convert = ""
if model in ("uint8", "sint8"):
kind = "u32" if model == "uint8" else "i32"
convert = "".join(f"\tv_cvt_f32_{kind}_e32 v{r}, v{r}\n" for r in range(4, 4 + count))
return (
"; image_load probe generated by tools/image_fuzz.py\n"
"\tv_interp_p1_f32_e32 v2, v0, attr0.x\n"
"\tv_interp_p2_f32_e32 v2, v1, attr0.x\n"
"\tv_interp_p1_f32_e32 v3, v0, attr0.y\n"
"\tv_interp_p2_f32_e32 v3, v1, attr0.y\n"
f"\tv_mul_f32_e32 v2, {float(width)}, v2\n"
f"\tv_mul_f32_e32 v3, {float(height)}, v3\n"
"\tv_cvt_u32_f32_e32 v2, v2\n"
"\tv_cvt_u32_f32_e32 v3, v3\n"
f"{init}"
f"\timage_load {dst}, v[2:3], s[8:15] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_2D\n"
"\ts_waitcnt vmcnt(0)\n"
f"{convert}"
"\texp mrt0 v4, v5, v6, v7 done vm\n"
"\ts_endpgm\n"
)
def make_texels(fmt_name: str, width: int, height: int, rng: random.Random):
"""Raw texel bytes and the T# words (the key; word 1 carries FORMAT for the translator)."""
vk_format, code, bpp, model = FORMATS[fmt_name]
# A fifth of the values are specials: a fetch is a memory read, so NaN/inf/+-0/denormal payloads must
# survive it unchanged (the comparison treats every NaN as equal to every NaN).
specials = [0.0, -0.0, float("inf"), float("-inf"), float("nan"), 1e-40, -1e-40]
raw = bytearray()
for _ in range(width * height):
if model in ("unorm8", "uint8", "sint8"):
raw += bytes([rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(256)])
elif model == "half4":
for _ in range(4):
value = rng.choice([struct.unpack("<e", struct.pack("<e", v))[0] for v in specials]
+ [rng.uniform(-64.0, 64.0)]) if rng.random() < 0.2 else rng.uniform(-64.0, 64.0)
raw += struct.pack("<e", value)
elif model == "float4":
for _ in range(4):
value = rng.choice(specials) if rng.random() < 0.2 else rng.uniform(-1e6, 1e6)
raw += struct.pack("<f", value)
else: # float1
value = rng.choice(specials) if rng.random() < 0.2 else rng.uniform(-1e6, 1e6)
raw += struct.pack("<f", value)
# A T# key: word 1 FORMAT [28:20] decides the numeric type, the rest only has to be unique and stable.
tsharp = [0x1000, code << 20, (width - 1) | ((height - 1) << 16), 0, 0, 0, 0, 0]
return bytes(raw), tsharp
def f32(value: float) -> float:
"""The float32 the GPU gets; the UNORM divide happens in float, not in Python's double."""
return struct.unpack("<f", struct.pack("<f", value))[0]
def oracle(fmt_name: str, texels: bytes, width: int, height: int) -> list:
"""Every texel as RGBA floats, the way an RDNA2 image_load of that format reads it."""
_, _, bpp, model = FORMATS[fmt_name]
texel = []
for i in range(width * height):
chunk = texels[i * bpp:(i + 1) * bpp]
if model == "unorm8":
texel.append([f32(chunk[c] / 255.0) for c in range(4)])
elif model in ("uint8", "sint8"):
texel.append(list(struct.unpack("<4B" if model == "uint8" else "<4b", chunk)))
elif model == "half4":
texel.append([struct.unpack_from("<e", chunk, 2 * c)[0] for c in range(4)])
elif model == "float4":
texel.append([struct.unpack_from("<f", chunk, 4 * c)[0] for c in range(4)])
else:
texel.append([struct.unpack_from("<f", chunk, 0)[0], 0.0, 0.0, 1.0])
return texel
def texel_of_pixel(x: int, y: int, width: int, height: int) -> tuple:
"""The texel the generated shader reads for pixel (x, y): floor(uv * size) with uv = (pixel + 0.5) / 64."""
return (x * width) // DRAW, (y * height) // DRAW
def read_rgba(path: str) -> list:
with open(path, "rb") as f:
data = f.read()
want = DRAW * DRAW * 16
if len(data) != want:
raise SystemExit(f"{path}: {len(data)} bytes, expected {want}")
return list(struct.unpack(f"<{DRAW * DRAW * 4}f", data))
def same_component(a: float, b: float) -> bool:
"""Bit equality of two f32 values, except that any NaN matches any NaN.
Ordinary float equality would hide a wrong binding that returns -0 where +0 is expected (and the reverse):
+0.0 == -0.0 is true in Python, but the 32-bit words differ and a texture fetch must preserve the sign.
"""
packed_a, packed_b = struct.pack("<f", a), struct.pack("<f", b)
if packed_a == packed_b:
return True
bits_a = struct.unpack("<I", packed_a)[0]
bits_b = struct.unpack("<I", packed_b)[0]
nan_a = (bits_a & 0x7F800000) == 0x7F800000 and bits_a & 0x007FFFFF
nan_b = (bits_b & 0x7F800000) == 0x7F800000 and bits_b & 0x007FFFFF
return bool(nan_a and nan_b)
def compare(fmt_name, texels, width, height, got, dmask=0xf) -> list:
expected = oracle(fmt_name, texels, width, height)
problems = []
for y in range(DRAW):
for x in range(DRAW):
tx, ty = texel_of_pixel(x, y, width, height)
want = masked_components(expected[ty * width + tx], dmask)
base = (y * DRAW + x) * 4
have = got[base:base + 4]
if all(same_component(have[c], want[c]) for c in range(4)):
continue
problems.append((x, y, want, have))
if len(problems) >= 6:
return problems
return problems
def exit_status(returncode: int) -> str:
"""How the harness ended, for a failure line: "exit 1", "killed by SIGSEGV", "exit 0xc0000005 (access violation)"."""
if returncode < 0: # POSIX: subprocess reports a fatal signal as its negative number
try:
name = signal.Signals(-returncode).name
except ValueError:
name = f"signal {-returncode}"
return f"killed by {name}"
status = returncode & 0xFFFFFFFF
if status >= 0xC0000000:
return f"exit 0x{status:08x}" + (f" ({NTSTATUS[status]})" if status in NTSTATUS else "")
return f"exit {returncode}"
def run_case(fmt_name, width, height, rng, work, build, keep, show, dmask=0xf) -> bool:
vk_format, _, _, model = FORMATS[fmt_name]
asm = pixel_shader(width, height, dmask, model)
assemble(asm, "ps_image_load", work)
if not os.path.exists(os.path.join(work, "disasm", "vs_ids.s")):
with open(os.path.join(SHADERS, "vs_ids.asm"), encoding="utf-8") as f:
assemble(f.read(), "vs_ids", work)
spirv = translate(work)
texels, tsharp = make_texels(fmt_name, width, height, rng)
texels_path = os.path.join(work, "texels.bin")
with open(texels_path, "wb") as f:
f.write(texels)
spec_path = os.path.join(work, "spec.txt")
with open(spec_path, "w", encoding="utf-8") as f:
f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n"
f"tsharp={','.join(hex(w) for w in tsharp)}\n")
out_path = os.path.join(work, "out.raw")
harness = os.path.join(build, HARNESS + (".exe" if os.name == "nt" else ""))
if not os.path.exists(harness):
raise SystemExit(f"{harness} not found: build the runtime first "
f"(cmake --build <build> --target {HARNESS})")
r = subprocess.run([harness, os.path.join(spirv, "vs_ids.spv"), os.path.join(spirv, "ps_image_load.spv"),
out_path, spec_path], capture_output=True, text=True)
if r.returncode == 77: # a device limit or missing feature, named on the harness's "unsupported:" line
why = next((ln for ln in f"{r.stdout}\n{r.stderr}".splitlines() if ln.startswith("unsupported:")),
"the device does not support the set")
print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: SKIP ({why})")
return None
if r.returncode != 0:
status = exit_status(r.returncode)
stream, lines = "stderr", (r.stderr or "").strip().splitlines()
if not lines:
stream, lines = "stdout", (r.stdout or "").strip().splitlines()
reason = f"{HARNESS} {status}" + (f": {lines[-1]}" if lines else ", no output")
print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: FAIL ({reason})")
if len(lines) > 1:
shown = lines[-STDERR_TAIL:]
print(f" {HARNESS} {stream}" + (f" (last {len(shown)} of {len(lines)} lines)"
if len(shown) < len(lines) else "") + ":")
for line in shown:
print(f" {line}")
return False
got = read_rgba(out_path)
problems = compare(fmt_name, texels, width, height, got, dmask)
if not problems:
if show:
print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: pass (every pixel matches)")
return True
print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: {len(problems)}+ mismatched pixels")
for x, y, want, have in problems:
print(f" pixel ({x}, {y}) texel ({texel_of_pixel(x, y, width, height)}): "
f"want {want} got {have}")
if keep:
print(f" case kept in {work} (spec.txt, ps_image_load.s, texels.bin, out.raw)")
return False
def self_test() -> int:
"""CPU-only: the oracle, the texel mapping and the generated shader without a GPU."""
rng = random.Random(7)
for name, (vk, code, bpp, model) in FORMATS.items():
width, height = 8, 8
texels, tsharp = make_texels(name, width, height, rng)
assert len(texels) == width * height * bpp, name
assert tsharp[1] == code << 20, name
values = oracle(name, texels, width, height)
assert len(values) == width * height, name
assert all(len(v) == 4 for v in values), name
assert texel_of_pixel(0, 0, 8, 8) == (0, 0)
assert texel_of_pixel(63, 63, 8, 8) == (7, 7)
assert texel_of_pixel(63, 63, 64, 64) == (63, 63)
asm = pixel_shader(16, 8)
assert "\timage_load" in asm and "16.0" in asm and "8.0" in asm
print(f"image_fuzz self-test: ok ({len(FORMATS)} formats, {DRAW}x{DRAW} draw)")
return 0
def main() -> int:
ap = argparse.ArgumentParser(description="Differential fuzzer for the translator's image_load path")
ap.add_argument("--programs", type=int, default=8)
ap.add_argument("--seed", type=int, default=1)
# runtime/build, as docs/shader_validation.md builds it and lds_fuzz/valu_fuzz default to; a Visual Studio build's
# RelWithDebInfo/Release subfolder is found below.
ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"))
ap.add_argument("--work")
ap.add_argument("--show", action="store_true")
ap.add_argument("--formats", default=",".join(FORMATS))
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
formats = [f.strip() for f in a.formats.split(",") if f.strip()]
unknown = [f for f in formats if f not in FORMATS]
if unknown:
print(f"unknown format(s): {', '.join(unknown)}; known: {', '.join(FORMATS)}", file=sys.stderr)
return 2
if a.programs < 1:
print("--programs must be at least 1", file=sys.stderr)
return 2
a.build = find_test_program(a.build, HARNESS) or a.build
rng = random.Random(a.seed)
work = a.work or tempfile.mkdtemp(prefix="image_fuzz_")
os.makedirs(work, exist_ok=True)
passed = failed = skipped = 0
for i in range(a.programs):
fmt = formats[i % len(formats)]
width = rng.choice(SIZES)
height = rng.choice(SIZES)
if a.show:
print(f"[{i + 1}/{a.programs}] {fmt} {width}x{height} (work {work})")
dmask = DMASKS[(i // len(formats)) % len(DMASKS)]
result = run_case(fmt, width, height, rng, work, a.build, False, a.show, dmask)
if result is None:
skipped += 1
elif result:
passed += 1
else:
failed += 1
print(f" work dir kept: {work}")
break
ran = passed + failed
summary = f"{passed}/{ran} programs that ran match"
if failed:
summary += f"; {failed} mismatched"
if skipped:
summary += f"; {skipped} skipped"
print(summary)
return 0 if not failed else 1
if __name__ == "__main__":
try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
sys.stdout.reconfigure(errors="replace")
except (AttributeError, ValueError, OSError):
pass
sys.exit(main())