| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241 |
- #!/usr/bin/env python3
- """Compatibility builder for local .pyz/.exe. Production Windows builds use build_windows_exes_remote.py."""
- from pathlib import Path
- import argparse, hashlib, json, re, shutil, subprocess, sys, tempfile, zipapp, zipfile
- 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'},
- '6400-v2': {'board': '6400V2.0', 'script': '6400_v2_hex_gui.py', 'generated': '6400-v2'},
- }
- 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
- 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')
- if receipt.get('build_parameters', {}).get('host_baud') not in (921600, 460800, 230400, 115200):
- raise ValueError('TD receipt must specify the actual firmware host_baud')
- return {
- 'product': product,
- 'profile': product,
- 'release_version': (ROOT / 'VERSION').read_text().strip(),
- 'host_baud': receipt['build_parameters']['host_baud'],
- 'bmc_baud': 115200,
- '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 gui_assets(product, metadata_path):
- generated = ROOT / 'generated' / PRODUCTS[product]['generated']
- assets = [(metadata_path, '.'), (ROOT / 'VERSION', '.')]
- if product in ('6400-front-rear', '6400-v2'):
- destination = 'generated/' + PRODUCTS[product]['generated']
- assets += [
- (generated / 'manual-uart-contract.json', destination),
- (generated / 'golden-vectors.json', destination),
- (ROOT / 'contracts/ct7428-format.json', destination),
- ]
- else:
- assets.append((generated / 'snapshot-layout.json', '.'))
- return assets
- def inspect_executable(exe, metadata, assets):
- raw = Path(exe).read_bytes()
- if raw.startswith(b'MZ'):
- try:
- from PyInstaller.archive.readers import CArchiveReader
- except ImportError:
- raise ValueError('PyInstaller not available to inspect 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')
- asset_hashes = {}
- for path, destination in assets:
- name = (destination + '/' + Path(path).name).removeprefix('./')
- matches = [key for key in reader.toc if key.replace('\\', '/') == name]
- if len(matches) != 1:
- raise ValueError('embedded GUI asset missing: ' + name)
- actual = hashlib.sha256(reader.extract(matches[0])).hexdigest()
- if actual != sha(path):
- raise ValueError('embedded GUI asset differs from source: ' + name)
- asset_hashes[name] = actual
- return {'embedded_metadata': embedded, 'embedded_assets_sha256': asset_hashes}
- elif b'PK\x03\x04' in raw[:1024]:
- with zipfile.ZipFile(exe) as reader:
- keys = [name for name in reader.namelist() if name.replace('\\', '/').endswith('gui-build-metadata.json')]
- if len(keys) != 1:
- raise ValueError('embedded GUI metadata missing or ambiguous')
- embedded = json.loads(reader.read(keys[0]))
- if embedded != metadata:
- raise ValueError('actual embedded GUI metadata mismatch')
- asset_hashes = {}
- for path, destination in assets:
- name = (destination + '/' + Path(path).name).removeprefix('./')
- matches = [key for key in reader.namelist() if key.replace('\\', '/') == name]
- if len(matches) != 1:
- raise ValueError('embedded GUI asset missing: ' + name)
- actual = hashlib.sha256(reader.read(matches[0])).hexdigest()
- if actual != sha(path):
- raise ValueError('embedded GUI asset differs from source: ' + name)
- asset_hashes[name] = actual
- return {'embedded_metadata': embedded, 'embedded_assets_sha256': asset_hashes}
- else:
- raise ValueError('GUI is neither a Windows PE executable nor a zipapp archive')
- def validate_executable(exe, metadata, assets):
- inspected = inspect_executable(exe, metadata, assets)
- raw = Path(exe).read_bytes()
- cmd = [str(exe), '--self-test'] if raw.startswith(b'MZ') else [sys.executable, str(exe), '--self-test']
- run = subprocess.run(cmd, capture_output=True, timeout=60, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
- if run.returncode:
- raise ValueError(f'offline GUI self-test failed ({run.returncode}): {run.stderr.decode(errors="replace")}')
- return {
- 'schema': 'prod2u-gui-validation-v1',
- 'exe_sha256': sha(exe),
- 'self_test_exit': run.returncode,
- **inspected,
- 'ui_visual_validation': 'NOT_RUN',
- '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()
- 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-v{metadata['release_version']}-{metadata['commit'][:8]}-{metadata['contract_sha256'][:8]}"
- 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)
- assets = gui_assets(product, meta_path)
- if sys.platform == 'win32':
- exe = out / (name + '.exe')
- if exe.exists():
- raise ValueError('GUI artifact already exists; use a new output directory')
- with tempfile.TemporaryDirectory(prefix='pyinstaller-', dir=out) as directory:
- work = Path(directory).resolve()
- command = [
- sys.executable, '-m', 'PyInstaller', '--noconfirm', '--clean', '--onefile', '--windowed', '--name', name,
- '--distpath', str(out), '--workpath', str(work / 'work'), '--specpath', str(work),
- '--paths', str(ROOT), '--paths', str(ROOT / 'tools/_vendor'), '--hidden-import', 'hth_protocol', '--hidden-import', 'prod2u_status',
- '--hidden-import', 'serial', '--hidden-import', 'serial.tools.list_ports'
- ]
- for path, destination in assets:
- command += ['--add-data', str(path) + ';' + destination]
- subprocess.run(command + [str(ROOT / 'tools' / PRODUCTS[product]['script'])], cwd=ROOT, check=True)
- else:
- # Linux standard zipapp (.pyz)
- exe = out / (name + '.pyz')
- if exe.exists():
- raise ValueError('GUI artifact already exists; use a new output directory')
- with tempfile.TemporaryDirectory(prefix='zipapp-', dir=out) as directory:
- work = Path(directory).resolve()
- # Copy sources and tools package
- tools_dir = work / 'tools'
- tools_dir.mkdir(parents=True, exist_ok=True)
- shutil.copy(ROOT / 'tools' / PRODUCTS[product]['script'], tools_dir / PRODUCTS[product]['script'])
- shutil.copy(ROOT / 'tools' / 'prod2u_gui.py', tools_dir / 'prod2u_gui.py')
- shutil.copy(ROOT / 'tools' / 'stream_receiver.py', tools_dir / 'stream_receiver.py')
- (tools_dir / '__init__.py').write_text('', encoding='utf-8')
- shutil.copytree(ROOT / 'tools/_vendor', tools_dir / '_vendor', dirs_exist_ok=True)
- script_stem = Path(PRODUCTS[product]['script']).stem
- (work / '__main__.py').write_text(
- "import sys, importlib\n"
- "from pathlib import Path\n"
- "sys.path.insert(0, str(Path(__file__).resolve().parent))\n"
- f"mod = importlib.import_module('tools.{script_stem}')\n"
- "if __name__ == '__main__':\n"
- " raise SystemExit(mod.main())\n",
- encoding='utf-8'
- )
- for path, destination in assets:
- dest_dir = work / destination
- dest_dir.mkdir(parents=True, exist_ok=True)
- shutil.copy(path, dest_dir / Path(path).name)
- zipapp.create_archive(work, target=exe, interpreter='/usr/bin/env python3')
- validation = validate_executable(exe, metadata, assets)
- (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())
|