refactor: split platform checks out of integrity

This commit is contained in:
Abdessamad Derraz committed 2026-11-24 06:19:54 +01:00
1 parent 4916b4a44e
commit c8258522a4
21 files changed
+870 -849

No files matched your search

+2 -1
View File
@@ -17,7 +17,8 @@ from core.options import reject_unknown
from model.registry import list_registered_platforms
from model.targets import load_target_config
from packs.archive import write_generated_member
from packs.integrity import check_pack_conformance, verify_pack
from packs.platformcheck import check_pack_conformance
from packs.integrity import verify_pack
from packs.naming import expected_pack_names, pack_archives
from packs.scope import annotate_pack_systems
+4 -805
View File
@@ -8,56 +8,19 @@ from __future__ import annotations
from pathlib import Path
from model.dbpaths import collection_root
from collections import Counter
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, TypedDict
from core.artifacts import build_timestamp
from packs.archive import PACK_DOCUMENTS, is_pack_note
from packs.paths import MEDIA_MARKER, has_path_conflict
from core.ziptools import build_zip_contents_index, is_archive_path, zip_members
from core.ziptools import safe_member_parts
from resolve.nativemode import digest_algorithm, platform_mode
from resolve.acceptance import (
baseline_verdict,
digest_verdict,
inner_rom_check,
inner_rom_data_check,
)
from resolve.nativemode import hash_mismatch_excludes_file
import sys
from resolve.cores import platform_scope_systems
from packs.archive import is_pack_note
from core.ziptools import build_zip_contents_index, zip_members
from core.hashing import (
compute_hashes, md5_composite, md5_composite_of, md5sum, parse_hash_list,
stream_hashes,
compute_hashes, md5sum, stream_hashes,
)
from core.options import reject_unknown
import io
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
import os
from packs.extras import platform_region_groups
from packs.naming import pack_variant
from packs.paths import flat_arcname
from resolve.nativemode import reads_file_contents
from resolve import regions as resolve_regions
from packs import slots
from resolve.lookup import held_record_for
from resolve.packfiles import resolve_declaration, resolve_file
from resolve.categories import BIOS, EntryCategories
from resolve.gamedata import without_game_data
from resolve.cores import resolve_platform_cores
from core.paths import BIOS_DIR, EMULATORS_DIR, declared_destination
from core.paths import BIOS_DIR
import zipfile
from collections.abc import Callable
# Imported at run time where typing has it: a test reads the signature of
# verify_pack_against_platform with its annotations evaluated.
if sys.version_info >= (3, 11):
from typing import Unpack
elif TYPE_CHECKING:
from typing_extensions import Unpack
def _members_are_held(data: bytes, by_md5: dict, held_inside: dict) -> bool:
"""Whether every member of an archive is a dump the collection holds."""
@@ -309,767 +272,3 @@ def verify_pack(
all_ok = len(errors) == 0
return all_ok, manifest
def _check_member_hash(
zf: zipfile.ZipFile, member: str, file_entry: dict, mode: str, rule: str = ""
) -> str | None:
"""Verify a pack member against its platform-declared hash.
Reproduces the platform's native check inside the pack: md5/sha1 of
the member bytes, or checkInsideZip when zipped_file is set
(Batocera hashes a ROM inside the ZIP, matched case-insensitively).
Returns an error string, or None when the member passes.
"""
zipped_file = file_entry.get("zipped_file")
if zipped_file:
# checkInsideZip runs with an empty md5 too, and needs the member.
verdict = inner_rom_data_check(file_entry, zf.read(member))
if verdict == "ok":
return None
if verdict == "not_in_zip":
return f"{member}: {zipped_file} not found inside ZIP"
if verdict == "error":
return f"{member}: {zipped_file} unreadable inside ZIP"
return (
f"{member}: {zipped_file} inside-zip md5 != declared "
f"{', '.join(parse_hash_list(file_entry.get('md5')))}"
)
declared = str(file_entry.get(mode) or "").strip()
if not declared:
return None
# The frontend's own rule, as the builder and verify apply it: RomM's
# size-then-any-hash included, which a bare md5 comparison refused.
with zf.open(member) as f:
computed = stream_hashes(f, frozenset({"md5", "sha1", "crc32"}))
unreadable: list[Exception] = []
def composite() -> str | None:
# Recalbox's Md5Composite, over the sorted members of a ZIP.
if not member.endswith(".zip"):
return None
try:
return md5_composite_of(io.BytesIO(zf.read(member)))
except (zipfile.BadZipFile, OSError) as exc:
unreadable.append(exc)
return None
if digest_verdict(
file_entry, zf.getinfo(member).file_size, lambda: computed, mode, rule, composite
):
return None
# Only a composite-only entry has the member digest as its one answer:
# elsewhere the container md5 is the comparison that failed.
if unreadable and file_entry.get("zip_digest") == "composite":
return f"{member}: unreadable nested archive ({unreadable[0]})"
return f"{member}: {mode} {computed[mode]} != declared {declared}"
def _repo_satisfies_declaration(
entries: list[dict], db: dict, mode: str
) -> bool:
"""Check whether any repo file matches one of the declarations.
Used to separate pack divergence (a matching file exists but was not
packed) from data coverage gaps (no repo file matches the upstream
declaration): only the former is a pack generation error. A held file
is the resolver's: every declared hash agrees with it, and a zipped_file
md5 names a member of a held archive, not a loose file. The verdict
compares whole digests as the frontend does, so a cut md5 names a held
file without being satisfied by it.
"""
files_db = db.get("files", {})
by_name = db.get("indexes", {}).get("by_name", {})
for fe in entries:
if fe.get("zipped_file"):
if _repo_holds_member(fe, db):
return True
continue
hashes = parse_hash_list(fe.get(mode))
if not hashes:
continue
held_sha1 = held_record_for(fe, db)
if held_sha1 is not None:
held = files_db[held_sha1]
digest = held_sha1 if mode == "sha1" else str(held.get(mode, ""))
if digest.lower() in hashes and os.path.exists(held.get("path", "")):
return True
if mode == "md5":
hash_set = set(hashes)
for cand_sha in by_name.get(fe.get("name", ""), []):
entry = files_db.get(cand_sha)
if not entry:
continue
path = entry.get("path", "")
if not is_archive_path(path) or not os.path.exists(path):
continue
try:
if md5_composite(path).lower() in hash_set:
return True
except (zipfile.BadZipFile, OSError):
continue
return False
def _repo_holds_member(file_entry: dict, db: dict) -> bool:
"""Whether a held archive of that name carries the declared member."""
files_db = db.get("files", {})
for sha1 in db.get("indexes", {}).get("by_name", {}).get(file_entry.get("name", ""), []):
path = (files_db.get(sha1) or {}).get("path", "")
if not is_archive_path(path) or not os.path.exists(path):
continue
if inner_rom_check(file_entry, path) == "ok":
return True
return False
def _held_nowhere(
entries: list[dict],
db: dict,
zip_contents: dict,
data_dir_registry: dict | None,
) -> bool:
"""Return whether no declaration for a destination resolves to a file."""
return bool(entries) and all(
resolve_file(
entry,
db,
BIOS_DIR,
zip_contents,
data_dir_registry=data_dir_registry,
offline=True,
)[1] == "not_found"
for entry in entries
)
def _intentional_hash_exclusion(
entries: list[dict],
db: dict,
bios_dir: str = BIOS_DIR,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
verification_mode: str = "md5",
hash_rule: str = "",
) -> bool:
"""Return whether the builder must omit every declaration as unsafe.
A hash platform never substitutes a same-named payload for an explicitly
hash-identified one, so a missing pack member is accounted for when every
declaration for that destination resolves to a local hash mismatch. An
existence platform reads no bytes and the builder ships the file anyway,
so nothing is ever excluded on its behalf. Genuine absence,
external-download failure and a packable alternative stay conformance
errors in both modes.
"""
if not entries or not hash_mismatch_excludes_file(verification_mode):
return False
archive_index = zip_contents if zip_contents is not None else {}
for entry in entries:
local_path, status = resolve_file(
entry,
db,
bios_dir,
archive_index,
data_dir_registry=data_dir_registry,
offline=True,
)
# The builder's own verdict: a zipped_file archive is refused when the
# member is missing whatever the outer resolution said, a hash
# mismatch when the frontend's digest disagrees too.
_status, refusal = baseline_verdict(
entry, local_path, status, verification_mode, hash_rule
)
if refusal is None:
return False
return True
def _structural_errors(zf: zipfile.ZipFile, zip_set: set) -> list[str]:
"""Faults in the archive itself, before any file is looked up.
A duplicate entry, an absolute path or a traversal makes the pack
unsafe to extract whatever it contains, and a zero-byte member is a
file the user will believe they have. The markers Dolphin ships for
its graphics mods are legitimately empty.
"""
errors: list[str] = []
# Structural checks
dupes = sum(1 for c in Counter(zf.namelist()).values() if c > 1)
if dupes:
errors.append(f"{dupes} duplicate entries")
errors.extend(f"double slash: {n}" for n in zip_set if "//" in n)
for info in zf.infolist():
try:
safe_member_parts(info)
except ValueError as exc:
errors.append(str(exc))
# Zero-byte check (exclude Dolphin GraphicMods markers)
errors.extend(
f"zero-byte: {info.filename}"
for info in zf.infolist()
if info.file_size == 0 and not info.is_dir()
and "GraphicMods" not in info.filename
and info.filename not in PACK_DOCUMENTS
and info.filename.rsplit("/", 1)[-1] != MEDIA_MARKER
)
return errors
def _shipped_copy(
entry: dict, db: dict, data_registry: dict | None, mode: str, hash_rule: str,
) -> str | None:
"""The file the builder packs for a declaration, or None.
The verdict verify applies before it lets a declaration hold its path.
"""
local, status = resolve_declaration(
entry, db, BIOS_DIR, None, data_registry, None, offline=True,
)
if local and baseline_verdict(entry, local, status, mode, hash_rule)[1] is None:
return local
return None
def _builder_extras(
expect: _Expectation,
db: dict,
baseline_groups: dict[str, list[dict]],
view: _PackView,
include_all: bool = False,
) -> dict[str, str]:
"""{full destination: local copy} of each core extra the builder writes.
The platform's paths come first, as in the builder: a destination the
pack holds whose declarations resolve to a file it ships, or that the
platform keeps for a user_provided or external entry. One whose
declarations resolve to nothing, or to a file the frontend's hash
refuses, is left free, since the builder then places a core's file
there: taken by the refused file, that core file was never compared.
"""
from packs.extras import ExtraResolver, hidden_extras
from resolve.validation import build_validation_index
from resolve.acceptance import destination_owners
config, emu_profiles = expect.config, expect.emu_profiles
data_registry = expect.opts.data_registry
base_dest = expect.base_dest
mode = platform_mode(config)
hash_rule = config.get("hash_rule", "")
shipped: dict[str, str | None] = {}
for expected, declarations in baseline_groups.items():
if not view.holds(expected):
continue
unflat = (
f"{base_dest}/{expected}"
if view.is_flat and base_dest and not expected.startswith(f"{base_dest}/")
else expected
)
if any(fe.get("storage") in ("user_provided", "external") for fe in declarations):
shipped[unflat] = None
continue
local = next(
(
found for fe in declarations
if (found := _shipped_copy(fe, db, data_registry, mode, hash_rule))
),
None,
)
if local:
shipped[unflat] = local
platform_profiles = {
name: emu_profiles[name] for name in resolve_platform_cores(config, emu_profiles)
}
placed_local: dict[str, str] = {}
hidden_extras(
config, expect.opts.emulators_dir, db, emu_profiles, shipped, expect.target_cores,
expect.region_drops or None,
resolver=ExtraResolver(
db, BIOS_DIR, build_zip_contents_index(db, collection_root(Path(BIOS_DIR))), data_registry,
build_validation_index(platform_profiles),
destination_owners(platform_profiles), True, profiles=emu_profiles,
),
placed_local=placed_local,
include_all=include_all,
required_only=expect.opts.required_only,
)
return placed_local
def _same_content(zf: zipfile.ZipFile, member: str, local: str) -> bool:
"""Whether a pack member carries the bytes of a local copy, or the
members of an archive the builder normalized."""
with open(local, "rb") as handle:
if zf.read(member) == handle.read():
return True
return is_archive_path(local) and same_members(zf, member, local)
class ConformanceOptions(TypedDict, total=False):
"""The keyword options of check_pack_conformance."""
emulators_dir: str
emu_profiles: dict | None
regions: list[str] | None
data_registry: dict | None
no_game_data: bool
class PlatformCheckOptions(ConformanceOptions, total=False):
"""The keyword options of verify_pack_against_platform."""
source: str
required_only: bool
@dataclass(frozen=True)
class _PlatformCheckSettings:
"""PlatformCheckOptions with their defaults."""
emulators_dir: str = EMULATORS_DIR
emu_profiles: dict | None = None
regions: list[str] | None = None
data_registry: dict | None = None
source: str = "full"
required_only: bool = False
no_game_data: bool = False
@dataclass(frozen=True)
class _Expectation:
"""What the builder would have packed for a platform, before the pack is read."""
config: dict
emu_profiles: dict
expected_systems: dict
region_drops: set[str]
db: dict | None
target_cores: set[str] | None
opts: _PlatformCheckSettings
@property
def base_dest(self) -> str:
return self.config.get("base_destination", "")
@dataclass(frozen=True)
class _PackView:
"""A pack's member names as the checks read them."""
zf: zipfile.ZipFile
zip_set: set[str]
zip_lower: dict[str, str]
zip_parents: set[str]
is_flat: bool
def holds(self, expected: str) -> bool:
return expected in self.zip_set or expected.lower() in self.zip_lower
@dataclass
class _BaselineCount:
"""The baseline destinations checked, and what each came to."""
checked: int = 0
present: int = 0
excluded: int = 0
absent: int = 0
decl_by_member: dict[str, list[dict]] = field(default_factory=dict)
def _cut_config(
platform_name: str,
platforms_dir: str,
target_cores: set[str] | None,
opts: _PlatformCheckSettings,
) -> tuple[dict, dict]:
"""The platform's config and the profiles, without game data when asked."""
config = load_platform_config(platform_name, platforms_dir)
emu_profiles = opts.emu_profiles
if emu_profiles is None:
emu_profiles = load_emulator_profiles(opts.emulators_dir)
if opts.no_game_data:
cut = without_game_data(config, emu_profiles, opts.data_registry, target_cores)
config, emu_profiles = cut.config, cut.profiles
return config, emu_profiles
def _region_drops(
config: dict,
emu_profiles: dict,
expected_systems: dict,
db: dict | None,
*,
target_cores: set[str] | None,
opts: _PlatformCheckSettings,
) -> set[str]:
"""The regional variants the builder leaves out, by the same selection."""
region_drops: set[str] = set()
if not opts.regions:
return region_drops
region_index = resolve_regions.platform_region_index(
config, emu_profiles, target_cores
)
held: set[str] = set()
held_zip_contents = build_zip_contents_index(db, collection_root(Path(BIOS_DIR))) if db is not None else {}
region_groups, _extra_dests = platform_region_groups(
config,
expected_systems,
opts.emulators_dir,
db,
config.get("base_destination", ""),
emu_profiles,
target_cores=target_cores,
include_extras=(opts.source != "platform"),
include_all=(opts.source == "truth"),
required_only=opts.required_only,
held_out=held,
zip_contents=held_zip_contents,
data_registry=opts.data_registry,
slot_overrides=slots.pack_overrides(
config, emu_profiles, db, held_zip_contents, opts.data_registry,
target_cores=target_cores, source=opts.source,
) if db is not None else None,
)
return resolve_regions.resolve_region_drops(
region_groups, region_index, opts.regions, held
)
def _pack_view(zf: zipfile.ZipFile, config: dict, base_dest: str) -> _PackView:
zip_set = set(zf.namelist())
# A case twin stands in for the file only where the platform's
# filesystem folds case, as the builder decides: on Lakka bios.col
# and BIOS.col are two files two cores open, and either one missing
# was counted present through the other.
zip_lower = (
{n.lower(): n for n in zip_set}
if config.get("case_insensitive_fs", False) else {}
)
# Auto-detect flat vs nested ZIP
is_flat = bool(base_dest) and not any(
n.startswith(base_dest + "/")
for n in zip_set
if n not in (*PACK_DOCUMENTS, MEDIA_MARKER) and not n.endswith("/")
)
# Mirror the builder's path-conflict logic: a declaration whose path
# collides file-vs-directory with a packed member was skipped by the
# builder (upstream declares e.g. both SGB1.sfc and SGB1.sfc/program.rom)
zip_parents: set[str] = set()
for n in zip_set:
parts = n.split("/")
for i in range(1, len(parts)):
zip_parents.add("/".join(parts[:i]))
return _PackView(zf, zip_set, zip_lower, zip_parents, is_flat)
def _baseline_groups(
expect: _Expectation, is_flat: bool,
) -> tuple[dict[str, list[dict]], dict[int, str]]:
"""The platform's declarations by the path they expect in the pack, and
the system of each declaration."""
opts = expect.opts
base_dest = expect.base_dest
baseline_groups: dict[str, list[dict]] = {}
system_of: dict[int, str] = {}
for sys_id, system in (expect.expected_systems if opts.source != "truth" else {}).items():
for fe in system.get("files", []):
system_of[id(fe)] = sys_id
if opts.required_only and fe.get("required") is False:
continue
dest = declared_destination(fe)
if not dest:
continue
if expect.region_drops and dest in expect.region_drops:
continue
expected = f"{base_dest}/{dest}" if base_dest and not is_flat else dest
baseline_groups.setdefault(expected, []).append(fe)
return baseline_groups, system_of
def _count_baseline(
expect: _Expectation,
view: _PackView,
baseline_groups: dict[str, list[dict]],
system_of: dict[int, str],
errors: list[str],
) -> _BaselineCount:
"""Each baseline destination present, accounted for, or missing."""
db = expect.db
data_registry = expect.opts.data_registry
count = _BaselineCount(checked=len(baseline_groups))
# RetroBat's group: one packed file of it is enough, as verify counts it.
packed_groups = {
(system_of[id(fe)], fe["group"])
for expected, declarations in baseline_groups.items()
if view.holds(expected)
for fe in declarations
if fe.get("group")
}
exclusion_index = build_zip_contents_index(db, collection_root(Path(BIOS_DIR))) if db is not None else {}
categories = EntryCategories(expect.config, expect.emu_profiles, data_registry)
for expected, declarations in baseline_groups.items():
if expected in view.zip_set:
member = expected
elif expected.lower() in view.zip_lower:
member = view.zip_lower[expected.lower()]
elif has_path_conflict(expected, view.zip_set, view.zip_parents):
# Skipped by the builder for the same reason: not an error
count.present += 1
continue
elif db is not None and _intentional_hash_exclusion(
declarations,
db,
zip_contents=exclusion_index,
data_dir_registry=data_registry,
verification_mode=platform_mode(expect.config),
hash_rule=expect.config.get("hash_rule", ""),
):
count.excluded += 1
continue
elif all(
fe.get("group") and (system_of[id(fe)], fe["group"]) in packed_groups
for fe in declarations
):
count.absent += 1
continue
elif db is not None and all(
categories.category(fe, fe.get("destination", fe.get("name", "")),
system_of[id(fe)]) != BIOS
for fe in declarations
) and _held_nowhere(declarations, db, exclusion_index, data_registry):
# A game's data or an entry no core opens that the collection
# lacks: verify counts it apart. Missing firmware stays an error.
count.absent += 1
continue
else:
errors.append(f"baseline missing: {expected}")
continue
count.present += 1
count.decl_by_member.setdefault(member, []).extend(declarations)
return count
def native_hash_errors(
zf: zipfile.ZipFile, decl_by_member: dict[str, list[dict]], config: dict, db: dict | None,
) -> list[str]:
"""The platform's native hash check replayed on the pack's bytes."""
# Reproduce the platform's native hash check on pack bytes.
# A destination declared by several entries passes when the packed
# member satisfies any of them. A failure only counts as a pack
# error when the repo holds a file matching a declaration: without
# one, the pack ships its best effort and the gap is a data issue
# reported by verify.py, not a generation bug.
verification_mode = platform_mode(config)
digest = digest_algorithm(verification_mode)
hash_rule = config.get("hash_rule", "")
errors: list[str] = []
if not (reads_file_contents(verification_mode) and digest):
return errors
for member, decl_entries in decl_by_member.items():
checkable = [
fe
for fe in decl_entries
if fe.get("zipped_file") or str(fe.get(digest) or "").strip()
]
if not checkable:
continue
# An archive declared once per ROM it must hold is checked
# once per ROM by the frontend: each such declaration has to
# pass on its own, where the repository holds an archive
# that would.
for fe in checkable:
if not fe.get("zipped_file"):
continue
err = _check_member_hash(zf, member, fe, digest, hash_rule)
if err is not None and (db is None or _repo_holds_member(fe, db)):
errors.append(err)
member_errors = []
satisfied = False
for fe in checkable:
err = _check_member_hash(zf, member, fe, digest, hash_rule)
if err is None:
satisfied = True
break
member_errors.append(err)
if satisfied:
continue
if db is None or _repo_satisfies_declaration(
checkable, db, verification_mode
):
errors.append(member_errors[0])
return errors
def _check_core_extras(
expect: _Expectation,
view: _PackView,
baseline_groups: dict[str, list[dict]],
errors: list[str],
) -> tuple[int, int]:
"""(checked, present) of the core extras the builder places."""
# 2. Core extras: the builder's own placement replayed
# (packextras.hidden_extras, which verify reads too), after the
# platform files it wrote. Each placed extra must sit at its path
# with the bytes the builder resolved: an empty seen set and a
# presence test credited a core file at a path where the pack
# holds the platform's other dump.
core_checked = 0
core_present = 0
opts = expect.opts
db = expect.db
if db is None or opts.source == "platform":
return core_checked, core_present
placed_local = _builder_extras(
expect, db, baseline_groups, view, include_all=(opts.source == "truth"),
)
for full, local in sorted(placed_local.items()):
core_checked += 1
flat = flat_arcname(full, expect.base_dest, view.is_flat)
member = flat if flat in view.zip_set else view.zip_lower.get(flat.lower())
if member is None:
errors.append(f"core missing: {full}")
elif not _same_content(view.zf, member, local):
errors.append(
f"core file differs: {member} is not the {os.path.basename(local)}"
" the builder places there"
)
else:
core_present += 1
return core_checked, core_present
def verify_pack_against_platform(
zip_path: str,
platform_name: str,
platforms_dir: str,
db: dict | None = None,
*,
target_cores: set[str] | None = None,
**options: Unpack[PlatformCheckOptions],
) -> tuple[bool, int, int, list[str], int, int, int, int, int, int]:
"""Verify a pack ZIP against its platform config and core requirements.
A region priority list narrows the expectation to what the builder would
have packed, using the same selection function. A hardware target narrows
it the same way and for the same reason: the systems it removes are not
missing from the pack, they were never asked for. ``source`` and
``required_only`` are the variant the pack was built as: a platform-only
pack is held to the platform's list alone, a truth pack to the cores'
files alone, and a required-only pack to the required entries of both.
``no_game_data`` holds the pack to the firmware alone, cut as the
builder cuts it.
Checks:
1. Every baseline file declared by the platform exists in the ZIP
at the correct destination path
2. Every in-repo core extra file (from emulator profiles) is present
3. No duplicate entries
4. No path anomalies (double slash, absolute, traversal)
5. No unexpected zero-byte BIOS files
Returns ``(all_ok, checked, present, errors, baseline_checked,
baseline_present, core_checked, core_present, baseline_excluded,
baseline_absent)``. ``baseline_absent`` counts destinations the collection
holds no file for that are a game's data or that no core the platform
runs opens. verify.py counts them apart from firmware.
"""
reject_unknown(
"verify_pack_against_platform", options, PlatformCheckOptions.__optional_keys__
)
opts = _PlatformCheckSettings(**options)
config, emu_profiles = _cut_config(platform_name, platforms_dir, target_cores, opts)
# The systems the builder packed, by the one rule verify and the pack read.
expected_systems = platform_scope_systems(config, emu_profiles, target_cores)
expect = _Expectation(
config, emu_profiles, expected_systems,
_region_drops(
config, emu_profiles, expected_systems, db,
target_cores=target_cores, opts=opts,
),
db, target_cores, opts,
)
errors: list[str] = []
with zipfile.ZipFile(zip_path, "r") as zf:
view = _pack_view(zf, expect.config, expect.base_dest)
errors.extend(_structural_errors(zf, view.zip_set))
# 1. Baseline file presence + native hash check
baseline_groups, system_of = _baseline_groups(expect, view.is_flat)
baseline = _count_baseline(expect, view, baseline_groups, system_of, errors)
errors.extend(native_hash_errors(zf, baseline.decl_by_member, expect.config, db))
core_checked, core_present = _check_core_extras(expect, view, baseline_groups, errors)
return (
len(errors) == 0,
baseline.checked + core_checked,
baseline.present + core_present,
errors,
baseline.checked,
baseline.present,
core_checked,
core_present,
baseline.excluded,
baseline.absent,
)
def baseline_shortfall(excluded: int, absent: int) -> list[str]:
"""Why a verified pack holds fewer baseline files than the platform declares."""
parts = []
if excluded:
parts.append(f"{excluded} unsafe excluded")
if absent:
parts.append(f"{absent} not in the collection")
return parts
@dataclass(frozen=True)
class PackConformance:
"""A pack checked against one platform, as verify_pack_against_platform returns it."""
ok: bool
checked: int
present: int
errors: list[str]
baseline_checked: int
baseline_present: int
core_checked: int
core_present: int
baseline_excluded: int
baseline_absent: int
@property
def shortfall(self) -> list[str]:
"""Why the baseline holds fewer files than the platform declares."""
return baseline_shortfall(self.baseline_excluded, self.baseline_absent)
def check_pack_conformance(
zip_path: str,
platform_name: str,
platforms_dir: str,
db: dict | None = None,
*,
target_cores: set[str] | None = None,
**options: Unpack[ConformanceOptions],
) -> PackConformance | None:
"""A pack checked against its platform under the variant its name says.
The build and --verify-packs both read this, so a pack gets one verdict:
a required-only, platform-only or truth pack is held to its own
expectation, never skipped by one and failed by the other. None for a
one-per-slot pack, whose slot choice the check does not replay.
"""
variant = pack_variant(os.path.basename(zip_path))
if variant is None:
return None
source, required_only = variant
return PackConformance(*verify_pack_against_platform(
zip_path, platform_name, platforms_dir, db,
target_cores=target_cores, source=source, required_only=required_only, **options,
))
+1 -1
View File
@@ -12,7 +12,7 @@ from model.database import load_database
from model.profiles import load_emulator_profiles
from model.registry import list_release_pack_platforms, load_data_dir_registry
from model.targets import target_scope
from packs.integrity import check_pack_conformance
from packs.platformcheck import check_pack_conformance
from packs.naming import expected_pack_names
from packs.variants import ALL_VARIANTS
+178
View File
@@ -0,0 +1,178 @@
"""Whether a pack's copy passes the hash check its platform runs natively."""
from __future__ import annotations
import io
import os
import zipfile
from core.hashing import md5_composite, md5_composite_of, parse_hash_list, stream_hashes
from core.ziptools import is_archive_path
from resolve.lookup import held_record_for
from resolve.nativemode import digest_algorithm, platform_mode, reads_file_contents
from resolve.acceptance import digest_verdict, inner_rom_check, inner_rom_data_check
def _check_member_hash(
zf: zipfile.ZipFile, member: str, file_entry: dict, mode: str, rule: str = ""
) -> str | None:
"""Verify a pack member against its platform-declared hash.
Reproduces the platform's native check inside the pack: md5/sha1 of
the member bytes, or checkInsideZip when zipped_file is set
(Batocera hashes a ROM inside the ZIP, matched case-insensitively).
Returns an error string, or None when the member passes.
"""
zipped_file = file_entry.get("zipped_file")
if zipped_file:
# checkInsideZip runs with an empty md5 too, and needs the member.
verdict = inner_rom_data_check(file_entry, zf.read(member))
if verdict == "ok":
return None
if verdict == "not_in_zip":
return f"{member}: {zipped_file} not found inside ZIP"
if verdict == "error":
return f"{member}: {zipped_file} unreadable inside ZIP"
return (
f"{member}: {zipped_file} inside-zip md5 != declared "
f"{', '.join(parse_hash_list(file_entry.get('md5')))}"
)
declared = str(file_entry.get(mode) or "").strip()
if not declared:
return None
# The frontend's own rule, as the builder and verify apply it: RomM's
# size-then-any-hash included, which a bare md5 comparison refused.
with zf.open(member) as f:
computed = stream_hashes(f, frozenset({"md5", "sha1", "crc32"}))
unreadable: list[Exception] = []
def composite() -> str | None:
# Recalbox's Md5Composite, over the sorted members of a ZIP.
if not member.endswith(".zip"):
return None
try:
return md5_composite_of(io.BytesIO(zf.read(member)))
except (zipfile.BadZipFile, OSError) as exc:
unreadable.append(exc)
return None
if digest_verdict(
file_entry, zf.getinfo(member).file_size, lambda: computed, mode, rule, composite
):
return None
# Only a composite-only entry has the member digest as its one answer:
# elsewhere the container md5 is the comparison that failed.
if unreadable and file_entry.get("zip_digest") == "composite":
return f"{member}: unreadable nested archive ({unreadable[0]})"
return f"{member}: {mode} {computed[mode]} != declared {declared}"
def _repo_satisfies_declaration(
entries: list[dict], db: dict, mode: str
) -> bool:
"""Check whether any repo file matches one of the declarations.
Used to separate pack divergence (a matching file exists but was not
packed) from data coverage gaps (no repo file matches the upstream
declaration): only the former is a pack generation error. A held file
is the resolver's: every declared hash agrees with it, and a zipped_file
md5 names a member of a held archive, not a loose file. The verdict
compares whole digests as the frontend does, so a cut md5 names a held
file without being satisfied by it.
"""
files_db = db.get("files", {})
by_name = db.get("indexes", {}).get("by_name", {})
for fe in entries:
if fe.get("zipped_file"):
if _repo_holds_member(fe, db):
return True
continue
hashes = parse_hash_list(fe.get(mode))
if not hashes:
continue
held_sha1 = held_record_for(fe, db)
if held_sha1 is not None:
held = files_db[held_sha1]
digest = held_sha1 if mode == "sha1" else str(held.get(mode, ""))
if digest.lower() in hashes and os.path.exists(held.get("path", "")):
return True
if mode == "md5":
hash_set = set(hashes)
for cand_sha in by_name.get(fe.get("name", ""), []):
entry = files_db.get(cand_sha)
if not entry:
continue
path = entry.get("path", "")
if not is_archive_path(path) or not os.path.exists(path):
continue
try:
if md5_composite(path).lower() in hash_set:
return True
except (zipfile.BadZipFile, OSError):
continue
return False
def _repo_holds_member(file_entry: dict, db: dict) -> bool:
"""Whether a held archive of that name carries the declared member."""
files_db = db.get("files", {})
for sha1 in db.get("indexes", {}).get("by_name", {}).get(file_entry.get("name", ""), []):
path = (files_db.get(sha1) or {}).get("path", "")
if not is_archive_path(path) or not os.path.exists(path):
continue
if inner_rom_check(file_entry, path) == "ok":
return True
return False
def native_hash_errors(
zf: zipfile.ZipFile, decl_by_member: dict[str, list[dict]], config: dict, db: dict | None,
) -> list[str]:
"""The platform's native hash check replayed on the pack's bytes."""
# Reproduce the platform's native hash check on pack bytes.
# A destination declared by several entries passes when the packed
# member satisfies any of them. A failure only counts as a pack
# error when the repo holds a file matching a declaration: without
# one, the pack ships its best effort and the gap is a data issue
# reported by verify.py, not a generation bug.
verification_mode = platform_mode(config)
digest = digest_algorithm(verification_mode)
hash_rule = config.get("hash_rule", "")
errors: list[str] = []
if not (reads_file_contents(verification_mode) and digest):
return errors
for member, decl_entries in decl_by_member.items():
checkable = [
fe
for fe in decl_entries
if fe.get("zipped_file") or str(fe.get(digest) or "").strip()
]
if not checkable:
continue
# An archive declared once per ROM it must hold is checked
# once per ROM by the frontend: each such declaration has to
# pass on its own, where the repository holds an archive
# that would.
for fe in checkable:
if not fe.get("zipped_file"):
continue
err = _check_member_hash(zf, member, fe, digest, hash_rule)
if err is not None and (db is None or _repo_holds_member(fe, db)):
errors.append(err)
member_errors = []
satisfied = False
for fe in checkable:
err = _check_member_hash(zf, member, fe, digest, hash_rule)
if err is None:
satisfied = True
break
member_errors.append(err)
if satisfied:
continue
if db is None or _repo_satisfies_declaration(
checkable, db, verification_mode
):
errors.append(member_errors[0])
return errors
+640
View File
@@ -0,0 +1,640 @@
"""A built pack held against its platform's declarations and the builder's extras."""
from __future__ import annotations
import os
import sys
import zipfile
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict
from core.options import reject_unknown
from core.paths import BIOS_DIR, EMULATORS_DIR, declared_destination
from core.ziptools import build_zip_contents_index, is_archive_path, safe_member_parts
from model.dbpaths import collection_root
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from packs import slots
from packs.archive import PACK_DOCUMENTS
from packs.extras import platform_region_groups
from packs.integrity import same_members
from packs.naming import pack_variant
from packs.packhashes import native_hash_errors
from packs.paths import MEDIA_MARKER, flat_arcname, has_path_conflict
from resolve import regions as resolve_regions
from resolve.categories import BIOS, EntryCategories
from resolve.cores import platform_scope_systems, resolve_platform_cores
from resolve.gamedata import without_game_data
from resolve.nativemode import hash_mismatch_excludes_file, platform_mode
from resolve.packfiles import resolve_declaration, resolve_file
from resolve.acceptance import baseline_verdict
# Imported at run time where typing has it: a test reads the signature of
# verify_pack_against_platform with its annotations evaluated.
if sys.version_info >= (3, 11):
from typing import Unpack
elif TYPE_CHECKING:
from typing_extensions import Unpack
def _held_nowhere(
entries: list[dict],
db: dict,
zip_contents: dict,
data_dir_registry: dict | None,
) -> bool:
"""Return whether no declaration for a destination resolves to a file."""
return bool(entries) and all(
resolve_file(
entry,
db,
BIOS_DIR,
zip_contents,
data_dir_registry=data_dir_registry,
offline=True,
)[1] == "not_found"
for entry in entries
)
def _intentional_hash_exclusion(
entries: list[dict],
db: dict,
bios_dir: str = BIOS_DIR,
zip_contents: dict | None = None,
data_dir_registry: dict | None = None,
verification_mode: str = "md5",
hash_rule: str = "",
) -> bool:
"""Return whether the builder must omit every declaration as unsafe.
A hash platform never substitutes a same-named payload for an explicitly
hash-identified one, so a missing pack member is accounted for when every
declaration for that destination resolves to a local hash mismatch. An
existence platform reads no bytes and the builder ships the file anyway,
so nothing is ever excluded on its behalf. Genuine absence,
external-download failure and a packable alternative stay conformance
errors in both modes.
"""
if not entries or not hash_mismatch_excludes_file(verification_mode):
return False
archive_index = zip_contents if zip_contents is not None else {}
for entry in entries:
local_path, status = resolve_file(
entry,
db,
bios_dir,
archive_index,
data_dir_registry=data_dir_registry,
offline=True,
)
# The builder's own verdict: a zipped_file archive is refused when the
# member is missing whatever the outer resolution said, a hash
# mismatch when the frontend's digest disagrees too.
_status, refusal = baseline_verdict(
entry, local_path, status, verification_mode, hash_rule
)
if refusal is None:
return False
return True
def _structural_errors(zf: zipfile.ZipFile, zip_set: set) -> list[str]:
"""Faults in the archive itself, before any file is looked up.
A duplicate entry, an absolute path or a traversal makes the pack
unsafe to extract whatever it contains, and a zero-byte member is a
file the user will believe they have. The markers Dolphin ships for
its graphics mods are legitimately empty.
"""
errors: list[str] = []
# Structural checks
dupes = sum(1 for c in Counter(zf.namelist()).values() if c > 1)
if dupes:
errors.append(f"{dupes} duplicate entries")
errors.extend(f"double slash: {n}" for n in zip_set if "//" in n)
for info in zf.infolist():
try:
safe_member_parts(info)
except ValueError as exc:
errors.append(str(exc))
# Zero-byte check (exclude Dolphin GraphicMods markers)
errors.extend(
f"zero-byte: {info.filename}"
for info in zf.infolist()
if info.file_size == 0 and not info.is_dir()
and "GraphicMods" not in info.filename
and info.filename not in PACK_DOCUMENTS
and info.filename.rsplit("/", 1)[-1] != MEDIA_MARKER
)
return errors
def _shipped_copy(
entry: dict, db: dict, data_registry: dict | None, mode: str, hash_rule: str,
) -> str | None:
"""The file the builder packs for a declaration, or None.
The verdict verify applies before it lets a declaration hold its path.
"""
local, status = resolve_declaration(
entry, db, BIOS_DIR, None, data_registry, None, offline=True,
)
if local and baseline_verdict(entry, local, status, mode, hash_rule)[1] is None:
return local
return None
def _builder_extras(
expect: _Expectation,
db: dict,
baseline_groups: dict[str, list[dict]],
view: _PackView,
include_all: bool = False,
) -> dict[str, str]:
"""{full destination: local copy} of each core extra the builder writes.
The platform's paths come first, as in the builder: a destination the
pack holds whose declarations resolve to a file it ships, or that the
platform keeps for a user_provided or external entry. One whose
declarations resolve to nothing, or to a file the frontend's hash
refuses, is left free, since the builder then places a core's file
there: taken by the refused file, that core file was never compared.
"""
from packs.extras import ExtraResolver, hidden_extras
from resolve.validation import build_validation_index
from resolve.acceptance import destination_owners
config, emu_profiles = expect.config, expect.emu_profiles
data_registry = expect.opts.data_registry
base_dest = expect.base_dest
mode = platform_mode(config)
hash_rule = config.get("hash_rule", "")
shipped: dict[str, str | None] = {}
for expected, declarations in baseline_groups.items():
if not view.holds(expected):
continue
unflat = (
f"{base_dest}/{expected}"
if view.is_flat and base_dest and not expected.startswith(f"{base_dest}/")
else expected
)
if any(fe.get("storage") in ("user_provided", "external") for fe in declarations):
shipped[unflat] = None
continue
local = next(
(
found for fe in declarations
if (found := _shipped_copy(fe, db, data_registry, mode, hash_rule))
),
None,
)
if local:
shipped[unflat] = local
platform_profiles = {
name: emu_profiles[name] for name in resolve_platform_cores(config, emu_profiles)
}
placed_local: dict[str, str] = {}
hidden_extras(
config, expect.opts.emulators_dir, db, emu_profiles, shipped, expect.target_cores,
expect.region_drops or None,
resolver=ExtraResolver(
db, BIOS_DIR, build_zip_contents_index(db, collection_root(Path(BIOS_DIR))), data_registry,
build_validation_index(platform_profiles),
destination_owners(platform_profiles), True, profiles=emu_profiles,
),
placed_local=placed_local,
include_all=include_all,
required_only=expect.opts.required_only,
)
return placed_local
def _same_content(zf: zipfile.ZipFile, member: str, local: str) -> bool:
"""Whether a pack member carries the bytes of a local copy, or the
members of an archive the builder normalized."""
with open(local, "rb") as handle:
if zf.read(member) == handle.read():
return True
return is_archive_path(local) and same_members(zf, member, local)
class ConformanceOptions(TypedDict, total=False):
"""The keyword options of check_pack_conformance."""
emulators_dir: str
emu_profiles: dict | None
regions: list[str] | None
data_registry: dict | None
no_game_data: bool
class PlatformCheckOptions(ConformanceOptions, total=False):
"""The keyword options of verify_pack_against_platform."""
source: str
required_only: bool
@dataclass(frozen=True)
class _PlatformCheckSettings:
"""PlatformCheckOptions with their defaults."""
emulators_dir: str = EMULATORS_DIR
emu_profiles: dict | None = None
regions: list[str] | None = None
data_registry: dict | None = None
source: str = "full"
required_only: bool = False
no_game_data: bool = False
@dataclass(frozen=True)
class _Expectation:
"""What the builder would have packed for a platform, before the pack is read."""
config: dict
emu_profiles: dict
expected_systems: dict
region_drops: set[str]
db: dict | None
target_cores: set[str] | None
opts: _PlatformCheckSettings
@property
def base_dest(self) -> str:
return self.config.get("base_destination", "")
@dataclass(frozen=True)
class _PackView:
"""A pack's member names as the checks read them."""
zf: zipfile.ZipFile
zip_set: set[str]
zip_lower: dict[str, str]
zip_parents: set[str]
is_flat: bool
def holds(self, expected: str) -> bool:
return expected in self.zip_set or expected.lower() in self.zip_lower
@dataclass
class _BaselineCount:
"""The baseline destinations checked, and what each came to."""
checked: int = 0
present: int = 0
excluded: int = 0
absent: int = 0
decl_by_member: dict[str, list[dict]] = field(default_factory=dict)
def _cut_config(
platform_name: str,
platforms_dir: str,
target_cores: set[str] | None,
opts: _PlatformCheckSettings,
) -> tuple[dict, dict]:
"""The platform's config and the profiles, without game data when asked."""
config = load_platform_config(platform_name, platforms_dir)
emu_profiles = opts.emu_profiles
if emu_profiles is None:
emu_profiles = load_emulator_profiles(opts.emulators_dir)
if opts.no_game_data:
cut = without_game_data(config, emu_profiles, opts.data_registry, target_cores)
config, emu_profiles = cut.config, cut.profiles
return config, emu_profiles
def _region_drops(
config: dict,
emu_profiles: dict,
expected_systems: dict,
db: dict | None,
*,
target_cores: set[str] | None,
opts: _PlatformCheckSettings,
) -> set[str]:
"""The regional variants the builder leaves out, by the same selection."""
region_drops: set[str] = set()
if not opts.regions:
return region_drops
region_index = resolve_regions.platform_region_index(
config, emu_profiles, target_cores
)
held: set[str] = set()
held_zip_contents = build_zip_contents_index(db, collection_root(Path(BIOS_DIR))) if db is not None else {}
region_groups, _extra_dests = platform_region_groups(
config,
expected_systems,
opts.emulators_dir,
db,
config.get("base_destination", ""),
emu_profiles,
target_cores=target_cores,
include_extras=(opts.source != "platform"),
include_all=(opts.source == "truth"),
required_only=opts.required_only,
held_out=held,
zip_contents=held_zip_contents,
data_registry=opts.data_registry,
slot_overrides=slots.pack_overrides(
config, emu_profiles, db, held_zip_contents, opts.data_registry,
target_cores=target_cores, source=opts.source,
) if db is not None else None,
)
return resolve_regions.resolve_region_drops(
region_groups, region_index, opts.regions, held
)
def _pack_view(zf: zipfile.ZipFile, config: dict, base_dest: str) -> _PackView:
zip_set = set(zf.namelist())
# A case twin stands in for the file only where the platform's
# filesystem folds case, as the builder decides: on Lakka bios.col
# and BIOS.col are two files two cores open, and either one missing
# was counted present through the other.
zip_lower = (
{n.lower(): n for n in zip_set}
if config.get("case_insensitive_fs", False) else {}
)
# Auto-detect flat vs nested ZIP
is_flat = bool(base_dest) and not any(
n.startswith(base_dest + "/")
for n in zip_set
if n not in (*PACK_DOCUMENTS, MEDIA_MARKER) and not n.endswith("/")
)
# Mirror the builder's path-conflict logic: a declaration whose path
# collides file-vs-directory with a packed member was skipped by the
# builder (upstream declares e.g. both SGB1.sfc and SGB1.sfc/program.rom)
zip_parents: set[str] = set()
for n in zip_set:
parts = n.split("/")
for i in range(1, len(parts)):
zip_parents.add("/".join(parts[:i]))
return _PackView(zf, zip_set, zip_lower, zip_parents, is_flat)
def _baseline_groups(
expect: _Expectation, is_flat: bool,
) -> tuple[dict[str, list[dict]], dict[int, str]]:
"""The platform's declarations by the path they expect in the pack, and
the system of each declaration."""
opts = expect.opts
base_dest = expect.base_dest
baseline_groups: dict[str, list[dict]] = {}
system_of: dict[int, str] = {}
for sys_id, system in (expect.expected_systems if opts.source != "truth" else {}).items():
for fe in system.get("files", []):
system_of[id(fe)] = sys_id
if opts.required_only and fe.get("required") is False:
continue
dest = declared_destination(fe)
if not dest:
continue
if expect.region_drops and dest in expect.region_drops:
continue
expected = f"{base_dest}/{dest}" if base_dest and not is_flat else dest
baseline_groups.setdefault(expected, []).append(fe)
return baseline_groups, system_of
def _count_baseline(
expect: _Expectation,
view: _PackView,
baseline_groups: dict[str, list[dict]],
system_of: dict[int, str],
errors: list[str],
) -> _BaselineCount:
"""Each baseline destination present, accounted for, or missing."""
db = expect.db
data_registry = expect.opts.data_registry
count = _BaselineCount(checked=len(baseline_groups))
# RetroBat's group: one packed file of it is enough, as verify counts it.
packed_groups = {
(system_of[id(fe)], fe["group"])
for expected, declarations in baseline_groups.items()
if view.holds(expected)
for fe in declarations
if fe.get("group")
}
exclusion_index = build_zip_contents_index(db, collection_root(Path(BIOS_DIR))) if db is not None else {}
categories = EntryCategories(expect.config, expect.emu_profiles, data_registry)
for expected, declarations in baseline_groups.items():
if expected in view.zip_set:
member = expected
elif expected.lower() in view.zip_lower:
member = view.zip_lower[expected.lower()]
elif has_path_conflict(expected, view.zip_set, view.zip_parents):
# Skipped by the builder for the same reason: not an error
count.present += 1
continue
elif db is not None and _intentional_hash_exclusion(
declarations,
db,
zip_contents=exclusion_index,
data_dir_registry=data_registry,
verification_mode=platform_mode(expect.config),
hash_rule=expect.config.get("hash_rule", ""),
):
count.excluded += 1
continue
elif all(
fe.get("group") and (system_of[id(fe)], fe["group"]) in packed_groups
for fe in declarations
):
count.absent += 1
continue
elif db is not None and all(
categories.category(fe, fe.get("destination", fe.get("name", "")),
system_of[id(fe)]) != BIOS
for fe in declarations
) and _held_nowhere(declarations, db, exclusion_index, data_registry):
# A game's data or an entry no core opens that the collection
# lacks: verify counts it apart. Missing firmware stays an error.
count.absent += 1
continue
else:
errors.append(f"baseline missing: {expected}")
continue
count.present += 1
count.decl_by_member.setdefault(member, []).extend(declarations)
return count
def _check_core_extras(
expect: _Expectation,
view: _PackView,
baseline_groups: dict[str, list[dict]],
errors: list[str],
) -> tuple[int, int]:
"""(checked, present) of the core extras the builder places."""
# 2. Core extras: the builder's own placement replayed
# (packextras.hidden_extras, which verify reads too), after the
# platform files it wrote. Each placed extra must sit at its path
# with the bytes the builder resolved: an empty seen set and a
# presence test credited a core file at a path where the pack
# holds the platform's other dump.
core_checked = 0
core_present = 0
opts = expect.opts
db = expect.db
if db is None or opts.source == "platform":
return core_checked, core_present
placed_local = _builder_extras(
expect, db, baseline_groups, view, include_all=(opts.source == "truth"),
)
for full, local in sorted(placed_local.items()):
core_checked += 1
flat = flat_arcname(full, expect.base_dest, view.is_flat)
member = flat if flat in view.zip_set else view.zip_lower.get(flat.lower())
if member is None:
errors.append(f"core missing: {full}")
elif not _same_content(view.zf, member, local):
errors.append(
f"core file differs: {member} is not the {os.path.basename(local)}"
" the builder places there"
)
else:
core_present += 1
return core_checked, core_present
def verify_pack_against_platform(
zip_path: str,
platform_name: str,
platforms_dir: str,
db: dict | None = None,
*,
target_cores: set[str] | None = None,
**options: Unpack[PlatformCheckOptions],
) -> tuple[bool, int, int, list[str], int, int, int, int, int, int]:
"""Verify a pack ZIP against its platform config and core requirements.
A region priority list narrows the expectation to what the builder would
have packed, using the same selection function. A hardware target narrows
it the same way and for the same reason: the systems it removes are not
missing from the pack, they were never asked for. ``source`` and
``required_only`` are the variant the pack was built as: a platform-only
pack is held to the platform's list alone, a truth pack to the cores'
files alone, and a required-only pack to the required entries of both.
``no_game_data`` holds the pack to the firmware alone, cut as the
builder cuts it.
Checks:
1. Every baseline file declared by the platform exists in the ZIP
at the correct destination path
2. Every in-repo core extra file (from emulator profiles) is present
3. No duplicate entries
4. No path anomalies (double slash, absolute, traversal)
5. No unexpected zero-byte BIOS files
Returns ``(all_ok, checked, present, errors, baseline_checked,
baseline_present, core_checked, core_present, baseline_excluded,
baseline_absent)``. ``baseline_absent`` counts destinations the collection
holds no file for that are a game's data or that no core the platform
runs opens. verify.py counts them apart from firmware.
"""
reject_unknown(
"verify_pack_against_platform", options, PlatformCheckOptions.__optional_keys__
)
opts = _PlatformCheckSettings(**options)
config, emu_profiles = _cut_config(platform_name, platforms_dir, target_cores, opts)
# The systems the builder packed, by the one rule verify and the pack read.
expected_systems = platform_scope_systems(config, emu_profiles, target_cores)
expect = _Expectation(
config, emu_profiles, expected_systems,
_region_drops(
config, emu_profiles, expected_systems, db,
target_cores=target_cores, opts=opts,
),
db, target_cores, opts,
)
errors: list[str] = []
with zipfile.ZipFile(zip_path, "r") as zf:
view = _pack_view(zf, expect.config, expect.base_dest)
errors.extend(_structural_errors(zf, view.zip_set))
# 1. Baseline file presence + native hash check
baseline_groups, system_of = _baseline_groups(expect, view.is_flat)
baseline = _count_baseline(expect, view, baseline_groups, system_of, errors)
errors.extend(native_hash_errors(zf, baseline.decl_by_member, expect.config, db))
core_checked, core_present = _check_core_extras(expect, view, baseline_groups, errors)
return (
len(errors) == 0,
baseline.checked + core_checked,
baseline.present + core_present,
errors,
baseline.checked,
baseline.present,
core_checked,
core_present,
baseline.excluded,
baseline.absent,
)
def baseline_shortfall(excluded: int, absent: int) -> list[str]:
"""Why a verified pack holds fewer baseline files than the platform declares."""
parts = []
if excluded:
parts.append(f"{excluded} unsafe excluded")
if absent:
parts.append(f"{absent} not in the collection")
return parts
@dataclass(frozen=True)
class PackConformance:
"""A pack checked against one platform, as verify_pack_against_platform returns it."""
ok: bool
checked: int
present: int
errors: list[str]
baseline_checked: int
baseline_present: int
core_checked: int
core_present: int
baseline_excluded: int
baseline_absent: int
@property
def shortfall(self) -> list[str]:
"""Why the baseline holds fewer files than the platform declares."""
return baseline_shortfall(self.baseline_excluded, self.baseline_absent)
def check_pack_conformance(
zip_path: str,
platform_name: str,
platforms_dir: str,
db: dict | None = None,
*,
target_cores: set[str] | None = None,
**options: Unpack[ConformanceOptions],
) -> PackConformance | None:
"""A pack checked against its platform under the variant its name says.
The build and --verify-packs both read this, so a pack gets one verdict:
a required-only, platform-only or truth pack is held to its own
expectation, never skipped by one and failed by the other. None for a
one-per-slot pack, whose slot choice the check does not replay.
"""
variant = pack_variant(os.path.basename(zip_path))
if variant is None:
return None
source, required_only = variant
return PackConformance(*verify_pack_against_platform(
zip_path, platform_name, platforms_dir, db,
target_cores=target_cores, source=source, required_only=required_only, **options,
))
+1 -1
View File
@@ -23,7 +23,7 @@ COMMANDS = {
"packs/manifest.py", "packs/manifestbuild.py", "packs/finalize.py", "packs/outputdir.py", "packs/variants.py",
"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/emulatorentries.py", "packs/integrity.py", "packs/packhashes.py", "packs/platformcheck.py",
"packs/hashinput.py", "packs/hashlookup.py", "packs/executable.py",
"packs/declsettle.py",
),
+2 -2
View File
@@ -141,7 +141,7 @@ class IntegrityChecksEveryMember(unittest.TestCase):
def test_a_missing_member_is_an_error_when_the_repository_holds_it(self):
import yaml
from packs import integrity as packverify
from packs import platformcheck
roms = {f"r{i}.bin": bytes([i]) * 32 for i in range(3)}
with tempfile.TemporaryDirectory() as tmp:
@@ -172,7 +172,7 @@ class IntegrityChecksEveryMember(unittest.TestCase):
zf.writestr("r0.bin", roms["r0.bin"])
with zipfile.ZipFile("pack.zip", "w") as zf:
zf.writestr("bios/set.zip", inner.getvalue())
ok, *_rest, = packverify.verify_pack_against_platform(
ok, *_rest, = platformcheck.verify_pack_against_platform(
"pack.zip", "p", "platforms", db, emulators_dir="emulators", emu_profiles={})
errors = _rest[2]
self.assertFalse(ok)
+4 -4
View File
@@ -37,7 +37,7 @@ from scripts.resolve import regionaudit, regions
from scripts.resolve.localfile import resolve_local_file
from scripts.core.ziptools import safe_extract_zip
from scripts.packs.extras import _emulator_region_group
from scripts.packs.integrity import verify_pack_against_platform
from scripts.packs.platformcheck import verify_pack_against_platform
from scripts.packs.targets import generate_target_manifests
HAS_JSONSCHEMA = jsonschema is not None
@@ -1471,7 +1471,7 @@ class OneBaselineVerdict(unittest.TestCase):
without d32.rom is one the builder left out on purpose."""
import hashlib
from scripts.packs.integrity import _intentional_hash_exclusion
from scripts.packs.platformcheck import _intentional_hash_exclusion
entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""}
with tempfile.TemporaryDirectory() as directory:
@@ -6267,7 +6267,7 @@ class ZippedFileMd5IsParsedOnce(unittest.TestCase):
for module in ("resolve/acceptance.py", "verify.py"):
source = script_source(module)
self.assertIn("parse_hash_list(", source, module)
self.assertIn("inner_rom_data_check(", script_source("packs/integrity.py"))
self.assertIn("inner_rom_data_check(", script_source("packs/packhashes.py"))
@@ -6960,7 +6960,7 @@ class ThePackCheckAppliesTheFrontendRule(unittest.TestCase):
import hashlib
import zipfile
from scripts.packs.integrity import _check_member_hash
from scripts.packs.packhashes import _check_member_hash
payload = b"revision B"
entry = {
+10 -10
View File
@@ -5429,7 +5429,7 @@ struct BurnDriver BurnDrvneogeo = {
"""Pack verification reproduces the native md5 check per member."""
import tempfile
from packs.integrity import verify_pack_against_platform
from packs.platformcheck import verify_pack_against_platform
with tempfile.TemporaryDirectory() as tmpdir:
plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture(
@@ -5452,7 +5452,7 @@ struct BurnDriver BurnDrvneogeo = {
"""Pack verification passes when member bytes match declared md5."""
import tempfile
from packs.integrity import verify_pack_against_platform
from packs.platformcheck import verify_pack_against_platform
with tempfile.TemporaryDirectory() as tmpdir:
plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture(
@@ -5474,7 +5474,7 @@ struct BurnDriver BurnDrvneogeo = {
import tempfile
from packs.platformpack import generate_pack
from packs.integrity import verify_pack_against_platform
from packs.platformcheck import verify_pack_against_platform
profiles = {"eng": {"emulator": "Eng", "type": "game", "cores": ["eng"],
"systems": ["arcade-sys"],
@@ -5724,7 +5724,7 @@ struct BurnDriver BurnDrvneogeo = {
import hashlib as hl
import tempfile
from packs.integrity import _check_member_hash
from packs.packhashes import _check_member_hash
rom = b"inner rom bytes"
rom_md5 = hl.md5(rom).hexdigest()
@@ -6427,13 +6427,13 @@ struct BurnDriver BurnDrvneogeo = {
"""
import inspect
from packs import integrity as packverify
from packs import platformcheck
from packs.naming import pack_narrowings, pack_variant
source = inspect.getsource(packverify.verify_pack_against_platform)
source = inspect.getsource(platformcheck.verify_pack_against_platform)
self.assertIn(
"target_cores",
inspect.signature(packverify.verify_pack_against_platform).parameters,
inspect.signature(platformcheck.verify_pack_against_platform).parameters,
"the pack verifier takes no target, so it cannot narrow by one",
)
self.assertIn(
@@ -6687,7 +6687,7 @@ struct BurnDriver BurnDrvneogeo = {
import typing
from packs.platformpack import generate_pack
from packs.integrity import verify_pack_against_platform
from packs.platformcheck import verify_pack_against_platform
self._create_region_fixtures()
profiles = self._region_profiles()
@@ -6775,7 +6775,7 @@ struct BurnDriver BurnDrvneogeo = {
self.assertIn("All are included", text)
def test_verify_agrees_with_region_filtered_pack(self):
from packs.integrity import verify_pack_against_platform
from packs.platformcheck import verify_pack_against_platform
out = self._region_pack(regions=["north-america"])
result = verify_pack_against_platform(
@@ -6790,7 +6790,7 @@ struct BurnDriver BurnDrvneogeo = {
self.assertTrue(ok, errors)
def test_verify_reports_the_gap_without_the_region_filter(self):
from packs.integrity import verify_pack_against_platform
from packs.platformcheck import verify_pack_against_platform
out = self._region_pack(regions=["north-america"])
result = verify_pack_against_platform(
+1 -1
View File
@@ -17,7 +17,7 @@ from pathlib import Path
from model.database import declared_records, record_for_hash, records_for_hash
from packs.crossrefsource import entry_source
from packs.integrity import _repo_satisfies_declaration
from packs.packhashes import _repo_satisfies_declaration
from resolve.lookup import held_record_for
from resolve.acceptance import _variant_candidates
+1 -1
View File
@@ -68,7 +68,7 @@ class TheIntegrityCheckFoldsCaseLikeTheBuilder(unittest.TestCase):
of the two passed step 6."""
def test_case_folding_reads_the_platform(self):
source = (REPO_ROOT / "scripts" / "packs" / "integrity.py").read_text(encoding="utf-8")
source = (REPO_ROOT / "scripts" / "packs" / "platformcheck.py").read_text(encoding="utf-8")
compact = " ".join(source.split())
self.assertRegex(
compact,
+1 -1
View File
@@ -84,7 +84,7 @@ class BothConsumersAgree(unittest.TestCase):
"""verify.py and generate_pack.py must answer the same for every mode."""
def test_builder_and_verifier_share_one_predicate(self):
from packs.integrity import _intentional_hash_exclusion
from packs.platformcheck import _intentional_hash_exclusion
from packs.verdicts import compute_severity
self.assertTrue(callable(compute_severity))
+3 -3
View File
@@ -34,7 +34,7 @@ from packs import archive as packs_archive
from packs import manifest as packs_manifest
from packs import platformpack
import install
from packs import integrity as packverify
from packs import platformcheck
from packs import coverage
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -190,14 +190,14 @@ class PackNarrowing(_Fixture):
)
self.assertEqual(set(result["pack_destinations"]), members)
self.assertTrue(any("doom/doom1.wad" in line for line in result["left_out"]))
checked = packverify.verify_pack_against_platform(
checked = platformcheck.verify_pack_against_platform(
zip_path, "handheld", str(self.platforms), db=self.db,
emulators_dir=str(self.emulators), emu_profiles=PROFILES,
no_game_data=True,
)
self.assertTrue(checked[0], checked[3])
# Held to the full list, the narrowed pack is short of the game data.
full = packverify.verify_pack_against_platform(
full = platformcheck.verify_pack_against_platform(
zip_path, "handheld", str(self.platforms), db=self.db,
emulators_dir=str(self.emulators), emu_profiles=PROFILES,
)
+3 -3
View File
@@ -18,7 +18,7 @@ from unittest import mock
from packs import platformrun
from packs import finalize as packs_finalize
from packs import integrity as packverify
from packs import platformcheck
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -75,7 +75,7 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase):
), \
mock.patch.object(packs_finalize, "inject_manifest"), \
mock.patch.object(packs_finalize, "_target_cores_for", return_value=None), \
mock.patch.object(packverify, "verify_pack_against_platform", record):
mock.patch.object(platformcheck, "verify_pack_against_platform", record):
packs_finalize.verify_and_finalize_packs(
str(out), {"files": {}, "indexes": {}},
platforms_dir="fixture-platforms",
@@ -110,7 +110,7 @@ class TheBuildChecksEachVariantAsVerifyPacksDoes(unittest.TestCase):
), \
mock.patch.object(packs_finalize, "inject_manifest"), \
mock.patch.object(packs_finalize, "_target_cores_for", return_value=None), \
mock.patch.object(packverify, "verify_pack_against_platform", record):
mock.patch.object(platformcheck, "verify_pack_against_platform", record):
packs_finalize.verify_and_finalize_packs(
tmp, {"files": {}, "indexes": {}}, platforms_dir="fixture-platforms",
)
+4 -4
View File
@@ -22,7 +22,7 @@ import yaml
from packs import naming
from packs import platformpack
from packs import integrity as packverify
from packs import platformcheck
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -69,7 +69,7 @@ class CoreFilesAsTheBuilderPlacesThem(unittest.TestCase):
with zipfile.ZipFile("pack.zip", "w") as zf:
zf.writestr("fuse/trdos.rom", b"platform dump")
zf.writestr("core/other.rom", other)
return packverify.verify_pack_against_platform(
return platformcheck.verify_pack_against_platform(
"pack.zip", "p", "platforms", self.db, emulators_dir="emulators",
emu_profiles=self.profiles,
)
@@ -122,7 +122,7 @@ class ARefusedPinLeavesItsPathToTheCore(unittest.TestCase):
def _check(self, member: bytes) -> tuple:
with zipfile.ZipFile("pack.zip", "w") as zf:
zf.writestr("dc/naomi.zip", member)
return packverify.verify_pack_against_platform(
return platformcheck.verify_pack_against_platform(
"pack.zip", "p", "platforms", self.db, emulators_dir="emulators",
emu_profiles=self.profiles,
)
@@ -200,7 +200,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase):
return zip_path, set(zf.namelist()) - {"README.txt"}
def _check(self, zip_path: str, source: str, required: bool) -> tuple:
return packverify.verify_pack_against_platform(
return platformcheck.verify_pack_against_platform(
zip_path, "p", "platforms", self.db, emulators_dir="emulators",
emu_profiles=self.profiles, source=source, required_only=required,
)
+4 -4
View File
@@ -345,26 +345,26 @@ class APackForAndroidHidesItsMedia(PackCountFixture):
self.assertEqual(manifest["pack_files"], len(set(members) | {"manifest.json"}))
def test_the_integrity_check_takes_it_for_a_marker(self):
from packs import integrity as packverify
from packs import platformcheck
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr(".nomedia", b"")
archive.writestr("empty.bin", b"")
with zipfile.ZipFile(buffer) as archive:
errors = packverify._structural_errors(archive, set(archive.namelist()))
errors = platformcheck._structural_errors(archive, set(archive.namelist()))
self.assertEqual(errors, ["zero-byte: empty.bin"])
def test_the_integrity_check_reads_paths_like_core_ziptools(self):
""""Read..me" was reported as a traversal, a backslash one was not."""
from packs import integrity as packverify
from packs import platformcheck
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("Docs/Read..me.txt", b"r")
archive.writestr("..\\escape.bin", b"x")
with zipfile.ZipFile(buffer) as archive:
errors = packverify._structural_errors(archive, set(archive.namelist()))
errors = platformcheck._structural_errors(archive, set(archive.namelist()))
self.assertEqual(errors, ["ZIP traversal detected: ../escape.bin"])
def test_a_platform_without_android_gets_none(self):
+1 -1
View File
@@ -34,7 +34,7 @@ class OnlyThePlatformsCores(unittest.TestCase):
self.assertTrue(regions.build_region_index(PROFILES)["bios_CD_E.bin"]["has_untagged"])
def test_every_platform_site_reads_it(self):
for module in ("verify.py", "generate_pack.py", "packs/integrity.py"):
for module in ("verify.py", "generate_pack.py", "packs/platformcheck.py"):
source = script_source(module)
self.assertNotIn("build_region_index(emu_profiles", source, module)
self.assertNotIn("build_region_index(profiles)", source, module)
+4 -1
View File
@@ -21,7 +21,10 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
class ValidationIndexScope(unittest.TestCase):
def test_no_index_over_every_profile(self):
pattern = re.compile(r"build_validation_index\(\s*(emu_)?profiles\s*\)")
for name in ("verify.py", "generate_pack.py", "packs/integrity.py", "packs/extras.py"):
for name in (
"verify.py", "generate_pack.py", "packs/integrity.py", "packs/packhashes.py",
"packs/platformcheck.py", "packs/extras.py",
):
source = script_source(name)
with self.subTest(module=name):
self.assertIsNone(pattern.search(source))
+1 -1
View File
@@ -18,7 +18,7 @@ from pathlib import Path
from core.ziptools import build_zip_contents_index, zip_members
from packs.supplemental import archive_members
from packs.integrity import _same_content
from packs.platformcheck import _same_content
from sitegen.cards import _release_name
from sitegen.lookup import _archive_member_records
+3 -3
View File
@@ -15,7 +15,7 @@ import json
import os
import tempfile
import unittest
from packs import integrity
from packs import platformcheck
from packs import naming
from packs import packcheck
from packs import variants
@@ -71,7 +71,7 @@ class VerifyPackChoice(unittest.TestCase):
self.variants: list[tuple[str, bool]] = []
with mock.patch.object(integrity, "verify_pack_against_platform", record):
with mock.patch.object(platformcheck, "verify_pack_against_platform", record):
self.ok = packcheck.run_verify_packs(args)
return checked
@@ -144,7 +144,7 @@ class VerifyPackChoice(unittest.TestCase):
self._touch(pack)
out, err = io.StringIO(), io.StringIO()
failed = (False, 0, 0, ["x: missing"], 1, 0, 1, 1, 0, 0)
with mock.patch.object(integrity, "verify_pack_against_platform",
with mock.patch.object(platformcheck, "verify_pack_against_platform",
return_value=failed), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
self.assertFalse(packcheck.run_verify_packs(self._args()))
+2 -2
View File
@@ -96,7 +96,7 @@ class PackIntegrityChecksTheMember(unittest.TestCase):
def _verdict(self, members: dict[str, bytes], entry: dict) -> str | None:
import io
from packs.integrity import _check_member_hash
from packs.packhashes import _check_member_hash
inner = io.BytesIO()
with zipfile.ZipFile(inner, "w") as zf:
@@ -128,7 +128,7 @@ class PackIntegrityChecksTheMember(unittest.TestCase):
import contextlib
import io
from packs.integrity import _check_member_hash
from packs.packhashes import _check_member_hash
pack = io.BytesIO()
with zipfile.ZipFile(pack, "w") as zf: