#!/usr/bin/env python3 """生成内置原生构建能力的 Linux x86_64 dever。""" import argparse import json import os from pathlib import Path import shutil import struct import subprocess import tarfile import tempfile import tomllib from development import SOURCE, TRIPLE, digest, output FOOTER = b"DVRLOC01" RUST = "+1.95.0" MANIFEST = str(SOURCE / "rust/Cargo.toml") NATIVE_PACKAGES = ("libc6", "libc6-dev", "libgcc-s1", "zlib1g") def runtime(work): command = ["cargo", RUST, "build", "--manifest-path", MANIFEST, "-p", "dever-runtime", "--all-features", "--locked", "--offline", "--release", "--message-format=json"] with (work / "runtime.jsonl").open("w+") as events: subprocess.run(command, stdout=events, check=True) events.seek(0) for line in events: event = json.loads(line) if event["reason"] == "compiler-artifact": for name in event["filenames"]: path = Path(name) if path.suffix in {".rlib", ".so"}: yield f"crates/{path.name}", path elif event["reason"] == "build-script-executed" and event["linked_libs"]: for path in Path(event["out_dir"]).glob("*.a"): yield f"native/{path.name}", path def licenses(rust, work): notices = work / "THIRD-PARTY.txt" docs = rust / "share/doc/rust" packages = json.loads(output( "cargo", RUST, "metadata", "--manifest-path", MANIFEST, "--locked", "--offline", "--all-features", "--filter-platform", TRIPLE, "--format-version", "1", ))["packages"] with notices.open("wb") as stream: def copy_notice(name, path): stream.write(f"\n=== {name} ===\n".encode()) with path.open("rb") as notice: shutil.copyfileobj(notice, stream) stream.write(b"\n") stream.write(b"Dever distribution: third-party notices\n") for path in sorted(docs.rglob("*")): if path.is_file(): copy_notice(f"Rust {RUST[1:]}/{path.relative_to(docs)}", path) for name, version in (line.split("\t") for line in output( "dpkg-query", "-W", *NATIVE_PACKAGES).splitlines()): copy_notice(f"Debian {name} {version}", Path("/usr/share/doc") / name.split(":")[0] / "copyright") for path in sorted(Path("/usr/share/common-licenses").iterdir()): if path.is_file() and not path.is_symlink(): copy_notice(f"Debian common licenses/{path.name}", path) for package in packages: if not package["source"]: continue name = f'{package["name"]} {package["version"]}' stream.write(f'\n{name}: {package["license"]}\n'.encode()) directory = Path(package["manifest_path"]).parent files = {path for path in directory.iterdir() if path.is_file() and path.name.upper().startswith(("LICENSE", "LICENCE", "COPYING", "COPYRIGHT", "NOTICE", "UNLICENSE"))} if package["license_file"]: files.add(directory / package["license_file"]) for path in sorted(files): copy_notice(f"{name}/{path.name}", path) return notices def inputs(work): rust = Path(output("rustc", RUST, "--print", "sysroot")) if f"host: {TRIPLE}" not in output("rustc", RUST, "-vV"): raise RuntimeError(f"expected a {TRIPLE} release environment") standard = rust / "lib/rustlib" / TRIPLE engine, = (rust / "lib").glob("librustc_driver-*.so") backend, = (rust / "lib").glob("libLLVM.so.*") native = Path("/usr/lib/x86_64-linux-gnu") selected = { "THIRD-PARTY.txt": licenses(rust, work), "bin/compile": rust / "bin/rustc", "bin/link": standard / "bin/rust-lld", "lib/engine": engine, "lib/backend": backend, "lib/zlib": native / "libz.so.1", } for path in (standard / "lib").iterdir(): if path.suffix in {".rlib", ".rmeta"}: selected[f"sysroot/lib/rustlib/{TRIPLE}/lib/{path.name}"] = path for name in ("Scrt1.o", "crti.o", "crtn.o", "libc_nonshared.a", "libdl.a", "librt.a", "libpthread.a", "libutil.a"): selected[f"crt/{name}"] = native / name for library in ("libc", "libm", "libgcc_s"): suffix = "1" if library == "libgcc_s" else "6" selected[f"crt/{library}.so"] = native / f"{library}.so.{suffix}" for name, path in runtime(work): previous = selected.setdefault(name, path) if previous != path: raise RuntimeError(f"conflicting build resource {name}: {previous} and {path}") return selected def append_resources(destination, selected, work): with subprocess.Popen(["xz", "-3", "-T2"], stdin=subprocess.PIPE, stdout=destination) as xz: with tarfile.open(fileobj=xz.stdin, mode="w|") as archive: for name, path in sorted(selected.items()): if name.startswith(("bin/", "lib/")) or path.suffix == ".so": stripped = work / "elf" shutil.copyfile(path, stripped) subprocess.run(["strip", "--strip-unneeded", str(stripped)], check=True) path = stripped path = path.resolve(strict=True) info = archive.gettarinfo(str(path), arcname=name) info.mode, info.mtime, info.uid, info.gid = 0o600, 0, 0, 0 info.uname = info.gname = "" with path.open("rb") as source: archive.addfile(info, source) xz.stdin.close() if xz.wait(): raise RuntimeError("compressing native build resources failed") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--compiler", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() compiler = args.compiler.resolve(strict=True) destination = args.output.absolute() version = tomllib.loads((SOURCE / "rust/Cargo.toml").read_text())["package"]["version"] if output(str(compiler), "--version") != f"dever {version}": parser.error("compiler and source versions differ") with compiler.open("rb") as source: if source.read(4) != b"\x7fELF": parser.error("expected a native ELF compiler") source.seek(-len(FOOTER), os.SEEK_END) if source.read() == FOOTER: parser.error("compiler already contains a native build image") if destination.exists(): parser.error("output must be a new path") with tempfile.TemporaryDirectory(prefix="dever-native-", dir=destination.parent) as work: work = Path(work) selected = inputs(work) stage = work / "dever" shutil.copyfile(compiler, stage) with stage.open("r+b", buffering=0) as stream: start = stream.seek(0, os.SEEK_END) append_resources(stream, selected, work) end = stream.seek(0, os.SEEK_END) stream.write(struct.pack("