build_product_gui.py 12 KB

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