vinix-ports / tests / release-imports.py
59 lines · 55 sloc · 2.32 KB · e301ebe826767c0a97c8d99095f38502558657ed
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 files = 0
20 with tempfile.TemporaryDirectory() as temp, tarfile.open(args.archive, "r|gz") as archive:
21 elf = Path(temp) / "member"
22 for entry in archive:
23 if not entry.isfile():
24 continue
25 with archive.extractfile(entry) as stream:
26 header = stream.read(4)
27 if header != b"\x7fELF":
28 continue
29 with elf.open("wb") as copy:
30 copy.write(header)
31 shutil.copyfileobj(stream, copy)
32 files += 1
33 report = subprocess.check_output(["readelf", "-Wd", "--dyn-syms", elf], text=True)
34 needed = ",".join(re.findall(r"\(NEEDED\)[^\n]*?\[([^\]]+)\]", report))
35 for line in report.splitlines():
36 cols = line.split()
37 if len(cols) < 8 or cols[6] != "UND" or not cols[0].removesuffix(":").isdigit():
38 continue
39 if cols[7].split("@", 1)[0] in symbols:
40 results.append((entry.name.removeprefix("./"), cols[7], cols[4], needed))
41 if not files:
42 raise ValueError("release archive contains no regular ELF files")
43 with args.output.open("x") as out:
44 table = csv.writer(out, delimiter="\t", lineterminator="\n")
45 table.writerow(("release_path", "import", "binding", "needed"))
46 table.writerows(sorted(results))
47 for name in sorted(symbols):
48 count = sum(symbol.split("@", 1)[0] == name for _, symbol, _, _ in results)
49 print(f"{name}\t{count}")
50 print(f"Scanned {files} regular ELF files")
51
52
53if __name__ == "__main__":
54 parser = argparse.ArgumentParser(description=__doc__)
55 parser.add_argument("archive", type=Path)
56 parser.add_argument("sha256")
57 parser.add_argument("output", type=Path)
58 parser.add_argument("symbol", nargs="+")
59 scan(parser.parse_args())
60