#!/usr/bin/env python3 """Xcode Release arm64 linker wrapper (--ld-path) for Swift bitcode opt lowering, Route 2 SDKs, and audit.""" from collections import Counter from concurrent.futures import ThreadPoolExecutor import fcntl import hashlib import json import os from pathlib import Path import re import shutil import struct import subprocess import sys import tempfile SCRIPT_DIR = Path(__file__).resolve().parent TOOLS_DIR = SCRIPT_DIR.parent TOOLCHAIN_ROOT = TOOLS_DIR.parent sys.path.insert(0, str(SCRIPT_DIR)) sys.path.insert(0, str(TOOLS_DIR / 'static_sdk_redirect')) sys.path.insert(0, str(TOOLS_DIR / 'macho_guard')) sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf')) from attribute_callsites import attribute # noqa: E402 from ig_toolchain_resolver import ( # noqa: E402 detect_sdk_info, detect_stock_tool, detect_xcode_info, discover_active_app_repo, file_sha256, resolve_effective_policy, resolve_opt, ) from machox import Macho # noqa: E402 from prepare_route2_sdks import ( # noqa: E402 MAPPING_PATH, PROFILE_PATH, STATIC_INPUTS, digest, run_xcrun, thin_arm64, verify_no_target_imports, ) from redirect_bitcode_members import rewrite as rewrite_bitcode # noqa: E402 from redirect_to_runtime import defined_symbols, link_symbols, patch # noqa: E402 from route2_archive_common import ( # noqa: E402 EXPECTED_DISPATCH_SYMBOLS, collect_variant_stubs, resolve_app_repo, ) from verify_baseline import inspect_binary # noqa: E402 PASSTHROUGH_FLAGS = {'-r', '-dylib', '-bundle', '-preload'} BRIDGE_SOURCE_REL = 'readoor/3.0/Base/Security/IGDefender/call_bridge/IGThreadID.c' BITCODE_MAGICS = (b'\xde\xc0\x17\x0b', b'BC\xc0\xde') LC_BUILD_VERSION = 0x32 PLATFORM_IOS = 2 def strip_ig_stamp(args): """Remove `-ig_stamp ` tokens injected via `-Wl,-ig_stamp,...` and return parsed control tuple.""" clean = [] stamp_val = '' i = 0 while i < len(args): arg = args[i] if arg == '-ig_stamp' and i + 1 < len(args): stamp_val = args[i + 1] i += 2 continue if arg.startswith('-ig_stamp='): stamp_val = arg.split('=', 1)[1] i += 1 continue clean.append(arg) i += 1 ctl = { 'mode': 'off', 'filter': 'all', 'route2': 'on', 'all_off': '0', 'seed': 'm0_seed_20261119_v1', 'stamp': 'default', 'policy_profile': 'default', } if stamp_val.startswith('ctl_'): parts = stamp_val[len('ctl_'):].split('__') if len(parts) >= 7: ctl['mode'] = parts[0] or ctl['mode'] ctl['filter'] = parts[1] or ctl['filter'] ctl['route2'] = parts[2] or ctl['route2'] ctl['all_off'] = parts[3] or ctl['all_off'] ctl['seed'] = parts[4] or ctl['seed'] ctl['stamp'] = parts[5] or ctl['stamp'] ctl['policy_profile'] = '__'.join(parts[6:]) or ctl['policy_profile'] elif len(parts) >= 6: ctl['mode'] = parts[0] or ctl['mode'] ctl['filter'] = parts[1] or ctl['filter'] ctl['route2'] = parts[2] or ctl['route2'] ctl['all_off'] = parts[3] or ctl['all_off'] ctl['seed'] = parts[4] or ctl['seed'] ctl['stamp'] = '__'.join(parts[5:]) or ctl['stamp'] if os.environ.get('IG_DISABLE_LLVM_OBF') == '1': ctl['mode'] = 'off' if os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1': ctl['route2'] = 'off' if os.environ.get('IG_ALL_GUARD_OFF') == '1': ctl['all_off'] = '1' ctl['mode'] = 'off' ctl['route2'] = 'off' if os.environ.get('IG_OBF_MODE'): ctl['mode'] = os.environ['IG_OBF_MODE'] if os.environ.get('IG_LLVM_PASS_FILTER'): ctl['filter'] = os.environ['IG_LLVM_PASS_FILTER'] if os.environ.get('IG_ROUTE2_MODE'): ctl['route2'] = os.environ['IG_ROUTE2_MODE'] if os.environ.get('IG_RELEASE_SEED'): ctl['seed'] = os.environ['IG_RELEASE_SEED'] if os.environ.get('IG_POLICY_PROFILE'): ctl['policy_profile'] = os.environ['IG_POLICY_PROFILE'] if ctl['all_off'] == '1': ctl['mode'] = 'off' ctl['route2'] = 'off' return clean, ctl def resolve_default_policy(profile='default'): names = [f'ig_llvm_policy_{profile}.json'] if profile and profile != 'default' else [] names.append('ig_llvm_policy.json') for name in names: for cand in ( TOOLCHAIN_ROOT / 'config' / name, TOOLCHAIN_ROOT / 'llvm_obf' / name, ): if cand.is_file(): return str(cand) return '' def resolve_real_ld(args): """Locate the real Apple ld without hardcoding /Applications/Xcode.app paths.""" for i, arg in enumerate(args): if arg == '-lto_library' and i + 1 < len(args): candidate = Path(args[i + 1]).resolve().parents[1] / 'bin/ld' if candidate.is_file() and os.access(candidate, os.X_OK): return str(candidate) resolved = subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '-f', 'ld'], text=True).strip() if resolved and Path(resolved).is_file(): return resolved fallback = shutil.which('ld') if fallback: return fallback raise FileNotFoundError('Unable to locate real ld binary via -lto_library or xcrun') def resolve_bridge_source(app_repo): in_repo = app_repo / BRIDGE_SOURCE_REL if in_repo.is_file(): return in_repo in_toolchain = TOOLCHAIN_ROOT / 'defender/call_bridge/IGThreadID.c' if in_toolchain.is_file(): return in_toolchain raise FileNotFoundError(f'Missing IGThreadID.c at {in_repo} or {in_toolchain}') def parse_flag_value(args, flag): """Return last value for an exact `-flag val` pair (ignoring `-object_path_lto` etc.).""" found = None i = 0 while i < len(args): if args[i] == flag and i + 1 < len(args): found = args[i + 1] i += 2 continue i += 1 return found def infer_cache_root(output_path, linkmap_arg): """Place shared SDK cache in IG_SDK_CACHE_DIR, Intermediates.noindex, or OBJROOT.""" env_cache = os.environ.get('IG_SDK_CACHE_DIR') if env_cache: return Path(env_cache) probe = Path(linkmap_arg) if linkmap_arg else output_path for target_dir in ('Intermediates.noindex', 'Build'): for parent in probe.parents: if parent.name == target_dir: return parent / 'ig-route2-sdk-cache' env_objroot = os.environ.get('OBJROOT') if env_objroot: return Path(env_objroot) / 'ig-route2-sdk-cache' return output_path.parent / 'ig-route2-sdk-cache' def infer_obj_cache_dir(output_path, linkmap_arg): env_dir = os.environ.get('IG_OBF_OBJ_CACHE_DIR') if env_dir: return Path(env_dir) probe = Path(linkmap_arg) if linkmap_arg else output_path for parent in probe.parents: if parent.name in ('Intermediates.noindex', 'Build'): return parent / 'ig-obf-obj-cache' return output_path.parent / '.ig-obf-obj-cache' def compute_sdk_fingerprint(app_repo, bridge_src): """Hash Route 2 inputs, scripts, Xcode build, and SDK version for cache invalidation.""" h = hashlib.sha256() xc = detect_xcode_info() sdk = detect_sdk_info() h.update(f"{xc.get('xcode_build', '')}:{sdk.get('sdk_version', '')}:".encode('utf-8')) tool_files = [ Path(__file__), MAPPING_PATH, PROFILE_PATH, bridge_src, TOOLS_DIR / 'static_sdk_redirect/redirect_symbols.py', TOOLS_DIR / 'static_sdk_redirect/redirect_bitcode_members.py', TOOLS_DIR / 'static_sdk_redirect/prepare_route2_sdks.py', ] for path in tool_files: h.update(str(path.name).encode()) h.update(digest(path).encode()) for entry in STATIC_INPUTS: src = app_repo / entry['relative'] h.update(entry['name'].encode()) h.update(digest(src).encode() if src.is_file() else b'missing') return h.hexdigest()[:20] def prepare_entry_in_stage(entry, app_repo, base_mapping, work, stage): source = (app_repo / entry['relative']).resolve() if not source.is_file(): return None thin = work / f"{entry['name']}.thin.a" thin_arm64(source, thin) dest = (stage / entry['dest']).resolve() dest.parent.mkdir(parents=True, exist_ok=True) if 'framework_dir' in entry: fw_src = app_repo / entry['framework_dir'] for sub in ('Headers', 'Modules'): if (fw_src / sub).exists(): shutil.copytree(fw_src / sub, dest.parent / sub, dirs_exist_ok=True) if (fw_src / 'Info.plist').exists(): shutil.copy2(fw_src / 'Info.plist', dest.parent / 'Info.plist') mapping = dict(base_mapping) mapping.update(entry.get('extra_mapping', {})) extra_passes = entry.get('extra_passes', []) if extra_passes: pass0 = work / f"{entry['name']}.pass0.a" rewrite_bitcode(thin, pass0, mapping) cur_input = pass0 for idx, ex_map in enumerate(extra_passes): is_last = (idx == len(extra_passes) - 1) out_target = dest if is_last else (work / f"{entry['name']}.pass{idx + 1}.a") rewrite_bitcode(cur_input, out_target, ex_map, allow_darwin_extsn=True) cur_input = out_target else: rewrite_bitcode(thin, dest, mapping) verify_no_target_imports(dest, set(mapping) | {'_fopen$DARWIN_EXTSN'}) return str(source) def ensure_prepared_stage(cache_root, app_repo, bridge_src): """Build or reuse process-locked cached static SDK candidates & IGThreadID.o.""" fingerprint = compute_sdk_fingerprint(app_repo, bridge_src) stage_dir = cache_root / fingerprint marker = stage_dir / '.ready.json' if marker.is_file(): return stage_dir cache_root.mkdir(parents=True, exist_ok=True) lock_path = cache_root / '.prepare.lock' with lock_path.open('w') as lock_file: fcntl.flock(lock_file, fcntl.LOCK_EX) if marker.is_file(): return stage_dir base_mapping = json.loads(MAPPING_PATH.read_text(encoding='utf-8')) with tempfile.TemporaryDirectory(prefix=f'.tmp-{fingerprint}-', dir=cache_root) as tmp: work = Path(tmp) stage = work / 'stage' stage.mkdir() available = {} for entry in STATIC_INPUTS: src_path = prepare_entry_in_stage(entry, app_repo, base_mapping, work, stage) if src_path: available[entry['name']] = dict(source=src_path, dest=entry['dest']) bridge_obj = stage / 'IGThreadID.o' run_xcrun( '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0', '-O2', '-Wall', '-Wextra', '-Werror', '-c', bridge_src, '-o', bridge_obj, ) if stage_dir.exists(): shutil.rmtree(stage_dir) stage.rename(stage_dir) marker.write_text(json.dumps(dict(fingerprint=fingerprint, entries=available), indent=2) + '\n') return stage_dir def is_bitcode_wrapper(path): try: with Path(path).open('rb') as f: return f.read(4) in BITCODE_MAGICS except OSError: return False def verify_macho_object_platform(obj_path): data = Path(obj_path).read_bytes() if len(data) < 32: raise RuntimeError(f'[IGObf] Truncated object file: {obj_path}') magic, cputype, _cpusubtype, filetype, ncmds, _sizeofcmds, _flags, _reserved = struct.unpack_from('<8I', data, 0) if magic != 0xFEEDFACF or cputype != 0x0100000C or filetype != 1: raise RuntimeError(f'[IGObf] Converted object is not arm64 Mach-O MH_OBJECT (magic=0x{magic:x}, filetype={filetype}): {obj_path}') off = 32 for _ in range(ncmds): cmd, cmdsize = struct.unpack_from('= 24: plat, minos, sdk_ver, _ = struct.unpack_from('> 16) & 0xff}.{(minos >> 8) & 0xff}', 'sdk': f'{(sdk_ver >> 16) & 0xff}.{(sdk_ver >> 8) & 0xff}', } off += cmdsize return {'platform': 'missing_build_version'} def extract_platform_flags(args): """Inherit target triple & SDK path from ld command line.""" min_os = os.environ.get('IPHONEOS_DEPLOYMENT_TARGET', '15.0') syslibroot = None i = 0 while i < len(args): if args[i] == '-platform_version' and i + 3 < len(args): plat_name = args[i + 1] raw_min = args[i + 2] if plat_name in ('ios', '2'): parts = raw_min.split('.') min_os = f'{parts[0]}.{parts[1]}' if len(parts) >= 2 else raw_min i += 4 continue if args[i] == '-syslibroot' and i + 1 < len(args): syslibroot = args[i + 1] i += 2 continue i += 1 if not syslibroot: syslibroot = detect_sdk_info().get('sdk_path') return f'arm64-apple-ios{min_os}', syslibroot def load_target_swift_output_map(filelist_path): """Map normalized llvm-bc/object path -> Swift source path from OutputFileMap.json next to LinkFileList.""" mapping = {} parent = filelist_path.parent ofms = sorted(parent.glob('*-OutputFileMap.json')) + sorted(parent.glob('OutputFileMap.json')) for ofm_path in ofms: try: raw = json.loads(ofm_path.read_text(encoding='utf-8')) except Exception: continue for src_key, entry in raw.items(): if not isinstance(entry, dict): continue target_label = src_key if src_key.endswith('.swift') else ('' if src_key == '' else None) if not target_label: continue for field in ('llvm-bc', 'object'): out_file = entry.get(field) if not out_file: continue norm_obj = os.path.normpath(out_file) if norm_obj not in mapping or target_label != '': mapping[norm_obj] = target_label return mapping def filelist_contains_bitcode(paths): for p in paths: if p and Path(p).is_file() and is_bitcode_wrapper(p): return True return False def args_contain_remaining_bitcode(args, replaced_filelist_entries): if filelist_contains_bitcode(replaced_filelist_entries): return True i = 0 while i < len(args): a = args[i] if a in ('-o', '-map', '-filelist', '-object_path_lto', '-cache_path_lto', '-lto_library', '-syslibroot'): i += 2 continue if not a.startswith('-') and a.endswith(('.o', '.bc')) and Path(a).is_file(): if is_bitcode_wrapper(a): return True i += 1 return False def strip_lto_link_flags(args): """Strip ThinLTO linker flags only when zero bitcode objects remain in link inputs.""" out = [] i = 0 while i < len(args): a = args[i] if a in ('-cache_path_lto', '-object_path_lto') and i + 1 < len(args): i += 2 continue if a.startswith('-flto') or a.startswith('-cache_path_lto=') or a.startswith('-object_path_lto='): i += 1 continue out.append(a) i += 1 return out def _lower_single_bitcode_object( bc_path, out_o, out_a, src_hint, swift_mod_name, backend_flags, tc, clang_bin, sdk_info, wrapper_sha, policy_sha, pipeline, ctl, policy_path, cache_root, cache_kind='swift_v1', extra_cache_fields=None, tmp_parent=None, ): """Run opt + clang lowering on a single LLVM bitcode object with content-addressed caching.""" bc_p = Path(bc_path) out_o = Path(out_o) out_a = Path(out_a) bc_sha = file_sha256(bc_p) xc_build = tc['xcode']['xcode_build'] cache_payload = { 'kind': cache_kind, 'bc_sha256': bc_sha, 'xcode_build': xc_build, 'sdk_version': sdk_info.get('sdk_version', ''), 'opt_sha256': tc['opt_sha256'], 'wrapper_sha256': wrapper_sha, 'policy_sha256': policy_sha, 'pipeline': pipeline, 'mode': ctl['mode'], 'filter': ctl['filter'], 'seed': ctl['seed'], 'stamp': ctl['stamp'], 'swift_module': swift_mod_name, 'backend_flags': backend_flags, } if extra_cache_fields: cache_payload.update(extra_cache_fields) key_hash = hashlib.sha256(json.dumps(cache_payload, sort_keys=True).encode('utf-8')).hexdigest()[:24] c_dir = cache_root / key_hash[:2] cached_o = c_dir / f'{key_hash}.o' cached_a = c_dir / f'{key_hash}.audit.json' if cached_o.is_file() and cached_a.is_file(): shutil.copy2(cached_o, out_o) shutil.copy2(cached_a, out_a) else: opt_path = tc['opt_path'] tmp_base = Path(tmp_parent) if tmp_parent else out_o.parent with tempfile.TemporaryDirectory(prefix='.ig-sw-', dir=tmp_base) as swtmp: obf_bc = Path(swtmp) / f'{bc_p.stem}.obf.bc' p_opt = subprocess.run([ opt_path, f'-passes={pipeline}', f'--ig-policy={policy_path}', f"--ig-mode={ctl['mode']}", f"--ig-pass-filter={ctl['filter']}", f"--ig-seed={ctl['seed']}", f'--ig-source-path={src_hint}', f'--ig-swift-module={swift_mod_name}', f'--ig-audit-out={out_a}', str(bc_p), '-o', str(obf_bc), ], capture_output=True, text=True) if p_opt.returncode != 0: raise RuntimeError( f'[IGObf] opt failed on Swift object {bc_p.name}: {p_opt.stderr.strip()}' ) p_cc = subprocess.run( [clang_bin, *backend_flags, str(obf_bc), '-o', str(out_o)], capture_output=True, text=True, ) if p_cc.returncode != 0: raise RuntimeError( f'[IGObf] clang IR lowering failed on {bc_p.name}: {p_cc.stderr.strip()}' ) verify_macho_object_platform(out_o) try: c_dir.mkdir(parents=True, exist_ok=True) tmp_o = c_dir / f'.tmp-{key_hash}-{os.getpid()}.o' tmp_a = c_dir / f'.tmp-{key_hash}-{os.getpid()}.audit.json' shutil.copy2(out_o, tmp_o) shutil.copy2(out_a, tmp_a) tmp_o.replace(cached_o) tmp_a.replace(cached_a) except OSError: pass return json.loads(out_a.read_text(encoding='utf-8')) def _parse_bsd_ar_members(archive_path): """Parse BSD/Mach-O static archive members; return None if not an ar archive.""" arch_p = Path(archive_path) data = arch_p.read_bytes() if len(data) >= 8 and data[:4] in (b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'): with tempfile.NamedTemporaryFile(dir=arch_p.parent, suffix='.thin.a', delete=False) as tf: thin_p = Path(tf.name) try: subprocess.run(['xcrun', 'lipo', str(arch_p), '-thin', 'arm64', '-output', str(thin_p)], check=True) data = thin_p.read_bytes() finally: if thin_p.exists(): thin_p.unlink() if not data.startswith(b'!\n'): return None members = [] pos = 8 total = len(data) while pos + 60 <= total: hdr = data[pos:pos + 60] if hdr[58:60] != b'`\n': raise RuntimeError(f'[IGObf] Corrupt ar member header in {arch_p} at offset {pos}') raw_name = hdr[0:16].decode('latin1') member_size = int(hdr[48:58].decode('ascii', errors='strict').strip()) pos += 60 payload = data[pos:pos + member_size] pos += member_size if member_size & 1: pos += 1 name = raw_name.rstrip(' ') if name.startswith('#1/'): name_len = int(name[3:]) ext_name = payload[:name_len].rstrip(b'\x00').decode('utf-8', errors='replace') payload = payload[name_len:] name = ext_name else: name = name.rstrip('/') if name.startswith('__.SYMDEF') or name in ('/', '//'): continue members.append((name, payload)) return members def _build_static_framework_source_map(fw_name, app_repo, anchor_path): """Map object stem / basename -> repo-relative source path for a static Pod framework.""" stem_map = {} vendor_dir = app_repo / 'Vendor' / fw_name if vendor_dir.is_dir(): for src in sorted(vendor_dir.rglob('*')): if src.is_file() and src.suffix in ('.swift', '.m', '.mm', '.c', '.cc', '.cpp'): rel = str(src.relative_to(app_repo)).replace('\\', '/') stem_map.setdefault(src.stem, rel) stem_map.setdefault(src.name, rel) # Also check sibling Pods Intermediates OutputFileMap.json if available. search_bases = [] if anchor_path: for parent in Path(anchor_path).parents: if parent.name in ('Intermediates.noindex', 'ArchiveIntermediates', 'Build'): search_bases.append(parent) seen_ofm = set() for base in search_bases: if not base.is_dir(): continue for ofm_path in base.glob(f'**/{fw_name}.build/**/*-OutputFileMap.json'): if ofm_path in seen_ofm: continue seen_ofm.add(ofm_path) try: raw = json.loads(ofm_path.read_text(encoding='utf-8')) except Exception: continue for src_key, entry in raw.items(): if not isinstance(entry, dict) or not src_key: continue norm_src = src_key.replace('\\', '/') if app_repo: repo_prefix = str(app_repo).replace('\\', '/').rstrip('/') + '/' if norm_src.startswith(repo_prefix): norm_src = norm_src[len(repo_prefix):] for field in ('llvm-bc', 'object'): out_file = entry.get(field) if out_file: stem = Path(out_file).stem stem_map[stem] = norm_src stem_map[Path(out_file).name] = norm_src return stem_map def convert_swift_objects(args, output_path, linkmap_arg, ctl, policy_path, policy, app_repo): """Identify Target Swift bitcode objects via OutputFileMap ∩ LinkFileList, lower via opt + clang.""" filelist_arg = parse_flag_value(args, '-filelist') if not filelist_arg or not Path(filelist_arg).is_file(): return args, { 'expected_swift_count': 0, 'converted_swift_count': 0, 'skipped_swift_count': 0, 'swift_audits': [], 'objc_audits': [], 'replaced_entries': [], } filelist_path = Path(filelist_arg) raw_entries = [line.strip() for line in filelist_path.read_text(encoding='utf-8').splitlines() if line.strip()] swift_ofm = load_target_swift_output_map(filelist_path) target_triple, syslibroot = extract_platform_flags(args) sdk_info = detect_sdk_info(syslibroot) if syslibroot else detect_sdk_info() exempt_subs = policy.get('exempt_path_substrings', []) expected_indices = [] skipped = [] for idx, entry in enumerate(raw_entries): norm = os.path.normpath(entry) src_hint = swift_ofm.get(norm) if src_hint is None: continue expected_indices.append((idx, entry, src_hint)) to_convert = [] for idx, entry, src_hint in expected_indices: if any(ex in src_hint or ex in entry for ex in exempt_subs): skipped.append({'object': entry, 'source': src_hint, 'reason': 'exempt_path'}) continue if not Path(entry).is_file(): skipped.append({'object': entry, 'source': src_hint, 'reason': 'missing_file'}) continue if not is_bitcode_wrapper(entry): skipped.append({'object': entry, 'source': src_hint, 'reason': 'not_bitcode'}) continue to_convert.append((idx, entry, src_hint)) converted_map = {} swift_audits = [] new_entries = list(raw_entries) if to_convert: require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop') tc = resolve_opt(require_obf=require_obf) if not tc.get('opt_path'): raise RuntimeError(tc.get('warning', 'Verified opt binary unavailable for Swift bitcode lowering')) clang_bin = detect_stock_tool('clang') wrapper_sha = file_sha256(__file__) policy_sha = file_sha256(policy_path) if policy_path and Path(policy_path).is_file() else 'none' pipeline = os.environ.get('IG_SWIFT_OPT_PIPELINE', 'default,ig-obfuscate') cache_root = infer_obj_cache_dir(output_path, linkmap_arg) swift_mod_name = os.environ.get('PRODUCT_MODULE_NAME') or re.sub( r'[^A-Za-z0-9_]', '_', Path(output_path).stem ) persistent_macho_dir = filelist_path.parent / 'ig-swift-macho' persistent_macho_dir.mkdir(parents=True, exist_ok=True) backend_flags = [ '-target', target_triple, '-isysroot', syslibroot, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', f'-ffile-prefix-map={app_repo}=.', '-x', 'ir', '-c', ] def worker(item): idx, bc_str, src_hint = item bc_p = Path(bc_str) out_o = persistent_macho_dir / f'{idx:04d}_{bc_p.stem}.o' out_a = persistent_macho_dir / f'{idx:04d}_{bc_p.stem}.o.ig-audit.json' audit_data = _lower_single_bitcode_object( bc_p, out_o, out_a, src_hint, swift_mod_name, backend_flags, tc, clang_bin, sdk_info, wrapper_sha, policy_sha, pipeline, ctl, policy_path, cache_root, cache_kind='swift_v1', tmp_parent=persistent_macho_dir, ) return idx, str(out_o), audit_data with ThreadPoolExecutor(max_workers=min(8, max(1, len(to_convert)))) as pool: for idx, macho_out, audit_data in pool.map(worker, to_convert): converted_map[idx] = macho_out new_entries[idx] = macho_out swift_audits.append(audit_data) ig_filelist = filelist_path.parent / f'{filelist_path.name}.ig' ig_filelist.write_text('\n'.join(new_entries) + '\n', encoding='utf-8') rewritten_args = [] i = 0 while i < len(args): if args[i] == '-filelist' and i + 1 < len(args) and args[i + 1] == filelist_arg: rewritten_args.extend(['-filelist', str(ig_filelist)]) i += 2 continue rewritten_args.append(args[i]) i += 1 args = rewritten_args # Collect matching ObjC/C sidecar audits (ignoring stale/mismatched mode sidecars) objc_audits = [] converted_set = set(converted_map.values()) for entry in new_entries: if entry in converted_set: continue sidecar = Path(entry + '.ig-audit.json') obj_p = Path(entry) if not sidecar.is_file() or not obj_p.is_file(): continue try: s_data = json.loads(sidecar.read_text(encoding='utf-8')) if s_data.get('mode') != ctl['mode'] or s_data.get('pass_filter') != ctl['filter']: continue if abs(sidecar.stat().st_mtime_ns - obj_p.stat().st_mtime_ns) > 10_000_000_000 and sidecar.stat().st_mtime_ns + 5_000_000_000 < obj_p.stat().st_mtime_ns: continue objc_audits.append(s_data) except Exception: continue return args, { 'expected_swift_count': len(expected_indices), 'converted_swift_count': len(converted_map), 'skipped_swift_count': len(skipped), 'skipped_swift': skipped, 'swift_audits': swift_audits, 'objc_audits': objc_audits, 'replaced_entries': new_entries, 'static_frameworks_obfuscated': [], } def convert_static_framework_bitcode(args, output_path, linkmap_arg, ctl, policy_path, policy, app_repo, conv_report): """Unpack target static framework archives containing Swift ThinLTO bitcode, obfuscate & repack.""" target_fws = set(policy.get('obfuscate_static_frameworks') or []) if not target_fws: return args, conv_report search_dirs = [] i = 0 while i < len(args): a = args[i] if a == '-F' and i + 1 < len(args): search_dirs.append(Path(args[i + 1])) i += 2 continue if a.startswith('-F') and len(a) > 2: search_dirs.append(Path(a[2:])) i += 1 continue i += 1 def find_framework_archive(fw_name): for sdir in search_dirs: cand = sdir / f'{fw_name}.framework' / fw_name if cand.is_file(): members = _parse_bsd_ar_members(cand) if members is not None: return cand, sdir, members return None, None, None filelist_arg = parse_flag_value(args, '-filelist') work_root_parent = Path(filelist_arg).parent if filelist_arg else output_path.parent target_triple, syslibroot = extract_platform_flags(args) sdk_info = detect_sdk_info(syslibroot) if syslibroot else detect_sdk_info() require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop') tc = None clang_bin = None wrapper_sha = None policy_sha = None pipeline = None cache_root = None backend_flags = None replaced_fw_map = {} fw_records = list(conv_report.get('static_frameworks_obfuscated') or []) i = 0 while i < len(args): if args[i] == '-framework' and i + 1 < len(args) and args[i + 1] in target_fws: fw_name = args[i + 1] if fw_name not in replaced_fw_map: arch_p, sdir, members = find_framework_archive(fw_name) if arch_p and members: bc_indices = [idx for idx, (_, payload) in enumerate(members) if payload[:4] in BITCODE_MAGICS] if bc_indices: if tc is None: tc = resolve_opt(require_obf=require_obf) if not tc.get('opt_path'): raise RuntimeError(tc.get('warning', 'Verified opt binary unavailable for static framework bitcode')) clang_bin = detect_stock_tool('clang') wrapper_sha = file_sha256(__file__) policy_sha = file_sha256(policy_path) if policy_path and Path(policy_path).is_file() else 'none' pipeline = os.environ.get('IG_SWIFT_OPT_PIPELINE', 'default,ig-obfuscate') cache_root = infer_obj_cache_dir(output_path, linkmap_arg) backend_flags = [ '-target', target_triple, '-isysroot', syslibroot, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', f'-ffile-prefix-map={app_repo}=.', '-x', 'ir', '-c', ] fw_work = work_root_parent / 'ig-static-fw' / fw_name if fw_work.exists(): shutil.rmtree(fw_work) fw_work.mkdir(parents=True, exist_ok=True) stem_map = _build_static_framework_source_map(fw_name, app_repo, linkmap_arg or output_path) bc_jobs = [] member_out_paths = [None] * len(members) passthrough_count = 0 for m_idx, (m_name, payload) in enumerate(members): safe_name = re.sub(r'[^A-Za-z0-9_.-]', '_', Path(m_name).name or f'member_{m_idx}.o') if not safe_name.endswith('.o'): safe_name = f'{safe_name}.o' if payload[:4] in BITCODE_MAGICS: bc_file = fw_work / f'{m_idx:04d}_{safe_name}.bc' bc_file.write_bytes(payload) m_stem = Path(m_name).stem src_hint = ( stem_map.get(m_name) or stem_map.get(m_stem) or f'Vendor/{fw_name}/{m_name}' ) out_o = fw_work / f'{m_idx:04d}_{safe_name}' out_a = fw_work / f'{m_idx:04d}_{safe_name}.ig-audit.json' bc_jobs.append((m_idx, bc_file, out_o, out_a, src_hint)) else: raw_o = fw_work / f'{m_idx:04d}_{safe_name}' raw_o.write_bytes(payload) member_out_paths[m_idx] = raw_o passthrough_count += 1 def fw_worker(job): m_idx, bc_file, out_o, out_a, src_hint = job audit_data = _lower_single_bitcode_object( bc_file, out_o, out_a, src_hint, fw_name, backend_flags, tc, clang_bin, sdk_info, wrapper_sha, policy_sha, pipeline, ctl, policy_path, cache_root, cache_kind='static_fw_v1', extra_cache_fields={'source_path': src_hint}, tmp_parent=fw_work, ) return m_idx, out_o, audit_data with ThreadPoolExecutor(max_workers=min(8, max(1, len(bc_jobs)))) as pool: for m_idx, out_o, audit_data in pool.map(fw_worker, bc_jobs): member_out_paths[m_idx] = out_o conv_report['swift_audits'].append(audit_data) out_archive = fw_work / f'{fw_name}.obf.a' subprocess.run( ['xcrun', 'libtool', '-static', '-o', str(out_archive), *[str(p) for p in member_out_paths]], check=True, ) conv_report['expected_swift_count'] += len(bc_jobs) conv_report['converted_swift_count'] += len(bc_jobs) replaced_fw_map[fw_name] = str(out_archive) fw_records.append({ 'framework': fw_name, 'source_archive': str(arch_p), 'bitcode_members': len(bc_jobs), 'passthrough_members': passthrough_count, 'output_archive': str(out_archive), }) i += 2 continue i += 1 conv_report['static_frameworks_obfuscated'] = fw_records if not replaced_fw_map: return args, conv_report new_args = [] seen_replaced = set() i = 0 while i < len(args): if args[i] == '-framework' and i + 1 < len(args) and args[i + 1] in replaced_fw_map: fw_name = args[i + 1] if fw_name not in seen_replaced: new_args.append(replaced_fw_map[fw_name]) seen_replaced.add(fw_name) i += 2 continue new_args.append(args[i]) i += 1 return new_args, conv_report def _bare_symbol_candidates(candidates): out = [] seen = set() for sc in candidates: if not sc: continue m = re.match(r'^(\d+)([A-Za-z_][A-Za-z0-9_]*)$', sc) if m: n = int(m.group(1)) rest = m.group(2) cand = rest[:n] if 0 < n <= len(rest) else sc else: cand = sc if cand not in seen: seen.add(cand) out.append(cand) return out def _demangle_swift_symbols(symbols): swift_syms = sorted({s for s in symbols if isinstance(s, str) and (s.startswith('$s') or s.startswith('_$s'))}) if not swift_syms: return {} try: res = subprocess.run( ['xcrun', 'swift-demangle', '--compact'], input='\n'.join(swift_syms) + '\n', capture_output=True, text=True, ) except OSError: return {} if res.returncode != 0: return {} out_lines = res.stdout.splitlines() if len(out_lines) != len(swift_syms): return {} return dict(zip(swift_syms, out_lines)) def evaluate_and_write_obf_audit(output_path, linkmap_arg, ctl, policy_path, policy, conv_report): audit_root = ( Path(linkmap_arg).parent if linkmap_arg else Path(os.environ.get('TARGET_TEMP_DIR') or str(output_path.parent)) ) audit_dir = audit_root / 'ig-route2-audit' audit_dir.mkdir(parents=True, exist_ok=True) all_audits = conv_report['swift_audits'] + conv_report['objc_audits'] demangled_map = _demangle_swift_symbols( fn for a in all_audits for fn in ((a.get('functions_flattened') or []) + (a.get('strings_encrypted_functions') or [])) ) def _matches_any(fn, raw_cands, bare_cands): if any(sc in fn for sc in raw_cands): return True dm = demangled_map.get(fn) return bool(dm and any(bc in dm for bc in bare_cands)) total_flattened = sum(len(a.get('functions_flattened') or []) for a in all_audits) total_strings = sum(int(a.get('strings_encrypted_count') or 0) for a in all_audits) total_strings_stack = sum(int(a.get('strings_stack_encrypted_count') or 0) for a in all_audits) total_objc_strings = sum(int(a.get('objc_strings_encrypted_count') or 0) for a in all_audits) total_swift_strings = sum(int(a.get('swift_strings_encrypted_count') or 0) for a in all_audits) total_strings_replaced = sum(int(a.get('strings_replaced_count') or 0) for a in all_audits) total_paths_scrubbed = sum(int(a.get('paths_scrubbed_count') or 0) for a in all_audits) total_indirect_calls = sum(int(a.get('indirect_calls_count') or 0) for a in all_audits) total_opaque_constants = sum(int(a.get('opaque_constants_count') or 0) for a in all_audits) total_arithmetic_rewrites = sum(int(a.get('arithmetic_rewrites_count') or 0) for a in all_audits) total_indirect_branches = sum(int(a.get('indirect_branches_count') or 0) for a in all_audits) total_anti_hook_functions = sum(int(a.get('anti_hook_functions_count') or 0) for a in all_audits) total_functions_outlined = sum(int(a.get('functions_outlined_count') or 0) for a in all_audits) total_opaque_field_access = sum(int(a.get('opaque_field_access_count') or 0) for a in all_audits) total_bb_split_count = sum(int(a.get('bb_split_count') or 0) for a in all_audits) total_bb_split_functions = sum(len(a.get('bb_split_functions') or []) for a in all_audits) total_nonlinear_mba = sum(int(a.get('nonlinear_mba_count') or 0) for a in all_audits) total_opaque_zero = sum(int(a.get('opaque_zero_count') or 0) for a in all_audits) req_results = [] failures = [] mode = ctl['mode'] filt = ctl['filter'] for req in policy.get('required_targets', []): tid = req.get('id', 'unknown') path_sub = req.get('path_contains', '') sym_sub = req.get('symbol_contains', '') str_sym_sub = req.get('str_symbol_contains', '') sym_candidates = req.get('symbol_contains_any') or ([sym_sub] if sym_sub else []) str_sym_candidates = req.get('str_symbol_contains_any') or ([str_sym_sub] if str_sym_sub else []) sym_bare = _bare_symbol_candidates(sym_candidates) str_sym_bare = _bare_symbol_candidates(str_sym_candidates) matched_recs = [] for a in all_audits: fns = (a.get('functions_flattened') or []) + (a.get('strings_encrypted_functions') or []) if (path_sub and path_sub in (a.get('source_path') or '')) or any( _matches_any(fn, sym_candidates, sym_bare) or _matches_any(fn, str_sym_candidates, str_sym_bare) for fn in fns ): matched_recs.append(a) flat_hits = sum( 1 for a in matched_recs for fn in (a.get('functions_flattened') or []) if not sym_candidates or _matches_any(fn, sym_candidates, sym_bare) ) str_hits = sum(int(a.get('strings_encrypted_count') or 0) for a in matched_recs) const_hits = sum(int(a.get('opaque_constants_count') or 0) for a in matched_recs) arith_hits = sum(int(a.get('arithmetic_rewrites_count') or 0) for a in matched_recs) ibr_hits = sum(int(a.get('indirect_branches_count') or 0) for a in matched_recs) antihook_hits = sum(int(a.get('anti_hook_functions_count') or 0) for a in matched_recs) req_results.append({ 'id': tid, 'matched_modules': len(matched_recs), 'flattened_hits': flat_hits, 'strings_encrypted_hits': str_hits, 'opaque_constants_hits': const_hits, 'arithmetic_rewrites_hits': arith_hits, 'indirect_branches_hits': ibr_hits, 'anti_hook_functions_hits': antihook_hits, }) if mode == 'full' and filt == 'all': if flat_hits < int(req.get('min_flattened', 0)): failures.append(f'{tid}: expected >= {req.get("min_flattened")} flattened hits, got {flat_hits}') if str_hits < int(req.get('min_strings_encrypted', 0)): failures.append(f'{tid}: expected >= {req.get("min_strings_encrypted")} encrypted strings, got {str_hits}') if const_hits < int(req.get('min_opaque_constants', 0)): failures.append(f'{tid}: expected >= {req.get("min_opaque_constants")} opaque constants, got {const_hits}') if arith_hits < int(req.get('min_arithmetic_rewrites', 0)): failures.append(f'{tid}: expected >= {req.get("min_arithmetic_rewrites")} arithmetic rewrites, got {arith_hits}') if ibr_hits < int(req.get('min_indirect_branches', 0)): failures.append(f'{tid}: expected >= {req.get("min_indirect_branches")} indirect branches, got {ibr_hits}') if antihook_hits < int(req.get('min_anti_hook_functions', 0)): failures.append(f'{tid}: expected >= {req.get("min_anti_hook_functions")} anti-hook functions, got {antihook_hits}') elif mode == 'str' or (mode == 'full' and filt == 'str'): if str_hits < int(req.get('min_strings_encrypted', 0)): failures.append(f'{tid}: expected >= {req.get("min_strings_encrypted")} encrypted strings, got {str_hits}') if mode == 'str' or (mode == 'full' and filt == 'str'): if ( total_flattened != 0 or total_indirect_calls != 0 or total_opaque_constants != 0 or total_arithmetic_rewrites != 0 or total_indirect_branches != 0 or total_anti_hook_functions != 0 or total_functions_outlined != 0 or total_opaque_field_access != 0 or total_bb_split_count != 0 ): failures.append( f'str mode expected total_flattened=0 and total_indirect_calls=0, ' f'got flattened={total_flattened}, indirect_calls={total_indirect_calls}, ' f'opaque_constants={total_opaque_constants}, arith={total_arithmetic_rewrites}, ' f'ibr={total_indirect_branches}, antihook={total_anti_hook_functions}, ' f'outline={total_functions_outlined}, field={total_opaque_field_access}, ' f'bbsplit={total_bb_split_count}' ) elif mode == 'full' and filt == 'fla': if ( total_indirect_calls != 0 or total_strings != 0 or total_paths_scrubbed != 0 or total_opaque_constants != 0 or total_arithmetic_rewrites != 0 or total_indirect_branches != 0 or total_anti_hook_functions != 0 or total_functions_outlined != 0 or total_opaque_field_access != 0 or total_bb_split_count != 0 ): failures.append( f'fla filter expected zero non-fla edits, ' f'got indirect_calls={total_indirect_calls}, strings={total_strings}, paths={total_paths_scrubbed}' ) elif mode in ('noop', 'off'): if ( total_flattened != 0 or total_strings != 0 or total_indirect_calls != 0 or total_paths_scrubbed != 0 or total_opaque_constants != 0 or total_arithmetic_rewrites != 0 or total_indirect_branches != 0 or total_anti_hook_functions != 0 or total_functions_outlined != 0 or total_opaque_field_access != 0 or total_bb_split_count != 0 ): failures.append( f'{mode} mode expected zero edits, got flattened={total_flattened}, ' f'strings={total_strings}, indirect_calls={total_indirect_calls}, paths={total_paths_scrubbed}' ) summary = { 'target_binary': output_path.name, 'mode': mode, 'pass_filter': filt, 'route2_mode': ctl['route2'], 'all_off': ctl['all_off'], 'seed': ctl['seed'], 'stamp': ctl['stamp'], 'policy_path': policy_path, 'l1_translation_active': bool(policy.get('l1_translation_active')), 'l1_map_digest': policy.get('l1_map_digest', ''), 'expected_swift_count': conv_report['expected_swift_count'], 'converted_swift_count': conv_report['converted_swift_count'], 'skipped_swift_count': conv_report['skipped_swift_count'], 'objc_audited_count': len(conv_report['objc_audits']), 'total_flattened': total_flattened, 'total_strings_encrypted': total_strings, 'total_strings_stack_encrypted': total_strings_stack, 'total_objc_strings_encrypted': total_objc_strings, 'total_swift_strings_encrypted': total_swift_strings, 'total_strings_replaced': total_strings_replaced, 'total_paths_scrubbed': total_paths_scrubbed, 'total_indirect_calls': total_indirect_calls, 'total_opaque_constants': total_opaque_constants, 'total_arithmetic_rewrites': total_arithmetic_rewrites, 'total_indirect_branches': total_indirect_branches, 'total_anti_hook_functions': total_anti_hook_functions, 'total_functions_outlined': total_functions_outlined, 'total_opaque_field_access': total_opaque_field_access, 'total_bb_split_count': total_bb_split_count, 'total_bb_split_functions': total_bb_split_functions, 'total_nonlinear_mba': total_nonlinear_mba, 'total_opaque_zero': total_opaque_zero, 'required_targets': req_results, 'static_frameworks_obfuscated': conv_report.get('static_frameworks_obfuscated', []), 'module_audits': [ { 'source_path': a.get('source_path'), 'strings_encrypted_count': a.get('strings_encrypted_count'), 'strings_stack_encrypted_count': int(a.get('strings_stack_encrypted_count') or 0), 'objc_strings_encrypted_count': int(a.get('objc_strings_encrypted_count') or 0), 'swift_strings_encrypted_count': int(a.get('swift_strings_encrypted_count') or 0), 'strings_replaced_count': int(a.get('strings_replaced_count') or 0), 'indirect_calls_count': int(a.get('indirect_calls_count') or 0), 'indirect_calls_functions': a.get('indirect_calls_functions') or [], 'opaque_constants_count': int(a.get('opaque_constants_count') or 0), 'arithmetic_rewrites_count': int(a.get('arithmetic_rewrites_count') or 0), 'indirect_branches_count': int(a.get('indirect_branches_count') or 0), 'indirect_branches_functions': a.get('indirect_branches_functions') or [], 'anti_hook_functions_count': int(a.get('anti_hook_functions_count') or 0), 'anti_hook_functions': a.get('anti_hook_functions') or [], 'functions_outlined_count': int(a.get('functions_outlined_count') or 0), 'outlined_functions': a.get('outlined_functions') or [], 'opaque_field_access_count': int(a.get('opaque_field_access_count') or 0), 'opaque_field_functions': a.get('opaque_field_functions') or [], 'bb_split_count': int(a.get('bb_split_count') or 0), 'bb_split_functions': a.get('bb_split_functions') or [], 'nonlinear_mba_count': int(a.get('nonlinear_mba_count') or 0), 'opaque_zero_count': int(a.get('opaque_zero_count') or 0), 'functions_flattened': a.get('functions_flattened'), 'functions_flattened_details': a.get('functions_flattened_details') or [], 'strings_encrypted_functions': a.get('strings_encrypted_functions'), } for a in all_audits if ( a.get('functions_flattened') or int(a.get('strings_encrypted_count') or 0) > 0 or int(a.get('opaque_constants_count') or 0) > 0 or int(a.get('arithmetic_rewrites_count') or 0) > 0 or int(a.get('indirect_branches_count') or 0) > 0 or int(a.get('anti_hook_functions_count') or 0) > 0 or int(a.get('functions_outlined_count') or 0) > 0 or int(a.get('opaque_field_access_count') or 0) > 0 or int(a.get('bb_split_count') or 0) > 0 ) ], } (audit_dir / 'ig_obfuscation_audit.json').write_text( json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8' ) if failures: raise RuntimeError('[IGObf] Audit gate failed: ' + '; '.join(failures)) return summary def build_rewritten_ld_args(args, app_repo, stage_dir, unpatched_out, linkmap_out, has_map_flag): """Rewrite SDK -l / -framework / direct path arguments and inject IGThreadID.o + -F stage_dir.""" by_framework = {} by_lib = {} by_source = {} for entry in STATIC_INPUTS: cand = stage_dir / entry['dest'] if not cand.is_file(): continue src = (app_repo / entry['relative']).resolve() by_source[str(src)] = str(cand) eargs = entry.get('arguments') or [] if len(eargs) == 2 and eargs[0] == '-framework': by_framework[eargs[1]] = str(cand) elif len(eargs) == 1 and eargs[0].startswith('-l'): by_lib[eargs[0][2:]] = str(cand) rewritten = [] inserted_stage_f = False replaced_sdks = [] i = 0 while i < len(args): arg = args[i] if not inserted_stage_f and (arg == '-F' or (arg.startswith('-F') and len(arg) > 2)): rewritten.extend(['-F', str(stage_dir)]) inserted_stage_f = True if arg in ('-framework', '-weak_framework') and i + 1 < len(args): fw_name = args[i + 1] if fw_name in by_framework: rewritten.append(by_framework[fw_name]) replaced_sdks.append(f'{arg} {fw_name}') i += 2 continue if arg.startswith('-l') and len(arg) > 2 and arg[2:] in by_lib: lib_name = arg[2:] rewritten.append(by_lib[lib_name]) replaced_sdks.append(f'-l{lib_name}') i += 1 continue if arg == '-l' and i + 1 < len(args) and args[i + 1] in by_lib: lib_name = args[i + 1] rewritten.append(by_lib[lib_name]) replaced_sdks.append(f'-l {lib_name}') i += 2 continue if arg == '-o' and i + 1 < len(args): if not inserted_stage_f: rewritten.extend(['-F', str(stage_dir)]) inserted_stage_f = True rewritten.append(str(stage_dir / 'IGThreadID.o')) if not has_map_flag: rewritten.extend(['-map', str(linkmap_out)]) rewritten.extend(['-o', str(unpatched_out)]) i += 2 continue if not arg.startswith('-'): p = Path(arg) if p.exists(): resolved = str(p.resolve()) if resolved in by_source: rewritten.append(by_source[resolved]) replaced_sdks.append(resolved) i += 1 continue rewritten.append(arg) i += 1 return rewritten, replaced_sdks def check_coverage_absent(args): for arg in args: if 'clang_rt.profile_' in arg: raise RuntimeError( f'[IGRoute2] Refusing Route 2 Release link because LLVM code coverage runtime ' f'is linked ({arg}). Set ENABLE_CODE_COVERAGE=NO / CLANG_ENABLE_CODE_COVERAGE=NO.' ) def select_matching_rules(profile, attributed_sites, link_sym_map): """Filter shared profile rules to (caller, symbol) pairs present in this target.""" observed = Counter((s.get('caller'), s.get('symbol')) for s in attributed_sites if s.get('caller')) selected = [] for rule in profile['rules']: key = (rule['caller'], rule['symbol']) if observed.get(key, 0) > 0 and rule['caller'] in link_sym_map and rule['destination'] in link_sym_map: selected.append(rule) return dict(rules=selected) def verify_patched_main(binary_path, linkmap_path): m = Macho(binary_path.read_bytes()) defined = defined_symbols(m) missing_dispatch = sorted(EXPECTED_DISPATCH_SYMBOLS - set(defined)) if missing_dispatch: raise RuntimeError(f'[IGRoute2] Main binary missing _IG_dispatch_* symbols: {missing_dispatch}') variants = collect_variant_stubs(binary_path) if variants: raise RuntimeError(f'[IGRoute2] Main binary still has Darwin-variant stubs: {variants}') info, sites = inspect_binary(binary_path) if sites: attributed = list(attribute(Path(binary_path), Path(linkmap_path))) details = [ f"{s.get('symbol')} in {s.get('caller', '?')} ({s.get('object', '?')}) @ 0x{s['site']:x}" for s in attributed[:20] ] raise RuntimeError( f'[IGRoute2] {len(sites)} residual direct callsite(s) remain in {binary_path.name}: ' + '; '.join(details) ) return info def should_passthrough(args, out_arg, ctl=None): if ctl and ctl.get('all_off') == '1' and ctl.get('route2') == 'off': return True, 'IG_ALL_GUARD_OFF=1' if (not ctl) and os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1': return True, 'IG_DISABLE_ROUTE2_ARCHIVE=1' if any(flag in args for flag in PASSTHROUGH_FLAGS): return True, 'non-executable link mode' if not out_arg: return True, 'no -o output' out_path = Path(out_arg) if out_path.parent.suffix != '.app': return True, f'non-.app output ({out_path.parent.name})' arch = parse_flag_value(args, '-arch') if arch and arch != 'arm64': return True, f'non-arm64 arch ({arch})' return False, '' def main(argv=None): raw_args = list(sys.argv[1:] if argv is None else argv) args, ctl = strip_ig_stamp(raw_args) real_ld = resolve_real_ld(args) out_arg = parse_flag_value(args, '-o') passthrough, _ = should_passthrough(args, out_arg, ctl=ctl) if passthrough: os.execv(real_ld, [real_ld, *args]) return 0 output_path = Path(out_arg) map_arg = parse_flag_value(args, '-map') filelist_arg = parse_flag_value(args, '-filelist') swift_hints = [filelist_arg or '', out_arg or ''] if filelist_arg and Path(filelist_arg).is_file(): ofm_map = load_target_swift_output_map(Path(filelist_arg)) for src_p in ofm_map.values(): if src_p and src_p != '' and src_p.endswith('.swift'): swift_hints.append(src_p) break app_repo = discover_active_app_repo(swift_hints, fallback_root=resolve_app_repo(TOOLCHAIN_ROOT)) policy_path = os.environ.get('IG_LLVM_POLICY_PATH') or resolve_default_policy(ctl.get('policy_profile', 'default')) policy = {} if policy_path and Path(policy_path).is_file(): policy_path, policy = resolve_effective_policy( policy_path, app_repo, infer_obj_cache_dir(output_path, map_arg) ) if ctl['all_off'] != '1': args, conv_report = convert_swift_objects( args, output_path, map_arg, ctl, policy_path, policy, app_repo ) args, conv_report = convert_static_framework_bitcode( args, output_path, map_arg, ctl, policy_path, policy, app_repo, conv_report ) if not args_contain_remaining_bitcode(args, conv_report.get('replaced_entries', [])): args = strip_lto_link_flags(args) obf_audit = evaluate_and_write_obf_audit(output_path, map_arg, ctl, policy_path, policy, conv_report) else: obf_audit = {'total_flattened': 0, 'total_strings_encrypted': 0, 'converted_swift_count': 0} if ctl['route2'] == 'off': os.execv(real_ld, [real_ld, *args]) return 0 check_coverage_absent(args) bridge_src = resolve_bridge_source(app_repo) cache_root = infer_cache_root(output_path, map_arg) stage_dir = ensure_prepared_stage(cache_root, app_repo, bridge_src) with tempfile.TemporaryDirectory(prefix='.ig-ld-', dir=output_path.parent) as tmp: work = Path(tmp) unpatched = work / f'{output_path.name}.unpatched' patched = work / f'{output_path.name}.patched' linkmap = Path(map_arg) if map_arg else (work / f'{output_path.name}-LinkMap.txt') linkmap.parent.mkdir(parents=True, exist_ok=True) ld_args, replaced_sdks = build_rewritten_ld_args( args, app_repo, stage_dir, unpatched, linkmap, bool(map_arg), ) proc = subprocess.run([real_ld, *ld_args]) if proc.returncode != 0: return proc.returncode link_sym_map = link_symbols(linkmap) attributed_sites = list(attribute(unpatched, linkmap)) profile = json.loads(PROFILE_PATH.read_text(encoding='utf-8')) filtered_profile = select_matching_rules(profile, attributed_sites, link_sym_map) if filtered_profile['rules']: patch(unpatched, patched, linkmap, filtered_profile) final_bin = patched else: final_bin = unpatched verify_patched_main(final_bin, linkmap) output_path.parent.mkdir(parents=True, exist_ok=True) final_bin.chmod(0o755) shutil.copy2(final_bin, output_path) output_path.chmod(0o755) print( f'[IGRoute2] ld OK for {output_path.name}: ' f'sdk_inputs={len(replaced_sdks)}, residual_rules={len(filtered_profile["rules"])}, ' f'swift_conv={obf_audit.get("converted_swift_count", 0)}, ' f'flat={obf_audit.get("total_flattened", 0)}, str={obf_audit.get("total_strings_encrypted", 0)}' ) return 0 if __name__ == '__main__': raise SystemExit(main())