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
This commit is contained in:
1 parent
f95fb3e074
commit
37f7f03cd2
3 files changed
+422
-2
No files matched your search
@@ -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 <package folder> # 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("<I", data, 0x3C)[0]
|
||||
if data[pe:pe + 4] != b"PE\0\0":
|
||||
raise ValueError(f"{path}: bad PE header")
|
||||
nsec, = struct.unpack_from("<H", data, pe + 6)
|
||||
opt_size, = struct.unpack_from("<H", data, pe + 20)
|
||||
opt = pe + 24
|
||||
magic, = struct.unpack_from("<H", data, opt)
|
||||
dd = opt + (112 if magic == 0x20B else 96)
|
||||
sections = []
|
||||
sec = opt + opt_size
|
||||
for i in range(nsec):
|
||||
vsize, va, rsize, raw = struct.unpack_from("<IIII", data, sec + i * 40 + 8)
|
||||
sections.append((va, max(vsize, rsize), raw))
|
||||
|
||||
def off(rva: int) -> 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("<II", data, dd + 8)
|
||||
if imp_rva and imp_size:
|
||||
o = off(imp_rva)
|
||||
while True:
|
||||
_, _, _, name_rva, _ = struct.unpack_from("<IIIII", data, o)
|
||||
if not name_rva:
|
||||
break
|
||||
names.append(cstr(off(name_rva)))
|
||||
o += 20
|
||||
delay_rva, delay_size = struct.unpack_from("<II", data, dd + 13 * 8)
|
||||
if delay_rva and delay_size:
|
||||
o = off(delay_rva)
|
||||
while True:
|
||||
attrs, name_rva = struct.unpack_from("<II", data, o)
|
||||
if not name_rva:
|
||||
break
|
||||
names.append(cstr(off(name_rva)))
|
||||
o += 32
|
||||
return names
|
||||
|
||||
|
||||
def elf_needed(path: Path) -> 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("<I", data, base)[0] not in (0xFEEDFACF, 0xFEEDFACE):
|
||||
raise ValueError(f"{path}: not a Mach-O file")
|
||||
is64 = struct.unpack_from("<I", data, base)[0] == 0xFEEDFACF
|
||||
ncmds, = struct.unpack_from("<I", data, base + 16)
|
||||
o = base + (32 if is64 else 28)
|
||||
out = []
|
||||
for _ in range(ncmds):
|
||||
cmd, size = struct.unpack_from("<II", data, o)
|
||||
if cmd in (0xC, 0x80000018, 0x8000001F): # LOAD_DYLIB, LOAD_WEAK_DYLIB, REEXPORT_DYLIB
|
||||
name_off, = struct.unpack_from("<I", data, o + 8)
|
||||
s = o + name_off
|
||||
out.append(data[s:data.index(b"\0", s)].decode("utf-8", "replace"))
|
||||
o += size
|
||||
return out
|
||||
|
||||
|
||||
def imports(path: Path) -> 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))
|
||||
@@ -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 <folder holding them> 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)})")
|
||||
|
||||
@@ -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("<IIIII", 0, 0, 0, name_rvas[i], 0)
|
||||
body += b"\0" * 20
|
||||
for j, _ in enumerate(delay):
|
||||
body += struct.pack("<II", 1, name_rvas[len(imports) + j]) + b"\0" * 24
|
||||
body += b"\0" * 32
|
||||
body += blob
|
||||
size = len(body)
|
||||
dos = bytearray(0x40)
|
||||
dos[:2] = b"MZ"
|
||||
struct.pack_into("<I", dos, 0x3C, 0x40)
|
||||
coff = b"PE\0\0" + struct.pack("<HHIIIHH", 0x8664, 1, 0, 0, 0, 240, 0x22)
|
||||
opt = bytearray(240)
|
||||
struct.pack_into("<H", opt, 0, 0x20B)
|
||||
struct.pack_into("<II", opt, 112 + 8, va if imports else 0, descriptors if imports else 0)
|
||||
struct.pack_into("<II", opt, 112 + 13 * 8, va + descriptors if delay else 0, delays if delay else 0)
|
||||
section = b".idata\0\0" + struct.pack("<IIIIIIHHI", size, va, size, raw, 0, 0, 0, 0, 0x40000040)
|
||||
head = bytes(dos) + coff + bytes(opt) + section
|
||||
return head + b"\0" * (raw - len(head)) + bytes(body)
|
||||
|
||||
|
||||
class Imports(unittest.TestCase):
|
||||
def test_pe_reader_lists_load_time_and_delay_load_imports(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = Path(d) / "a.exe"
|
||||
p.write_bytes(make_pe(["cublas64_13.dll", "KERNEL32.dll"], delay=["cudart64_13.dll"]))
|
||||
self.assertEqual(binary_deps.pe_imports(p), ["cublas64_13.dll", "KERNEL32.dll", "cudart64_13.dll"])
|
||||
|
||||
@unittest.skipUnless(sys.platform.startswith("linux"), "needs a real ELF")
|
||||
def test_elf_reader_on_a_system_binary(self):
|
||||
names = binary_deps.elf_needed(Path("/bin/ls") if Path("/bin/ls").exists() else Path(sys.executable))
|
||||
self.assertTrue(any(n.startswith("libc.so") for n in names), names)
|
||||
|
||||
|
||||
class Rule(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.pkg = Path(self.dir.name) / "pkg"
|
||||
self.pkg.mkdir()
|
||||
|
||||
def test_a_missing_cuda_dll_is_reported_and_the_driver_and_os_are_not(self):
|
||||
(self.pkg / "strata.exe").write_bytes(make_pe(["cublas64_13.dll", "KERNEL32.dll", "ADVAPI32.dll", "nvcuda.dll", "api-ms-win-crt-heap-l1-1-0.dll"]))
|
||||
self.assertEqual(binary_deps.uncovered(self.pkg), [("strata.exe", "cublas64_13.dll")])
|
||||
|
||||
def test_the_visual_cpp_runtime_is_not_an_os_library(self):
|
||||
(self.pkg / "strata.exe").write_bytes(make_pe(["VCRUNTIME140.dll", "MSVCP140.dll"]))
|
||||
self.assertEqual({n for _, n in binary_deps.uncovered(self.pkg)}, {"VCRUNTIME140.dll", "MSVCP140.dll"})
|
||||
|
||||
def test_bundled_libraries_count_and_their_own_imports_are_checked(self):
|
||||
(self.pkg / "strata.exe").write_bytes(make_pe(["cublas64_13.dll"]))
|
||||
(self.pkg / "cublas64_13.dll").write_bytes(make_pe(["cublasLt64_13.dll", "KERNEL32.dll"]))
|
||||
self.assertEqual(binary_deps.uncovered(self.pkg), [("cublas64_13.dll", "cublasLt64_13.dll")])
|
||||
(self.pkg / "CUBLASLT64_13.DLL").write_bytes(make_pe(["KERNEL32.dll"]))
|
||||
self.assertEqual(binary_deps.uncovered(self.pkg), [])
|
||||
|
||||
|
||||
@unittest.skipUnless(os.name == "nt", "the packager only copies DLLs for Windows targets")
|
||||
class Packager(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.root = Path(self.dir.name)
|
||||
self.src = self.root / "src"
|
||||
self.src.mkdir()
|
||||
(self.src / "strata.exe").write_bytes(make_pe(["cublas64_13.dll", "KERNEL32.dll"]))
|
||||
self.toolkit = self.root / "toolkit"
|
||||
self.toolkit.mkdir()
|
||||
(self.toolkit / "cublas64_13.dll").write_bytes(make_pe(["cublasLt64_13.dll", "KERNEL32.dll"]))
|
||||
(self.toolkit / "cublasLt64_13.dll").write_bytes(make_pe(["KERNEL32.dll"]))
|
||||
self.out = self.root / "out"
|
||||
self.out.mkdir()
|
||||
|
||||
def build(self, search):
|
||||
return package_engine.build(self.src, "cuda", "0.1.45.1", "windows-x86_64", self.out, archs=("sm_86",), build_id="t", search=search)
|
||||
|
||||
def test_it_bundles_the_imported_dlls_and_what_they_import(self):
|
||||
folder = self.build([self.toolkit])
|
||||
self.assertTrue((folder / "cublas64_13.dll").is_file() and (folder / "cublasLt64_13.dll").is_file())
|
||||
self.assertEqual(binary_deps.uncovered(folder), [])
|
||||
self.assertEqual(package_engine.main(["--verify", str(folder)]), 0)
|
||||
|
||||
def test_it_refuses_when_a_dll_cannot_be_found(self):
|
||||
empty = self.root / "empty"
|
||||
empty.mkdir()
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.build([empty])
|
||||
self.assertIn("cublas64_13.dll", str(raised.exception))
|
||||
self.assertFalse(any(self.out.iterdir()) and any(p.name.startswith("0.1.45.1") for p in self.out.iterdir()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user