#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Copy an optional locally built compiler runtime into an Xcode app bundle.""" import argparse import hashlib import json import os from pathlib import Path import shutil import subprocess import sys sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tools/toolchain")) sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tools")) from runtime_inputs import validate_private_inputs from build_content import content_profile MACHO = ('libexec/cmoc', 'bin/cpp', 'bin/mcpp', 'bin/make', 'bin/lwasm', 'bin/lwlink', 'bin/lwar', 'bin/writecocofile') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', type=Path) parser.add_argument('--destination', type=Path) args = parser.parse_args() profile = content_profile() source = args.source or (Path(os.environ.get('VCC_SOURCE_TOOLCHAIN_DIR') or str(Path(os.environ['SRCROOT']) / 'LocalResources/SourceToolchainBundle')) if profile == 'source' else Path(os.environ['SRCROOT']) / 'LocalResources/ToolchainBundle') destination = args.destination or (Path(os.environ['TARGET_BUILD_DIR']) / os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH'] / 'Toolchain') # Restrict cleanup to this build phase's app resource directory. if destination.name != 'Toolchain' or destination.parent.name != 'Resources' or destination.parent.parent.name != 'Contents' or destination.parent.parent.parent.suffix != '.app': parser.error('Destination must be APP.app/Contents/Resources/Toolchain') if source.exists(): record = json.loads((source / 'manifest.json').read_text()) if record.get('schemaVersion') != 1: parser.error('Unsupported toolchain manifest') if profile == 'source' and record.get('privateRuntimeInputs') is not False: parser.error('Source content profile requires an explicitly source-only compiler runtime') try: validate_private_inputs(source, record) except ValueError as error: parser.error(str(error)) disk = record.get('decbfile') if disk: if disk.get('profile') != 'rom-backed-core' or disk.get('standaloneDriverIncluded') is not False: parser.error('Unsupported disk-library profile') for relative, key in [('share/cmoc/lib/libdecbfile.a', 'archiveSHA256'), ('share/cmoc/include/decbfile.h', 'headerSHA256')]: if hashlib.sha256((source / relative).read_bytes()).hexdigest() != disk.get(key): parser.error('Disk-library payload does not match its manifest: ' + relative) declared = set(record.get('architectures', [])) requested = set(os.environ.get('ARCHS', '').split()) & {'arm64', 'x86_64'} required = requested or declared if not declared or declared - {'arm64', 'x86_64'} or not required.issubset(declared): parser.error('Toolchain architectures do not cover this app build') helpers = {relative: sorted(declared) for relative in MACHO} for relative, architectures in record.get('nativeHelpers', {}).items(): path = Path(relative) if path.is_absolute() or '..' in path.parts or not architectures or not set(architectures).issubset(declared): parser.error('Invalid native helper declaration: ' + relative) helpers[relative] = architectures for relative, architectures in helpers.items(): slices = set(subprocess.check_output(['/usr/bin/lipo', '-archs', str(source / relative)], text=True).split()) if not set(architectures).issubset(slices): parser.error('Toolchain helper is missing a declared architecture: ' + relative) for item in source.rglob('*'): if item.is_symlink(): parser.error('Toolchain bundle must not contain symbolic links') if item.is_file(): with item.open('rb') as stream: magic = stream.read(4) if magic in (b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf', b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca') and item.relative_to(source).as_posix() not in helpers: parser.error('Undeclared native helper: ' + str(item.relative_to(source))) for library in record.get('libraries', {}).values(): for relative, expected in library['filesSHA256'].items(): path = Path(relative) if path.is_absolute() or '..' in path.parts or hashlib.sha256((source / path).read_bytes()).hexdigest() != expected: parser.error('Library payload does not match its manifest: ' + relative) if record.get('perl') and ('bin/perl' not in helpers or not (source / 'bin/install-coco-boot-loader').is_file()): parser.error('Perl runtime is incomplete') for relative in (*MACHO, 'bin/cmoc', 'share/cmoc/include/cmoc.h'): if not (source / relative).is_file(): parser.error('Incomplete toolchain: ' + relative) if destination.exists(): shutil.rmtree(destination) if not source.exists(): print('Optional CMOC runtime not staged; C Development will report that its tools are unavailable.') return destination.parent.mkdir(parents=True, exist_ok=True) shutil.copytree(source, destination) # Cache keys consume the installed manifest. Fingerprint actual payload # bytes before signing so a locally rebuilt compiler/helper also invalidates # old dependencies/objects even when its upstream version is unchanged. payload = hashlib.sha256() for item in sorted(source.rglob('*')): if item.is_file() and item.relative_to(source).as_posix() != 'manifest.json': relative = item.relative_to(source).as_posix().encode('utf-8') payload.update(len(relative).to_bytes(8, 'big')) payload.update(relative) payload.update(hashlib.sha256(item.read_bytes()).digest()) record['payloadSHA256'] = payload.hexdigest() (destination / 'manifest.json').write_text(json.dumps(record, indent=2) + '\n') # Raw executables inside Resources are not automatically signed by Xcode. # Release packaging replaces these ad-hoc signatures with Developer ID. for relative in sorted(helpers, key=lambda name: (-name.count('/'), name)): subprocess.run(['/usr/bin/codesign', '--force', '--sign', '-', '--timestamp=none', str(destination / relative)], check=True) print('Included self-contained CMOC/LWTools/mcpp/Make runtime, optional Perl/libraries and upstream notices.') if __name__ == '__main__': main()