#!/usr/bin/env python3 """Relink one captured release command with hash-verified SDK candidate inputs.""" import argparse import hashlib import json from pathlib import Path import shlex import subprocess from redirect_to_runtime import patch def sha(path): with path.open('rb') as stream: return hashlib.file_digest(stream, 'sha256').hexdigest() def relink(log, manifest_path, output, working_directory): manifest = json.loads(manifest_path.read_text()) root = manifest_path.parent verified = set() for record in manifest['files']: path = (root / record['path']).resolve() verified.add(path) if sha(path) != record['sha256']: raise ValueError(f'SDK candidate changed: {path}') required = [(root / item).resolve() for item in manifest['objects']] required += [(root / rule['file']).resolve() for rule in manifest['replacements']] required.append((root / manifest['patch_profile']).resolve()) if not set(required) <= verified: raise ValueError('Candidate file missing from hash manifest') commands = [] for line in log.read_text(errors='replace').splitlines(): if '/bin/clang++ ' in line: argv = shlex.split(line) if '-o' in argv and argv[argv.index('-o') + 1].endswith( '.app/' + manifest['executable']): commands.append(argv) if len(commands) != 1: raise ValueError('Need exactly one matching release link command') argv = commands[0] if any(arg.startswith(('-fprofile', '-fcoverage')) for arg in argv): raise ValueError('Release link still enables coverage') for rule in manifest['replacements']: needle = rule['arguments'] positions = [i for i in range(len(argv) - len(needle) + 1) if argv[i:i + len(needle)] == needle] if len(positions) != 1: raise ValueError(f'Link input missing or duplicated: {needle}') i = positions[0] argv[i:i + len(needle)] = [str((root / rule['file']).resolve())] prepend = [str((root / item).resolve()) for item in manifest['objects']] prepend += ['-F' + str((root / item).resolve()) for item in manifest['framework_search']] argv[1:1] = prepend if output.exists(): raise FileExistsError(output) output.mkdir() for key, name in [('-map', 'LinkMap.txt'), ('-object_path_lto', 'lto.o'), ('-dependency_info', 'dependency_info.dat')]: if key not in argv and key == '-map': argv[1:1] = ['-Xlinker', '-map', '-Xlinker', str(output / name)] continue i = argv.index(key) if argv[i + 1] != '-Xlinker': raise ValueError(f'Unexpected linker argument layout: {key}') argv[i + 2] = str(output / name) binary = output / manifest['executable'] argv[argv.index('-o') + 1] = str(output / 'unpatched') (output / 'link-argv.json').write_text(json.dumps(argv, indent=2) + '\n') with (output / 'link.log').open('w') as stream: subprocess.run(argv, cwd=working_directory, stdout=stream, stderr=subprocess.STDOUT, check=True) profile = json.loads((root / manifest['patch_profile']).read_text()) report = patch(output / 'unpatched', binary, output / 'LinkMap.txt', profile) (output / 'patch.json').write_text(json.dumps(report, indent=2) + '\n') (output / 'inputs.json').write_text(json.dumps(manifest, indent=2) + '\n') return binary if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) for name in ('build_log', 'manifest', 'output', 'working_directory'): parser.add_argument(name, type=Path) args = parser.parse_args() print(relink(args.build_log.resolve(), args.manifest.resolve(), args.output.resolve(), args.working_directory.resolve()))