musllvm

musl and LLVM cross-toolchain build system
git clone https://git.daat.foo/musllvm.git
Log | Files | Refs | README | LICENSE

test_release.py (17377B)


      1 import hashlib
      2 import importlib.util
      3 import json
      4 import os
      5 from pathlib import Path
      6 import platform
      7 import shutil
      8 import struct
      9 import subprocess
     10 import tarfile
     11 import tempfile
     12 import unittest
     13 from unittest.mock import patch
     14 
     15 
     16 ROOT = Path(__file__).resolve().parent.parent
     17 SPEC = importlib.util.spec_from_file_location("package", ROOT / "scripts/package.py")
     18 PACKAGE = importlib.util.module_from_spec(SPEC)
     19 SPEC.loader.exec_module(PACKAGE)
     20 ARCHIVES = [f"musllvm-{arch}-linux-musl-host-x86_64-linux.tar.xz" for arch in ("x86_64", "aarch64")]
     21 FAKE_GH = r'''#!/usr/bin/env python3
     22 import json
     23 import os
     24 import sys
     25 from pathlib import Path
     26 
     27 args = sys.argv[1:]
     28 with open(os.environ["FAKE_GH_LOG"], "a") as stream:
     29     stream.write(json.dumps(args) + "\n")
     30 action = args[1]
     31 if action == os.environ.get("FAKE_GH_FAIL"):
     32     sys.exit(1)
     33 if action == "view":
     34     state = os.environ.get("FAKE_RELEASE", "missing")
     35     if state == "missing":
     36         sys.exit("release not found")
     37     print("true" if state == "draft" else "false")
     38 elif action in ("create", "upload"):
     39     for name in ("SHA256SUMS", "sources.list"):
     40         if not Path(name).is_file():
     41             sys.exit(2)
     42 '''
     43 FAKE_GIT = r'''#!/usr/bin/env python3
     44 import os
     45 import sys
     46 if "rev-parse" in sys.argv:
     47     print(os.environ["FAKE_GIT_SHA"])
     48 else:
     49     print("2026-10-12")
     50 '''
     51 
     52 
     53 def host_elf(arch="x86_64", pie=False, interpreter=False, needed=False):
     54     count = 1 + interpreter + (pie or needed)
     55     start = 64 + 56 * count
     56     payload = b"\x90"
     57     segments = []
     58     if interpreter:
     59         loader = b"/lib/fixture-loader.so\0"
     60         segments.append((3, start + len(payload), len(loader)))
     61         payload += loader
     62     if pie or needed:
     63         dynamic = struct.pack("<qQ", 1 if needed else 0x6ffffffb, 1)
     64         dynamic += struct.pack("<qQ", 0, 0)
     65         segments.append((2, start + len(payload), len(dynamic)))
     66         payload += dynamic
     67     size = start + len(payload)
     68     header = b"\x7fELF\x02\x01\x01" + b"\0" * 9
     69     header += struct.pack("<HHIQQQIHHHHHH", 3 if pie else 2,
     70                           {"x86_64": 62, "aarch64": 183}[arch], 1, 0x400000 + start,
     71                           64, 0, 0, 64, 56, count, 0, 0, 0)
     72     program = struct.pack("<IIQQQQQQ", 1, 5, 0, 0x400000, 0x400000, size, size, 4096)
     73     for kind, offset, length in segments:
     74         program += struct.pack("<IIQQQQQQ", kind, 4, offset, 0x400000 + offset, 0,
     75                                length, length, 8)
     76     return header + program + payload
     77 
     78 
     79 class StaticHostTests(unittest.TestCase):
     80     def setUp(self):
     81         self.temporary = tempfile.TemporaryDirectory(prefix="musllvm-static-test-")
     82         self.addCleanup(self.temporary.cleanup)
     83         self.path = Path(self.temporary.name) / "clang"
     84 
     85     def test_static_executables_and_static_pie_for_both_hosts(self):
     86         for arch in ("x86_64", "aarch64"):
     87             for pie in (False, True):
     88                 with self.subTest(arch=arch, pie=pie):
     89                     self.path.write_bytes(host_elf(arch, pie=pie))
     90                     PACKAGE.check_static_elf(self.path, arch)
     91 
     92     def test_dynamic_loader_is_rejected_without_a_needed_entry(self):
     93         self.path.write_bytes(host_elf(interpreter=True))
     94         with self.assertRaisesRegex(ValueError, "dynamic loader"):
     95             PACKAGE.check_static_elf(self.path, "x86_64")
     96 
     97     def test_needed_library_is_rejected_without_a_loader(self):
     98         self.path.write_bytes(host_elf(pie=True, needed=True))
     99         with self.assertRaisesRegex(ValueError, "shared library"):
    100             PACKAGE.check_static_elf(self.path, "x86_64")
    101 
    102     def test_wrong_host_and_malformed_elf_are_rejected(self):
    103         valid = host_elf()
    104         for content in (b"#!/bin/sh\n", valid[:40], valid[:80],
    105                         valid[:5] + b"\x02" + valid[6:],
    106                         valid[:16] + struct.pack("<H", 1) + valid[18:]):
    107             with self.subTest(content=content[:20]):
    108                 self.path.write_bytes(content)
    109                 with self.assertRaises(ValueError):
    110                     PACKAGE.check_static_elf(self.path, "x86_64")
    111         self.path.write_bytes(host_elf("aarch64"))
    112         with self.assertRaisesRegex(ValueError, "architecture"):
    113             PACKAGE.check_static_elf(self.path, "x86_64")
    114 
    115     def test_truncated_or_unterminated_dynamic_section_is_rejected(self):
    116         content = host_elf(pie=True)
    117         for invalid in (content[:-1], content[:-16] + struct.pack("<qQ", 21, 0)):
    118             with self.subTest(length=len(invalid)):
    119                 self.path.write_bytes(invalid)
    120                 with self.assertRaises(ValueError):
    121                     PACKAGE.check_static_elf(self.path, "x86_64")
    122 
    123 
    124 class PackageTests(unittest.TestCase):
    125     def setUp(self):
    126         self.temporary = tempfile.TemporaryDirectory(prefix="musllvm-package-test-")
    127         self.addCleanup(self.temporary.cleanup)
    128         self.root = Path(self.temporary.name)
    129         self.prefix = self.root / "original"
    130         self.output = self.root / "releases"
    131         self.target = "x86_64-linux-musl"
    132         for relative in ("host/bin/clang", "host/bin/ld.lld", "bin/" + self.target + "-cc",
    133                          "sysroot/usr/lib/libc.so", "share/musllvm/resource-version", ".musllvm-config"):
    134             path = self.prefix / relative
    135             path.parent.mkdir(parents=True, exist_ok=True)
    136             path.write_text("fixture\n")
    137         (self.prefix / "host/bin/clang").chmod(0o755)
    138         (self.prefix / "libexec").mkdir()
    139         (self.prefix / "libexec/clang").symlink_to("../host/bin/clang")
    140         (self.prefix / "sysroot/lib").mkdir()
    141         (self.prefix / "sysroot/lib/ld-musl-x86_64.so.1").symlink_to("../usr/lib/libc.so")
    142         self.sources = self.root / "sources.list"
    143         self.sources.write_text("llvm llvm-test.tar.xz " + "0" * 64 + " https://example.invalid/llvm\n")
    144         self.source_root = self.root / "src"
    145         for relative in ("llvm-test/LICENSE.TXT", "llvm-test/libcxx/LICENSE.TXT",
    146                          "llvm-test/LICENSES/exceptions/test-exception"):
    147             path = self.source_root / relative
    148             path.parent.mkdir(parents=True, exist_ok=True)
    149             path.write_text(relative + "\n")
    150 
    151     def package(self, target=None, mode="source"):
    152         return PACKAGE.package(self.prefix, target or self.target, self.sources, self.output,
    153                                self.source_root, llvm_mode=mode)
    154 
    155     def install_static_host(self):
    156         for name in ("clang", "clang++", "ld.lld", "llvm-ar", "llvm-readelf"):
    157             path = self.prefix / "host/bin" / name
    158             path.write_bytes(host_elf(platform.machine()))
    159             path.chmod(0o755)
    160         (self.prefix / "share/musllvm/llvm-mode").write_text("static\n")
    161 
    162     def test_static_cross_package_records_the_compiler_host_runtime(self):
    163         self.install_static_host()
    164         target = "aarch64-linux-musl" if platform.machine() == "x86_64" else "x86_64-linux-musl"
    165         (self.prefix / "bin" / (target + "-cc")).write_text("fixture\n")
    166         with patch.object(PACKAGE.platform, "libc_ver", return_value=("glibc", "2.39")):
    167             archive = self.package(target, mode="static")
    168         with tarfile.open(archive) as stream:
    169             metadata = json.load(stream.extractfile("musllvm-" + target + "/share/musllvm/build-info.json"))
    170         self.assertEqual(metadata["llvm_mode"], "static")
    171         self.assertEqual(metadata["host"], platform.machine() + "-linux")
    172         self.assertEqual(metadata["host_libc"], {"name": "musl"})
    173         self.assertEqual(metadata["host_linkage"], "static")
    174         self.assertEqual(metadata["build_host_libc"], {"name": "glibc", "version": "2.39"})
    175 
    176     def test_static_packaging_checks_every_host_executable(self):
    177         self.install_static_host()
    178         extra = self.prefix / "host/bin/llvm-extra"
    179         extra.write_bytes(host_elf(platform.machine(), needed=True))
    180         extra.chmod(0o755)
    181         with self.assertRaisesRegex(ValueError, "shared library"):
    182             self.package(mode="static")
    183         self.assertFalse(self.output.exists())
    184 
    185     def test_packaging_rejects_a_missing_or_wrong_build_mode(self):
    186         self.install_static_host()
    187         with self.assertRaisesRegex(ValueError, "does not match"):
    188             self.package()
    189         (self.prefix / "share/musllvm/llvm-mode").unlink()
    190         with self.assertRaisesRegex(ValueError, "marker is missing"):
    191             self.package(mode="static")
    192 
    193     def test_static_host_requires_bundled_executable_tools(self):
    194         self.install_static_host()
    195         path = self.prefix / "host/bin/llvm-ar"
    196         path.chmod(0o644)
    197         with self.assertRaisesRegex(ValueError, "not executable"):
    198             self.package(mode="static")
    199         path.unlink()
    200         path.symlink_to("/bin/sh")
    201         with self.assertRaisesRegex(ValueError, "outside"):
    202             self.package(mode="static")
    203 
    204     def test_archive_preserves_links_modes_and_source_metadata(self):
    205         archive = self.package()
    206         digest, filename = archive.with_name(archive.name + ".sha256").read_text().split()
    207         self.assertEqual(digest, hashlib.sha256(archive.read_bytes()).hexdigest())
    208         self.assertEqual(filename, archive.name)
    209         self.assertIn("host-" + platform.machine() + "-linux", filename)
    210         root = "musllvm-" + self.target
    211         with tarfile.open(archive) as stream:
    212             self.assertEqual(stream.getmember(root + "/libexec/clang").linkname, "../host/bin/clang")
    213             self.assertEqual(stream.getmember(root + "/host/bin/clang").mode, 0o755)
    214             self.assertNotIn(root + "/.musllvm-config", stream.getnames())
    215             self.assertEqual(stream.extractfile(root + "/share/musllvm/sources.list").read(), self.sources.read_bytes())
    216             metadata = json.load(stream.extractfile(root + "/share/musllvm/build-info.json"))
    217             self.assertEqual(metadata["target"], self.target)
    218             self.assertEqual(metadata["llvm_mode"], "source")
    219             self.assertEqual(metadata["source_manifest_sha256"], hashlib.sha256(self.sources.read_bytes()).hexdigest())
    220             for relative in ("LICENSE.TXT", "libcxx/LICENSE.TXT", "LICENSES/exceptions/test-exception"):
    221                 self.assertEqual(stream.extractfile(root + "/share/musllvm/licenses/llvm/" + relative).read(),
    222                                  (self.source_root / "llvm-test" / relative).read_bytes())
    223             self.assertEqual(len({member.mtime for member in stream}), 1)
    224             extracted = self.root / "unpacked"
    225             stream.extractall(extracted, filter="data")
    226         relocated = extracted / root
    227         self.assertEqual((relocated / "libexec/clang").resolve(), relocated / "host/bin/clang")
    228         self.assertEqual((relocated / "sysroot/lib/ld-musl-x86_64.so.1").read_bytes(), b"fixture\n")
    229 
    230     def test_archive_is_independent_of_file_timestamps(self):
    231         archive = self.package()
    232         first = archive.read_bytes()
    233         os.utime(self.prefix / "host/bin/clang", (1, 1))
    234         self.assertEqual(self.package().read_bytes(), first)
    235 
    236     def test_absolute_or_escaping_links_are_rejected(self):
    237         external = self.root / "external"
    238         external.write_text("fixture")
    239         link = self.prefix / "libexec/bad"
    240         for destination in (str(external), str(self.prefix / "host/bin/clang"), "../../external", "missing"):
    241             with self.subTest(destination=destination):
    242                 link.symlink_to(destination)
    243                 with self.assertRaises(ValueError):
    244                     self.package()
    245                 link.unlink()
    246         self.assertFalse(self.output.exists())
    247 
    248     def test_incomplete_toolchains_and_unsafe_targets_are_rejected(self):
    249         (self.prefix / "host/bin/ld.lld").unlink()
    250         with self.assertRaisesRegex(ValueError, "incomplete toolchain"):
    251             self.package()
    252         with self.assertRaisesRegex(ValueError, "invalid target"):
    253             self.package("../../escape")
    254 
    255     def test_failed_packaging_keeps_the_existing_archive(self):
    256         archive = self.package()
    257         first = archive.read_bytes()
    258         with patch.object(PACKAGE.tarfile, "open", side_effect=OSError("fixture write failure")):
    259             with self.assertRaises(OSError):
    260                 self.package()
    261         self.assertEqual(archive.read_bytes(), first)
    262         self.assertFalse(list(self.output.glob(".package-*")))
    263 
    264     def test_new_core_component_keeps_its_license_and_requires_its_source(self):
    265         with self.sources.open("a") as stream:
    266             stream.write("pkgconf pkgconf-test.tar.gz " + "1" * 64 + " https://example.invalid/pkgconf\n")
    267         with self.assertRaisesRegex(ValueError, "missing extracted source"):
    268             self.package()
    269         directory = self.source_root / "pkgconf-test"
    270         directory.mkdir()
    271         (directory / "COPYING").write_text("pkgconf license fixture\n")
    272         with tarfile.open(self.package()) as stream:
    273             self.assertEqual(stream.extractfile("musllvm-" + self.target + "/share/musllvm/licenses/pkgconf/COPYING").read(),
    274                              b"pkgconf license fixture\n")
    275 
    276 
    277 class PublishTests(unittest.TestCase):
    278     def setUp(self):
    279         self.temporary = tempfile.TemporaryDirectory(prefix="musllvm-publish-test-")
    280         self.addCleanup(self.temporary.cleanup)
    281         self.root = Path(self.temporary.name)
    282         (self.root / "scripts").mkdir()
    283         shutil.copyfile(ROOT / "scripts/publish.sh", self.root / "scripts/publish.sh")
    284         (self.root / "sources.list").write_text("# component archive sha256 url\nllvm llvm-test.tar.xz digest url\npkgconf pkgconf-test.tar.xz digest url\n")
    285         self.output = self.root / "build/releases"
    286         self.output.mkdir(parents=True)
    287         for name in ARCHIVES:
    288             content = name.encode()
    289             (self.output / name).write_bytes(content)
    290             (self.output / (name + ".sha256")).write_text(hashlib.sha256(content).hexdigest() + "  " + name + "\n")
    291         tools = self.root / "tools"
    292         tools.mkdir()
    293         for name, content in (("gh", FAKE_GH), ("git", FAKE_GIT)):
    294             path = tools / name
    295             path.write_text(content)
    296             path.chmod(0o755)
    297         self.log = self.root / "gh.jsonl"
    298         self.env = {**os.environ, "PATH": str(tools) + os.pathsep + os.environ["PATH"],
    299                     "GITHUB_SHA": "1" * 40, "FAKE_GIT_SHA": "1" * 40,
    300                     "FAKE_GH_LOG": str(self.log), "FAKE_RELEASE": "missing", "FAKE_GH_FAIL": ""}
    301 
    302     def publish(self, success=True, **environment):
    303         result = subprocess.run(["sh", str(self.root / "scripts/publish.sh")],
    304                                 env={**self.env, **environment}, text=True,
    305                                 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    306         self.assertEqual(result.returncode == 0, success, result.stdout)
    307         return [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else []
    308 
    309     def test_new_release_uploads_both_targets_before_publication(self):
    310         calls = self.publish()
    311         self.assertEqual([call[1] for call in calls], ["view", "create", "edit"])
    312         self.assertEqual(calls[1][2], "musllvm-2026-10-12-" + "1" * 12)
    313         self.assertIn("--draft", calls[1])
    314         self.assertEqual(calls[1][calls[1].index("--target") + 1], self.env["GITHUB_SHA"])
    315         for archive in ARCHIVES:
    316             self.assertIn(archive, calls[1])
    317         self.assertIn("--draft=false", calls[2])
    318         self.assertIn("pkgconf-test.tar.xz", (self.output / "notes.md").read_text())
    319         self.assertEqual(len((self.output / "SHA256SUMS").read_text().splitlines()), 2)
    320 
    321     def test_published_release_is_not_overwritten(self):
    322         calls = self.publish(FAKE_RELEASE="published")
    323         self.assertEqual([call[1] for call in calls], ["view"])
    324 
    325     def test_draft_release_resumes_its_upload(self):
    326         calls = self.publish(FAKE_RELEASE="draft")
    327         self.assertEqual([call[1] for call in calls], ["view", "upload", "edit"])
    328         self.assertIn("--clobber", calls[1])
    329 
    330     def test_missing_or_corrupt_archives_prevent_publication(self):
    331         archive = self.output / ARCHIVES[0]
    332         archive.write_text("corrupt")
    333         self.assertEqual(self.publish(success=False), [])
    334         archive.unlink()
    335         self.assertEqual(self.publish(success=False), [])
    336 
    337     def test_checksum_for_another_archive_prevents_publication(self):
    338         shutil.copyfile(self.output / (ARCHIVES[0] + ".sha256"), self.output / (ARCHIVES[1] + ".sha256"))
    339         self.assertEqual(self.publish(success=False), [])
    340 
    341     def test_upload_failure_leaves_the_release_unpublished(self):
    342         for state, action in (("missing", "create"), ("draft", "upload")):
    343             with self.subTest(state=state):
    344                 if self.log.exists():
    345                     self.log.unlink()
    346                 calls = self.publish(success=False, FAKE_RELEASE=state, FAKE_GH_FAIL=action)
    347                 self.assertNotIn("edit", [call[1] for call in calls])
    348 
    349     def test_failed_release_lookup_creates_nothing(self):
    350         calls = self.publish(success=False, FAKE_GH_FAIL="view")
    351         self.assertEqual([call[1] for call in calls], ["view"])
    352 
    353     def test_wrong_checkout_prevents_publication(self):
    354         self.assertEqual(self.publish(success=False, FAKE_GIT_SHA="2" * 40), [])
    355 
    356 
    357 if __name__ == "__main__":
    358     unittest.main()