okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1a5c6dd19
main
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 4python 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) 36and is the same file (SameFileError broke the second binary's pass for the AMD packages).""" 37try : 38if os .path .exists (dst )and os .path .samefile (src ,dst ): 39return 40except OSError : 41pass 42shutil .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 : 56return path .startswith (SYSTEM_DIRS ) 57 58 59def bundled_anyway (name :str ,extra :list [str ]| tuple [str , ...]= ())-> bool : 60return 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.""" 65for 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 ())): 67try : 68done = subprocess .run (command ,capture_output = True ,text = True ,timeout = 30 ) 69except (OSError ,subprocess .SubprocessError ): 70continue 71if done .returncode == 0 and done .stdout .strip (): 72package = parse (done .stdout .splitlines ()[0 ]) 73ask = ["dpkg-query" ,"-W" ,"-f" ,"${Version}" ,package ]if command [0 ]== "dpkg-query" else ["rpm" ,"-q" ,"--qf" ,"%{VERSION}-%{RELEASE}" ,package ] 74try : 75version = subprocess .run (ask ,capture_output = True ,text = True ,timeout = 30 ).stdout .strip () 76except (OSError ,subprocess .SubprocessError ): 77version = "" 78return package ,version 79return 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 84came 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 85machine when it has them (/usr/share/doc/<package>/copyright, /usr/share/common-licenses/GPL-3).""" 86stem = name .split (".so" ,1 )[0 ] 87source = NOTICES / f" { stem } .txt" 88if not source .is_file (): 89f"WARNING: { name } is bundled but packaging/notices/ { stem } .txt does not exist" ,file = sys .stderr ) 90return 91folder = out / "licenses" 92folder .mkdir (parents = True ,exist_ok = True ) 93text = source .read_text (encoding = "utf-8" ) 94owner = (_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 96if origin : 97text += 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" ) 99if 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" ) 101if 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 : 106return 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.""" 114if not wanted : 115return True 116named = {m .group (0 ).lower ()for m in GFX .finditer (name )} 117return 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 : 124try : 125with path .open ("rb" )as stream : 126return stream .read (4 )== ELF_MAGIC 127except OSError : 128return 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.""" 133done = subprocess .run (["readelf" ,"-d" ,str (path )],capture_output = True ,text = True ) 134match = re .search (r"\(SONAME\)\s+Library soname: \[([^\]]+)\]" ,done .stdout ) 135return 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.""" 140env = dict (os .environ ) 141env ["LD_LIBRARY_PATH" ]= ":" .join (search + ([env ["LD_LIBRARY_PATH" ]]if env .get ("LD_LIBRARY_PATH" )else [])) 142done = subprocess .run (["ldd" ,str (binary )],capture_output = True ,text = True ,env = env ,timeout = 120 ) 143found ,missing = {}, [] 144for line in done .stdout .splitlines (): 145if "not found" in line : 146missing .append (line .split ("=>" )[0 ].strip ()) 147continue 148match = LDD_LINE .match (line ) 149if match : 150found [match .group (1 )]= match .group (2 ) 151return found ,missing 152 153 154def main (argv = None )-> int : 155ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 156ap .add_argument ("--binary" ,required = True ,type = Path ) 157ap .add_argument ("--search" ,action = "append" ,default = [],help = "a library folder to resolve against (repeatable)" ) 158ap .add_argument ("--out" ,required = True ,type = Path ) 159ap .add_argument ("--also" ,action = "append" ,default = [],help = "glob of dlopen'd libraries to add, searched in --search" ) 160ap .add_argument ("--data" ,action = "append" ,default = [],metavar = "SRC=DEST" ) 161ap .add_argument ("--data-glob" ,action = "append" ,default = [],help = "keep only data files matching one of these globs" ) 162ap .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" ) 164ap .add_argument ("--bundle-system" ,action = "append" ,default = [],metavar = "GLOB" , 165help = "a distribution library (soname glob) to bundle all the same, beside " + ", " .join (BUNDLE_FROM_SYSTEM )) 166a = ap .parse_args (argv ) 167a .out .mkdir (parents = True ,exist_ok = True ) 168copied :dict [str ,str ]= {} 169system :set [str ]= set () 170queue = [a .binary ] 171seen = set () 172while queue : 173item = queue .pop () 174if item in seen : 175continue 176seen .add (item ) 177found ,missing = dependencies (item ,a .search ) 178for name in missing : 179if not is_driver (name ): 180f"WARNING: { item . name } needs { name } , which ldd cannot find" ,file = sys .stderr ) 181for name ,path in found .items (): 182if is_driver (name ): 183continue 184if is_system (path )and not bundled_anyway (name ,a .bundle_system ): 185system .add (name ) 186continue 187if name in copied : 188continue 189real = Path (path ).resolve () 190_copy (real ,a .out / name )# the real file under its soname (a package holds no symlinks) 191copied [name ]= str (real ) 192if is_system (path ): 193copy_notice (name ,a .out ,path ) 194queue .append (a .out / name ) 195for pattern in a .also : 196hits = [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 )] 197if not hits : 198f"WARNING: --also { pattern !r } matched nothing in { a . search } " ,file = sys .stderr ) 199for hit in hits : 200if not hit .is_file ()or not is_elf (hit ): 201continue 202real = hit .resolve () 203if str (real )in copied .values ():# libX.so -> libX.so.1 -> libX.so.1.2.3: one file, one name (the soname) 204continue 205name = soname (real )or hit .name 206if name in copied : 207continue 208_copy (real ,a .out / name ) 209copied [name ]= str (real ) 210found ,missing = dependencies (a .out / name ,a .search ) 211for dep in missing : 212if not is_driver (dep ): 213f"WARNING: { name } needs { dep } , which ldd cannot find" ,file = sys .stderr ) 214for dep ,path in found .items (): 215if is_driver (dep )or dep in copied : 216continue 217if is_system (path )and not bundled_anyway (dep ,a .bundle_system ): 218system .add (dep ) 219else : 220_copy (Path (path ).resolve (),a .out / dep ) 221copied [dep ]= str (Path (path ).resolve ()) 222if is_system (path ): 223copy_notice (dep ,a .out ,path ) 224for spec in a .data : 225src ,_ ,dest = spec .partition ("=" ) 226if not dest : 227ap .error (f"--data { spec !r } is not SRC=DEST" ) 228for path in sorted (Path (src ).rglob ("*" )): 229if 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 ): 230target = a .out / dest / path .relative_to (src ) 231target .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" ) 234total = sum (p .stat ().st_size for p in a .out .rglob ("*" )if p .is_file ()) 235f"copied { len ( copied ) } libraries ( { total / ( 1 << 20 ):.1f } MiB incl. data) to { a . out } ; { len ( system ) } system libraries left to the OS" ) 236for name in sorted (copied ): 237f" { name } <- { copied [ name ] } " ) 238return 0 239 240 241if __name__ == "__main__" : 242raise SystemExit (main ())