okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-hf-misc' into f-14028aeefca2d

main
7.3 KiB155 linesraw
1"""#461: the DLLs the Windows HIP runtime needs beside strata.exe, from the PE import tables.
2
3    python tools/test_dll_closure.py          (the real-zip test skips when the 0.1.40.2 HIP zip is not here)
4
5Covers tools/hip/dll_closure.py and setup.hip_runtime_beside_exe on a fake engine folder.
6"""
7import os
8import struct
9import sys
10import tempfile
11import unittest
12import zipfile
13from pathlib import Path
14from unittest import mock
15
16ROOT = Path(__file__).resolve().parent.parent
17sys.path.insert(0, str(ROOT / "tools" / "hip"))
18sys.path.insert(0, str(ROOT))
19
20import dll_closure as dc  # noqa: E402
21import setup  # noqa: E402
22
23
24def fake_pe(imports, delay=()):
25    """A minimal PE32+ image whose import table (and delay-import table) names `imports` (`delay`)."""
26    text = bytearray()
27    va = 0x1000
28
29    def add_str(s):
30        off = len(text)
31        text.extend(s.encode() + b"\0")
32        return va + off
33
34    names = [add_str(n) for n in imports]
35    dnames = [add_str(n) for n in delay]
36    while len(text) % 8:
37        text.append(0)
38    imp_off = len(text)
39    for rva in names:
40        text.extend(struct.pack("<IIIII", 0, 0, 0, rva, 0))
41    text.extend(b"\0" * 20)
42    dly_off = len(text)
43    for rva in dnames:
44        text.extend(struct.pack("<IIIIIIII", 1, rva, 0, 0, 0, 0, 0, 0))
45    text.extend(b"\0" * 32)
46    opt_size = 112 + 16 * 8
47    pe = 0x80
48    hdr = bytearray(0x200)
49    hdr[0:2] = b"MZ"
50    struct.pack_into("<I", hdr, 0x3C, pe)
51    hdr[pe:pe + 4] = b"PE\0\0"
52    struct.pack_into("<HHIIIHH", hdr, pe + 4, 0x8664, 1, 0, 0, 0, opt_size, 0x2022)
53    opt = pe + 24
54    struct.pack_into("<H", hdr, opt, 0x20B)
55    dd = opt + 112
56    struct.pack_into("<II", hdr, dd + 8 * 1, va + imp_off, 20 * (len(names) + 1))
57    struct.pack_into("<II", hdr, dd + 8 * 13, va + dly_off, 32 * (len(dnames) + 1))
58    sec = opt + opt_size
59    hdr[sec:sec + 8] = b".idata\0\0"
60    struct.pack_into("<IIII", hdr, sec + 8, len(text), va, len(text), 0x200)
61    return bytes(hdr) + bytes(text)
62
63
64class Closure(unittest.TestCase):
65    def test_reads_imports_and_delay_imports(self):
66        with tempfile.TemporaryDirectory() as d:
67            f = Path(d) / "a.dll"
68            f.write_bytes(fake_pe(["KERNEL32.dll", "b.dll"], delay=["c.dll"]))
69            self.assertEqual(dc.pe_imports(f), ["KERNEL32.dll", "b.dll", "c.dll"])
70
71    def test_not_a_pe_is_a_leaf(self):
72        with tempfile.TemporaryDirectory() as d:
73            f = Path(d) / "a.dll"
74            f.write_bytes(b"hip-3686")
75            self.assertEqual(dc.pe_imports(f), [])
76            self.assertEqual(dc.pe_imports(Path(d) / "missing.dll"), [])
77
78    def test_follows_only_what_is_shipped(self):
79        with tempfile.TemporaryDirectory() as d:
80            d = Path(d)
81            (d / "AmdHip64_7.dll").write_bytes(fake_pe(["KERNEL32.dll", "ROCM_KPACK.dll", "SETUPAPI.dll"]))
82            (d / "rocm_kpack.dll").write_bytes(fake_pe(["MSVCP140.dll", "VCRUNTIME140.dll", "kernel32.dll"]))
83            (d / "msvcp140.dll").write_bytes(fake_pe(["VCRUNTIME140.dll", "api-ms-win-crt-heap-l1-1-0.dll"]))
84            (d / "vcruntime140.dll").write_bytes(fake_pe(["KERNEL32.dll"]))
85            (d / "amd_comgr.dll").write_bytes(fake_pe(["msvcp140.dll"]))
86            (d / "hipblas.dll").write_bytes(fake_pe(["amdhip64_7.dll", "rocblas.dll"]))     # not a root: left out
87            got = dc.dll_closure(d, ["AmdHip64_7.dll", "amd_comgr.dll", "not_there.dll"])
88            self.assertEqual(sorted(x.lower() for x in got),
89                             ["amd_comgr.dll", "amdhip64_7.dll", "msvcp140.dll", "rocm_kpack.dll", "vcruntime140.dll"])
90            self.assertEqual(got[:2], ["AmdHip64_7.dll", "amd_comgr.dll"])               # roots first, as spelled
91
92    def test_cycle_terminates(self):
93        with tempfile.TemporaryDirectory() as d:
94            d = Path(d)
95            (d / "a.dll").write_bytes(fake_pe(["b.dll"]))
96            (d / "b.dll").write_bytes(fake_pe(["a.dll"]))
97            self.assertEqual(dc.dll_closure(d, ["a.dll"]), ["a.dll", "b.dll"])
98
99    ZIP = ROOT.parent / "release" / "z04002" / "strata-windows-x64-hip.zip"
100
101    @unittest.skipUnless(ZIP.exists(), "the 0.1.40.2 HIP zip is not here")
102    def test_real_zip(self):
103        """The reporter's finding: amdhip64_7.dll needs rocm_kpack.dll and the MSVC runtime, which the 0.1.40.2 setup
104        did not put beside strata.exe."""
105        with tempfile.TemporaryDirectory() as d, zipfile.ZipFile(self.ZIP) as z:
106            for n in z.namelist():
107                if n.startswith("rocm/bin/") and n.endswith(".dll"):
108                    z.extract(n, d)
109            got = dc.dll_closure(Path(d) / "rocm" / "bin", ["amdhip64_7.dll", "amd_comgr.dll"])
110            self.assertEqual(sorted(got), ["amd_comgr.dll", "amdhip64_7.dll", "msvcp140.dll", "rocm_kpack.dll",
111                                           "vcruntime140.dll", "vcruntime140_1.dll"])
112            self.assertNotIn("hipblas.dll", got)            # strata.exe loads that one from rocm/bin by PATH
113
114
115class SetupCopy(unittest.TestCase):
116    def test_copies_the_closure_not_the_rest(self):
117        import json
118        with tempfile.TemporaryDirectory() as d:
119            eng = Path(d)
120            rb = eng / "rocm" / "bin"
121            rb.mkdir(parents=True)
122            (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "lib_dirs": ["rocm/bin"]}))
123            (rb / "amdhip64_7.dll").write_bytes(fake_pe(["KERNEL32.dll", "rocm_kpack.dll"]))
124            (rb / "rocm_kpack.dll").write_bytes(fake_pe(["MSVCP140.dll", "VCRUNTIME140.dll", "VCRUNTIME140_1.dll"]))
125            for n in ("msvcp140.dll", "vcruntime140.dll", "vcruntime140_1.dll"):
126                (rb / n).write_bytes(fake_pe(["KERNEL32.dll"]))
127            (rb / "amd_comgr.dll").write_bytes(fake_pe(["msvcp140.dll"]))
128            (rb / "rocblas.dll").write_bytes(fake_pe(["amdhip64_7.dll"]))
129            (rb / "hipblas.dll").write_bytes(fake_pe(["rocblas.dll"]))
130            # a 0.1.40.2 install: the two runtime DLLs beside the exe, and nothing else
131            (eng / "amdhip64_7.dll").write_bytes((rb / "amdhip64_7.dll").read_bytes())
132            with mock.patch.object(setup, "warn", lambda *a: None):
133                setup.hip_runtime_beside_exe(eng)
134            beside = sorted(p.name for p in eng.glob("*.dll"))
135            self.assertEqual(beside, ["amd_comgr.dll", "amdhip64_7.dll", "msvcp140.dll", "rocm_kpack.dll",
136                                      "vcruntime140.dll", "vcruntime140_1.dll"])
137            self.assertFalse((eng / "rocblas.dll").exists())
138            self.assertFalse((eng / "hipblas.dll").exists())
139            before = {p.name: p.stat().st_mtime_ns for p in eng.glob("*.dll")}
140            with mock.patch.object(setup, "warn", lambda *a: None):
141                setup.hip_runtime_beside_exe(eng)           # a second run changes nothing
142            self.assertEqual(before, {p.name: p.stat().st_mtime_ns for p in eng.glob("*.dll")})
143
144    def test_unreadable_helper_falls_back_to_the_runtime_pair(self):
145        with tempfile.TemporaryDirectory() as d:
146            d = Path(d)
147            (d / "amdhip64_7.dll").write_bytes(b"x")
148            (d / "amd_comgr.dll").write_bytes(b"y")
149            (d / "rocm_kpack.dll").write_bytes(b"z")
150            with mock.patch.object(setup, "ROOT", d):        # no tools/hip/dll_closure.py under this root
151                self.assertEqual(setup.hip_runtime_closure(d), ["amd_comgr.dll", "amdhip64_7.dll"])
152
153
154if __name__ == "__main__":
155    unittest.main()