#!/usr/bin/env python3 """Resolve verified standalone `opt` toolchain, self-heal on Xcode upgrades, and translate policy maps.""" import argparse import datetime import fcntl import hashlib import json import os from pathlib import Path import platform import plistlib import re import shutil import subprocess import sys import tarfile import tempfile SCRIPT_DIR = Path(__file__).resolve().parent TOOLS_DIR = SCRIPT_DIR.parent REPO_ROOT = TOOLS_DIR.parent DEFAULT_MANIFEST_PATH = REPO_ROOT / 'config' / 'toolchain_manifest.json' DEFAULT_LLVM_MAP_PATH = REPO_ROOT / 'config' / 'xcode_llvm_map.json' DEFAULT_CACHE_ROOT = Path.home() / '.cache' / 'iosguard' / 'toolchains' DEFAULT_GIT_REMOTE = 'https://github.com/swiftlang/llvm-project.git' _MEM_SHA_CACHE = {} _PASS_SOURCE_SUFFIXES = {'.cpp', '.cc', '.c', '.h', '.hpp', '.td', '.def', '.cmake', '.txt'} _PASS_SKIP_DIR_NAMES = {'build', '__pycache__', '.git'} def _log(log_fn, msg): if log_fn is not None: log_fn(msg) else: sys.stderr.write(f'{msg}\n') sys.stderr.flush() def augmented_tool_env(base_env=None): """Return environment with Homebrew/local CLI dirs appended so launchd daemons find cmake/ninja.""" env = dict(os.environ if base_env is None else base_env) parts = [p for p in env.get('PATH', '').split(':') if p] for extra in ('/opt/homebrew/bin', '/usr/local/bin'): if extra not in parts and Path(extra).is_dir(): parts.append(extra) env['PATH'] = ':'.join(parts) env.setdefault('GIT_TERMINAL_PROMPT', '0') return env def find_cli_tool(name, env=None): """Locate CLI binary even under minimal launchd PATH.""" eff_env = augmented_tool_env(env) found = shutil.which(name, path=eff_env.get('PATH', '')) if found: return found for cand in (Path('/opt/homebrew/bin') / name, Path('/usr/local/bin') / name, Path('/usr/bin') / name): if cand.is_file() and os.access(cand, os.X_OK): return str(cand) return None def file_sha256(path): p = Path(path) st = p.stat() key = (str(p), st.st_mtime_ns, st.st_size) cached = _MEM_SHA_CACHE.get(key) if cached: return cached h = hashlib.sha256() with p.open('rb') as stream: for chunk in iter(lambda: stream.read(1 << 20), b''): h.update(chunk) digest = h.hexdigest() _MEM_SHA_CACHE[key] = digest return digest def _read_plist(path): p = Path(path) if not p.is_file(): return None with p.open('rb') as f: return plistlib.load(f) def resolve_developer_dir(): env_dev = os.environ.get('DEVELOPER_DIR', '').strip() if env_dev and Path(env_dev).is_dir(): return Path(env_dev) active = subprocess.check_output(['xcode-select', '-p'], text=True).strip() return Path(active) def detect_xcode_info(developer_dir=None): dev_dir = Path(developer_dir) if developer_dir else resolve_developer_dir() for candidate in (dev_dir.parent / 'version.plist', dev_dir / 'version.plist'): pl = _read_plist(candidate) if pl and pl.get('ProductBuildVersion'): return { 'xcode_version': str(pl.get('CFBundleShortVersionString', '')), 'xcode_build': str(pl.get('ProductBuildVersion', '')), 'developer_dir': str(dev_dir), } env = dict(os.environ) if developer_dir: env['DEVELOPER_DIR'] = str(developer_dir) out = subprocess.check_output(['xcodebuild', '-version'], env=env, text=True).splitlines() ver = out[0].split()[-1] if out else '' build = out[1].split()[-1] if len(out) > 1 else '' return { 'xcode_version': ver, 'xcode_build': build, 'developer_dir': str(dev_dir), } def detect_sdk_info(sdk_path=None, developer_dir=None): if sdk_path: p = Path(sdk_path) pl = _read_plist(p / 'SDKSettings.plist') if pl: return { 'sdk_path': str(p), 'sdk_name': str(pl.get('CanonicalName', '')), 'sdk_version': str(pl.get('Version', '')), 'sdk_build': str( pl.get('ProductBuildVersion', '') or pl.get('DefaultProperties', {}).get('PLATFORM_PRODUCT_BUILD_VERSION', '') ), } env = dict(os.environ) if developer_dir: env['DEVELOPER_DIR'] = str(developer_dir) if not sdk_path: sdk_path = subprocess.check_output( ['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], env=env, text=True ).strip() pl = _read_plist(Path(sdk_path) / 'SDKSettings.plist') or {} return { 'sdk_path': str(sdk_path), 'sdk_name': str(pl.get('CanonicalName', 'iphoneos')), 'sdk_version': str(pl.get('Version', '')), 'sdk_build': str(pl.get('ProductBuildVersion', '')), } def detect_stock_tool(tool_name, developer_dir=None, sdk=None): dev_dir = Path(developer_dir) if developer_dir else resolve_developer_dir() tc_bin = dev_dir / 'Toolchains' / 'XcodeDefault.xctoolchain' / 'usr' / 'bin' / tool_name if tc_bin.is_file() and os.access(tc_bin, os.X_OK): return str(tc_bin) env = dict(os.environ) if developer_dir: env['DEVELOPER_DIR'] = str(developer_dir) cmd = ['xcrun'] if sdk: cmd.extend(['--sdk', sdk]) cmd.extend(['-f', tool_name]) return subprocess.check_output(cmd, env=env, text=True).strip() def parse_swift_version_output(text): """Parse `swiftc --version` output into structured Swift/SwiftLang/Clang metadata.""" first_line = next((ln.strip() for ln in (text or '').splitlines() if ln.strip()), '') m_sw = re.search(r'Apple Swift version\s+(\d+\.\d+(?:\.\d+)?)', first_line) if not m_sw: m_sw = re.search(r'Swift version\s+(\d+\.\d+(?:\.\d+)?)', first_line) swift_version = m_sw.group(1) if m_sw else '' m_sl = re.search(r'swiftlang-(\d+\.\d+\.\d+(?:\.\d+)*)', first_line) raw_sl = m_sl.group(1) if m_sl else '' sl_parts = raw_sl.split('.') swiftlang_version = '.'.join(sl_parts[:3]) if len(sl_parts) >= 3 else raw_sl m_cl = re.search(r'clang-(\d+(?:\.\d+)*)', first_line) clang_version = m_cl.group(1) if m_cl else '' mm_source = swift_version or swiftlang_version mm_parts = mm_source.split('.') swift_major_minor = '.'.join(mm_parts[:2]) if len(mm_parts) >= 2 else mm_source return { 'swift_version': swift_version, 'swiftlang_version': swiftlang_version, 'swift_major_minor': swift_major_minor, 'clang_version': clang_version, 'raw': first_line, } def detect_swift_info(developer_dir=None): swiftc_bin = detect_stock_tool('swiftc', developer_dir=developer_dir) env = dict(os.environ) if developer_dir: env['DEVELOPER_DIR'] = str(developer_dir) out = subprocess.check_output([swiftc_bin, '--version'], env=env, stderr=subprocess.DEVNULL, text=True) return parse_swift_version_output(out) def host_arch(): m = platform.machine().lower() if m in ('arm64', 'aarch64'): return 'arm64' return m def compute_passes_hash(passes_dir=None): """Compute deterministic SHA256 digest of llvm_passes C++/CMake sources; 'legacy' if absent.""" pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') if not pdir.is_dir(): return 'legacy' entries = [] for path in pdir.rglob('*'): if not path.is_file(): continue rel = path.relative_to(pdir) if any(part.startswith('.') or part in _PASS_SKIP_DIR_NAMES for part in rel.parts): continue if path.suffix not in _PASS_SOURCE_SUFFIXES: continue entries.append((rel.as_posix(), path)) if not entries: return 'legacy' entries.sort(key=lambda item: item[0]) h = hashlib.sha256() for rel_posix, path in entries: h.update(rel_posix.encode('utf-8')) h.update(b'\x00') h.update(path.read_bytes()) return h.hexdigest() def verify_portability(opt_path): out = subprocess.check_output(['otool', '-L', str(opt_path)], text=True) bad = [] for line in out.splitlines()[1:]: dep = line.strip().split(' ', 1)[0] if not dep: continue if not dep.startswith('/usr/lib/'): bad.append(dep) if bad: raise RuntimeError(f'Built opt links non-system dylibs: {bad}\nFull otool -L:\n{out}') def _run_smoke_cmd(cmd, env): res = subprocess.run(cmd, env=env, capture_output=True, text=True) if res.returncode != 0: raise RuntimeError( f'Smoke command failed (rc={res.returncode}): {" ".join(cmd)}\n' f'{res.stdout[-1000:]}\n{res.stderr[-1500:]}' ) return res def smoke_test_opt(opt_path, developer_dir=None): """Run C + Swift async/ThinLTO bitcode obfuscation & backend lowering smoke test.""" clang_bin = detect_stock_tool('clang', developer_dir=developer_dir) swiftc_bin = detect_stock_tool('swiftc', developer_dir=developer_dir) sdk = detect_sdk_info(developer_dir=developer_dir)['sdk_path'] env = dict(os.environ) if developer_dir: env['DEVELOPER_DIR'] = str(developer_dir) with tempfile.TemporaryDirectory(prefix='igopt-smoke-') as td: p = Path(td) policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'string_encrypt_targets': [{'path_contains': 'smoke'}], 'string_encrypt_stack_targets': [{'path_contains': 'smoke'}], 'opaque_const_targets': [{'path_contains': 'smoke', 'opaque_zero': True}], 'arithmetic_targets': [{'path_contains': 'smoke', 'nonlinear_mba': True}], 'indirect_call_targets': [{'path_contains': 'smoke'}], 'indirect_call_dual_table': True, 'indirect_call_same_image_prefixes': ['ext_'], 'flatten_targets': [{'path_contains': 'smoke'}], 'indirect_branch_targets': [{'path_contains': 'smoke'}], 'anti_hooking_targets': [{'path_contains': 'smoke'}], 'function_outline_min_insts': 2, 'function_outline_targets': [{'path_contains': 'smoke'}], 'opaque_field_targets': [{'path_contains': 'smoke'}], 'bb_split_min_insts': 4, 'bb_split_targets': [{'path_contains': 'smoke'}], }), encoding='utf-8') # 1. C smoke test (p / 'smoke.c').write_text( '#include \n' 'extern int ext_a(int);\n' 'extern int ext_b(int);\n' 'struct smoke_box { int tag; int val; int acc; };\n' 'static int g_smoke_state = 11;\n' 'int check_flag(int x, struct smoke_box *box) {\n' ' const char *v = getenv("DYLD_INSERT_LIBRARIES");\n' ' int r = g_smoke_state;\n' ' if (v && x > 10) {\n' ' int t = (box->val * 3) ^ (box->acc + 7);\n' ' r += ext_a(x + t);\n' ' }\n' ' if (x < 0) r += ext_b(x);\n' ' if (r > 5) return r;\n' ' return r + 1;\n' '}\n', encoding='utf-8', ) _run_smoke_cmd([ clang_bin, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, '-Os', '-g', '-emit-llvm', '-c', str(p / 'smoke.c'), '-o', str(p / 'smoke_c.bc'), ], env=env) _run_smoke_cmd([ str(opt_path), '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=smoke_seed_1', f'--ig-source-path={p / "smoke.c"}', f'--ig-audit-out={p / "audit_c.json"}', str(p / 'smoke_c.bc'), '-o', str(p / 'smoke_c.obf.bc'), ], env=env) _run_smoke_cmd([ clang_bin, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(p / 'smoke_c.obf.bc'), '-o', str(p / 'smoke_c.o'), ], env=env) audit_c = json.loads((p / 'audit_c.json').read_text(encoding='utf-8')) assert audit_c['strings_encrypted_count'] >= 1, 'Expected >=1 C string encrypted' assert audit_c['opaque_constants_count'] >= 1, 'Expected >=1 C opaque constant' assert audit_c['arithmetic_rewrites_count'] >= 1, 'Expected >=1 C MBA arithmetic rewrite' assert audit_c['indirect_calls_count'] >= 2, 'Expected >=2 C indirect calls' assert len(audit_c['functions_flattened']) >= 1, 'Expected >=1 C function flattened' assert audit_c['indirect_branches_count'] >= 1, 'Expected >=1 C indirect branch' assert audit_c['anti_hook_functions_count'] >= 1, 'Expected >=1 C anti-hook function' assert audit_c['functions_outlined_count'] >= 1, 'Expected >=1 C function outlined' assert audit_c['opaque_field_access_count'] >= 2, 'Expected >=2 C opaque field/global accesses' assert audit_c['nonlinear_mba_count'] >= 1, 'Expected >=1 C nonlinear MBA rewrite' assert audit_c['opaque_zero_count'] >= 1, 'Expected >=1 C OpaqueZero constant' assert audit_c['bb_split_count'] >= 1, 'Expected >=1 C basic block split' # 2. Swift async throws smoke test (p / 'smoke.swift').write_text( 'import Foundation\n' '@inline(never) public func sw_sink(_ x: Int) -> Int { return x ^ 0x55 }\n' 'public func swiftDecision(_ a: Int) -> Int {\n' ' let r = getenv("DYLD_INSERT_LIBRARIES")\n' ' var acc = 0\n' ' if r != nil && a > 5 { acc += sw_sink(a) }\n' ' if a < 0 { acc -= sw_sink(-a) }\n' ' if acc > 10 { return acc }\n' ' return acc + 1\n' '}\n' 'public func swiftAsync(_ v: Int) async throws -> Int {\n' ' try await Task.sleep(nanoseconds: 1000)\n' ' return swiftDecision(v)\n' '}\n', encoding='utf-8', ) _run_smoke_cmd([ swiftc_bin, '-sdk', sdk, '-target', 'arm64-apple-ios15.0', '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(p / 'smoke.swift'), '-o', str(p / 'smoke_sw.bc'), ], env=env) _run_smoke_cmd([ str(opt_path), '-passes=default,ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=smoke_seed_1', f'--ig-source-path={p / "smoke.swift"}', f'--ig-audit-out={p / "audit_sw.json"}', str(p / 'smoke_sw.bc'), '-o', str(p / 'smoke_sw.obf.bc'), ], env=env) _run_smoke_cmd([ clang_bin, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(p / 'smoke_sw.obf.bc'), '-o', str(p / 'smoke_sw.o'), ], env=env) audit_sw = json.loads((p / 'audit_sw.json').read_text(encoding='utf-8')) assert audit_sw['strings_encrypted_count'] >= 1, 'Expected >=1 Swift C string encrypted' assert audit_sw['opaque_constants_count'] >= 1, 'Expected >=1 Swift opaque constant' assert audit_sw['arithmetic_rewrites_count'] >= 1, 'Expected >=1 Swift MBA arithmetic rewrite' assert audit_sw['indirect_calls_count'] >= 1, 'Expected >=1 Swift indirect call' assert len(audit_sw['functions_flattened']) >= 1, 'Expected >=1 Swift function flattened' assert audit_sw['indirect_branches_count'] >= 1, 'Expected >=1 Swift indirect branch' return {'c_audit': audit_c, 'swift_audit': audit_sw} def _semver_key(ver_str): return tuple(int(p) if p.isdigit() else 0 for p in re.findall(r'\d+', ver_str or '')) def resolve_llvm_branch_for_swift(swift_info, xcode_info=None, map_path=None, git_remote=None): """Resolve `swiftlang/llvm-project` release branch or tag matching active Swift compiler.""" map_p = Path(map_path) if map_path is not None else DEFAULT_LLVM_MAP_PATH xc_build = str((xcode_info or {}).get('xcode_build', '') or '') swiftlang = str((swift_info or {}).get('swiftlang_version', '') or '') swift_mm = str((swift_info or {}).get('swift_major_minor', '') or '') if map_p.is_file(): try: ovr = json.loads(map_p.read_text(encoding='utf-8')) if xc_build and xc_build in (ovr.get('by_xcode_build') or {}): return ovr['by_xcode_build'][xc_build] if swiftlang and swiftlang in (ovr.get('by_swiftlang') or {}): return ovr['by_swiftlang'][swiftlang] if swift_mm and swift_mm in (ovr.get('by_swift_major_minor') or {}): return ovr['by_swift_major_minor'][swift_mm] except Exception: pass remote = (git_remote or os.environ.get('IG_LLVM_GIT_MIRROR') or DEFAULT_GIT_REMOTE).strip() env = augmented_tool_env() ls_out = subprocess.check_output( ['git', 'ls-remote', '--heads', '--tags', remote], env=env, text=True, timeout=30, ) heads = set() tags = set() for line in ls_out.splitlines(): parts = line.split() if len(parts) < 2: continue ref = parts[1] if ref.endswith('^{}'): continue if ref.startswith('refs/heads/'): heads.add(ref[len('refs/heads/'):]) elif ref.startswith('refs/tags/'): tags.add(ref[len('refs/tags/'):]) for cand in ( f'swift/release/{swiftlang}' if swiftlang else '', f'swift/release/{swift_mm}' if swift_mm else '', f'swift/release/{swift_mm}.0' if swift_mm else '', ): if cand and cand in heads: return cand if swift_mm: head_pat = re.compile(rf'^swift/release/{re.escape(swift_mm)}(?:\.(\d+))?$') matched_heads = [h for h in heads if head_pat.match(h)] if matched_heads: return max(matched_heads, key=_semver_key) if swiftlang: tag_exact = f'swift-{swiftlang}-RELEASE' if tag_exact in tags: return tag_exact if swift_mm: tag_pat = re.compile(rf'^swift-{re.escape(swift_mm)}(?:\.\d+)*-RELEASE$') matched_tags = [t for t in tags if tag_pat.match(t)] if matched_tags: return max(matched_tags, key=_semver_key) raise RuntimeError( f'Unable to resolve matching swiftlang/llvm-project branch for swift={swift_info} (xcode_build={xc_build}) from {remote}' ) def _verify_cached_binary(opt_path, expected_sha256): if not opt_path.is_file() or not os.access(opt_path, os.X_OK): return False marker = opt_path.parent.parent / '.verified.json' st = opt_path.stat() if marker.is_file(): try: meta = json.loads(marker.read_text(encoding='utf-8')) if ( meta.get('sha256') == expected_sha256 and meta.get('size') == st.st_size and meta.get('mtime_ns') == st.st_mtime_ns ): return True except Exception: pass actual = file_sha256(opt_path) if actual != expected_sha256: return False marker.write_text( json.dumps( { 'sha256': actual, 'size': st.st_size, 'mtime_ns': st.st_mtime_ns, }, indent=2, ) + '\n', encoding='utf-8', ) return True def _write_verified_marker(opt_path, expected_sha256): st = opt_path.stat() marker = opt_path.parent.parent / '.verified.json' marker.write_text( json.dumps( { 'sha256': expected_sha256, 'size': st.st_size, 'mtime_ns': st.st_mtime_ns, }, indent=2, ) + '\n', encoding='utf-8', ) def _versioned_dir_name(xcode_build, arch, passes_hash): if passes_hash and passes_hash != 'legacy': return f'{xcode_build}-{arch}-{passes_hash[:8]}' return f'{xcode_build}-{arch}' def _verify_meta_dir(target_dir, expected_passes_hash=None): meta_p = Path(target_dir) / 'meta.json' opt_bin = Path(target_dir) / 'bin' / 'opt' if not meta_p.is_file(): return None try: meta = json.loads(meta_p.read_text(encoding='utf-8')) except Exception: return None if not isinstance(meta, dict): return None expected_sha = meta.get('opt_sha256') if not expected_sha: return None if expected_passes_hash is not None and meta.get('passes_hash') != expected_passes_hash: return None if not _verify_cached_binary(opt_bin, expected_sha): return None return meta def _extract_bundle(bundle_path, target_dir, expected_sha256): bundle_p = Path(os.path.expanduser(str(bundle_path))) if not bundle_p.is_file(): raise FileNotFoundError(f'Missing igopt bundle at {bundle_p}') target_dir.parent.mkdir(parents=True, exist_ok=True) lock_path = target_dir.parent / f'.{target_dir.name}.lock' with lock_path.open('w') as lockf: fcntl.flock(lockf, fcntl.LOCK_EX) opt_bin = target_dir / 'bin' / 'opt' if _verify_cached_binary(opt_bin, expected_sha256): return opt_bin with tempfile.TemporaryDirectory(prefix='.igopt-extract-', dir=target_dir.parent) as tmp: stage = Path(tmp) / 'stage' stage.mkdir() with tarfile.open(bundle_p, 'r:gz') as tf: for member in tf.getmembers(): mp = Path(member.name) if mp.is_absolute() or '..' in mp.parts or member.issym() or member.islnk(): raise ValueError(f'Unsafe archive member in {bundle_p}: {member.name}') tf.extractall(stage) stage_opt = stage / 'bin' / 'opt' if not stage_opt.is_file(): raise FileNotFoundError(f'Extracted bundle missing bin/opt: {bundle_p}') stage_opt.chmod(0o755) actual = file_sha256(stage_opt) if actual != expected_sha256: raise RuntimeError( f'Extracted opt SHA256 mismatch: expected {expected_sha256}, got {actual}' ) if target_dir.exists(): shutil.rmtree(target_dir) stage.rename(target_dir) if not _verify_cached_binary(opt_bin, expected_sha256): raise RuntimeError(f'Failed to verify extracted opt at {opt_bin}') return opt_bin def _resolve_manifest_path(manifest_path=None): if manifest_path is not None: return Path(manifest_path) manifest_p = Path(os.environ.get('IG_TOOLCHAIN_MANIFEST') or DEFAULT_MANIFEST_PATH) if not manifest_p.is_file(): alt = REPO_ROOT / 'config' / 'toolchain_manifest.json' if alt.is_file(): manifest_p = alt return manifest_p def prune_old_toolchains(cache_root, keep=3, current_dir_name=None): """Delete oldest cached toolchain directories beyond `keep` while preserving current_dir_name.""" root = Path(cache_root) if not root.is_dir(): return [] keep_n = max(1, int(keep)) candidates = [] for entry in root.iterdir(): if not entry.is_dir() or entry.name.startswith('.'): continue if current_dir_name and entry.name == current_dir_name: continue meta_p = entry / 'meta.json' try: mtime = meta_p.stat().st_mtime_ns if meta_p.is_file() else entry.stat().st_mtime_ns except OSError: mtime = 0 candidates.append((mtime, entry)) candidates.sort(key=lambda item: item[0], reverse=True) retain_others = max(0, keep_n - (1 if current_dir_name else 0)) removed = [] for _, old_dir in candidates[retain_others:]: shutil.rmtree(old_dir, ignore_errors=True) removed.append(old_dir.name) return removed def _failure_marker_path(cache_root, xcode_build, arch, passes_hash): h8 = passes_hash[:8] if passes_hash != 'legacy' else 'legacy' return Path(cache_root) / '.locks' / f'failed_{xcode_build}_{arch}_{h8}.json' def _gather_l2_candidates(root, xcode_build, arch, swift_mm, passes_hash, manifest_p, default_cache_root): """Collect candidate opt binaries matching passes_hash ordered by Swift compatibility & recency.""" h8 = passes_hash[:8] if passes_hash != 'legacy' else 'legacy' scored = [] if root.is_dir(): suffix = f'-{arch}-{h8}' if passes_hash != 'legacy' else f'-{arch}' for entry in root.iterdir(): if not entry.is_dir() or entry.name.startswith('.'): continue if not entry.name.endswith(suffix): continue meta = _verify_meta_dir(entry, expected_passes_hash=passes_hash) if not meta: continue same_mm = 1 if (swift_mm and meta.get('swift_major_minor') == swift_mm) else 0 try: mtime = (entry / 'meta.json').stat().st_mtime_ns except OSError: mtime = 0 scored.append((same_mm, mtime, entry / 'bin' / 'opt', meta['opt_sha256'], entry.name, None)) scored.sort(key=lambda item: (item[0], item[1]), reverse=True) results = [] seen_sha = set() for _, _, opt_bin, opt_sha, label, legacy_info in scored: if opt_sha not in seen_sha: seen_sha.add(opt_sha) results.append((opt_bin, opt_sha, label, legacy_info)) # Legacy toolchain_manifest.json seed support (exact build dir in root or default_cache_root) if manifest_p and manifest_p.is_file(): try: manifest = json.loads(manifest_p.read_text(encoding='utf-8')) toolchains = manifest.get('toolchains') or {} seed_bases = [root] def_root = Path(default_cache_root) if default_cache_root else DEFAULT_CACHE_ROOT if def_root != root: seed_bases.append(def_root) for tc_key, entry in toolchains.items(): if not isinstance(entry, dict): continue if entry.get('host_arch', 'arm64') != arch: continue if entry.get('passes_hash') and entry['passes_hash'] != passes_hash: continue xc_b = entry.get('xcode_build') or tc_key.split(':', 1)[0] exp_sha = entry.get('opt_sha256') if not exp_sha or exp_sha in seen_sha: continue for base in seed_bases: cand_dir = base / f'{xc_b}-{arch}' cand_opt = cand_dir / 'bin' / 'opt' if _verify_cached_binary(cand_opt, exp_sha): seen_sha.add(exp_sha) results.append((cand_opt, exp_sha, f'legacy:{cand_dir.name}', entry)) break bundle_loc = entry.get('bundle_path') or '' if bundle_loc and base == def_root: bp = Path(os.path.expanduser(str(bundle_loc))) if bp.is_file(): try: extracted = _extract_bundle(bp, cand_dir, exp_sha) seen_sha.add(exp_sha) results.append((extracted, exp_sha, f'bundle:{cand_dir.name}', entry)) break except Exception: pass except Exception: pass return results def ensure_opt( cache_root=None, developer_dir=None, passes_dir=None, git_remote=None, jobs=None, keep_versions=3, force_rebuild=False, allow_rebuild=True, log_fn=None, manifest_path=None, default_cache_root=None, ): """Ensure a smoke-tested `opt` matching active Xcode & llvm_passes is ready in cache_root.""" root = Path(os.path.expanduser(str(cache_root or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT))) pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') xc = detect_xcode_info(developer_dir) swift_info = detect_swift_info(developer_dir) arch = host_arch() passes_hash = compute_passes_hash(pdir) xc_build = xc['xcode_build'] target_name = _versioned_dir_name(xc_build, arch, passes_hash) target_dir = root / target_name key = f'{xc_build}:{arch}' manifest_p = _resolve_manifest_path(manifest_path) locks_dir = root / '.locks' locks_dir.mkdir(parents=True, exist_ok=True) lock_path = locks_dir / 'toolchain_update.lock' fail_marker = _failure_marker_path(root, xc_build, arch, passes_hash) with lock_path.open('w') as lockf: fcntl.flock(lockf, fcntl.LOCK_EX) # L1: Exact cached match if not force_rebuild: meta = _verify_meta_dir(target_dir, expected_passes_hash=passes_hash) if meta: return { 'opt_path': str(target_dir / 'bin' / 'opt'), 'opt_sha256': meta['opt_sha256'], 'xcode': xc, 'swift': swift_info, 'arch': arch, 'key': key, 'passes_hash': passes_hash, 'passes_hash8': passes_hash[:8], 'target_dir': str(target_dir), 'source_mode': 'cached', 'updated': False, 'meta': meta, } if force_rebuild and fail_marker.is_file(): fail_marker.unlink(missing_ok=True) elif fail_marker.is_file(): try: finfo = json.loads(fail_marker.read_text(encoding='utf-8')) raise RuntimeError( f"[IGLLVM] Circuit breaker active for {key} (passes={passes_hash[:8]}) " f"since {finfo.get('failed_at')}: {finfo.get('error_summary')}. " f"Fix llvm_passes or run with --force-rebuild to retry." ) except json.JSONDecodeError: fail_marker.unlink(missing_ok=True) # L2: Compatible opt reuse + real C & Swift Bitcode smoke test if not force_rebuild: candidates = _gather_l2_candidates( root, xc_build, arch, swift_info.get('swift_major_minor', ''), passes_hash, manifest_p, default_cache_root ) for cand_opt, cand_sha, cand_label, legacy_entry in candidates: _log(log_fn, f'[IGLLVM] Testing cached opt candidate ({cand_label}) for Xcode {xc_build}...') try: verify_portability(cand_opt) smoke_test_opt(cand_opt, developer_dir=developer_dir) except Exception as exc: _log(log_fn, f'[IGLLVM] Candidate {cand_label} failed compatibility smoke test: {exc}') continue with tempfile.TemporaryDirectory(prefix='.igopt-stage-', dir=root) as td: stage = Path(td) / 'stage' (stage / 'bin').mkdir(parents=True) stage_opt = stage / 'bin' / 'opt' shutil.copy2(cand_opt, stage_opt) stage_opt.chmod(0o755) actual_sha = file_sha256(stage_opt) if actual_sha != cand_sha: raise RuntimeError(f'Copied opt SHA256 mismatch: {actual_sha} != {cand_sha}') meta_out = { 'schema_version': 1, 'xcode_version': xc['xcode_version'], 'xcode_build': xc_build, 'swift_version': swift_info.get('swift_version', ''), 'swiftlang_version': swift_info.get('swiftlang_version', ''), 'swift_major_minor': swift_info.get('swift_major_minor', ''), 'arch': arch, 'passes_hash': passes_hash, 'opt_sha256': actual_sha, 'source_mode': 'reused', 'reused_from': cand_label, 'llvm_branch': (legacy_entry or {}).get('llvm_branch', ''), 'llvm_commit': (legacy_entry or {}).get('llvm_commit', ''), 'smoke_passed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), } (stage / 'meta.json').write_text(json.dumps(meta_out, indent=2) + '\n', encoding='utf-8') _write_verified_marker(stage_opt, actual_sha) if target_dir.exists(): shutil.rmtree(target_dir) stage.rename(target_dir) fail_marker.unlink(missing_ok=True) pruned = prune_old_toolchains(root, keep=keep_versions, current_dir_name=target_dir.name) _log(log_fn, f'[IGLLVM] Reused & verified opt from {cand_label} -> {target_dir}') return { 'opt_path': str(target_dir / 'bin' / 'opt'), 'opt_sha256': actual_sha, 'xcode': xc, 'swift': swift_info, 'arch': arch, 'key': key, 'passes_hash': passes_hash, 'passes_hash8': passes_hash[:8], 'target_dir': str(target_dir), 'source_mode': 'reused', 'reused_from': cand_label, 'pruned': pruned, 'updated': True, 'meta': meta_out, } # L4: Rebuild standalone opt from swiftlang/llvm-project if not allow_rebuild: raise RuntimeError(f'[IGLLVM] No compatible cached opt found for {key} (passes={passes_hash[:8]}) and rebuild is disabled') if not (pdir / 'CMakeLists.txt').is_file(): raise FileNotFoundError(f'[IGLLVM] Missing llvm_passes source at {pdir}; cannot rebuild opt') if not find_cli_tool('cmake'): raise RuntimeError('[IGLLVM] cmake not found on PATH (/opt/homebrew/bin, /usr/local/bin); cannot rebuild opt') remote = (git_remote or os.environ.get('IG_LLVM_GIT_MIRROR') or DEFAULT_GIT_REMOTE).strip() resolved_branch = '' try: resolved_branch = resolve_llvm_branch_for_swift(swift_info, xcode_info=xc, git_remote=remote) _log(log_fn, f'[IGLLVM] Rebuilding opt for Xcode {xc["xcode_version"]} ({xc_build}) from {remote} @ {resolved_branch}...') import build_igopt_local # lazy import avoids circular dependency mirror_dir = root.parent / 'llvm-src-mirror' res = build_igopt_local.build_opt( branch=resolved_branch, keep_work=False, jobs=jobs, git_remote=remote, cache_dir=root, mirror_dir=mirror_dir, passes_dir=pdir, developer_dir=developer_dir, update_manifest=False, log_fn=log_fn, ) except Exception as exc: err_text = str(exc)[-3000:] fail_marker.write_text( json.dumps( { 'xcode_version': xc['xcode_version'], 'xcode_build': xc_build, 'swift': swift_info, 'arch': arch, 'passes_hash': passes_hash, 'llvm_branch': resolved_branch, 'failed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'error_summary': err_text, }, ensure_ascii=False, indent=2, ) + '\n', encoding='utf-8', ) raise fail_marker.unlink(missing_ok=True) pruned = prune_old_toolchains(root, keep=keep_versions, current_dir_name=target_dir.name) meta_out = res.get('meta') or _verify_meta_dir(target_dir, expected_passes_hash=passes_hash) or {} return { 'opt_path': str(target_dir / 'bin' / 'opt'), 'opt_sha256': res['opt_sha256'], 'xcode': xc, 'swift': swift_info, 'arch': arch, 'key': key, 'passes_hash': passes_hash, 'passes_hash8': passes_hash[:8], 'target_dir': str(target_dir), 'llvm_branch': resolved_branch, 'source_mode': 'built', 'pruned': pruned, 'updated': True, 'meta': meta_out, } def check_toolchain_status(cache_root=None, developer_dir=None, passes_dir=None, manifest_path=None): """Read-only inspection of current Xcode/Swift/opt cache readiness and circuit-breaker state.""" root = Path(os.path.expanduser(str(cache_root or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT))) pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') xc = detect_xcode_info(developer_dir) swift_info = detect_swift_info(developer_dir) arch = host_arch() passes_hash = compute_passes_hash(pdir) target_dir = root / _versioned_dir_name(xc['xcode_build'], arch, passes_hash) meta = _verify_meta_dir(target_dir, expected_passes_hash=passes_hash) legacy_info = None if meta is None: legacy_res = resolve_opt( manifest_path=manifest_path, cache_root=root, developer_dir=developer_dir, require_obf=False, passes_dir=pdir, allow_auto_update=False, ) if legacy_res.get('opt_path'): legacy_info = legacy_res fail_marker = _failure_marker_path(root, xc['xcode_build'], arch, passes_hash) cb_info = None if fail_marker.is_file(): try: cb_info = json.loads(fail_marker.read_text(encoding='utf-8')) except Exception: cb_info = {'raw_path': str(fail_marker)} cached_versions = [] if root.is_dir(): cached_versions = sorted( d.name for d in root.iterdir() if d.is_dir() and not d.name.startswith('.') ) ready = meta is not None opt_path = str(target_dir / 'bin' / 'opt') if ready else (legacy_info.get('opt_path') if legacy_info else None) return { 'xcode': xc, 'swift': swift_info, 'arch': arch, 'passes_hash': passes_hash, 'passes_hash8': passes_hash[:8], 'cache_root': str(root), 'target_dir': str(target_dir), 'ready': ready, 'legacy_fallback_ready': legacy_info is not None, 'opt_path': opt_path, 'meta': meta, 'circuit_breaker': cb_info, 'cached_versions': cached_versions, } def resolve_opt( manifest_path=None, cache_root=None, developer_dir=None, require_obf=None, passes_dir=None, allow_auto_update=None, ): if require_obf is None: require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' if allow_auto_update is None: allow_auto_update = os.environ.get('IG_AUTO_UPDATE_OPT') == '1' xc = detect_xcode_info(developer_dir) arch = host_arch() key = f"{xc['xcode_build']}:{arch}" root = Path(os.path.expanduser(str(cache_root or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT))) pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') passes_hash = compute_passes_hash(pdir) # 1. Fast read-only versioned cache lookup (<5ms; no lock/smoke/network) if passes_hash != 'legacy': v_dir = root / _versioned_dir_name(xc['xcode_build'], arch, passes_hash) v_meta = _verify_meta_dir(v_dir, expected_passes_hash=passes_hash) if v_meta: return { 'opt_path': str(v_dir / 'bin' / 'opt'), 'opt_sha256': v_meta['opt_sha256'], 'xcode': xc, 'arch': arch, 'key': key, 'passes_hash': passes_hash, 'source_mode': 'cached', 'meta': v_meta, } # 2. Backward-compatible manifest lookup manifest_p = _resolve_manifest_path(manifest_path) if manifest_p.is_file(): manifest = json.loads(manifest_p.read_text(encoding='utf-8')) entry = (manifest.get('toolchains') or {}).get(key) if entry and (not entry.get('passes_hash') or entry.get('passes_hash') == passes_hash): expected_sha = entry['opt_sha256'] target_dir = root / f"{xc['xcode_build']}-{arch}" opt_bin = target_dir / 'bin' / 'opt' if _verify_cached_binary(opt_bin, expected_sha): return { 'opt_path': str(opt_bin), 'opt_sha256': expected_sha, 'xcode': xc, 'arch': arch, 'key': key, 'entry': entry, 'source_mode': 'manifest_cached', } # Optional read-only bundle fallback if bundle exists on disk bundle_loc = entry.get('bundle_path') or '' if bundle_loc and Path(os.path.expanduser(str(bundle_loc))).is_file(): opt_bin = _extract_bundle(bundle_loc, target_dir, expected_sha) return { 'opt_path': str(opt_bin), 'opt_sha256': expected_sha, 'xcode': xc, 'arch': arch, 'key': key, 'entry': entry, 'source_mode': 'bundle_cached', } # 3. Optional explicit self-healing path if allow_auto_update: return ensure_opt( cache_root=root, developer_dir=developer_dir, passes_dir=pdir, manifest_path=manifest_p, ) msg = f'[IGLLVM] No verified opt toolchain ready for {key} (passes={passes_hash[:8]}) in {root}' if not manifest_p.is_file(): msg = f'[IGLLVM] Manifest not found at {manifest_p} and no cached versioned opt for {key} (passes={passes_hash[:8]})' if require_obf: raise RuntimeError(msg) return {'opt_path': None, 'xcode': xc, 'arch': arch, 'key': key, 'warning': msg} def discover_active_app_repo(hint_paths=(), fallback_root=None): """Find active app repo root (SRCROOT or parent holding obfuscation_maps/readoor.xcodeproj).""" srcroot = os.environ.get('SRCROOT', '').strip() if srcroot: p = Path(srcroot).resolve() if p.is_dir(): return p for hint in hint_paths or (): if not hint: continue hp = Path(hint) parents = [hp] + list(hp.parents) for parent in parents: if (parent / 'obfuscation_maps').is_dir() or (parent / 'readoor.xcodeproj').exists(): return parent if fallback_root is not None: return Path(fallback_root) return None def _unwrap_l1_mappings(raw_payload): if not isinstance(raw_payload, dict): return {} if isinstance(raw_payload.get('mappings'), dict) and ( 'schema_version' in raw_payload or raw_payload.get('kind') in ('symbol_map', 'method_map') ): return raw_payload['mappings'] return raw_payload def _pick_latest_map(files, target_name=''): if not files: return None if target_name: exact = [p for p in files if f'_{target_name}_' in p.name or p.name.startswith(f'{target_name}_')] if exact: files = exact return max(files, key=lambda p: (p.stat().st_mtime_ns, p.name)) def _find_l1_map_files(app_repo): """Locate latest (sym_file, meth_file) under app_repo/obfuscation_maps without parsing JSON.""" if app_repo is None: return None, None maps_dir = Path(app_repo) / 'obfuscation_maps' if not maps_dir.is_dir(): return None, None target_name = os.environ.get('TARGET_NAME', '').strip() sym_candidates = [p for p in sorted(maps_dir.glob('symbol_map_*.json')) if p.is_file()] if not sym_candidates: sym_candidates = [ p for p in sorted(maps_dir.glob('*.json')) if p.is_file() and not p.name.startswith(('method_map', 'ig_', 'symbol_map')) and p.name != 'unmapped_mappings.json' ] meth_candidates = [p for p in sorted(maps_dir.glob('method_map_*.json')) if p.is_file()] return _pick_latest_map(sym_candidates, target_name), _pick_latest_map(meth_candidates, target_name) def load_l1_forward_symbol_map(app_repo): """Build forward map (orig -> obf) from app_repo/obfuscation_maps/{symbol_map,method_map}_*.json.""" sym_file, meth_file = _find_l1_map_files(app_repo) if sym_file is None and meth_file is None: return {}, '' forward = {} if sym_file and sym_file.is_file(): try: entries = _unwrap_l1_mappings(json.loads(sym_file.read_text(encoding='utf-8'))) for orig, val in entries.items(): if not isinstance(orig, str) or not orig: continue if isinstance(val, str) and val: forward[orig] = val elif isinstance(val, dict) and isinstance(val.get('obfuscated'), str) and val['obfuscated']: forward[orig] = val['obfuscated'] except Exception: pass if meth_file and meth_file.is_file(): try: entries = _unwrap_l1_mappings(json.loads(meth_file.read_text(encoding='utf-8'))) for orig, val in entries.items(): if not isinstance(orig, str) or not orig: continue if isinstance(val, str) and val: forward[orig] = val if ':' in orig: forward.setdefault(orig.split(':', 1)[0], f'{val}_1') elif isinstance(val, dict): kind = val.get('kind') if kind == 'swift_signature': continue obf_full = val.get('obfuscated') tok = val.get('token') parts = val.get('parts') if isinstance(obf_full, str) and obf_full: forward[orig] = obf_full if ':' in orig: orig_base = orig.split(':', 1)[0] if isinstance(parts, list) and parts: p0 = str(parts[0]).rstrip(':') if p0: forward.setdefault(orig_base, p0) elif isinstance(tok, str) and tok: forward.setdefault(orig_base, tok) elif isinstance(tok, str) and tok: forward.setdefault(orig, tok) except Exception: pass if not forward: return {}, '' map_digest = hashlib.sha256( json.dumps(forward, ensure_ascii=False, sort_keys=True).encode('utf-8') ).hexdigest()[:16] return forward, map_digest def translate_policy_symbol_substring(sub, forward, sorted_items=None): """Expand a function/symbol match substring with Layer-1 renamed identifier variants.""" if not sub: return [] variants = [sub] if not forward: return variants def add(v): if v and v not in variants: variants.append(v) if sub in forward: add(forward[sub]) m = re.match(r'^(\d+)(.+)$', sub) if m: n = int(m.group(1)) rest = m.group(2) if n > 0 and len(rest) >= n: ident, suffix = rest[:n], rest[n:] if ident in forward: obf_id = forward[ident] add(f'{len(obf_id)}{obf_id}{suffix}') replaced = sub matched_any = False candidates = sorted_items if candidates is None: candidates = [ (orig, obf) for orig, obf in sorted(forward.items(), key=lambda kv: -len(kv[0])) if len(orig) >= 4 and ':' not in orig ] for orig, obf in candidates: if orig not in replaced: continue pat = rf'(?= 4 and ':' not in orig ] for rule_key in ( 'flatten_targets', 'indirect_call_targets', 'string_encrypt_targets', 'string_encrypt_objc_targets', 'string_encrypt_swift_targets', 'string_encrypt_stack_targets', 'opaque_const_targets', 'arithmetic_targets', 'indirect_branch_targets', 'anti_hooking_targets', 'function_outline_targets', 'opaque_field_targets', 'bb_split_targets', ): if rule_key not in eff: continue expanded = [] for rule in eff.get(rule_key) or []: expanded.append(rule) fn_sub = rule.get('function_contains', '') if fn_sub: for idx, alt in enumerate(translate_policy_symbol_substring(fn_sub, forward, sorted_items=sorted_items)): if alt != fn_sub: expanded.append({ **rule, 'id': f"{rule.get('id', 'rule')}__l1_{idx}", 'function_contains': alt, }) eff[rule_key] = expanded new_required = [] for req in eff.get('required_targets') or []: r = dict(req) if r.get('symbol_contains'): r['symbol_contains_any'] = translate_policy_symbol_substring( r['symbol_contains'], forward, sorted_items=sorted_items ) if r.get('str_symbol_contains'): r['str_symbol_contains_any'] = translate_policy_symbol_substring( r['str_symbol_contains'], forward, sorted_items=sorted_items ) new_required.append(r) eff['required_targets'] = new_required eff['l1_translation_active'] = True eff['l1_map_digest'] = map_digest[:12] else: eff['l1_translation_active'] = False eff['l1_map_digest'] = '' out_dir.mkdir(parents=True, exist_ok=True) eff_text = json.dumps(eff, ensure_ascii=False, indent=2) + '\n' if not eff_path.is_file() or eff_path.read_text(encoding='utf-8') != eff_text: tmp = out_dir / f'.tmp-{eff_path.name}-{os.getpid()}' tmp.write_text(eff_text, encoding='utf-8') tmp.replace(eff_path) return str(eff_path), eff def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--require-obf', action='store_true') parser.add_argument('--manifest', default=None) parser.add_argument('--cache-dir', default=None) parser.add_argument('--json', action='store_true') parser.add_argument('--ensure', action='store_true') parser.add_argument('--check-only', action='store_true') parser.add_argument('--force-rebuild', action='store_true') parser.add_argument('--no-rebuild', action='store_true') parser.add_argument('--git-remote', default=None) parser.add_argument('--keep-versions', type=int, default=3) args = parser.parse_args() try: if args.check_only: res = check_toolchain_status( cache_root=args.cache_dir, manifest_path=args.manifest, ) elif args.ensure: res = ensure_opt( cache_root=args.cache_dir, git_remote=args.git_remote, keep_versions=args.keep_versions, force_rebuild=args.force_rebuild, allow_rebuild=(not args.no_rebuild), manifest_path=args.manifest, ) else: res = resolve_opt( manifest_path=args.manifest, cache_root=args.cache_dir, require_obf=(True if args.require_obf else None), ) except Exception as exc: if args.json: sys.stdout.write(json.dumps({'error': str(exc)}, ensure_ascii=False) + '\n') else: sys.stderr.write(f'{exc}\n') return 1 if not args.check_only and args.require_obf and not res.get('opt_path'): if args.json: sys.stdout.write(json.dumps(res, ensure_ascii=False) + '\n') else: sys.stderr.write(str(res.get('warning', 'opt unavailable')) + '\n') return 1 sys.stdout.write(json.dumps(res, ensure_ascii=False, indent=2) + '\n') return 0 if __name__ == '__main__': raise SystemExit(main())