diff --git a/packaging/binary_deps.py b/packaging/binary_deps.py index ad9043c952..cab9fda359 100644 --- a/packaging/binary_deps.py +++ b/packaging/binary_deps.py @@ -40,12 +40,14 @@ WINDOWS_DRIVER = ( ) # ---- Linux ----------------------------------------------------------------------------------------------------------------- -# Every distribution has these (glibc and the compiler runtime). Names are sonames or glob patterns. +# The base system: what every Linux has, a container and a minimal install included (glibc, the C++ runtime). Names are sonames or glob +# patterns. Anything else an engine file needs travels in the package. Until 0.2.14 this list also held libgomp, libatomic, libz, libnuma, +# libdrm, libelf, libtinfo, libcrypt, libffi, libpci, libudev, libX11 and libxcb as "every distribution has these": the AMD packages then +# shipped without libatomic.so.1 (librocm_sysdeps_numa.so.1 needs it) and a container without the libatomic1 package could not start the +# 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). 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", + "librt.so.1", "libutil.so.1", "libresolv.so.2", "libnss_*.so.*", "libgcc_s.so.1", "libstdc++.so.6", ) # From the GPU driver package: never bundled. LINUX_DRIVER = ( @@ -117,9 +119,13 @@ def pe_imports(path: Path) -> list[str]: 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() + return elf_needed_bytes(path.read_bytes(), str(path)) + + +def elf_needed_bytes(data: bytes, where: str = "the file") -> list[str]: + """elf_needed() for the bytes of an ELF file (a member of a package archive that is never unpacked).""" if data[:4] != b"\x7fELF": - raise ValueError(f"{path}: not an ELF file") + raise ValueError(f"{where}: not an ELF file") is64 = data[4] == 2 le = "<" if data[5] == 1 else ">" if is64: @@ -230,10 +236,41 @@ def uncovered(folder: Path, files: list[str] | None = None) -> list[tuple[str, s return problems +def archive_uncovered(archive: Path, base: tuple[str, ...] | None = None) -> list[tuple[str, str]]: + """The Linux rule of `uncovered` for a finished package archive (.tar.gz), read member by member and never unpacked: (file, imported + 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 + archive does not count as bundled: the package manifest and the install never keep symlinks (package_engine.py, engine_component.verify).""" + import tarfile + base = LINUX_OS if base is None else base + needs: list[tuple[str, str]] = [] + bundled: set[str] = set() + with tarfile.open(archive, "r:*") as tar: + for member in tar: + if not member.isfile(): + continue + bundled.add(member.name.rsplit("/", 1)[-1]) + stream = tar.extractfile(member) + if stream is None or stream.read(4) != b"\x7fELF": + continue + data = b"\x7fELF" + stream.read() + try: + needs += [(member.name, n) for n in elf_needed_bytes(data, member.name)] + except (ValueError, struct.error): + continue + 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)] + + def main(argv: list[str]) -> int: if len(argv) != 2: print(__doc__) return 2 + if argv[1].endswith((".tar.gz", ".tgz", ".tar")) and Path(argv[1]).is_file(): + bad = archive_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 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") diff --git a/packaging/build_hip_linux.sh b/packaging/build_hip_linux.sh index 9e59e1a824..8782247fca 100644 --- a/packaging/build_hip_linux.sh +++ b/packaging/build_hip_linux.sh @@ -117,4 +117,7 @@ python3 packaging/package_engine.py --src "$STAGE" --backend hip --version "$PKG --variant "$V" --build-id "$COMMIT+rocm" --tree $shape_pkg --notes "AMD $V build: engine, CPU picture reader, GPU picture reader${NOTE_EXTRA:-}" > "$OUT/package.log" 2>&1 chk $? "packaged" cat "$OUT/package.log" >> "$S" +# every library a bundled file needs is in the package or on binary_deps.py's short base-system list (glibc, libgcc_s, libstdc++); +# collect_libs.py bundles libatomic.so.1 (librocm_sysdeps_numa.so.1 needs it) with its notice in licenses/ +for d in "$OUT/components/engine"/*/; do python3 packaging/binary_deps.py "$d" >> "$S" 2>&1; chk $? "imports covered in $(basename "$d")"; done st "BUILD-DONE" diff --git a/packaging/collect_libs.py b/packaging/collect_libs.py index 7ed3b7745f..c5ddcacbb4 100644 --- a/packaging/collect_libs.py +++ b/packaging/collect_libs.py @@ -11,9 +11,12 @@ copied library (their own dependencies), and adds libraries that are loaded with (--also, a glob searched in --search). `--data SRC=DEST` copies a data folder (rocBLAS / hipBLASLt kernel libraries) to DEST under --out, optionally filtered by --data-glob. -Distribution libraries (libc, libm, libstdc++, libdrm, libnuma, ...) are not copied: they are listed in +Distribution libraries (libc, libm, libstdc++, ...) are not copied: they are listed in `SYSTEM-LIBS.txt` beside the output so a missing one on a target PC can be named. The GPU driver's own libraries (libcuda.so.1, libnvidia-*, libze_intel_gpu, libOpenCL ICDs) are never bundled: they belong to the driver. +A distribution library that is not on every system is copied from the build machine all the same (BUNDLE_FROM_SYSTEM, more +with --bundle-system): libatomic.so.1, which TheRock's librocm_sysdeps_numa.so.1 needs; a container with no libatomic1 package +could not start the AMD engine (boxia, 2026-11-15). Its notice goes into licenses/ (packaging/notices/). Nothing is downloaded; this only reads files on the build machine. """ @@ -43,12 +46,62 @@ SYSTEM_DIRS = ("/lib/", "/lib64/", "/usr/lib/", "/usr/lib64/") DRIVER_PATTERNS = ("libcuda.so*", "libnvidia-*", "libnvcuvid*", "libze_intel_gpu*", "libigdrcl*", "libOpenCL.so*", "libGLX*", "libEGL*", "libvulkan*", "libdrm_amdgpu*", "libdrm.so*", "libamdgpu*") LDD_LINE = re.compile(r"^\s*(\S+)\s+=>\s+(\S+)\s+\(0x") +#: Distribution libraries that are bundled anyway (by soname glob): not on packaging/binary_deps.py's base list, so a PC without them +#: could not start the engine. Each one has its notice in packaging/notices/.txt, which is copied to /licenses/. +BUNDLE_FROM_SYSTEM = ("libatomic.so.1",) +NOTICES = Path(__file__).resolve().parent / "notices" def is_system(path: str) -> bool: return path.startswith(SYSTEM_DIRS) +def bundled_anyway(name: str, extra: list[str] | tuple[str, ...] = ()) -> bool: + return any(fnmatch.fnmatch(name, pattern) for pattern in (*BUNDLE_FROM_SYSTEM, *extra)) + + +def _owner_package(path: str) -> tuple[str, str] | None: + """(package, version) of the distribution package that installed ``path`` (dpkg on Debian / Ubuntu, rpm elsewhere), or None.""" + for command, parse in ((["dpkg-query", "-S", path], lambda t: t.split(":", 1)[0].strip()), + (["rpm", "-qf", "--qf", "%{NAME}\n", path], lambda t: t.strip())): + try: + done = subprocess.run(command, capture_output=True, text=True, timeout=30) + except (OSError, subprocess.SubprocessError): + continue + if done.returncode == 0 and done.stdout.strip(): + package = parse(done.stdout.splitlines()[0]) + ask = ["dpkg-query", "-W", "-f", "${Version}", package] if command[0] == "dpkg-query" else ["rpm", "-q", "--qf", "%{VERSION}-%{RELEASE}", package] + try: + version = subprocess.run(ask, capture_output=True, text=True, timeout=30).stdout.strip() + except (OSError, subprocess.SubprocessError): + version = "" + return package, version + return None + + +def copy_notice(name: str, out: Path, origin: str = "") -> None: + """For a distribution library that was bundled: packaging/notices/.txt into /licenses/, followed by where the copy + 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 + machine when it has them (/usr/share/doc//copyright, /usr/share/common-licenses/GPL-3).""" + stem = name.split(".so", 1)[0] + source = NOTICES / f"{stem}.txt" + if not source.is_file(): + print(f"WARNING: {name} is bundled but packaging/notices/{stem}.txt does not exist", file=sys.stderr) + return + folder = out / "licenses" + folder.mkdir(parents=True, exist_ok=True) + text = source.read_text(encoding="utf-8") + owner = (_owner_package(origin) or _owner_package(str(Path(origin).resolve())) or # /lib vs /usr/lib on a merged-/usr system + _owner_package(origin.replace("/lib/", "/usr/lib/", 1) if origin.startswith("/lib/") else origin)) if origin else None + if origin: + text += f"\nCopied from {origin}" + (f" (distribution package {owner[0]} {owner[1]})" if owner else "") + " on the build machine.\n" + (folder / source.name).write_text(text, encoding="utf-8") + if owner and Path(f"/usr/share/doc/{owner[0]}/copyright").is_file(): + _copy(Path(f"/usr/share/doc/{owner[0]}/copyright"), folder / f"{stem}-copyright.txt") + if Path("/usr/share/common-licenses/GPL-3").is_file(): + _copy(Path("/usr/share/common-licenses/GPL-3"), folder / "GPL-3.txt") + + def is_driver(name: str) -> bool: return any(fnmatch.fnmatch(name, pattern) for pattern in DRIVER_PATTERNS) @@ -108,6 +161,8 @@ def main(argv=None) -> int: ap.add_argument("--data-glob", action="append", default=[], help="keep only data files matching one of these globs") ap.add_argument("--data-arch", default="", help="comma list (gfx1200,gfx1201): of the data files that name a gfx arch keep " "only these; files naming none (shared tables) are kept") + ap.add_argument("--bundle-system", action="append", default=[], metavar="GLOB", + help="a distribution library (soname glob) to bundle all the same, beside " + ", ".join(BUNDLE_FROM_SYSTEM)) a = ap.parse_args(argv) a.out.mkdir(parents=True, exist_ok=True) copied: dict[str, str] = {} @@ -126,14 +181,16 @@ def main(argv=None) -> int: for name, path in found.items(): if is_driver(name): continue - if is_system(path): + if is_system(path) and not bundled_anyway(name, a.bundle_system): system.add(name) continue if name in copied: continue real = Path(path).resolve() - _copy(real, a.out / name) + _copy(real, a.out / name) # the real file under its soname (a package holds no symlinks) copied[name] = str(real) + if is_system(path): + copy_notice(name, a.out, path) queue.append(a.out / name) for pattern in a.also: 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)] @@ -157,11 +214,13 @@ def main(argv=None) -> int: for dep, path in found.items(): if is_driver(dep) or dep in copied: continue - if is_system(path): + if is_system(path) and not bundled_anyway(dep, a.bundle_system): system.add(dep) else: _copy(Path(path).resolve(), a.out / dep) copied[dep] = str(Path(path).resolve()) + if is_system(path): + copy_notice(dep, a.out, path) for spec in a.data: src, _, dest = spec.partition("=") if not dest: diff --git a/packaging/notices/libatomic.txt b/packaging/notices/libatomic.txt new file mode 100644 index 0000000000..3ccac96f5a --- /dev/null +++ b/packaging/notices/libatomic.txt @@ -0,0 +1,13 @@ +libatomic.so.1: the GNU atomic library, part of the GCC runtime + +This engine package carries an unmodified copy of libatomic.so.1 from the build machine. The AMD ROCm library +librocm_sysdeps_numa.so.1 in this package needs it, and some Linux systems (containers, minimal installs) do not have it. + +License: the GNU General Public License, version 3 or later, with the GCC Runtime Library Exception, version 3.1 +(SPDX: GPL-3.0-or-later WITH GCC-exception-3.1). + GPL-3.0: https://www.gnu.org/licenses/gpl-3.0.html (GPL-3.txt in this folder when the build machine had it) + GCC Runtime Exception: https://www.gnu.org/licenses/gcc-exception-3.1.html +Copyright: Free Software Foundation, Inc. + +Source code: libatomic is in the GCC source tree (https://gcc.gnu.org/, directory libatomic). The exact source of this copy is the +source package of the distribution package named below (for Debian and Ubuntu: `apt-get source` of the gcc package that built it). diff --git a/tests/terminal/test_engine_deps_linux.py b/tests/terminal/test_engine_deps_linux.py new file mode 100644 index 0000000000..96dff2d7d4 --- /dev/null +++ b/tests/terminal/test_engine_deps_linux.py @@ -0,0 +1,186 @@ +"""The Linux rule of an engine package: every library a bundled file needs (DT_NEEDED) is in the package or on the short base-system list. + +boxia 2026-11-15: the hip-rx6000 / rx9070 / rx7900 packages of 0.2.14 hold librocm_sysdeps_numa.so.1, which needs libatomic.so.1; no package +bundled it, because the old list called libatomic "a library every distribution has". A container without the libatomic1 package could not start +the engine. Proves: the base list is glibc and the C++ runtime only; a finished archive is checked member by member (a symlink is not bundled, +the install keeps none); collect_libs.py bundles libatomic.so.1 from the build machine as a real file under its soname, with its notice; and, +on the owner PC where the published 0.2.14 files are (C:\\rc214\\FINAL4\\UPLOAD, read only, or STRATA_FINAL4_DIR), the archive check finds +exactly today's gap: libatomic.so.1 in the three AMD packages, nothing in hip-halo or the CUDA ones. Tiny real ELF files, no toolchain needed.""" + +import io +import os +import struct +import sys +import tarfile +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "packaging")) +import binary_deps # noqa: E402 +import collect_libs # noqa: E402 + +FINAL4 = Path(os.environ.get("STRATA_FINAL4_DIR", r"C:\rc214\FINAL4\UPLOAD")) + + +def make_elf(needed, soname=None) -> bytes: + """A minimal ELF64 little-endian file with a .dynstr and a .dynamic section naming `needed` (DT_NEEDED) and `soname` (DT_SONAME).""" + strtab = bytearray(b"\0") + entries = [] + for name in needed: + entries.append((1, len(strtab))) + strtab += name.encode() + b"\0" + if soname: + entries.append((14, len(strtab))) + strtab += soname.encode() + b"\0" + entries.append((0, 0)) + str_off = 64 + dyn_off = (str_off + len(strtab) + 7) // 8 * 8 + dynamic = b"".join(struct.pack(" None: + with tarfile.open(path, "w:gz") as tar: + for name, data in files.items(): + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + for name, target in (links or {}).items(): + info = tarfile.TarInfo(name) + info.type = tarfile.SYMTYPE + info.linkname = target + tar.addfile(info) + + +class BaseList(unittest.TestCase): + def test_the_reader_reads_the_tiny_elf(self): + self.assertEqual(binary_deps.elf_needed_bytes(make_elf(["libatomic.so.1", "libc.so.6"], soname="librocm_sysdeps_numa.so.1")), + ["libatomic.so.1", "libc.so.6"]) + + def test_the_base_list_is_glibc_and_the_cpp_runtime(self): + for name in ("libc.so.6", "libm.so.6", "libdl.so.2", "libpthread.so.0", "librt.so.1", "ld-linux-x86-64.so.2", "libgcc_s.so.1", "libstdc++.so.6"): + self.assertTrue(binary_deps._match(name, binary_deps.LINUX_OS, False), name) + for name in ("libatomic.so.1", "libgomp.so.1", "libz.so.1", "libnuma.so.1", "libdrm.so.2", "libelf.so.1", "libtinfo.so.6"): + self.assertFalse(binary_deps._match(name, binary_deps.LINUX_OS, False), name) + + def test_a_package_folder_without_libatomic_is_refused_and_with_it_passes(self): + with tempfile.TemporaryDirectory() as d: + pkg = Path(d) + (pkg / "strata").write_bytes(make_elf(["librocm_sysdeps_numa.so.1", "libc.so.6", "libstdc++.so.6"])) + (pkg / "librocm_sysdeps_numa.so.1").write_bytes(make_elf(["libatomic.so.1", "libc.so.6"])) + self.assertEqual(binary_deps.uncovered(pkg), [("librocm_sysdeps_numa.so.1", "libatomic.so.1")]) + (pkg / "libatomic.so.1").write_bytes(make_elf(["libc.so.6"], soname="libatomic.so.1")) + self.assertEqual(binary_deps.uncovered(pkg), []) + + +class Archive(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.files = {"strata": make_elf(["librocm_sysdeps_numa.so.1", "libhsa-runtime64.so.1", "libc.so.6"]), + "librocm_sysdeps_numa.so.1": make_elf(["libatomic.so.1", "libc.so.6"]), + "BUILD.json": b"{}", "licenses/notice.txt": b"text"} + + def test_the_archive_check_names_the_gap(self): + tar = self.root / "a.tar.gz" + make_tar(tar, self.files) + self.assertEqual(binary_deps.archive_uncovered(tar), [("librocm_sysdeps_numa.so.1", "libatomic.so.1")]) + self.assertEqual(binary_deps.main(["binary_deps.py", str(tar)]), 1) + + def test_a_bundled_libatomic_closes_it_and_a_symlink_does_not(self): + tar = self.root / "b.tar.gz" + make_tar(tar, self.files, links={"libatomic.so.1": "libatomic.so.1.2.0"}) + self.assertEqual(binary_deps.archive_uncovered(tar), [("librocm_sysdeps_numa.so.1", "libatomic.so.1")]) + tar = self.root / "c.tar.gz" + make_tar(tar, {**self.files, "libatomic.so.1": make_elf(["libc.so.6"], soname="libatomic.so.1")}) + self.assertEqual(binary_deps.archive_uncovered(tar), []) + self.assertEqual(binary_deps.main(["binary_deps.py", str(tar)]), 0) + + +class Collect(unittest.TestCase): + """collect_libs.py with ldd faked: the build machine's libatomic is copied as a real file under its soname, with its notice; libc stays the OS's.""" + + def test_libatomic_is_bundled_with_its_notice(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + system = root / "usr" / "lib" + system.mkdir(parents=True) + real = system / "libatomic.so.1.2.0" + real.write_bytes(make_elf(["libc.so.6"], soname="libatomic.so.1")) + (system / "libc.so.6").write_bytes(make_elf([])) + rocm = root / "rocm" + rocm.mkdir() + (rocm / "librocm_sysdeps_numa.so.1").write_bytes(make_elf(["libatomic.so.1", "libc.so.6"])) + binary = root / "strata" + binary.write_bytes(make_elf(["librocm_sysdeps_numa.so.1", "libc.so.6"])) + out = root / "stage" + + def deps(item, _search): + name = Path(item).name + if name == "strata": + return {"librocm_sysdeps_numa.so.1": str(rocm / "librocm_sysdeps_numa.so.1"), "libc.so.6": str(system / "libc.so.6")}, [] + if name == "librocm_sysdeps_numa.so.1": + return {"libatomic.so.1": str(real), "libc.so.6": str(system / "libc.so.6")}, [] + return {"libc.so.6": str(system / "libc.so.6")}, [] + with mock.patch.object(collect_libs, "dependencies", deps), \ + mock.patch.object(collect_libs, "is_system", lambda p: str(p).startswith(str(system))), \ + mock.patch.object(collect_libs, "_owner_package", return_value=("libatomic1", "14.2.0-4ubuntu2~24.04.1")): + self.assertEqual(collect_libs.main(["--binary", str(binary), "--out", str(out)]), 0) + atomic = out / "libatomic.so.1" + self.assertTrue(atomic.is_file() and not atomic.is_symlink()) + self.assertEqual(atomic.read_bytes(), real.read_bytes()) + self.assertFalse((out / "libc.so.6").exists()) + self.assertEqual((out / "SYSTEM-LIBS.txt").read_text().split(), ["libc.so.6"]) + notice = (out / "licenses" / "libatomic.txt").read_text() + self.assertIn("GPL-3.0-or-later WITH GCC-exception-3.1", notice) + self.assertIn("(distribution package libatomic1 14.2.0-4ubuntu2~24.04.1)", notice) + self.assertEqual(binary_deps.uncovered(out), []) + + def test_the_bundle_list(self): + self.assertTrue(collect_libs.bundled_anyway("libatomic.so.1")) + self.assertFalse(collect_libs.bundled_anyway("libc.so.6")) + self.assertTrue(collect_libs.bundled_anyway("libfoo.so.2", ["libfoo.so*"])) + self.assertTrue((ROOT / "packaging" / "notices" / "libatomic.txt").is_file()) + + +@unittest.skipUnless(FINAL4.is_dir(), "the published 0.2.14 files are only on the owner PC (C:\\rc214\\FINAL4\\UPLOAD) or in STRATA_FINAL4_DIR") +class PublishedPackages(unittest.TestCase): + """The check on the real 0.2.14 Linux engine archives (read only): it would have refused the three AMD packages for libatomic.so.1.""" + + def check(self, name): + path = FINAL4 / name + if not path.is_file(): + self.skipTest(f"{name} is not in {FINAL4}") + return binary_deps.archive_uncovered(path) + + def test_the_three_amd_packages_lack_libatomic(self): + for variant in ("rx6000", "rx9070", "rx7900"): + self.assertEqual(self.check(f"strata-engine-0.1.60-linux-x86_64-hip-{variant}.tar.gz"), [("librocm_sysdeps_numa.so.1", "libatomic.so.1")], variant) + + def test_halo_and_cuda_need_nothing_else(self): + for name in ("strata-engine-0.1.60-linux-x86_64-hip-halo.tar.gz", "strata-engine-0.1.60-linux-x86_64-cuda-cuda13.tar.gz", + "strata-engine-0.1.60-linux-x86_64-cuda-cuda12.tar.gz", "strata-engine-0.1.59-linux-aarch64-cuda-cuda13.tar.gz"): + self.assertEqual(self.check(name), [], name) + + +if __name__ == "__main__": + unittest.main()