#!/usr/bin/env python3 """Symbolicate modern JSON (.ips) and classic text (.crash) Apple crash reports with UUID enforcement.""" import argparse import json from pathlib import Path import re import subprocess import sys FRAME_LINE_RE = re.compile( r'^(\d+)\s+(\S+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)(?:\s*\+\s*(\d+))?(.*)$' ) BIN_IMAGE_RE = re.compile( r'^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+(\S+)\s+(\S+)\s+<([0-9a-fA-F-]+)>\s+(.+)$' ) def norm_uuid(u): return str(u).replace('-', '').upper() def index_dsyms(dsym_root): """Map normalized UUID -> {'arch': ..., 'dwarf': Path, 'dsym': Path}.""" mapping = {} root = Path(dsym_root) candidates = [] if root.is_dir() and root.suffix == '.dSYM': candidates.append(root) elif root.is_dir(): candidates.extend(sorted(root.glob('*.dSYM'))) else: raise FileNotFoundError(f'dSYM path not found: {root}') for dsym in candidates: dwarf_dir = dsym / 'Contents' / 'Resources' / 'DWARF' if not dwarf_dir.is_dir(): continue out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(dsym)], text=True) for line in out.splitlines(): m = re.match(r'^UUID:\s*([0-9A-Fa-f-]+)\s+\(([^)]+)\)\s+(.+)$', line.strip()) if m: uid = norm_uuid(m.group(1)) arch = m.group(2) dwarf_path = Path(m.group(3).strip()) mapping[uid] = {'arch': arch, 'dwarf': dwarf_path, 'dsym': dsym} return mapping def _unwrap_v2_mappings(raw) -> dict: if not isinstance(raw, dict): return {} if isinstance(raw.get('mappings'), dict) and ( 'schema_version' in raw or raw.get('kind') in ('symbol_map', 'method_map') ): return raw['mappings'] return raw def load_reverse_maps(symbol_map_path=None, method_map_path=None): cls_rev = {} sel_rev = {} if symbol_map_path and Path(symbol_map_path).is_file(): raw = _unwrap_v2_mappings(json.loads(Path(symbol_map_path).read_text(encoding='utf-8'))) for orig, obf in raw.items(): if isinstance(obf, str): cls_rev[obf] = orig elif isinstance(obf, dict) and isinstance(obf.get('obfuscated'), str): cls_rev[obf['obfuscated']] = orig if method_map_path and Path(method_map_path).is_file(): raw = _unwrap_v2_mappings(json.loads(Path(method_map_path).read_text(encoding='utf-8'))) for orig, obf in raw.items(): if isinstance(obf, str): sel_rev[obf] = orig if ':' in orig: orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig) for idx, orig_part in enumerate(orig_parts, start=1): sel_rev.setdefault(f'{obf}_{idx}:', orig_part) if orig_parts: sel_rev.setdefault(f'{obf}_1', orig_parts[0][:-1]) elif isinstance(obf, list): for item in obf: if isinstance(item, str): sel_rev[item] = orig elif isinstance(obf, dict): full_obf = obf.get('obfuscated') tok = obf.get('token') parts = obf.get('parts') if isinstance(full_obf, str) and full_obf: sel_rev[full_obf] = orig if obf.get('kind') == 'objc_selector' and isinstance(parts, list) and ':' in orig: orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig) if len(orig_parts) == len(parts): for obf_part, orig_part in zip(parts, orig_parts): norm_obf = obf_part if obf_part.endswith(':') else f'{obf_part}:' sel_rev.setdefault(norm_obf, orig_part) if isinstance(tok, str) and tok and orig_parts: sel_rev.setdefault(tok, orig_parts[0][:-1]) elif isinstance(tok, str) and tok: sel_rev[tok] = orig return cls_rev, sel_rev def deobfuscate_symbol_text(text, cls_rev, sel_rev): out = text combined = {} combined.update(cls_rev) combined.update(sel_rev) for obf, orig in sorted(combined.items(), key=lambda kv: -len(kv[0])): if not obf or obf not in out: continue if ':' in obf: out = out.replace(obf, orig) else: out = re.sub(r'(? 1 else header return header, body def symbolicate_ips(text, dsym_index, cls_rev, sel_rev): _, body = parse_ips(text) used_images = body.get('usedImages') or [] results = [] for t_idx, thread in enumerate(body.get('threads') or []): if not thread.get('triggered') and len(body.get('threads') or []) > 1 and t_idx != 0: continue frames_out = [] for f_idx, frame in enumerate(thread.get('frames') or []): img_idx = frame.get('imageIndex') img_off = frame.get('imageOffset') if img_idx is None or img_off is None or img_idx >= len(used_images): continue img = used_images[img_idx] uid = norm_uuid(img.get('uuid', '')) base = img.get('base', 0) name = img.get('name', img.get('path', f'img_{img_idx}')) addr_hex = hex(base + img_off) base_hex = hex(base) dsym_entry = dsym_index.get(uid) if not dsym_entry: # Require UUID match for app/embedded bundle binaries img_path = img.get('path', '') if '.app/' in img_path: raise RuntimeError( f'UUID mismatch or missing dSYM for bundle image {name} (uuid={img.get("uuid")})' ) frames_out.append({ 'frame_index': f_idx, 'image': name, 'uuid': img.get('uuid'), 'address': addr_hex, 'status': 'system_or_unindexed', 'inline_frames': [], }) continue raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img.get('arch', 'arm64')) restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms] frames_out.append({ 'frame_index': f_idx, 'image': name, 'uuid': img.get('uuid'), 'dsym': str(dsym_entry['dsym']), 'load_address': base_hex, 'address': addr_hex, 'status': 'symbolicated', 'raw_atos': raw_syms, 'restored_frames': restored, }) results.append({'thread_index': t_idx, 'triggered': bool(thread.get('triggered')), 'frames': frames_out}) return {'format': 'ips_json', 'threads': results} def symbolicate_crash(text, dsym_index, cls_rev, sel_rev): images_by_name = {} in_bin_images = False for line in text.splitlines(): if line.strip().startswith('Binary Images:'): in_bin_images = True continue if in_bin_images: m = BIN_IMAGE_RE.match(line) if m: start_hex, _, name, arch, uid_str, path = m.groups() images_by_name[name] = { 'base_hex': start_hex, 'name': name, 'arch': arch, 'uuid': uid_str, 'uuid_norm': norm_uuid(uid_str), 'path': path.strip(), } frames_out = [] for line in text.splitlines(): m = FRAME_LINE_RE.match(line.strip()) if not m: continue f_idx, img_name, addr_hex, base_or_sym, _, _ = m.groups() img = images_by_name.get(img_name) if not img: continue uid = img['uuid_norm'] base_hex = img['base_hex'] dsym_entry = dsym_index.get(uid) if not dsym_entry: if '.app/' in img['path']: raise RuntimeError( f'UUID mismatch or missing dSYM for bundle image {img_name} (uuid={img["uuid"]})' ) frames_out.append({ 'frame_index': int(f_idx), 'image': img_name, 'uuid': img['uuid'], 'address': addr_hex, 'status': 'system_or_unindexed', 'restored_frames': [], }) continue raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img['arch']) restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms] frames_out.append({ 'frame_index': int(f_idx), 'image': img_name, 'uuid': img['uuid'], 'dsym': str(dsym_entry['dsym']), 'load_address': base_hex, 'address': addr_hex, 'status': 'symbolicated', 'raw_atos': raw_syms, 'restored_frames': restored, }) return {'format': 'crash_text', 'images_parsed': len(images_by_name), 'frames': frames_out} def restore_report(report_path, dsym_dir, symbol_map=None, method_map=None): text = Path(report_path).read_text(encoding='utf-8', errors='replace') dsym_index = index_dsyms(dsym_dir) cls_rev, sel_rev = load_reverse_maps(symbol_map, method_map) first_nonempty = next((l.strip() for l in text.splitlines() if l.strip()), '') if first_nonempty.startswith('{'): return symbolicate_ips(text, dsym_index, cls_rev, sel_rev) return symbolicate_crash(text, dsym_index, cls_rev, sel_rev) def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--report', required=True, type=Path) p.add_argument('--dsym-dir', required=True, type=Path) p.add_argument('--symbol-map', type=Path) p.add_argument('--method-map', type=Path) p.add_argument('--out', type=Path) args = p.parse_args() res = restore_report(args.report, args.dsym_dir, args.symbol_map, args.method_map) text = json.dumps(res, ensure_ascii=False, indent=2) + '\n' if args.out: args.out.write_text(text, encoding='utf-8') else: sys.stdout.write(text) return 0 if __name__ == '__main__': raise SystemExit(main())