@app-swiss-knife/react-native-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,1287 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift
|
|
2
|
+
//
|
|
3
|
+
// Sentry-compatible crash reporting SDK for swiss-knife (iOS).
|
|
4
|
+
// Captures NSExceptions, signal-based crashes, and breadcrumbs.
|
|
5
|
+
// On next launch, any pending crash report is read and sent before
|
|
6
|
+
// normal operation resumes.
|
|
7
|
+
|
|
8
|
+
import Foundation
|
|
9
|
+
import Darwin
|
|
10
|
+
|
|
11
|
+
#if canImport(UIKit)
|
|
12
|
+
import UIKit
|
|
13
|
+
#endif
|
|
14
|
+
|
|
15
|
+
// MARK: - Supporting Types
|
|
16
|
+
|
|
17
|
+
public enum SKErrorLevel: String, Codable {
|
|
18
|
+
case debug
|
|
19
|
+
case info
|
|
20
|
+
case warning
|
|
21
|
+
case error
|
|
22
|
+
case fatal
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
public struct SKStackFrame: Codable {
|
|
26
|
+
public var filename: String?
|
|
27
|
+
public var function: String?
|
|
28
|
+
public var module: String?
|
|
29
|
+
public var lineno: Int?
|
|
30
|
+
public var colno: Int?
|
|
31
|
+
public var instructionAddress: String?
|
|
32
|
+
public var inApp: Bool
|
|
33
|
+
|
|
34
|
+
public init(filename: String? = nil, function: String? = nil, module: String? = nil, lineno: Int? = nil, colno: Int? = nil, instructionAddress: String? = nil, inApp: Bool = true) {
|
|
35
|
+
self.filename = filename
|
|
36
|
+
self.function = function
|
|
37
|
+
self.module = module
|
|
38
|
+
self.lineno = lineno
|
|
39
|
+
self.colno = colno
|
|
40
|
+
self.instructionAddress = instructionAddress
|
|
41
|
+
self.inApp = inApp
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public struct SKBreadcrumb: Codable {
|
|
46
|
+
public var timestamp: Date
|
|
47
|
+
public var category: String?
|
|
48
|
+
public var message: String?
|
|
49
|
+
public var level: SKErrorLevel
|
|
50
|
+
public var data: [String: String]?
|
|
51
|
+
|
|
52
|
+
public init(category: String? = nil, message: String? = nil, level: SKErrorLevel = .info, data: [String: String]? = nil) {
|
|
53
|
+
self.timestamp = Date()
|
|
54
|
+
self.category = category
|
|
55
|
+
self.message = message
|
|
56
|
+
self.level = level
|
|
57
|
+
self.data = data
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
public struct SKUser: Codable {
|
|
62
|
+
public var id: String?
|
|
63
|
+
public var email: String?
|
|
64
|
+
public var username: String?
|
|
65
|
+
|
|
66
|
+
public init(id: String? = nil, email: String? = nil, username: String? = nil) {
|
|
67
|
+
self.id = id
|
|
68
|
+
self.email = email
|
|
69
|
+
self.username = username
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
public struct SKErrorEvent: Codable {
|
|
74
|
+
public var eventId: String
|
|
75
|
+
public var timestamp: Date
|
|
76
|
+
public var level: SKErrorLevel
|
|
77
|
+
public var message: String?
|
|
78
|
+
public var exceptionType: String?
|
|
79
|
+
public var exceptionValue: String?
|
|
80
|
+
public var stacktrace: [SKStackFrame]?
|
|
81
|
+
public var breadcrumbs: [SKBreadcrumb]?
|
|
82
|
+
public var tags: [String: String]?
|
|
83
|
+
public var extra: [String: String]?
|
|
84
|
+
public var user: SKUser?
|
|
85
|
+
public var environment: String?
|
|
86
|
+
public var release: String?
|
|
87
|
+
public var platform: String
|
|
88
|
+
public var deviceModel: String?
|
|
89
|
+
public var osVersion: String?
|
|
90
|
+
public var appVersion: String?
|
|
91
|
+
public var bundleId: String?
|
|
92
|
+
public var mechanism: String?
|
|
93
|
+
|
|
94
|
+
public init(
|
|
95
|
+
level: SKErrorLevel = .error,
|
|
96
|
+
message: String? = nil,
|
|
97
|
+
exceptionType: String? = nil,
|
|
98
|
+
exceptionValue: String? = nil
|
|
99
|
+
) {
|
|
100
|
+
self.eventId = IDs.eventId()
|
|
101
|
+
self.timestamp = Date()
|
|
102
|
+
self.level = level
|
|
103
|
+
self.message = message
|
|
104
|
+
self.exceptionType = exceptionType
|
|
105
|
+
self.exceptionValue = exceptionValue
|
|
106
|
+
self.platform = "cocoa"
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// MARK: - Scope
|
|
111
|
+
|
|
112
|
+
public final class SKErrorScope {
|
|
113
|
+
internal var tags: [String: String] = [:]
|
|
114
|
+
internal var extra: [String: String] = [:]
|
|
115
|
+
internal var user: SKUser?
|
|
116
|
+
|
|
117
|
+
public func setTag(_ key: String, value: String) {
|
|
118
|
+
tags[key] = value
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
public func setExtra(_ key: String, value: Any) {
|
|
122
|
+
extra[key] = "\(value)"
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
public func setUser(_ user: SKUser?) {
|
|
126
|
+
self.user = user
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// MARK: - Ring Buffer
|
|
131
|
+
|
|
132
|
+
internal final class RingBuffer<T> {
|
|
133
|
+
private var buffer: [T] = []
|
|
134
|
+
private let capacity: Int
|
|
135
|
+
|
|
136
|
+
init(capacity: Int) {
|
|
137
|
+
self.capacity = max(1, capacity)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
func append(_ element: T) {
|
|
141
|
+
if buffer.count >= capacity {
|
|
142
|
+
buffer.removeFirst()
|
|
143
|
+
}
|
|
144
|
+
buffer.append(element)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
func snapshot() -> [T] { buffer }
|
|
148
|
+
|
|
149
|
+
func clear() { buffer = [] }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// MARK: - Main SDK
|
|
153
|
+
|
|
154
|
+
public final class SKCrashReporting {
|
|
155
|
+
|
|
156
|
+
public static let shared = SKCrashReporting()
|
|
157
|
+
|
|
158
|
+
public struct Configuration {
|
|
159
|
+
public let apiKey: String
|
|
160
|
+
public var serverURL: String
|
|
161
|
+
public var environment: String
|
|
162
|
+
public var release: String?
|
|
163
|
+
public var maxBreadcrumbs: Int
|
|
164
|
+
public var enableAutoSessionTracking: Bool
|
|
165
|
+
public var beforeSend: ((SKErrorEvent) -> SKErrorEvent?)?
|
|
166
|
+
public var sampleRate: Double
|
|
167
|
+
public var tracesSampleRate: Double
|
|
168
|
+
/// ANR watchdog timeout in seconds. Set to 0 to disable. Default 5.0.
|
|
169
|
+
public var anrTimeoutSeconds: TimeInterval
|
|
170
|
+
|
|
171
|
+
public init(
|
|
172
|
+
apiKey: String,
|
|
173
|
+
serverURL: String = "",
|
|
174
|
+
environment: String = "production",
|
|
175
|
+
release: String? = nil,
|
|
176
|
+
maxBreadcrumbs: Int = 100,
|
|
177
|
+
enableAutoSessionTracking: Bool = true,
|
|
178
|
+
beforeSend: ((SKErrorEvent) -> SKErrorEvent?)? = nil,
|
|
179
|
+
sampleRate: Double = 1.0,
|
|
180
|
+
tracesSampleRate: Double = 1.0,
|
|
181
|
+
anrTimeoutSeconds: TimeInterval = 5.0
|
|
182
|
+
) {
|
|
183
|
+
self.apiKey = apiKey
|
|
184
|
+
self.serverURL = serverURL
|
|
185
|
+
self.environment = environment
|
|
186
|
+
self.release = release
|
|
187
|
+
self.maxBreadcrumbs = maxBreadcrumbs
|
|
188
|
+
self.enableAutoSessionTracking = enableAutoSessionTracking
|
|
189
|
+
self.beforeSend = beforeSend
|
|
190
|
+
self.sampleRate = sampleRate
|
|
191
|
+
self.tracesSampleRate = tracesSampleRate
|
|
192
|
+
self.anrTimeoutSeconds = anrTimeoutSeconds
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private var configuration: Configuration?
|
|
197
|
+
private let scope = SKErrorScope()
|
|
198
|
+
private var breadcrumbs: RingBuffer<SKBreadcrumb> = RingBuffer(capacity: 100)
|
|
199
|
+
private let queue = DispatchQueue(label: "com.swissknife.crashreporting", qos: .utility)
|
|
200
|
+
/// Counter for periodic breadcrumb/scope persistence
|
|
201
|
+
private var breadcrumbsSinceLastPersist: Int = 0
|
|
202
|
+
private static let persistEveryNBreadcrumbs = 10
|
|
203
|
+
|
|
204
|
+
// Session tracking
|
|
205
|
+
//
|
|
206
|
+
// The session id is sourced from `Session.shared.current.id` — the same
|
|
207
|
+
// primitive that stamps envelope-level `ContextSnapshot.session_id`. Prior
|
|
208
|
+
// to this fix SKCrashReporting minted its own `sessionId` via
|
|
209
|
+
// `IDs.sessionId()`, which diverged from the envelope and made
|
|
210
|
+
// session_event payloads disagree with their own enclosing envelope.
|
|
211
|
+
private var sessionErrorCount: Int = 0
|
|
212
|
+
|
|
213
|
+
// ANR watchdog
|
|
214
|
+
private var anrWatchdogRunning = false
|
|
215
|
+
|
|
216
|
+
/// Session-rotation observer token — re-persists crash context on
|
|
217
|
+
/// rotation so signal-path recovery closes the right session.
|
|
218
|
+
private var sessionPersistToken: UUID?
|
|
219
|
+
|
|
220
|
+
/// IngestClient seam — production wires the shared singleton; tests can
|
|
221
|
+
/// swap a custom instance via `_setIngestForTesting` to assert on
|
|
222
|
+
/// enqueued items without a live network. All crash / error / feedback /
|
|
223
|
+
/// session events route through this — there is NO direct HTTP
|
|
224
|
+
/// transport path left in SKCrashReporting.
|
|
225
|
+
internal var ingest: IngestClient = IngestClient.shared
|
|
226
|
+
|
|
227
|
+
private static let crashDirectory: URL = {
|
|
228
|
+
let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
|
|
229
|
+
return caches.appendingPathComponent("swiss-knife-crash", isDirectory: true)
|
|
230
|
+
}()
|
|
231
|
+
|
|
232
|
+
private static let pendingCrashURL: URL = {
|
|
233
|
+
crashDirectory.appendingPathComponent("pending-crash.json")
|
|
234
|
+
}()
|
|
235
|
+
|
|
236
|
+
/// Signal marker file — written by async-signal-safe handler (just signal number)
|
|
237
|
+
private static let signalMarkerURL: URL = {
|
|
238
|
+
crashDirectory.appendingPathComponent("signal-marker")
|
|
239
|
+
}()
|
|
240
|
+
|
|
241
|
+
/// Persisted breadcrumbs/scope (written periodically during normal operation)
|
|
242
|
+
private static let persistedContextURL: URL = {
|
|
243
|
+
crashDirectory.appendingPathComponent("persisted-context.json")
|
|
244
|
+
}()
|
|
245
|
+
|
|
246
|
+
/// Pre-allocated C string path for signal handler (no Swift allocation at crash time)
|
|
247
|
+
private static var signalMarkerPathCString: [CChar] = []
|
|
248
|
+
/// Pre-allocated C string path for backtrace binary file (signal handler writes raw addresses here)
|
|
249
|
+
private static var backtracePathCString: [CChar] = []
|
|
250
|
+
private static let backtraceFileURL: URL = {
|
|
251
|
+
crashDirectory.appendingPathComponent("backtrace-bin")
|
|
252
|
+
}()
|
|
253
|
+
|
|
254
|
+
private init() {}
|
|
255
|
+
|
|
256
|
+
// MARK: - Start
|
|
257
|
+
|
|
258
|
+
public func start(configuration: Configuration) {
|
|
259
|
+
self.configuration = configuration
|
|
260
|
+
self.breadcrumbs = RingBuffer(capacity: configuration.maxBreadcrumbs)
|
|
261
|
+
|
|
262
|
+
// Ensure crash directory exists
|
|
263
|
+
try? FileManager.default.createDirectory(
|
|
264
|
+
at: SKCrashReporting.crashDirectory,
|
|
265
|
+
withIntermediateDirectories: true
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
// Pre-allocate C string paths for the signal handler (async-signal-safe)
|
|
269
|
+
SKCrashReporting.signalMarkerPathCString = SKCrashReporting.signalMarkerURL.path.utf8CString.map { $0 }
|
|
270
|
+
SKCrashReporting.backtracePathCString = SKCrashReporting.backtraceFileURL.path.utf8CString.map { $0 }
|
|
271
|
+
|
|
272
|
+
// Send any crash from previous session (signal marker or pending JSON).
|
|
273
|
+
// Both paths enqueue the recovered events onto IngestClient's DISK
|
|
274
|
+
// queue (via sendEvent → queue.async) — but IngestClient only drains
|
|
275
|
+
// at ≥batchSize items, on reachability regain, or on
|
|
276
|
+
// didEnterBackground, so without a kick a recovered crash would sit
|
|
277
|
+
// on disk for the whole next session. Schedule a launch-time flush
|
|
278
|
+
// BEHIND the recovery enqueues on the same serial queue, so the items
|
|
279
|
+
// are on the ingest queue before the drain starts.
|
|
280
|
+
let recoveredSignalCrash = flushSignalMarker()
|
|
281
|
+
let recoveredPendingCrash = flushPendingCrash()
|
|
282
|
+
if recoveredSignalCrash || recoveredPendingCrash {
|
|
283
|
+
queue.async { [ingest] in
|
|
284
|
+
ingest.scheduleImmediateFlush()
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Install handlers
|
|
289
|
+
installUncaughtExceptionHandler()
|
|
290
|
+
installSignalHandlers()
|
|
291
|
+
|
|
292
|
+
// Fix for the signal-path crashed-session gap: session context must
|
|
293
|
+
// already be ON DISK when a signal fires (the handler is restricted
|
|
294
|
+
// to async-signal-safe calls, so it cannot persist anything itself).
|
|
295
|
+
// `installSignalHandlers()` persists once at install time; this
|
|
296
|
+
// observer re-persists whenever the session rotates (foreground after
|
|
297
|
+
// background timeout) so next-launch recovery always closes the
|
|
298
|
+
// session that actually crashed.
|
|
299
|
+
if let token = sessionPersistToken {
|
|
300
|
+
Session.shared.removeObserver(token)
|
|
301
|
+
}
|
|
302
|
+
sessionPersistToken = Session.shared.addObserver { [weak self] _ in
|
|
303
|
+
guard let self else { return }
|
|
304
|
+
self.queue.async { self.persistContextToDisk() }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Auto-breadcrumbs & session tracking
|
|
308
|
+
if configuration.enableAutoSessionTracking {
|
|
309
|
+
registerLifecycleObservers()
|
|
310
|
+
startSession()
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ANR watchdog
|
|
314
|
+
if configuration.anrTimeoutSeconds > 0 {
|
|
315
|
+
startANRWatchdog()
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// MARK: - Sampling & beforeSend
|
|
320
|
+
|
|
321
|
+
private func applyBeforeSend(_ event: SKErrorEvent) -> SKErrorEvent? {
|
|
322
|
+
guard let config = configuration else { return event }
|
|
323
|
+
if config.sampleRate < 1.0 && Double.random(in: 0...1) > config.sampleRate { return nil }
|
|
324
|
+
if let hook = config.beforeSend { return hook(event) }
|
|
325
|
+
return event
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// MARK: - Public API
|
|
329
|
+
|
|
330
|
+
@discardableResult
|
|
331
|
+
public func captureError(_ error: Error, tags: [String: String]? = nil) -> String {
|
|
332
|
+
sessionErrorCount += 1
|
|
333
|
+
// Keep the on-disk session error count fresh for signal recovery.
|
|
334
|
+
queue.async { [weak self] in self?.persistContextToDisk() }
|
|
335
|
+
var event = buildEvent(level: .error)
|
|
336
|
+
event.exceptionType = String(describing: type(of: error))
|
|
337
|
+
event.exceptionValue = error.localizedDescription
|
|
338
|
+
event.stacktrace = currentStackFrames()
|
|
339
|
+
if let tags { event.tags = mergeTags(scope.tags, tags) }
|
|
340
|
+
guard let finalEvent = applyBeforeSend(event) else { return event.eventId }
|
|
341
|
+
sendEvent(finalEvent)
|
|
342
|
+
return finalEvent.eventId
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
@discardableResult
|
|
346
|
+
public func captureException(_ exception: NSException, tags: [String: String]? = nil) -> String {
|
|
347
|
+
sessionErrorCount += 1
|
|
348
|
+
// Keep the on-disk session error count fresh for signal recovery.
|
|
349
|
+
queue.async { [weak self] in self?.persistContextToDisk() }
|
|
350
|
+
var event = buildEvent(level: .fatal)
|
|
351
|
+
event.exceptionType = exception.name.rawValue
|
|
352
|
+
event.exceptionValue = exception.reason
|
|
353
|
+
event.stacktrace = parseCallStackSymbols(exception.callStackSymbols)
|
|
354
|
+
if let tags { event.tags = mergeTags(scope.tags, tags) }
|
|
355
|
+
guard let finalEvent = applyBeforeSend(event) else { return event.eventId }
|
|
356
|
+
sendEvent(finalEvent)
|
|
357
|
+
return finalEvent.eventId
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
public func captureMessage(_ message: String, level: SKErrorLevel = .info) {
|
|
361
|
+
var event = buildEvent(level: level)
|
|
362
|
+
event.message = message
|
|
363
|
+
guard let finalEvent = applyBeforeSend(event) else { return }
|
|
364
|
+
sendEvent(finalEvent)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/// Submit user feedback for a previously captured error event.
|
|
368
|
+
/// Routes through `IngestClient` as a `feedback`-typed item so the
|
|
369
|
+
/// server-side `/ingest` dispatcher can fan it back to the feedback
|
|
370
|
+
/// schema. ContextSnapshot stamping (identity/session/device) happens
|
|
371
|
+
/// at flush time inside IngestClient — we only carry the domain
|
|
372
|
+
/// payload here.
|
|
373
|
+
public func captureUserFeedback(
|
|
374
|
+
eventId: String,
|
|
375
|
+
name: String? = nil,
|
|
376
|
+
email: String? = nil,
|
|
377
|
+
comments: String
|
|
378
|
+
) {
|
|
379
|
+
guard configuration != nil else { return }
|
|
380
|
+
queue.async { [ingest] in
|
|
381
|
+
var body: [String: Any] = [
|
|
382
|
+
"eventId": eventId,
|
|
383
|
+
"comments": comments,
|
|
384
|
+
]
|
|
385
|
+
if let name { body["name"] = name }
|
|
386
|
+
if let email { body["email"] = email }
|
|
387
|
+
ingest.enqueue(type: .feedback, jsonObject: body)
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/// Returns the current trace propagation headers for distributed tracing.
|
|
392
|
+
/// Add these to outbound URLRequest headers to link spans across services.
|
|
393
|
+
public func traceHeaders() -> [String: String] {
|
|
394
|
+
guard let tx = SKPerformance.shared.currentTransaction else { return [:] }
|
|
395
|
+
let sampled = (SKPerformance.shared.currentTransaction?.sampled ?? false) ? "1" : "0"
|
|
396
|
+
return [
|
|
397
|
+
"sk-trace-id": tx.traceId,
|
|
398
|
+
"sk-parent-span-id": tx.spanId,
|
|
399
|
+
"sk-sampled": sampled,
|
|
400
|
+
]
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
public func captureEvent(_ event: SKErrorEvent) {
|
|
404
|
+
var e = event
|
|
405
|
+
if e.environment == nil { e.environment = configuration?.environment }
|
|
406
|
+
if e.release == nil { e.release = configuration?.release }
|
|
407
|
+
applyDeviceContext(to: &e)
|
|
408
|
+
applyScope(to: &e)
|
|
409
|
+
sendEvent(e)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/// Flush all pending operations (queued error/message events).
|
|
413
|
+
///
|
|
414
|
+
/// Post-IngestClient migration, this delegates to
|
|
415
|
+
/// `IngestClient.flushBestEffort()` — items captured via `captureError`,
|
|
416
|
+
/// `captureException`, etc. are already on the IngestClient queue by
|
|
417
|
+
/// the time this is called, so a successful flush sends them to
|
|
418
|
+
/// `/ingest` immediately rather than waiting for the 30s timer.
|
|
419
|
+
public func flush(completion: (() -> Void)? = nil) {
|
|
420
|
+
let ingest = self.ingest
|
|
421
|
+
Task { [weak self] in
|
|
422
|
+
await ingest.flushBestEffort()
|
|
423
|
+
self?.queue.async {
|
|
424
|
+
completion?()
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
public func addBreadcrumb(_ breadcrumb: SKBreadcrumb) {
|
|
430
|
+
queue.async { [weak self] in
|
|
431
|
+
guard let self else { return }
|
|
432
|
+
self.breadcrumbs.append(breadcrumb)
|
|
433
|
+
self.breadcrumbsSinceLastPersist += 1
|
|
434
|
+
if self.breadcrumbsSinceLastPersist >= SKCrashReporting.persistEveryNBreadcrumbs {
|
|
435
|
+
self.breadcrumbsSinceLastPersist = 0
|
|
436
|
+
self.persistContextToDisk()
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
public func configureScope(_ callback: (SKErrorScope) -> Void) {
|
|
442
|
+
callback(scope)
|
|
443
|
+
queue.async { [weak self] in self?.persistContextToDisk() }
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
public func setUser(_ user: SKUser?) {
|
|
447
|
+
scope.setUser(user)
|
|
448
|
+
queue.async { [weak self] in self?.persistContextToDisk() }
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
public func setTag(_ key: String, value: String) {
|
|
452
|
+
scope.setTag(key, value: value)
|
|
453
|
+
queue.async { [weak self] in self?.persistContextToDisk() }
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
public func setExtra(_ key: String, value: Any) {
|
|
457
|
+
scope.setExtra(key, value: value)
|
|
458
|
+
queue.async { [weak self] in self?.persistContextToDisk() }
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/// Convenience method for network layers to record HTTP breadcrumbs.
|
|
462
|
+
/// Call this from your HTTP session delegate (the SDK ships one for
|
|
463
|
+
/// this — see Performance/), an Alamofire interceptor, or a custom
|
|
464
|
+
/// URLProtocol to auto-capture HTTP activity.
|
|
465
|
+
public func captureHTTPBreadcrumb(method: String, url: String, statusCode: Int, duration: TimeInterval) {
|
|
466
|
+
let durationMs = Int(duration * 1000)
|
|
467
|
+
let level: SKErrorLevel = (200..<400).contains(statusCode) ? .info : .warning
|
|
468
|
+
addBreadcrumb(SKBreadcrumb(
|
|
469
|
+
category: "http",
|
|
470
|
+
message: "\(method) \(url)",
|
|
471
|
+
level: level,
|
|
472
|
+
data: [
|
|
473
|
+
"method": method,
|
|
474
|
+
"url": url,
|
|
475
|
+
"status_code": "\(statusCode)",
|
|
476
|
+
"duration_ms": "\(durationMs)"
|
|
477
|
+
]
|
|
478
|
+
))
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// MARK: - Private: Build / Send
|
|
482
|
+
|
|
483
|
+
private func buildEvent(level: SKErrorLevel) -> SKErrorEvent {
|
|
484
|
+
var event = SKErrorEvent(level: level)
|
|
485
|
+
event.environment = configuration?.environment
|
|
486
|
+
event.release = configuration?.release
|
|
487
|
+
event.tags = scope.tags.isEmpty ? nil : scope.tags
|
|
488
|
+
event.extra = scope.extra.isEmpty ? nil : scope.extra
|
|
489
|
+
event.user = scope.user
|
|
490
|
+
event.breadcrumbs = queue.sync { breadcrumbs.snapshot() }
|
|
491
|
+
applyDeviceContext(to: &event)
|
|
492
|
+
return event
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
private func applyDeviceContext(to event: inout SKErrorEvent) {
|
|
496
|
+
// Intentionally empty. `deviceModel`, `osVersion`, `appVersion`,
|
|
497
|
+
// and `bundleId` used to be stamped here, but they are already
|
|
498
|
+
// carried by the envelope-level `ContextSnapshot.device` that
|
|
499
|
+
// `IngestClient` stamps at flush time. Duplicating them on the
|
|
500
|
+
// data payload made every error event ~4 keys heavier with the
|
|
501
|
+
// exact same values. SDK-config-derived fields (`environment`,
|
|
502
|
+
// `release`) and scope-derived fields (`user`, `tags`, `extra`,
|
|
503
|
+
// `breadcrumbs`) are stamped elsewhere in `buildEvent` and stay.
|
|
504
|
+
//
|
|
505
|
+
// The method itself stays as a hook for any future per-event
|
|
506
|
+
// override (e.g. pinning the device snapshot at crash-time vs
|
|
507
|
+
// flush-time) without churning every call site.
|
|
508
|
+
_ = event
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
private func applyScope(to event: inout SKErrorEvent) {
|
|
512
|
+
if event.tags == nil { event.tags = scope.tags.isEmpty ? nil : scope.tags }
|
|
513
|
+
if event.extra == nil { event.extra = scope.extra.isEmpty ? nil : scope.extra }
|
|
514
|
+
if event.user == nil { event.user = scope.user }
|
|
515
|
+
if event.breadcrumbs == nil { event.breadcrumbs = queue.sync { breadcrumbs.snapshot() } }
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/// Hand a single error event off to IngestClient. The envelope-level
|
|
519
|
+
/// ContextSnapshot (event_id, anonymous_id, user_id, session_id,
|
|
520
|
+
/// device, timestamp, sdk_version) is stamped by IngestClient at
|
|
521
|
+
/// flush time — we DO NOT duplicate those here, the domain payload
|
|
522
|
+
/// is pure crash data only.
|
|
523
|
+
private func sendEvent(_ event: SKErrorEvent) {
|
|
524
|
+
queue.async { [ingest] in
|
|
525
|
+
do {
|
|
526
|
+
let encoder = JSONEncoder()
|
|
527
|
+
encoder.dateEncodingStrategy = .iso8601
|
|
528
|
+
let data = try encoder.encode(event)
|
|
529
|
+
if let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
|
530
|
+
ingest.enqueue(type: .error, jsonObject: obj)
|
|
531
|
+
}
|
|
532
|
+
} catch {
|
|
533
|
+
// Encoding failures are non-recoverable — drop with no
|
|
534
|
+
// retry. The event was already lost the moment Codable
|
|
535
|
+
// failed; persisting it wouldn't help.
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/// Hand a batch of buffered crashes off to IngestClient as a single
|
|
541
|
+
/// `error_batch` item — saves the server one envelope parse per crash
|
|
542
|
+
/// when the host accumulated many fatals.
|
|
543
|
+
private func sendBatch(_ events: [SKErrorEvent]) {
|
|
544
|
+
guard !events.isEmpty else { return }
|
|
545
|
+
queue.async { [ingest] in
|
|
546
|
+
do {
|
|
547
|
+
let encoder = JSONEncoder()
|
|
548
|
+
encoder.dateEncodingStrategy = .iso8601
|
|
549
|
+
var items: [[String: Any]] = []
|
|
550
|
+
for ev in events {
|
|
551
|
+
let d = try encoder.encode(ev)
|
|
552
|
+
if let obj = try JSONSerialization.jsonObject(with: d) as? [String: Any] {
|
|
553
|
+
items.append(obj)
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
ingest.enqueue(type: .errorBatch, jsonObject: ["items": items])
|
|
557
|
+
} catch {
|
|
558
|
+
// Same drop policy as sendEvent above.
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// MARK: - Context Persistence (breadcrumbs + scope → disk)
|
|
564
|
+
|
|
565
|
+
/// Persisted context structure for recovery after signal crashes.
|
|
566
|
+
/// Envelope-redundant device fields (`deviceModel`, `osVersion`,
|
|
567
|
+
/// `appVersion`, `bundleId`) used to be persisted here too — dropped
|
|
568
|
+
/// since `ContextSnapshot.device` carries them at flush time and the
|
|
569
|
+
/// signal-recovered crash flows through the same IngestClient path.
|
|
570
|
+
/// `environment` / `release` are SDK-config specific (not envelope-derived)
|
|
571
|
+
/// and stay.
|
|
572
|
+
private struct PersistedContext: Codable {
|
|
573
|
+
var breadcrumbs: [SKBreadcrumb]
|
|
574
|
+
var tags: [String: String]
|
|
575
|
+
var extra: [String: String]
|
|
576
|
+
var user: SKUser?
|
|
577
|
+
var environment: String?
|
|
578
|
+
var release: String?
|
|
579
|
+
// Session context for the signal-path crashed-session close. The
|
|
580
|
+
// NSException hook marks the session "crashed" at crash time, but a
|
|
581
|
+
// signal handler is restricted to async-signal-safe calls and cannot
|
|
582
|
+
// — so we persist the live session's identity PROACTIVELY (handler
|
|
583
|
+
// install, session rotation, every periodic persist) and, on
|
|
584
|
+
// next-launch signal recovery, send the session-crashed close from
|
|
585
|
+
// these fields. All optional so context files written by older SDK
|
|
586
|
+
// versions still decode.
|
|
587
|
+
var sessionId: String?
|
|
588
|
+
var sessionStartedAt: Date?
|
|
589
|
+
var sessionErrorCount: Int?
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/// Called periodically (every N breadcrumbs, on scope change) to persist
|
|
593
|
+
/// crash context so the signal handler doesn't need to touch Swift runtime.
|
|
594
|
+
private func persistContextToDisk() {
|
|
595
|
+
let session = Session.shared.current
|
|
596
|
+
let ctx = PersistedContext(
|
|
597
|
+
breadcrumbs: breadcrumbs.snapshot(),
|
|
598
|
+
tags: scope.tags,
|
|
599
|
+
extra: scope.extra,
|
|
600
|
+
user: scope.user,
|
|
601
|
+
environment: configuration?.environment,
|
|
602
|
+
release: configuration?.release,
|
|
603
|
+
sessionId: session.id,
|
|
604
|
+
sessionStartedAt: session.startedAt,
|
|
605
|
+
sessionErrorCount: sessionErrorCount
|
|
606
|
+
)
|
|
607
|
+
let encoder = JSONEncoder()
|
|
608
|
+
encoder.dateEncodingStrategy = .iso8601
|
|
609
|
+
guard let data = try? encoder.encode(ctx) else { return }
|
|
610
|
+
try? data.write(to: SKCrashReporting.persistedContextURL, options: .atomic)
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// MARK: - Pending Crash (disk)
|
|
614
|
+
|
|
615
|
+
/// Returns `true` when a pending crash was recovered and enqueued —
|
|
616
|
+
/// `start()` uses this to trigger the launch-time ingest flush.
|
|
617
|
+
private func flushPendingCrash() -> Bool {
|
|
618
|
+
let url = SKCrashReporting.pendingCrashURL
|
|
619
|
+
guard FileManager.default.fileExists(atPath: url.path),
|
|
620
|
+
let data = try? Data(contentsOf: url) else { return false }
|
|
621
|
+
|
|
622
|
+
// Delete before sending to avoid re-sending on failure (best-effort delivery)
|
|
623
|
+
try? FileManager.default.removeItem(at: url)
|
|
624
|
+
|
|
625
|
+
guard configuration != nil else { return false }
|
|
626
|
+
// The crash JSON on disk is a single SKErrorEvent. Decode and
|
|
627
|
+
// re-enqueue through IngestClient so retry / batching / context
|
|
628
|
+
// stamping all happen uniformly with live errors.
|
|
629
|
+
let decoder = JSONDecoder()
|
|
630
|
+
decoder.dateDecodingStrategy = .iso8601
|
|
631
|
+
if let event = try? decoder.decode(SKErrorEvent.self, from: data) {
|
|
632
|
+
sendEvent(event)
|
|
633
|
+
return true
|
|
634
|
+
}
|
|
635
|
+
return false
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/// On next launch, read the signal marker file + backtrace binary +
|
|
639
|
+
/// persisted context and construct a full crash event to send.
|
|
640
|
+
/// The async-signal-safe signal handler writes the signal number to the
|
|
641
|
+
/// marker and raw backtrace addresses to the backtrace-bin file.
|
|
642
|
+
/// Returns `true` when a signal crash was recovered and enqueued —
|
|
643
|
+
/// `start()` uses this to trigger the launch-time ingest flush.
|
|
644
|
+
private func flushSignalMarker() -> Bool {
|
|
645
|
+
let markerURL = SKCrashReporting.signalMarkerURL
|
|
646
|
+
let contextURL = SKCrashReporting.persistedContextURL
|
|
647
|
+
let backtraceURL = SKCrashReporting.backtraceFileURL
|
|
648
|
+
guard FileManager.default.fileExists(atPath: markerURL.path),
|
|
649
|
+
let markerData = try? Data(contentsOf: markerURL) else { return false }
|
|
650
|
+
|
|
651
|
+
// The marker's mtime approximates the crash instant — grab it before
|
|
652
|
+
// deleting the file so the recovered session close below can report a
|
|
653
|
+
// real duration instead of measuring across the relaunch gap.
|
|
654
|
+
let crashedAt = (try? FileManager.default.attributesOfItem(atPath: markerURL.path))?[.modificationDate] as? Date ?? Date()
|
|
655
|
+
|
|
656
|
+
// Delete marker immediately
|
|
657
|
+
try? FileManager.default.removeItem(at: markerURL)
|
|
658
|
+
|
|
659
|
+
let signalString = String(data: markerData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "unknown"
|
|
660
|
+
|
|
661
|
+
// Build event from persisted context (if available)
|
|
662
|
+
var event = SKErrorEvent(level: .fatal)
|
|
663
|
+
event.exceptionType = "Signal"
|
|
664
|
+
event.exceptionValue = "Signal \(signalString)"
|
|
665
|
+
event.mechanism = "signal"
|
|
666
|
+
|
|
667
|
+
// Read backtrace binary file and resolve addresses using dladdr()
|
|
668
|
+
if let btData = try? Data(contentsOf: backtraceURL), btData.count >= MemoryLayout<Int32>.size * 2 {
|
|
669
|
+
event.stacktrace = readBacktraceFile(btData)
|
|
670
|
+
try? FileManager.default.removeItem(at: backtraceURL)
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
var recoveredSessionId: String?
|
|
674
|
+
var recoveredSessionStartedAt: Date?
|
|
675
|
+
var recoveredErrorCount = 0
|
|
676
|
+
if let contextData = try? Data(contentsOf: contextURL) {
|
|
677
|
+
let decoder = JSONDecoder()
|
|
678
|
+
decoder.dateDecodingStrategy = .iso8601
|
|
679
|
+
if let ctx = try? decoder.decode(PersistedContext.self, from: contextData) {
|
|
680
|
+
event.breadcrumbs = ctx.breadcrumbs
|
|
681
|
+
event.tags = ctx.tags.isEmpty ? nil : ctx.tags
|
|
682
|
+
event.extra = ctx.extra.isEmpty ? nil : ctx.extra
|
|
683
|
+
event.user = ctx.user
|
|
684
|
+
event.environment = ctx.environment
|
|
685
|
+
event.release = ctx.release
|
|
686
|
+
recoveredSessionId = ctx.sessionId
|
|
687
|
+
recoveredSessionStartedAt = ctx.sessionStartedAt
|
|
688
|
+
recoveredErrorCount = ctx.sessionErrorCount ?? 0
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// Clean up persisted context
|
|
693
|
+
try? FileManager.default.removeItem(at: contextURL)
|
|
694
|
+
|
|
695
|
+
// Fill in defaults from current config if context was missing
|
|
696
|
+
if event.environment == nil { event.environment = configuration?.environment }
|
|
697
|
+
if event.release == nil { event.release = configuration?.release }
|
|
698
|
+
|
|
699
|
+
// Send it
|
|
700
|
+
sendEvent(event)
|
|
701
|
+
|
|
702
|
+
// Session-crashed close for the signal path. The NSException hook
|
|
703
|
+
// marks the session crashed AT crash time; the signal handler cannot
|
|
704
|
+
// (async-signal-safe only), so before this fix abort/segv crashes
|
|
705
|
+
// never counted against crash-free sessions. The session id / start
|
|
706
|
+
// were persisted proactively during the crashed run — send its
|
|
707
|
+
// "crashed" close now, mirroring sendSessionEvent's payload.
|
|
708
|
+
if let sessionId = recoveredSessionId {
|
|
709
|
+
sendRecoveredCrashedSession(
|
|
710
|
+
sessionId: sessionId,
|
|
711
|
+
startedAt: recoveredSessionStartedAt,
|
|
712
|
+
errorsCount: recoveredErrorCount,
|
|
713
|
+
crashedAt: crashedAt,
|
|
714
|
+
environment: event.environment,
|
|
715
|
+
release: event.release
|
|
716
|
+
)
|
|
717
|
+
}
|
|
718
|
+
return true
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/// Parse the binary backtrace file written by the signal handler.
|
|
722
|
+
/// Layout: Int32 signal | Int32 frameCount | frameCount * UInt addresses
|
|
723
|
+
/// Resolves each address with `dladdr()` for symbol name, image path,
|
|
724
|
+
/// and symbol offset. Sends raw addresses alongside for server-side symbolication.
|
|
725
|
+
private func readBacktraceFile(_ data: Data) -> [SKStackFrame] {
|
|
726
|
+
let int32Size = MemoryLayout<Int32>.size
|
|
727
|
+
let uintSize = MemoryLayout<UInt>.size
|
|
728
|
+
|
|
729
|
+
// Skip signal number (first Int32) — already captured from marker file
|
|
730
|
+
guard data.count >= int32Size * 2 else { return [] }
|
|
731
|
+
|
|
732
|
+
let frameCount: Int32 = data.withUnsafeBytes { buf in
|
|
733
|
+
buf.load(fromByteOffset: int32Size, as: Int32.self)
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
let expectedSize = int32Size * 2 + Int(frameCount) * uintSize
|
|
737
|
+
guard frameCount > 0, data.count >= expectedSize else { return [] }
|
|
738
|
+
|
|
739
|
+
let appExecutable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
|
|
740
|
+
var frames: [SKStackFrame] = []
|
|
741
|
+
|
|
742
|
+
for i in 0..<Int(frameCount) {
|
|
743
|
+
let offset = int32Size * 2 + i * uintSize
|
|
744
|
+
let addr: UInt = data.withUnsafeBytes { buf in
|
|
745
|
+
buf.load(fromByteOffset: offset, as: UInt.self)
|
|
746
|
+
}
|
|
747
|
+
frames.append(symbolicate(address: addr, appExecutable: appExecutable))
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
return frames
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/// Resolve a single instruction address into a structured frame via
|
|
754
|
+
/// `dladdr()` — symbol name, image name, in-app heuristic. The raw
|
|
755
|
+
/// address is always carried in `instructionAddress` for server-side
|
|
756
|
+
/// symbolication. Shared by the signal-backtrace recovery path and the
|
|
757
|
+
/// ANR main-thread stack walker.
|
|
758
|
+
private func symbolicate(address: UInt, appExecutable: String?) -> SKStackFrame {
|
|
759
|
+
var info = Dl_info()
|
|
760
|
+
let resolved = dladdr(UnsafeRawPointer(bitPattern: address), &info) != 0
|
|
761
|
+
|
|
762
|
+
let symbolName: String?
|
|
763
|
+
let imageName: String?
|
|
764
|
+
let isInApp: Bool
|
|
765
|
+
|
|
766
|
+
if resolved {
|
|
767
|
+
symbolName = info.dli_sname.map { String(cString: $0) }
|
|
768
|
+
if let fname = info.dli_fname {
|
|
769
|
+
let fullPath = String(cString: fname)
|
|
770
|
+
imageName = (fullPath as NSString).lastPathComponent
|
|
771
|
+
} else {
|
|
772
|
+
imageName = nil
|
|
773
|
+
}
|
|
774
|
+
if let appExec = appExecutable {
|
|
775
|
+
isInApp = imageName == appExec
|
|
776
|
+
} else {
|
|
777
|
+
let img = imageName ?? ""
|
|
778
|
+
isInApp = !img.hasPrefix("lib") && !img.hasPrefix("_")
|
|
779
|
+
&& img != "UIKitCore" && img != "Foundation"
|
|
780
|
+
&& img != "CoreFoundation" && img != "libdyld.dylib"
|
|
781
|
+
}
|
|
782
|
+
} else {
|
|
783
|
+
symbolName = nil
|
|
784
|
+
imageName = nil
|
|
785
|
+
isInApp = false
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
return SKStackFrame(
|
|
789
|
+
filename: nil,
|
|
790
|
+
function: symbolName,
|
|
791
|
+
module: imageName,
|
|
792
|
+
lineno: nil,
|
|
793
|
+
colno: nil,
|
|
794
|
+
instructionAddress: String(format: "0x%016lx", address),
|
|
795
|
+
inApp: isInApp
|
|
796
|
+
)
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
internal func writeCrashToDisk(_ event: SKErrorEvent) {
|
|
800
|
+
let encoder = JSONEncoder()
|
|
801
|
+
encoder.dateEncodingStrategy = .iso8601
|
|
802
|
+
guard let data = try? encoder.encode(event) else { return }
|
|
803
|
+
try? FileManager.default.createDirectory(
|
|
804
|
+
at: SKCrashReporting.crashDirectory,
|
|
805
|
+
withIntermediateDirectories: true
|
|
806
|
+
)
|
|
807
|
+
try? data.write(to: SKCrashReporting.pendingCrashURL, options: .atomic)
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// MARK: - Crash Handlers
|
|
811
|
+
|
|
812
|
+
private func installUncaughtExceptionHandler() {
|
|
813
|
+
NSSetUncaughtExceptionHandler { exception in
|
|
814
|
+
let reporting = SKCrashReporting.shared
|
|
815
|
+
var event = SKErrorEvent(level: .fatal)
|
|
816
|
+
event.exceptionType = exception.name.rawValue
|
|
817
|
+
event.exceptionValue = exception.reason
|
|
818
|
+
event.mechanism = "nsexception"
|
|
819
|
+
event.stacktrace = reporting.parseCallStackSymbols(exception.callStackSymbols)
|
|
820
|
+
event.breadcrumbs = reporting.queue.sync { reporting.breadcrumbs.snapshot() }
|
|
821
|
+
event.tags = reporting.scope.tags.isEmpty ? nil : reporting.scope.tags
|
|
822
|
+
event.user = reporting.scope.user
|
|
823
|
+
event.environment = reporting.configuration?.environment
|
|
824
|
+
event.release = reporting.configuration?.release
|
|
825
|
+
reporting.applyDeviceContext(to: &event)
|
|
826
|
+
reporting.writeCrashToDisk(event)
|
|
827
|
+
// Mark session as crashed
|
|
828
|
+
reporting.sendSessionEvent(status: "crashed")
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
private func installSignalHandlers() {
|
|
833
|
+
// Persist initial context so there is something on disk for signal recovery
|
|
834
|
+
queue.async { [weak self] in self?.persistContextToDisk() }
|
|
835
|
+
|
|
836
|
+
let signals = [SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP]
|
|
837
|
+
for sig in signals {
|
|
838
|
+
signal(sig) { signum in
|
|
839
|
+
// ASYNC-SIGNAL-SAFE: only POSIX write(), open(), close(), backtrace().
|
|
840
|
+
// No Swift objects, no ObjC, no malloc.
|
|
841
|
+
let path = SKCrashReporting.signalMarkerPathCString
|
|
842
|
+
guard !path.isEmpty else {
|
|
843
|
+
signal(signum, SIG_DFL)
|
|
844
|
+
raise(signum)
|
|
845
|
+
return
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// Convert signal number to ASCII digits (no String allocation)
|
|
849
|
+
var numBuf: [UInt8] = Array(repeating: 0, count: 12)
|
|
850
|
+
var n = signum < 0 ? -Int(signum) : Int(signum)
|
|
851
|
+
var idx = numBuf.count - 1
|
|
852
|
+
if n == 0 {
|
|
853
|
+
numBuf[idx] = 0x30 // '0'
|
|
854
|
+
idx -= 1
|
|
855
|
+
} else {
|
|
856
|
+
while n > 0 && idx >= 0 {
|
|
857
|
+
numBuf[idx] = UInt8(0x30 + (n % 10))
|
|
858
|
+
n /= 10
|
|
859
|
+
idx -= 1
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
if signum < 0 && idx >= 0 {
|
|
863
|
+
numBuf[idx] = 0x2D // '-'
|
|
864
|
+
idx -= 1
|
|
865
|
+
}
|
|
866
|
+
let start = idx + 1
|
|
867
|
+
let length = numBuf.count - start
|
|
868
|
+
|
|
869
|
+
// Open, write signal number, close — all POSIX async-signal-safe
|
|
870
|
+
path.withUnsafeBufferPointer { buf in
|
|
871
|
+
let fd = open(buf.baseAddress!, O_WRONLY | O_CREAT | O_TRUNC, 0o644)
|
|
872
|
+
if fd >= 0 {
|
|
873
|
+
numBuf.withUnsafeMutableBufferPointer { numPtr in
|
|
874
|
+
_ = write(fd, numPtr.baseAddress! + start, length)
|
|
875
|
+
}
|
|
876
|
+
close(fd)
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// Capture stack trace via backtrace() — async-signal-safe on macOS/iOS.
|
|
881
|
+
// Write raw addresses as binary (signal number as Int32 + frame count
|
|
882
|
+
// as Int32 + N UInt pointers).
|
|
883
|
+
let btPath = SKCrashReporting.backtracePathCString
|
|
884
|
+
if !btPath.isEmpty {
|
|
885
|
+
var callstack = [UnsafeMutableRawPointer?](repeating: nil, count: 128)
|
|
886
|
+
let frameCount = backtrace(&callstack, 128)
|
|
887
|
+
|
|
888
|
+
btPath.withUnsafeBufferPointer { buf in
|
|
889
|
+
let fd = open(buf.baseAddress!, O_WRONLY | O_CREAT | O_TRUNC, 0o644)
|
|
890
|
+
if fd >= 0 {
|
|
891
|
+
var sigCopy = signum
|
|
892
|
+
withUnsafePointer(to: &sigCopy) { ptr in
|
|
893
|
+
_ = write(fd, ptr, MemoryLayout<Int32>.size)
|
|
894
|
+
}
|
|
895
|
+
var count = frameCount
|
|
896
|
+
withUnsafePointer(to: &count) { ptr in
|
|
897
|
+
_ = write(fd, ptr, MemoryLayout<Int32>.size)
|
|
898
|
+
}
|
|
899
|
+
for i in 0..<Int(frameCount) {
|
|
900
|
+
var addr = UInt(bitPattern: callstack[i])
|
|
901
|
+
withUnsafePointer(to: &addr) { ptr in
|
|
902
|
+
_ = write(fd, ptr, MemoryLayout<UInt>.size)
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
close(fd)
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// Re-raise to allow OS crash reporter to run
|
|
911
|
+
signal(signum, SIG_DFL)
|
|
912
|
+
raise(signum)
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// MARK: - ANR Watchdog
|
|
918
|
+
|
|
919
|
+
private func startANRWatchdog() {
|
|
920
|
+
guard let timeout = configuration?.anrTimeoutSeconds, timeout > 0 else { return }
|
|
921
|
+
anrWatchdogRunning = true
|
|
922
|
+
DispatchQueue.global(qos: .background).async { [weak self] in
|
|
923
|
+
while self?.anrWatchdogRunning == true {
|
|
924
|
+
var responded = false
|
|
925
|
+
DispatchQueue.main.async { responded = true }
|
|
926
|
+
Thread.sleep(forTimeInterval: timeout)
|
|
927
|
+
if self?.anrWatchdogRunning == true && !responded {
|
|
928
|
+
self?.captureANR()
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
private func stopANRWatchdog() {
|
|
935
|
+
anrWatchdogRunning = false
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
private func captureANR() {
|
|
939
|
+
// Capture main thread stack trace via thread_get_state if possible,
|
|
940
|
+
// otherwise fall back to current thread symbols as a hint.
|
|
941
|
+
let frames = captureMainThreadStack()
|
|
942
|
+
|
|
943
|
+
var event = buildEvent(level: .error)
|
|
944
|
+
event.message = "Application Not Responding"
|
|
945
|
+
event.mechanism = "anr"
|
|
946
|
+
event.stacktrace = frames
|
|
947
|
+
guard let finalEvent = applyBeforeSend(event) else { return }
|
|
948
|
+
sendEvent(finalEvent)
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/// Capture the main thread's stack trace using Mach thread APIs.
|
|
952
|
+
///
|
|
953
|
+
/// The watchdog thread suspends the main thread, reads its register
|
|
954
|
+
/// state (`pc` / `lr` / `fp`), walks the frame-pointer chain reading
|
|
955
|
+
/// each frame record via `vm_read_overwrite` (fails soft on bad memory
|
|
956
|
+
/// instead of faulting), resumes the thread, and only THEN symbolicates
|
|
957
|
+
/// via `dladdr`. NOTHING between suspend and resume may allocate — if
|
|
958
|
+
/// the main thread hung while holding the malloc lock, an allocation
|
|
959
|
+
/// here would deadlock the watchdog against it. The address buffer is
|
|
960
|
+
/// therefore pre-allocated before the suspend.
|
|
961
|
+
///
|
|
962
|
+
/// Falls back to the watchdog thread's own `Thread.callStackSymbols`
|
|
963
|
+
/// (far less useful, but a signal that an ANR happened) if the main
|
|
964
|
+
/// thread cannot be inspected.
|
|
965
|
+
private func captureMainThreadStack() -> [SKStackFrame] {
|
|
966
|
+
// Only ever inspect the main thread from OFF the main thread —
|
|
967
|
+
// suspending yourself never resumes.
|
|
968
|
+
guard !Thread.isMainThread else {
|
|
969
|
+
return parseCallStackSymbols(Thread.callStackSymbols)
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
var threadList: thread_act_array_t?
|
|
973
|
+
var threadCount: mach_msg_type_number_t = 0
|
|
974
|
+
guard task_threads(mach_task_self_, &threadList, &threadCount) == KERN_SUCCESS,
|
|
975
|
+
let threads = threadList, threadCount > 0 else {
|
|
976
|
+
return parseCallStackSymbols(Thread.callStackSymbols)
|
|
977
|
+
}
|
|
978
|
+
defer {
|
|
979
|
+
let ptr = UnsafeMutableRawPointer(threads)
|
|
980
|
+
vm_deallocate(
|
|
981
|
+
mach_task_self_,
|
|
982
|
+
vm_address_t(bitPattern: ptr),
|
|
983
|
+
vm_size_t(threadCount) * vm_size_t(MemoryLayout<thread_act_t>.size)
|
|
984
|
+
)
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// The first thread returned by task_threads is the main thread.
|
|
988
|
+
let mainThread = threads[0]
|
|
989
|
+
|
|
990
|
+
// Pre-allocate the address buffer BEFORE suspending (see doc comment).
|
|
991
|
+
let maxFrames = 128
|
|
992
|
+
var addresses = [UInt](repeating: 0, count: maxFrames)
|
|
993
|
+
var addressCount = 0
|
|
994
|
+
|
|
995
|
+
guard thread_suspend(mainThread) == KERN_SUCCESS else {
|
|
996
|
+
return parseCallStackSymbols(Thread.callStackSymbols)
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
var pc: UInt = 0
|
|
1000
|
+
var lr: UInt = 0
|
|
1001
|
+
var fp: UInt = 0
|
|
1002
|
+
|
|
1003
|
+
#if arch(arm64)
|
|
1004
|
+
var state = arm_thread_state64_t()
|
|
1005
|
+
var stateCount = mach_msg_type_number_t(
|
|
1006
|
+
MemoryLayout<arm_thread_state64_t>.size / MemoryLayout<natural_t>.size
|
|
1007
|
+
)
|
|
1008
|
+
let stateResult = withUnsafeMutablePointer(to: &state) { statePtr in
|
|
1009
|
+
statePtr.withMemoryRebound(to: natural_t.self, capacity: Int(stateCount)) { ptr in
|
|
1010
|
+
thread_get_state(mainThread, ARM_THREAD_STATE64, ptr, &stateCount)
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
if stateResult == KERN_SUCCESS {
|
|
1014
|
+
pc = UInt(state.__pc)
|
|
1015
|
+
lr = SKCrashReporting.stripPtrAuth(UInt(state.__lr))
|
|
1016
|
+
fp = UInt(state.__fp)
|
|
1017
|
+
}
|
|
1018
|
+
#else
|
|
1019
|
+
var state = x86_thread_state64_t()
|
|
1020
|
+
var stateCount = mach_msg_type_number_t(
|
|
1021
|
+
MemoryLayout<x86_thread_state64_t>.size / MemoryLayout<natural_t>.size
|
|
1022
|
+
)
|
|
1023
|
+
let stateResult = withUnsafeMutablePointer(to: &state) { statePtr in
|
|
1024
|
+
statePtr.withMemoryRebound(to: natural_t.self, capacity: Int(stateCount)) { ptr in
|
|
1025
|
+
thread_get_state(mainThread, x86_THREAD_STATE64, ptr, &stateCount)
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
if stateResult == KERN_SUCCESS {
|
|
1029
|
+
pc = UInt(state.__rip)
|
|
1030
|
+
lr = 0 // no link register on x86_64 — return addr comes off the stack
|
|
1031
|
+
fp = UInt(state.__rbp)
|
|
1032
|
+
}
|
|
1033
|
+
#endif
|
|
1034
|
+
|
|
1035
|
+
if stateResult == KERN_SUCCESS {
|
|
1036
|
+
if pc != 0 {
|
|
1037
|
+
addresses[addressCount] = pc
|
|
1038
|
+
addressCount += 1
|
|
1039
|
+
}
|
|
1040
|
+
if lr != 0, addressCount < maxFrames {
|
|
1041
|
+
addresses[addressCount] = lr
|
|
1042
|
+
addressCount += 1
|
|
1043
|
+
}
|
|
1044
|
+
// Walk the frame-pointer chain. On both arm64 and x86_64 the
|
|
1045
|
+
// frame record at `fp` is two pointers: [fp] = caller's frame
|
|
1046
|
+
// pointer, [fp + 8] = return address. Reads go through
|
|
1047
|
+
// vm_read_overwrite so a corrupt / exotic frame ends the walk
|
|
1048
|
+
// gracefully instead of faulting the watchdog thread.
|
|
1049
|
+
var currentFP = fp
|
|
1050
|
+
while currentFP != 0, addressCount < maxFrames {
|
|
1051
|
+
var record: (previous: UInt, returnAddress: UInt) = (0, 0)
|
|
1052
|
+
var outSize: vm_size_t = 0
|
|
1053
|
+
let kr = withUnsafeMutablePointer(to: &record) { recordPtr -> kern_return_t in
|
|
1054
|
+
vm_read_overwrite(
|
|
1055
|
+
mach_task_self_,
|
|
1056
|
+
vm_address_t(currentFP),
|
|
1057
|
+
vm_size_t(MemoryLayout<UInt>.size * 2),
|
|
1058
|
+
vm_address_t(bitPattern: UnsafeMutableRawPointer(recordPtr)),
|
|
1059
|
+
&outSize
|
|
1060
|
+
)
|
|
1061
|
+
}
|
|
1062
|
+
guard kr == KERN_SUCCESS, outSize >= vm_size_t(MemoryLayout<UInt>.size * 2) else { break }
|
|
1063
|
+
let returnAddress = SKCrashReporting.stripPtrAuth(record.returnAddress)
|
|
1064
|
+
if returnAddress == 0 { break }
|
|
1065
|
+
addresses[addressCount] = returnAddress
|
|
1066
|
+
addressCount += 1
|
|
1067
|
+
// Stacks grow down, so the caller's frame pointer must be
|
|
1068
|
+
// strictly higher — anything else is a cycle or corruption.
|
|
1069
|
+
guard record.previous > currentFP else { break }
|
|
1070
|
+
currentFP = record.previous
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
thread_resume(mainThread)
|
|
1075
|
+
|
|
1076
|
+
guard addressCount > 0 else {
|
|
1077
|
+
// State capture failed — fall back to the watchdog thread's own
|
|
1078
|
+
// symbols as a last-resort hint that an ANR happened.
|
|
1079
|
+
return parseCallStackSymbols(Thread.callStackSymbols)
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// Main thread is running again — safe to allocate and symbolicate.
|
|
1083
|
+
let appExecutable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
|
|
1084
|
+
return (0..<addressCount).map { symbolicate(address: addresses[$0], appExecutable: appExecutable) }
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/// Strip arm64e pointer-authentication bits from a code address.
|
|
1088
|
+
/// Userspace code pointers on iOS fit in the low 36 bits; PAC signature
|
|
1089
|
+
/// bits live above. Same mask Sentry / PLCrashReporter use. No-op for
|
|
1090
|
+
/// plain arm64 / x86_64 addresses.
|
|
1091
|
+
private static func stripPtrAuth(_ address: UInt) -> UInt {
|
|
1092
|
+
#if arch(arm64)
|
|
1093
|
+
return address & 0x0000_000F_FFFF_FFFF
|
|
1094
|
+
#else
|
|
1095
|
+
return address
|
|
1096
|
+
#endif
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
// MARK: - Session Tracking
|
|
1100
|
+
|
|
1101
|
+
private func startSession() {
|
|
1102
|
+
sessionErrorCount = 0
|
|
1103
|
+
sendSessionEvent(status: "started")
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
private func endSession() {
|
|
1107
|
+
sendSessionEvent(status: "ended")
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
private func sendSessionEvent(status: String) {
|
|
1111
|
+
guard let config = configuration else { return }
|
|
1112
|
+
// Source session_id (and start time) from the canonical Session
|
|
1113
|
+
// primitive so the data payload agrees with the envelope-level
|
|
1114
|
+
// ContextSnapshot.session_id. No more divergent IDs.
|
|
1115
|
+
let snapshot = Session.shared.current
|
|
1116
|
+
let duration = Date().timeIntervalSince(snapshot.startedAt)
|
|
1117
|
+
|
|
1118
|
+
let body: [String: Any] = [
|
|
1119
|
+
"sessionId": snapshot.id,
|
|
1120
|
+
"status": status,
|
|
1121
|
+
"duration": duration,
|
|
1122
|
+
"errorsCount": sessionErrorCount,
|
|
1123
|
+
"releaseVersion": config.release ?? "",
|
|
1124
|
+
"environment": config.environment,
|
|
1125
|
+
"osName": "iOS",
|
|
1126
|
+
"osVersion": ProcessInfo.processInfo.operatingSystemVersionString,
|
|
1127
|
+
"deviceModel": deviceModel()
|
|
1128
|
+
]
|
|
1129
|
+
ingest.enqueue(type: .session, jsonObject: body)
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/// Session close for a signal-terminated PREVIOUS run, sent on next-launch
|
|
1133
|
+
/// recovery (see `flushSignalMarker`). Mirrors `sendSessionEvent(status:)`'s
|
|
1134
|
+
/// payload key-for-key, but sources session id / start / error count from
|
|
1135
|
+
/// the persisted context of the run that crashed — the current
|
|
1136
|
+
/// `Session.shared` snapshot belongs to the NEW launch. Like the
|
|
1137
|
+
/// NSException path's crash-time session event, the enclosing envelope's
|
|
1138
|
+
/// `ContextSnapshot.session_id` is stamped at flush time (new session);
|
|
1139
|
+
/// consumers read the crashed session from `data.sessionId`.
|
|
1140
|
+
private func sendRecoveredCrashedSession(
|
|
1141
|
+
sessionId: String,
|
|
1142
|
+
startedAt: Date?,
|
|
1143
|
+
errorsCount: Int,
|
|
1144
|
+
crashedAt: Date,
|
|
1145
|
+
environment: String?,
|
|
1146
|
+
release: String?
|
|
1147
|
+
) {
|
|
1148
|
+
guard let config = configuration else { return }
|
|
1149
|
+
let duration = startedAt.map { max(0, crashedAt.timeIntervalSince($0)) } ?? 0
|
|
1150
|
+
let body: [String: Any] = [
|
|
1151
|
+
"sessionId": sessionId,
|
|
1152
|
+
"status": "crashed",
|
|
1153
|
+
"duration": duration,
|
|
1154
|
+
"errorsCount": errorsCount,
|
|
1155
|
+
"releaseVersion": release ?? config.release ?? "",
|
|
1156
|
+
"environment": environment ?? config.environment,
|
|
1157
|
+
"osName": "iOS",
|
|
1158
|
+
"osVersion": ProcessInfo.processInfo.operatingSystemVersionString,
|
|
1159
|
+
"deviceModel": deviceModel()
|
|
1160
|
+
]
|
|
1161
|
+
ingest.enqueue(type: .session, jsonObject: body)
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// MARK: - Auto-Breadcrumbs
|
|
1165
|
+
|
|
1166
|
+
private func registerLifecycleObservers() {
|
|
1167
|
+
let nc = NotificationCenter.default
|
|
1168
|
+
#if canImport(UIKit)
|
|
1169
|
+
nc.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] _ in
|
|
1170
|
+
self?.addBreadcrumb(SKBreadcrumb(category: "app.lifecycle", message: "didBecomeActive", level: .info))
|
|
1171
|
+
}
|
|
1172
|
+
nc.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { [weak self] _ in
|
|
1173
|
+
self?.addBreadcrumb(SKBreadcrumb(category: "app.lifecycle", message: "willResignActive", level: .info))
|
|
1174
|
+
}
|
|
1175
|
+
nc.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { [weak self] _ in
|
|
1176
|
+
self?.addBreadcrumb(SKBreadcrumb(category: "app.lifecycle", message: "didEnterBackground", level: .info))
|
|
1177
|
+
self?.endSession()
|
|
1178
|
+
}
|
|
1179
|
+
#endif
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// MARK: - Helpers
|
|
1183
|
+
|
|
1184
|
+
private func currentStackFrames() -> [SKStackFrame] {
|
|
1185
|
+
let symbols = Thread.callStackSymbols
|
|
1186
|
+
let addresses = Thread.callStackReturnAddresses
|
|
1187
|
+
return parseCallStackSymbols(symbols, returnAddresses: addresses.map { $0.intValue })
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
/// Parse `Thread.callStackSymbols` into structured stack frames.
|
|
1191
|
+
/// Each line has the format:
|
|
1192
|
+
/// `<frame_number> <image_name> <address> <symbol> + <offset>`
|
|
1193
|
+
/// e.g. `0 MyApp 0x0000000104a8b1c4 $s5MyApp14ViewControllerC11viewDidLoadyyF + 84`
|
|
1194
|
+
internal func parseCallStackSymbols(_ symbols: [String], returnAddresses: [Int] = []) -> [SKStackFrame] {
|
|
1195
|
+
let appExecutable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
|
|
1196
|
+
|
|
1197
|
+
return symbols.enumerated().map { index, symbol in
|
|
1198
|
+
let trimmed = symbol.trimmingCharacters(in: .whitespaces)
|
|
1199
|
+
|
|
1200
|
+
// Regex-free parsing: split by whitespace groups
|
|
1201
|
+
// Format: <frame#> <image> <address> <symbol> + <offset>
|
|
1202
|
+
let parts = trimmed.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true)
|
|
1203
|
+
guard parts.count >= 4 else {
|
|
1204
|
+
return SKStackFrame(function: trimmed, inApp: false)
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
let imageName = String(parts[1])
|
|
1208
|
+
let addressStr = String(parts[2])
|
|
1209
|
+
|
|
1210
|
+
// The remainder is "<symbol> + <offset>" — split off the trailing " + <number>"
|
|
1211
|
+
let remainder = String(parts[3])
|
|
1212
|
+
let functionName: String
|
|
1213
|
+
if let plusRange = remainder.range(of: " + ", options: .backwards) {
|
|
1214
|
+
functionName = String(remainder[remainder.startIndex..<plusRange.lowerBound])
|
|
1215
|
+
} else {
|
|
1216
|
+
functionName = remainder
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
// Use raw return address if available for better symbolication later
|
|
1220
|
+
let rawAddress: String?
|
|
1221
|
+
if index < returnAddresses.count {
|
|
1222
|
+
rawAddress = String(format: "0x%016lx", returnAddresses[index])
|
|
1223
|
+
} else {
|
|
1224
|
+
rawAddress = addressStr.hasPrefix("0x") ? addressStr : nil
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
let isInApp: Bool
|
|
1228
|
+
if let appExec = appExecutable {
|
|
1229
|
+
isInApp = imageName == appExec
|
|
1230
|
+
} else {
|
|
1231
|
+
isInApp = !imageName.hasPrefix("lib") && !imageName.hasPrefix("_")
|
|
1232
|
+
&& imageName != "UIKitCore" && imageName != "Foundation"
|
|
1233
|
+
&& imageName != "CoreFoundation" && imageName != "libdyld.dylib"
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
return SKStackFrame(
|
|
1237
|
+
filename: nil,
|
|
1238
|
+
function: functionName,
|
|
1239
|
+
module: imageName,
|
|
1240
|
+
lineno: nil,
|
|
1241
|
+
colno: nil,
|
|
1242
|
+
instructionAddress: rawAddress,
|
|
1243
|
+
inApp: isInApp
|
|
1244
|
+
)
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
private func mergeTags(_ base: [String: String], _ override: [String: String]) -> [String: String] {
|
|
1249
|
+
var result = base
|
|
1250
|
+
for (k, v) in override { result[k] = v }
|
|
1251
|
+
return result
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
private func deviceModel() -> String {
|
|
1255
|
+
var info = utsname()
|
|
1256
|
+
uname(&info)
|
|
1257
|
+
return withUnsafeBytes(of: &info.machine) { rawPtr -> String in
|
|
1258
|
+
let ptr = rawPtr.baseAddress!.assumingMemoryBound(to: CChar.self)
|
|
1259
|
+
return String(cString: ptr)
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// MARK: - Test Hooks
|
|
1264
|
+
|
|
1265
|
+
internal func _snapshotBreadcrumbs() -> [SKBreadcrumb] {
|
|
1266
|
+
queue.sync { breadcrumbs.snapshot() }
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
internal func _clearBreadcrumbs() {
|
|
1270
|
+
queue.sync { breadcrumbs.clear() }
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/// Test seam — swap in a custom IngestClient instance so tests can
|
|
1274
|
+
/// assert what was enqueued without exercising the shared singleton's
|
|
1275
|
+
/// disk queue. Pass `nil`/the shared singleton in tearDown to restore.
|
|
1276
|
+
internal func _setIngestForTesting(_ client: IngestClient) {
|
|
1277
|
+
self.ingest = client
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/// Test seam — expose `buildEvent(level:)` so the envelope-redundancy
|
|
1281
|
+
/// regression test can inspect what the event-construction path stamps.
|
|
1282
|
+
internal func _buildEventForTesting(level: SKErrorLevel) -> SKErrorEvent {
|
|
1283
|
+
buildEvent(level: level)
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
internal var _pendingCrashURL: URL { SKCrashReporting.pendingCrashURL }
|
|
1287
|
+
}
|