"""Find dynamic imports of specified symbols in a checksum-pinned release archive.""" import argparse import csv import hashlib from pathlib import Path import re import shutil import subprocess import tarfile import tempfile def scan(args): symbols = set(args.symbol) with args.archive.open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != args.sha256: raise ValueError("release archive checksum mismatch") results = [] dependencies = [] files = 0 with tempfile.TemporaryDirectory() as temp, tarfile.open(args.archive, "r|gz") as archive: elf = Path(temp) / "member" for entry in archive: if not entry.isfile(): continue with archive.extractfile(entry) as stream: header = stream.read(4) if header != b"\x7fELF": continue with elf.open("wb") as copy: copy.write(header) shutil.copyfileobj(stream, copy) files += 1 report = subprocess.check_output(["readelf", "-Wd", "--dyn-syms", elf], text=True) needed = ",".join(re.findall(r"\(NEEDED\)[^\n]*?\[([^\]]+)\]", report)) path = entry.name.removeprefix("./") if args.dependencies: dependencies.append((path, needed)) for line in report.splitlines(): cols = line.split() if len(cols) < 8 or cols[6] != "UND" or not cols[0].removesuffix(":").isdigit(): continue if cols[7].split("@", 1)[0] in symbols: results.append((path, cols[7], cols[4], needed)) if not files: raise ValueError("release archive contains no regular ELF files") with args.output.open("x") as out: table = csv.writer(out, delimiter="\t", lineterminator="\n") table.writerow(("release_path", "import", "binding", "needed")) table.writerows(sorted(results)) if args.dependencies: with args.dependencies.open("x") as out: table = csv.writer(out, delimiter="\t", lineterminator="\n") table.writerow(("release_path", "needed")) table.writerows(sorted(dependencies)) for name in sorted(symbols): count = sum(symbol.split("@", 1)[0] == name for _, symbol, _, _ in results) print(f"{name}\t{count}") print(f"Scanned {files} regular ELF files") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("sha256") parser.add_argument("output", type=Path) parser.add_argument("symbol", nargs="+") parser.add_argument("--dependencies", type=Path, help="list DT_NEEDED entries for every regular ELF") scan(parser.parse_args())