|
| 1 | +/* |
| 2 | + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. |
| 3 | + * This product includes software developed at Datadog (https://www.datadoghq.com/). |
| 4 | + * Copyright 2019-Present Datadog, Inc. |
| 5 | + */ |
| 6 | + |
| 7 | +import Foundation |
| 8 | + |
| 9 | +// swiftlint:disable duplicate_imports |
| 10 | +#if COCOAPODS |
| 11 | +import KSCrash |
| 12 | +#elseif swift(>=6.0) |
| 13 | +internal import KSCrashRecording |
| 14 | +#else |
| 15 | +@_implementationOnly import KSCrashRecording |
| 16 | +#endif |
| 17 | +// swiftlint:enable duplicate_imports |
| 18 | + |
| 19 | +/// A KSCrash filter that generates human-readable diagnostic messages for crash reports. |
| 20 | +/// |
| 21 | +/// This filter is modeled after KSCrash's `KSCrashReportFilterDoctor` and serves the same |
| 22 | +/// purpose: analyzing crash reports and producing descriptive diagnostic messages that explain |
| 23 | +/// the cause of the crash in plain language. |
| 24 | +/// |
| 25 | +/// ## Crash Types Handled |
| 26 | +/// |
| 27 | +/// 1. **Uncaught Exceptions**: Objective-C/Swift exceptions that weren't caught by the application |
| 28 | +/// - Extracts exception name and reason |
| 29 | +/// - Format: `"Terminating app due to uncaught exception 'ExceptionName', reason: 'detailed reason'."` |
| 30 | +/// |
| 31 | +/// 2. **Signal-based Crashes**: Low-level crashes caused by Unix signals |
| 32 | +/// - Maps signal names to human-readable descriptions (SIGSEGV → Segmentation fault, etc.) |
| 33 | +/// - Format: `"Application crash: SIGSEGV (Segmentation fault)"` |
| 34 | +/// |
| 35 | +/// ## Processing Flow |
| 36 | +/// |
| 37 | +/// For each crash report: |
| 38 | +/// 1. Validates the report structure |
| 39 | +/// 2. Analyzes crash data to determine the crash type |
| 40 | +/// 3. Generates an appropriate diagnostic message |
| 41 | +/// 4. Injects the diagnosis into both the main crash and recrash reports (if present) |
| 42 | +/// 5. Returns the updated report |
| 43 | +/// |
| 44 | +/// ## Integration |
| 45 | +/// |
| 46 | +/// This filter should be placed early in the KSCrash filter chain, before the |
| 47 | +/// `DatadogCrashReportFilter`, to ensure diagnostic information is available for |
| 48 | +/// subsequent processing and reporting. |
| 49 | +internal final class DatadogDiagnosticFilter: NSObject, CrashReportFilter { |
| 50 | + /// Placeholder text used when crash information is unavailable. |
| 51 | + private let unknown = "<unknown>" |
| 52 | + |
| 53 | + /// Mapping of Unix signal names to human-readable descriptions. |
| 54 | + /// |
| 55 | + /// This dictionary provides user-friendly descriptions for all standard POSIX signals, |
| 56 | + /// matching the behavior of KSCrash's diagnostic filter. |
| 57 | + private let knownSignalDescriptionByName = [ |
| 58 | + "SIGSIGNAL 0": "Signal 0", |
| 59 | + "SIGHUP": "Hangup", |
| 60 | + "SIGINT": "Interrupt", |
| 61 | + "SIGQUIT": "Quit", |
| 62 | + "SIGILL": "Illegal instruction", |
| 63 | + "SIGTRAP": "Trace/BPT trap", |
| 64 | + "SIGABRT": "Abort trap", |
| 65 | + "SIGEMT": "EMT trap", |
| 66 | + "SIGFPE": "Floating point exception", |
| 67 | + "SIGKILL": "Killed", |
| 68 | + "SIGBUS": "Bus error", |
| 69 | + "SIGSEGV": "Segmentation fault", |
| 70 | + "SIGSYS": "Bad system call", |
| 71 | + "SIGPIPE": "Broken pipe", |
| 72 | + "SIGALRM": "Alarm clock", |
| 73 | + "SIGTERM": "Terminated", |
| 74 | + "SIGURG": "Urgent I/O condition", |
| 75 | + "SIGSTOP": "Suspended (signal)", |
| 76 | + "SIGTSTP": "Suspended", |
| 77 | + "SIGCONT": "Continued", |
| 78 | + "SIGCHLD": "Child exited", |
| 79 | + "SIGTTIN": "Stopped (tty input)", |
| 80 | + "SIGTTOU": "Stopped (tty output)", |
| 81 | + "SIGIO": "I/O possible", |
| 82 | + "SIGXCPU": "Cputime limit exceeded", |
| 83 | + "SIGXFSZ": "Filesize limit exceeded", |
| 84 | + "SIGVTALRM": "Virtual timer expired", |
| 85 | + "SIGPROF": "Profiling timer expired", |
| 86 | + "SIGWINCH": "Window size changes", |
| 87 | + "SIGINFO": "Information request", |
| 88 | + "SIGUSR1": "User defined signal 1", |
| 89 | + "SIGUSR2": "User defined signal 2", |
| 90 | + ] |
| 91 | + |
| 92 | + /// Processes crash reports by adding human-readable diagnostic messages. |
| 93 | + /// |
| 94 | + /// This method analyzes each crash report, generates a diagnostic message describing |
| 95 | + /// the crash cause, and injects it into the report. The diagnosis is added to both |
| 96 | + /// the main crash report and any recrash reports present. |
| 97 | + /// |
| 98 | + /// - Parameters: |
| 99 | + /// - reports: The crash reports to process and enhance with diagnostic information |
| 100 | + /// - onCompletion: Completion handler called with the processed reports. If diagnosis |
| 101 | + /// generation fails for any report, the original reports are returned |
| 102 | + /// along with the error. |
| 103 | + func filterReports( |
| 104 | + _ reports: [CrashReport], |
| 105 | + onCompletion: (([CrashReport]?, (Error)?) -> Void)? |
| 106 | + ) { |
| 107 | + do { |
| 108 | + let reports = try reports.map { report in |
| 109 | + // Validate and extract the type-safe report dictionary |
| 110 | + guard var dict = report.untypedValue as? CrashFieldDictionary else { |
| 111 | + throw CrashReportException(description: "KSCrash report untypedValue is not a CrashDictionary") |
| 112 | + } |
| 113 | + |
| 114 | + if let crash: CrashFieldDictionary = try dict.valueIfPresent(forKey: .crash) { |
| 115 | + let diagnosis = try diagnose(crash: crash) |
| 116 | + dict.setValue(forKey: .crash, .diagnosis, value: diagnosis) |
| 117 | + } |
| 118 | + |
| 119 | + if let crash: CrashFieldDictionary = try dict.valueIfPresent(forKey: .recrashReport, .crash) { |
| 120 | + let diagnosis = try diagnose(crash: crash) |
| 121 | + dict.setValue(forKey: .recrashReport, .crash, .diagnosis, value: diagnosis) |
| 122 | + } |
| 123 | + |
| 124 | + return AnyCrashReport(dict) |
| 125 | + } |
| 126 | + |
| 127 | + onCompletion?(reports, nil) |
| 128 | + } catch { |
| 129 | + onCompletion?(reports, error) |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + /// Analyzes a crash report and generates a human-readable diagnostic message. |
| 134 | + /// |
| 135 | + /// This method examines the crash data to determine the crash type and constructs |
| 136 | + /// an appropriate diagnostic message. It follows a prioritized analysis: |
| 137 | + /// |
| 138 | + /// 1. **Exception-based crashes**: Checks for uncaught NSException |
| 139 | + /// 2. **Signal-based crashes**: Checks for Unix signals with known descriptions |
| 140 | + /// 3. **Unknown crashes**: Returns a generic message for unrecognized crash types |
| 141 | + /// |
| 142 | + /// - Parameter dict: The crash report dictionary containing crash information |
| 143 | + /// - Returns: A diagnostic message describing the crash, or `nil` if no crash data is found |
| 144 | + /// - Throws: `CrashReportException` if the report structure is invalid |
| 145 | + /// |
| 146 | + /// ## Example Messages |
| 147 | + /// |
| 148 | + /// - Exception: `"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unrecognized selector'."` |
| 149 | + /// - Signal: `"Application crash: SIGSEGV (Segmentation fault)"` |
| 150 | + /// - Unknown: `"Application crash: <unknown>"` |
| 151 | + func diagnose(crash dict: CrashFieldDictionary) throws -> String { |
| 152 | + // Check for uncaught exception |
| 153 | + if let exception: CrashFieldDictionary = try dict.valueIfPresent(forKey: .error, .nsException) { |
| 154 | + let name: String = try exception.valueIfPresent(forKey: .name) ?? unknown // e.g. `NSInvalidArgumentException` |
| 155 | + let reason = try dict.valueIfPresent(forKey: .error, .reason) ?? unknown // e.g. `-[NSObject objectForKey:]: unrecognized selector sent to instance 0x...` |
| 156 | + return "Terminating app due to uncaught exception '\(name)', reason: '\(reason)'." |
| 157 | + } |
| 158 | + |
| 159 | + // Check for signal-based crash with known description |
| 160 | + if |
| 161 | + let name: String = try dict.valueIfPresent(forKey: .error, .signal, .name), |
| 162 | + let description = knownSignalDescriptionByName[name] { |
| 163 | + return "Application crash: \(name) (\(description))" |
| 164 | + } |
| 165 | + |
| 166 | + // Fallback for unknown crash types |
| 167 | + return "Application crash: \(unknown)" |
| 168 | + } |
| 169 | +} |
0 commit comments