Files
nvdriver/tools/prepare_kernel_archive.py

76 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Leave strlen to Linux instead of linking Rust's precompiled, unhardened copy.
Select by exported symbol, not compiler-specific archive member hashes. Refuse
an unexpected layout rather than removing another helper along with strlen.
Only the generated copy is modified; the rustc archive remains intact.
"""
import argparse
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
def prepare(source: Path, destination: Path, ar: str = "ar", nm: str = "nm") -> None:
if not source.is_file():
raise FileNotFoundError(f"source archive not found: {source}")
if source.resolve() == destination.resolve():
raise ValueError("source and destination must differ")
output = subprocess.check_output(
[nm, "--format=posix", "--print-file-name", "--extern-only", "--defined-only", str(source)],
text=True, env=dict(os.environ, LC_ALL="C"),
)
pattern = re.compile(re.escape(str(source)) + r"\[(.+)\]: (\S+)\s+(\S)(?:\s|$)")
exports = {}
for line in output.splitlines():
if not line.strip():
continue
match = pattern.match(line)
if not match:
raise ValueError(f"unrecognised nm archive output: {line}")
member, symbol, kind = match.groups()
exports.setdefault(member, set()).add((symbol, kind))
kernel_c_builtins = {"strlen", "memcpy", "memmove", "memset", "memcmp", "bcmp"}
remove = [
member
for member, symbols in exports.items()
if any(s in kernel_c_builtins for s, _ in symbols)
]
members = subprocess.check_output(
[ar, "t", str(source)], text=True, env=dict(os.environ, LC_ALL="C")
).splitlines()
for member in remove:
sym_names = {s for s, _ in exports[member]}
sym_kinds = {k for _, k in exports[member]}
if (
not member.startswith("compiler_builtins-")
or not sym_names.issubset(kernel_c_builtins)
or not sym_kinds.issubset({"W", "T"})
or members.count(member) != 1
):
raise ValueError(f"cannot safely omit builtin member {member}: {sorted(exports[member])}")
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=destination.parent) as directory:
temporary = Path(directory) / "kernel.a"
shutil.copyfile(source, temporary)
if remove:
subprocess.run([ar, "d", str(temporary), *remove], check=True)
temporary.replace(destination)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("destination", type=Path)
parser.add_argument("--ar", default="ar")
parser.add_argument("--nm", default="nm")
args = parser.parse_args()
prepare(args.source, args.destination, args.ar, args.nm)
if __name__ == "__main__":
main()