feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固
- defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测 - llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言) - tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化) - tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json
This commit is contained in:
Executable
+543
@@ -0,0 +1,543 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Physical-device M0-2/M0-3 verification: cross-file Swift async throws + ObjC + embedded framework + .ips/.crash restore."""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TOOLS_ARCHIVE = ROOT / 'tools' / 'xcode_archive'
|
||||
TOOLS_LLVM = ROOT / 'tools' / 'llvm_obf'
|
||||
TOOLS_CRASH = ROOT / 'tools' / 'crash_restore'
|
||||
|
||||
sys.path.insert(0, str(TOOLS_LLVM))
|
||||
sys.path.insert(0, str(TOOLS_ARCHIVE))
|
||||
sys.path.insert(0, str(TOOLS_CRASH))
|
||||
|
||||
from ig_ld_wrapper import verify_macho_object_platform # noqa: E402
|
||||
from ig_toolchain_resolver import detect_sdk_info, detect_stock_tool # noqa: E402
|
||||
import restore_crash_report # noqa: E402
|
||||
|
||||
DEFAULT_PROFILE = Path.home() / 'Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision'
|
||||
DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8'
|
||||
DEFAULT_DEVICE = '00008140-000960811493001C'
|
||||
DEFAULT_BUNDLE_ID = 'cn.touchv.iosguard.hookpilot.m0async'
|
||||
|
||||
|
||||
def run(cmd, env=None, cwd=None):
|
||||
return subprocess.run(list(map(str, cmd)), env=env, cwd=cwd, capture_output=True, text=True)
|
||||
|
||||
|
||||
def write_sources(src_dir):
|
||||
src_dir.mkdir(parents=True, exist_ok=True)
|
||||
# 1. Embedded framework (ObjC + C flattened & string-encrypted + captures live stack return addr)
|
||||
fw_h = src_dir / 'IGM0ProbeKit.h'
|
||||
fw_m = src_dir / 'M0Kit.m'
|
||||
fw_h.write_text(
|
||||
'#import <Foundation/Foundation.h>\n'
|
||||
'#include <stdint.h>\n'
|
||||
'FOUNDATION_EXPORT uintptr_t ig_m0_kit_probe_address(int selector);\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
fw_m.write_text(
|
||||
'#import "IGM0ProbeKit.h"\n'
|
||||
'#include <stdlib.h>\n'
|
||||
'#include <string.h>\n'
|
||||
'__attribute__((noinline)) static uintptr_t ig_m0_kit_leaf(void) {\n'
|
||||
' return (uintptr_t)__builtin_return_address(0) - 4;\n'
|
||||
'}\n'
|
||||
'__attribute__((noinline)) uintptr_t ig_m0_kit_probe_address(int selector) {\n'
|
||||
' const char *envv = getenv("IG_M0_NONEXISTENT_ENV_FLAG");\n'
|
||||
' int score = envv ? 99 : 0;\n'
|
||||
' if (selector == 1) score += 10;\n'
|
||||
' else if (selector == 2) score += 20;\n'
|
||||
' else score += 30;\n'
|
||||
' uintptr_t pc = ig_m0_kit_leaf();\n'
|
||||
' if (score == 10 || score == 20 || score == 30) {\n'
|
||||
' return pc;\n'
|
||||
' }\n'
|
||||
' return 0;\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# 2. ObjC main object (concurrent string decryption + multi-branch flattening)
|
||||
objc_h = src_dir / 'ObjCBridge.h'
|
||||
objc_m = src_dir / 'ObjCBridge.m'
|
||||
objc_h.write_text(
|
||||
'#import <Foundation/Foundation.h>\n'
|
||||
'#import "IGM0ProbeKit.h"\n'
|
||||
'FOUNDATION_EXPORT int ig_m0_objc_concurrent_check(int thread_idx);\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
objc_m.write_text(
|
||||
'#import "ObjCBridge.h"\n'
|
||||
'#include <stdlib.h>\n'
|
||||
'#include <string.h>\n'
|
||||
'__attribute__((noinline)) static int ig_m0_branch_a(const char *s, int x) { return (int)s[x & 3] ^ x; }\n'
|
||||
'__attribute__((noinline)) static int ig_m0_branch_b(const char *s, int x) { return (int)s[(x + 1) & 3] + x; }\n'
|
||||
'__attribute__((noinline)) int ig_m0_objc_concurrent_check(int thread_idx) {\n'
|
||||
' const char *envv = getenv("M0_DEVICE_CONCURRENT_OBJC_SECRET");\n'
|
||||
' const char *secret = "M0_DEVICE_CONCURRENT_OBJC_SECRET";\n'
|
||||
' int base = envv ? 99 : 33;\n'
|
||||
' int r = 0;\n'
|
||||
' if (thread_idx == 0) { r = ig_m0_branch_a(secret, 1); }\n'
|
||||
' else if (thread_idx == 1) { r = ig_m0_branch_b(secret, 2); }\n'
|
||||
' else if (thread_idx == 2) { r = ig_m0_branch_a(secret, 3); }\n'
|
||||
' else { r = ig_m0_branch_b(secret, 4); }\n'
|
||||
' if (r == 0x7fffffff) return -1;\n'
|
||||
' return base + (thread_idx & 3);\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# 3. Cross-file Swift 1: AsyncWorker.swift
|
||||
(src_dir / 'AsyncWorker.swift').write_text(
|
||||
'import Foundation\n'
|
||||
'\n'
|
||||
'enum M0AsyncError: Error {\n'
|
||||
' case simulatedFailure(Int)\n'
|
||||
'}\n'
|
||||
'\n'
|
||||
'final class AsyncWorker {\n'
|
||||
' @inline(never)\n'
|
||||
' static func stepMix(_ tag: Int, _ val: UnsafePointer<Int8>?) -> Int {\n'
|
||||
' let extra = (val != nil) ? Int(strlen(val!)) : 0\n'
|
||||
' return tag + extra + Int(ProcessInfo.processInfo.processIdentifier & 0)\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' @inline(never)\n'
|
||||
' static func controlledEnvCheck(_ mode: Int) -> Int {\n'
|
||||
' let val = getenv("M0_DEVICE_SWIFT_CONTROLLED_VAR")\n'
|
||||
' var acc = 10\n'
|
||||
' if mode == 1 { acc += stepMix(7, val) }\n'
|
||||
' else if mode == 2 { acc += stepMix(14, val) }\n'
|
||||
' else { acc += stepMix(21, val) }\n'
|
||||
' if acc > 50 { acc += stepMix(1, val) }\n'
|
||||
' return acc\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func computeAsync(value: Int, shouldThrow: Bool) async throws -> Int {\n'
|
||||
' try await Task.sleep(nanoseconds: 5_000_000)\n'
|
||||
' try Task.checkCancellation()\n'
|
||||
' let base = controlledEnvCheck(value)\n'
|
||||
' try await Task.sleep(nanoseconds: 3_000_000)\n'
|
||||
' if shouldThrow {\n'
|
||||
' throw M0AsyncError.simulatedFailure(base + 1)\n'
|
||||
' }\n'
|
||||
' return base * 2\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func cancellableWork() async throws -> Int {\n'
|
||||
' while true {\n'
|
||||
' try Task.checkCancellation()\n'
|
||||
' try await Task.sleep(nanoseconds: 4_000_000)\n'
|
||||
' }\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# 4. Cross-file Swift 2: AsyncCaller.swift (async @main calling AsyncWorker + IGM0ProbeKit + ObjCBridge)
|
||||
(src_dir / 'AsyncCaller.swift').write_text(
|
||||
'import Foundation\n'
|
||||
'import MachO\n'
|
||||
'\n'
|
||||
'@main\n'
|
||||
'struct M0Entry {\n'
|
||||
' @inline(never)\n'
|
||||
' static func logLine(_ s: String) {\n'
|
||||
' NSLog("%@", s)\n'
|
||||
' fputs(s + "\\n", stderr)\n'
|
||||
' fflush(stderr)\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' @inline(never)\n'
|
||||
' static func captureMainCallerFrame() -> UInt {\n'
|
||||
' let stack = Thread.callStackReturnAddresses\n'
|
||||
' let ra = stack.first?.uintValue ?? 0\n'
|
||||
' return ra > 4 ? (ra - 4) : 0\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func imageInfoString(matching nameSuffix: String) -> String {\n'
|
||||
' for i in 0..<_dyld_image_count() {\n'
|
||||
' guard let cname = _dyld_get_image_name(i) else { continue }\n'
|
||||
' let path = String(cString: cname)\n'
|
||||
' if path.hasSuffix(nameSuffix), let hdr = _dyld_get_image_header(i) {\n'
|
||||
' let base = UInt(bitPattern: hdr)\n'
|
||||
' return "\\(nameSuffix)|0x\\(String(base, radix: 16))|\\(path)"\n'
|
||||
' }\n'
|
||||
' }\n'
|
||||
' return "\\(nameSuffix)|0x0|missing"\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func main() async {\n'
|
||||
' // 1. Cross-file async normal resume\n'
|
||||
' do {\n'
|
||||
' let v = try await AsyncWorker.computeAsync(value: 2, shouldThrow: false)\n'
|
||||
' logLine("M0_DEV_CASE async_normal_resume \\(v == 48 ? "PASS" : "FAIL(\\(v))")")\n'
|
||||
' } catch {\n'
|
||||
' logLine("M0_DEV_CASE async_normal_resume FAIL(\\(error))")\n'
|
||||
' }\n'
|
||||
' // 2. Cross-file async throw/catch across suspension\n'
|
||||
' do {\n'
|
||||
' _ = try await AsyncWorker.computeAsync(value: 1, shouldThrow: true)\n'
|
||||
' logLine("M0_DEV_CASE async_throw_catch FAIL(no_throw)")\n'
|
||||
' } catch M0AsyncError.simulatedFailure(let code) {\n'
|
||||
' logLine("M0_DEV_CASE async_throw_catch \\(code == 18 ? "PASS" : "FAIL(\\(code))")")\n'
|
||||
' } catch {\n'
|
||||
' logLine("M0_DEV_CASE async_throw_catch FAIL(\\(error))")\n'
|
||||
' }\n'
|
||||
' // 3. Cross-file async cancellation\n'
|
||||
' let t = Task { try await AsyncWorker.cancellableWork() }\n'
|
||||
' try? await Task.sleep(nanoseconds: 12_000_000)\n'
|
||||
' t.cancel()\n'
|
||||
' do {\n'
|
||||
' _ = try await t.value\n'
|
||||
' logLine("M0_DEV_CASE async_cancellation FAIL(completed)")\n'
|
||||
' } catch is CancellationError {\n'
|
||||
' logLine("M0_DEV_CASE async_cancellation PASS")\n'
|
||||
' } catch {\n'
|
||||
' logLine("M0_DEV_CASE async_cancellation FAIL(\\(error))")\n'
|
||||
' }\n'
|
||||
' // 4. 8-thread concurrent flattened ObjC + encrypted string\n'
|
||||
' let grp = DispatchGroup()\n'
|
||||
' let q = DispatchQueue.global(qos: .userInitiated)\n'
|
||||
' let lock = NSLock()\n'
|
||||
' var ok = true\n'
|
||||
' for idx in 0..<8 {\n'
|
||||
' grp.enter()\n'
|
||||
' q.async {\n'
|
||||
' let r = ig_m0_objc_concurrent_check(Int32(idx % 4))\n'
|
||||
' let expected = Int32(33 + (idx % 4))\n'
|
||||
' if r != expected {\n'
|
||||
' lock.lock(); ok = false; lock.unlock()\n'
|
||||
' }\n'
|
||||
' grp.leave()\n'
|
||||
' }\n'
|
||||
' }\n'
|
||||
' grp.wait()\n'
|
||||
' logLine("M0_DEV_CASE objc_concurrent_str_flatten \\(ok ? "PASS" : "FAIL")")\n'
|
||||
'\n'
|
||||
' // 5. Capture runtime addresses from main app & embedded framework\n'
|
||||
' let mainImg = imageInfoString(matching: "/IGM0AsyncPilot")\n'
|
||||
' let kitImg = imageInfoString(matching: "/IGM0ProbeKit")\n'
|
||||
' let kitAddr = ig_m0_kit_probe_address(2)\n'
|
||||
' let mainAddr = captureMainCallerFrame()\n'
|
||||
' logLine("M0_RUNTIME_IMG \\(mainImg)")\n'
|
||||
' logLine("M0_RUNTIME_IMG \\(kitImg)")\n'
|
||||
' logLine(String(format: "M0_RUNTIME_FRAME main=0x%lx kit=0x%lx", UInt(mainAddr), UInt(kitAddr)))\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
|
||||
def verify_and_run(device, profile, identity, bundle_id, output_dir):
|
||||
output_dir = Path(output_dir).resolve()
|
||||
if output_dir.exists():
|
||||
shutil.rmtree(output_dir)
|
||||
output_dir.mkdir(parents=True)
|
||||
|
||||
r_prof = subprocess.run(['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(profile)],
|
||||
capture_output=True, check=True)
|
||||
pdata = plistlib.loads(r_prof.stdout)
|
||||
ent = pdata['Entitlements']
|
||||
prefix = pdata['ApplicationIdentifierPrefix'][0]
|
||||
if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'):
|
||||
raise RuntimeError('Provisioning profile must be wildcard development profile')
|
||||
if pdata['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None):
|
||||
raise RuntimeError('Provisioning profile expired')
|
||||
if identity.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}:
|
||||
raise RuntimeError('Identity does not match provisioning profile')
|
||||
|
||||
src_dir = output_dir / 'src'
|
||||
write_sources(src_dir)
|
||||
|
||||
policy_path = output_dir / 'm0_device_policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'string_encrypt_targets': [
|
||||
{'path_contains': 'M0Kit.m'},
|
||||
{'path_contains': 'ObjCBridge.m'},
|
||||
{'path_contains': 'AsyncWorker.swift'},
|
||||
],
|
||||
'flatten_targets': [
|
||||
{'path_contains': 'M0Kit.m', 'function_contains': 'ig_m0_kit_probe_address'},
|
||||
{'path_contains': 'ObjCBridge.m', 'function_contains': 'ig_m0_objc_concurrent_check'},
|
||||
{'path_contains': 'AsyncWorker.swift', 'function_contains': '18controlledEnvCheck'},
|
||||
],
|
||||
'required_targets': [
|
||||
{'id': 'dev_objc', 'path_contains': 'ObjCBridge.m', 'symbol_contains': 'ig_m0_objc_concurrent_check', 'min_flattened': 1, 'min_strings_encrypted': 1},
|
||||
{'id': 'dev_swift', 'path_contains': 'AsyncWorker.swift', 'symbol_contains': '18controlledEnvCheck', 'min_flattened': 1, 'min_strings_encrypted': 1},
|
||||
],
|
||||
}, indent=2), encoding='utf-8')
|
||||
|
||||
sdk_info = detect_sdk_info()
|
||||
sdk = sdk_info['sdk_path']
|
||||
swiftc = detect_stock_tool('swiftc')
|
||||
cc_wrapper = str(TOOLS_ARCHIVE / 'ig_cc_wrapper.py')
|
||||
ld_wrapper = str(TOOLS_ARCHIVE / 'ig_ld_wrapper.py')
|
||||
|
||||
env = dict(os.environ)
|
||||
env['IG_LLVM_POLICY_PATH'] = str(policy_path)
|
||||
env['IG_OBF_MODE'] = 'full'
|
||||
env['IG_LLVM_PASS_FILTER'] = 'all'
|
||||
env['IG_ROUTE2_MODE'] = 'off'
|
||||
env['IG_ALL_GUARD_OFF'] = '0'
|
||||
env['IG_RELEASE_SEED'] = 'm0_device_seed_1'
|
||||
env['IG_REQUIRE_LLVM_OBF'] = '1'
|
||||
env['CONFIGURATION'] = 'Release'
|
||||
env['PLATFORM_NAME'] = 'iphoneos'
|
||||
env['SRCROOT'] = str(src_dir)
|
||||
env['TARGET_TEMP_DIR'] = str(output_dir / 'temp')
|
||||
|
||||
app_dir = output_dir / 'IGM0AsyncPilot.app'
|
||||
fw_dir = app_dir / 'Frameworks' / 'IGM0ProbeKit.framework'
|
||||
dsym_dir = output_dir / 'dSYMs'
|
||||
fw_dir.mkdir(parents=True)
|
||||
dsym_dir.mkdir(parents=True)
|
||||
|
||||
# Build embedded IGM0ProbeKit.framework via ig_cc_wrapper.py
|
||||
fw_obj = output_dir / 'M0Kit.o'
|
||||
p1 = run([
|
||||
cc_wrapper, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
|
||||
'-Os', '-g', '-fobjc-arc', '-fPIC', '-I', str(src_dir),
|
||||
'-c', str(src_dir / 'M0Kit.m'), '-o', str(fw_obj),
|
||||
], env=env)
|
||||
if p1.returncode != 0:
|
||||
raise RuntimeError(f'M0Kit.m failed:\n{p1.stdout}\n{p1.stderr}')
|
||||
|
||||
clang = detect_stock_tool('clang')
|
||||
fw_bin = fw_dir / 'IGM0ProbeKit'
|
||||
subprocess.run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, '-dynamiclib',
|
||||
str(fw_obj), '-framework', 'Foundation',
|
||||
'-Wl,-install_name,@rpath/IGM0ProbeKit.framework/IGM0ProbeKit',
|
||||
'-o', str(fw_bin),
|
||||
], check=True)
|
||||
subprocess.run(['xcrun', 'dsymutil', str(fw_bin), '-o', str(dsym_dir / 'IGM0ProbeKit.framework.dSYM')], check=True)
|
||||
(fw_dir / 'Info.plist').write_bytes(plistlib.dumps({
|
||||
'CFBundleExecutable': 'IGM0ProbeKit',
|
||||
'CFBundleIdentifier': bundle_id + '.probekit',
|
||||
'CFBundleInfoDictionaryVersion': '6.0',
|
||||
'CFBundleName': 'IGM0ProbeKit',
|
||||
'CFBundlePackageType': 'FMWK',
|
||||
'CFBundleShortVersionString': '1.0',
|
||||
'CFBundleSupportedPlatforms': ['iPhoneOS'],
|
||||
'CFBundleVersion': '1',
|
||||
'MinimumOSVersion': '15.0',
|
||||
}))
|
||||
|
||||
# Compile ObjCBridge.m via ig_cc_wrapper.py
|
||||
obj_dir = output_dir / 'objs'
|
||||
obj_dir.mkdir()
|
||||
objc_obj = obj_dir / 'ObjCBridge.o'
|
||||
p2 = run([
|
||||
cc_wrapper, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
|
||||
'-Os', '-g', '-fobjc-arc', '-I', str(src_dir),
|
||||
'-c', str(src_dir / 'ObjCBridge.m'), '-o', str(objc_obj),
|
||||
], env=env)
|
||||
if p2.returncode != 0:
|
||||
raise RuntimeError(f'ObjCBridge.m failed:\n{p2.stdout}\n{p2.stderr}')
|
||||
|
||||
# Compile cross-file Swift via stock swiftc -O -g -lto=llvm-thin using OutputFileMap.json (matching Xcode SWIFT_LTO=YES_THIN)
|
||||
w_src = str(src_dir / 'AsyncWorker.swift')
|
||||
c_src = str(src_dir / 'AsyncCaller.swift')
|
||||
w_obj = obj_dir / 'AsyncWorker.o'
|
||||
c_obj = obj_dir / 'AsyncCaller.o'
|
||||
w_bc = obj_dir / 'AsyncWorker.bc'
|
||||
c_bc = obj_dir / 'AsyncCaller.bc'
|
||||
ofm_path = obj_dir / 'IGM0AsyncPilot-OutputFileMap.json'
|
||||
ofm_path.write_text(json.dumps({
|
||||
'': {'swift-dependencies': str(obj_dir / 'master.swiftdeps')},
|
||||
w_src: {'object': str(w_obj), 'llvm-bc': str(w_bc)},
|
||||
c_src: {'object': str(c_obj), 'llvm-bc': str(c_bc)},
|
||||
}, indent=2), encoding='utf-8')
|
||||
filelist_path = obj_dir / 'IGM0AsyncPilot.LinkFileList'
|
||||
filelist_path.write_text('\n'.join([str(objc_obj), str(w_bc), str(c_bc)]) + '\n', encoding='utf-8')
|
||||
|
||||
p_sw = run([
|
||||
swiftc, '-sdk', sdk, '-target', 'arm64-apple-ios15.0',
|
||||
'-module-name', 'IGM0AsyncPilot',
|
||||
'-O', '-g', '-lto=llvm-thin',
|
||||
'-import-objc-header', str(src_dir / 'ObjCBridge.h'),
|
||||
'-I', str(src_dir),
|
||||
'-output-file-map', str(ofm_path),
|
||||
'-c', w_src, c_src,
|
||||
], env=env)
|
||||
if p_sw.returncode != 0:
|
||||
raise RuntimeError(f'swiftc failed:\n{p_sw.stdout}\n{p_sw.stderr}')
|
||||
|
||||
# Link main executable through real ig_ld_wrapper.py (--ld-path)
|
||||
app_bin = app_dir / 'IGM0AsyncPilot'
|
||||
linkmap_p = output_dir / 'temp' / 'IGM0AsyncPilot-LinkMap.txt'
|
||||
linkmap_p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p_ld = run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
|
||||
f'--ld-path={ld_wrapper}',
|
||||
'-Wl,-ig_stamp,ctl_full__all__off__0__m0_device_seed_1__devstamp1',
|
||||
f'-Wl,-filelist,{filelist_path}',
|
||||
f'-Wl,-map,{linkmap_p}',
|
||||
'-Wl,-rpath,@executable_path/Frameworks',
|
||||
str(fw_bin),
|
||||
'-L', str(Path(swiftc).parents[1] / 'lib/swift/iphoneos'),
|
||||
'-L', str(Path(sdk) / 'usr/lib/swift'),
|
||||
'-framework', 'UIKit', '-framework', 'Foundation', '-lobjc',
|
||||
'-o', str(app_bin),
|
||||
], env=env)
|
||||
if p_ld.returncode != 0:
|
||||
raise RuntimeError(f'ig_ld_wrapper link failed:\n{p_ld.stdout}\n{p_ld.stderr}')
|
||||
|
||||
# Check converted Swift objects LC_BUILD_VERSION
|
||||
swift_machos = sorted((obj_dir / 'ig-swift-macho').glob('*.o'))
|
||||
assert len(swift_machos) == 2, f'Expected 2 converted Swift objects, got {swift_machos}'
|
||||
lc_versions = {m.name: verify_macho_object_platform(m) for m in swift_machos}
|
||||
|
||||
subprocess.run(['xcrun', 'dsymutil', str(app_bin), '-o', str(dsym_dir / 'IGM0AsyncPilot.app.dSYM')], check=True)
|
||||
(app_dir / 'Info.plist').write_bytes(plistlib.dumps({
|
||||
'CFBundleExecutable': 'IGM0AsyncPilot',
|
||||
'CFBundleIdentifier': bundle_id,
|
||||
'CFBundleName': 'IGM0AsyncPilot',
|
||||
'CFBundleDisplayName': 'IGM0AsyncPilot',
|
||||
'CFBundlePackageType': 'APPL',
|
||||
'CFBundleVersion': '1',
|
||||
'CFBundleShortVersionString': '1.0',
|
||||
'MinimumOSVersion': '15.0',
|
||||
'LSRequiresIPhoneOS': True,
|
||||
'UIDeviceFamily': [1, 2],
|
||||
'UILaunchScreen': {},
|
||||
}))
|
||||
shutil.copy2(profile, app_dir / 'embedded.mobileprovision')
|
||||
ent_plist = dict(ent)
|
||||
ent_plist['application-identifier'] = f'{prefix}.{bundle_id}'
|
||||
ent_plist['keychain-access-groups'] = [f'{prefix}.{bundle_id}']
|
||||
(output_dir / 'ent.plist').write_bytes(plistlib.dumps(ent_plist))
|
||||
|
||||
subprocess.run(['codesign', '--force', '--sign', identity, str(fw_dir)], check=True)
|
||||
subprocess.run(['codesign', '--force', '--sign', identity, '--entitlements', str(output_dir / 'ent.plist'), str(app_dir)], check=True)
|
||||
|
||||
# Install and launch on physical device; guarantee uninstall afterwards
|
||||
installed = False
|
||||
try:
|
||||
subprocess.run([
|
||||
'xcrun', 'devicectl', 'device', 'install', 'app',
|
||||
'--device', device, '--timeout', '60', str(app_dir),
|
||||
], check=True)
|
||||
installed = True
|
||||
launch = subprocess.run([
|
||||
'xcrun', 'devicectl', 'device', 'process', 'launch',
|
||||
'--device', device, '--console', '--timeout', '25',
|
||||
'--terminate-existing', bundle_id,
|
||||
], capture_output=True, text=True)
|
||||
console_log = launch.stdout + '\n' + launch.stderr
|
||||
(output_dir / 'device-console.log').write_text(console_log, encoding='utf-8')
|
||||
finally:
|
||||
if installed:
|
||||
subprocess.run([
|
||||
'xcrun', 'devicectl', 'device', 'uninstall', 'app',
|
||||
'--device', device, '--timeout', '60', bundle_id,
|
||||
], check=False)
|
||||
|
||||
cases = {}
|
||||
for m in re.finditer(r'M0_DEV_CASE\s+(\S+)\s+(PASS|FAIL(?:\([^)]*\))?)', console_log):
|
||||
cases[m.group(1)] = m.group(2)
|
||||
|
||||
img_bases = {}
|
||||
for m in re.finditer(r'M0_RUNTIME_IMG\s+([^|\s]+)\|(0x[0-9a-fA-F]+)\|(\S+)', console_log):
|
||||
img_bases[m.group(1)] = {'base': int(m.group(2), 16), 'path': m.group(3)}
|
||||
|
||||
frame_m = re.search(r'M0_RUNTIME_FRAME\s+main=(0x[0-9a-fA-F]+)\s+kit=(0x[0-9a-fA-F]+)', console_log)
|
||||
if not frame_m:
|
||||
raise RuntimeError(f'Missing M0_RUNTIME_FRAME in device console:\n{console_log}')
|
||||
|
||||
main_pc = int(frame_m.group(1), 16)
|
||||
kit_pc = int(frame_m.group(2), 16)
|
||||
main_base = img_bases['/IGM0AsyncPilot']['base']
|
||||
kit_base = img_bases['/IGM0ProbeKit']['base']
|
||||
|
||||
def uuid_of(path):
|
||||
out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True)
|
||||
return out.split()[1]
|
||||
|
||||
main_uid = uuid_of(app_bin)
|
||||
kit_uid = uuid_of(fw_bin)
|
||||
|
||||
# Symbolicate live device addresses in BOTH .ips JSON and .crash text formats!
|
||||
ips_p = output_dir / 'device_live.ips'
|
||||
ips_p.write_text(
|
||||
json.dumps({'app_name': 'IGM0AsyncPilot', 'bug_type': '309'}) + '\n' +
|
||||
json.dumps({
|
||||
'usedImages': [
|
||||
{'base': main_base, 'size': 0x40000, 'uuid': main_uid, 'name': 'IGM0AsyncPilot', 'arch': 'arm64', 'path': img_bases['/IGM0AsyncPilot']['path']},
|
||||
{'base': kit_base, 'size': 0x10000, 'uuid': kit_uid, 'name': 'IGM0ProbeKit', 'arch': 'arm64', 'path': img_bases['/IGM0ProbeKit']['path']},
|
||||
],
|
||||
'threads': [{
|
||||
'triggered': True,
|
||||
'frames': [
|
||||
{'imageIndex': 0, 'imageOffset': main_pc - main_base},
|
||||
{'imageIndex': 1, 'imageOffset': kit_pc - kit_base},
|
||||
],
|
||||
}],
|
||||
}) + '\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
crash_p = output_dir / 'device_live.crash'
|
||||
crash_p.write_text(
|
||||
'Thread 0 Crashed:\n'
|
||||
f'0 IGM0AsyncPilot {hex(main_pc)} {hex(main_base)} + {main_pc - main_base}\n'
|
||||
f'1 IGM0ProbeKit {hex(kit_pc)} {hex(kit_base)} + {kit_pc - kit_base}\n\n'
|
||||
'Binary Images:\n'
|
||||
f' {hex(main_base)} - {hex(main_base + 0x40000)} IGM0AsyncPilot arm64 <{main_uid}> {img_bases["/IGM0AsyncPilot"]["path"]}\n'
|
||||
f' {hex(kit_base)} - {hex(kit_base + 0x10000)} IGM0ProbeKit arm64 <{kit_uid}> {img_bases["/IGM0ProbeKit"]["path"]}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
sym_ips = restore_crash_report.restore_report(ips_p, dsym_dir)
|
||||
sym_crash = restore_crash_report.restore_report(crash_p, dsym_dir)
|
||||
|
||||
audit_file = output_dir / 'temp' / 'ig-route2-audit' / 'ig_obfuscation_audit.json'
|
||||
audit = json.loads(audit_file.read_text(encoding='utf-8'))
|
||||
|
||||
result = {
|
||||
'device': device,
|
||||
'lc_build_version': lc_versions,
|
||||
'cases': cases,
|
||||
'obf_audit': audit,
|
||||
'ips_restored': sym_ips,
|
||||
'crash_restored': sym_crash,
|
||||
}
|
||||
(output_dir / 'device-m0-verification.json').write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8'
|
||||
)
|
||||
|
||||
expected_cases = ('async_normal_resume', 'async_throw_catch', 'async_cancellation', 'objc_concurrent_str_flatten')
|
||||
for cname in expected_cases:
|
||||
if cases.get(cname) != 'PASS':
|
||||
raise AssertionError(f'Device case {cname} did not PASS: {cases}')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--device', default=DEFAULT_DEVICE)
|
||||
p.add_argument('--profile', type=Path, default=DEFAULT_PROFILE)
|
||||
p.add_argument('--identity', default=DEFAULT_IDENTITY)
|
||||
p.add_argument('--bundle-id', default=DEFAULT_BUNDLE_ID)
|
||||
p.add_argument('--output', type=Path, default=Path('/tmp/ig-m0-async-device'))
|
||||
a = p.parse_args()
|
||||
res = verify_and_run(a.device, a.profile, a.identity, a.bundle_id, a.output)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user