vinix-ports / tests / release-imports.py
69 lines · 65 sloc · 2.8 KB
Raw
1"""Find dynamic imports of specified symbols in a checksum-pinned release archive."""
2import argparse
3import csv
4import hashlib
5from pathlib import Path
6import re
7import shutil
8import subprocess
9import tarfile
10import tempfile
11
12
13def scan(args):
14 symbols = set(args.symbol)
15 with args.archive.open("rb") as stream:
16 if hashlib.file_digest(stream, "sha256").hexdigest() != args.sha256:
17 raise ValueError("release archive checksum mismatch")
18 results = []
19 dependencies = []
20 files = 0
21 with tempfile.TemporaryDirectory() as temp, tarfile.open(args.archive, "r|gz") as archive:
22 elf = Path(temp) / "member"
23 for entry in archive:
24 if not entry.isfile():
25 continue
26 with archive.extractfile(entry) as stream:
27 header = stream.read(4)
28 if header != b"\x7fELF":
29 continue
30 with elf.open("wb") as copy:
31 copy.write(header)
32 shutil.copyfileobj(stream, copy)
33 files += 1
34 report = subprocess.check_output(["readelf", "-Wd", "--dyn-syms", elf], text=True)
35 needed = ",".join(re.findall(r"\(NEEDED\)[^\n]*?\[([^\]]+)\]", report))
36 path = entry.name.removeprefix("./")
37 if args.dependencies:
38 dependencies.append((path, needed))
39 for line in report.splitlines():
40 cols = line.split()
41 if len(cols) < 8 or cols[6] != "UND" or not cols[0].removesuffix(":").isdigit():
42 continue
43 if cols[7].split("@", 1)[0] in symbols:
44 results.append((path, cols[7], cols[4], needed))
45 if not files:
46 raise ValueError("release archive contains no regular ELF files")
47 with args.output.open("x") as out:
48 table = csv.writer(out, delimiter="\t", lineterminator="\n")
49 table.writerow(("release_path", "import", "binding", "needed"))
50 table.writerows(sorted(results))
51 if args.dependencies:
52 with args.dependencies.open("x") as out:
53 table = csv.writer(out, delimiter="\t", lineterminator="\n")
54 table.writerow(("release_path", "needed"))
55 table.writerows(sorted(dependencies))
56 for name in sorted(symbols):
57 count = sum(symbol.split("@", 1)[0] == name for _, symbol, _, _ in results)
58 print(f"{name}\t{count}")
59 print(f"Scanned {files} regular ELF files")
60
61
62if __name__ == "__main__":
63 parser = argparse.ArgumentParser(description=__doc__)
64 parser.add_argument("archive", type=Path)
65 parser.add_argument("sha256")
66 parser.add_argument("output", type=Path)
67 parser.add_argument("symbol", nargs="+")
68 parser.add_argument("--dependencies", type=Path, help="list DT_NEEDED entries for every regular ELF")
69 scan(parser.parse_args())
70