Skip to content

Commit acda7b2

Browse files
Add CrashKiOS Swift package
1 parent 149ab7f commit acda7b2

9 files changed

Lines changed: 318 additions & 0 deletions

File tree

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,5 @@ fastlane/test_output
7171

7272
buildboth.sh
7373
Pods
74+
.build/
75+
Package.resolved

‎Package.swift‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// swift-tools-version: 5.5
2+
// CrashKiOS Swift sinks — live in the app's build graph, where the crash-SDK
3+
// binaries are already linked. See docs-plans/crashkios-linking-remediation-plan.md.
4+
5+
import PackageDescription
6+
7+
let package = Package(
8+
name: "CrashKiOS",
9+
platforms: [.iOS(.v15), .macOS(.v10_15), .tvOS(.v15), .watchOS(.v7)],
10+
products: [
11+
.library(
12+
name: "CrashKiOSCrashlytics",
13+
targets: ["CrashKiOSCrashlytics"]
14+
),
15+
.library(
16+
name: "CrashKiOSBugsnag",
17+
targets: ["CrashKiOSBugsnag"]
18+
),
19+
],
20+
dependencies: [
21+
.package(
22+
url: "https://github.com/firebase/firebase-ios-sdk.git",
23+
"11.0.0"..<"13.0.0"
24+
),
25+
.package(
26+
url: "https://github.com/bugsnag/bugsnag-cocoa.git",
27+
"6.22.1"..<"7.0.0"
28+
),
29+
],
30+
targets: [
31+
// Header-only targets: they own the sink protocols (cinterop'd by the Kotlin
32+
// modules) so Swift sinks compile without importing the app's Kotlin framework.
33+
.target(
34+
name: "CrashKiOSCrashlyticsObjC",
35+
path: "Sources/CrashKiOSCrashlyticsObjC"
36+
),
37+
.target(
38+
name: "CrashKiOSCrashlytics",
39+
dependencies: [
40+
.target(name: "CrashKiOSCrashlyticsObjC"),
41+
.product(name: "FirebaseCrashlytics", package: "firebase-ios-sdk"),
42+
],
43+
path: "Sources/CrashKiOSCrashlytics"
44+
),
45+
.target(
46+
name: "CrashKiOSBugsnagObjC",
47+
path: "Sources/CrashKiOSBugsnagObjC"
48+
),
49+
.target(
50+
name: "CrashKiOSBugsnag",
51+
dependencies: [
52+
.target(name: "CrashKiOSBugsnagObjC"),
53+
.product(name: "Bugsnag", package: "bugsnag-cocoa"),
54+
],
55+
path: "Sources/CrashKiOSBugsnag"
56+
),
57+
]
58+
)
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import Foundation
2+
import ObjectiveC
3+
import CrashKiOSBugsnagObjC
4+
import Bugsnag
5+
6+
/// Feature flag used to mark the Kotlin termination crash.
7+
/// Public so custom `CrashKiOSBugsnagSink` implementations can honor the same contract.
8+
public let kotlinCrashedFeatureFlag = "crashkios.kotlin_crashed"
9+
10+
/// Prepares `config` for Kotlin crash handling: installs the OnSendError filter that
11+
/// suppresses the duplicate termination crash following a recorded Kotlin fatal, and
12+
/// works around Bugsnag 6.26.2+ refusing to persist synthetic unhandled events.
13+
///
14+
/// Custom sink implementations MUST call this before `Bugsnag.start(with: config)` —
15+
/// otherwise every fatal Kotlin exception is reported twice.
16+
public func configureBugsnagForKotlin(_ config: BugsnagConfiguration) {
17+
overrideOriginalUnhandledValue()
18+
config.addOnSendError { event in
19+
// Drop Bugsnag's own report of the abort that terminates the app after a
20+
// Kotlin fatal was already recorded (flagged via markFatalCrashRecorded).
21+
!event.unhandled || !event.featureFlags.contains { $0.name == kotlinCrashedFeatureFlag }
22+
}
23+
config.clearFeatureFlag(name: kotlinCrashedFeatureFlag)
24+
}
25+
26+
/// Reference `CrashKiOSBugsnagSink` implementation.
27+
///
28+
/// Start Bugsnag through this class so the configuration is prepared for Kotlin
29+
/// crash handling, then register the returned sink with the Kotlin side:
30+
/// ```swift
31+
/// let sink = BugsnagSink.start(BugsnagConfiguration.loadConfig())
32+
/// BugsnagKt.registerBugsnagSink(sink: sink)
33+
/// ```
34+
/// (Add `export("co.touchlab.crashkios:bugsnag")` to the Kotlin framework for clean names.)
35+
public final class BugsnagSink: NSObject, CrashKiOSBugsnagSink {
36+
37+
/// Configures `config` via `configureBugsnagForKotlin(_:)`, starts Bugsnag,
38+
/// and returns the sink.
39+
public static func start(_ config: BugsnagConfiguration) -> BugsnagSink {
40+
configureBugsnagForKotlin(config)
41+
Bugsnag.start(with: config)
42+
return BugsnagSink()
43+
}
44+
45+
public func leaveBreadcrumb(_ message: String) {
46+
Bugsnag.leaveBreadcrumb(withMessage: message)
47+
}
48+
49+
public func notify(with exceptions: [NSException], handled: Bool) {
50+
guard let exception = exceptions.first else { return }
51+
// Notify persists unhandled events, so the caller can safely terminate afterwards.
52+
// https://github.com/bugsnag/bugsnag-cocoa/blob/6bcd46f5f8dc06ac26537875d501f02b27d219a9/Bugsnag/Client/BugsnagClient.m#L744
53+
Bugsnag.notify(exception) { event in
54+
if handled {
55+
event.severity = .warning
56+
} else {
57+
event.unhandled = true
58+
event.severity = .error
59+
}
60+
event.errors += exceptions.dropFirst().map(BugsnagError.init)
61+
return true
62+
}
63+
}
64+
65+
public func addMetadata(_ value: Any, key: String, section: String) {
66+
Bugsnag.addMetadata(value, key: key, section: section)
67+
}
68+
69+
public func markFatalCrashRecorded() {
70+
// Called only by the Kotlin unhandled-exception hook, right before termination —
71+
// never on direct sendFatalException() calls, which would poison the session and
72+
// make the OnSendError filter discard later genuine crashes.
73+
Bugsnag.addFeatureFlag(name: kotlinCrashedFeatureFlag)
74+
}
75+
}
76+
77+
/// In Bugsnag 6.26.2+ the `originalUnhandledValue` property prevents our synthetic
78+
/// unhandled exceptions from being stored to disk; alias it to `unhandled`.
79+
/// https://github.com/bugsnag/bugsnag-cocoa/pull/1549
80+
private func overrideOriginalUnhandledValue() {
81+
guard let handledStateClass = NSClassFromString("BugsnagHandledState"),
82+
let originalMethod = class_getInstanceMethod(handledStateClass, NSSelectorFromString("originalUnhandledValue")),
83+
let method = class_getInstanceMethod(handledStateClass, NSSelectorFromString("unhandled"))
84+
else {
85+
// Loud, not silent: if Bugsnag renames these internals, fatal Kotlin crashes
86+
// would silently stop reaching the dashboard (>=6.26.2 refuses to persist them).
87+
assertionFailure("CrashKiOS: BugsnagHandledState internals changed — Kotlin fatal crashes may not be persisted. Update CrashKiOSBugsnag.")
88+
return
89+
}
90+
method_setImplementation(originalMethod, method_getImplementation(method))
91+
}
92+
93+
private extension BugsnagError {
94+
/// Creates a BugsnagError from a (Kotlin-synthesized) NSException.
95+
convenience init(_ exception: NSException) {
96+
self.init()
97+
errorClass = exception.name.rawValue
98+
errorMessage = exception.reason
99+
stacktrace = BugsnagStackframe.stackframes(withCallStackReturnAddresses: exception.callStackReturnAddresses)
100+
type = .cocoa
101+
}
102+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
// We need this empty file, else SPM won't build this header-only target.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#ifndef CrashKiOSBugsnagSink_h
2+
#define CrashKiOSBugsnagSink_h
3+
4+
#import <Foundation/Foundation.h>
5+
6+
/// Receives crash-reporting events from Kotlin and forwards them to Bugsnag.
7+
///
8+
/// Implemented in Swift, inside the app's build graph — where Bugsnag is already
9+
/// linked — and registered with the Kotlin side via `registerBugsnagSink`.
10+
///
11+
/// Contract for implementations (the shipped `BugsnagSink` does all of this):
12+
/// - MUST NOT throw: Kotlin cannot catch ObjC exceptions thrown across this
13+
/// boundary (KT-53004), and the fatal path runs inside the unhandled-exception hook.
14+
/// - MUST prepare the Bugsnag configuration with `configureBugsnagForKotlin(_:)`
15+
/// (CrashKiOSBugsnag package) before `Bugsnag.start`, otherwise every fatal Kotlin
16+
/// exception is reported twice (the Kotlin notify plus Bugsnag's own report of the
17+
/// termination abort).
18+
@protocol CrashKiOSBugsnagSink <NSObject>
19+
20+
/// Bugsnag `leaveBreadcrumbWithMessage:`.
21+
- (void)leaveBreadcrumb:(NSString * _Nonnull)message;
22+
23+
/// Notify Bugsnag of a Kotlin exception. `exceptions` is `[main, cause, causeOfCause, ...]`;
24+
/// each element's `callStackReturnAddresses` carries its Kotlin stack trace.
25+
/// When `handled` is NO the event must be persisted synchronously before returning
26+
/// (`Bugsnag.notify` does) — the process may terminate right after.
27+
- (void)notifyWithExceptions:(NSArray<NSException *> * _Nonnull)exceptions handled:(BOOL)handled;
28+
29+
/// Bugsnag `addMetadata:key:section:`.
30+
- (void)addMetadata:(id _Nonnull)value key:(NSString * _Nonnull)key section:(NSString * _Nonnull)section;
31+
32+
/// Called by the Kotlin unhandled-exception hook — and ONLY that hook — right after
33+
/// the fatal notify, just before the process terminates. Implementations flag the
34+
/// session (Bugsnag feature flag `crashkios.kotlin_crashed`) so the OnSendError filter
35+
/// installed by `configureBugsnagForKotlin(_:)` drops Bugsnag's own report of the
36+
/// termination abort. Direct `sendFatalException()` calls do NOT trigger this.
37+
- (void)markFatalCrashRecorded;
38+
39+
@end
40+
41+
#endif /* CrashKiOSBugsnagSink_h */
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import Foundation
2+
import CrashKiOSCrashlyticsObjC
3+
import FirebaseCrashlytics
4+
5+
/// Reference `CrashKiOSCrashlyticsSink` implementation.
6+
///
7+
/// Register from your `AppDelegate`, right after Firebase is configured and before
8+
/// any Kotlin code runs:
9+
/// ```swift
10+
/// FirebaseApp.configure()
11+
/// CrashlyticsKt.registerCrashlyticsSink(sink: CrashlyticsSink())
12+
/// ```
13+
/// (The Kotlin function name depends on your framework's export configuration; add
14+
/// `export("co.touchlab.crashkios:crashlytics")` to the framework for clean names.)
15+
public final class CrashlyticsSink: NSObject, CrashKiOSCrashlyticsSink {
16+
17+
private let crashlytics: Crashlytics
18+
19+
public init(_ crashlytics: Crashlytics = Crashlytics.crashlytics()) {
20+
self.crashlytics = crashlytics
21+
}
22+
23+
public func logMessage(_ message: String) {
24+
crashlytics.log(message)
25+
}
26+
27+
public func recordHandledException(withName name: String, reason: String, stackAddresses: [NSNumber]) {
28+
let model = ExceptionModel(name: name, reason: reason)
29+
model.stackTrace = stackAddresses.map { StackFrame(address: $0.uintValue) }
30+
crashlytics.record(exceptionModel: model)
31+
}
32+
33+
public func recordFatalException(_ exception: NSException) {
34+
// Persists synchronously; Crashlytics stores a single fatal per session, so the
35+
// termination abort that follows is not double-reported.
36+
FIRCLSExceptionRecordNSException(exception)
37+
}
38+
39+
public func setCustomValue(_ value: Any?, forKey key: String) {
40+
crashlytics.setCustomValue(value as Any, forKey: key)
41+
}
42+
43+
public func setUserId(_ identifier: String) {
44+
crashlytics.setUserID(identifier)
45+
}
46+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
// We need this empty file, else SPM won't build this header-only target.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#ifndef CrashKiOSCrashlyticsSink_h
2+
#define CrashKiOSCrashlyticsSink_h
3+
4+
#import <Foundation/Foundation.h>
5+
6+
/// Receives crash-reporting events from Kotlin and forwards them to Firebase Crashlytics.
7+
///
8+
/// Implemented in Swift, inside the app's build graph — where FirebaseCrashlytics is
9+
/// already linked — and registered with the Kotlin side via `registerCrashlyticsSink`.
10+
///
11+
/// Implementations MUST NOT throw: Kotlin cannot catch ObjC exceptions thrown across
12+
/// this boundary (KT-53004), and the fatal path runs inside the unhandled-exception hook.
13+
@protocol CrashKiOSCrashlyticsSink <NSObject>
14+
15+
/// Crashlytics `log:`.
16+
- (void)logMessage:(NSString * _Nonnull)message;
17+
18+
/// A non-fatal exception. `addresses` are Kotlin stack-trace return addresses,
19+
/// mappable to `FIRStackFrame stackFrameWithAddress:`.
20+
- (void)recordHandledExceptionWithName:(NSString * _Nonnull)name
21+
reason:(NSString * _Nonnull)reason
22+
stackAddresses:(NSArray<NSNumber *> * _Nonnull)addresses;
23+
24+
/// A fatal exception. The process terminates right after this returns —
25+
/// the record must be persisted synchronously (FIRCLSExceptionRecordNSException does).
26+
/// `exception.callStackReturnAddresses` carries the Kotlin stack trace.
27+
- (void)recordFatalException:(NSException * _Nonnull)exception;
28+
29+
/// Crashlytics `setCustomValue:forKey:`.
30+
- (void)setCustomValue:(id _Nullable)value forKey:(NSString * _Nonnull)key;
31+
32+
/// Crashlytics `setUserID:`.
33+
- (void)setUserId:(NSString * _Nonnull)identifier;
34+
35+
@end
36+
37+
#endif /* CrashKiOSCrashlyticsSink_h */
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#ifndef CrashKiOSFIRCLSException_h
2+
#define CrashKiOSFIRCLSException_h
3+
4+
// Declaration copied from firebase-ios-sdk's private header:
5+
// https://github.com/firebase/firebase-ios-sdk/blob/main/Crashlytics/Crashlytics/Handlers/FIRCLSException.h
6+
//
7+
// Copyright 2019-2020 Google LLC
8+
//
9+
// Licensed under the Apache License, Version 2.0 (the "License");
10+
// you may not use this file except in compliance with the License.
11+
// You may obtain a copy of the License at
12+
//
13+
// http://www.apache.org/licenses/LICENSE-2.0
14+
//
15+
// Unless required by applicable law or agreed to in writing, software
16+
// distributed under the License is distributed on an "AS IS" BASIS,
17+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18+
// See the License for the specific language governing permissions and
19+
// limitations under the License.
20+
21+
#import <Foundation/Foundation.h>
22+
23+
// Records `exception` as the session's fatal exception and persists it synchronously.
24+
// Private Crashlytics SPI, resolved HARD at app link time via the FirebaseCrashlytics
25+
// product this target depends on — nothing dynamic is left for the App Store's
26+
// deployment-processing strip pass to break (the CrashKiOS <= 0.9.0 failure mode).
27+
// Fallback if Firebase ever removes it: -[FIRCrashlytics recordOnDemandExceptionModel:].
28+
extern void FIRCLSExceptionRecordNSException(NSException *exception);
29+
30+
#endif /* CrashKiOSFIRCLSException_h */

0 commit comments

Comments
 (0)