okami.mom/strata

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

Niko1221packaging: bundle libatomic.so.1 in the Linux AMD packages; check imports against the base system1a5c6dd19

main
14.3 KiB283 linesraw
1#!/usr/bin/env python3
2"""What an engine file needs from the machine it runs on: PE (Windows), ELF (Linux) and Mach-O (macOS) import lists, read
3with no tools and no third-party packages, and the rule "everything imported is bundled or belongs to the OS or the GPU driver".
4
5Why: on 2026-10-17 a tester's clean Windows 11 PC failed to start the engine with 0xC0000135 (a DLL was not found): the
6package held strata.exe and strata_kq.dll but not cublas64_13.dll / cublasLt64_13.dll, which strata.exe imports. Our own
7clean-profile test passed only because the build PC has the CUDA Toolkit on PATH. The packager now refuses a package whose imports
8are not covered, and `--check-deps` / the test suite run the same rule on any finished package.
9
10    python packaging/binary_deps.py <package folder>          # exit 0 when every import is bundled or system, 1 with the list
11
12Library names are compared case-insensitively on Windows and by soname elsewhere.
13"""
14
15from __future__ import annotations
16
17import fnmatch
18import struct
19import sys
20from pathlib import Path
21
22# ---- Windows ---------------------------------------------------------------------------------------------------------------
23# Libraries Windows itself ships (a clean Windows 10/11 has them) or the GPU driver installs in System32. Anything else an
24# engine file imports (the Visual C++ runtime, CUDA, HIP, SYCL/Level Zero loaders, OpenMP...) must travel in the package.
25WINDOWS_OS = (
26    "kernel32.dll", "kernelbase.dll", "user32.dll", "gdi32.dll", "advapi32.dll", "shell32.dll", "ole32.dll", "oleaut32.dll",
27    "ws2_32.dll", "wsock32.dll", "mswsock.dll", "iphlpapi.dll", "bcrypt.dll", "crypt32.dll", "secur32.dll", "sechost.dll",
28    "ntdll.dll", "msvcrt.dll", "ucrtbase.dll", "rpcrt4.dll", "shlwapi.dll", "setupapi.dll", "cfgmgr32.dll", "version.dll",
29    "winmm.dll", "imm32.dll", "comctl32.dll", "comdlg32.dll", "dbghelp.dll", "psapi.dll", "pdh.dll", "powrprof.dll",
30    "userenv.dll", "netapi32.dll", "wininet.dll", "winhttp.dll", "dxgi.dll", "d3d11.dll", "d3d12.dll", "dwmapi.dll",
31    "dxcore.dll", "wtsapi32.dll", "ncrypt.dll", "normaliz.dll", "api-ms-win-*.dll", "ext-ms-win-*.dll", "hid.dll",
32    "opengl32.dll", "glu32.dll", "wldap32.dll", "authz.dll", "msi.dll", "propsys.dll", "uxtheme.dll", "dnsapi.dll",
33)
34# Installed by the GPU driver into System32 (never redistributable by us): the CUDA driver API, the NVIDIA management library,
35# and the AMD / Intel user-mode driver pieces the driver package owns.
36WINDOWS_DRIVER = (
37    "nvcuda.dll", "nvml.dll", "nvapi64.dll", "nvapi.dll", "nvcuvid.dll", "nvEncodeAPI64.dll", "nvfatbinaryloader.dll",
38    "amdxx64.dll", "amdhip64_*.dll", "amdhip64.dll", "atiadlxx.dll", "atiadlxy.dll", "amdadlx64.dll",
39    "igdrcl64.dll", "ze_intel_gpu64.dll", "ze_loader.dll", "OpenCL.dll", "vulkan-1.dll",
40)
41
42# ---- Linux -----------------------------------------------------------------------------------------------------------------
43# The base system: what every Linux has, a container and a minimal install included (glibc, the C++ runtime). Names are sonames or glob
44# patterns. Anything else an engine file needs travels in the package. Until 0.2.14 this list also held libgomp, libatomic, libz, libnuma,
45# libdrm, libelf, libtinfo, libcrypt, libffi, libpci, libudev, libX11 and libxcb as "every distribution has these": the AMD packages then
46# shipped without libatomic.so.1 (librocm_sysdeps_numa.so.1 needs it) and a container without the libatomic1 package could not start the
47# engine (boxia, 2026-11-15). Every Linux engine package of 0.2.14 needs nothing else outside this list (archive_uncovered on the release files).
48LINUX_OS = (
49    "linux-vdso.so.1", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1", "libc.so.6", "libm.so.6", "libdl.so.2", "libpthread.so.0",
50    "librt.so.1", "libutil.so.1", "libresolv.so.2", "libnss_*.so.*", "libgcc_s.so.1", "libstdc++.so.6",
51)
52# From the GPU driver package: never bundled.
53LINUX_DRIVER = (
54    "libcuda.so.1", "libcuda.so", "libnvidia-*.so*", "libnvcuvid.so*", "libze_intel_gpu.so*", "libze_loader.so*",
55    "libOpenCL.so*", "libvulkan.so*", "libGLX*.so*", "libEGL*.so*", "libamdgpu*.so*", "libhsa-runtime64.so*",
56    "libdrm_amdgpu.so*", "libigdrcl.so*", "libnvidia-ml.so*",
57)
58
59# ---- macOS -----------------------------------------------------------------------------------------------------------------
60MAC_OS_PREFIXES = ("/usr/lib/", "/System/Library/")
61
62
63def _match(name: str, patterns: tuple[str, ...], fold: bool) -> bool:
64    n = name.lower() if fold else name
65    return any(fnmatch.fnmatchcase(n, (p.lower() if fold else p)) for p in patterns)
66
67
68# ---- readers ---------------------------------------------------------------------------------------------------------------
69def pe_imports(path: Path) -> list[str]:
70    """DLL names a PE file imports at load time (import table) plus delay-load imports (loaded at first call)."""
71    data = path.read_bytes()
72    if data[:2] != b"MZ":
73        raise ValueError(f"{path}: not a PE file")
74    pe = struct.unpack_from("<I", data, 0x3C)[0]
75    if data[pe:pe + 4] != b"PE\0\0":
76        raise ValueError(f"{path}: bad PE header")
77    nsec, = struct.unpack_from("<H", data, pe + 6)
78    opt_size, = struct.unpack_from("<H", data, pe + 20)
79    opt = pe + 24
80    magic, = struct.unpack_from("<H", data, opt)
81    dd = opt + (112 if magic == 0x20B else 96)
82    sections = []
83    sec = opt + opt_size
84    for i in range(nsec):
85        vsize, va, rsize, raw = struct.unpack_from("<IIII", data, sec + i * 40 + 8)
86        sections.append((va, max(vsize, rsize), raw))
87
88    def off(rva: int) -> int:
89        for va, size, raw in sections:
90            if va <= rva < va + size:
91                return raw + rva - va
92        raise ValueError(f"{path}: RVA {rva:#x} is outside every section")
93
94    def cstr(o: int) -> str:
95        end = data.index(b"\0", o)
96        return data[o:end].decode("ascii", "replace")
97
98    names: list[str] = []
99    imp_rva, imp_size = struct.unpack_from("<II", data, dd + 8)
100    if imp_rva and imp_size:
101        o = off(imp_rva)
102        while True:
103            _, _, _, name_rva, _ = struct.unpack_from("<IIIII", data, o)
104            if not name_rva:
105                break
106            names.append(cstr(off(name_rva)))
107            o += 20
108    delay_rva, delay_size = struct.unpack_from("<II", data, dd + 13 * 8)
109    if delay_rva and delay_size:
110        o = off(delay_rva)
111        while True:
112            attrs, name_rva = struct.unpack_from("<II", data, o)
113            if not name_rva:
114                break
115            names.append(cstr(off(name_rva)))
116            o += 32
117    return names
118
119
120def elf_needed(path: Path) -> list[str]:
121    """DT_NEEDED sonames of an ELF file (what ldd lists); libraries opened with dlopen are not visible here."""
122    return elf_needed_bytes(path.read_bytes(), str(path))
123
124
125def elf_needed_bytes(data: bytes, where: str = "the file") -> list[str]:
126    """elf_needed() for the bytes of an ELF file (a member of a package archive that is never unpacked)."""
127    if data[:4] != b"\x7fELF":
128        raise ValueError(f"{where}: not an ELF file")
129    is64 = data[4] == 2
130    le = "<" if data[5] == 1 else ">"
131    if is64:
132        shoff, = struct.unpack_from(le + "Q", data, 0x28)
133        shentsize, shnum = struct.unpack_from(le + "HH", data, 0x3A)
134    else:
135        shoff, = struct.unpack_from(le + "I", data, 0x20)
136        shentsize, shnum = struct.unpack_from(le + "HH", data, 0x2E)
137    out: list[str] = []
138    for i in range(shnum):
139        base = shoff + i * shentsize
140        if is64:
141            stype, = struct.unpack_from(le + "I", data, base + 4)
142            offset, size, link = struct.unpack_from(le + "QQI", data, base + 0x18)
143        else:
144            stype, = struct.unpack_from(le + "I", data, base + 4)
145            offset, size, link = struct.unpack_from(le + "III", data, base + 0x10)
146        if stype != 6:      # SHT_DYNAMIC
147            continue
148        sbase = shoff + link * shentsize
149        stroff = struct.unpack_from(le + ("Q" if is64 else "I"), data, sbase + (0x18 if is64 else 0x10))[0]
150        step = 16 if is64 else 8
151        for o in range(offset, offset + size, step):
152            tag, val = struct.unpack_from(le + ("qQ" if is64 else "iI"), data, o)
153            if tag == 0:
154                break
155            if tag == 1:
156                s = stroff + val
157                out.append(data[s:data.index(b"\0", s)].decode("ascii", "replace"))
158    return out
159
160
161def macho_dylibs(path: Path) -> list[str]:
162    """Install names a Mach-O file loads (LC_LOAD_DYLIB, weak, reexport). A fat file reads its first slice."""
163    data = path.read_bytes()
164    magic = struct.unpack_from(">I", data, 0)[0]
165    base = 0
166    if magic in (0xCAFEBABE, 0xCAFEBABF):
167        base = struct.unpack_from(">I", data, 16)[0] if magic == 0xCAFEBABE else struct.unpack_from(">Q", data, 24)[0]
168        magic = struct.unpack_from(">I", data, base)[0]
169    if struct.unpack_from("<I", data, base)[0] not in (0xFEEDFACF, 0xFEEDFACE):
170        raise ValueError(f"{path}: not a Mach-O file")
171    is64 = struct.unpack_from("<I", data, base)[0] == 0xFEEDFACF
172    ncmds, = struct.unpack_from("<I", data, base + 16)
173    o = base + (32 if is64 else 28)
174    out = []
175    for _ in range(ncmds):
176        cmd, size = struct.unpack_from("<II", data, o)
177        if cmd in (0xC, 0x80000018, 0x8000001F):     # LOAD_DYLIB, LOAD_WEAK_DYLIB, REEXPORT_DYLIB
178            name_off, = struct.unpack_from("<I", data, o + 8)
179            s = o + name_off
180            out.append(data[s:data.index(b"\0", s)].decode("utf-8", "replace"))
181        o += size
182    return out
183
184
185def imports(path: Path) -> tuple[str, list[str]]:
186    """(kind, names) for a binary, or ("", []) when it is not an executable format this module reads."""
187    with path.open("rb") as f:
188        head = f.read(4)
189    if head[:2] == b"MZ":
190        return "pe", pe_imports(path)
191    if head == b"\x7fELF":
192        return "elf", elf_needed(path)
193    if head in (b"\xcf\xfa\xed\xfe", b"\xce\xfa\xed\xfe", b"\xca\xfe\xba\xbe", b"\xbe\xba\xfe\xca"):
194        return "macho", macho_dylibs(path)
195    return "", []
196
197
198# ---- the rule --------------------------------------------------------------------------------------------------------------
199def uncovered(folder: Path, files: list[str] | None = None) -> list[tuple[str, str]]:
200    """(file, imported library) pairs that are neither in the package nor the OS's nor the GPU driver's. Empty = a clean PC runs it."""
201    folder = Path(folder)
202    rels = files if files is not None else [p.relative_to(folder).as_posix() for p in sorted(folder.rglob("*")) if p.is_file() and not p.is_symlink()]
203    # Windows loads a DLL from the program's own folder, System32 and PATH; a DLL in a sub-folder counts only when BUILD.json lists
204    # that folder in "lib_dirs" (Control and the app put those folders on PATH when they start the engine). Found 2026-10-18: the
205    # RX 9000 package kept rocblas.dll under rocm/bin, which only Control's PATH finds, and a plain start died with 0xC0000135.
206    lib_dirs = {""}
207    if any(r == "BUILD.json" for r in rels):
208        try:
209            import json
210            lib_dirs |= {str(d).strip("/\\").replace("\\", "/") for d in json.loads((folder / "BUILD.json").read_text(encoding="utf-8")).get("lib_dirs", [])}
211        except (OSError, ValueError):
212            pass
213    bundled_win = {Path(r).name.lower() for r in rels if ("" if Path(r).parent.as_posix() == "." else Path(r).parent.as_posix()) in lib_dirs}
214    bundled = {Path(r).name for r in rels}
215    problems: list[tuple[str, str]] = []
216    for rel in rels:
217        p = folder / rel
218        if p.suffix.lower() in (".json", ".txt", ".md", ".cu", ".h", ".py", ".yaml", ".yml", ".metallib", ".bin"):
219            continue
220        try:
221            kind, names = imports(p)
222        except (ValueError, OSError, struct.error):
223            continue
224        for name in names:
225            if kind == "pe":
226                if name.lower() in bundled_win or _match(name, WINDOWS_OS, True) or _match(name, WINDOWS_DRIVER, True):
227                    continue
228            elif kind == "elf":
229                if name in bundled or _match(name, LINUX_OS, False) or _match(name, LINUX_DRIVER, False):
230                    continue
231            else:
232                base = name.rsplit("/", 1)[-1]
233                if name.startswith(MAC_OS_PREFIXES) or base in bundled:
234                    continue
235            problems.append((rel, name))
236    return problems
237
238
239def archive_uncovered(archive: Path, base: tuple[str, ...] | None = None) -> list[tuple[str, str]]:
240    """The Linux rule of `uncovered` for a finished package archive (.tar.gz), read member by member and never unpacked: (file, imported
241    library) pairs whose library is neither a file in the archive nor on ``base`` (default LINUX_OS) nor a GPU driver library. A symlink in the
242    archive does not count as bundled: the package manifest and the install never keep symlinks (package_engine.py, engine_component.verify)."""
243    import tarfile
244    base = LINUX_OS if base is None else base
245    needs: list[tuple[str, str]] = []
246    bundled: set[str] = set()
247    with tarfile.open(archive, "r:*") as tar:
248        for member in tar:
249            if not member.isfile():
250                continue
251            bundled.add(member.name.rsplit("/", 1)[-1])
252            stream = tar.extractfile(member)
253            if stream is None or stream.read(4) != b"\x7fELF":
254                continue
255            data = b"\x7fELF" + stream.read()
256            try:
257                needs += [(member.name, n) for n in elf_needed_bytes(data, member.name)]
258            except (ValueError, struct.error):
259                continue
260    return [(rel, name) for rel, name in needs if name not in bundled and not _match(name, base, False) and not _match(name, LINUX_DRIVER, False)]
261
262
263def main(argv: list[str]) -> int:
264    if len(argv) != 2:
265        print(__doc__)
266        return 2
267    if argv[1].endswith((".tar.gz", ".tgz", ".tar")) and Path(argv[1]).is_file():
268        bad = archive_uncovered(Path(argv[1]))
269        for rel, name in bad:
270            print(f"{rel}: needs {name}, which is not in the package and not an OS or driver library")
271        if not bad:
272            print(f"{argv[1]}: every imported library is bundled or belongs to the OS / GPU driver")
273        return 1 if bad else 0
274    bad = uncovered(Path(argv[1]))
275    for rel, name in bad:
276        print(f"{rel}: needs {name}, which is not in the package and not an OS or driver library")
277    if not bad:
278        print(f"{argv[1]}: every imported library is bundled or belongs to the OS / GPU driver")
279    return 1 if bad else 0
280
281
282if __name__ == "__main__":
283    raise SystemExit(main(sys.argv))