"""从最终链接的 arm64 镜像生成随应用签名的 ObjC 方法基线。""" import hashlib import os from pathlib import Path import re import struct import subprocess import sys import tempfile sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'macho_guard')) from batch import Slice from machox import Macho NAME = 'IGMethods.bin' MAGIC = b'IGMB0001' ROW = struct.Struct('<32s16sQI32s4x') METHOD = re.compile(r'^\s*(0x[0-9a-fA-F]+)\s+([+-])\[([^ (]+)(?:\([^)]*\))? ([^\]]+)\]$') def _is_top_level_swift_objc_class(name): raw = name.encode('utf-8') if not raw.startswith(b'_TtC'): return False idx = 4 for _ in range(2): start = idx while idx < len(raw) and 48 <= raw[idx] <= 57: idx += 1 if idx == start: return False length = int(raw[start:idx]) if length <= 0 or idx + length > len(raw): return False idx += length return idx == len(raw) def image_records(binary): data = binary.read_bytes() if data[:4] in (bytes.fromhex('cafebabe'), bytes.fromhex('cafebabf')): with tempfile.TemporaryDirectory() as tmp: thin = Path(tmp) / 'arm64' subprocess.run(['xcrun', 'lipo', str(binary), '-thin', 'arm64', '-output', str(thin)], check=True) data = thin.read_bytes() image = Macho(data) uuid, = [data[o + 8:o + 24] for cmd, _, o in image.cmds if cmd == 0x1b] layout = Slice(data, 0) listing = subprocess.check_output( ['xcrun', 'dyld_info', '-arch', 'arm64', '-function_starts', '-objc', str(binary)], text=True, ) start_listing, marker, objc_listing = listing.partition(' -objc:') if not marker or ' -function_starts:' not in start_listing: raise ValueError(f'无法解析 dyld_info 输出: {binary.name}') starts = sorted({int(a, 16) for a in re.findall(r'^\s*(0x[0-9a-fA-F]+)\s', start_listing, re.M)}) methods = [m.groups() for line in objc_listing.splitlines() if (m := METHOD.match(line))] # 同一镜像内,任一已知方法入口也构成前一方法的上界。 start_set = set(starts) boundaries = sorted(start_set.union(int(addr, 16) for addr, _, _, _ in methods)) lengths = {a: min(32, b - a) for a, b in zip(boundaries, boundaries[1:]) if a in start_set} records = [] swift_names = sorted({cls for _, _, cls, _ in methods if _is_top_level_swift_objc_class(cls)}) runtime_names = {} if swift_names: demangled = subprocess.run(['xcrun', 'swift-demangle', '--compact'], input='\n'.join(swift_names) + '\n', text=True, check=True, stdout=subprocess.PIPE).stdout.splitlines() if len(demangled) != len(swift_names): raise ValueError(f'Swift 类名解析失败: {binary.name}') runtime_names = dict(zip(swift_names, demangled)) text, text_size, offset = layout.text or (0, 0, 0) for address, kind, cls, selector in methods: cls = runtime_names.get(cls, cls) addr = int(address, 16) # 方法元数据给出了入口,缺少完整边界时只读取首条指令。 length = lengths.get(addr, 4) pos = offset + addr - text if pos < 0 or pos + length > len(data) or addr % 4 or length % 4 or not (text <= addr and addr + length <= text + text_size): length = 0 key = hashlib.sha256(f'{kind}{cls} {selector}'.encode()).digest() digest = hashlib.sha256(data[pos:pos + length]).digest() if length else bytes(32) records.append((key, uuid, addr - layout.text_vmaddr if length else 0, length, digest)) return uuid, records def input_images(app, main): """只记录主程序(Debug 还包括承载代码的 *.debug.dylib)。 受监控的方法都在主镜像中;Framework 的方法从不登记,收录它们只会增加包体与构建耗时, 并可能与主镜像同名方法冲突。新增监控方法须位于主镜像,否则运行时记为校验不可用。 """ return [main, *sorted(app.glob('*.debug.dylib'))] def image_uuid(binary): """只读取 Mach-O 头部取 arm64 切片的 LC_UUID,用于判断镜像是否重新链接。""" with open(binary, 'rb') as f: head = f.read(4096) base = 0 if head[:4] in (bytes.fromhex('cafebabe'), bytes.fromhex('cafebabf')): wide = head[3] == 0xbf step = 32 if wide else 20 count, = struct.unpack_from('>I', head, 4) for i in range(count): cpu, sub = struct.unpack_from('>II', head, 8 + i * step) if cpu == 0x0100000c and (sub & 0x00ffffff) == 0: base, = struct.unpack_from('>Q' if wide else '>I', head, 16 + i * step) break else: raise ValueError(f'缺少 arm64 切片: {binary}') f.seek(base) magic, _, _, _, ncmds, sizeofcmds = struct.unpack('