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
12.1 KiB242 linesraw
1#!/usr/bin/env python3
2"""Collect the shared libraries an engine binary needs into one folder, ready for packaging/package_engine.py (Linux).
3
4    python packaging/collect_libs.py --binary build/strata --search /usr/local/cuda/lib64 --out stage/ \
5        [--also 'libcublasLt.so*'] [--data /opt/rocm/lib/rocblas/library=rocblas/library --data-glob '*gfx1201*']
6
7What it does: runs `ldd` on the binary with LD_LIBRARY_PATH set to --search, copies every dependency that is NOT
8supplied by the distribution (anything resolved outside /lib, /lib64, /usr/lib, /usr/lib64 and their x86_64-linux-gnu
9folders) into --out under its soname (symlinks are resolved, the real file is copied once per name), repeats for each
10copied library (their own dependencies), and adds libraries that are loaded with dlopen and so never show up in ldd
11(--also, a glob searched in --search). `--data SRC=DEST` copies a data folder (rocBLAS / hipBLASLt kernel libraries)
12to DEST under --out, optionally filtered by --data-glob.
13
14Distribution libraries (libc, libm, libstdc++, ...) are not copied: they are listed in
15`SYSTEM-LIBS.txt` beside the output so a missing one on a target PC can be named. The GPU driver's own libraries
16(libcuda.so.1, libnvidia-*, libze_intel_gpu, libOpenCL ICDs) are never bundled: they belong to the driver.
17A distribution library that is not on every system is copied from the build machine all the same (BUNDLE_FROM_SYSTEM, more
18with --bundle-system): libatomic.so.1, which TheRock's librocm_sysdeps_numa.so.1 needs; a container with no libatomic1 package
19could not start the AMD engine (boxia, 2026-11-15). Its notice goes into licenses/ (packaging/notices/).
20Nothing is downloaded; this only reads files on the build machine.
21"""
22
23from __future__ import annotations
24
25import argparse
26import fnmatch
27import os
28import re
29import shutil
30import subprocess
31import sys
32
33
34def _copy(src, dst) -> None:
35    """shutil.copy2, except onto itself: a library that an earlier binary's pass already put in --out is found there again by ldd (RUNPATH $ORIGIN)
36    and is the same file (SameFileError broke the second binary's pass for the AMD packages)."""
37    try:
38        if os.path.exists(dst) and os.path.samefile(src, dst):
39            return
40    except OSError:
41        pass
42    shutil.copy2(src, dst)
43from pathlib import Path
44
45SYSTEM_DIRS = ("/lib/", "/lib64/", "/usr/lib/", "/usr/lib64/")
46DRIVER_PATTERNS = ("libcuda.so*", "libnvidia-*", "libnvcuvid*", "libze_intel_gpu*", "libigdrcl*", "libOpenCL.so*",
47                   "libGLX*", "libEGL*", "libvulkan*", "libdrm_amdgpu*", "libdrm.so*", "libamdgpu*")
48LDD_LINE = re.compile(r"^\s*(\S+)\s+=>\s+(\S+)\s+\(0x")
49#: Distribution libraries that are bundled anyway (by soname glob): not on packaging/binary_deps.py's base list, so a PC without them
50#: could not start the engine. Each one has its notice in packaging/notices/<name>.txt, which is copied to <out>/licenses/.
51BUNDLE_FROM_SYSTEM = ("libatomic.so.1",)
52NOTICES = Path(__file__).resolve().parent / "notices"
53
54
55def is_system(path: str) -> bool:
56    return path.startswith(SYSTEM_DIRS)
57
58
59def bundled_anyway(name: str, extra: list[str] | tuple[str, ...] = ()) -> bool:
60    return any(fnmatch.fnmatch(name, pattern) for pattern in (*BUNDLE_FROM_SYSTEM, *extra))
61
62
63def _owner_package(path: str) -> tuple[str, str] | None:
64    """(package, version) of the distribution package that installed ``path`` (dpkg on Debian / Ubuntu, rpm elsewhere), or None."""
65    for command, parse in ((["dpkg-query", "-S", path], lambda t: t.split(":", 1)[0].strip()),
66                           (["rpm", "-qf", "--qf", "%{NAME}\n", path], lambda t: t.strip())):
67        try:
68            done = subprocess.run(command, capture_output=True, text=True, timeout=30)
69        except (OSError, subprocess.SubprocessError):
70            continue
71        if done.returncode == 0 and done.stdout.strip():
72            package = parse(done.stdout.splitlines()[0])
73            ask = ["dpkg-query", "-W", "-f", "${Version}", package] if command[0] == "dpkg-query" else ["rpm", "-q", "--qf", "%{VERSION}-%{RELEASE}", package]
74            try:
75                version = subprocess.run(ask, capture_output=True, text=True, timeout=30).stdout.strip()
76            except (OSError, subprocess.SubprocessError):
77                version = ""
78            return package, version
79    return None
80
81
82def copy_notice(name: str, out: Path, origin: str = "") -> None:
83    """For a distribution library that was bundled: packaging/notices/<soname without .so.N>.txt into <out>/licenses/, followed by where the copy
84    came from (the file and the distribution package with its version), and that package's own copyright file and the GPL-3 text from the build
85    machine when it has them (/usr/share/doc/<package>/copyright, /usr/share/common-licenses/GPL-3)."""
86    stem = name.split(".so", 1)[0]
87    source = NOTICES / f"{stem}.txt"
88    if not source.is_file():
89        print(f"WARNING: {name} is bundled but packaging/notices/{stem}.txt does not exist", file=sys.stderr)
90        return
91    folder = out / "licenses"
92    folder.mkdir(parents=True, exist_ok=True)
93    text = source.read_text(encoding="utf-8")
94    owner = (_owner_package(origin) or _owner_package(str(Path(origin).resolve())) or        # /lib vs /usr/lib on a merged-/usr system
95             _owner_package(origin.replace("/lib/", "/usr/lib/", 1) if origin.startswith("/lib/") else origin)) if origin else None
96    if origin:
97        text += f"\nCopied from {origin}" + (f" (distribution package {owner[0]} {owner[1]})" if owner else "") + " on the build machine.\n"
98    (folder / source.name).write_text(text, encoding="utf-8")
99    if owner and Path(f"/usr/share/doc/{owner[0]}/copyright").is_file():
100        _copy(Path(f"/usr/share/doc/{owner[0]}/copyright"), folder / f"{stem}-copyright.txt")
101    if Path("/usr/share/common-licenses/GPL-3").is_file():
102        _copy(Path("/usr/share/common-licenses/GPL-3"), folder / "GPL-3.txt")
103
104
105def is_driver(name: str) -> bool:
106    return any(fnmatch.fnmatch(name, pattern) for pattern in DRIVER_PATTERNS)
107
108
109GFX = re.compile(r"gfx[0-9a-f]+", re.I)
110
111
112def arch_wanted(name: str, wanted: str) -> bool:
113    """Data files for other GPU architectures are left out; shared ones (no gfx name) stay."""
114    if not wanted:
115        return True
116    named = {m.group(0).lower() for m in GFX.finditer(name)}
117    return not named or bool(named & {w.strip().lower() for w in wanted.split(",") if w.strip()})
118
119
120ELF_MAGIC = bytes([0x7F]) + b"ELF"
121
122
123def is_elf(path: Path) -> bool:
124    try:
125        with path.open("rb") as stream:
126            return stream.read(4) == ELF_MAGIC
127    except OSError:
128        return False
129
130
131def soname(path: Path) -> str | None:
132    """The library's own name (DT_SONAME), which is the name its users ask the loader for."""
133    done = subprocess.run(["readelf", "-d", str(path)], capture_output=True, text=True)
134    match = re.search(r"\(SONAME\)\s+Library soname: \[([^\]]+)\]", done.stdout)
135    return match.group(1) if match else None
136
137
138def dependencies(binary: Path, search: list[str]) -> tuple[dict[str, str], list[str]]:
139    """{soname: resolved path} and the sonames ldd could not find."""
140    env = dict(os.environ)
141    env["LD_LIBRARY_PATH"] = ":".join(search + ([env["LD_LIBRARY_PATH"]] if env.get("LD_LIBRARY_PATH") else []))
142    done = subprocess.run(["ldd", str(binary)], capture_output=True, text=True, env=env, timeout=120)
143    found, missing = {}, []
144    for line in done.stdout.splitlines():
145        if "not found" in line:
146            missing.append(line.split("=>")[0].strip())
147            continue
148        match = LDD_LINE.match(line)
149        if match:
150            found[match.group(1)] = match.group(2)
151    return found, missing
152
153
154def main(argv=None) -> int:
155    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
156    ap.add_argument("--binary", required=True, type=Path)
157    ap.add_argument("--search", action="append", default=[], help="a library folder to resolve against (repeatable)")
158    ap.add_argument("--out", required=True, type=Path)
159    ap.add_argument("--also", action="append", default=[], help="glob of dlopen'd libraries to add, searched in --search")
160    ap.add_argument("--data", action="append", default=[], metavar="SRC=DEST")
161    ap.add_argument("--data-glob", action="append", default=[], help="keep only data files matching one of these globs")
162    ap.add_argument("--data-arch", default="", help="comma list (gfx1200,gfx1201): of the data files that name a gfx arch keep "
163                                                    "only these; files naming none (shared tables) are kept")
164    ap.add_argument("--bundle-system", action="append", default=[], metavar="GLOB",
165                    help="a distribution library (soname glob) to bundle all the same, beside " + ", ".join(BUNDLE_FROM_SYSTEM))
166    a = ap.parse_args(argv)
167    a.out.mkdir(parents=True, exist_ok=True)
168    copied: dict[str, str] = {}
169    system: set[str] = set()
170    queue = [a.binary]
171    seen = set()
172    while queue:
173        item = queue.pop()
174        if item in seen:
175            continue
176        seen.add(item)
177        found, missing = dependencies(item, a.search)
178        for name in missing:
179            if not is_driver(name):
180                print(f"WARNING: {item.name} needs {name}, which ldd cannot find", file=sys.stderr)
181        for name, path in found.items():
182            if is_driver(name):
183                continue
184            if is_system(path) and not bundled_anyway(name, a.bundle_system):
185                system.add(name)
186                continue
187            if name in copied:
188                continue
189            real = Path(path).resolve()
190            _copy(real, a.out / name)                    # the real file under its soname (a package holds no symlinks)
191            copied[name] = str(real)
192            if is_system(path):
193                copy_notice(name, a.out, path)
194            queue.append(a.out / name)
195    for pattern in a.also:
196        hits = [Path(d) / n for d in a.search if os.path.isdir(d) for n in sorted(os.listdir(d)) if fnmatch.fnmatch(n, pattern)]
197        if not hits:
198            print(f"WARNING: --also {pattern!r} matched nothing in {a.search}", file=sys.stderr)
199        for hit in hits:
200            if not hit.is_file() or not is_elf(hit):
201                continue
202            real = hit.resolve()
203            if str(real) in copied.values():          # libX.so -> libX.so.1 -> libX.so.1.2.3: one file, one name (the soname)
204                continue
205            name = soname(real) or hit.name
206            if name in copied:
207                continue
208            _copy(real, a.out / name)
209            copied[name] = str(real)
210            found, missing = dependencies(a.out / name, a.search)
211            for dep in missing:
212                if not is_driver(dep):
213                    print(f"WARNING: {name} needs {dep}, which ldd cannot find", file=sys.stderr)
214            for dep, path in found.items():
215                if is_driver(dep) or dep in copied:
216                    continue
217                if is_system(path) and not bundled_anyway(dep, a.bundle_system):
218                    system.add(dep)
219                else:
220                    _copy(Path(path).resolve(), a.out / dep)
221                    copied[dep] = str(Path(path).resolve())
222                    if is_system(path):
223                        copy_notice(dep, a.out, path)
224    for spec in a.data:
225        src, _, dest = spec.partition("=")
226        if not dest:
227            ap.error(f"--data {spec!r} is not SRC=DEST")
228        for path in sorted(Path(src).rglob("*")):
229            if path.is_file() and (not a.data_glob or any(fnmatch.fnmatch(path.name, g) for g in a.data_glob))                     and arch_wanted(path.name, a.data_arch):
230                target = a.out / dest / path.relative_to(src)
231                target.parent.mkdir(parents=True, exist_ok=True)
232                _copy(path.resolve(), target)
233    (a.out / "SYSTEM-LIBS.txt").write_text("\n".join(sorted(system)) + "\n", encoding="utf-8")
234    total = sum(p.stat().st_size for p in a.out.rglob("*") if p.is_file())
235    print(f"copied {len(copied)} libraries ({total / (1 << 20):.1f} MiB incl. data) to {a.out}; {len(system)} system libraries left to the OS")
236    for name in sorted(copied):
237        print(f"  {name} <- {copied[name]}")
238    return 0
239
240
241if __name__ == "__main__":
242    raise SystemExit(main())