#!/usr/bin/env python3 """Verify that every flattened function in linked Mach-O binary has a single-center star-switch CFG.""" import argparse import bisect from concurrent.futures import ThreadPoolExecutor import json from pathlib import Path import re import subprocess import sys INSN_PC_RE = re.compile(r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+(.*)$') BRANCH_UNCOND_RE = re.compile(r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+b\s+(0x[0-9a-f]+)\b') BRANCH_ANY_RE = re.compile( r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+(b|b\.\w+|cbz|cbnz|tbz|tbnz)\s+.*?(0x[0-9a-f]+)\b' ) JUMP_TABLE_BR_RE = re.compile(r'\bbr\s+x\d+\b') RET_INSN_RE = re.compile(r'^\s*ret(?:aa|ab)?\b') def parse_dwarf_text_ranges(dwarf_bin: Path) -> dict[str, list[tuple[int, int]]]: """Return mapping of symbol name -> list of (start_addr, end_addr) ranges from DWARF nm.""" out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_bin)], text=True) syms: list[tuple[int, str]] = [] for line in out.splitlines(): parts = line.strip().split(maxsplit=2) if len(parts) == 3 and parts[1].lower() == 't': try: syms.append((int(parts[0], 16), parts[2])) except ValueError: continue syms.sort() unique_addrs = sorted({addr for addr, _ in syms}) ranges: dict[str, list[tuple[int, int]]] = {} for addr, name in syms: pos = bisect.bisect_right(unique_addrs, addr) next_addr = unique_addrs[pos] if pos < len(unique_addrs) else addr + 0x400 if next_addr > addr: ranges.setdefault(name, []).append((addr, next_addr)) return ranges def _inspect_range(main_bin: Path, start_addr: int, end_addr: int) -> dict: dis = subprocess.check_output( [ 'xcrun', 'llvm-objdump', '--disassemble', f'--start-address={hex(start_addr)}', f'--stop-address={hex(end_addr)}', str(main_bin), ], text=True, ) insns: list[tuple[int, str, str]] = [] uncond_in: dict[int, int] = {} uncond_back_in: dict[int, int] = {} func_back_edges = 0 has_jump_table_br = False indirect_br_count = 0 for line in dis.splitlines(): mp = INSN_PC_RE.match(line) if not mp: continue pc = int(mp.group(1), 16) rest = mp.group(2).strip() insns.append((pc, rest, line)) if JUMP_TABLE_BR_RE.search(rest): has_jump_table_br = True indirect_br_count += 1 mu = BRANCH_UNCOND_RE.match(line) if mu: tgt = int(mu.group(2), 16) if start_addr <= tgt < end_addr: uncond_in[tgt] = uncond_in.get(tgt, 0) + 1 if tgt < pc: uncond_back_in[tgt] = uncond_back_in.get(tgt, 0) + 1 ma = BRANCH_ANY_RE.match(line) if ma: tgt = int(ma.group(3), 16) if start_addr <= tgt < pc: func_back_edges += 1 # Single central dispatcher hub must have >=2 unconditional fan-in, continue dispatching # before returning (not a shared ret epilogue), and participate in a loop back-edge or jump table. best_hub = None best_uncond = 0 best_back = 0 best_valid = False has_cycle_or_jt = func_back_edges >= 1 or has_jump_table_br for tgt, u_cnt in uncond_in.items(): if u_cnt < 2: continue hub_continues_in_func = False for pc, rest, raw_line in insns: if pc < tgt: continue if RET_INSN_RE.match(rest): break if JUMP_TABLE_BR_RE.search(rest): hub_continues_in_func = True break ma = BRANCH_ANY_RE.match(raw_line) if ma: b_tgt = int(ma.group(3), 16) if start_addr <= b_tgt < end_addr: hub_continues_in_func = True break b_cnt = uncond_back_in.get(tgt, 0) is_valid = hub_continues_in_func and (b_cnt >= 1 or has_cycle_or_jt) score = (1 if is_valid else 0, b_cnt, u_cnt) best_score = (1 if best_valid else 0, best_back, best_uncond) if score > best_score: best_hub = tgt best_uncond = u_cnt best_back = b_cnt best_valid = is_valid reported_back = max(best_back, 1 if best_valid and has_cycle_or_jt else 0) return { 'start_addr': hex(start_addr), 'end_addr': hex(end_addr), 'insn_count': len(insns), 'hub_addr': hex(best_hub) if best_hub is not None else None, 'hub_uncond_fan_in': best_uncond, 'hub_back_edges': reported_back, 'indirect_br_count': indirect_br_count, 'is_star_dispatcher': best_valid, } def _candidate_symbol_keys(raw_name: str) -> list[str]: clean = raw_name.lstrip('\x01') keys = [] if clean.startswith('-') or clean.startswith('+'): keys.append(clean) else: keys.append('_' + clean) keys.append(clean) return keys def verify_binary_star_cfg( main_bin: Path, dwarf_bin: Path, obf_audit: dict, *, require_topology: str = 'sparse_switch', fail_on_missing: bool = False, ) -> dict: """Disassemble every audited flattened function in main_bin and enforce 100% star-hub CFG.""" ranges_map = parse_dwarf_text_ranges(dwarf_bin) ibr_funcs = { fn for mod in (obf_audit.get('module_audits') or []) for fn in (mod.get('indirect_branches_functions') or []) } verified = [] failed = [] dead_stripped = [] to_check: list[tuple[str, dict, list[tuple[int, int]]]] = [] for mod in obf_audit.get('module_audits') or []: src_name = Path(mod.get('source_path') or 'unknown').name for det in mod.get('functions_flattened_details') or []: raw_name = det['name'] topo = det.get('topology', '') if require_topology and topo != require_topology: failed.append({ 'source': src_name, 'name': raw_name, 'reason': f'unexpected_topology:{topo}', }) continue cand_ranges = [] for key in _candidate_symbol_keys(raw_name): if key in ranges_map: cand_ranges = ranges_map[key] break if not cand_ranges: rec = {'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'} dead_stripped.append(rec) if fail_on_missing: failed.append(rec) continue to_check.append((src_name, det, cand_ranges)) unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist}) inspected_by_range: dict[tuple[int, int], dict] = {} if unique_ranges: with ThreadPoolExecutor(max_workers=8) as pool: results = pool.map(lambda se: _inspect_range(main_bin, se[0], se[1]), unique_ranges) for se, res in zip(unique_ranges, results): inspected_by_range[se] = res for src_name, det, cand_ranges in to_check: raw_name = det['name'] topo = det.get('topology', '') has_ibr = raw_name in ibr_funcs # If static C symbols have duplicates across TUs, require every linked copy to pass range_results = [inspected_by_range[se] for se in cand_ranges] bad = [ r for r in range_results if not (r['is_star_dispatcher'] or (has_ibr and r.get('indirect_br_count', 0) >= 2)) ] if bad: failed.append({ 'source': src_name, 'name': raw_name, 'topology': topo, 'blocks': det.get('blocks'), 'reason': 'missing_star_dispatcher_hub', 'range_results': range_results, }) else: verified.append({ 'source': src_name, 'name': raw_name, 'topology': topo, 'blocks': det.get('blocks'), 'verified_via': ( 'star_dispatcher' if range_results[0]['is_star_dispatcher'] else 'indirect_br' ), **range_results[0], }) summary = { 'total_audited': len(verified) + len(failed) + (0 if fail_on_missing else len(dead_stripped)), 'linked_checked_count': len(verified) + len(failed), 'verified_star_count': len(verified), 'dead_stripped_count': len(dead_stripped), 'failed_count': len(failed), 'failed': failed, 'sample_verified_hubs': verified[:12], } if failed: preview = json.dumps(failed[:5], ensure_ascii=False, indent=2) raise AssertionError(f'[StarCFGGate] {len(failed)} function(s) failed star-switch CFG check:\n{preview}') return summary def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--binary', type=Path, required=True) parser.add_argument('--dwarf', type=Path, required=True) parser.add_argument('--audit', type=Path, required=True) parser.add_argument('--require-topology', default='sparse_switch') args = parser.parse_args() audit = json.loads(args.audit.read_text(encoding='utf-8')) res = verify_binary_star_cfg( args.binary, args.dwarf, audit, require_topology=args.require_topology, ) print(json.dumps(res, ensure_ascii=False, indent=2)) if __name__ == '__main__': main()