"""Unit tests for tools/pe_shader_containers.py, on synthetic containers (no game data, no PE needed). The containers are built by hand here: a u32 offset table at +32, and each chunk beginning with its fourcc and a u32 size. The scan's job is to accept exactly that shape and to reject the `DXBC` immediates and error strings that occur in ordinary code. """ import contextlib import io import json import os import random import struct import sys import tempfile import unittest from unittest import mock import zlib HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) sys.path.insert(0, os.path.join(ROOT, "tools")) import pe_shader_containers as psc def container(parts) -> bytes: """Assemble a DXBC container from (fourcc, payload) pairs.""" header = 32 + 4 * len(parts) offsets, body, end = [], b"", header for fourcc, payload in parts: offsets.append(header + len(body)) body += fourcc + struct.pack(" bytes: """An XDAT directory whose payload offsets are relative to the DXIL part, as the package has it.""" head = base + 12 + 12 * len(entries) directory, payload = b"", b"" for tag, value in entries: directory += struct.pack(" bytes: entries = [(0x12, bytes(16))] if xbch: entries.append((0x0D, b"XBCH" + bytes(20) + b"payload")) if bitcode: entries.append((0x07, b"BC\xc0\xde" + bytes(8))) prefix = ( b"e\x00\x05\x00" + struct.pack(" bytes: path = ( "X:\\americas\\src\\dev\\rage\\3rdparty\\Microsoft\\XboxBvhBuilder\\Build\\Release\\Output\\" f"XboxBvhBuilder\\{name}.pdb" ).encode() return b"\x00\x00" + struct.pack("= 4: at = rng.randrange(0, size - 3) data[at : at + 4] = b"DXBC" try: psc.parse_container(bytes(data), at) except psc.ContainerError: pass except Exception as e: # noqa: BLE001 - any other type is the failure being asserted self.fail(f"parse_container raised {type(e).__name__}: {e}") try: psc.inspect(bytes(data), "fuzz.dll") except Exception as e: # noqa: BLE001 - any exception is the failure being asserted self.fail(f"inspect raised {type(e).__name__}: {e}") class ReportPathTests(unittest.TestCase): """--json and --extract must not overwrite an input, each other, or a folder.""" def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.dir = self.tmp.name self.image = os.path.join(self.dir, "shader.dll") with open(self.image, "wb") as f: f.write(container([(b"SFI0", bytes(8))])) def run_main(self, argv): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): try: code = psc.main(argv) except SystemExit as e: return e.code, out.getvalue(), err.getvalue() return code, out.getvalue(), err.getvalue() def test_json_must_not_overwrite_an_image(self): with open(self.image, "rb") as f: before = f.read() code, _, err = self.run_main([self.image, "--json", self.image]) self.assertEqual(code, 2) self.assertIn("would overwrite the input image", err) with open(self.image, "rb") as f: self.assertEqual(f.read(), before) def test_json_creates_a_missing_folder(self): out = os.path.join(self.dir, "reports", "containers.json") code, _, err = self.run_main([self.image, "--json", out]) self.assertEqual(code, 0, err) with open(out, encoding="utf-8") as f: self.assertIsInstance(json.load(f), list) def test_json_refuses_a_folder(self): folder = os.path.join(self.dir, "folder") os.makedirs(folder) code, _, err = self.run_main([self.image, "--json", folder]) self.assertEqual(code, 2) self.assertIn("is a folder, not a file", err) def test_extract_refuses_an_existing_file(self): blocker = os.path.join(self.dir, "blocked") with open(blocker, "wb") as f: f.write(b"keep me") code, _, err = self.run_main([self.image, "--extract", blocker]) self.assertEqual(code, 2) self.assertIn("is not a folder", err) with open(blocker, "rb") as f: self.assertEqual(f.read(), b"keep me") def test_extract_index_must_not_overwrite_an_image(self): with open(self.image, "rb") as f: before = f.read() index = os.path.join(self.dir, "index.json") with open(index, "wb") as f: f.write(before) code, stdout, err = self.run_main([self.image, index, "--extract", self.dir]) self.assertEqual(code, 2) self.assertIn("would overwrite the input image", err) self.assertEqual(stdout, "") self.assertCountEqual(os.listdir(self.dir), ["shader.dll", "index.json"]) with open(index, "rb") as f: self.assertEqual(f.read(), before) def test_json_must_not_overwrite_the_extract_index(self): extract = os.path.join(self.dir, "out") index = os.path.join(extract, "index.json") code, _, err = self.run_main([self.image, "--extract", extract, "--json", index]) self.assertEqual(code, 2) self.assertIn("would overwrite the extract index", err) self.assertFalse(os.path.exists(extract)) def test_a_failed_json_write_is_one_line(self): blocker = os.path.join(self.dir, "not_a_folder") with open(blocker, "wb") as f: f.write(b"keep me") code, _, err = self.run_main([self.image, "--json", os.path.join(blocker, "containers.json")]) self.assertEqual(code, 2) self.assertIn("ERROR: cannot write", err) self.assertNotIn("Traceback", err) with open(blocker, "rb") as f: self.assertEqual(f.read(), b"keep me") def test_extract_multi_image_sequential_stems(self): blob1 = container([(b"DXIL", dxil_payload("cs", xbch=True, bitcode=False))]) blob2 = container([(b"DXIL", dxil_payload("cs", xbch=True, bitcode=False))]) with tempfile.TemporaryDirectory() as tmp: img1 = os.path.join(tmp, "img1.dll") img2 = os.path.join(tmp, "img2.dll") out = os.path.join(tmp, "out") with open(img1, "wb") as f: f.write(b"MZ" + blob1) with open(img2, "wb") as f: f.write(b"MZ" + blob2) code, stdout, err = self.run_main([img1, img2, "--extract", out]) self.assertEqual(code, 0) self.assertEqual(err, " these are game data: do not commit them\n") with open(os.path.join(out, "index.json"), encoding="utf-8") as f: index = json.load(f) self.assertEqual( index, [ {"name": "container_00", "file": "container_00.dxbc", "stage": "cs"}, {"name": "container_01", "file": "container_01.dxbc", "stage": "cs"}, ], ) self.assertTrue(os.path.exists(os.path.join(out, "container_00.dxbc"))) self.assertTrue(os.path.exists(os.path.join(out, "container_01.dxbc"))) def psv0(stage_code: int) -> bytes: """Build a minimal PSV0 chunk payload whose ShaderStage byte is `stage_code`.""" return struct.pack("