Jelajahi Sumber

fix(gui): share validated Windows builds and support exported source identity

codex 2 bulan lalu
induk
melakukan
ea630a93ee

+ 50 - 0
tests/unit/test_gui_build_identity.py

@@ -0,0 +1,50 @@
+from pathlib import Path
+import hashlib,json
+import pytest
+from tools import build_product_gui as gui
+
+@pytest.fixture(params=['6400-front-rear','mrdimm-chamber'])
+def build_context(tmp_path,monkeypatch,request):
+    product=request.param;root=tmp_path/'source';root.mkdir()
+    monkeypatch.setattr(gui,'ROOT',root)
+    monkeypatch.setattr(gui,'source_identity',lambda _: {'source_kind':'exported','clean':None,'commit':'a'*40,'tree':'b'*40})
+    monkeypatch.setattr(gui,'generate_named_target',lambda *a,**kw:None)
+    inputs={}
+    for name in ('model.v','project.json','closure.json'):
+        (root/name).write_text(name);inputs[name]=gui.sha(root/name)
+    monkeypatch.setattr(gui.td,'input_manifest',lambda _:inputs)
+    monkeypatch.setattr(gui.td,'HARDWARE_PROFILES',{product:{'project':'project.json','closure':'closure.json'}})
+    generated=root/'generated'/gui.PRODUCTS[product]['generated'];generated.mkdir(parents=True)
+    (generated/'contract-sha256.txt').write_text('c'*64+'\n')
+    vendor=root/'tools/_vendor';vendor.mkdir(parents=True)
+    for name in ('hth_protocol','prod2u_status'):
+        (vendor/(name+'.py')).write_bytes(b'codec fixture')
+        (vendor/(name+'.sha256')).write_text(gui.sha(vendor/(name+'.py')))
+    bit=tmp_path/'fixture.bit';bit.write_bytes(b'unit fixture, not a hardware bitstream')
+    receipt={'profile':product,'status':'PASS','production':True,'simulation_only':False,'timing_pass_25mhz':True,
+        'warning_audit':{'status':'PASS'},'commit':'d'*40,'tree':'e'*40,'inputs':inputs,
+        'source_manifest_sha256':hashlib.sha256(json.dumps(inputs,sort_keys=True,separators=(',',':')).encode()).hexdigest(),
+        'project_sha256':inputs['project.json'],'source_closure_sha256':inputs['closure.json'],'bitstream_sha256':gui.sha(bit)}
+    path=tmp_path/'receipt.json';path.write_text(json.dumps(receipt))
+    return product,root,bit,path,receipt
+
+def test_product_build_identity_uses_export_and_real_bit_hash(build_context):
+    product,_,bit,path,_=build_context
+    meta=gui.prepare_identity(product,bit,path)
+    assert meta['source_kind']=='exported' and meta['commit']=='a'*40
+    assert meta['bitstream_source_commit']=='d'*40 and meta['bitstream_source_tree']=='e'*40
+    assert meta['bitstream_sha256']==gui.sha(bit)
+    assert meta['product']==product
+
+@pytest.mark.parametrize('change',['profile','failed','timing','bit','source','missing_input','project_identity'])
+def test_gui_rejects_unqualified_or_mismatched_bit(build_context,change):
+    product,root,bit,path,receipt=build_context
+    if change=='profile':receipt['profile']='wrong-product'
+    elif change=='failed':receipt['status']='FAIL'
+    elif change=='timing':receipt['timing_pass_25mhz']=False
+    elif change=='bit':bit.write_bytes(b'changed')
+    elif change=='source':(root/'model.v').write_text('changed')
+    elif change=='missing_input':receipt['inputs']=dict(receipt['inputs']);receipt['inputs'].pop('model.v')
+    else:receipt['project_sha256']='0'*64
+    path.write_text(json.dumps(receipt))
+    with pytest.raises(ValueError):gui.prepare_identity(product,bit,path)

+ 6 - 83
tools/build_6400_hex_gui.py

@@ -1,85 +1,8 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-"""Build one profile-specific Windows HEX-only GUI from generated contracts."""
-
-from __future__ import annotations
-
-import argparse
-import hashlib
-import json
-import shutil
-import subprocess
-import sys
+"""Product-bound adapter to the shared Windows GUI builder."""
 from pathlib import Path
 from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-def sha(path: Path) -> str:
-    return hashlib.sha256(path.read_bytes()).hexdigest()
-
-
-def main() -> int:
-    parser = argparse.ArgumentParser()
-    parser.add_argument("--profile", choices=("6400-front-rear",), default="6400-front-rear")
-    parser.add_argument("--output-dir", type=Path, required=True)
-    parser.add_argument("--bitstream", type=Path, required=True,
-                        help="real TD bitstream file; its SHA-256 is computed here")
-    parser.add_argument("--wsl-source-root")
-    parser.add_argument('--td-receipt',type=Path,required=True)
-    args = parser.parse_args()
-    bitstream = args.bitstream.resolve()
-    if not bitstream.is_file():
-        raise SystemExit(f"bitstream file not found: {bitstream}")
-    bitstream_sha = hashlib.sha256(bitstream.read_bytes()).hexdigest()
-    td_receipt=json.loads(args.td_receipt.read_text(encoding='utf-8'))
-    if td_receipt.get('status')!='PASS' or td_receipt.get('bitstream_sha256')!=bitstream_sha:
-        raise SystemExit('BIT does not match a passing TD receipt')
-    changed=[name for name,value in td_receipt['inputs'].items() if not (ROOT/name).is_file() or sha(ROOT/name)!=value]
-    if changed:raise SystemExit('production inputs changed since TD: '+', '.join(changed))
-    contract_path = ROOT / "generated/6400/manual-uart-contract.json"
-    golden_path = ROOT / "generated/6400/golden-vectors.json"
-    contract = json.loads(contract_path.read_text(encoding="utf-8"))
-    golden = json.loads(golden_path.read_text(encoding="utf-8"))
-    if contract["contract_sha256"] != golden["contract_sha256"]:
-        raise SystemExit("contract/golden SHA mismatch")
-    git_prefix = ["git"]
-    git_cwd = ROOT
-    if args.wsl_source_root:
-        if sys.platform != "win32":
-            raise SystemExit("--wsl-source-root is only valid for the Windows GUI build")
-        git_prefix = ["wsl.exe", "-d", "Debian13", "--cd", args.wsl_source_root, "git"]
-        git_cwd = None
-    commit = subprocess.check_output([*git_prefix, "rev-parse", "HEAD"], cwd=git_cwd, text=True).strip()
-    if subprocess.check_output([*git_prefix, "status", "--porcelain"], cwd=git_cwd, text=True).strip():
-        raise SystemExit("GUI packaging requires an exact clean commit")
-    output = args.output_dir.resolve()
-    output.mkdir(parents=True, exist_ok=True)
-    meta = {"profile": args.profile, "commit": commit, "contract_sha256": contract["contract_sha256"], "bitstream_sha256": bitstream_sha}
-    meta['bitstream_source_commit']=td_receipt['commit']
-    meta['source_manifest_sha256']=td_receipt['source_manifest_sha256']
-    meta_path = output / "gui-build-metadata.json"
-    meta_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
-    name = f"6400-HEX-GUI-{args.profile}-{commit[:8]}-{contract['contract_sha256'][:8]}"
-    work = output / ("pyinstaller-" + args.profile)
-    sep = ";" if sys.platform == "win32" else ":"
-    command = [sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", "--onefile", "--windowed",
-        "--name", name, "--distpath", str(output), "--workpath", str(work), "--specpath", str(work),
-        "--add-data", f"{contract_path}{sep}generated/6400", "--add-data", f"{golden_path}{sep}generated/6400",
-        "--add-data", f"{meta_path}{sep}.",
-        "--add-data", f"{ROOT/'contracts/ct7428-format.json'}{sep}generated/6400",
-        "--paths", str(ROOT / "tools/_vendor"), "--hidden-import", "hth_protocol", "--hidden-import", "prod2u_status",
-        str(ROOT / "tools/6400_hex_gui.py")]
-    subprocess.run(command, cwd=ROOT, check=True)
-    exe = output / (name + (".exe" if sys.platform == "win32" else ""))
-    if sys.platform != "win32" or exe.read_bytes()[:2] != b"MZ":
-        raise SystemExit("Windows x64 Python/PyInstaller is required")
-    embedded = json.loads(meta_path.read_text(encoding="utf-8"))
-    if embedded["contract_sha256"] != contract["contract_sha256"]:
-        raise SystemExit("embedded GUI contract SHA mismatch")
-    print(json.dumps({"exe": str(exe), "sha256": sha(exe), **meta}, indent=2))
-    shutil.rmtree(work, ignore_errors=True)
-    return 0
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())
+import sys
+ROOT=Path(__file__).resolve().parents[1]
+if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
+from tools.build_product_gui import main
+if __name__=='__main__':raise SystemExit(main('6400-front-rear'))

+ 6 - 27
tools/build_mrdimm_hex_gui.py

@@ -1,29 +1,8 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-"""Build the product-bound MRDIMM offline GUI on Windows."""
-from __future__ import annotations
-import argparse, hashlib, json, shutil, subprocess, sys
+"""Product-bound adapter to the shared Windows GUI builder."""
 from pathlib import Path
 from pathlib import Path
-ROOT = Path(__file__).resolve().parents[1]
-def main() -> int:
-    ap = argparse.ArgumentParser(); ap.add_argument("--output-dir", type=Path, required=True); ap.add_argument("--bitstream", type=Path, required=True, help="real TD bitstream file"); a = ap.parse_args()
-    bitstream = a.bitstream.resolve()
-    if not bitstream.is_file(): raise SystemExit(f"bitstream file not found: {bitstream}")
-    bitstream_sha = hashlib.sha256(bitstream.read_bytes()).hexdigest()
-    contract_path = ROOT/"generated/mrdimm/snapshot-layout.json"
-    contract = json.loads(contract_path.read_text(encoding="utf-8")); out = a.output_dir.resolve(); out.mkdir(parents=True, exist_ok=True)
-    contract_sha = contract.get("contract_sha256") or hashlib.sha256(contract_path.read_bytes()).hexdigest()
-    commit = subprocess.check_output(["git","rev-parse","HEAD"], cwd=ROOT, text=True).strip()
-    if subprocess.check_output(["git","status","--porcelain"], cwd=ROOT, text=True).strip(): raise SystemExit("GUI packaging requires clean commit")
-    meta = {"product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"contract_sha256":contract_sha,"bitstream_sha256":bitstream_sha}
-    (out/"gui-build-metadata.json").write_text(json.dumps(meta, indent=2)+"\n", encoding="utf-8")
-    name = f"Prod2U-MRDIMM-V1.2-HEX-GUI-{commit[:8]}-{meta['contract_sha256'][:8]}"
-    work = out/("pyinstaller-"+name); sep = ";" if sys.platform == "win32" else ":"
-    status_codec=ROOT/'tools/_vendor/prod2u_status.py'
-    expected=(ROOT/'tools/_vendor/prod2u_status.sha256').read_text().strip()
-    if hashlib.sha256(status_codec.read_bytes()).hexdigest()!=expected:raise SystemExit('status codec hash mismatch')
-    cmd=[sys.executable,"-m","PyInstaller","--noconfirm","--clean","--onefile","--windowed","--name",name,"--distpath",str(out),"--workpath",str(work),"--specpath",str(work),"--add-data",f"{contract_path}{sep}.","--add-data",f"{out/'gui-build-metadata.json'}{sep}.","--paths",str(ROOT/"tools/_vendor"),"--hidden-import","hth_protocol","--hidden-import","prod2u_status",str(ROOT/"tools/mrdimm_hex_gui.py")]
-    subprocess.run(cmd,cwd=ROOT,check=True); exe=out/(name+(".exe" if sys.platform=="win32" else ""))
-    if sys.platform=="win32" and exe.read_bytes()[:2] != b"MZ": raise SystemExit("not a Windows PE")
-    zip_path=out/(name+".zip"); shutil.make_archive(str(zip_path.with_suffix("")),"zip",root_dir=out,base_dir=exe.name)
-    print(json.dumps({"exe":str(exe),"zip":str(zip_path),"sha256":hashlib.sha256(exe.read_bytes()).hexdigest(),**meta},indent=2)); shutil.rmtree(work,ignore_errors=True); return 0
-if __name__ == "__main__": raise SystemExit(main())
+import sys
+ROOT=Path(__file__).resolve().parents[1]
+if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
+from tools.build_product_gui import main
+if __name__=='__main__':raise SystemExit(main('mrdimm-chamber'))

+ 101 - 0
tools/build_product_gui.py

@@ -0,0 +1,101 @@
+#!/usr/bin/env python3
+"""One Windows GUI builder with product/TD/source/embedded-asset binding."""
+from pathlib import Path
+import argparse,hashlib,json,re,shutil,subprocess,sys,tempfile
+ROOT=Path(__file__).resolve().parents[1]
+if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
+sys.dont_write_bytecode=True
+from tools.source_identity import source_identity
+from tools import run_6400_td as td
+from tools.generate_target import generate_named_target
+
+PRODUCTS={'6400-front-rear':{'board':'FCB V1.1','script':'6400_hex_gui.py','generated':'6400'},
+          'mrdimm-chamber':{'board':'FCB V1.2','script':'mrdimm_hex_gui.py','generated':'mrdimm'}}
+def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
+
+def prepare_identity(product,bitstream,receipt_path):
+    identity=source_identity(ROOT)
+    if identity['clean'] is False:raise ValueError('GUI build requires a clean source snapshot')
+    generate_named_target(product,check=True)
+    receipt=json.loads(Path(receipt_path).read_text(encoding='utf-8'))
+    if receipt.get('profile')!=product or receipt.get('status')!='PASS' or receipt.get('production') is not True or receipt.get('simulation_only') is not False:
+        raise ValueError('GUI requires a passing production TD receipt for this product')
+    if not receipt.get('timing_pass_25mhz') or receipt.get('warning_audit',{}).get('status')!='PASS':
+        raise ValueError('TD timing/warning audit did not pass')
+    if any(not re.fullmatch('[0-9a-f]{40}',str(receipt.get(k,''))) for k in ('commit','tree')):
+        raise ValueError('TD source commit/tree missing')
+    expected=td.input_manifest(product)
+    if set(receipt.get('inputs',{}))!=set(expected):raise ValueError('TD input closure mismatch')
+    for name,value in receipt['inputs'].items():
+        if sha(ROOT/name)==value:continue
+        # Windows CRLF checkout may differ from the exact Linux Git content.
+        if identity['source_kind']=='git':
+            canonical=subprocess.check_output(['git','show','HEAD:'+name],cwd=ROOT)
+            if hashlib.sha256(canonical).hexdigest()==value:continue
+        raise ValueError('source changed since TD: '+name)
+    manifest_sha=hashlib.sha256(json.dumps(receipt['inputs'],sort_keys=True,separators=(',',':')).encode()).hexdigest()
+    if manifest_sha!=receipt.get('source_manifest_sha256'):raise ValueError('TD source manifest identity mismatch')
+    profile=td.HARDWARE_PROFILES[product]
+    if receipt.get('project_sha256')!=receipt['inputs'][profile['project']] or receipt.get('source_closure_sha256')!=receipt['inputs'][profile['closure']]:
+        raise ValueError('TD project/closure identity mismatch')
+    bit_hash=sha(bitstream)
+    if bit_hash!=receipt.get('bitstream_sha256'):raise ValueError('BIT does not match TD receipt')
+    for name in ('hth_protocol','prod2u_status'):
+        if sha(ROOT/f'tools/_vendor/{name}.py')!=(ROOT/f'tools/_vendor/{name}.sha256').read_text().strip():
+            raise ValueError('vendored codec hash mismatch: '+name)
+    contract=(ROOT/'generated'/PRODUCTS[product]['generated']/'contract-sha256.txt').read_text().strip()
+    if not re.fullmatch('[0-9a-f]{64}',contract):raise ValueError('generated contract identity invalid')
+    return {'product':product,'profile':product,'board':PRODUCTS[product]['board'],'commit':identity['commit'],
+            'source_tree':identity['tree'],'source_kind':identity['source_kind'],'contract_sha256':contract,
+            'bitstream_sha256':bit_hash,'bitstream_source_commit':receipt['commit'],'bitstream_source_tree':receipt['tree'],
+            'source_manifest_sha256':manifest_sha,'td_receipt_sha256':sha(receipt_path)}
+
+def validate_executable(exe,metadata):
+    from PyInstaller.archive.readers import CArchiveReader
+    if Path(exe).read_bytes()[:2]!=b'MZ':raise ValueError('GUI is not a Windows PE executable')
+    reader=CArchiveReader(str(exe))
+    keys=[name for name in reader.toc if name.replace('\\','/').endswith('gui-build-metadata.json')]
+    if len(keys)!=1:raise ValueError('embedded GUI metadata missing or ambiguous')
+    embedded=json.loads(reader.extract(keys[0]))
+    if embedded!=metadata:raise ValueError('actual embedded GUI metadata mismatch')
+    run=subprocess.run([str(exe),'--self-test'],capture_output=True,timeout=60,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
+    if run.returncode:raise ValueError('offline GUI self-test failed: '+str(run.returncode))
+    return {'schema':'prod2u-gui-validation-v1','exe_sha256':sha(exe),'self_test_exit':run.returncode,
+            'embedded_metadata':embedded,'ui_visual_validation':'PENDING','hardware':'NOT_RUN'}
+
+def main(fixed_product=None):
+    ap=argparse.ArgumentParser(description=__doc__)
+    if fixed_product:ap.add_argument('--profile',choices=(fixed_product,),default=fixed_product)
+    else:ap.add_argument('--product',choices=tuple(PRODUCTS),required=True)
+    ap.add_argument('--bitstream',type=Path,required=True);ap.add_argument('--td-receipt',type=Path,required=True)
+    ap.add_argument('--output-dir',type=Path,required=True);args=ap.parse_args()
+    if sys.platform!='win32':ap.error('Windows x64 Python/PyInstaller is required')
+    product=fixed_product or args.product
+    metadata=prepare_identity(product,args.bitstream.resolve(),args.td_receipt.resolve())
+    out=args.output_dir.resolve()
+    if out==ROOT or ROOT in out.parents:ap.error('output-dir must be outside the source checkout')
+    out.mkdir(parents=True,exist_ok=True)
+    name=f"Prod2U-{product}-GUI-{metadata['commit'][:8]}-{metadata['contract_sha256'][:8]}"
+    exe=out/(name+'.exe')
+    if exe.exists():raise ValueError('GUI artifact already exists; use a new output directory')
+    meta_path=out/'gui-build-metadata.json';meta_bytes=(json.dumps(metadata,indent=2)+'\n').encode()
+    if meta_path.exists() and meta_path.read_bytes()!=meta_bytes:raise ValueError('different GUI metadata already exists in output-dir')
+    meta_path.write_bytes(meta_bytes)
+    generated=ROOT/'generated'/PRODUCTS[product]['generated']
+    assets=[(meta_path,'.')]
+    if product=='6400-front-rear':
+        assets += [(generated/'manual-uart-contract.json','generated/6400'),(generated/'golden-vectors.json','generated/6400'),(ROOT/'contracts/ct7428-format.json','generated/6400')]
+    else:assets.append((generated/'snapshot-layout.json','.'))
+    with tempfile.TemporaryDirectory(prefix='pyinstaller-',dir=out) as directory:
+        work=Path(directory).resolve()
+        if work.parent!=out:raise ValueError('unexpected build workspace')
+        command=[sys.executable,'-m','PyInstaller','--noconfirm','--clean','--onefile','--windowed','--name',name,
+                 '--distpath',str(out),'--workpath',str(work/'work'),'--specpath',str(work),
+                 '--paths',str(ROOT/'tools/_vendor'),'--hidden-import','hth_protocol','--hidden-import','prod2u_status']
+        for path,destination in assets:command+=['--add-data',str(path)+';'+destination]
+        subprocess.run(command+[str(ROOT/'tools'/PRODUCTS[product]['script'])],cwd=ROOT,check=True)
+    validation=validate_executable(exe,metadata)
+    (out/'GUI-VALIDATION.json').write_text(json.dumps(validation,indent=2)+'\n')
+    print(json.dumps({'exe':str(exe),'sha256':sha(exe),'bytes':exe.stat().st_size,**metadata},indent=2))
+    return 0
+if __name__=='__main__':raise SystemExit(main())