package.py (9530B)
1 import argparse 2 import hashlib 3 import io 4 import json 5 import os 6 from pathlib import Path 7 import platform 8 import struct 9 import subprocess 10 import tarfile 11 import tempfile 12 13 14 ROOT = Path(__file__).resolve().parent.parent 15 16 17 def check_static_elf(path, arch): 18 machines = {"x86_64": 62, "aarch64": 183} 19 if arch not in machines: 20 raise ValueError("unsupported host architecture: " + arch) 21 with path.open("rb") as stream: 22 size = os.fstat(stream.fileno()).st_size 23 header = stream.read(64) 24 if len(header) != 64 or header[:6] != b"\x7fELF\x02\x01" or header[6] != 1: 25 raise ValueError("host tool is not a little-endian ELF64 executable: " + str(path)) 26 fields = struct.unpack("<HHIQQQIHHHHHH", header[16:]) 27 kind, machine, version, entry, offset = fields[:5] 28 header_size, stride, count = fields[7:10] 29 if kind not in (2, 3) or not entry or version != 1 or machine != machines[arch]: 30 raise ValueError("wrong host ELF type or architecture: " + str(path)) 31 if header_size != 64 or stride != 56 or not count or offset < 64 or offset + stride * count > size: 32 raise ValueError("invalid host ELF program headers: " + str(path)) 33 loaded = False 34 for index in range(count): 35 stream.seek(offset + stride * index) 36 segment = struct.unpack("<IIQQQQQQ", stream.read(56)) 37 tag, _, start, _, _, length, _, _ = segment 38 if start + length > size: 39 raise ValueError("truncated host ELF segment: " + str(path)) 40 if tag == 3: 41 raise ValueError("host tool needs a dynamic loader: " + str(path)) 42 loaded |= tag == 1 43 if tag == 2: 44 if not length or length % 16: 45 raise ValueError("invalid host ELF dynamic section: " + str(path)) 46 stream.seek(start) 47 for _ in range(length // 16): 48 dynamic_tag, _ = struct.unpack("<qQ", stream.read(16)) 49 if dynamic_tag == 0: 50 break 51 if dynamic_tag in (1, 0x7fffffff, 0x7ffffffd): 52 raise ValueError("host tool needs a shared library: " + str(path)) 53 else: 54 raise ValueError("unterminated host ELF dynamic section: " + str(path)) 55 if not loaded: 56 raise ValueError("host tool has no loadable segment: " + str(path)) 57 58 59 def check_static_host(prefix, arch=None): 60 prefix = prefix.resolve() 61 tools = prefix / "host/bin" 62 for required in ("clang", "clang++", "ld.lld", "llvm-ar", "llvm-readelf"): 63 if not (tools / required).is_file(): 64 raise ValueError("missing host tool: " + required) 65 seen = set() 66 for path in sorted(tools.iterdir()): 67 if not path.is_file() or not path.stat().st_mode & 0o111: 68 raise ValueError("host tool is not executable: " + str(path)) 69 try: 70 path.resolve(strict=True).relative_to(prefix) 71 except (ValueError, OSError, RuntimeError) as error: 72 raise ValueError("host tool points outside the toolchain: " + str(path)) from error 73 identity = (path.stat().st_dev, path.stat().st_ino) 74 if identity not in seen: 75 check_static_elf(path, arch or platform.machine()) 76 seen.add(identity) 77 78 79 def source_licenses(manifest, source_root, root): 80 licenses = {} 81 for line in manifest.decode().splitlines(): 82 if not line.strip() or line.lstrip().startswith("#"): 83 continue 84 component, archive, *_ = line.split() 85 for value in (component, archive): 86 if value in (".", "..") or any(character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" for character in value): 87 raise ValueError("invalid source name: " + value) 88 directory = source_root / archive.rsplit(".tar.", 1)[0] 89 if not directory.is_dir(): 90 raise ValueError("missing extracted source: " + str(directory)) 91 for path in sorted(directory.rglob("*")): 92 relative = path.relative_to(directory) 93 if (path.name.upper().startswith(("LICENSE", "COPYING", "COPYRIGHT", "NOTICE")) 94 or relative.parts[0].upper() == "LICENSES") and path.is_file(): 95 licenses[root + "/share/musllvm/licenses/" + component + "/" + relative.as_posix()] = path.read_bytes() 96 return licenses 97 98 99 def package(prefix, target, sources, output, source_root=None, llvm_mode="source"): 100 if not target or any(character not in "abcdefghijklmnopqrstuvwxyz0123456789_-" for character in target): 101 raise ValueError("invalid target: " + target) 102 if platform.system() != "Linux": 103 raise ValueError("packaging requires a Linux host") 104 prefix = prefix.resolve() 105 if llvm_mode not in ("source", "static"): 106 raise ValueError("packaging requires source or static LLVM") 107 mode = prefix / "share/musllvm/llvm-mode" 108 if mode.exists() and mode.read_text().strip() != llvm_mode: 109 raise ValueError("LLVM_MODE does not match the installed toolchain") 110 if llvm_mode == "static": 111 if not mode.is_file(): 112 raise ValueError("static LLVM build marker is missing") 113 check_static_host(prefix) 114 for required in ("host/bin/clang", "host/bin/ld.lld", "bin/" + target + "-cc", 115 "sysroot/usr/lib/libc.so", "share/musllvm/resource-version"): 116 if not (prefix / required).is_file(): 117 raise ValueError("incomplete toolchain: " + required) 118 for path in prefix.rglob("*"): 119 if path.is_symlink(): 120 if os.path.isabs(os.readlink(path)): 121 raise ValueError("absolute symlink: " + str(path)) 122 try: 123 path.resolve(strict=True).relative_to(prefix) 124 except (ValueError, FileNotFoundError, RuntimeError) as error: 125 raise ValueError("symlink outside the toolchain or missing its target: " + str(path)) from error 126 127 commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() 128 epoch = int(subprocess.check_output(["git", "show", "-s", "--format=%ct", commit], cwd=ROOT, text=True)) 129 host = platform.machine() + "-linux" 130 libc_name, libc_version = platform.libc_ver() 131 manifest = sources.read_bytes() 132 metadata = { 133 "commit": commit, 134 "host": host, 135 "host_libc": {"name": libc_name, "version": libc_version}, 136 "target": target, 137 "llvm_mode": llvm_mode, 138 "source_manifest_sha256": hashlib.sha256(manifest).hexdigest(), 139 } 140 if llvm_mode == "static": 141 metadata["build_host_libc"] = metadata["host_libc"] 142 metadata["host_libc"] = {"name": "musl"} 143 metadata["host_linkage"] = "static" 144 root = "musllvm-" + target 145 generated = { 146 root + "/share/musllvm/sources.list": manifest, 147 root + "/share/musllvm/build-info.json": (json.dumps(metadata, indent=2, sort_keys=True) + "\n").encode(), 148 } 149 generated.update(source_licenses(manifest, source_root or ROOT / "build/src", root)) 150 151 def normalize(info): 152 info.uid = info.gid = 0 153 info.uname = info.gname = "" 154 info.mtime = epoch 155 return info 156 157 def installed(info): 158 if info.name == root + "/.musllvm-config" or info.name in generated: 159 return None 160 return normalize(info) 161 162 output.mkdir(parents=True, exist_ok=True) 163 archive = output / (root + "-host-" + host + ".tar.xz") 164 descriptor, temporary = tempfile.mkstemp(prefix=".package-", dir=output) 165 os.close(descriptor) 166 try: 167 with tarfile.open(temporary, "w:xz", dereference=False) as stream: 168 stream.add(prefix, arcname=root, filter=installed) 169 for name, content in generated.items(): 170 info = tarfile.TarInfo(name) 171 info.size = len(content) 172 info.mode = 0o644 173 stream.addfile(normalize(info), io.BytesIO(content)) 174 os.replace(temporary, archive) 175 finally: 176 if os.path.exists(temporary): 177 os.unlink(temporary) 178 digest = hashlib.sha256() 179 with archive.open("rb") as stream: 180 for block in iter(lambda: stream.read(1024 * 1024), b""): 181 digest.update(block) 182 archive.with_name(archive.name + ".sha256").write_text(digest.hexdigest() + " " + archive.name + "\n") 183 return archive 184 185 186 def main(): 187 parser = argparse.ArgumentParser(description="Package a toolchain with bundled host tools") 188 parser.add_argument("--prefix", type=Path, required=True) 189 parser.add_argument("--target") 190 parser.add_argument("--sources", type=Path) 191 parser.add_argument("--output", type=Path) 192 parser.add_argument("--llvm-mode", choices=("source", "static"), default="source") 193 parser.add_argument("--check-host", action="store_true") 194 args = parser.parse_args() 195 if not args.check_host and not all((args.target, args.sources, args.output)): 196 parser.error("packaging requires --target, --sources and --output") 197 try: 198 if args.check_host: 199 check_static_host(args.prefix) 200 print("Verified static host tools: " + str(args.prefix)) 201 else: 202 print(package(args.prefix, args.target, args.sources, args.output, llvm_mode=args.llvm_mode)) 203 except (OSError, ValueError, subprocess.CalledProcessError) as error: 204 parser.exit(1, "package: " + str(error) + "\n") 205 206 207 if __name__ == "__main__": 208 main()