@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.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/CHANGELOG.md +465 -0
- package/LICENSE +21 -0
- package/README.md +229 -42
- package/SwissKnifePurchases.podspec +1 -1
- package/android/build.gradle +24 -2
- package/android/consumer-rules.pro +12 -0
- package/android/src/main/AndroidManifest.xml +15 -1
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
- package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
- package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
- package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
- package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
- package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
- package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
- package/android/vendor-rustore/AndroidManifest.xml +59 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
- package/app.plugin.js +287 -0
- package/ios/SwissKnifePurchases.m +20 -0
- package/ios/SwissKnifePurchases.swift +97 -3
- package/ios/SwissKnifePushBootstrap.m +34 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
- package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
- package/lib/commonjs/attribution.js +4 -3
- package/lib/commonjs/attribution.js.map +1 -1
- package/lib/commonjs/identity.js +12 -11
- package/lib/commonjs/identity.js.map +1 -1
- package/lib/commonjs/index.js +16 -5
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/config.js +105 -8
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/internal/telemetry-context.js +70 -0
- package/lib/commonjs/internal/telemetry-context.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +18 -25
- package/lib/commonjs/modules/analytics.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +353 -31
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/commonjs/modules/log.js +1 -1
- package/lib/commonjs/modules/notifications.js +500 -0
- package/lib/commonjs/modules/notifications.js.map +1 -0
- package/lib/commonjs/modules/performance.js +57 -8
- package/lib/commonjs/modules/performance.js.map +1 -1
- package/lib/commonjs/native/module.js +6 -0
- package/lib/commonjs/native/module.js.map +1 -1
- package/lib/commonjs/native/spec.js +12 -5
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/purchases.js +4 -4
- package/lib/commonjs/types.js +12 -15
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/attribution.js +4 -3
- package/lib/module/attribution.js.map +1 -1
- package/lib/module/identity.js +12 -11
- package/lib/module/identity.js.map +1 -1
- package/lib/module/index.js +8 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/config.js +103 -8
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/internal/telemetry-context.js +63 -0
- package/lib/module/internal/telemetry-context.js.map +1 -0
- package/lib/module/modules/analytics.js +18 -25
- package/lib/module/modules/analytics.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +353 -31
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/log.js +1 -1
- package/lib/module/modules/notifications.js +491 -0
- package/lib/module/modules/notifications.js.map +1 -0
- package/lib/module/modules/performance.js +57 -8
- package/lib/module/modules/performance.js.map +1 -1
- package/lib/module/native/module.js +6 -1
- package/lib/module/native/module.js.map +1 -1
- package/lib/module/native/spec.js +11 -4
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/purchases.js +4 -4
- package/lib/module/types.js +12 -15
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/attribution.d.ts +3 -2
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
- package/lib/typescript/commonjs/identity.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +3 -1
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts +16 -2
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
- package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/module.d.ts +2 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +33 -4
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/purchases.d.ts +4 -4
- package/lib/typescript/commonjs/types.d.ts +4 -5
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/attribution.d.ts +3 -2
- package/lib/typescript/module/attribution.d.ts.map +1 -1
- package/lib/typescript/module/identity.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +3 -1
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts +16 -2
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +8 -11
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/notifications.d.ts +110 -0
- package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +13 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -1
- package/lib/typescript/module/native/module.d.ts +2 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +33 -4
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/purchases.d.ts +4 -4
- package/lib/typescript/module/types.d.ts +4 -5
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +13 -4
- package/src/attribution.ts +4 -3
- package/src/identity.ts +12 -11
- package/src/index.ts +18 -4
- package/src/internal/config.ts +113 -8
- package/src/internal/telemetry-context.ts +76 -0
- package/src/modules/analytics.ts +24 -33
- package/src/modules/crash-reporting.ts +476 -67
- package/src/modules/log.ts +1 -1
- package/src/modules/notifications.ts +557 -0
- package/src/modules/performance.ts +94 -14
- package/src/native/module.ts +6 -0
- package/src/native/spec.ts +45 -10
- package/src/purchases.ts +4 -4
- package/src/types.ts +12 -15
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
// Sentry-compatible crash reporting SDK for swiss-knife (Android).
|
|
4
4
|
// Captures uncaught JVM exceptions, ANRs, and breadcrumbs.
|
|
5
5
|
// On next init(), any pending crash is sent before normal operation resumes.
|
|
6
|
+
//
|
|
7
|
+
// Every report goes through ONE pipeline: IngestClient (disk queue, POST
|
|
8
|
+
// /ingest), wired by SwissKnife.configureCore / configure /
|
|
9
|
+
// ensureObservabilityBackend. See "Pre-configure buffer" below for what happens
|
|
10
|
+
// when crash reporting starts first. The direct /api/sdk/errors/event,
|
|
11
|
+
// /event/batch and /session fallbacks and their pending-queue.json are gone.
|
|
6
12
|
|
|
7
13
|
package com.appswissknife.crashreporting
|
|
8
14
|
|
|
@@ -21,10 +27,17 @@ import java.io.File
|
|
|
21
27
|
import java.text.SimpleDateFormat
|
|
22
28
|
import java.util.Date
|
|
23
29
|
import java.util.Locale
|
|
30
|
+
import java.util.TimeZone
|
|
31
|
+
import java.util.concurrent.ConcurrentHashMap
|
|
32
|
+
import java.util.concurrent.ConcurrentLinkedDeque
|
|
24
33
|
import java.util.concurrent.CopyOnWriteArrayList
|
|
25
34
|
import com.appswissknife.context.IDs
|
|
35
|
+
import com.appswissknife.diagnostics.SKLog
|
|
26
36
|
import com.appswissknife.identity.Identity
|
|
37
|
+
import com.appswissknife.net.IngestClient
|
|
38
|
+
import com.appswissknife.net.IngestItemType
|
|
27
39
|
import java.util.concurrent.Executors
|
|
40
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
28
41
|
|
|
29
42
|
// MARK: - Supporting Types
|
|
30
43
|
|
|
@@ -50,6 +63,27 @@ data class SKStackFrame(
|
|
|
50
63
|
}
|
|
51
64
|
}
|
|
52
65
|
|
|
66
|
+
/**
|
|
67
|
+
* The wire format of every error and breadcrumb timestamp: ISO-8601 in UTC,
|
|
68
|
+
* millisecond precision, e.g. `2023-11-14T22:13:20.123Z`.
|
|
69
|
+
*
|
|
70
|
+
* Both used to share a `SimpleDateFormat("...'Z'")` with no time zone set,
|
|
71
|
+
* so the device's LOCAL time went out labelled UTC (shifted by up to 14 h),
|
|
72
|
+
* and `SimpleDateFormat` is not thread-safe, so concurrent formatting could
|
|
73
|
+
* garble a value. One formatter per thread, pinned to UTC. (minSdk 24 has no
|
|
74
|
+
* java.time without desugaring.)
|
|
75
|
+
*/
|
|
76
|
+
internal object SKIsoTimestamp {
|
|
77
|
+
private val formatter = object : ThreadLocal<SimpleDateFormat>() {
|
|
78
|
+
override fun initialValue(): SimpleDateFormat =
|
|
79
|
+
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
|
|
80
|
+
timeZone = TimeZone.getTimeZone("UTC")
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
fun format(epochMillis: Long): String = formatter.get()!!.format(Date(epochMillis))
|
|
85
|
+
}
|
|
86
|
+
|
|
53
87
|
data class SKBreadcrumb(
|
|
54
88
|
val timestamp: Long = System.currentTimeMillis(),
|
|
55
89
|
val category: String? = null,
|
|
@@ -58,16 +92,12 @@ data class SKBreadcrumb(
|
|
|
58
92
|
val data: Map<String, String>? = null
|
|
59
93
|
) {
|
|
60
94
|
fun toJSON(): JSONObject = JSONObject().apply {
|
|
61
|
-
put("timestamp",
|
|
95
|
+
put("timestamp", SKIsoTimestamp.format(timestamp))
|
|
62
96
|
category?.let { put("category", it) }
|
|
63
97
|
message?.let { put("message", it) }
|
|
64
98
|
put("level", level.name.lowercase())
|
|
65
99
|
data?.let { put("data", JSONObject(it as Map<*, *>)) }
|
|
66
100
|
}
|
|
67
|
-
|
|
68
|
-
companion object {
|
|
69
|
-
private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
|
|
70
|
-
}
|
|
71
101
|
}
|
|
72
102
|
|
|
73
103
|
data class SKUser(
|
|
@@ -126,7 +156,7 @@ data class SKErrorEvent(
|
|
|
126
156
|
) {
|
|
127
157
|
fun toJSON(): JSONObject = JSONObject().apply {
|
|
128
158
|
put("eventId", eventId)
|
|
129
|
-
put("timestamp",
|
|
159
|
+
put("timestamp", SKIsoTimestamp.format(timestamp))
|
|
130
160
|
put("level", level.name.lowercase())
|
|
131
161
|
message?.let { put("message", it) }
|
|
132
162
|
exceptionType?.let { put("exceptionType", it) }
|
|
@@ -148,17 +178,16 @@ data class SKErrorEvent(
|
|
|
148
178
|
mechanism?.let { put("mechanism", it) }
|
|
149
179
|
put("platform", platform)
|
|
150
180
|
}
|
|
151
|
-
|
|
152
|
-
companion object {
|
|
153
|
-
private val ISO_DATE = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
|
|
154
|
-
}
|
|
155
181
|
}
|
|
156
182
|
|
|
157
183
|
// MARK: - Scope
|
|
158
184
|
|
|
159
185
|
class SKErrorScope {
|
|
160
|
-
|
|
161
|
-
|
|
186
|
+
// Written from any host thread while events are built (and copied) on
|
|
187
|
+
// others: concurrent maps, so a copy never throws
|
|
188
|
+
// ConcurrentModificationException.
|
|
189
|
+
internal val tags: MutableMap<String, String> = ConcurrentHashMap()
|
|
190
|
+
internal val extra: MutableMap<String, String> = ConcurrentHashMap()
|
|
162
191
|
internal var user: SKUser? = null
|
|
163
192
|
|
|
164
193
|
fun setTag(key: String, value: String) { tags[key] = value }
|
|
@@ -183,37 +212,82 @@ internal class RingBuffer<T>(private val capacity: Int) {
|
|
|
183
212
|
|
|
184
213
|
// MARK: - ANR Watchdog
|
|
185
214
|
|
|
215
|
+
/**
|
|
216
|
+
* Detects a blocked main thread by posting a ping and checking that it ran
|
|
217
|
+
* within [timeoutMs].
|
|
218
|
+
*
|
|
219
|
+
* **Latched:** one hang is reported exactly once. After a report the
|
|
220
|
+
* watchdog stops posting new pings and waits for the SAME ping to run; only
|
|
221
|
+
* once the main thread has responded does it re-arm. Before the latch, a
|
|
222
|
+
* 30-second hang produced six identical "Application Not Responding" events.
|
|
223
|
+
*
|
|
224
|
+
* [onRecover] fires when a reported hang ends (the main thread ran the
|
|
225
|
+
* ping), so the caller can drop state that only applies to a hang still in
|
|
226
|
+
* progress at process death.
|
|
227
|
+
*
|
|
228
|
+
* [postToMain] and [mainStack] are test seams; production uses the main
|
|
229
|
+
* Looper.
|
|
230
|
+
*/
|
|
186
231
|
internal class AnrWatchdog(
|
|
187
232
|
private val timeoutMs: Long,
|
|
188
|
-
|
|
233
|
+
postToMain: ((Runnable) -> Unit)? = null,
|
|
234
|
+
private val mainStack: () -> Array<StackTraceElement> = { Looper.getMainLooper().thread.stackTrace },
|
|
235
|
+
private val onRecover: () -> Unit = {},
|
|
236
|
+
private val onAnr: (Array<StackTraceElement>) -> Unit
|
|
189
237
|
) {
|
|
190
|
-
private val executor = Executors.newSingleThreadExecutor
|
|
191
|
-
|
|
238
|
+
private val executor = Executors.newSingleThreadExecutor { r ->
|
|
239
|
+
Thread(r, "sk-anr-watchdog").apply { isDaemon = true }
|
|
240
|
+
}
|
|
241
|
+
private val post: (Runnable) -> Unit = postToMain ?: run {
|
|
242
|
+
val handler = Handler(Looper.getMainLooper())
|
|
243
|
+
val fn: (Runnable) -> Unit = { r -> handler.post(r) }
|
|
244
|
+
fn
|
|
245
|
+
}
|
|
192
246
|
@Volatile private var active = false
|
|
193
247
|
|
|
194
248
|
fun start() {
|
|
195
249
|
active = true
|
|
196
250
|
executor.execute {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
251
|
+
try {
|
|
252
|
+
while (active) {
|
|
253
|
+
val responded = AtomicBoolean(false)
|
|
254
|
+
post(Runnable { responded.set(true) })
|
|
255
|
+
Thread.sleep(timeoutMs)
|
|
256
|
+
if (!active) break
|
|
257
|
+
if (responded.get()) continue
|
|
258
|
+
|
|
259
|
+
// Main thread did not respond — report this hang once.
|
|
260
|
+
try {
|
|
261
|
+
onAnr(mainStack())
|
|
262
|
+
} catch (_: Throwable) { /* never kill the watchdog */ }
|
|
263
|
+
|
|
264
|
+
// Latch: wait for the same ping before re-arming.
|
|
265
|
+
val pollMs = minOf(timeoutMs, 500L).coerceAtLeast(1L)
|
|
266
|
+
while (active && !responded.get()) Thread.sleep(pollMs)
|
|
267
|
+
if (active) {
|
|
268
|
+
try {
|
|
269
|
+
onRecover()
|
|
270
|
+
} catch (_: Throwable) { /* never kill the watchdog */ }
|
|
271
|
+
}
|
|
207
272
|
}
|
|
273
|
+
} catch (_: InterruptedException) {
|
|
274
|
+
// stop() — exit quietly
|
|
208
275
|
}
|
|
209
276
|
}
|
|
210
277
|
}
|
|
211
278
|
|
|
212
279
|
fun stop() {
|
|
213
280
|
active = false
|
|
281
|
+
executor.shutdownNow()
|
|
214
282
|
}
|
|
215
283
|
}
|
|
216
284
|
|
|
285
|
+
/**
|
|
286
|
+
* A watchdog-reported ANR, persisted so the next launch can recognise the
|
|
287
|
+
* matching `ApplicationExitInfo.REASON_ANR` record as the same hang.
|
|
288
|
+
*/
|
|
289
|
+
internal data class AnrMark(val pid: Int, val timestampMs: Long)
|
|
290
|
+
|
|
217
291
|
// MARK: - Main SDK
|
|
218
292
|
|
|
219
293
|
object SKCrashReporting {
|
|
@@ -239,7 +313,34 @@ object SKCrashReporting {
|
|
|
239
313
|
private val scope = SKErrorScope()
|
|
240
314
|
private var breadcrumbs = RingBuffer<SKBreadcrumb>(100)
|
|
241
315
|
private var anrWatchdog: AnrWatchdog? = null
|
|
316
|
+
|
|
317
|
+
// Uncaught-exception chaining. Installed ONCE per process: a second
|
|
318
|
+
// `init()` (the React Native bridge calls it again on every JS reload)
|
|
319
|
+
// used to capture our own handler as "original", so the next crash
|
|
320
|
+
// recursed until StackOverflowError and the host's handler never ran.
|
|
321
|
+
private val crashHandlerInstalled = AtomicBoolean(false)
|
|
322
|
+
@Volatile
|
|
242
323
|
private var originalExceptionHandler: Thread.UncaughtExceptionHandler? = null
|
|
324
|
+
|
|
325
|
+
private object CrashHandler : Thread.UncaughtExceptionHandler {
|
|
326
|
+
override fun uncaughtException(thread: Thread, throwable: Throwable) {
|
|
327
|
+
handleUncaughtException(thread, throwable)
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Lifecycle + connectivity callbacks: registered once per Application
|
|
332
|
+
// (they used to be added again on every `init()`).
|
|
333
|
+
@Volatile
|
|
334
|
+
private var lifecycleRegisteredOn: android.app.Application? = null
|
|
335
|
+
@Volatile
|
|
336
|
+
private var connectivityRegisteredOn: Context? = null
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Activities started and not yet stopped, by identity. Main thread only.
|
|
340
|
+
* The session ends when the last one stops (the app went to the
|
|
341
|
+
* background), not on every pause, which fired on each screen change.
|
|
342
|
+
*/
|
|
343
|
+
private val startedActivities = HashSet<Int>()
|
|
243
344
|
private val executor = Executors.newSingleThreadExecutor()
|
|
244
345
|
|
|
245
346
|
// Session tracking
|
|
@@ -258,10 +359,52 @@ object SKCrashReporting {
|
|
|
258
359
|
private const val FLUSH_INTERVAL_MS = 30_000L
|
|
259
360
|
private const val FLUSH_THRESHOLD = 10
|
|
260
361
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
362
|
+
// MARK: - Pre-configure buffer
|
|
363
|
+
//
|
|
364
|
+
// A host may call init() before SwissKnife.configureCore has wired
|
|
365
|
+
// IngestClient. Until it is wired:
|
|
366
|
+
// - reports from THIS process wait in memory, bounded: at most
|
|
367
|
+
// PRE_CONFIGURE_LIMIT captured events (in pendingEvents) and
|
|
368
|
+
// PRE_CONFIGURE_LIMIT other items (sessions, ANR / native-crash /
|
|
369
|
+
// captureEvent reports, in preConfigureItems), oldest dropped first;
|
|
370
|
+
// - reports from EARLIER processes stay where they already are, the
|
|
371
|
+
// crash files on disk (see "Pending crash files") and
|
|
372
|
+
// ApplicationExitInfo in the OS.
|
|
373
|
+
// An init() that finds IngestClient unwired starts a watch that hands all
|
|
374
|
+
// of it over within INGEST_WATCH_MS of the client being wired (for the
|
|
375
|
+
// first five minutes), then stops; the first delivery after that, the 30 s
|
|
376
|
+
// flush tick and flush() do the same. Nothing leaves the device before then.
|
|
377
|
+
internal const val PRE_CONFIGURE_LIMIT = 100
|
|
378
|
+
internal const val INGEST_WATCH_MS = 1_000L
|
|
379
|
+
private const val INGEST_WATCH_MAX_RUNS = 300
|
|
380
|
+
private val preConfigureItems = ConcurrentLinkedDeque<Pair<IngestItemType, JSONObject>>()
|
|
381
|
+
@Volatile private var exitInfoCheckDeferred = false
|
|
382
|
+
@Volatile private var preConfigureOverflowLogged = false
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* The retry file of the removed direct-POST path (one failed batch, at
|
|
386
|
+
* most). init() deletes it on an upgraded install; its pipeline is gone.
|
|
387
|
+
*/
|
|
388
|
+
internal const val LEGACY_QUEUE_FILE = "swiss-knife-crash/pending-queue.json"
|
|
389
|
+
|
|
390
|
+
// MARK: - Pending crash files
|
|
391
|
+
//
|
|
392
|
+
// The uncaught-exception handler writes the crash to filesDir/CRASH_DIR,
|
|
393
|
+
// and the next hand-off moves every waiting file to IngestClient's durable
|
|
394
|
+
// queue. A file that is still waiting (IngestClient was not wired yet, or
|
|
395
|
+
// its queue refused the write) is never overwritten: the next crash gets a
|
|
396
|
+
// file of its own, so a crash loop before configureCore keeps each report.
|
|
397
|
+
// init() keeps the newest MAX_PENDING_CRASH_FILES. Each file is written
|
|
398
|
+
// aside and renamed into place, so a concurrent hand-off reads all of it
|
|
399
|
+
// or none of it.
|
|
400
|
+
private const val CRASH_DIR = "swiss-knife-crash"
|
|
401
|
+
/** The first slot, and the only file an older SDK version reads. */
|
|
402
|
+
private const val PENDING_CRASH_FILE = "pending-crash.json"
|
|
403
|
+
internal const val MAX_PENDING_CRASH_FILES = 10
|
|
404
|
+
private val crashFileLock = Any()
|
|
405
|
+
|
|
406
|
+
private val crashDir: File?
|
|
407
|
+
get() = appContext?.let { ctx -> File(ctx.filesDir, CRASH_DIR) }
|
|
265
408
|
|
|
266
409
|
// MARK: - Identity-derived subject
|
|
267
410
|
//
|
|
@@ -339,6 +482,7 @@ object SKCrashReporting {
|
|
|
339
482
|
this.config = config
|
|
340
483
|
this.appContext = appCtx
|
|
341
484
|
this.breadcrumbs = RingBuffer(config.maxBreadcrumbs)
|
|
485
|
+
val ingestWired = IngestClient.shared != null
|
|
342
486
|
|
|
343
487
|
// Pre-capture the identified user BEFORE the crash handler is armed,
|
|
344
488
|
// and keep the cache warm via an Identity observer. Crash-handler
|
|
@@ -351,23 +495,22 @@ object SKCrashReporting {
|
|
|
351
495
|
identityUserId = change.current.userId?.takeIf { it.isNotEmpty() }
|
|
352
496
|
}
|
|
353
497
|
|
|
354
|
-
// Send any crash from
|
|
498
|
+
// Send any crash from earlier sessions (kept on disk until IngestClient
|
|
499
|
+
// is wired).
|
|
500
|
+
prunePendingCrashFiles()
|
|
355
501
|
flushPendingCrash()
|
|
356
502
|
|
|
357
503
|
// Check for native crashes / ANRs from previous session via ApplicationExitInfo
|
|
358
504
|
// (Android 11+). This catches NDK native crashes and system-confirmed ANRs.
|
|
505
|
+
// Deferred until IngestClient is wired: the records stay in the OS, and
|
|
506
|
+
// the high-water mark only moves once a report is on the durable queue.
|
|
359
507
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
360
|
-
|
|
508
|
+
exitInfoCheckDeferred = !ingestWired
|
|
509
|
+
if (ingestWired) checkPreviousNativeCrashes(appCtx)
|
|
361
510
|
}
|
|
362
511
|
|
|
363
|
-
// Install uncaught exception handler (chain with existing)
|
|
364
|
-
|
|
365
|
-
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
|
|
366
|
-
val event = buildCrashEvent(throwable)
|
|
367
|
-
writeCrashToDisk(event)
|
|
368
|
-
sendSessionEvent("crashed")
|
|
369
|
-
originalExceptionHandler?.uncaughtException(thread, throwable)
|
|
370
|
-
}
|
|
512
|
+
// Install uncaught exception handler (chain with existing), once.
|
|
513
|
+
installCrashHandler()
|
|
371
514
|
|
|
372
515
|
// Auto-breadcrumbs: activity lifecycle + connectivity
|
|
373
516
|
registerActivityLifecycle(appCtx)
|
|
@@ -375,26 +518,59 @@ object SKCrashReporting {
|
|
|
375
518
|
|
|
376
519
|
// ANR watchdog
|
|
377
520
|
anrWatchdog?.stop()
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
|
|
521
|
+
val pid = android.os.Process.myPid()
|
|
522
|
+
anrWatchdog = AnrWatchdog(
|
|
523
|
+
config.anrTimeoutMs,
|
|
524
|
+
// The hang ended: the process was not killed for it, so a later
|
|
525
|
+
// system ANR in this process is a DIFFERENT hang (service start
|
|
526
|
+
// timeout, broadcast timeout, …) and must not be deduped.
|
|
527
|
+
// Same executor as the report, so clear always runs after record.
|
|
528
|
+
onRecover = { executor.execute { clearWatchdogAnrMarks(appCtx, pid) } },
|
|
529
|
+
) { mainStack ->
|
|
530
|
+
val detectedAtMs = System.currentTimeMillis()
|
|
531
|
+
executor.execute { reportWatchdogAnr(appCtx, pid, detectedAtMs, mainStack) }
|
|
387
532
|
}
|
|
388
533
|
anrWatchdog?.start()
|
|
389
534
|
|
|
390
535
|
// Start session tracking
|
|
391
536
|
startSession()
|
|
392
537
|
|
|
393
|
-
//
|
|
394
|
-
|
|
538
|
+
// An older SDK's direct-POST retry file; its pipeline is gone.
|
|
539
|
+
runCatching { File(appCtx.filesDir, LEGACY_QUEUE_FILE).delete() }
|
|
540
|
+
|
|
541
|
+
// Start periodic flush timer (and the ingest watch when unwired)
|
|
542
|
+
startFlushTimer(watchForIngest = !ingestWired)
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Install [CrashHandler] as the default handler, capturing the handler it
|
|
547
|
+
* replaces as the one to chain to. Only the first call installs; a later
|
|
548
|
+
* `init()` leaves the chain alone, so it can never capture our own
|
|
549
|
+
* handler as the original.
|
|
550
|
+
*/
|
|
551
|
+
private fun installCrashHandler() {
|
|
552
|
+
if (!crashHandlerInstalled.compareAndSet(false, true)) return
|
|
553
|
+
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
|
554
|
+
originalExceptionHandler = previous?.takeIf { it !== CrashHandler }
|
|
555
|
+
Thread.setDefaultUncaughtExceptionHandler(CrashHandler)
|
|
556
|
+
}
|
|
395
557
|
|
|
396
|
-
|
|
397
|
-
|
|
558
|
+
/**
|
|
559
|
+
* Record the crash, then ALWAYS chain: a failure while building or
|
|
560
|
+
* writing the report must not swallow the crash or skip the host's own
|
|
561
|
+
* handler (another crash reporter, or the platform's, which kills the
|
|
562
|
+
* process).
|
|
563
|
+
*/
|
|
564
|
+
private fun handleUncaughtException(thread: Thread, throwable: Throwable) {
|
|
565
|
+
try {
|
|
566
|
+
val event = buildCrashEvent(throwable)
|
|
567
|
+
writeCrashToDisk(event)
|
|
568
|
+
sendSessionEvent("crashed")
|
|
569
|
+
} catch (t: Throwable) {
|
|
570
|
+
runCatching { println("[SwissKnife CrashReporting] crash report failed: $t") }
|
|
571
|
+
} finally {
|
|
572
|
+
originalExceptionHandler?.takeIf { it !== CrashHandler }?.uncaughtException(thread, throwable)
|
|
573
|
+
}
|
|
398
574
|
}
|
|
399
575
|
|
|
400
576
|
// MARK: - Sampling & beforeSend
|
|
@@ -511,14 +687,14 @@ object SKCrashReporting {
|
|
|
511
687
|
|
|
512
688
|
/**
|
|
513
689
|
* Flush all pending operations. Blocks until the internal executor drains
|
|
514
|
-
* previously submitted work
|
|
515
|
-
*
|
|
690
|
+
* previously submitted work, then hands everything that is waiting to
|
|
691
|
+
* IngestClient's durable queue when it is wired (see "Pre-configure
|
|
692
|
+
* buffer"). Useful before app shutdown or when you need delivery guarantees.
|
|
516
693
|
*/
|
|
517
694
|
fun flush() {
|
|
518
|
-
//
|
|
519
|
-
// submitted work on the executor is complete.
|
|
695
|
+
// Runs after all previously submitted work on the executor.
|
|
520
696
|
try {
|
|
521
|
-
executor.submit {}.get(10, java.util.concurrent.TimeUnit.SECONDS)
|
|
697
|
+
executor.submit { handOffToIngest() }.get(10, java.util.concurrent.TimeUnit.SECONDS)
|
|
522
698
|
} catch (_: Exception) {
|
|
523
699
|
// timeout or interrupted — best effort
|
|
524
700
|
}
|
|
@@ -624,6 +800,36 @@ object SKCrashReporting {
|
|
|
624
800
|
return chain
|
|
625
801
|
}
|
|
626
802
|
|
|
803
|
+
/**
|
|
804
|
+
* Deliver a watchdog ANR durably, and only then persist the dedupe mark.
|
|
805
|
+
*
|
|
806
|
+
* The mark makes the next launch skip the system `REASON_ANR` record, so
|
|
807
|
+
* it must never outlive an event that was lost. The in-memory
|
|
808
|
+
* [pendingEvents] batch is not good enough: it flushes every 30 s and dies
|
|
809
|
+
* with the process, and the system kills an ANR'd process well within
|
|
810
|
+
* that. So the event goes through [sendEventPayload] (IngestClient's disk
|
|
811
|
+
* queue) and the mark is written only on success. Before IngestClient is
|
|
812
|
+
* wired the event is only held in memory, so no mark is written. A kill
|
|
813
|
+
* between the two costs a duplicate report, never a lost one.
|
|
814
|
+
*/
|
|
815
|
+
internal fun reportWatchdogAnr(
|
|
816
|
+
context: Context,
|
|
817
|
+
pid: Int,
|
|
818
|
+
detectedAtMs: Long,
|
|
819
|
+
mainStack: Array<StackTraceElement>,
|
|
820
|
+
) {
|
|
821
|
+
val event = buildEvent(SKErrorLevel.ERROR).apply {
|
|
822
|
+
this.message = "Application Not Responding"
|
|
823
|
+
this.mechanism = "anr_watchdog"
|
|
824
|
+
// The stack captured at detection time, not re-read later
|
|
825
|
+
// (by then the main thread may have moved on).
|
|
826
|
+
this.stacktrace = parseStackTraceElements(mainStack)
|
|
827
|
+
}
|
|
828
|
+
if (sendEventPayload(event)) {
|
|
829
|
+
recordWatchdogAnr(context, pid, detectedAtMs)
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
627
833
|
private fun sendEvent(event: SKErrorEvent) {
|
|
628
834
|
executor.execute { enqueueEvent(event) }
|
|
629
835
|
}
|
|
@@ -633,9 +839,14 @@ object SKCrashReporting {
|
|
|
633
839
|
if (pendingEvents.size >= FLUSH_THRESHOLD) {
|
|
634
840
|
flushEventQueue()
|
|
635
841
|
}
|
|
842
|
+
// Still held because IngestClient is not wired: keep the newest.
|
|
843
|
+
while (pendingEvents.size > PRE_CONFIGURE_LIMIT) {
|
|
844
|
+
pendingEvents.removeAt(0)
|
|
845
|
+
notePreConfigureOverflow()
|
|
846
|
+
}
|
|
636
847
|
}
|
|
637
848
|
|
|
638
|
-
private fun startFlushTimer() {
|
|
849
|
+
private fun startFlushTimer(watchForIngest: Boolean) {
|
|
639
850
|
flushTimer?.cancel()
|
|
640
851
|
flushTimer = java.util.Timer("sk-event-flush", true).also { timer ->
|
|
641
852
|
timer.scheduleAtFixedRate(object : java.util.TimerTask() {
|
|
@@ -645,156 +856,198 @@ object SKCrashReporting {
|
|
|
645
856
|
// identity through `SwissKnife.configure(appUserID = ...)`
|
|
646
857
|
// AFTER crash reporting started, which sets the id without
|
|
647
858
|
// firing an Identity change notification.
|
|
648
|
-
executor.execute { refreshIdentityUserId();
|
|
859
|
+
executor.execute { refreshIdentityUserId(); handOffToIngest() }
|
|
649
860
|
}
|
|
650
861
|
}, FLUSH_INTERVAL_MS, FLUSH_INTERVAL_MS)
|
|
862
|
+
if (watchForIngest) {
|
|
863
|
+
// Started before SwissKnife.configureCore: hand the backlog over
|
|
864
|
+
// as soon as IngestClient is wired, not at the next 30 s tick.
|
|
865
|
+
// One volatile read per period; stops after the hand-off, or
|
|
866
|
+
// after INGEST_WATCH_MAX_RUNS, when the tick alone remains.
|
|
867
|
+
timer.schedule(object : java.util.TimerTask() {
|
|
868
|
+
private var runs = 0
|
|
869
|
+
override fun run() {
|
|
870
|
+
if (IngestClient.shared == null) {
|
|
871
|
+
if (++runs >= INGEST_WATCH_MAX_RUNS) cancel()
|
|
872
|
+
return
|
|
873
|
+
}
|
|
874
|
+
cancel()
|
|
875
|
+
executor.execute { handOffToIngest() }
|
|
876
|
+
}
|
|
877
|
+
}, INGEST_WATCH_MS, INGEST_WATCH_MS)
|
|
878
|
+
}
|
|
651
879
|
}
|
|
652
880
|
}
|
|
653
881
|
|
|
882
|
+
/**
|
|
883
|
+
* Batch the captured events onto IngestClient as `error_batch` items. Not
|
|
884
|
+
* wired yet: they stay in [pendingEvents] (bounded in [enqueueEvent]).
|
|
885
|
+
* Executor thread only.
|
|
886
|
+
*/
|
|
654
887
|
private fun flushEventQueue() {
|
|
655
888
|
if (pendingEvents.isEmpty()) return
|
|
656
|
-
|
|
889
|
+
if (config == null) return
|
|
890
|
+
val ingest = IngestClient.shared ?: return
|
|
891
|
+
val ctx = appContext ?: return
|
|
657
892
|
|
|
658
893
|
val batch = pendingEvents.toList()
|
|
659
894
|
pendingEvents.clear()
|
|
660
|
-
|
|
661
|
-
//
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
// alone (e.g. integration tests).
|
|
666
|
-
val ingest = com.appswissknife.net.IngestClient.shared
|
|
667
|
-
val ctx = appContext
|
|
668
|
-
if (ingest != null && ctx != null) {
|
|
669
|
-
val itemsJson = org.json.JSONArray(batch.map { it.toJSON() })
|
|
670
|
-
val data = JSONObject().put("items", itemsJson)
|
|
671
|
-
ingest.enqueue(com.appswissknife.net.IngestItemType.ErrorBatch, data, ctx)
|
|
672
|
-
return
|
|
895
|
+
// Normally under FLUSH_THRESHOLD, so one item as before; a backlog held
|
|
896
|
+
// before configure goes out in items of the same size.
|
|
897
|
+
for (chunk in batch.chunked(FLUSH_THRESHOLD)) {
|
|
898
|
+
val data = JSONObject().put("items", JSONArray(chunk.map { it.toJSON() }))
|
|
899
|
+
ingest.enqueue(IngestItemType.ErrorBatch, data, ctx)
|
|
673
900
|
}
|
|
901
|
+
}
|
|
674
902
|
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
903
|
+
/**
|
|
904
|
+
* Put one item on IngestClient's durable queue, after anything held in
|
|
905
|
+
* [preConfigureItems]; before IngestClient is wired, hold it there.
|
|
906
|
+
* Returns true only when the item is on the durable queue. Lock-free,
|
|
907
|
+
* because the uncaught-exception handler calls it (session "crashed").
|
|
908
|
+
*/
|
|
909
|
+
private fun deliver(type: IngestItemType, data: JSONObject): Boolean {
|
|
910
|
+
val ingest = IngestClient.shared
|
|
911
|
+
val ctx = appContext
|
|
912
|
+
if (ingest == null || ctx == null) {
|
|
913
|
+
preConfigureItems.addLast(type to data)
|
|
914
|
+
while (preConfigureItems.size > PRE_CONFIGURE_LIMIT) {
|
|
915
|
+
preConfigureItems.pollFirst()
|
|
916
|
+
notePreConfigureOverflow()
|
|
689
917
|
}
|
|
690
|
-
|
|
691
|
-
println("[SwissKnife CrashReporting] batch send error: ${e.message}")
|
|
692
|
-
persistQueueToDisk(batch)
|
|
918
|
+
return false
|
|
693
919
|
}
|
|
920
|
+
drainPreConfigureItems(ingest, ctx)
|
|
921
|
+
return ingest.enqueue(type, data, ctx)
|
|
694
922
|
}
|
|
695
923
|
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
} catch (e: Exception) {
|
|
704
|
-
println("[SwissKnife CrashReporting] persistQueue error: ${e.message}")
|
|
924
|
+
/** Returns how many held items were handed to [ingest]. */
|
|
925
|
+
private fun drainPreConfigureItems(ingest: IngestClient, ctx: Context): Int {
|
|
926
|
+
var handed = 0
|
|
927
|
+
while (true) {
|
|
928
|
+
val (type, data) = preConfigureItems.pollFirst() ?: break
|
|
929
|
+
ingest.enqueue(type, data, ctx)
|
|
930
|
+
handed++
|
|
705
931
|
}
|
|
932
|
+
return handed
|
|
706
933
|
}
|
|
707
934
|
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
println("[SwissKnife CrashReporting] restoreQueue error: ${e.message}")
|
|
935
|
+
/**
|
|
936
|
+
* Hand everything that waited for IngestClient to it: held items, the
|
|
937
|
+
* previous process's crash file and exit records, captured events.
|
|
938
|
+
* No-op until IngestClient is wired. Executor thread only.
|
|
939
|
+
*/
|
|
940
|
+
private fun handOffToIngest() {
|
|
941
|
+
val ingest = IngestClient.shared ?: return
|
|
942
|
+
val ctx = appContext ?: return
|
|
943
|
+
if (config == null) return
|
|
944
|
+
if (drainPreConfigureItems(ingest, ctx) > 0) ingest.scheduleFlush(ctx)
|
|
945
|
+
flushPendingCrash()
|
|
946
|
+
if (exitInfoCheckDeferred && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
947
|
+
exitInfoCheckDeferred = false
|
|
948
|
+
checkPreviousNativeCrashes(ctx)
|
|
723
949
|
}
|
|
950
|
+
flushEventQueue()
|
|
724
951
|
}
|
|
725
952
|
|
|
726
|
-
private fun
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
.simplePost(
|
|
733
|
-
path = "/api/sdk/errors/event",
|
|
734
|
-
body = json.toString(),
|
|
735
|
-
)
|
|
736
|
-
} catch (_: Exception) { /* best-effort */ }
|
|
953
|
+
private fun notePreConfigureOverflow() {
|
|
954
|
+
if (preConfigureOverflowLogged) return
|
|
955
|
+
preConfigureOverflowLogged = true
|
|
956
|
+
SKLog.warn("crash") {
|
|
957
|
+
"IngestClient is not wired (call SwissKnife.configureCore); holding the newest " +
|
|
958
|
+
"$PRE_CONFIGURE_LIMIT reports in memory and dropping older ones"
|
|
737
959
|
}
|
|
738
960
|
}
|
|
739
961
|
|
|
740
|
-
/**
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
try {
|
|
751
|
-
val r = com.appswissknife.net.BackendHttpClient
|
|
752
|
-
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
753
|
-
.simplePost(
|
|
754
|
-
path = "/api/sdk/errors/event",
|
|
755
|
-
body = event.toJSON().toString(),
|
|
756
|
-
)
|
|
757
|
-
if (r.code !in 200..299) {
|
|
758
|
-
println("[SwissKnife CrashReporting] send failed: HTTP ${r.code}")
|
|
759
|
-
}
|
|
760
|
-
} catch (e: Exception) {
|
|
761
|
-
println("[SwissKnife CrashReporting] send error: ${e.message}")
|
|
762
|
-
}
|
|
962
|
+
/**
|
|
963
|
+
* Single-event send (ANR watchdog, ApplicationExitInfo, captureEvent).
|
|
964
|
+
*
|
|
965
|
+
* Returns true when the event is durable: on IngestClient's on-disk
|
|
966
|
+
* queue. Before IngestClient is wired it is held in memory (see
|
|
967
|
+
* "Pre-configure buffer") and this returns false.
|
|
968
|
+
*/
|
|
969
|
+
internal fun sendEventPayload(event: SKErrorEvent): Boolean {
|
|
970
|
+
if (config == null) return false
|
|
971
|
+
return deliver(IngestItemType.Error, event.toJSON())
|
|
763
972
|
}
|
|
764
973
|
|
|
765
974
|
// MARK: - Pending Crash (disk)
|
|
766
975
|
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
if (!file.exists()) return
|
|
976
|
+
private fun isPendingCrashName(name: String) =
|
|
977
|
+
name.startsWith("pending-crash") && name.endsWith(".json")
|
|
770
978
|
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
979
|
+
/** Waiting crash files, oldest first. */
|
|
980
|
+
private fun pendingCrashFiles(dir: File): List<File> =
|
|
981
|
+
(dir.listFiles { f -> f.isFile && isPendingCrashName(f.name) } ?: emptyArray())
|
|
982
|
+
.sortedWith(compareBy<File>({ it.lastModified() }, { it.name }))
|
|
774
983
|
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
984
|
+
/**
|
|
985
|
+
* Move every waiting crash file onto IngestClient's durable queue. Before
|
|
986
|
+
* IngestClient is wired the files stay where they are (they are already
|
|
987
|
+
* durable) and the next hand-off picks them up.
|
|
988
|
+
*/
|
|
989
|
+
internal fun flushPendingCrash() {
|
|
990
|
+
synchronized(crashFileLock) {
|
|
991
|
+
val dir = crashDir ?: return
|
|
992
|
+
if (config == null) return
|
|
993
|
+
val ingest = IngestClient.shared ?: return
|
|
994
|
+
val ctx = appContext ?: return
|
|
995
|
+
|
|
996
|
+
var queued = false
|
|
997
|
+
for (file in pendingCrashFiles(dir)) {
|
|
998
|
+
val text = runCatching { file.readText(Charsets.UTF_8) }.getOrNull() ?: continue
|
|
999
|
+
val json = runCatching { JSONObject(text) }.getOrNull()
|
|
1000
|
+
if (json == null) {
|
|
1001
|
+
file.delete() // unparsable — retrying can never help
|
|
1002
|
+
continue
|
|
786
1003
|
}
|
|
787
|
-
|
|
788
|
-
|
|
1004
|
+
// Once enqueued, IngestClient owns delivery (and its 429 / 5xx
|
|
1005
|
+
// backoff), so the file can go. A refused write keeps the rest
|
|
1006
|
+
// for the next hand-off.
|
|
1007
|
+
if (!ingest.enqueue(IngestItemType.Error, json, ctx)) break
|
|
1008
|
+
file.delete()
|
|
1009
|
+
queued = true
|
|
789
1010
|
}
|
|
1011
|
+
if (queued) ingest.scheduleFlush(ctx)
|
|
790
1012
|
}
|
|
791
1013
|
}
|
|
792
1014
|
|
|
1015
|
+
/**
|
|
1016
|
+
* Drop what an interrupted write left behind and the oldest waiting crash
|
|
1017
|
+
* files past [MAX_PENDING_CRASH_FILES]. Called by init(), before this
|
|
1018
|
+
* process can crash into the directory.
|
|
1019
|
+
*/
|
|
1020
|
+
private fun prunePendingCrashFiles() {
|
|
1021
|
+
val dir = crashDir ?: return
|
|
1022
|
+
runCatching {
|
|
1023
|
+
dir.listFiles { f -> f.name.startsWith("pending-crash") && f.name.endsWith(".tmp") }
|
|
1024
|
+
?.forEach { it.delete() }
|
|
1025
|
+
val waiting = pendingCrashFiles(dir)
|
|
1026
|
+
waiting.take((waiting.size - MAX_PENDING_CRASH_FILES).coerceAtLeast(0))
|
|
1027
|
+
.forEach { it.delete() }
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
/**
|
|
1032
|
+
* Crash-handler context: plain file IO, no locks. See "Pending crash
|
|
1033
|
+
* files": a crash that is still waiting is never overwritten.
|
|
1034
|
+
*/
|
|
793
1035
|
internal fun writeCrashToDisk(event: SKErrorEvent) {
|
|
794
1036
|
try {
|
|
795
|
-
val
|
|
796
|
-
|
|
797
|
-
|
|
1037
|
+
val dir = crashDir ?: return
|
|
1038
|
+
dir.mkdirs()
|
|
1039
|
+
val first = File(dir, PENDING_CRASH_FILE)
|
|
1040
|
+
val target = if (!first.exists()) first else {
|
|
1041
|
+
val id = event.eventId.filter { it.isLetterOrDigit() || it == '-' }.take(64)
|
|
1042
|
+
File(dir, "pending-crash-${System.currentTimeMillis()}-$id.json")
|
|
1043
|
+
}
|
|
1044
|
+
val json = event.toJSON().toString()
|
|
1045
|
+
val tmp = File(dir, "${target.name}.tmp")
|
|
1046
|
+
tmp.writeText(json)
|
|
1047
|
+
if (!tmp.renameTo(target)) {
|
|
1048
|
+
target.writeText(json)
|
|
1049
|
+
tmp.delete()
|
|
1050
|
+
}
|
|
798
1051
|
} catch (e: Exception) {
|
|
799
1052
|
println("[SwissKnife CrashReporting] writeCrashToDisk error: ${e.message}")
|
|
800
1053
|
}
|
|
@@ -833,60 +1086,67 @@ object SKCrashReporting {
|
|
|
833
1086
|
put("deviceModel", Build.MODEL)
|
|
834
1087
|
}
|
|
835
1088
|
|
|
836
|
-
|
|
837
|
-
val ingest = com.appswissknife.net.IngestClient.shared
|
|
838
|
-
if (ingest != null) {
|
|
839
|
-
ingest.enqueue(com.appswissknife.net.IngestItemType.Session, body, ctx)
|
|
840
|
-
return
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
executor.execute {
|
|
844
|
-
try {
|
|
845
|
-
com.appswissknife.net.BackendHttpClient
|
|
846
|
-
.create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
|
|
847
|
-
.simplePost(
|
|
848
|
-
path = "/api/sdk/errors/session",
|
|
849
|
-
body = body.toString(),
|
|
850
|
-
)
|
|
851
|
-
} catch (e: Exception) {
|
|
852
|
-
println("[SwissKnife CrashReporting] session event error: ${e.message}")
|
|
853
|
-
}
|
|
854
|
-
}
|
|
1089
|
+
deliver(IngestItemType.Session, body)
|
|
855
1090
|
}
|
|
856
1091
|
|
|
857
1092
|
// MARK: - Auto-Breadcrumbs
|
|
858
1093
|
|
|
859
1094
|
private fun registerActivityLifecycle(context: Context) {
|
|
860
1095
|
val app = context as? android.app.Application ?: return
|
|
1096
|
+
if (lifecycleRegisteredOn === app) return // once per Application
|
|
1097
|
+
lifecycleRegisteredOn = app
|
|
861
1098
|
app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
|
|
862
1099
|
override fun onActivityCreated(activity: android.app.Activity, b: android.os.Bundle?) {
|
|
863
1100
|
addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: created"))
|
|
864
1101
|
}
|
|
1102
|
+
// A resumed or paused activity is a started one. Recording it here
|
|
1103
|
+
// too tracks an activity that started before `init()` from its
|
|
1104
|
+
// first callback, so a translucent one closing over it (a billing
|
|
1105
|
+
// sheet) does not end the session.
|
|
865
1106
|
override fun onActivityResumed(activity: android.app.Activity) {
|
|
1107
|
+
startedActivities.add(System.identityHashCode(activity))
|
|
866
1108
|
addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: resumed"))
|
|
867
1109
|
}
|
|
868
1110
|
override fun onActivityPaused(activity: android.app.Activity) {
|
|
1111
|
+
startedActivities.add(System.identityHashCode(activity))
|
|
869
1112
|
addBreadcrumb(SKBreadcrumb(category = "activity.lifecycle", message = "${activity.localClassName}: paused"))
|
|
870
|
-
endSession()
|
|
871
1113
|
}
|
|
872
|
-
override fun onActivityStarted(activity: android.app.Activity) {
|
|
873
|
-
|
|
1114
|
+
override fun onActivityStarted(activity: android.app.Activity) {
|
|
1115
|
+
startedActivities.add(System.identityHashCode(activity))
|
|
1116
|
+
}
|
|
1117
|
+
override fun onActivityStopped(activity: android.app.Activity) {
|
|
1118
|
+
startedActivities.remove(System.identityHashCode(activity))
|
|
1119
|
+
// A rotation stops the activity and starts its replacement
|
|
1120
|
+
// straight away: not the end of a session.
|
|
1121
|
+
if (activity.isChangingConfigurations) return
|
|
1122
|
+
// Nothing left on screen: the app went to the background. An
|
|
1123
|
+
// activity started before `init()` (React Native initialises
|
|
1124
|
+
// from JS, after MainActivity started) is not in the set, so
|
|
1125
|
+
// its stop with nothing else started also lands here.
|
|
1126
|
+
if (startedActivities.isEmpty()) endSession()
|
|
1127
|
+
}
|
|
874
1128
|
override fun onActivitySaveInstanceState(activity: android.app.Activity, b: android.os.Bundle) {}
|
|
875
1129
|
override fun onActivityDestroyed(activity: android.app.Activity) {}
|
|
876
1130
|
})
|
|
877
1131
|
}
|
|
878
1132
|
|
|
879
1133
|
private fun registerConnectivityObserver(context: Context) {
|
|
1134
|
+
if (connectivityRegisteredOn === context) return // once per context
|
|
880
1135
|
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
|
|
881
1136
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
1137
|
+
// Breadcrumbs only: a missing permission or the per-app callback
|
|
1138
|
+
// limit (TooManyRequestsException) must not fail `init()`.
|
|
1139
|
+
runCatching {
|
|
1140
|
+
cm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
|
|
1141
|
+
override fun onAvailable(network: Network) {
|
|
1142
|
+
addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network available"))
|
|
1143
|
+
}
|
|
1144
|
+
override fun onLost(network: Network) {
|
|
1145
|
+
addBreadcrumb(SKBreadcrumb(category = "connectivity", message = "network lost"))
|
|
1146
|
+
}
|
|
1147
|
+
})
|
|
1148
|
+
connectivityRegisteredOn = context
|
|
1149
|
+
}.onFailure { println("[SwissKnife CrashReporting] connectivity breadcrumbs unavailable: ${it.message}") }
|
|
890
1150
|
}
|
|
891
1151
|
}
|
|
892
1152
|
|
|
@@ -905,13 +1165,26 @@ object SKCrashReporting {
|
|
|
905
1165
|
val exitInfos = am.getHistoricalProcessExitReasons(context.packageName, 0, 5)
|
|
906
1166
|
val prefs = context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE)
|
|
907
1167
|
val lastReported = prefs.getLong("last_native_crash_ts", 0)
|
|
1168
|
+
val watchdogMarks = readWatchdogAnrMarks(context)
|
|
908
1169
|
|
|
909
|
-
|
|
1170
|
+
// getHistoricalProcessExitReasons returns newest first. Walk
|
|
1171
|
+
// oldest → newest so the persisted high-water mark only ever
|
|
1172
|
+
// moves forward; newest-first left it at the OLDEST record,
|
|
1173
|
+
// and the newer ones were re-sent on the following launch.
|
|
1174
|
+
for (info in exitInfos.sortedBy { it.timestamp }) {
|
|
910
1175
|
if (info.timestamp <= lastReported) continue
|
|
911
1176
|
if (info.reason != ApplicationExitInfo.REASON_CRASH_NATIVE &&
|
|
912
1177
|
info.reason != ApplicationExitInfo.REASON_ANR) continue
|
|
913
1178
|
|
|
914
1179
|
val isNative = info.reason == ApplicationExitInfo.REASON_CRASH_NATIVE
|
|
1180
|
+
|
|
1181
|
+
// The in-process watchdog usually already reported this
|
|
1182
|
+
// hang (with a live main-thread stack). Don't send it twice.
|
|
1183
|
+
if (!isNative && isDuplicateOfWatchdogAnr(watchdogMarks, info.pid, info.timestamp)) {
|
|
1184
|
+
prefs.edit().putLong("last_native_crash_ts", info.timestamp).apply()
|
|
1185
|
+
continue
|
|
1186
|
+
}
|
|
1187
|
+
|
|
915
1188
|
val traceText = try {
|
|
916
1189
|
info.traceInputStream?.use { stream ->
|
|
917
1190
|
stream.bufferedReader().readText()
|
|
@@ -922,7 +1195,9 @@ object SKCrashReporting {
|
|
|
922
1195
|
exceptionType = if (isNative) "NativeCrash" else "ANR",
|
|
923
1196
|
exceptionValue = info.description ?: if (isNative) "Native crash detected via ApplicationExitInfo" else "ANR detected via ApplicationExitInfo",
|
|
924
1197
|
mechanism = if (isNative) "native_crash" else "anr_system",
|
|
925
|
-
stacktrace = traceText?.let {
|
|
1198
|
+
stacktrace = traceText?.let {
|
|
1199
|
+
if (isNative) parseNativeTrace(it) else parseAnrThreadDump(it)
|
|
1200
|
+
} ?: emptyList()
|
|
926
1201
|
)
|
|
927
1202
|
|
|
928
1203
|
sendEventPayload(event)
|
|
@@ -935,21 +1210,117 @@ object SKCrashReporting {
|
|
|
935
1210
|
}
|
|
936
1211
|
}
|
|
937
1212
|
|
|
1213
|
+
// MARK: - Watchdog / system ANR dedupe
|
|
1214
|
+
|
|
1215
|
+
private const val ANR_MARKS_KEY = "anr_watchdog_marks"
|
|
1216
|
+
private const val MAX_ANR_MARKS = 8
|
|
1217
|
+
|
|
938
1218
|
/**
|
|
939
|
-
*
|
|
940
|
-
*
|
|
1219
|
+
* How far an `ApplicationExitInfo` ANR timestamp may sit from a watchdog
|
|
1220
|
+
* mark for the same pid and still count as the same hang. The exit record
|
|
1221
|
+
* is stamped when the process dies, which can be well after detection
|
|
1222
|
+
* (the user leaves the "App isn't responding" dialog up), so the window
|
|
1223
|
+
* is generous; the pid match is what makes it specific.
|
|
1224
|
+
*/
|
|
1225
|
+
internal const val ANR_DEDUPE_BEFORE_MS = 60_000L
|
|
1226
|
+
internal const val ANR_DEDUPE_AFTER_MS = 30 * 60_000L
|
|
1227
|
+
|
|
1228
|
+
internal fun isDuplicateOfWatchdogAnr(marks: List<AnrMark>, pid: Int, exitTimestampMs: Long): Boolean =
|
|
1229
|
+
marks.any { m ->
|
|
1230
|
+
m.pid == pid &&
|
|
1231
|
+
exitTimestampMs >= m.timestampMs - ANR_DEDUPE_BEFORE_MS &&
|
|
1232
|
+
exitTimestampMs <= m.timestampMs + ANR_DEDUPE_AFTER_MS
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
internal fun encodeAnrMarks(marks: List<AnrMark>): String =
|
|
1236
|
+
marks.joinToString(";") { "${it.pid}:${it.timestampMs}" }
|
|
1237
|
+
|
|
1238
|
+
internal fun decodeAnrMarks(raw: String?): List<AnrMark> =
|
|
1239
|
+
raw.orEmpty().split(';').mapNotNull { part ->
|
|
1240
|
+
val pid = part.substringBefore(':', "").toIntOrNull()
|
|
1241
|
+
val ts = part.substringAfter(':', "").toLongOrNull()
|
|
1242
|
+
if (pid != null && ts != null) AnrMark(pid, ts) else null
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
/**
|
|
1246
|
+
* Watchdog-thread context. Uses `commit()` (synchronous) on purpose: the
|
|
1247
|
+
* system may kill the process moments after an ANR, and an `apply()`
|
|
1248
|
+
* that never reached disk would defeat the dedupe.
|
|
1249
|
+
*/
|
|
1250
|
+
internal fun recordWatchdogAnr(context: Context, pid: Int, timestampMs: Long) {
|
|
1251
|
+
try {
|
|
1252
|
+
val prefs = context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE)
|
|
1253
|
+
val marks = (decodeAnrMarks(prefs.getString(ANR_MARKS_KEY, null)) + AnrMark(pid, timestampMs))
|
|
1254
|
+
.takeLast(MAX_ANR_MARKS)
|
|
1255
|
+
prefs.edit().putString(ANR_MARKS_KEY, encodeAnrMarks(marks)).commit()
|
|
1256
|
+
} catch (_: Throwable) { /* best effort */ }
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/**
|
|
1260
|
+
* The main thread recovered from the hang the watchdog reported, so none
|
|
1261
|
+
* of this process's marks describe a hang in progress at death. Dropping
|
|
1262
|
+
* them keeps a later, unrelated system ANR in the same process (one the
|
|
1263
|
+
* main-thread ping cannot see) from being deduped away.
|
|
1264
|
+
*/
|
|
1265
|
+
internal fun clearWatchdogAnrMarks(context: Context, pid: Int) {
|
|
1266
|
+
try {
|
|
1267
|
+
val prefs = context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE)
|
|
1268
|
+
val marks = decodeAnrMarks(prefs.getString(ANR_MARKS_KEY, null))
|
|
1269
|
+
val kept = marks.filter { it.pid != pid }
|
|
1270
|
+
if (kept.size != marks.size) {
|
|
1271
|
+
prefs.edit().putString(ANR_MARKS_KEY, encodeAnrMarks(kept)).commit()
|
|
1272
|
+
}
|
|
1273
|
+
} catch (_: Throwable) { /* best effort */ }
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
internal fun readWatchdogAnrMarks(context: Context): List<AnrMark> =
|
|
1277
|
+
try {
|
|
1278
|
+
decodeAnrMarks(
|
|
1279
|
+
context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE).getString(ANR_MARKS_KEY, null)
|
|
1280
|
+
)
|
|
1281
|
+
} catch (_: Throwable) { emptyList() }
|
|
1282
|
+
|
|
1283
|
+
// MARK: - Trace parsing
|
|
1284
|
+
|
|
1285
|
+
private val NATIVE_FRAME = Regex("""^\s*(?:native:\s*)?#\d+\s+pc\s+([0-9a-fA-F]+)\s+(\S+)(.*)$""", RegexOption.MULTILINE)
|
|
1286
|
+
private val NATIVE_ANNOTATION = Regex("""\((?:offset 0x[0-9a-fA-F]+|BuildId: [0-9a-fA-F]+|deleted)\)""")
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* Reduce a native module path to its stable basename.
|
|
1290
|
+
*
|
|
1291
|
+
* `/data/app/~~Xy==/com.app-Zq==/lib/arm64/libfoo.so` → `libfoo.so`, and
|
|
1292
|
+
* `…/base.apk!libhermes.so` → `libhermes.so`. The `/data/app/~~X==/`
|
|
1293
|
+
* directory is randomised per install and per update, so hashing the full
|
|
1294
|
+
* path split one native crash into a new issue for every install.
|
|
1295
|
+
* Bracketed pseudo-mappings (`[anon:…]`, `<anonymous:…>`) are kept as-is.
|
|
1296
|
+
*/
|
|
1297
|
+
internal fun nativeModuleBasename(path: String): String {
|
|
1298
|
+
if (path.startsWith("[") || path.startsWith("<")) return path
|
|
1299
|
+
return path.substringAfterLast('/').substringAfterLast('!').ifEmpty { path }
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
/**
|
|
1303
|
+
* Parse Android tombstone / native trace format, one frame per line:
|
|
1304
|
+
* `#00 pc 0001a4e8 /system/lib/libc.so (abort+4) (BuildId: 1f2e…)`
|
|
1305
|
+
* `#05 pc 000a1b2c /data/app/~~X==/pkg-Y==/base.apk!libhermes.so (offset 0x1a000) (hermes::foo+44)`
|
|
1306
|
+
*
|
|
1307
|
+
* `module` is the basename (see [nativeModuleBasename]); `(offset …)`,
|
|
1308
|
+
* `(BuildId: …)` and `(deleted)` annotations are stripped so they can
|
|
1309
|
+
* never leak into `function`. In-app detection still uses the full path.
|
|
941
1310
|
*/
|
|
942
1311
|
internal fun parseNativeTrace(tombstone: String): List<SKStackFrame> {
|
|
943
1312
|
val frames = mutableListOf<SKStackFrame>()
|
|
944
|
-
|
|
945
|
-
for (match in regex.findAll(tombstone)) {
|
|
1313
|
+
for (match in NATIVE_FRAME.findAll(tombstone)) {
|
|
946
1314
|
val address = match.groupValues[1]
|
|
947
1315
|
val modulePath = match.groupValues[2]
|
|
948
|
-
val
|
|
1316
|
+
val rest = NATIVE_ANNOTATION.replace(match.groupValues[3], "").trim()
|
|
1317
|
+
val funcName = if (rest.length > 2 && rest.startsWith("(") && rest.endsWith(")")) {
|
|
1318
|
+
rest.substring(1, rest.length - 1).trim().ifEmpty { null }
|
|
1319
|
+
} else null
|
|
949
1320
|
frames.add(
|
|
950
1321
|
SKStackFrame(
|
|
951
1322
|
instructionAddress = "0x$address",
|
|
952
|
-
module = modulePath,
|
|
1323
|
+
module = nativeModuleBasename(modulePath),
|
|
953
1324
|
function = funcName,
|
|
954
1325
|
inApp = !modulePath.startsWith("/system/") &&
|
|
955
1326
|
!modulePath.startsWith("/apex/") &&
|
|
@@ -961,6 +1332,54 @@ object SKCrashReporting {
|
|
|
961
1332
|
return frames
|
|
962
1333
|
}
|
|
963
1334
|
|
|
1335
|
+
private val JAVA_DUMP_FRAME = Regex("""^\s*at\s+(\S+)\((.*)\)\s*$""")
|
|
1336
|
+
|
|
1337
|
+
/**
|
|
1338
|
+
* Extract the main thread's Java frames from an ANR trace
|
|
1339
|
+
* (`ApplicationExitInfo.REASON_ANR` gives a full ART thread dump, not a
|
|
1340
|
+
* tombstone). Running the tombstone parser over it mixed the native
|
|
1341
|
+
* frames of every thread in the process into one "stack".
|
|
1342
|
+
*
|
|
1343
|
+
* Finds the `"main" … tid=1` block, reads `at pkg.Class.method(File.kt:42)`
|
|
1344
|
+
* lines until the block ends, and maps them through the same
|
|
1345
|
+
* [parseStackTraceElements] used for JVM crashes so in-app rules match.
|
|
1346
|
+
* Falls back to the main block's `native: #NN pc …` frames when it has no
|
|
1347
|
+
* Java frames. Returns empty when there is no main-thread block.
|
|
1348
|
+
*/
|
|
1349
|
+
internal fun parseAnrThreadDump(dump: String): List<SKStackFrame> {
|
|
1350
|
+
val lines = dump.lines()
|
|
1351
|
+
val start = lines.indexOfFirst { it.startsWith("\"main\"") && it.contains("tid=1") }
|
|
1352
|
+
.takeIf { it >= 0 }
|
|
1353
|
+
?: lines.indexOfFirst { it.startsWith("\"main\"") }
|
|
1354
|
+
if (start < 0) return emptyList()
|
|
1355
|
+
|
|
1356
|
+
val block = mutableListOf<String>()
|
|
1357
|
+
for (i in start + 1 until lines.size) {
|
|
1358
|
+
val line = lines[i]
|
|
1359
|
+
if (line.isBlank() || line.startsWith("\"")) break
|
|
1360
|
+
block.add(line)
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
val elements = block.mapNotNull { line ->
|
|
1364
|
+
val m = JAVA_DUMP_FRAME.matchEntire(line) ?: return@mapNotNull null
|
|
1365
|
+
val qualified = m.groupValues[1]
|
|
1366
|
+
val location = m.groupValues[2]
|
|
1367
|
+
val className = qualified.substringBeforeLast('.', "")
|
|
1368
|
+
val method = qualified.substringAfterLast('.')
|
|
1369
|
+
if (className.isEmpty()) return@mapNotNull null
|
|
1370
|
+
val (file, lineNo) = when {
|
|
1371
|
+
location == "Native method" -> null to -2
|
|
1372
|
+
location.contains(':') -> location.substringBeforeLast(':') to
|
|
1373
|
+
(location.substringAfterLast(':').toIntOrNull() ?: -1)
|
|
1374
|
+
location.isEmpty() || location == "Unknown Source" -> null to -1
|
|
1375
|
+
else -> location to -1
|
|
1376
|
+
}
|
|
1377
|
+
StackTraceElement(className, method, file, lineNo)
|
|
1378
|
+
}
|
|
1379
|
+
if (elements.isNotEmpty()) return parseStackTraceElements(elements.toTypedArray())
|
|
1380
|
+
return parseNativeTrace(block.joinToString("\n"))
|
|
1381
|
+
}
|
|
1382
|
+
|
|
964
1383
|
// MARK: - Helpers
|
|
965
1384
|
|
|
966
1385
|
/**
|
|
@@ -1029,6 +1448,12 @@ object SKCrashReporting {
|
|
|
1029
1448
|
/** Test seam — events that have been enqueued but not yet flushed. */
|
|
1030
1449
|
internal fun _pendingEventsForTesting(): List<SKErrorEvent> = pendingEvents.toList()
|
|
1031
1450
|
|
|
1451
|
+
/** Test seam — set config + context without the full [initialize] side effects. */
|
|
1452
|
+
internal fun _configureForTesting(cfg: Configuration, context: Context) {
|
|
1453
|
+
config = cfg
|
|
1454
|
+
appContext = context
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1032
1457
|
internal fun _resetForTesting() {
|
|
1033
1458
|
config = null
|
|
1034
1459
|
appContext = null
|
|
@@ -1046,8 +1471,16 @@ object SKCrashReporting {
|
|
|
1046
1471
|
anrWatchdog = null
|
|
1047
1472
|
sessionErrorCount = 0
|
|
1048
1473
|
pendingEvents.clear()
|
|
1474
|
+
preConfigureItems.clear()
|
|
1475
|
+
exitInfoCheckDeferred = false
|
|
1476
|
+
preConfigureOverflowLogged = false
|
|
1049
1477
|
flushTimer?.cancel()
|
|
1050
1478
|
flushTimer = null
|
|
1479
|
+
// Let the next test's `init()` install against ITS default handler.
|
|
1480
|
+
// (Callers restore the default handler themselves.)
|
|
1481
|
+
crashHandlerInstalled.set(false)
|
|
1482
|
+
originalExceptionHandler = null
|
|
1483
|
+
startedActivities.clear()
|
|
1051
1484
|
}
|
|
1052
1485
|
}
|
|
1053
1486
|
|