#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Validate the offline-only Phase-1.0F startup interval artifact record.""" from __future__ import annotations import argparse import json from pathlib import Path import subprocess from typing import Any PHASE = "PHASE_1_0F_STARTUP_INTERVAL_DIAGNOSTIC" STATUS = "OFFLINE_ARTIFACT_PREPARED_NO_DEVICE_AUTHORIZATION" SOURCE_COMMIT = "0eaf68d6de4dc9757d85cc7ad5c714b1d151c8f8" ARTIFACT_SHA256 = "e8bfc01c61bfb14b5814280a6e5442f1a5ad05ace5439d1c09e7e5ee00cd0055" ARTIFACT_SIZE = 1845152 MAP_SHA256 = "638642b750b8d5b108cf6c73215a3f1759bcb6da0b29ee0a0ade5c47e8b7b2d5" MAP_SIZE = 637603 DISASSEMBLY_SHA256 = "32725415b86a8b3aafbd8b7fa2d089633a3cf90935b111e3c175bdd28dde242a" AUTHORIZATION_FIELDS = ( "ps5_connection_authorized", "device_transfer_authorized", "device_execution_authorized", "result_receive_authorized", "installation_authorized", "autoload_authorized", "device_write_authorized", "automatic_retry", ) ACTION_FIELDS = ( "ps5_connected", "device_request_performed", "files_transferred", "device_write_performed", "target_execution_performed", "result_received_from_device", "installation_performed", "autoload_performed", ) FORBIDDEN_IMPORTS = { "socket", "connect", "bind", "listen", "accept", "recv", "recvfrom", "sendto", "dlopen", "dlsym", "sceGnmSubmitCommandBuffers", "sceGnmSubmitAndFlipCommandBuffers", } DELIVERABLES = ( "docs/retroarch/phase-1.0f-startup-interval.md", "docs/approvals/phase-1.0f-device-test-template.md", "manifests/retroarch/phase-1.0f-startup-interval.json", "tools/validate_retroarch_phase10f.py", "tests/test_retroarch_phase10f.py", "packaging/retroarch/phase10f/SHA256SUMS.txt", ) def load_json(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"{path} is not a JSON object") return value def git(root: Path, *args: str) -> str: result = subprocess.run( ["git", *args], cwd=root, capture_output=True, text=True, check=False ) if result.returncode: raise RuntimeError(result.stderr.strip() or "git failed") return result.stdout.strip() def all_false(record: dict[str, Any], fields: tuple[str, ...]) -> bool: return all(record.get(field) is False for field in fields) def artifact_is_exact(record: dict[str, Any]) -> bool: return ( record.get("size") == ARTIFACT_SIZE and record.get("sha256") == ARTIFACT_SHA256 and record.get("clean_build_sha256") == [ARTIFACT_SHA256] * 2 and record.get("linker_map_size") == MAP_SIZE and record.get("linker_map_sha256") == MAP_SHA256 and record.get("clean_map_sha256") == [MAP_SHA256] * 2 and record.get("execution_eligible") is False and record.get("transfer_eligible") is False and record.get("installation_eligible") is False and record.get("device_action_performed") is False and record.get("tracked") is False ) def protocol_is_bounded(record: dict[str, Any]) -> bool: return ( record.get("magic") == "CHD10F01" and record.get("version") == 1 and record.get("frame_size") == 64 and record.get("interval_stages") == [f"I{index:02d}" for index in range(15)] and record.get("interval_notification_calls") == 0 and record.get("interval_notification_result_sentinel") == -2147483648 and record.get("target_write_attempts_per_reached_stage") == 1 and record.get("target_write_retry") is False and record.get("short_write_retry") is False and record.get("new_target_imports_from_phase10e") == [] and set(record.get("forbidden_target_imports_absent", [])) == {"socket", "connect", "bind", "listen", "accept", "recv"} ) def interval_callsites_are_complete(items: list[dict[str, Any]]) -> bool: return ( len(items) == 15 and [item.get("stage") for item in items] == [f"I{index:02d}" for index in range(15)] and len({item.get("address") for item in items}) == 15 and all(item.get("source") and item.get("function") for item in items) ) def elf_is_closed(record: dict[str, Any], phase10e: dict[str, Any]) -> bool: headers = record.get("program_headers", []) imports = record.get("undefined_symbols", []) old_imports = phase10e.get("elf", {}).get("undefined_symbols", []) return ( record.get("rwx_load_segment_count") == 0 and len(headers) == 3 and all(not ({"W", "E"} <= set(item.get("flags", ""))) for item in headers) and record.get("preinit_array_size") == 0 and record.get("init_array_size") == 0 and record.get("fini_array_size") == 0 and record.get("tls") is False and record.get("relocations", {}).get("total") == 1055 and record.get("undefined_symbol_count") == len(imports) == 142 and imports == old_imports and not (set(imports) & FORBIDDEN_IMPORTS) and "send" in imports ) def parser_is_offline_only(record: dict[str, Any]) -> bool: return ( record.get("offline_interval_parser_available") is True and record.get("live_cli_defaults_to_consumed_phase10e_protocol") is True and record.get("live_interval_activation_available") is False and record.get("manifest_must_be_execution_eligible") is True and record.get("authorization_must_be_active_and_exact") is True and record.get("retry") is False and record.get("reconnect") is False and record.get("resume") is False and record.get("trace_overwrite") is False ) def validate(root: Path, retroarch_root: Path | None = None) -> list[str]: errors: list[str] = [] for relative in DELIVERABLES: if not (root / relative).is_file(): errors.append(f"missing deliverable: {relative}") try: record = load_json( root / "manifests/retroarch/phase-1.0f-startup-interval.json" ) phase10e = load_json( root / "manifests/retroarch/phase-1.0e-result-channel.json" ) except (OSError, ValueError, json.JSONDecodeError) as error: return errors + [str(error)] if record.get("phase") != PHASE or record.get("status") != STATUS: errors.append("phase/status mismatch") if record.get("source_commit") != SOURCE_COMMIT: errors.append("source commit mismatch") if not all_false(record.get("authorizations", {}), AUTHORIZATION_FIELDS): errors.append("all Phase-1.0F authorizations must remain false") if not all_false(record.get("phase_actions", {}), ACTION_FIELDS): errors.append("Phase-1.0F must record no device action") prior = record.get("prior_evidence", {}) if not ( prior.get("last_proven_stage") == "D02" and prior.get("d02_raw0") == 0 and prior.get("authorization_consumed") is True and prior.get("authority_inherited") is False ): errors.append("prior RUN-C evidence is overclaimed or incomplete") if not artifact_is_exact(record.get("artifact", {})): errors.append("artifact identity/reproducibility mismatch") if not protocol_is_bounded(record.get("result_protocol", {})): errors.append("interval protocol is not bounded") if not interval_callsites_are_complete(record.get("interval_callsites", [])): errors.append("interval callsite matrix is incomplete") reachability = record.get("static_reachability", {}) if reachability.get("normalized_disassembly_sha256") != [DISASSEMBLY_SHA256] * 2: errors.append("normalized disassembly is not reproducible") if not elf_is_closed(record.get("elf", {}), phase10e): errors.append("ELF/import closure mismatch") if not parser_is_offline_only(record.get("host_parser", {})): errors.append("host parser is not offline/fail-closed") effects = record.get("startup_effects", {}) if not ( effects.get("patch_init_reachable_from_start") is True and effects.get("interval_notification_effect") == "NONE" and effects.get("side_effect_free") is False ): errors.append("startup effects are hidden or overclaimed") tests = record.get("tests", {}) if not ( tests.get("double_clean_build") == "PASS_BYTE_IDENTICAL" and tests.get("hardware_evidence_from_phase10f") is False ): errors.append("offline tests are missing or mislabeled as hardware evidence") tracked = git(root, "ls-files").splitlines() if any(path.lower().endswith((".elf", ".self", ".sprx", ".pkg", ".map")) for path in tracked): errors.append("target artifact or linker map is tracked") sums = (root / "packaging/retroarch/phase10f/SHA256SUMS.txt").read_text( encoding="utf-8" ) if ARTIFACT_SHA256 not in sums or MAP_SHA256 not in sums: errors.append("hash-only record is incomplete") if retroarch_root is not None: try: git(retroarch_root, "cat-file", "-e", f"{SOURCE_COMMIT}^{{commit}}") stream = git( retroarch_root, "show", f"{SOURCE_COMMIT}:pkg/ps5/chimera_ps5_diag_stream.c", ) interval = git( retroarch_root, "show", f"{SOURCE_COMMIT}:pkg/ps5/chimera_ps5_interval_diag.c", ) if ( "CHIMERA_PS5_INTERVAL_DIAG" not in stream or "'C', 'H', 'D', '1', '0', 'F', '0', '1'" not in stream ): errors.append("source commit lacks Phase-1.0F magic") if "chimera_ps5_diag_stream_emit" not in interval or "send(" in interval: errors.append("source commit interval wrapper is not stream-only") except RuntimeError as error: errors.append(str(error)) return errors def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--root", type=Path, required=True) parser.add_argument("--retroarch-root", type=Path) args = parser.parse_args() errors = validate(args.root.resolve(), args.retroarch_root) if errors: for error in errors: print(f"ERROR: {error}") return 1 print("Phase-1.0F offline startup interval validation passed") return 0 if __name__ == "__main__": raise SystemExit(main())