From 37f7f03cd2a50d98f2be1bfaef09bc33d2f863dc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 18:59:45 +0200 Subject: [PATCH] Engine packages: bundle every imported non-system library, refuse a package a clean PC could not start, PE/ELF/Mach-O import scanner and tests --- packaging/binary_deps.py | 236 +++++++++++++++++++++++++++++ packaging/package_engine.py | 64 +++++++- tests/terminal/test_engine_deps.py | 124 +++++++++++++++ 3 files changed, 422 insertions(+), 2 deletions(-) create mode 100644 packaging/binary_deps.py create mode 100644 tests/terminal/test_engine_deps.py diff --git a/packaging/binary_deps.py b/packaging/binary_deps.py new file mode 100644 index 00000000..0c222732 --- /dev/null +++ b/packaging/binary_deps.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""What an engine file needs from the machine it runs on: PE (Windows), ELF (Linux) and Mach-O (macOS) import lists, read +with no tools and no third-party packages, and the rule "everything imported is bundled or belongs to the OS or the GPU driver". + +Why: on 2026-10-17 a tester's clean Windows 11 PC failed to start the engine with 0xC0000135 (a DLL was not found): the +package held strata.exe and strata_kq.dll but not cublas64_13.dll / cublasLt64_13.dll, which strata.exe imports. Our own +clean-profile test passed only because the build PC has the CUDA Toolkit on PATH. The packager now refuses a package whose imports +are not covered, and `--check-deps` / the test suite run the same rule on any finished package. + + python packaging/binary_deps.py # exit 0 when every import is bundled or system, 1 with the list + +Library names are compared case-insensitively on Windows and by soname elsewhere. +""" + +from __future__ import annotations + +import fnmatch +import struct +import sys +from pathlib import Path + +# ---- Windows --------------------------------------------------------------------------------------------------------------- +# Libraries Windows itself ships (a clean Windows 10/11 has them) or the GPU driver installs in System32. Anything else an +# engine file imports (the Visual C++ runtime, CUDA, HIP, SYCL/Level Zero loaders, OpenMP...) must travel in the package. +WINDOWS_OS = ( + "kernel32.dll", "kernelbase.dll", "user32.dll", "gdi32.dll", "advapi32.dll", "shell32.dll", "ole32.dll", "oleaut32.dll", + "ws2_32.dll", "wsock32.dll", "mswsock.dll", "iphlpapi.dll", "bcrypt.dll", "crypt32.dll", "secur32.dll", "sechost.dll", + "ntdll.dll", "msvcrt.dll", "ucrtbase.dll", "rpcrt4.dll", "shlwapi.dll", "setupapi.dll", "cfgmgr32.dll", "version.dll", + "winmm.dll", "imm32.dll", "comctl32.dll", "comdlg32.dll", "dbghelp.dll", "psapi.dll", "pdh.dll", "powrprof.dll", + "userenv.dll", "netapi32.dll", "wininet.dll", "winhttp.dll", "dxgi.dll", "d3d11.dll", "d3d12.dll", "dwmapi.dll", + "dxcore.dll", "wtsapi32.dll", "ncrypt.dll", "normaliz.dll", "api-ms-win-*.dll", "ext-ms-win-*.dll", "hid.dll", + "opengl32.dll", "glu32.dll", "wldap32.dll", "authz.dll", "msi.dll", "propsys.dll", "uxtheme.dll", "dnsapi.dll", +) +# Installed by the GPU driver into System32 (never redistributable by us): the CUDA driver API, the NVIDIA management library, +# and the AMD / Intel user-mode driver pieces the driver package owns. +WINDOWS_DRIVER = ( + "nvcuda.dll", "nvml.dll", "nvapi64.dll", "nvapi.dll", "nvcuvid.dll", "nvEncodeAPI64.dll", "nvfatbinaryloader.dll", + "amdxx64.dll", "amdhip64_*.dll", "amdhip64.dll", "atiadlxx.dll", "atiadlxy.dll", "amdadlx64.dll", + "igdrcl64.dll", "ze_intel_gpu64.dll", "ze_loader.dll", "OpenCL.dll", "vulkan-1.dll", +) + +# ---- Linux ----------------------------------------------------------------------------------------------------------------- +# Every distribution has these (glibc and the compiler runtime). Names are sonames or glob patterns. +LINUX_OS = ( + "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", + "librt.so.1", "libutil.so.1", "libresolv.so.2", "libnss_*.so.*", "libgcc_s.so.1", "libstdc++.so.6", "libgomp.so.1", + "libatomic.so.1", "libz.so.1", "libnuma.so.1", "libdrm.so.2", "libdrm_amdgpu.so.1", "libelf.so.1", "libtinfo.so.*", + "libcrypt.so.1", "libffi.so.*", "libpci.so.3", "libudev.so.1", "libX11.so.6", "libxcb.so.1", +) +# From the GPU driver package: never bundled. +LINUX_DRIVER = ( + "libcuda.so.1", "libcuda.so", "libnvidia-*.so*", "libnvcuvid.so*", "libze_intel_gpu.so*", "libze_loader.so*", + "libOpenCL.so*", "libvulkan.so*", "libGLX*.so*", "libEGL*.so*", "libamdgpu*.so*", "libhsa-runtime64.so*", + "libdrm_amdgpu.so*", "libigdrcl.so*", "libnvidia-ml.so*", +) + +# ---- macOS ----------------------------------------------------------------------------------------------------------------- +MAC_OS_PREFIXES = ("/usr/lib/", "/System/Library/") + + +def _match(name: str, patterns: tuple[str, ...], fold: bool) -> bool: + n = name.lower() if fold else name + return any(fnmatch.fnmatchcase(n, (p.lower() if fold else p)) for p in patterns) + + +# ---- readers --------------------------------------------------------------------------------------------------------------- +def pe_imports(path: Path) -> list[str]: + """DLL names a PE file imports at load time (import table) plus delay-load imports (loaded at first call).""" + data = path.read_bytes() + if data[:2] != b"MZ": + raise ValueError(f"{path}: not a PE file") + pe = struct.unpack_from(" int: + for va, size, raw in sections: + if va <= rva < va + size: + return raw + rva - va + raise ValueError(f"{path}: RVA {rva:#x} is outside every section") + + def cstr(o: int) -> str: + end = data.index(b"\0", o) + return data[o:end].decode("ascii", "replace") + + names: list[str] = [] + imp_rva, imp_size = struct.unpack_from(" list[str]: + """DT_NEEDED sonames of an ELF file (what ldd lists); libraries opened with dlopen are not visible here.""" + data = path.read_bytes() + if data[:4] != b"\x7fELF": + raise ValueError(f"{path}: not an ELF file") + is64 = data[4] == 2 + le = "<" if data[5] == 1 else ">" + if is64: + shoff, = struct.unpack_from(le + "Q", data, 0x28) + shentsize, shnum = struct.unpack_from(le + "HH", data, 0x3A) + else: + shoff, = struct.unpack_from(le + "I", data, 0x20) + shentsize, shnum = struct.unpack_from(le + "HH", data, 0x2E) + out: list[str] = [] + for i in range(shnum): + base = shoff + i * shentsize + if is64: + stype, = struct.unpack_from(le + "I", data, base + 4) + offset, size, link = struct.unpack_from(le + "QQI", data, base + 0x18) + else: + stype, = struct.unpack_from(le + "I", data, base + 4) + offset, size, link = struct.unpack_from(le + "III", data, base + 0x10) + if stype != 6: # SHT_DYNAMIC + continue + sbase = shoff + link * shentsize + stroff = struct.unpack_from(le + ("Q" if is64 else "I"), data, sbase + (0x18 if is64 else 0x10))[0] + step = 16 if is64 else 8 + for o in range(offset, offset + size, step): + tag, val = struct.unpack_from(le + ("qQ" if is64 else "iI"), data, o) + if tag == 0: + break + if tag == 1: + s = stroff + val + out.append(data[s:data.index(b"\0", s)].decode("ascii", "replace")) + return out + + +def macho_dylibs(path: Path) -> list[str]: + """Install names a Mach-O file loads (LC_LOAD_DYLIB, weak, reexport). A fat file reads its first slice.""" + data = path.read_bytes() + magic = struct.unpack_from(">I", data, 0)[0] + base = 0 + if magic in (0xCAFEBABE, 0xCAFEBABF): + base = struct.unpack_from(">I", data, 16)[0] if magic == 0xCAFEBABE else struct.unpack_from(">Q", data, 24)[0] + magic = struct.unpack_from(">I", data, base)[0] + if struct.unpack_from(" tuple[str, list[str]]: + """(kind, names) for a binary, or ("", []) when it is not an executable format this module reads.""" + with path.open("rb") as f: + head = f.read(4) + if head[:2] == b"MZ": + return "pe", pe_imports(path) + if head == b"\x7fELF": + return "elf", elf_needed(path) + if head in (b"\xcf\xfa\xed\xfe", b"\xce\xfa\xed\xfe", b"\xca\xfe\xba\xbe", b"\xbe\xba\xfe\xca"): + return "macho", macho_dylibs(path) + return "", [] + + +# ---- the rule -------------------------------------------------------------------------------------------------------------- +def uncovered(folder: Path, files: list[str] | None = None) -> list[tuple[str, str]]: + """(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.""" + folder = Path(folder) + 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()] + bundled_win = {Path(r).name.lower() for r in rels} + bundled = {Path(r).name for r in rels} + problems: list[tuple[str, str]] = [] + for rel in rels: + p = folder / rel + if p.suffix.lower() in (".json", ".txt", ".md", ".cu", ".h", ".py", ".yaml", ".yml", ".metallib", ".bin"): + continue + try: + kind, names = imports(p) + except (ValueError, OSError, struct.error): + continue + for name in names: + if kind == "pe": + if name.lower() in bundled_win or _match(name, WINDOWS_OS, True) or _match(name, WINDOWS_DRIVER, True): + continue + elif kind == "elf": + if name in bundled or _match(name, LINUX_OS, False) or _match(name, LINUX_DRIVER, False): + continue + else: + base = name.rsplit("/", 1)[-1] + if name.startswith(MAC_OS_PREFIXES) or base in bundled: + continue + problems.append((rel, name)) + return problems + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + print(__doc__) + return 2 + bad = uncovered(Path(argv[1])) + for rel, name in bad: + print(f"{rel}: needs {name}, which is not in the package and not an OS or driver library") + if not bad: + print(f"{argv[1]}: every imported library is bundled or belongs to the OS / GPU driver") + return 1 if bad else 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/packaging/package_engine.py b/packaging/package_engine.py index 1b6c33c7..15820294 100644 --- a/packaging/package_engine.py +++ b/packaging/package_engine.py @@ -35,6 +35,9 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import binary_deps # noqa: E402 from strata_control import engine_component as ec # noqa: E402 from strata_control.components import BACKEND_MATRIX, host_platform # noqa: E402 @@ -84,7 +87,7 @@ def select(src: Path, entrypoint: str, *, tree: bool, include: list[str]) -> lis def build(src: Path, backend: str, version: str, target: str, out: Path, *, entry: str | None = None, archs: tuple[str, ...] = (), min_driver: dict | None = None, build_id: str | None = None, min_runtime: str | None = None, notes: str = "", tree: bool = False, include: list[str] | None = None, - variant: str = "") -> Path: + variant: str = "", search: list[Path] | None = None, allow_libs: list[str] | None = None) -> Path: if backend not in BACKEND_MATRIX: raise SystemExit(f"unknown backend {backend!r}") if backend != "cpu" and not archs: @@ -106,6 +109,7 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src / rel, destination) files.append({"path": rel, "sha256": sha256(destination), "bytes": destination.stat().st_size}) + files += _bundle_missing_libraries(staging, target, [f["path"] for f in files], search or [], allow_libs or []) manifest = {"schema_version": ec.SCHEMA_VERSION, "id": ec.COMPONENT_ID, "name": ec.COMPONENT_ID, "version": version, "platform": target, "backend": backend, "archs": list(archs), "min_driver": dict(min_driver or {}), "build_id": build_id or git_build_id(), @@ -127,6 +131,52 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr return folder +def _default_search(target: str) -> list[Path]: + """Where a Windows build finds the redistributable DLLs its engine imports: the CUDA/HIP toolkits and PATH.""" + if not target.startswith("windows"): + return [] + found: list[Path] = [] + for var in ("CUDA_PATH", "HIP_PATH"): + root = os.environ.get(var) + if root: + found += [Path(root) / "bin" / "x64", Path(root) / "bin"] + found += [Path(x) for x in os.environ.get("PATH", "").split(os.pathsep) if x] + return [d for d in found if d.is_dir()] + + +def _bundle_missing_libraries(staging: Path, target: str, rels: list[str], search: list[Path], allow: list[str]) -> list[dict]: + """Every library the package's binaries import must be in the package, or belong to the OS or the GPU driver + (binary_deps.py). Windows builds copy a missing one from the search folders (the CUDA toolkit's bin/x64, PATH): the packager + runs on a PC that has the toolkit, the person's PC does not. Anything still missing refuses the package.""" + added: list[dict] = [] + roots = search or _default_search(target) + for _ in range(8): # a copied DLL can import more DLLs + missing = [(f, n) for f, n in binary_deps.uncovered(staging) if n.lower() not in {a.lower() for a in allow}] + if not missing: + return added + progressed = False + for _file, name in sorted(set(missing), key=lambda x: x[1].lower()): + if not target.startswith("windows"): + continue + hit = next((d / name for d in roots if (d / name).is_file()), None) + if hit is None: + hit = next((c for d in roots for c in d.glob("*") if c.name.lower() == name.lower() and c.is_file()), None) + if hit is None or (staging / hit.name).exists(): + continue + shutil.copy2(hit, staging / hit.name) + added.append({"path": hit.name, "sha256": sha256(staging / hit.name), "bytes": (staging / hit.name).stat().st_size}) + progressed = True + print(f"bundled {hit.name} (imported by the engine; from {hit.parent})") + if not progressed: + break + left = [(f, n) for f, n in binary_deps.uncovered(staging) if n.lower() not in {a.lower() for a in allow}] + if left: + lines = "\n".join(f" {f} needs {n}" for f, n in sorted(set(left))) + raise SystemExit("refusing to package: these libraries are neither bundled nor part of the OS or the GPU driver, so a clean PC could not " + f"start the engine (0xC0000135 / 'library not found'):\n{lines}\nGive --search or fix the build.") + return added + + def package_sha256(folder: Path) -> str: """One digest for the whole package: SHA-256 of the manifest file (it holds every file's hash).""" return sha256(folder / ec.MANIFEST) @@ -150,6 +200,10 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("--min-runtime", default=None) ap.add_argument("--notes", default="") ap.add_argument("--tree", action="store_true", help="every regular file under --src, recursively") + ap.add_argument("--search", action="append", default=[], type=Path, metavar="DIR", + help="folder to copy a missing imported DLL from (default on Windows: CUDA_PATH/bin/x64, HIP_PATH/bin, PATH)") + ap.add_argument("--allow-lib", action="append", default=[], metavar="NAME", + help="an imported library that really is provided by the target system (rare; named so the check passes)") ap.add_argument("--include", action="append", default=[], metavar="GLOB", help="more files, relative to --src") a = ap.parse_args(argv) if a.verify: @@ -159,6 +213,11 @@ def main(argv: list[str] | None = None) -> int: except ec.ComponentProblem as exc: print(f"{a.verify}: REFUSED: {exc}") return 1 + bad = binary_deps.uncovered(a.verify) + if bad: + for rel, name in bad: + print(f"{a.verify}: REFUSED: {rel} needs {name}, which is neither bundled nor an OS / GPU driver library") + return 1 print(f"{a.verify}: ok ({len(component.files)} files, manifest sha256 {package_sha256(a.verify)})") return 0 for needed in ("src", "backend", "version", "out"): @@ -173,7 +232,8 @@ def main(argv: list[str] | None = None) -> int: a.out.mkdir(parents=True, exist_ok=True) folder = build(a.src, a.backend, a.version, a.platform or host_platform(), a.out, entry=a.entrypoint, archs=tuple(a.arch), min_driver=drivers, build_id=a.build_id, min_runtime=a.min_runtime, - notes=a.notes, tree=a.tree, include=a.include, variant=a.variant) + notes=a.notes, tree=a.tree, include=a.include, variant=a.variant, + search=a.search, allow_libs=a.allow_lib) entries = [p for p in folder.rglob("*") if p.is_file()] total = sum(p.stat().st_size for p in entries) print(f"{folder} ({total / (1 << 20):.1f} MiB, {len(entries)} files, manifest sha256 {package_sha256(folder)})") diff --git a/tests/terminal/test_engine_deps.py b/tests/terminal/test_engine_deps.py new file mode 100644 index 00000000..66d6b4eb --- /dev/null +++ b/tests/terminal/test_engine_deps.py @@ -0,0 +1,124 @@ +"""An engine package must carry every library its binaries import, except the OS's and the GPU driver's. + +Tester report 2026-10-17: a clean Windows 11 PC failed with 0xC0000135 because strata.exe imports cublas64_13.dll and the package +did not hold it (the build PC had the CUDA Toolkit on PATH, which hid the problem). These tests build tiny real PE files, so they +run anywhere and need no GPU or toolkit.""" + +import os +import struct +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "packaging")) +import binary_deps # noqa: E402 +import package_engine # noqa: E402 + + +def make_pe(imports, delay=()): + """A minimal PE32+ file with a .idata section that imports the named DLLs (and delay-loads `delay`).""" + va, raw = 0x1000, 0x400 + body = bytearray() + descriptors = (len(imports) + 1) * 20 + delays = (len(delay) + 1) * 32 + names_at = descriptors + delays + name_rvas = [] + blob = bytearray() + for n in list(imports) + list(delay): + name_rvas.append(va + names_at + len(blob)) + blob += n.encode("ascii") + b"\0" + for i, _ in enumerate(imports): + body += struct.pack("