diff --git a/scripts/build_port.py b/scripts/build_port.py index 169c729c8..30e4d7f38 100644 --- a/scripts/build_port.py +++ b/scripts/build_port.py @@ -21,8 +21,8 @@ one-line command of the same commit. The site builds them at each deploy and serves them under get/handheld/ (scripts/sitegen/handheld.py): they are no release files, and are written to tmp/handheld/ by default, away from the packs of dist/. Members are written as the packs write -theirs: fixed timestamps, sorted names, the executable bit read from the -source, so the same tree gives the same archives. +theirs, fixed timestamps and sorted names, with the executable bit ports/ +commits on each launcher, so the same tree gives the same archives. Usage: python scripts/build_port.py diff --git a/scripts/installer_build/port.py b/scripts/installer_build/port.py index efaf90c3b..fe2925fe4 100644 --- a/scripts/installer_build/port.py +++ b/scripts/installer_build/port.py @@ -140,7 +140,10 @@ def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path: try: with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: for member, path in members: - add_pack_member(zf, str(path or table), member) + # A launcher is runnable where ports/ commits it so, and + # install.py, run by python, is not. + runnable = bool(path and path.stat().st_mode & 0o111) + add_pack_member(zf, str(path or table), member, executable=runnable) finally: table.unlink() scratch.replace(output) diff --git a/scripts/packs/archive.py b/scripts/packs/archive.py index a2fddd24c..7f1a4d671 100644 --- a/scripts/packs/archive.py +++ b/scripts/packs/archive.py @@ -12,6 +12,7 @@ from dataclasses import dataclass, field from core.artifacts import atomic_scratch from core.hashing import compute_hashes from core.paths import comparable_destination, sanitize_pack_path +from packs.executable import ships_executable from packs.paths import MEDIA_MARKER, has_path_conflict, register_path, placement_block @@ -56,7 +57,10 @@ class PackRecord: def add_pack_member( - zf: zipfile.ZipFile | PackRecord, source_path: str, arcname: str + zf: zipfile.ZipFile | PackRecord, + source_path: str, + arcname: str, + executable: bool | None = None, ) -> None: """Add a file to the pack with metadata that does not depend on the build. @@ -67,6 +71,8 @@ def add_pack_member( byte of content matched: 348 members of the Recalbox pack moved between two consecutive builds. The content is streamed rather than read whole, because some members are firmware images of several hundred megabytes. + `executable` defaults to the rule the manifest applies to a collection + file. """ if isinstance(zf, PackRecord): zf.members.append(arcname) @@ -76,13 +82,13 @@ def add_pack_member( info.compress_type = _member_compression(arcname) # The executable bit is the one permission worth carrying: the RetroDECK # pack ships the two Voxatron engine binaries, and a user who extracts - # them at 644 cannot run them. Git records the bit, so reading it from - # the source keeps the pack the same from any clone. Nothing else about - # the source's mode reaches the archive. - stat_result = os.stat(source_path) - mode = 0o755 if stat_result.st_mode & 0o111 else 0o644 + # them at 644 cannot run them. Nothing else about the source's mode + # reaches the archive. + if executable is None: + executable = ships_executable(source_path) + mode = 0o755 if executable else 0o644 info.external_attr = (0o100000 | mode) << 16 - size = stat_result.st_size + size = os.stat(source_path).st_size info.file_size = size with open(source_path, "rb") as source, zf.open( info, "w", force_zip64=size >= 1 << 31 diff --git a/scripts/packs/datatrees.py b/scripts/packs/datatrees.py index d41ca8780..fc332cb58 100644 --- a/scripts/packs/datatrees.py +++ b/scripts/packs/datatrees.py @@ -271,7 +271,8 @@ def pack_data_tree( if placed.block(full): continue placed.take(full) - add_pack_member(zf, src, full) + # The installer writes a data tree member without the bit. + add_pack_member(zf, src, full, executable=False) if packed_at is not None: packed_at[full.lower()] = src added += 1 diff --git a/scripts/packs/executable.py b/scripts/packs/executable.py new file mode 100644 index 000000000..ae7ec395f --- /dev/null +++ b/scripts/packs/executable.py @@ -0,0 +1,22 @@ +"""Whether a collection file ships executable, read from its header.""" + +from __future__ import annotations + +# A program (RetroDECK's pico8, Voxatron's vox) has to stay runnable once +# extracted or installed. The git mode cannot say: hundreds of MAME archives +# carry an execute bit nothing reads, and the Lindbergh segaboot is an ELF +# committed without one. +_PROGRAM_MAGIC = ( + b"\x7fELF", + b"#!", + b"\xcf\xfa\xed\xfe", + b"\xce\xfa\xed\xfe", + b"\xca\xfe\xba\xbe", +) + + +def ships_executable(path: str) -> bool: + """An ELF or Mach-O binary, or a script with an interpreter line.""" + with open(path, "rb") as handle: + head = handle.read(4) + return any(head.startswith(magic) for magic in _PROGRAM_MAGIC) diff --git a/scripts/packs/manifestentry.py b/scripts/packs/manifestentry.py index cdcb15236..b1e1adeca 100644 --- a/scripts/packs/manifestentry.py +++ b/scripts/packs/manifestentry.py @@ -13,6 +13,7 @@ from model.database import sha1_at from model.declarations import OUTER_ROOTS, declared_root from model.profiles import profile_names from model.largefiles import asset_name, load_registered_paths, published_asset_name +from packs.executable import ships_executable from packs.extras import ( detect_extras_prefix, extra_system_ids, @@ -152,30 +153,13 @@ def manifest_entry( if local_path and is_release_asset: entry["storage"] = "release" entry["release_asset"] = _release_asset_name(local_path, repo_root) - # The installer writes what it downloads with the umask's mode, but a program - # (RetroDECK's pico8, vox) has to stay runnable. The git mode cannot say: - # hundreds of MAME archives carry an execute bit nothing reads. - if local_path and _is_program(local_path): + # The installer writes what it downloads with the umask's mode, and the + # pack writes the same file executable by the same rule. + if local_path and ships_executable(local_path): entry["executable"] = True return entry, file_size -_PROGRAM_MAGIC = ( - b"\x7fELF", - b"#!", - b"\xcf\xfa\xed\xfe", - b"\xce\xfa\xed\xfe", - b"\xca\xfe\xba\xbe", -) - - -def _is_program(path: str) -> bool: - """An ELF or Mach-O binary, or a script with an interpreter line.""" - with open(path, "rb") as handle: - head = handle.read(4) - return any(head.startswith(magic) for magic in _PROGRAM_MAGIC) - - @dataclass(frozen=True) class ClaimContext: """How a manifest resolves and judges the copy a core claim names.""" diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index 40f9a859d..080ac74da 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -969,7 +969,8 @@ class _PlatformPackBuild: self.placed, required_only=required_only, core_trees=core_trees, uncached_out=uncached, ): - add_pack_member(self.zf, src, self._flat(full)) + # The installer writes a data tree member without the bit. + add_pack_member(self.zf, src, self._flat(full), executable=False) if isinstance(self.zf, PackRecord): self.zf.trees.append(self._flat(full)) added += 1 diff --git a/tests/sources.py b/tests/sources.py index a7dcd579f..70a1392e1 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -23,7 +23,7 @@ COMMANDS = { "packs/manifestrun.py", "packs/packcheck.py", "packs/runscope.py", "packs/platformrun.py", "packs/packoptions.py", "packs/packmodes.py", "packs/packcounts.py", "packs/emulatorentries.py", "packs/integrity.py", - "packs/hashinput.py", "packs/hashlookup.py", + "packs/hashinput.py", "packs/hashlookup.py", "packs/executable.py", ), "verify.py": ( "packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py", diff --git a/tests/test_deterministic_zip.py b/tests/test_deterministic_zip.py index 5ca3c4817..35e29fafe 100644 --- a/tests/test_deterministic_zip.py +++ b/tests/test_deterministic_zip.py @@ -200,15 +200,16 @@ class TestPackDeterminism(unittest.TestCase): """Pinning the mode stripped the bit the RetroDECK pack needs. It ships the two Voxatron engine binaries, and extracted at 644 they - cannot be run. Git records the bit, so reading it from the source - leaves the pack the same from any clone. + cannot be run. The bit is read from the header, as the manifest + reads it, so a ROM committed with an execute bit stays 644. """ import os import stat as stat_module runnable = self.bios / "engine.bin" - runnable.write_bytes(b"NOT REALLY AN ELF") - os.chmod(runnable, 0o755) + runnable.write_bytes(b"\x7fELF NOT REALLY") + os.chmod(runnable, 0o644) + os.chmod(self.bios / "boot.rom", 0o755) digest = hashlib.sha1(runnable.read_bytes()).hexdigest() self.db["files"][digest] = { "path": str(runnable), "name": "engine.bin", diff --git a/tests/test_install_experience.py b/tests/test_install_experience.py index d29bf9742..3ddf027da 100644 --- a/tests/test_install_experience.py +++ b/tests/test_install_experience.py @@ -213,7 +213,7 @@ class ProgramsAreMarked(unittest.TestCase): the git mode cannot, hundreds of MAME archives carrying an execute bit.""" def test_header_decides(self): - from packs import manifestentry + from packs.executable import ships_executable with tempfile.TemporaryDirectory() as tmp: for data, expected in ((b"\x7fELF\x02", True), (b"#!/bin/sh\n", True), @@ -221,7 +221,42 @@ class ProgramsAreMarked(unittest.TestCase): path = Path(tmp) / "f" path.write_bytes(data) with self.subTest(head=data): - self.assertEqual(manifestentry._is_program(str(path)), expected) + self.assertEqual(ships_executable(str(path)), expected) + + def test_pack_and_manifest_agree_on_every_file(self): + """A file extracted from a pack and the same file written by + install.py carry the same execute bit: 833 committed archives + carried a git bit the manifest ignored, 75 programs the reverse.""" + import zipfile + from packs import manifestentry + from packs.archive import add_pack_member + + db = json.loads((REPO_ROOT / "database.json").read_text()) + written: list[zipfile.ZipInfo] = [] + + class Members: + def open(self, info, mode, force_zip64=False): + written.append(info) + return io.BytesIO() + + held = 0 + for sha1, record in db["files"].items(): + path = str(REPO_ROOT / record["path"]) + if not os.path.isfile(path): + continue + held += 1 + with mock.patch.object(manifestentry, "_stable_hashes", + return_value={"sha1": sha1, "sha256": ""}), \ + mock.patch("packs.archive.shutil.copyfileobj"): + entry, _size = manifestentry.manifest_entry( + path, "x", None, db, str(REPO_ROOT), {}) + add_pack_member(Members(), path, "x") # type: ignore[arg-type] + packed = bool((written[-1].external_attr >> 16) & 0o111) + with self.subTest(path=record["path"]): + self.assertIsNotNone(entry) + self.assertEqual(packed, bool(entry and entry.get("executable"))) + if not held: + self.skipTest("no collection file on disk") def test_retrodeck_launchers_are_executable(self): manifest = json.loads((REPO_ROOT / "install" / "retrodeck.json").read_text()) diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index 273acf8dc..04eefdb32 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -238,7 +238,7 @@ class EmulatorPackHoldsTheCache(unittest.TestCase): (cache / "a.dat").write_bytes(b"a") held: list[bool] = [] - def member(_zf, _src, _dest): + def member(_zf, _src, _dest, executable=None): with open(cache.with_name(".scummvm.lock"), "a") as handle: try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)