FIRCrashlytics.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright 2019 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdatomic.h>
  15. #if __has_include(<FBLPromises/FBLPromises.h>)
  16. #import <FBLPromises/FBLPromises.h>
  17. #else
  18. #import "FBLPromises.h"
  19. #endif
  20. #import "FIRCLSApplicationIdentifierModel.h"
  21. #include "FIRCLSCrashedMarkerFile.h"
  22. #import "FIRCLSDataCollectionArbiter.h"
  23. #import "FIRCLSDefines.h"
  24. #include "FIRCLSException.h"
  25. #import "FIRCLSFileManager.h"
  26. #include "FIRCLSGlobals.h"
  27. #import "FIRCLSHost.h"
  28. #include "FIRCLSProfiling.h"
  29. #import "FIRCLSReport_Private.h"
  30. #import "FIRCLSSettings.h"
  31. #import "FIRCLSUserDefaults.h"
  32. #include "FIRCLSUserLogging.h"
  33. #include "FIRCLSUtility.h"
  34. #import "FIRCLSByteUtility.h"
  35. #import "FIRCLSFABHost.h"
  36. #import "FIRCLSLogger.h"
  37. #import "FIRCLSReportManager.h"
  38. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  39. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  40. #import "Interop/Analytics/Public/FIRAnalyticsInterop.h"
  41. #import <GoogleDataTransport/GDTCORTargets.h>
  42. #import <GoogleDataTransport/GDTCORTransport.h>
  43. #if TARGET_OS_IPHONE
  44. #import <UIKit/UIKit.h>
  45. #endif
  46. FIRCLSContext _firclsContext;
  47. dispatch_queue_t _firclsLoggingQueue;
  48. dispatch_queue_t _firclsBinaryImageQueue;
  49. dispatch_queue_t _firclsExceptionQueue;
  50. static atomic_bool _hasInitializedInstance;
  51. NSString *const FIRCLSGoogleTransportMappingID = @"1206";
  52. /// Empty protocol to register with FirebaseCore's component system.
  53. @protocol FIRCrashlyticsInstanceProvider <NSObject>
  54. @end
  55. @interface FIRCrashlytics () <FIRLibrary, FIRCrashlyticsInstanceProvider>
  56. @property(nonatomic) BOOL didPreviouslyCrash;
  57. @property(nonatomic, copy) NSString *googleAppID;
  58. @property(nonatomic) FIRCLSDataCollectionArbiter *dataArbiter;
  59. @property(nonatomic) FIRCLSFileManager *fileManager;
  60. @property(nonatomic) FIRCLSReportManager *reportManager;
  61. @property(nonatomic) GDTCORTransport *googleTransport;
  62. @end
  63. @implementation FIRCrashlytics
  64. #pragma mark - Singleton Support
  65. - (instancetype)initWithApp:(FIRApp *)app
  66. appInfo:(NSDictionary *)appInfo
  67. installations:(FIRInstallations *)installations
  68. analytics:(id<FIRAnalyticsInterop>)analytics {
  69. self = [super init];
  70. if (self) {
  71. bool expectedCalled = NO;
  72. if (!atomic_compare_exchange_strong(&_hasInitializedInstance, &expectedCalled, YES)) {
  73. FIRCLSErrorLog(@"Cannot instantiate more than one instance of Crashlytics.");
  74. return nil;
  75. }
  76. FIRCLSProfileMark mark = FIRCLSProfilingStart();
  77. NSLog(@"[Firebase/Crashlytics] Version %@", @CLS_SDK_DISPLAY_VERSION);
  78. FIRCLSDeveloperLog("Crashlytics", @"Running on %@, %@ (%@)", FIRCLSHostModelInfo(),
  79. FIRCLSHostOSDisplayVersion(), FIRCLSHostOSBuildVersion());
  80. _googleTransport = [[GDTCORTransport alloc] initWithMappingID:FIRCLSGoogleTransportMappingID
  81. transformers:nil
  82. target:kGDTCORTargetCSH];
  83. _fileManager = [[FIRCLSFileManager alloc] init];
  84. _googleAppID = app.options.googleAppID;
  85. _dataArbiter = [[FIRCLSDataCollectionArbiter alloc] initWithApp:app withAppInfo:appInfo];
  86. FIRCLSApplicationIdentifierModel *appModel = [[FIRCLSApplicationIdentifierModel alloc] init];
  87. FIRCLSSettings *settings = [[FIRCLSSettings alloc] initWithFileManager:_fileManager
  88. appIDModel:appModel];
  89. _reportManager = [[FIRCLSReportManager alloc] initWithFileManager:_fileManager
  90. installations:installations
  91. analytics:analytics
  92. googleAppID:_googleAppID
  93. dataArbiter:_dataArbiter
  94. googleTransport:_googleTransport
  95. appIDModel:appModel
  96. settings:settings];
  97. // Process did crash during previous execution
  98. NSString *crashedMarkerFileName = [NSString stringWithUTF8String:FIRCLSCrashedMarkerFileName];
  99. NSString *crashedMarkerFileFullPath =
  100. [[_fileManager rootPath] stringByAppendingPathComponent:crashedMarkerFileName];
  101. _didPreviouslyCrash = [_fileManager fileExistsAtPath:crashedMarkerFileFullPath];
  102. if (_didPreviouslyCrash) {
  103. // Delete the crash file marker in the background ensure start up is as fast as possible
  104. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  105. [self.fileManager removeItemAtPath:crashedMarkerFileFullPath];
  106. });
  107. }
  108. [[[_reportManager startWithProfilingMark:mark] then:^id _Nullable(NSNumber *_Nullable value) {
  109. if (![value boolValue]) {
  110. FIRCLSErrorLog(@"Crash reporting could not be initialized");
  111. }
  112. return value;
  113. }] catch:^void(NSError *error) {
  114. FIRCLSErrorLog(@"Crash reporting failed to initialize with error: %@", error);
  115. }];
  116. }
  117. return self;
  118. }
  119. + (void)load {
  120. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  121. withName:@"firebase-crashlytics"
  122. withVersion:@CLS_SDK_DISPLAY_VERSION];
  123. }
  124. + (NSArray<FIRComponent *> *)componentsToRegister {
  125. FIRDependency *analyticsDep =
  126. [FIRDependency dependencyWithProtocol:@protocol(FIRAnalyticsInterop)];
  127. FIRComponentCreationBlock creationBlock =
  128. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  129. if (!container.app.isDefaultApp) {
  130. FIRCLSErrorLog(@"Crashlytics must be used with the default Firebase app.");
  131. return nil;
  132. }
  133. id<FIRAnalyticsInterop> analytics = FIR_COMPONENT(FIRAnalyticsInterop, container);
  134. FIRInstallations *installations = [FIRInstallations installationsWithApp:container.app];
  135. *isCacheable = YES;
  136. return [[FIRCrashlytics alloc] initWithApp:container.app
  137. appInfo:NSBundle.mainBundle.infoDictionary
  138. installations:installations
  139. analytics:analytics];
  140. };
  141. FIRComponent *component =
  142. [FIRComponent componentWithProtocol:@protocol(FIRCrashlyticsInstanceProvider)
  143. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  144. dependencies:@[ analyticsDep ]
  145. creationBlock:creationBlock];
  146. return @[ component ];
  147. }
  148. + (instancetype)crashlytics {
  149. // The container will return the same instance since isCacheable is set
  150. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  151. // Get the instance from the `FIRApp`'s container. This will create a new instance the
  152. // first time it is called, and since `isCacheable` is set in the component creation
  153. // block, it will return the existing instance on subsequent calls.
  154. id<FIRCrashlyticsInstanceProvider> instance =
  155. FIR_COMPONENT(FIRCrashlyticsInstanceProvider, defaultApp.container);
  156. // In the component creation block, we return an instance of `FIRCrashlytics`. Cast it and
  157. // return it.
  158. return (FIRCrashlytics *)instance;
  159. }
  160. - (void)setCrashlyticsCollectionEnabled:(BOOL)enabled {
  161. [self.dataArbiter setCrashlyticsCollectionEnabled:enabled];
  162. }
  163. - (BOOL)isCrashlyticsCollectionEnabled {
  164. return [self.dataArbiter isCrashlyticsCollectionEnabled];
  165. }
  166. #pragma mark - API: didCrashDuringPreviousExecution
  167. - (BOOL)didCrashDuringPreviousExecution {
  168. return self.didPreviouslyCrash;
  169. }
  170. - (void)processDidCrashDuringPreviousExecution {
  171. NSString *crashedMarkerFileName = [NSString stringWithUTF8String:FIRCLSCrashedMarkerFileName];
  172. NSString *crashedMarkerFileFullPath =
  173. [[self.fileManager rootPath] stringByAppendingPathComponent:crashedMarkerFileName];
  174. self.didPreviouslyCrash = [self.fileManager fileExistsAtPath:crashedMarkerFileFullPath];
  175. if (self.didPreviouslyCrash) {
  176. // Delete the crash file marker in the background ensure start up is as fast as possible
  177. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  178. [self.fileManager removeItemAtPath:crashedMarkerFileFullPath];
  179. });
  180. }
  181. }
  182. #pragma mark - API: Logging
  183. - (void)log:(NSString *)msg {
  184. FIRCLSLog(@"%@", msg);
  185. }
  186. - (void)logWithFormat:(NSString *)format, ... {
  187. va_list args;
  188. va_start(args, format);
  189. [self logWithFormat:format arguments:args];
  190. va_end(args);
  191. }
  192. - (void)logWithFormat:(NSString *)format arguments:(va_list)args {
  193. [self log:[[NSString alloc] initWithFormat:format arguments:args]];
  194. }
  195. #pragma mark - API: Accessors
  196. - (void)checkForUnsentReportsWithCompletion:(void (^)(BOOL))completion {
  197. [[self.reportManager checkForUnsentReports] then:^id _Nullable(NSNumber *_Nullable value) {
  198. completion([value boolValue]);
  199. return nil;
  200. }];
  201. }
  202. - (void)sendUnsentReports {
  203. [self.reportManager sendUnsentReports];
  204. }
  205. - (void)deleteUnsentReports {
  206. [self.reportManager deleteUnsentReports];
  207. }
  208. #pragma mark - API: setUserID
  209. - (void)setUserID:(NSString *)userID {
  210. FIRCLSUserLoggingRecordInternalKeyValue(FIRCLSUserIdentifierKey, userID);
  211. }
  212. #pragma mark - API: setCustomValue
  213. - (void)setCustomValue:(id)value forKey:(NSString *)key {
  214. FIRCLSUserLoggingRecordUserKeyValue(key, value);
  215. }
  216. #pragma mark - API: Development Platform
  217. // These two methods are depercated by our own API, so
  218. // its ok to implement them
  219. #pragma clang diagnostic push
  220. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  221. + (void)setDevelopmentPlatformName:(NSString *)name {
  222. [[self crashlytics] setDevelopmentPlatformName:name];
  223. }
  224. + (void)setDevelopmentPlatformVersion:(NSString *)version {
  225. [[self crashlytics] setDevelopmentPlatformVersion:version];
  226. }
  227. #pragma clang diagnostic pop
  228. - (NSString *)developmentPlatformName {
  229. FIRCLSErrorLog(@"developmentPlatformName is write-only");
  230. return nil;
  231. }
  232. - (void)setDevelopmentPlatformName:(NSString *)developmentPlatformName {
  233. FIRCLSUserLoggingRecordInternalKeyValue(FIRCLSDevelopmentPlatformNameKey,
  234. developmentPlatformName);
  235. }
  236. - (NSString *)developmentPlatformVersion {
  237. FIRCLSErrorLog(@"developmentPlatformVersion is write-only");
  238. return nil;
  239. }
  240. - (void)setDevelopmentPlatformVersion:(NSString *)developmentPlatformVersion {
  241. FIRCLSUserLoggingRecordInternalKeyValue(FIRCLSDevelopmentPlatformVersionKey,
  242. developmentPlatformVersion);
  243. }
  244. #pragma mark - API: Errors and Exceptions
  245. - (void)recordError:(NSError *)error {
  246. FIRCLSUserLoggingRecordError(error, nil);
  247. }
  248. - (void)recordExceptionModel:(FIRExceptionModel *)exceptionModel {
  249. FIRCLSExceptionRecordModel(exceptionModel);
  250. }
  251. @end