#!/usr/bin/env python3 """Minimal multi-target firmware entry. Users remember: target + action.""" from __future__ import annotations import argparse import hashlib import json import os import re import signal import subprocess import sys import tempfile import uuid import xml.etree.ElementTree as ET from pathlib import Path ROOT = Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from tools.fw_targets import list_aliases, load_registry, resolve_target as resolve_dict, target_status_line from tools.generate_target import generate_named_target from tools.target_registry import TargetError, resolve_target from tools.source_identity import source_identity def _new_run_path(name: str) -> Path: base=Path(os.environ.get('XDG_STATE_HOME') or tempfile.gettempdir())/'prod2u/fw' return base/(name+'-'+uuid.uuid4().hex[:12]) def _die(message: str, code: int = 2) -> int: print(message, file=sys.stderr) return code def cmd_list(_args: argparse.Namespace) -> int: for alias in list_aliases(ROOT): print(target_status_line(alias, ROOT)) return 0 def _generate_one(alias: str, *, check: bool=False) -> dict: return generate_named_target(alias, check=check) def cmd_generate(args: argparse.Namespace) -> int: names=list_aliases(ROOT) if args.target=='all' else (args.target,) for name in names: print(json.dumps(_generate_one(name,check=args.check),sort_keys=True)) return 0 def _python() -> str: return sys.executable def cmd_build(args: argparse.Namespace) -> int: target=resolve_target(args.target) if sys.platform!='linux':return _die('Run TD builds in the authorized Linux container') _generate_one(target.alias,check=True) out=args.run_root or _new_run_path(target.project_id+'-td') print('TD run: '+str(out.resolve()),flush=True) return subprocess.call([_python(),str(ROOT/'tools/run_6400_td.py'),'--profile',target.project_id,'--run-root',str(out)],cwd=ROOT) def cmd_test(args: argparse.Namespace) -> int: if sys.platform!='linux':return _die('Run current product verification in the authorized Linux container') products=tuple(resolve_target(name).project_id for name in list_aliases(ROOT)) if args.target=='all' else (resolve_target(args.target).project_id,) for product in products:_generate_one(product,check=True) out=(args.run_root or _new_run_path('current-regression')).resolve() if out==ROOT or ROOT in out.parents:return _die('--run-root must be outside the source checkout') out.mkdir(parents=True,exist_ok=False) manifest=json.loads((ROOT/'config/current-product-tests.json').read_text(encoding='utf-8')) unit_tests=list(manifest['shared_unit_tests']) for product in products:unit_tests.extend(manifest['targets'][product]['unit_tests']) unit_tests=list(dict.fromkeys(unit_tests)) if not unit_tests:return _die('empty current unit test set') identity=source_identity(ROOT) receipt={'schema':'prod2u-current-regression-v1','scope':'current unit and RTL regression; not Full acceptance', 'run_id':out.name,'products':products,'source':identity,'status':'RUNNING','complete':False} receipt_path=out/'RESULT.json' receipt_path.write_text(json.dumps(receipt,indent=2)+'\n') command=[_python(),'-m','pytest','-q',*unit_tests,'--junitxml='+str(out/'python.xml'),'--basetemp='+str(out/'pytest-temp')] log_path=out/'python.log' with log_path.open('w') as log: log.write(json.dumps(command)+'\n');log.flush() process=subprocess.Popen(command,cwd=ROOT,stdout=log,stderr=subprocess.STDOUT,start_new_session=True) try:unit_code=process.wait(timeout=args.timeout) except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();unit_code=124 unit_count=0;unit_errors=1;unit_skipped=1 try: suites=list(ET.parse(out/'python.xml').getroot().iter('testsuite')) unit_count=sum(int(x.get('tests','0')) for x in suites) unit_errors=sum(int(x.get('errors','0'))+int(x.get('failures','0')) for x in suites) unit_skipped=sum(int(x.get('skipped','0')) for x in suites) except (OSError,ET.ParseError,ValueError):pass unit_pass=unit_code==0 and unit_count>0 and unit_errors==0 and unit_skipped==0 receipt['unit']={'command':command,'exit_code':unit_code,'tests':unit_count,'skipped':unit_skipped,'status':'PASS' if unit_pass else 'FAIL','log':str(log_path),'log_sha256':hashlib.sha256(log_path.read_bytes()).hexdigest()} print('Unit tests: '+('PASS' if unit_pass else 'FAIL')+'; '+str(log_path),flush=True) rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)==2 else products[0],run_root=out/'rtl',timeout=args.timeout)) receipt['rtl_result']=str(out/'rtl/RESULT.json');receipt['complete']=True receipt['status']='PASS' if unit_pass and rtl_code==0 else 'FAIL' receipt_path.write_text(json.dumps(receipt,indent=2)+'\n') print(str(receipt_path),flush=True) return 0 if receipt['status']=='PASS' else (unit_code or rtl_code or 1) def cmd_package(args: argparse.Namespace) -> int: # There is only one public package implementation/command surface. from tools.package_prod2u import main as package_main return package_main(args.package_args) def cmd_diagnose(args: argparse.Namespace) -> int: """Bounded migrated RTL checks; explicitly not the full Quick/Full gate.""" if sys.platform != "linux": return _die("Run RTL diagnostics in the authorized LAN Linux container") out = args.run_root.resolve() if out == ROOT or ROOT in out.parents: return _die("--run-root must be outside the source checkout") out.mkdir(parents=True, exist_ok=False) products = ("6400-front-rear", "mrdimm-chamber") if args.target == "all" else (args.target,) test_manifest_path=ROOT/'config/current-product-tests.json' test_manifest=json.loads(test_manifest_path.read_text(encoding='utf-8')) if test_manifest.get('schema')!='prod2u-current-product-tests-v1': return _die('current test manifest schema mismatch') tests={name:entry['testbenches'] for name,entry in test_manifest['targets'].items()} if any(not tests[p] for p in products): return _die('empty current product test set') receipt = {"scope": "migration-diagnostic-only", "run_id": out.name, "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False, "expected_check_count": sum(1 + 2 * len(tests[p]) for p in products)} identity=source_identity(ROOT) receipt['commit']=identity['commit'];receipt['tree']=identity['tree'];receipt['source']=identity for tool, flag in (("iverilog", "-V"), ("vvp", "-V")): receipt[tool] = subprocess.check_output([tool, flag], stderr=subprocess.STDOUT, text=True).splitlines()[0] def execute(name: str, command: list[str], marker: str | None = None) -> bool: log_path = out / (name + ".log") with log_path.open("w", encoding="utf-8") as log: log.write(json.dumps(command) + "\n"); log.flush() process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) try: code = process.wait(timeout=args.timeout) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124 observed = log_path.read_text(errors="replace") passed = code == 0 and (marker is None or marker in observed) receipt["results"].append({"name": name, "command": command, "exit_code": code, "status": "PASS" if passed else "FAIL", "required_marker": marker, "log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()}) # An interrupted partial run must never look like a completed PASS. receipt["status"] = "RUNNING" (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n") print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True) return passed for product in products: manifest_path = ROOT / "products" / product / "source-closure.json" manifest = json.loads(manifest_path.read_text()) sources = manifest["sources"] benches = tests[product] contract_paths = ["contracts/6400-manual.yaml"] if product == "6400-front-rear" else ["contracts/mrdimm-wire.yaml", "projects/mrdimm-chamber/project.json"] input_paths = set(sources + contract_paths + [f"tests/sim/{test}.v" for test in benches]) input_paths.add(manifest_path.relative_to(ROOT).as_posix()) # Include transitive generated headers imported by the mailbox. input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "generated").rglob("*.vh")) input_paths.add("tools/fw_cli.py") input_paths.add("config/current-product-tests.json") input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "tests/sim").glob("*.vh")) if product == "6400-front-rear": input_paths.add("src/modules/double_bank_target_store.v") receipt["inputs"][product] = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in sorted(input_paths)} source_args = [p for p in sources if p.endswith(".v")] for top, behavior in [(manifest["top_module"], False), *((test, True) for test in benches)]: binary = out / (top + ".vvp") argv = ["iverilog", "-g2012", "-Wall", "-I.", "-s", top, "-o", str(binary), *source_args] if behavior: argv.append(f"tests/sim/{top}.v") if top == "prod2u_6400_uart_e2e_tb": argv.append("src/modules/double_bank_target_store.v") if execute(top + "-compile", argv) and behavior: execute(top, ["vvp", str(binary), "+ARTIFACT_DIR=" + str(out)], top + " PASS") receipt["complete"] = True receipt["artifacts"] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in out.glob("*.hex")} receipt["status"] = "PASS" if len(receipt["results"]) == receipt["expected_check_count"] and all( item["status"] == "PASS" for item in receipt["results"]) else "FAIL" (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n") return 0 if receipt["status"] == "PASS" else 1 def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="fw", description="Prod2U multi-target firmware entry") sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("list") gen = sub.add_parser("generate") gen.add_argument("target") gen.add_argument("--check",action="store_true") tes = sub.add_parser("test") tes.add_argument("target") tes.add_argument("--run-root",type=Path) tes.add_argument("--timeout",type=int,default=180) diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance") diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber")) diag.add_argument("--run-root", type=Path, required=True) diag.add_argument("--timeout", type=int, default=60) bld = sub.add_parser("build") bld.add_argument("target") bld.add_argument("--run-root",type=Path) pkg = sub.add_parser("package") pkg.add_argument("package_args",nargs=argparse.REMAINDER) args = parser.parse_args(argv) commands = { "list": cmd_list, "generate": cmd_generate, "test": cmd_test, "diagnose": cmd_diagnose, "build": cmd_build, "package": cmd_package, } try: return commands[args.command](args) except SystemExit as exc: return int(exc.code or 0) except (TargetError, ValueError, OSError) as exc: return _die(str(exc), 2) if __name__ == "__main__": load_registry(ROOT) raise SystemExit(main())