"""Check packaged ELF load segments against the page size of the released Vinix kernel.""" import argparse import csv import struct import subprocess import sys import tarfile from pathlib import Path def check(stream, size, arch): header = stream.read(64) if not header.startswith(b"\x7fELF"): return None machine, page = (183, 16384) if arch == "aarch64" else (62, 4096) if len(header) != 64 or header[4:7] != bytes((2, 1, 1)): raise ValueError("invalid ELF64 little-endian header") kind, target = struct.unpack_from(" size: raise ValueError("invalid program header table") remaining = offset - len(header) while remaining: chunk = stream.read(min(remaining, 65536)) if not chunk: raise ValueError("truncated data before the program headers") remaining -= len(chunk) loads = 0 for index in range(count): kind, _, off, addr, _, filesz, memsz, _ = struct.unpack(" memsz or off > size or filesz > size - off: raise ValueError(f"invalid PT_LOAD {index}") if memsz: loads += 1 if off % page != addr % page: return f"PT_LOAD {index}, offset 0x{off:x}, vaddr 0x{addr:x}, page {page}" if not loads: raise ValueError("ELF lacks a nonempty PT_LOAD") return "" def audit(args): writer = csv.writer(sys.stdout, delimiter="\t", lineterminator="\n") writer.writerow(["archive", "member", "result", "detail"]) incompatible = 0 for path in args.archives: total = failed = 0 with subprocess.Popen(["zstd", "-qdc", "--", path], stdout=subprocess.PIPE) as proc: with tarfile.open(fileobj=proc.stdout, mode="r|") as archive: for member in archive: if not member.isfile(): continue with archive.extractfile(member) as contents: try: reason = check(contents, member.size, args.arch) except (ValueError, struct.error) as error: raise ValueError(f"{path}:{member.name}: {error}") from error if reason is None: continue total += 1 failed += bool(reason) writer.writerow([path.name, member.name, "incompatible" if reason else "compatible", reason]) # Drain any padding beyond the final tar member before checking zstd. while proc.stdout.read(65536): pass if proc.wait(): raise ValueError(f"could not decompress {path}") writer.writerow([path.name, "", "summary", f"{failed} incompatible of {total} executables and DSOs"]) incompatible += failed return int(bool(incompatible) and not args.inventory) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("arch", choices=("aarch64", "x86_64")) parser.add_argument("archives", type=Path, nargs="+") parser.add_argument("--inventory", action="store_true", help="record incompatible files without failing the survey") sys.exit(audit(parser.parse_args()))