okami.mom/strata

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

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

main
4.6 KiB117 linesraw
1"""tools/hip/dll_closure.py - which DLLs a DLL needs, read from the PE import tables (no pefile, no objdump).
2
3    python tools/hip/dll_closure.py DIR amdhip64_7.dll amd_comgr.dll      # prints the closure inside DIR
4
5Why: the Windows HIP engine puts amdhip64_7.dll and amd_comgr.dll next to strata.exe so that Windows binds THEM and not
6an AMD driver's copy in System32 (#468, #461).  But amdhip64_7.dll itself imports rocm_kpack.dll, which imports the
7MSVC runtime; with only the two DLLs beside the exe the full-path load fails (error 126, ERROR_MOD_NOT_FOUND), Windows
8falls back to System32's copy, and the first big prompt dies with hipErrorInvalidDeviceFunction (#461, maraa081).  So
9what goes beside the exe is the DLLs' whole dependency closure, computed here from the files actually shipped rather
10than from a list of names that goes stale with the next ROCm.
11
12A name is followed only when the DLL exists in `search_dir` (the bundle's rocm/bin).  Everything else - kernel32,
13user32, setupapi, the api-ms-win-* forwarders - is a Windows system DLL and is left alone.
14"""
15from __future__ import annotations
16
17import struct
18import sys
19from pathlib import Path
20
21
22def pe_imports(path) -> list[str]:
23    """The DLL names in a PE file's import table and delay-import table, in file order.  [] for a file that is not a
24    PE image (or is truncated): the caller treats it as a leaf."""
25    try:
26        data = Path(path).read_bytes()
27    except OSError:
28        return []
29    try:
30        if data[:2] != b"MZ":
31            return []
32        pe = struct.unpack_from("<I", data, 0x3C)[0]
33        if data[pe:pe + 4] != b"PE\0\0":
34            return []
35        nsec, = struct.unpack_from("<H", data, pe + 6)
36        opt_size, = struct.unpack_from("<H", data, pe + 20)
37        opt = pe + 24
38        magic, = struct.unpack_from("<H", data, opt)
39        dd = opt + (112 if magic == 0x20B else 96)          # PE32+ : 112, PE32 : 96
40        secs = []
41        sec0 = opt + opt_size
42        for i in range(nsec):
43            o = sec0 + 40 * i
44            vsize, va, rsize, raw = struct.unpack_from("<IIII", data, o + 8)
45            secs.append((va, max(vsize, rsize), raw))
46
47        def off(rva):
48            for va, size, raw in secs:
49                if va <= rva < va + size:
50                    return rva - va + raw
51            return None
52
53        def cstr(o):
54            e = data.index(b"\0", o)
55            return data[o:e].decode("ascii", "replace")
56
57        names: list[str] = []
58        imp_rva, = struct.unpack_from("<I", data, dd + 8 * 1)                 # directory 1: imports
59        o = off(imp_rva) if imp_rva else None
60        while o is not None:
61            name_rva = struct.unpack_from("<I", data, o + 12)[0]
62            if name_rva == 0:
63                break
64            n = off(name_rva)
65            if n is not None:
66                names.append(cstr(n))
67            o += 20
68        dly_rva, = struct.unpack_from("<I", data, dd + 8 * 13)                # directory 13: delay imports
69        o = off(dly_rva) if dly_rva else None
70        while o is not None:
71            attrs, name_rva = struct.unpack_from("<II", data, o)
72            if name_rva == 0:
73                break
74            n = off(name_rva)                                                 # (RVA form, attrs bit 0)
75            if n is not None:
76                names.append(cstr(n))
77            o += 32
78        return names
79    except (struct.error, ValueError, IndexError):
80        return []
81
82
83def dll_closure(search_dir, roots, imports=pe_imports) -> list[str]:
84    """`roots` (file names inside `search_dir`) plus every DLL in `search_dir` they import, followed recursively.
85    The names are returned as spelled on disk, roots first, the rest in discovery order.  A root that is not in the
86    directory is skipped; an import that is not in the directory (a Windows system DLL) is not followed."""
87    d = Path(search_dir)
88    on_disk = {p.name.lower(): p.name for p in d.iterdir() if p.is_file() and p.suffix.lower() == ".dll"} \
89        if d.is_dir() else {}
90    out: list[str] = []
91    todo = [r for r in roots]
92    seen: set[str] = set()
93    while todo:
94        name = todo.pop(0)
95        low = name.lower()
96        if low in seen or low not in on_disk:
97            continue
98        seen.add(low)
99        real = on_disk[low]
100        out.append(real)
101        for dep in imports(d / real):
102            if dep.lower() not in seen:
103                todo.append(dep)
104    return out
105
106
107def main() -> int:
108    if len(sys.argv) < 3:
109        print(__doc__)
110        return 2
111    for n in dll_closure(sys.argv[1], sys.argv[2:]):
112        print(n)
113    return 0
114
115
116if __name__ == "__main__":
117    raise SystemExit(main())