From 3b436e2f7d6a2f3f8d7f133a16ab1f4b26d383bf Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Fri, 28 Nov 2025 12:27:20 -0800 Subject: [PATCH] Add scripts folder and symbolication scripts. --- scripts/README_SYMBOLICATION.md | 247 ++++++++++++++++++++++++ scripts/SYMBOLICATION_README.md | 190 ------------------- scripts/symbolicate_all_crashes.sh | 10 +- scripts/symbolicate_crash.sh | 41 ++-- scripts/symbolicate_crash_simple.sh | 11 +- scripts/symbolicate_json_crash.sh | 285 ++++++++++++++++++++++++++++ 6 files changed, 578 insertions(+), 206 deletions(-) create mode 100644 scripts/README_SYMBOLICATION.md delete mode 100644 scripts/SYMBOLICATION_README.md create mode 100755 scripts/symbolicate_json_crash.sh diff --git a/scripts/README_SYMBOLICATION.md b/scripts/README_SYMBOLICATION.md new file mode 100644 index 000000000..7a43ffca0 --- /dev/null +++ b/scripts/README_SYMBOLICATION.md @@ -0,0 +1,247 @@ +# Crash Log Symbolication Scripts + +This directory contains scripts for symbolicating macOS crash logs. Different scripts are needed for different crash log formats. + +## Quick Start + +```bash +# Traditional text format crash logs +./symbolicate_crash_simple.sh MacCrash.log + +# JSON format crash logs (macOS 15+) +./symbolicate_json_crash.sh crash.log + +# Batch process all crashes in a directory +./symbolicate_all_crashes.sh /path/to/crash/logs +``` + +## Script Overview + +### Traditional Text Format Crash Logs + +For standard macOS crash logs (plain text format with "Process:", "Binary Images:", etc.): + +- **`symbolicate_crash.sh`** - Full-featured symbolication script + - Automatically finds matching .xcarchive by UUID + - Symbolicates all frames using `atos` + - Supports both macOS and iOS crash logs + - Detailed logging with `DEBUG=1` option + +- **`symbolicate_crash_simple.sh`** - Uses Apple's `symbolicatecrash` tool (recommended) + - Simpler approach using Apple's built-in tool + - Requires Xcode to be installed + +- **`symbolicate_all_crashes.sh`** - Batch process multiple crash logs + - Automatically processes all .crash files in a directory + - Uses `symbolicate_crash.sh` internally + +### JSON Format Crash Logs (macOS 15+) + +For newer JSON-format crash logs (as seen in macOS 15 and later): + +- **`symbolicate_json_crash.sh`** - Handles JSON crash log format + - Parses JSON crash data structure + - Extracts and symbolicates thread backtraces + - Reformats output into readable text format + - Numbers frames starting from 0 (like traditional format) + - **Requires `jq`** (install with: `brew install jq`) + +## Identifying Crash Log Format + +### Traditional Text Format +``` +Process: NetNewsWire [12345] +Path: /Applications/NetNewsWire.app/Contents/MacOS/NetNewsWire +Identifier: com.ranchero.NetNewsWire-Evergreen +Version: 6.2 (6200) +Code Type: ARM-64 + +Binary Images: +0x100000000 - 0x100ffffff +NetNewsWire arm64 /path/to/app +``` + +### JSON Format (macOS 15+) +```json +{"app_name":"NetNewsWire","timestamp":"2025-11-17 06:48:17.00 -0800",...} +{ + "uptime" : 2300000, + "procRole" : "Foreground", + "threads" : [...], + "usedImages" : [...] +} +``` + +**Key difference**: JSON format has two JSON objects - a header on line 1, and the main crash data starting on line 2. + +## Usage Examples + +### Symbolicate a Traditional Crash Log +```bash +# Auto-find archive by UUID +./symbolicate_crash_simple.sh MacCrash.log + +# Or use advanced script with debug output +DEBUG=1 ./symbolicate_crash.sh MacCrash.log + +# Specify archive path manually +./symbolicate_crash.sh MacCrash.log ~/Library/Developer/Xcode/Archives/2024-11-28/MyApp.xcarchive +``` + +### Symbolicate a JSON Crash Log +```bash +# Auto-find archive by UUID +./symbolicate_json_crash.sh crash.log + +# Specify archive path manually +./symbolicate_json_crash.sh crash.log ~/Library/Developer/Xcode/Archives/2024-11-28/MyApp.xcarchive +``` + +### Symbolicate All Crashes in a Directory +```bash +# Process all .crash files in current directory +./symbolicate_all_crashes.sh + +# Process crashes in specific directory +./symbolicate_all_crashes.sh /path/to/crash/directory +``` + +### Advanced Usage +```bash +# Specify custom dSYM directory +./symbolicate_crash_simple.sh MacCrash.log ~/path/to/dSYMs + +# Enable debug output +DEBUG=1 ./symbolicate_crash.sh MacCrash.log + +# Process specific pattern +find . -name "*production*.log" -exec ./symbolicate_crash_simple.sh {} \; +``` + +## What Gets Symbolicated + +The scripts symbolicate your app's code: +- Your main app binary +- Your frameworks and libraries +- App extensions +- Embedded frameworks + +**Example:** +``` +Before: 0 NetNewsWire 0x00000001059feea0 0x1058d0000 + 1240736 +After: 0 NetNewsWire 0x00000001059feea0 closure #1 in ReaderAPICaller.retrieveEntries(articleIDs:completion:) (ReaderAPICaller.swift:527) +``` + +## Understanding the Output + +### Symbolicated Frame: +``` +0 Account 0x1059feea0 closure #1 in ReaderAPICaller.retrieveEntries(articleIDs:completion:) (ReaderAPICaller.swift:527) +``` +- **Frame Number**: `0` (top of stack) +- **Function**: `closure #1 in ReaderAPICaller.retrieveEntries` +- **File**: `ReaderAPICaller.swift` +- **Line**: `527` + +## Output Files + +All scripts create a `*_symbolicated.log` or `*_symbolicated.txt` file with: +- App and system information +- Exception details +- Symbolicated stack traces for all threads (with frame numbers) +- Binary image information + +The output maintains Apple's standard crash log format and can be: +- Opened in Console.app +- Shared with Apple via Feedback Assistant +- Analyzed with other crash analysis tools +- Searched for specific functions/files + +## Requirements + +### All Scripts +- macOS with Xcode installed +- Xcode command line tools +- Matching .xcarchive with dSYMs in `~/Library/Developer/Xcode/Archives` +- The crash log must match the architecture and UUID of a built archive + +### JSON Crash Log Script Only +- **`jq`** command-line JSON processor + - Install with: `brew install jq` + - Used to parse JSON crash log structure + +## Troubleshooting + +### "No matching archive found" +- Ensure you have an Xcode archive for this build +- Check that archive contains dSYM files +- Verify archive matches crash log's architecture (arm64/x86_64) +- Try specifying the archive path manually + +### "Could not find dSYMs" +- Archive may not have been created with debug symbols +- Check Build Settings → Debug Information Format = "DWARF with dSYM File" + +### "jq is required" (JSON script only) +```bash +brew install jq +``` + +### Partial or Missing Symbols +- Verify the dSYM files exist in the archive's `dSYMs` directory +- Check that the architecture matches (arm64 vs x86_64) +- Ensure the crash log matches the exact build that was archived + +### Wrong archive selected +- Script matches by UUID (most accurate) +- Falls back to name matching if UUID fails +- Specify archive manually to override + +### Script Hangs or is Very Slow +- The JSON script may take a while for crashes with many threads +- Consider using the traditional format scripts if possible + +## Technical Details + +### How It Works + +1. **Extract App Info** - Reads process name, architecture, platform from crash log +2. **Extract UUIDs** - Gets unique identifiers for each binary +3. **Find Archive** - Searches Xcode archives for matching UUID +4. **Symbolicate** - Uses `atos` or Apple's `symbolicatecrash` tool +5. **Add Symbols** - Replaces addresses with function names, file names, and line numbers + +### Files Created + +- `*_symbolicated.log` or `*_symbolicated.txt` - Output file with symbols +- Original crash log is never modified + +## Best Practices + +1. **Always archive with dSYMs** - Enable "Debug Information Format" in build settings +2. **Keep all archives** - You need the exact build's archive to symbolicate +3. **Save archives by version** - Organize by version number and build number +4. **Test symbolication** - Verify after each release that you can symbolicate +5. **Archive before distribution** - Create archive before exporting for distribution + +## Limitations + +- Cannot symbolicate crashes from App Store builds without matching archive +- Requires Xcode installation +- macOS only (for macOS crash logs) +- JSON crash logs require `jq` to be installed +- Traditional scripts will not work on JSON format logs and vice versa + +## Notes + +- The JSON crash log format appeared in macOS 15 (Sequoia) and is structurally different from traditional crash logs +- Archives must be built with debug symbols (dSYMs) enabled +- The scripts search for archives from newest to oldest by default +- Frame numbers start from 0 (top of stack) to match Apple's format +- Scripts automatically skip files with "symbolicated" in the filename to avoid re-symbolicating +- "Translated Report" format crash logs (with both a translated section and full report) may not symbolicate app code correctly - use the JSON format script instead if available + +## Additional Resources + +- [Apple Technical Note TN2151 - Understanding Crash Reports](https://developer.apple.com/documentation/xcode/diagnosing-issues-using-crash-reports-and-device-logs) +- [WWDC Videos on Crash Analysis](https://developer.apple.com/videos/) +- Xcode Help → "Analyzing Crash Reports" diff --git a/scripts/SYMBOLICATION_README.md b/scripts/SYMBOLICATION_README.md deleted file mode 100644 index ad3a653cd..000000000 --- a/scripts/SYMBOLICATION_README.md +++ /dev/null @@ -1,190 +0,0 @@ -# Crash Log Symbolication Scripts - -## Overview - -Three scripts for symbolicating macOS crash logs: - -1. **symbolicate_all_crashes.sh** - Batch process multiple crash logs -2. **symbolicate_crash_simple.sh** - Symbolicate single crash log (recommended) -3. **symbolicate_crash.sh** - Advanced single file with detailed logging - -## Quick Start - -```bash -# Symbolicate all crash logs in current directory -./symbolicate_all_crashes.sh - -# Symbolicate a single crash log -./symbolicate_crash_simple.sh MacCrash.log - -# Symbolicate crashes in specific directory -./symbolicate_all_crashes.sh /path/to/crash/logs -``` - -## What Gets Symbolicated - -### ✅ Your App's Code (Always) -- Your main app binary -- Your frameworks and libraries -- App extensions -- Embedded frameworks - -**Example:** -``` -Before: 0x00000001059feea0 0x1058d0000 + 1240736 -After: closure #1 in ReaderAPICaller.retrieveEntries(articleIDs:completion:) (ReaderAPICaller.swift:527) -``` - -### ⚠️ System Frameworks (Limited) -- AppKit, CoreFoundation, UIKit, etc. -- **May NOT symbolicate** on newer macOS versions -- Symbols often stripped from release builds -- Requires OS-specific symbols from Apple - -**Why System Symbols Are Limited:** - -1. **Stripped Binaries** - Release builds of macOS don't include debug symbols -2. **Dyld Shared Cache** - System frameworks are in a shared cache, not individual files -3. **OS Version Matching** - Requires exact OS build symbols -4. **Availability** - Apple doesn't always provide public symbol downloads for all macOS versions - -## System Symbol Options - -### Option 1: Use Current Scripts (Best Effort) -The scripts attempt to find system symbols by searching: -- `/System/Library/Frameworks` -- `/System/Library/PrivateFrameworks` -- `/usr/lib` - -This works for some frameworks but not all. - -### Option 2: Download Symbols from Apple (If Available) - -For older macOS versions, you may be able to download symbols: - -1. **Xcode Downloads** (For older OS versions): - - Xcode → Settings → Platforms - - Download symbols for specific OS versions - -2. **Manual Symbol Download**: - - Some macOS versions have public symbol packages - - Not available for all versions/builds - -### Option 3: Run on Matching OS Version - -Symbolicate on a Mac running the **same OS version** as the crash: -- Symbols may be available locally -- Best chance for system framework symbolication - -### Option 4: Focus on Your Code - -Often, system framework symbols aren't needed: -- **Your code symbols** are what you can fix -- System framework stack frames show the call path -- Offsets can still indicate which system API was called - -## Understanding the Output - -### Fully Symbolicated Frame: -``` -0 Account 0x1059feea0 closure #1 in ReaderAPICaller.retrieveEntries(articleIDs:completion:) + 1240736 (ReaderAPICaller.swift:527) -``` -- **Function**: `closure #1 in ReaderAPICaller.retrieveEntries` -- **File**: `ReaderAPICaller.swift` -- **Line**: `527` - -### Partially Symbolicated Frame (System): -``` -12 CoreFoundation 0x18464e980 0x1845c5000 + 563584 -``` -- Shows framework name and offset -- No function/file info (symbols not available) -- Still useful for understanding call stack - -## Technical Details - -### How It Works - -1. **Extract App Info** - Reads process name, architecture, platform from crash log -2. **Extract UUIDs** - Gets unique identifiers for each binary -3. **Find Archive** - Searches Xcode archives for matching UUID -4. **Symbolicate** - Uses Apple's `symbolicatecrash` tool -5. **Add Symbols** - Replaces addresses with function names - -### Requirements - -- macOS with Xcode installed -- Xcode archives with dSYM files -- Crash log must be from your own build - -### Files Created - -- `*_symbolicated.log` - Output file with symbols -- Original crash log is never modified - -## Troubleshooting - -### "No matching archive found" -- Ensure you have an Xcode archive for this build -- Check that archive contains dSYM files -- Verify archive matches crash log's architecture (arm64/x86_64) - -### "Could not find dSYMs" -- Archive may not have been created with debug symbols -- Check Build Settings → Debug Information Format = "DWARF with dSYM File" - -### System frameworks not symbolicated -- **This is normal** for many macOS versions -- See "System Symbol Options" above -- Focus on your own code's symbols - -### Wrong archive selected -- Script matches by UUID (most accurate) -- Falls back to name matching if UUID fails -- Specify archive manually: `./symbolicate_crash_simple.sh crash.log /path/to/archive/dSYMs` - -## Advanced Usage - -### Specify Custom dSYM Directory -```bash -./symbolicate_crash_simple.sh MacCrash.log ~/path/to/dSYMs -``` - -### Enable Debug Output -```bash -DEBUG=1 ./symbolicate_crash.sh MacCrash.log -``` - -### Process Specific Pattern -```bash -# Only files matching pattern -find . -name "*production_crash*.log" -exec ./symbolicate_crash_simple.sh {} \; -``` - -## Best Practices - -1. **Always archive with dSYMs** - Enable "Debug Information Format" in build settings -2. **Keep all archives** - You need the exact build's archive to symbolicate -3. **Save archives by version** - Organize by version number and build number -4. **Test symbolication** - Verify after each release that you can symbolicate - -## Limitations - -- Cannot symbolicate crashes from App Store builds without matching archive -- System framework symbolication depends on OS version -- Requires Xcode installation -- macOS only (for macOS crash logs) - -## Output Format - -Symbolicated logs maintain Apple's standard crash log format and can be: -- Opened in Console.app -- Shared with Apple via Feedback Assistant -- Analyzed with other crash analysis tools -- Searched for specific functions/files - -## Additional Resources - -- [Apple Technical Note TN2151 - Understanding Crash Reports](https://developer.apple.com/documentation/xcode/diagnosing-issues-using-crash-reports-and-device-logs) -- [WWDC Videos on Crash Analysis](https://developer.apple.com/videos/) -- Xcode Help → "Analyzing Crash Reports" diff --git a/scripts/symbolicate_all_crashes.sh b/scripts/symbolicate_all_crashes.sh index e369b216d..cfb7dd94b 100755 --- a/scripts/symbolicate_all_crashes.sh +++ b/scripts/symbolicate_all_crashes.sh @@ -53,9 +53,13 @@ print_section "Crash Log Batch Symbolication" print_info "Directory: $CRASH_DIR" print_info "Pattern: *crash*.log (case-insensitive)" -# Find all crash log files (case-insensitive) +# Find all crash log files (case-insensitive), excluding already symbolicated files CRASH_LOGS=() while IFS= read -r -d '' file; do + # Skip files with "symbolicated" in the name + if [[ "$file" == *"symbolicated"* ]]; then + continue + fi CRASH_LOGS+=("$file") done < <(find "$CRASH_DIR" -maxdepth 1 -type f -iname "*crash*.log" -print0 2>/dev/null) @@ -113,8 +117,8 @@ symbolicate_single() { fi print_info "Platform: $PLATFORM" - # Extract UUID - APP_UUID=$(sed -n '/^Binary Images:/,$p' "$crash_log" | grep "0x" | grep "+$APP_NAME " | head -n 1 | grep -o '<[a-f0-9]*>' | tr -d '<>' || echo "") + # Extract UUID - try both formats (+AppName and AppName.app) + APP_UUID=$(sed -n '/^Binary Images:/,$p' "$crash_log" | grep "0x" | grep -E "(\+$APP_NAME |$APP_NAME\.app)" | head -n 1 | grep -o '<[a-f0-9-]*>' | tr -d '<>' || echo "") # Find matching archive DSYM_DIR="" diff --git a/scripts/symbolicate_crash.sh b/scripts/symbolicate_crash.sh index 180972dd0..96e59a15c 100755 --- a/scripts/symbolicate_crash.sh +++ b/scripts/symbolicate_crash.sh @@ -58,6 +58,13 @@ if [ ! -f "$CRASH_LOG" ]; then exit 1 fi +# Skip if already symbolicated +if [[ "$CRASH_LOG" == *"symbolicated"* ]]; then + print_warning "File appears to already be symbolicated (contains 'symbolicated' in name): $CRASH_LOG" + print_info "Skipping to avoid re-symbolicating" + exit 0 +fi + print_info "Crash log: $CRASH_LOG" # Extract app info from crash log @@ -98,18 +105,26 @@ temp_uuids=$(mktemp) # Extract lines from "Binary Images:" section sed -n '/^Binary Images:/,$p' "$CRASH_LOG" | grep "0x" | while read line; do # Extract binary name and UUID - # Format: 0xaddress - 0xaddress [+]BinaryName arch /path - # Fields: 1=start_addr 2=- 3=end_addr 4=[+]binary 5=arch 6= 7+=path - if [[ "$line" =~ \<([a-f0-9]+)\> ]]; then + # Two formats supported: + # Old: 0xaddress - 0xaddress +BinaryName arch /path + # New: 0xaddress - 0xaddress com.bundle.id (version) /path + if [[ "$line" =~ \<([a-f0-9-]+)\> ]]; then uuid="${BASH_REMATCH[1]}" - # Extract field 4 which is the binary name - binary=$(echo "$line" | awk '{ - # Field 4 contains the binary name (possibly with + prefix) - bin = $4 - # Remove leading + if present - gsub(/^\+/, "", bin) - print bin - }') + + # Try to extract binary name from path (last component) + if [[ "$line" =~ /([^/]+)$ ]]; then + binary="${BASH_REMATCH[1]}" + else + # Fallback: try field 4 (old format with + prefix) + binary=$(echo "$line" | awk '{ + bin = $4 + gsub(/^\+/, "", bin) + print bin + }') + fi + + # Clean up UUID (remove hyphens) + uuid=$(echo "$uuid" | tr -d '-') echo "$binary:$uuid" >> "$temp_uuids" fi done @@ -142,7 +157,11 @@ else fi # Get the main app UUID to search for + # First try from the extracted UUIDs, then try direct extraction from Binary Images APP_UUID=$(grep "^$APP_NAME:" /tmp/crash_uuids.txt | cut -d: -f2 | head -n 1) + if [ -z "$APP_UUID" ]; then + APP_UUID=$(sed -n '/^Binary Images:/,$p' "$CRASH_LOG" | grep "0x" | grep -E "(\+$APP_NAME |$APP_NAME\.app)" | head -n 1 | grep -o '<[a-f0-9-]*>' | tr -d '<>-' | tr '[:upper:]' '[:lower:]' || echo "") + fi if [ -z "$APP_UUID" ]; then print_warning "Could not find UUID for $APP_NAME in crash log" diff --git a/scripts/symbolicate_crash_simple.sh b/scripts/symbolicate_crash_simple.sh index 003a15eb6..6e6702331 100755 --- a/scripts/symbolicate_crash_simple.sh +++ b/scripts/symbolicate_crash_simple.sh @@ -45,6 +45,13 @@ if [ ! -f "$CRASH_LOG" ]; then exit 1 fi +# Skip if already symbolicated +if [[ "$CRASH_LOG" == *"symbolicated"* ]]; then + print_warning "File appears to already be symbolicated (contains 'symbolicated' in name): $CRASH_LOG" + print_info "Skipping to avoid re-symbolicating" + exit 0 +fi + # Find symbolicatecrash SYMBOLICATE_CRASH=$(find /Applications/Xcode.app -name "symbolicatecrash" 2>/dev/null | head -n 1) @@ -77,8 +84,8 @@ if [ -z "$DSYM_DIR" ]; then print_info "Platform: iOS" fi - # Extract UUID - APP_UUID=$(sed -n '/^Binary Images:/,$p' "$CRASH_LOG" | grep "0x" | grep "+$APP_NAME " | head -n 1 | grep -o '<[a-f0-9]*>' | tr -d '<>' || echo "") + # Extract UUID - try both formats (+AppName and AppName.app) + APP_UUID=$(sed -n '/^Binary Images:/,$p' "$CRASH_LOG" | grep "0x" | grep -E "(\+$APP_NAME |$APP_NAME\.app)" | head -n 1 | grep -o '<[a-f0-9-]*>' | tr -d '<>' || echo "") if [ -n "$APP_UUID" ]; then print_info "App UUID: $APP_UUID" diff --git a/scripts/symbolicate_json_crash.sh b/scripts/symbolicate_json_crash.sh new file mode 100755 index 000000000..17473e8e2 --- /dev/null +++ b/scripts/symbolicate_json_crash.sh @@ -0,0 +1,285 @@ +#!/bin/bash + +# symbolicate_json_crash.sh - Symbolicate JSON-format macOS crash logs +# Usage: ./symbolicate_json_crash.sh [archive_path] +# +# This script handles the newer JSON crash report format (as seen in macOS 15+). +# Unlike traditional text-based crash logs, JSON crash logs have: +# - A header JSON object on line 1 +# - The main crash data JSON on line 2+ +# - Binary images in a usedImages array +# - Thread frames as structured objects +# +# Requirements: +# - jq (install with: brew install jq) +# - Xcode with matching dSYMs in ~/Library/Developer/Xcode/Archives + +set -e + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +print_info() { + echo -e "${GREEN}[INFO]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +# Check if jq is available +if ! command -v jq &> /dev/null; then + print_error "jq is required. Install with: brew install jq" + exit 1 +fi + +if [ $# -lt 1 ]; then + echo "Usage: $0 [archive_path]" + exit 1 +fi + +CRASH_LOG="$1" +SPECIFIC_ARCHIVE="$2" + +if [ ! -f "$CRASH_LOG" ]; then + print_error "Crash log not found: $CRASH_LOG" + exit 1 +fi + +# Skip if already symbolicated +if [[ "$CRASH_LOG" == *"symbolicated"* ]]; then + print_warning "File appears to already be symbolicated (contains 'symbolicated' in name): $CRASH_LOG" + print_info "Skipping to avoid re-symbolicating" + exit 0 +fi + +print_info "JSON crash log: $CRASH_LOG" + +# Extract header +HEADER_JSON=$(head -n 1 "$CRASH_LOG") +APP_NAME=$(echo "$HEADER_JSON" | jq -r '.app_name // empty') +APP_VERSION=$(echo "$HEADER_JSON" | jq -r '.app_version // empty') +BUILD_VERSION=$(echo "$HEADER_JSON" | jq -r '.build_version // empty') +BUNDLE_ID=$(echo "$HEADER_JSON" | jq -r '.bundleID // empty') +SLICE_UUID=$(echo "$HEADER_JSON" | jq -r '.slice_uuid // empty' | tr -d '-') + +if [ -z "$APP_NAME" ]; then + print_error "Could not parse app name" + exit 1 +fi + +print_info "App: $APP_NAME ($BUNDLE_ID)" +print_info "Version: $APP_VERSION ($BUILD_VERSION)" +print_info "UUID: $SLICE_UUID" + +# Save crash JSON to temp file +CRASH_JSON=$(mktemp) +tail -n +2 "$CRASH_LOG" > "$CRASH_JSON" + +CPU_TYPE=$(jq -r '.cpuType // "ARM-64"' < "$CRASH_JSON") +ARCH=$([ "$CPU_TYPE" == "ARM-64" ] && echo "arm64" || echo "x86_64") + +print_info "Architecture: $CPU_TYPE ($ARCH)" + +# Find archive +ARCHIVE_PATH="" + +if [ -n "$SPECIFIC_ARCHIVE" ]; then + ARCHIVE_PATH="$SPECIFIC_ARCHIVE" + print_info "Using specified archive: $(basename "$ARCHIVE_PATH")" +else + ARCHIVE_BASE="$HOME/Library/Developer/Xcode/Archives" + + if [ -n "$SLICE_UUID" ]; then + print_info "Searching for archive with UUID: $SLICE_UUID" + + while IFS= read -r archive; do + app_dsym=$(find "$archive/dSYMs" -name "$APP_NAME.app.dSYM" -type d 2>/dev/null | head -n 1) + if [ -n "$app_dsym" ]; then + dwarf_file=$(find "$app_dsym" -type f -path "*/DWARF/$APP_NAME" 2>/dev/null | head -n 1) + if [ -f "$dwarf_file" ]; then + archive_uuid=$(dwarfdump --uuid "$dwarf_file" 2>/dev/null | grep "$ARCH" | awk '{print $2}' | tr -d '-' | tr '[:upper:]' '[:lower:]') + if [ "$archive_uuid" == "$SLICE_UUID" ]; then + ARCHIVE_PATH="$archive" + print_info "Found archive: $(basename "$archive")" + break + fi + fi + fi + done < <(find "$ARCHIVE_BASE" -name "*.xcarchive" -type d 2>/dev/null | sort -r) + fi + + if [ -z "$ARCHIVE_PATH" ]; then + print_error "No matching archive found" + exit 1 + fi +fi + +DSYMS_DIR="$ARCHIVE_PATH/dSYMs" +if [ ! -d "$DSYMS_DIR" ]; then + print_error "dSYMs directory not found: $DSYMS_DIR" + exit 1 +fi + +print_info "dSYMs: $(basename "$ARCHIVE_PATH")/dSYMs" + +# Build dSYM cache +DSYM_CACHE=$(mktemp) + +find "$DSYMS_DIR" -name "*.dSYM" -type d 2>/dev/null | while IFS= read -r dsym; do + base_name=$(basename "$dsym" .dSYM) + base_name=$(basename "$base_name" .app) + base_name=$(basename "$base_name" .appex) + base_name=$(basename "$base_name" .framework) + + binary_path=$(find "$dsym" -type f -path "*/DWARF/$base_name" 2>/dev/null | head -n 1) + if [ -n "$binary_path" ]; then + echo "$base_name|$binary_path" >> "$DSYM_CACHE" + fi +done + +print_info "Found $(wc -l < "$DSYM_CACHE" | tr -d ' ') dSYMs" + +# Create output file +OUTPUT_FILE="${CRASH_LOG%.log}_symbolicated.txt" + +print_info "Generating symbolicated report..." + +{ + echo "========================================" + echo "Symbolicated Crash Report" + echo "========================================" + echo "" + echo "Process: $APP_NAME" + echo "Bundle ID: $BUNDLE_ID" + echo "Version: $APP_VERSION ($BUILD_VERSION)" + echo "Architecture: $CPU_TYPE" + echo "Crash Time: $(jq -r '.captureTime // "Unknown"' < "$CRASH_JSON")" + echo "OS Version: $(jq -r '.osVersion.train // "Unknown"' < "$CRASH_JSON") ($(jq -r '.osVersion.build // "Unknown"' < "$CRASH_JSON"))" + echo "" + echo "Exception Information:" + echo "Type: $(jq -r '.exception.type // "Unknown"' < "$CRASH_JSON")" + echo "Signal: $(jq -r '.exception.signal // "Unknown"' < "$CRASH_JSON")" + echo "Codes: $(jq -r '.exception.codes // "Unknown"' < "$CRASH_JSON")" + + asi=$(jq -r '.asi // empty | to_entries[] | "\(.key): \(.value[])"' < "$CRASH_JSON" 2>/dev/null || echo "") + if [ -n "$asi" ]; then + echo "" + echo "Application Specific Information:" + echo "$asi" + fi + + echo "" + echo "========================================" + echo "Thread Backtraces" + echo "========================================" + echo "" + + # Extract all thread data at once and process + jq -r '.threads[] | @json' < "$CRASH_JSON" | while IFS= read -r thread_json; do + thread_id=$(echo "$thread_json" | jq -r '.id') + thread_name=$(echo "$thread_json" | jq -r '.name // empty') + triggered=$(echo "$thread_json" | jq -r '.triggered // false') + queue=$(echo "$thread_json" | jq -r '.queue // empty') + + # Get thread index for display + thread_num=$(jq -r --argjson tid "$thread_id" '.threads | to_entries[] | select(.value.id == $tid) | .key' < "$CRASH_JSON") + + echo "----------------------------------------" + if [ "$triggered" == "true" ]; then + echo "Thread $thread_num Crashed (ID: $thread_id)" + else + echo "Thread $thread_num (ID: $thread_id)" + fi + + [ -n "$thread_name" ] && echo "Name: $thread_name" + [ -n "$queue" ] && echo "Queue: $queue" + echo "----------------------------------------" + + # Extract all frames for this thread at once + frame_num=0 + echo "$thread_json" | jq -r '.frames[]? | @json' | while IFS= read -r frame_json; do + image_index=$(echo "$frame_json" | jq -r '.imageIndex') + image_offset=$(echo "$frame_json" | jq -r '.imageOffset') + symbol=$(echo "$frame_json" | jq -r '.symbol // empty') + symbol_location=$(echo "$frame_json" | jq -r '.symbolLocation // empty') + + # Get image info + image_info=$(jq -r ".usedImages[$image_index] | {name: (.name // (.path | if type == \"string\" then split(\"/\")[-1] else \"unknown\" end)), base: .base}" < "$CRASH_JSON") + image_name=$(echo "$image_info" | jq -r '.name') + base_address=$(echo "$image_info" | jq -r '.base') + + # Calculate address + actual_address=$((base_address + image_offset)) + actual_address_hex=$(printf "0x%x" "$actual_address") + + # Convert base address to hex (atos requires hex format for -l flag) + base_address_hex=$(printf "0x%x" "$base_address") + + # Try to symbolicate if it's one of our binaries + symbolicated="" + dsym_binary=$(grep "^$image_name|" "$DSYM_CACHE" 2>/dev/null | cut -d'|' -f2) + + if [ -n "$dsym_binary" ]; then + symbolicated=$(atos -arch "$ARCH" -o "$dsym_binary" -l "$base_address_hex" "$actual_address_hex" 2>/dev/null || echo "") + + # Check if we got a real symbol (not just address back) + if [ -n "$symbolicated" ] && [[ ! "$symbolicated" =~ ^0x[0-9a-f]+ ]]; then + # Valid symbolication + : + else + symbolicated="" + fi + fi + + # Format output with frame number + if [ -n "$symbolicated" ]; then + printf "%-3d %-30s %s %s\n" "$frame_num" "$image_name" "$actual_address_hex" "$symbolicated" + elif [ -n "$symbol" ]; then + if [ -n "$symbol_location" ] && [ "$symbol_location" != "null" ]; then + printf "%-3d %-30s %s %s + %s\n" "$frame_num" "$image_name" "$actual_address_hex" "$symbol" "$symbol_location" + else + printf "%-3d %-30s %s %s\n" "$frame_num" "$image_name" "$actual_address_hex" "$symbol" + fi + else + printf "%-3d %-30s %s 0x%x\n" "$frame_num" "$image_name" "$actual_address_hex" "$image_offset" + fi + + frame_num=$((frame_num + 1)) + done + + echo "" + done + + echo "========================================" + echo "Binary Images" + echo "========================================" + echo "" + + jq -r '.usedImages[] | select(.uuid != "00000000-0000-0000-0000-000000000000") | + (if .name then .name elif .path then (.path | if type == "string" then split("/")[-1] else "unknown" end) else "unknown" end) as $name | + (if .path and (.path | type == "string") then .path else "unknown" end) as $path | + "\(.base | "0x" + (tonumber | tostring)) \($name) <\(.uuid)> \($path)"' < "$CRASH_JSON" + +} > "$OUTPUT_FILE" + +# Cleanup +rm -f "$DSYM_CACHE" "$CRASH_JSON" + +print_info "Symbolication complete!" +print_info "Output: $OUTPUT_FILE" + +# Show preview +echo "" +print_info "Preview (Thread 0):" +echo "" +sed -n '/^Thread 0 Crashed/,/^Thread [0-9]/p' "$OUTPUT_FILE" | head -n 25 +echo "" +print_info "Full report: $OUTPUT_FILE"