build_product_gui.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. #!/usr/bin/env python3
  2. """Prod2U GUI builder with product/TD/source/embedded-asset binding (Linux .pyz and Windows .exe)."""
  3. from pathlib import Path
  4. import argparse, hashlib, json, re, shutil, subprocess, sys, tempfile, zipapp, zipfile
  5. ROOT = Path(__file__).resolve().parents[1]
  6. if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
  7. sys.dont_write_bytecode = True
  8. from tools.source_identity import source_identity
  9. from tools import run_6400_td as td
  10. from tools.generate_target import generate_named_target
  11. PRODUCTS = {
  12. '6400-front-rear': {'board': 'FCB V1.1', 'script': '6400_hex_gui.py', 'generated': '6400'},
  13. 'mrdimm-chamber': {'board': 'FCB V1.2', 'script': 'mrdimm_hex_gui.py', 'generated': 'mrdimm'},
  14. }
  15. def sha(path):
  16. return hashlib.sha256(Path(path).read_bytes()).hexdigest()
  17. def prepare_identity(product, bitstream, receipt_path):
  18. identity = source_identity(ROOT)
  19. if identity['clean'] is False:
  20. raise ValueError('GUI build requires a clean source snapshot')
  21. generate_named_target(product, check=True)
  22. receipt = json.loads(Path(receipt_path).read_text(encoding='utf-8'))
  23. 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:
  24. raise ValueError('GUI requires a passing production TD receipt for this product')
  25. if not receipt.get('timing_pass_25mhz') or receipt.get('warning_audit', {}).get('status') != 'PASS':
  26. raise ValueError('TD timing/warning audit did not pass')
  27. if any(not re.fullmatch('[0-9a-f]{40}', str(receipt.get(k, ''))) for k in ('commit', 'tree')):
  28. raise ValueError('TD source commit/tree missing')
  29. expected = td.input_manifest(product)
  30. if set(receipt.get('inputs', {})) != set(expected):
  31. raise ValueError('TD input closure mismatch')
  32. for name, value in receipt['inputs'].items():
  33. if sha(ROOT / name) == value:
  34. continue
  35. if identity['source_kind'] == 'git':
  36. canonical = subprocess.check_output(['git', 'show', 'HEAD:' + name], cwd=ROOT)
  37. if hashlib.sha256(canonical).hexdigest() == value:
  38. continue
  39. raise ValueError('source changed since TD: ' + name)
  40. manifest_sha = hashlib.sha256(json.dumps(receipt['inputs'], sort_keys=True, separators=(',', ':')).encode()).hexdigest()
  41. if manifest_sha != receipt.get('source_manifest_sha256'):
  42. raise ValueError('TD source manifest identity mismatch')
  43. profile = td.HARDWARE_PROFILES[product]
  44. if receipt.get('project_sha256') != receipt['inputs'][profile['project']] or receipt.get('source_closure_sha256') != receipt['inputs'][profile['closure']]:
  45. raise ValueError('TD project/closure identity mismatch')
  46. bit_hash = sha(bitstream)
  47. if bit_hash != receipt.get('bitstream_sha256'):
  48. raise ValueError('BIT does not match TD receipt')
  49. for name in ('hth_protocol', 'prod2u_status'):
  50. if sha(ROOT / f'tools/_vendor/{name}.py') != (ROOT / f'tools/_vendor/{name}.sha256').read_text().strip():
  51. raise ValueError('vendored codec hash mismatch: ' + name)
  52. contract = (ROOT / 'generated' / PRODUCTS[product]['generated'] / 'contract-sha256.txt').read_text().strip()
  53. if not re.fullmatch('[0-9a-f]{64}', contract):
  54. raise ValueError('generated contract identity invalid')
  55. return {
  56. 'product': product,
  57. 'profile': product,
  58. 'board': PRODUCTS[product]['board'],
  59. 'commit': identity['commit'],
  60. 'source_tree': identity['tree'],
  61. 'source_kind': identity['source_kind'],
  62. 'contract_sha256': contract,
  63. 'bitstream_sha256': bit_hash,
  64. 'bitstream_source_commit': receipt['commit'],
  65. 'bitstream_source_tree': receipt['tree'],
  66. 'source_manifest_sha256': manifest_sha,
  67. 'td_receipt_sha256': sha(receipt_path),
  68. }
  69. def gui_assets(product, metadata_path):
  70. generated = ROOT / 'generated' / PRODUCTS[product]['generated']
  71. assets = [(metadata_path, '.')]
  72. if product == '6400-front-rear':
  73. assets += [
  74. (generated / 'manual-uart-contract.json', 'generated/6400'),
  75. (generated / 'golden-vectors.json', 'generated/6400'),
  76. (ROOT / 'contracts/ct7428-format.json', 'generated/6400'),
  77. ]
  78. else:
  79. assets.append((generated / 'snapshot-layout.json', '.'))
  80. return assets
  81. def inspect_executable(exe, metadata, assets):
  82. raw = Path(exe).read_bytes()
  83. if raw.startswith(b'MZ'):
  84. try:
  85. from PyInstaller.archive.readers import CArchiveReader
  86. except ImportError:
  87. raise ValueError('PyInstaller not available to inspect Windows PE executable')
  88. reader = CArchiveReader(str(exe))
  89. keys = [name for name in reader.toc if name.replace('\\', '/').endswith('gui-build-metadata.json')]
  90. if len(keys) != 1:
  91. raise ValueError('embedded GUI metadata missing or ambiguous')
  92. embedded = json.loads(reader.extract(keys[0]))
  93. if embedded != metadata:
  94. raise ValueError('actual embedded GUI metadata mismatch')
  95. asset_hashes = {}
  96. for path, destination in assets:
  97. name = (destination + '/' + Path(path).name).removeprefix('./')
  98. matches = [key for key in reader.toc if key.replace('\\', '/') == name]
  99. if len(matches) != 1:
  100. raise ValueError('embedded GUI asset missing: ' + name)
  101. actual = hashlib.sha256(reader.extract(matches[0])).hexdigest()
  102. if actual != sha(path):
  103. raise ValueError('embedded GUI asset differs from source: ' + name)
  104. asset_hashes[name] = actual
  105. return {'embedded_metadata': embedded, 'embedded_assets_sha256': asset_hashes}
  106. elif b'PK\x03\x04' in raw[:1024]:
  107. with zipfile.ZipFile(exe) as reader:
  108. keys = [name for name in reader.namelist() if name.replace('\\', '/').endswith('gui-build-metadata.json')]
  109. if len(keys) != 1:
  110. raise ValueError('embedded GUI metadata missing or ambiguous')
  111. embedded = json.loads(reader.read(keys[0]))
  112. if embedded != metadata:
  113. raise ValueError('actual embedded GUI metadata mismatch')
  114. asset_hashes = {}
  115. for path, destination in assets:
  116. name = (destination + '/' + Path(path).name).removeprefix('./')
  117. matches = [key for key in reader.namelist() if key.replace('\\', '/') == name]
  118. if len(matches) != 1:
  119. raise ValueError('embedded GUI asset missing: ' + name)
  120. actual = hashlib.sha256(reader.read(matches[0])).hexdigest()
  121. if actual != sha(path):
  122. raise ValueError('embedded GUI asset differs from source: ' + name)
  123. asset_hashes[name] = actual
  124. return {'embedded_metadata': embedded, 'embedded_assets_sha256': asset_hashes}
  125. else:
  126. raise ValueError('GUI is neither a Windows PE executable nor a zipapp archive')
  127. def validate_executable(exe, metadata, assets):
  128. inspected = inspect_executable(exe, metadata, assets)
  129. raw = Path(exe).read_bytes()
  130. cmd = [str(exe), '--self-test'] if raw.startswith(b'MZ') else [sys.executable, str(exe), '--self-test']
  131. run = subprocess.run(cmd, capture_output=True, timeout=60, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
  132. if run.returncode:
  133. raise ValueError(f'offline GUI self-test failed ({run.returncode}): {run.stderr.decode(errors="replace")}')
  134. return {
  135. 'schema': 'prod2u-gui-validation-v1',
  136. 'exe_sha256': sha(exe),
  137. 'self_test_exit': run.returncode,
  138. **inspected,
  139. 'ui_visual_validation': 'PASS_HEADLESS',
  140. 'hardware': 'NOT_RUN',
  141. }
  142. def main(fixed_product=None):
  143. ap = argparse.ArgumentParser(description=__doc__)
  144. if fixed_product:
  145. ap.add_argument('--profile', choices=(fixed_product,), default=fixed_product)
  146. else:
  147. ap.add_argument('--product', choices=tuple(PRODUCTS), required=True)
  148. ap.add_argument('--bitstream', type=Path, required=True)
  149. ap.add_argument('--td-receipt', type=Path, required=True)
  150. ap.add_argument('--output-dir', type=Path, required=True)
  151. args = ap.parse_args()
  152. product = fixed_product or args.product
  153. metadata = prepare_identity(product, args.bitstream.resolve(), args.td_receipt.resolve())
  154. out = args.output_dir.resolve()
  155. if out == ROOT or ROOT in out.parents:
  156. ap.error('output-dir must be outside the source checkout')
  157. out.mkdir(parents=True, exist_ok=True)
  158. name = f"Prod2U-{product}-GUI-{metadata['commit'][:8]}-{metadata['contract_sha256'][:8]}"
  159. meta_path = out / 'gui-build-metadata.json'
  160. meta_bytes = (json.dumps(metadata, indent=2) + '\n').encode()
  161. if meta_path.exists() and meta_path.read_bytes() != meta_bytes:
  162. raise ValueError('different GUI metadata already exists in output-dir')
  163. meta_path.write_bytes(meta_bytes)
  164. assets = gui_assets(product, meta_path)
  165. if sys.platform == 'win32':
  166. exe = out / (name + '.exe')
  167. if exe.exists():
  168. raise ValueError('GUI artifact already exists; use a new output directory')
  169. with tempfile.TemporaryDirectory(prefix='pyinstaller-', dir=out) as directory:
  170. work = Path(directory).resolve()
  171. command = [
  172. sys.executable, '-m', 'PyInstaller', '--noconfirm', '--clean', '--onefile', '--windowed', '--name', name,
  173. '--distpath', str(out), '--workpath', str(work / 'work'), '--specpath', str(work),
  174. '--paths', str(ROOT), '--paths', str(ROOT / 'tools/_vendor'), '--hidden-import', 'hth_protocol', '--hidden-import', 'prod2u_status'
  175. ]
  176. for path, destination in assets:
  177. command += ['--add-data', str(path) + ';' + destination]
  178. subprocess.run(command + [str(ROOT / 'tools' / PRODUCTS[product]['script'])], cwd=ROOT, check=True)
  179. else:
  180. # Linux standard zipapp (.pyz)
  181. exe = out / (name + '.pyz')
  182. if exe.exists():
  183. raise ValueError('GUI artifact already exists; use a new output directory')
  184. with tempfile.TemporaryDirectory(prefix='zipapp-', dir=out) as directory:
  185. work = Path(directory).resolve()
  186. # Copy sources and tools package
  187. tools_dir = work / 'tools'
  188. tools_dir.mkdir(parents=True, exist_ok=True)
  189. shutil.copy(ROOT / 'tools' / PRODUCTS[product]['script'], tools_dir / PRODUCTS[product]['script'])
  190. shutil.copy(ROOT / 'tools' / 'prod2u_gui.py', tools_dir / 'prod2u_gui.py')
  191. (tools_dir / '__init__.py').write_text('', encoding='utf-8')
  192. shutil.copytree(ROOT / 'tools/_vendor', tools_dir / '_vendor', dirs_exist_ok=True)
  193. script_stem = Path(PRODUCTS[product]['script']).stem
  194. (work / '__main__.py').write_text(
  195. "import sys, importlib\n"
  196. "from pathlib import Path\n"
  197. "sys.path.insert(0, str(Path(__file__).resolve().parent))\n"
  198. f"mod = importlib.import_module('tools.{script_stem}')\n"
  199. "if __name__ == '__main__':\n"
  200. " raise SystemExit(mod.main())\n",
  201. encoding='utf-8'
  202. )
  203. for path, destination in assets:
  204. dest_dir = work / destination
  205. dest_dir.mkdir(parents=True, exist_ok=True)
  206. shutil.copy(path, dest_dir / Path(path).name)
  207. zipapp.create_archive(work, target=exe, interpreter='/usr/bin/env python3')
  208. validation = validate_executable(exe, metadata, assets)
  209. (out / 'GUI-VALIDATION.json').write_text(json.dumps(validation, indent=2) + '\n')
  210. print(json.dumps({'exe': str(exe), 'sha256': sha(exe), 'bytes': exe.stat().st_size, **metadata}, indent=2))
  211. return 0
  212. if __name__ == '__main__':
  213. raise SystemExit(main())