|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2026 The Fuchsia Authors |
| 3 | +# |
| 4 | +# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 |
| 5 | +# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT |
| 6 | +# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. |
| 7 | +# This file may not be copied, modified, or distributed except according to |
| 8 | +# those terms. |
| 9 | +"""Relocate and statically check Darwin translation tools in new archive staging. |
| 10 | +
|
| 11 | +Never invokes translated tools, compilers, or the Lean SDK publisher. This is |
| 12 | +separate from the Lean-consumed closure and its identity. System libraries are |
| 13 | +an explicit Darwin platform assumption; this is not dynamic ABI acceptance. |
| 14 | +""" |
| 15 | +import argparse |
| 16 | +from pathlib import Path |
| 17 | +import re |
| 18 | +import subprocess |
| 19 | + |
| 20 | + |
| 21 | +def tool(name, *args): |
| 22 | + return subprocess.run(['/usr/bin/' + name, *map(str, args)], check=True, |
| 23 | + capture_output=True, text=True, timeout=60, |
| 24 | + env={'PATH': '/usr/bin:/bin:/usr/sbin:/sbin', 'LC_ALL': 'C'}).stdout |
| 25 | + |
| 26 | + |
| 27 | +def loads(text): |
| 28 | + result = {'needed': [], 'rpaths': [], 'identity': None, 'interpreter': None, |
| 29 | + 'code_signature': False} |
| 30 | + command = None |
| 31 | + for line in text.splitlines(): |
| 32 | + line = line.strip() |
| 33 | + if line.startswith('cmd '): |
| 34 | + command = line.split()[1] |
| 35 | + if command == 'LC_CODE_SIGNATURE': |
| 36 | + result['code_signature'] = True |
| 37 | + elif line.startswith('name ') and command: |
| 38 | + name = line[5:].rsplit(' (offset ', 1)[0] |
| 39 | + if command == 'LC_ID_DYLIB': |
| 40 | + result['identity'] = name |
| 41 | + elif command == 'LC_LOAD_DYLINKER': |
| 42 | + result['interpreter'] = name |
| 43 | + elif command in {'LC_LOAD_DYLIB', 'LC_LOAD_WEAK_DYLIB', 'LC_REEXPORT_DYLIB', 'LC_LOAD_UPWARD_DYLIB', 'LC_LAZY_LOAD_DYLIB'}: |
| 44 | + result['needed'].append(name) |
| 45 | + elif line.startswith('path ') and command == 'LC_RPATH': |
| 46 | + result['rpaths'].append(line[5:].rsplit(' (offset ', 1)[0]) |
| 47 | + return result |
| 48 | + |
| 49 | + |
| 50 | +def changes(name, dependencies, symbols): |
| 51 | + result = {} |
| 52 | + for dependency in dependencies: |
| 53 | + replacement = None |
| 54 | + if name in {'charon', 'charon-driver'}: |
| 55 | + if re.fullmatch(r'/nix/store/[^/]+-libiconv-109/lib/libiconv\.2\.dylib', dependency): |
| 56 | + replacement = '/usr/lib/libiconv.2.dylib' |
| 57 | + elif name == 'charon-driver' and re.fullmatch(r'/nix/store/[^/]+-zlib-1\.3\.1/lib/libz\.dylib', dependency): |
| 58 | + replacement = '/usr/lib/libz.1.dylib' |
| 59 | + elif name == 'charon-driver' and re.fullmatch(r'@rpath/librustc_driver-[0-9a-f]+\.dylib', dependency): |
| 60 | + # System shell shims on macOS strip DYLD_LIBRARY_PATH. The |
| 61 | + # archive already fixes this provider beside the tools. |
| 62 | + result[dependency] = '@loader_path/../../rust/lib/' + dependency[len('@rpath/'):] |
| 63 | + continue |
| 64 | + if replacement: |
| 65 | + family = 'libiconv' if 'iconv' in replacement else 'libz' |
| 66 | + if re.search(r'\(from ' + family + r'[^)]*\)', symbols): |
| 67 | + raise ValueError('system substitution needs a new ABI review: ' + dependency) |
| 68 | + result[dependency] = replacement |
| 69 | + return result |
| 70 | + |
| 71 | + |
| 72 | +def system(reference): |
| 73 | + return '..' not in Path(reference).parts and reference.startswith(('/usr/lib/', '/System/Library/Frameworks/')) |
| 74 | + |
| 75 | + |
| 76 | +def owned(path, root): |
| 77 | + path = path.resolve(strict=True) |
| 78 | + if not path.is_file() or not any(path.is_relative_to(root / family) for family in ('aeneas/bin', 'rust/lib')): |
| 79 | + raise ValueError('native provider escapes owned archive payload: ' + str(path)) |
| 80 | + return path |
| 81 | + |
| 82 | + |
| 83 | +def provider(reference, image, root, rpaths): |
| 84 | + if system(reference): |
| 85 | + return None |
| 86 | + def expand(value): |
| 87 | + value = value.replace('@loader_path', str(image.parent)).replace('@executable_path', str(root / 'aeneas/bin')) |
| 88 | + if '@' in value or '$' in value or not Path(value).is_absolute(): |
| 89 | + raise ValueError('unsupported native path: ' + value) |
| 90 | + return Path(value) |
| 91 | + if reference.startswith(('@loader_path/', '@executable_path/')): |
| 92 | + return owned(expand(reference), root) |
| 93 | + if reference.startswith('@rpath/'): |
| 94 | + name = reference[len('@rpath/'):] |
| 95 | + if '/' in name: |
| 96 | + raise ValueError('unsupported nested rpath provider: ' + reference) |
| 97 | + # Physical presence alone does not make a dyld search path. In |
| 98 | + # particular a system shell can discard DYLD_LIBRARY_PATH. |
| 99 | + directories = [expand(path).resolve(strict=True) for path in rpaths] |
| 100 | + for directory in directories: |
| 101 | + if not directory.is_dir() or not any(directory.is_relative_to(root / family) for family in ('aeneas/bin', 'rust/lib')): |
| 102 | + raise ValueError('loader search directory escapes owned archive payload: ' + str(directory)) |
| 103 | + candidates = {owned(directory / name, root) for directory in directories if (directory / name).exists()} |
| 104 | + if len(candidates) != 1: |
| 105 | + raise ValueError('missing or ambiguous native provider: ' + reference) |
| 106 | + return candidates.pop() |
| 107 | + raise ValueError('non-system or unrecognized native reference: ' + reference) |
| 108 | + |
| 109 | + |
| 110 | +def prepare(root, platform): |
| 111 | + root = root.resolve(strict=True) |
| 112 | + if (root / 'lean-sdk').exists(): |
| 113 | + raise ValueError('translation relocation must precede SDK assembly') |
| 114 | + architecture = {'aarch64-darwin': 'arm64', 'x86_64-darwin': 'x86_64'}[platform] |
| 115 | + pending = [owned(root / 'aeneas/bin' / name, root) for name in ('aeneas', 'charon', 'charon-driver')] |
| 116 | + owned(root / 'aeneas/bin/libs/libgmp.10.dylib', root) |
| 117 | + plans = [] |
| 118 | + for image in pending: |
| 119 | + if architecture not in tool('lipo', '-archs', image).split(): |
| 120 | + raise ValueError('native provider lacks selected architecture: ' + str(image)) |
| 121 | + information = loads(tool('otool', '-l', image)) |
| 122 | + symbols = tool('nm', '-m', '-u', image) if image.name in {'charon', 'charon-driver'} else '' |
| 123 | + replacements = changes(image.name, information['needed'], symbols) |
| 124 | + for new in replacements.values(): |
| 125 | + if new.startswith('@loader_path/'): |
| 126 | + provider(new, image, root, []) |
| 127 | + plans.append((image, replacements)) |
| 128 | + for image, replacements in plans: |
| 129 | + for old, new in replacements.items(): |
| 130 | + tool('install_name_tool', '-change', old, new, image) |
| 131 | + if replacements: |
| 132 | + tool('codesign', '--force', '--sign', '-', '--timestamp=none', image) |
| 133 | + visited = set() |
| 134 | + while pending: |
| 135 | + image = owned(pending.pop(), root) |
| 136 | + if image in visited: |
| 137 | + continue |
| 138 | + visited.add(image) |
| 139 | + if architecture not in tool('lipo', '-archs', image).split(): |
| 140 | + raise ValueError('native provider lacks selected architecture: ' + str(image)) |
| 141 | + information = loads(tool('otool', '-l', image)) |
| 142 | + if information['interpreter'] not in (None, '/usr/lib/dyld'): |
| 143 | + raise ValueError('foreign native interpreter') |
| 144 | + identity = information['identity'] |
| 145 | + if identity and identity.startswith('/') and not system(identity): |
| 146 | + raise ValueError('non-system absolute native install ID') |
| 147 | + for path in information['rpaths']: |
| 148 | + if system(path): |
| 149 | + continue |
| 150 | + expanded = path.replace('@loader_path', str(image.parent)).replace('@executable_path', str(root / 'aeneas/bin')) |
| 151 | + if '@' in expanded or '$' in expanded or not Path(expanded).is_absolute(): |
| 152 | + raise ValueError('unsupported native rpath: ' + path) |
| 153 | + directory = Path(expanded).resolve(strict=True) |
| 154 | + if not directory.is_dir() or not any(directory.is_relative_to(root / family) for family in ('aeneas/bin', 'rust/lib')): |
| 155 | + raise ValueError('native rpath escapes owned payload: ' + path) |
| 156 | + for reference in information['needed']: |
| 157 | + dependency = provider(reference, image, root, information['rpaths']) |
| 158 | + if dependency: |
| 159 | + pending.append(dependency) |
| 160 | + # Intel permits unsigned Mach-O providers. Determine absence from the |
| 161 | + # inspected load commands, never from a failed codesign invocation. |
| 162 | + # Arm64 still requires verification, as does any signature-present |
| 163 | + # image (including a signed slice of a universal provider). |
| 164 | + if architecture == 'arm64' or information['code_signature']: |
| 165 | + tool('codesign', '--verify', '--strict', image) |
| 166 | + |
| 167 | + |
| 168 | +if __name__ == '__main__': |
| 169 | + parser = argparse.ArgumentParser(description=__doc__) |
| 170 | + parser.add_argument('--root', type=Path, required=True) |
| 171 | + parser.add_argument('--platform', choices=['aarch64-darwin', 'x86_64-darwin'], required=True) |
| 172 | + args = parser.parse_args() |
| 173 | + prepare(args.root, args.platform) |
0 commit comments