firebase / firebase-ios-sdk

Firebase SDK for Apple App Development
https://firebase.google.com
Apache License 2.0
5.67k stars 1.49k forks source link

Crashed: com.apple.main-thread EXC_BAD_ACCESS KERN_INVALID_ADDRESS -[FIRQueryDocumentSnapshot data] + 44 #10514

Closed philip511 closed 1 year ago

philip511 commented 1 year ago

Description

  1. This is a crash that occurs within seconds of a user opening the app.
  2. This crash occurs randomly, it is not reproducible.
  3. This crash occurs in one place only, in the method that queries all of the user's posts
  4. I have multiple methods that are structured similarly to this method that query different sets of data and the crash does not occur in those methods.
  5. I have checked the data being queried and it is perfectly ok.
  6. It appears that the crash occurs when the FIRDocumentSnapshot's data is trying to be used. (doc.data)
  7. The try, catch block surrounding the method does not prevent the crash.

I am all out of ideas of what to do.

Crashed: com.apple.main-thread
0  FirebaseFirestore              0x905a4 -[FSTUserDataWriter convertedValue:] + 268
1  FirebaseFirestore              0x906cc -[FSTUserDataWriter convertedObject:] + 120
2  FirebaseFirestore              0x90610 -[FSTUserDataWriter convertedValue:] + 376
3  FirebaseFirestore              0x5865c -[FIRDocumentSnapshot dataWithServerTimestampBehavior:] + 200
4  FirebaseFirestore              0x58b14 -[FIRQueryDocumentSnapshot dataWithServerTimestampBehavior:] + 44
5  FirebaseFirestore              0x58a70 -[FIRQueryDocumentSnapshot data] + 44
6  WeDivvy                        0x1189c __125-[GetDataObject GetDataGetItemsInSpecificHome:collection:keyArray:currentViewController:crashlyticsString:completionHandler:]_block_invoke + 1408 (GetDataObject.m:1408)
7  FirebaseFirestore              0x87db0 -[FIRQuery wrapQuerySnapshotBlock:]::Converter::OnEvent(firebase::firestore::util::StatusOr<firebase::firestore::api::QuerySnapshot>) + 128
8  FirebaseFirestore              0x11ce0c firebase::firestore::api::Query::GetDocuments(firebase::firestore::api::Source, std::__1::unique_ptr<firebase::firestore::core::EventListener<firebase::firestore::api::QuerySnapshot>, std::__1::default_delete<firebase::firestore::core::EventListener<firebase::firestore::api::QuerySnapshot> > >&&)::ListenOnce::OnEvent(firebase::firestore::util::StatusOr<firebase::firestore::api::QuerySnapshot>) + 352
9  FirebaseFirestore              0x11d3b8 firebase::firestore::api::Query::AddSnapshotListener(firebase::firestore::core::ListenOptions, std::__1::unique_ptr<firebase::firestore::core::EventListener<firebase::firestore::api::QuerySnapshot>, std::__1::default_delete<firebase::firestore::core::EventListener<firebase::firestore::api::QuerySnapshot> > >&&)::Converter::OnEvent(firebase::firestore::util::StatusOr<firebase::firestore::core::ViewSnapshot>) + 756
10 FirebaseFirestore              0x3d15c void std::__1::__invoke_void_return_wrapper<void, true>::__call<firebase::firestore::core::AsyncEventListener<firebase::firestore::core::ViewSnapshot>::OnEvent(firebase::firestore::util::StatusOr<firebase::firestore::core::ViewSnapshot>)::'lambda'()&>(firebase::firestore::core::AsyncEventListener<firebase::firestore::core::ViewSnapshot>::OnEvent(firebase::firestore::util::StatusOr<firebase::firestore::core::ViewSnapshot>)::'lambda'()&) + 104
11 FirebaseFirestore              0x151604 firebase::firestore::util::Task::ExecuteAndRelease() + 184
12 libdispatch.dylib              0x647c8 _dispatch_client_callout + 16
13 libdispatch.dylib              0x45f18 _dispatch_main_queue_drain + 888
14 libdispatch.dylib              0x45b90 _dispatch_main_queue_callback_4CF$VARIANT$armv81 + 36
15 CoreFoundation                 0x93848 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
16 CoreFoundation                 0x774d4 __CFRunLoopRun + 2096
17 CoreFoundation                 0x7bb7c CFRunLoopRunSpecific + 584
18 GraphicsServices               0x1984 GSEventRunModal + 160
19 UIKitCore                      0x3753c8 -[UIApplication _run] + 868
20 UIKitCore                      0x375040 UIApplicationMain + 312
21 WeDivvy                        0x1af38 main + 18 (main.m:18)
22 ???                            0x1d7bc4df0 (Missing)
-(void)GetDataGetItemsInSpecificHome:(NSString *)homeID collection:(NSString *)collection keyArray:(NSArray *)keyArray currentViewController:(UIViewController *)currentViewController crashlyticsString:(NSString *)crashlyticsString completionHandler:(void (^)(BOOL finished, NSMutableDictionary *returningDataDict))finishBlock {

    @try {

        [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome %@ Processing(1)", collection];

        __block NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];

        FIRFirestore *defaultFirestore = [FIRFirestore firestore];

        [[[defaultFirestore collectionWithPath:collection]
          queryWhereField:@"ItemHomeID" isEqualTo:homeID] getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) {

            [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome %@ Processing(2)", collection];

            for (FIRDocumentSnapshot *doc in snapshot.documents) {

                [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome Processing(3)"];

                for (NSString *key in keyArray) {

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ Processing(4)", crashlyticsString, key];

                    NSMutableArray *arr = dataDict[key] ? [dataDict[key] mutableCopy] : [NSMutableArray array];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ arr:%@ Processing(4.1)", crashlyticsString, key, arr];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ Processing(4.1)", crashlyticsString, key];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ Processing(4.2)", crashlyticsString, key];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc:%@ Processing(4.3)", crashlyticsString, key, doc];

**************************************************************************************************************              
*****************************************Crash Occurs Here Because of doc.data*****************************
**************************************************************************************************************

   [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc:%@ doc.data:%@ Processing(4.4)", crashlyticsString, key, doc, doc.data];

**************************************************************************************************************              
*****************************************Crash Occurs Here Because of doc.data*****************************
**************************************************************************************************************

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc.data[key]:%@ Processing(4.5)", crashlyticsString, key, doc.data[key]];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc.data[key]:%@ GenerateDefaultValueBasedOnKey:%@ Processing(4.6)", crashlyticsString, key, doc.data[key], [[[GeneralObject alloc] init] GenerateDefaultValueBasedOnKey:key]];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc.data[key]:%@ GenerateDefaultValueBasedOnKey:%@ Processing(4.7)", crashlyticsString, key, doc.data[key], [[[GeneralObject alloc] init] GenerateDefaultValueBasedOnKey:key]];

                    id object = doc.data[key] ? doc.data[key] : [[[GeneralObject alloc] init] GenerateDefaultValueBasedOnKey:key];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc.data[key]:%@ GenerateDefaultValueBasedOnKey:%@ object:%@ Processing(4.8)", crashlyticsString, key, doc.data[key], [[[GeneralObject alloc] init] GenerateDefaultValueBasedOnKey:key], object];

                    [arr addObject:object];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc.data[key]:%@ GenerateDefaultValueBasedOnKey:%@ object:%@ arr:%@ Processing(4.9)", crashlyticsString, key, doc.data[key], [[[GeneralObject alloc] init] GenerateDefaultValueBasedOnKey:key], object, arr];

                    [dataDict setObject:arr forKey:key];

                    [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc.data[key]:%@ GenerateDefaultValueBasedOnKey:%@ object:%@ arr:%@ dataDict:%@ Processing(4.10)", crashlyticsString, key, doc.data[key], [[[GeneralObject alloc] init] GenerateDefaultValueBasedOnKey:key], object, arr, dataDict];

                }

            }

            [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome Processing(5)"];

            if (dataDict[@"ItemAssignedTo"]) {

                for (NSMutableArray *itemAssignedTo in dataDict[@"ItemAssignedTo"]) {

                    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UsersUserID"] &&
                        ([itemAssignedTo containsObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UsersUserID"]] || itemAssignedTo.count == 0)) {

                        [[NSUserDefaults standardUserDefaults] setObject:@"Yes" forKey:@"RegisterForNotifications"];

                    }

                }

            }

            [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome Processing(6)"];

            finishBlock(YES, dataDict);

        }];

    } @catch (NSException *exception) {

        NSDictionary *dataDict = @{
            @"CrashLineID" : [[[GeneralObject alloc] init] GenerateRandomESTNumberIntoString] ? [[[GeneralObject alloc] init] GenerateRandomESTNumberIntoString] : @"UnknownCrashLineID",
            @"CrashLineMethod" : [NSString stringWithFormat:@"%@", NSStringFromSelector(_cmd)] ? [NSString stringWithFormat:@"%@", NSStringFromSelector(_cmd)] : @"UnknownCrashMethod",
            @"CrashLineNumber" : [NSString stringWithFormat:@"%d", __LINE__] ? [NSString stringWithFormat:@"%d", __LINE__] : @"UnknownCrashLineNumber",
            @"CrashLineDescription" : [NSString stringWithFormat:@"%@", exception.description] ? [NSString stringWithFormat:@"%@", exception.description] : @"UnknownCrashLineDescription",
            @"CrashLineAppVersion" : @"6.4.40",
            @"CrashLineSubmittedBy" : [[NSUserDefaults standardUserDefaults] objectForKey:@"UsersUserID"] ? [[NSUserDefaults standardUserDefaults] objectForKey:@"UsersUserID"] : @"UnknownCrashSubmittedBy",
            @"CrashDatePosted" : [[[GeneralObject alloc] init] GenerateCurrentDateString] ? [[[GeneralObject alloc] init] GenerateCurrentDateString] : @"UnknownCrashDatePosted",
            @"CrashLineViewController" : @"GetDataObject",
        };

        [[[SetDataObject alloc] init] SetDataCrashLineData:dataDict completionHandler:^(BOOL finished) {

        }];

        [[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome Crashed"];

        finishBlock(YES, [NSMutableDictionary dictionary]);

    }

}

Reproducing the issue

No response

Firebase SDK Version

10.2.0

Xcode Version

14.1.0

Installation Method

CocoaPods

Firebase Product(s)

Analytics, Authentication, Crashlytics, Firestore, Functions, Storage

Targeted Platforms

iOS

Relevant Log Output

No response

If using Swift Package Manager, the project's Package.resolved

Expand Package.resolved snippet
```json Replace this line with the contents of your Package.resolved. ```

If using CocoaPods, the project's Podfile.lock

Expand Podfile.lock snippet
```yml # Uncomment the next line to define a global platform for your project platform :ios, '14.0' target 'WeDivvy' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # Pods for WeDivvy ENV['SWIFT_VERSION'] = '5' pod 'Firebase/Core' pod 'Firebase/Crashlytics' pod 'Firebase/Database' pod 'Firebase/Analytics' pod 'Firebase/Auth' pod 'Firebase/Storage' pod 'Firebase/Messaging' pod 'Firebase/Firestore' pod 'Firebase/Functions' pod 'MRProgress' pod 'InstantSearch' pod 'InstantSearchClient' pod 'SDWebImage' pod 'Mixpanel' pod 'GoogleSignIn' end ```
google-oss-bot commented 1 year ago

I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

morganchen12 commented 1 year ago

@philip511 do you have a full intact crash report? The error message in the title of this issue doesn't match the stack trace.

philip511 commented 1 year ago

@philip511 do you have a full intact crash report? The error message in the title of this issue doesn't match the stack trace.

@morganchen12 For some reason Firebase Crashlytics does not report it in stack trace. This is what I see https://imgur.com/a/DzmxekQ

Here is the full stack trace that I downloaded from Crashlytics com.WeDivvy.WeDivvy_issue_a3452583de58f75dbf8d08c7cd553993_crash_session_30dbf59d92ef494ca8d6fe8c8c7c8cc1_DNE_0_v2_stacktrace.txt

tom-andersen commented 1 year ago

@philip511 I don't see an obvious reason for error. What would be helpful:

philip511 commented 1 year ago

@tom-andersen I'm so sorry I forgot to specify the line where it crashes. I updated my code and posted the line where it crashes below. I've played around with the code several times before posting here and it always seems to crash when doc.data is used. Whether it is being printed or being stored in a variable.

[[FIRCrashlytics crashlytics] logWithFormat:@"GetDataGetItemsInSpecificHome:%@ key:%@ doc:%@ doc.data:%@ Processing(4.4)", crashlyticsString, key, doc, doc.data];

However, the strange thing is this occurs randomly, the data being retrieved is not broken, I have checked. If it was broken the crash would occur over and over again, which it does not. This also doesn't crash right away, sometimes it crashes on the 3rd or 4th iteration of the outer for loop.

for (NSString *key in keyArray) {

tom-andersen commented 1 year ago

This is very difficult to test, but I have a nagging suspicion that doc.data method is invoked lazily by logging, perhaps after loop has exited and data has been released. If you convert doc.data to string, and then pass that string to logger, does the problem disappear?

philip511 commented 1 year ago

@tom-andersen Well, here is the thing. I don't really need to log it, I added those logs to see if I can find what's going wrong. This is my code without the logs. I'm trying to create a dictionary of arrays that looks like this. Also, as a side note I query this same data else where in the app and loop through it the same way as well, and no crash. I'm thinking it's some sort of memory or synchronization issue.

@{ @"ItemName" : @[@"A", @"B", @"C"], @"ItemID" : [@"1", @"2", @"3"] }

__block NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];

        FIRFirestore *defaultFirestore = [FIRFirestore firestore];

        [[[defaultFirestore collectionWithPath:collection]
          queryWhereField:@"ItemHomeID" isEqualTo:homeID] getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) {

            for (FIRDocumentSnapshot *doc in snapshot.documents) {

                for (NSString *key in keyArray) {

                    NSMutableArray *arr = dataDict[key] ? [dataDict[key] mutableCopy] : [NSMutableArray array];

*****************************************Crash Occurs Here Because of doc.data*****************************
**************************************************************************************************************

  id object = doc.data[key] ? doc.data[key] : [[[GeneralObject alloc] init] GenerateDefaultValueBasedOnKey:key];

*****************************************Crash Occurs Here Because of doc.data*****************************
**************************************************************************************************************

                    [arr addObject:object];

                    [dataDict setObject:arr forKey:key];

                }

            }

            finishBlock(YES, dataDict);

        }];
tom-andersen commented 1 year ago

@philip511 Could you try to enable Address Sanitizer since there seems to be a null pointer problem. (see https://developer.apple.com/documentation/xcode/diagnosing-memory-thread-and-crash-issues-early)

We might get lucky and have the location of the problem identified.

philip511 commented 1 year ago

@tom-andersen Got it, will do

google-oss-bot commented 1 year ago

Hey @philip511. We need more information to resolve this issue but there hasn't been an update in 5 weekdays. I'm marking the issue as stale and if there are no new updates in the next 5 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

philip511 commented 1 year ago

@tom-andersen I'm sorry, I've never used Address Sanitizer, I'm trying to figure out how to use this to figure out my issue

philip511 commented 1 year ago

@tom-andersen Do you have any tutorials on how to use Address Sanitizer? I enabled it but there was nothing useful showing in my debug view

tom-andersen commented 1 year ago

@philip511 If it doesn't find any problems then the app will run as normal (although probably much slower!).

morganchen12 commented 1 year ago

@philip511 you may find this Apple documentation helpful.

google-oss-bot commented 1 year ago

Hey @philip511. We need more information to resolve this issue but there hasn't been an update in 5 weekdays. I'm marking the issue as stale and if there are no new updates in the next 5 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

google-oss-bot commented 1 year ago

Since there haven't been any recent updates here, I am going to close this issue.

@philip511 if you're still experiencing this problem and want to continue the discussion just leave a comment here and we are happy to re-open this.