vinix-ports / tests / library-upgrades.py
139 lines · 131 sloc · 6.95 KB · e301ebe826767c0a97c8d99095f38502558657ed
Raw
1"""Compare the release's shared-library interface to its package-owned replacement."""
2import argparse
3import csv
4import hashlib
5from pathlib import Path
6import re
7import shutil
8import subprocess
9import tarfile
10import tempfile
11
12
13def interface(path, arch):
14 report = subprocess.check_output(["readelf", "-W", "-h", "-d", "--dyn-syms", path], text=True)
15 machine = "AArch64" if arch == "aarch64" else "Advanced Micro Devices X86-64"
16 fields = [line.strip() for line in report.splitlines()]
17 if not any(line.startswith("Machine:") and line.split(":", 1)[1].strip() == machine for line in fields):
18 raise ValueError(f"unexpected ELF target in {path}")
19 names = [line.split("[", 1)[1].split("]", 1)[0] for line in fields if "(SONAME)" in line]
20 if len(names) > 1:
21 raise ValueError(f"multiple SONAME entries in {path}")
22 soname = names[0] if names else ""
23 exports = set()
24 for line in fields:
25 row = line.split()
26 if (len(row) >= 8 and row[0].endswith(":") and row[0][:-1].isdigit()
27 and row[4] in ("GLOBAL", "WEAK", "UNIQUE") and row[5] in ("DEFAULT", "PROTECTED")
28 and row[6] not in ("UND", "ABS")):
29 kind = "FUNC" if row[3] in ("FUNC", "IFUNC") else row[3]
30 exports.add((row[7], kind, row[2] if kind in ("OBJECT", "TLS") else ""))
31 if not exports:
32 raise ValueError(f"no exported dynamic symbols in {path}")
33 return soname, exports
34
35
36def package_owners(client):
37 owners = {}
38 for desc in (client / "db/local").glob("*/desc"):
39 name, = [block.splitlines()[1] for block in desc.read_text().split("\n\n") if block.startswith("%NAME%\n")]
40 records = desc.with_name("files").read_text().split("\n\n")
41 for path in next((b.splitlines()[1:] for b in records if b.startswith("%FILES%\n")), []):
42 if not path.endswith("/"):
43 if path in owners:
44 raise ValueError(f"duplicate owner for {path}")
45 owners[path] = name
46 return owners
47
48
49def run(args):
50 with args.initramfs.open("rb") as source:
51 if hashlib.file_digest(source, "sha256").hexdigest() != args.sha256:
52 raise ValueError("release initramfs checksum mismatch")
53 subprocess.run([args.auditor, args.arch, args.client], check=True)
54 root = (args.client / "root").resolve()
55 owners = package_owners(args.client)
56 expected = {path: (package, soname) for package, path, soname in args.library or []}
57 if len(expected) != len(args.library or []):
58 raise ValueError("each release path must occur only once")
59 results = {}
60 coverage = {}
61 installed_interfaces = {}
62 with tempfile.TemporaryDirectory() as temp, tarfile.open(args.initramfs, "r|gz") as contents:
63 for entry in contents:
64 path = entry.name.removeprefix("./")
65 if args.system_providers:
66 original = Path(path)
67 if (not entry.isfile() or original.parent.as_posix() not in ("lib", "usr/lib") or
68 not re.search(r"\.so($|\.)", original.name)):
69 continue
70 elif path not in expected:
71 continue
72 if not entry.isfile() or path in coverage:
73 raise ValueError(f"expected one regular release library at {path}")
74 reference = Path(temp) / "reference"
75 with contents.extractfile(entry) as source:
76 magic = source.read(4)
77 if args.system_providers and magic != b"\x7fELF":
78 continue
79 with reference.open("wb") as copy:
80 copy.write(magic)
81 shutil.copyfileobj(source, copy)
82 old_name, old = interface(reference, args.arch)
83 if args.system_providers and not old_name:
84 coverage[path] = ("", "", "no SONAME")
85 continue
86 package, name = expected.get(path, ("", old_name))
87 if not name or Path(name).name != name or old_name != name:
88 raise ValueError(f"{path}: expected {name}, found {old_name}")
89 alias = Path(path).with_name(name)
90 alias_owner = owners.get(alias.as_posix())
91 if args.system_providers:
92 if not alias_owner:
93 coverage[path] = (name, "", "provider absent")
94 continue
95 package = alias_owner
96 current = (root / alias).resolve()
97 current_path = current.relative_to(root)
98 if package != alias_owner or package != owners.get(current_path.as_posix()):
99 raise ValueError(f"{package} must own both {alias} and {current_path}")
100 if current not in installed_interfaces:
101 installed_interfaces[current] = interface(current, args.arch)
102 new_name, new = installed_interfaces[current]
103 if new_name != name:
104 raise ValueError(f"{current_path}: expected {name}, found {new_name}")
105 missing = sorted(old - new)
106 results[path] = (package, name, current_path, len(old), len(new), len(missing),
107 ",".join(symbol for symbol, _, _ in missing))
108 coverage[path] = (name, package, "missing exports" if missing else "compared")
109 if expected and set(results) != set(expected):
110 raise ValueError(f"missing release libraries: {sorted(set(expected) - set(results))}")
111 if args.system_providers:
112 if not coverage:
113 raise ValueError("no release system libraries found")
114 with args.system_providers.open("x") as stream:
115 table = csv.writer(stream, delimiter="\t", lineterminator="\n")
116 table.writerow(("release_path", "soname", "installed_owner", "status"))
117 table.writerows((path, *record) for path, record in sorted(coverage.items()))
118 with args.output.open("x") as stream:
119 table = csv.writer(stream, delimiter="\t", lineterminator="\n")
120 table.writerow(("release_path", "package", "soname", "installed_path", "old_exports",
121 "new_exports", "missing_count", "missing_symbols"))
122 for path, result in sorted(results.items()):
123 table.writerow((path, *result))
124 if any(row[-2] for row in results.values()):
125 return 1
126 return 2 if len(coverage) > len(results) else 0
127
128
129if __name__ == "__main__":
130 parser = argparse.ArgumentParser(description=__doc__)
131 parser.add_argument("arch", choices=("aarch64", "x86_64"))
132 for arg in ("client", "auditor", "initramfs", "output"):
133 parser.add_argument(arg, type=Path)
134 parser.add_argument("sha256", help="published initramfs digest")
135 selection = parser.add_mutually_exclusive_group(required=True)
136 selection.add_argument("--library", nargs=3, action="append", metavar=("PACKAGE", "RELEASE_PATH", "SONAME"))
137 selection.add_argument("--system-providers", type=Path, metavar="REPORT",
138 help="compare all regular shared libraries in /lib and /usr/lib and record every provider")
139 raise SystemExit(run(parser.parse_args()))
140