152 lines
7.6 KiB
Python
152 lines
7.6 KiB
Python
"""Stage the already-built Windows x64 Release with its redistributable runtime."""
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import shutil
|
||
import struct
|
||
import subprocess
|
||
import zipfile
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
NAME = 'CmvrControlStation-Windows-x64-Release'
|
||
|
||
|
||
def pe_imports(file):
|
||
data = file.read_bytes()
|
||
if data[:2] != b'MZ':
|
||
raise ValueError(f'Not a Windows executable: {file}')
|
||
pe = struct.unpack_from('<I', data, 0x3c)[0]
|
||
if data[pe:pe + 4] != b'PE\0\0':
|
||
raise ValueError(f'Invalid PE header: {file}')
|
||
machine, count = struct.unpack_from('<HH', data, pe + 4)
|
||
optional_size = struct.unpack_from('<H', data, pe + 20)[0]
|
||
optional = pe + 24
|
||
magic = struct.unpack_from('<H', data, optional)[0]
|
||
directory = optional + (112 if magic == 0x20b else 96)
|
||
import_rva = struct.unpack_from('<I', data, directory + 8)[0]
|
||
section_start = optional + optional_size
|
||
sections = [struct.unpack_from('<8sIIII', data, section_start + i * 40)
|
||
for i in range(count)]
|
||
|
||
def offset(rva):
|
||
for _, virtual_size, virtual_address, raw_size, raw_start in sections:
|
||
if virtual_address <= rva < virtual_address + max(virtual_size, raw_size):
|
||
return raw_start + rva - virtual_address
|
||
if rva < section_start:
|
||
return rva
|
||
raise ValueError(f'Unmapped import RVA in {file}')
|
||
|
||
imports = []
|
||
if import_rva:
|
||
cursor = offset(import_rva)
|
||
while True:
|
||
descriptor = struct.unpack_from('<IIIII', data, cursor)
|
||
if not any(descriptor):
|
||
break
|
||
start = offset(descriptor[3])
|
||
imports.append(data[start:data.index(b'\0', start)].decode('ascii'))
|
||
cursor += 20
|
||
return machine, imports
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument('--qt', default='C:/Qt/Qt5.12.4/5.12.4/mingw73_64')
|
||
parser.add_argument('--compiler', default='C:/Qt/Qt5.12.4/Tools/mingw730_64/bin')
|
||
args = parser.parse_args()
|
||
qt, compiler = Path(args.qt), Path(args.compiler)
|
||
built = ROOT / 'bin/release/CmvrControlStation.exe'
|
||
deploy = qt / 'bin/windeployqt.exe'
|
||
if not built.is_file() or not deploy.is_file():
|
||
raise RuntimeError('Build the Release application and provide its matching Qt kit first')
|
||
stage = ROOT / 'dist' / NAME
|
||
if stage.parent.resolve() != (ROOT / 'dist').resolve() or stage.name != NAME:
|
||
raise RuntimeError('Unexpected staging path')
|
||
if stage.exists():
|
||
shutil.rmtree(stage)
|
||
stage.mkdir(parents=True)
|
||
shutil.copy2(built, stage / built.name)
|
||
for dll in (ROOT / 'lib').glob('*.dll'):
|
||
shutil.copy2(dll, stage / dll.name)
|
||
for name in ['libgcc_s_seh-1.dll', 'libstdc++-6.dll', 'libwinpthread-1.dll']:
|
||
shutil.copy2(compiler / name, stage / name)
|
||
env = dict(os.environ)
|
||
env['PATH'] = str(qt / 'bin') + os.pathsep + str(compiler) + os.pathsep + env.get('PATH', '')
|
||
print('Deploying Qt Release runtime...', flush=True)
|
||
subprocess.run([str(deploy), '--release', '--compiler-runtime', '--no-translations',
|
||
str(stage / built.name)], env=env, check=True)
|
||
subprocess.run(['powershell.exe', '-NoProfile', '-ExecutionPolicy', 'RemoteSigned',
|
||
'-File', str(ROOT / 'scripts/repair_qt3d_release.ps1'),
|
||
'-RuntimeDirectory', str(stage)], check=True)
|
||
scene = stage / 'sceneparsers'
|
||
scene.mkdir(exist_ok=True)
|
||
shutil.copy2(qt / 'plugins/sceneparsers/assimpsceneimport.dll', scene / 'assimpsceneimport.dll')
|
||
shutil.copytree(ROOT / 'models', stage / 'models')
|
||
shutil.copytree(ROOT / 'third_party/handeye-runtime', stage / 'runtime/handeye',
|
||
ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
|
||
algorithms = stage / 'scripts'
|
||
algorithms.mkdir()
|
||
for name in ['handeye_worker.py', 'handeye_math.py', 'handeye_refinement.py']:
|
||
shutil.copy2(ROOT / 'scripts' / name, algorithms / name)
|
||
(stage / 'data').mkdir()
|
||
shutil.copy2(ROOT / 'resources/application_settings.json', stage / 'data/application_settings.json')
|
||
for name in ['quic-test-server.pfx', 'quic-test-ca.crt']:
|
||
shutil.copy2(ROOT / 'certs' / name, stage / name)
|
||
(stage / 'qt.conf').write_text('[Paths]\nPlugins=.\n', encoding='utf-8')
|
||
(stage / '使用说明.txt').write_text(
|
||
'CMVR 控制台 Windows x64 Release 免安装包\n\n'
|
||
'完整解压到可写目录,双击 CmvrControlStation.exe。不要只复制 exe。\n'
|
||
'已包含 Qt 5.12.4、MinGW运行库、音视频DLL、Qt插件、模型与手眼标定Python环境。\n'
|
||
'普通界面使用不需要另行安装Qt;手眼标定使用随包运行环境。\n'
|
||
'无实物演示:勾选“演示模式”,地址填127.0.0.1,再连接。确认提示“演示数据源”。\n'
|
||
'使用真实设备时取消演示模式,核实服务地址和设备状态后再操作。\n'
|
||
'图形驱动有问题时可尝试“启动_兼容模式.cmd”,使用软件OpenGL。\n'
|
||
'本包为Windows 64位程序,不适用于麒麟Linux;未在其他电脑上实机验证。\n'
|
||
'quic-test-server.pfx为工程开发测试证书,仅供QUIC测试。\n', encoding='utf-8-sig')
|
||
(stage / '启动_兼容模式.cmd').write_bytes(
|
||
b'@echo off\r\ncd /d "%~dp0"\r\nset "QT_OPENGL=software"\r\n'
|
||
b'"%~dp0CmvrControlStation.exe"\r\n')
|
||
|
||
# Check imports of the executable, redistributable root DLLs and Qt plugins.
|
||
# Windows API-set names are virtual OS modules, not redistributable files.
|
||
system = Path(os.environ.get('SystemRoot', 'C:/Windows')) / 'System32'
|
||
binaries = [stage / built.name] + list(stage.glob('*.dll'))
|
||
binaries += [p for p in stage.glob('*/*.dll') if p.parent.name not in ['runtime']]
|
||
missing = []
|
||
for binary in binaries:
|
||
machine, imports = pe_imports(binary)
|
||
if machine != 0x8664:
|
||
raise RuntimeError(f'Not x64: {binary}')
|
||
for name in imports:
|
||
if name.lower().startswith(('api-ms-', 'ext-ms-')):
|
||
continue
|
||
if not any((folder / name).exists() for folder in [binary.parent, stage, system]):
|
||
missing.append((str(binary.relative_to(stage)), name))
|
||
if missing:
|
||
raise RuntimeError(f'Missing DLL dependencies: {missing}')
|
||
# Qt's debug configuration is recorded in its plugin metadata.
|
||
if any((stage / name).exists() for name in ['Qt5Cored.dll', 'Qt5Guid.dll', 'Qt5Widgetsd.dll', 'platforms/qwindowsd.dll']):
|
||
raise RuntimeError('Debug Qt DLL detected in Release package')
|
||
manifest = {}
|
||
for file in sorted(stage.rglob('*')):
|
||
if file.is_file():
|
||
manifest[file.relative_to(stage).as_posix()] = hashlib.sha256(file.read_bytes()).hexdigest()
|
||
(stage / 'SHA256.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
|
||
archive = stage.with_suffix('.zip')
|
||
print(f'Writing archive ({len(manifest)} files)...', flush=True)
|
||
with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED, compresslevel=5) as output:
|
||
for file in sorted(stage.rglob('*')):
|
||
if file.is_file():
|
||
output.write(file, NAME + '/' + file.relative_to(stage).as_posix())
|
||
with zipfile.ZipFile(archive) as output:
|
||
if output.testzip() is not None:
|
||
raise RuntimeError('ZIP integrity validation failed')
|
||
print(json.dumps({'archive': str(archive), 'size_bytes': archive.stat().st_size,
|
||
'pe_files_checked': len(binaries), 'files': len(manifest) + 1}, ensure_ascii=False))
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|