getsentry / sentry-dotnet

Sentry SDK for .NET
https://docs.sentry.io/platforms/dotnet
MIT License
598 stars 207 forks source link

Sentry.MAUI crashing when launching #3235

Closed Curs3W4ll closed 5 months ago

Curs3W4ll commented 8 months ago

Package

Sentry.Maui

.NET Flavor

Xamarin

.NET Version

7.0.407

OS

macOS

SDK Version

4.2.1

Self-Hosted Sentry Version

No response

Steps to Reproduce

  1. Create a basic MAUI app
  2. Add Sentry to it in MauiProgram.cs
  3. Launch the app

Expected Result

The app is launching and logging into Sentry

Actual Result

The app is crashing, below error details

2024-03-21 14:35:23.892 Sentry.reproduce[5261:74199] 
Unhandled Exception:
System.Exception: Could not create an native instance of the type 'Sentry.CocoaSdk.SentryOptions': the native class hasn't been loaded.
It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.
   at Foundation.NSObject.InitializeObject(Boolean alloced)
   at Foundation.NSObject..ctor(NSObjectFlag x)
   at Sentry.CocoaSdk.SentryOptions..ctor()
   at Sentry.SentrySdk.InitSentryCocoaSdk(SentryOptions options)
   at Sentry.SentrySdk.InitHub(SentryOptions options)
   at Sentry.SentrySdk.Init(SentryOptions options)
   at Sentry.Maui.Internal.SentryMauiInitializer.Initialize(IServiceProvider services)
   at Microsoft.Maui.Hosting.MauiAppBuilder.Build()
   at Sentry.reproduce.MauiProgram.CreateMauiApp() in /private/tmp/Sentry.reproduce/Sentry.reproduce/MauiProgram.cs:line 33
   at Sentry.reproduce.AppDelegate.CreateMauiApp() in /private/tmp/Sentry.reproduce/Sentry.reproduce/Platforms/MacCatalyst/AppDelegate.cs:line 8
   at Microsoft.Maui.MauiUIApplicationDelegate.WillFinishLaunching(UIApplication application, NSDictionary launchOptions)
   at UIKit.UIApplication.UIApplicationMain(Int32 argc, String[] argv, IntPtr principalClassName, IntPtr delegateClassName)
   at UIKit.UIApplication.Main(String[] args, Type principalClass, Type delegateClass)
   at Sentry.reproduce.Program.Main(String[] args) in /private/tmp/Sentry.reproduce/Sentry.reproduce/Platforms/MacCatalyst/Program.cs:line 13
2024-03-21 14:35:23.893 Sentry.reproduce[5261:74199] Unhandled managed exception: Could not create an native instance of the type 'Sentry.CocoaSdk.SentryOptions': the native class hasn't been loaded.
It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false. (System.Exception)
   at Foundation.NSObject.InitializeObject(Boolean alloced)
   at Foundation.NSObject..ctor(NSObjectFlag x)
   at Sentry.CocoaSdk.SentryOptions..ctor()
   at Sentry.SentrySdk.InitSentryCocoaSdk(SentryOptions options)
   at Sentry.SentrySdk.InitHub(SentryOptions options)
   at Sentry.SentrySdk.Init(SentryOptions options)
   at Sentry.Maui.Internal.SentryMauiInitializer.Initialize(IServiceProvider services)
   at Microsoft.Maui.Hosting.MauiAppBuilder.Build()
   at Sentry.reproduce.MauiProgram.CreateMauiApp() in /private/tmp/Sentry.reproduce/Sentry.reproduce/MauiProgram.cs:line 33
   at Sentry.reproduce.AppDelegate.CreateMauiApp() in /private/tmp/Sentry.reproduce/Sentry.reproduce/Platforms/MacCatalyst/AppDelegate.cs:line 8
   at Microsoft.Maui.MauiUIApplicationDelegate.WillFinishLaunching(UIApplication application, NSDictionary launchOptions)
   at UIKit.UIApplication.UIApplicationMain(Int32 argc, String[] argv, IntPtr principalClassName, IntPtr delegateClassName)
   at UIKit.UIApplication.Main(String[] args, Type principalClass, Type delegateClass)
   at Sentry.reproduce.Program.Main(String[] args) in /private/tmp/Sentry.reproduce/Sentry.reproduce/Platforms/MacCatalyst/Program.cs:line 13

=================================================================
    Native Crash Reporting
=================================================================
Got a SIGABRT while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries 
used by your application.
=================================================================

=================================================================
    Native stacktrace:
=================================================================
    0x1028c8bdc - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : mono_dump_native_crash_info
    0x10288ec0c - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : mono_handle_native_crash
    0x1029c548c - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : sigabrt_signal_handler.cold.1
    0x1028c8490 - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : mono_runtime_setup_stat_profiler
    0x1904ff584 - /usr/lib/system/libsystem_platform.dylib : _sigtramp
    0x1904cec20 - /usr/lib/system/libsystem_pthread.dylib : pthread_kill
    0x1903dba20 - /usr/lib/system/libsystem_c.dylib : abort
    0x102557328 - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : xamarin_find_protocol_wrapper_type
    0x10272d5c0 - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : mono_invoke_unhandled_exception_hook
    0x102874160 - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : mono_jit_exec
    0x1025699fc - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : xamarin_main
    0x1029c5148 - /private/tmp/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-arm64/Sentry.reproduce.app/Contents/MacOS/Sentry.reproduce : main
    0x1901460e0 - /usr/lib/dyld : start
Curs3W4ll commented 8 months ago

MacOS version: Sonoma 14.4 (23E214)

bitsandfoxes commented 7 months ago

Thanks for reaching out. I'll be giving this a try locally.

Curs3W4ll commented 7 months ago

If needed, below is the reproduced example.

sentry.reproduce.zip

jamescrosswell commented 7 months ago

Hi @Curs3W4ll ,

I tried this myself with a new MAUI project (in Rider) and also tried opening/running the example that you provided but was unable to reproduce the issue. In both cases, the application runs fine for me.

From the logs, it looked like you were trying to run the MAUI application using macCatalyst, which is also what I tried.

The only thing I did have to change in the project (simply to get it to run) was to comment out this line in your csproj file:

<!--        <RuntimeIdentifier>maccatalyst-arm64</RuntimeIdentifier>-->
Curs3W4ll commented 7 months ago

Hey @jamescrosswell

I changed it, but it is still crashing.

I have the same error on another MacOS machine, with the same version. FYI, this issue has been raised 1 day after I updated my Mac a few days ago.

PS: I tried with .net 8, and there is no issue.

jamescrosswell commented 7 months ago

FYI, this issue has been raised 1 day after I updated my Mac a few days ago.

OK... that was it. I was running macOS 14.2.1 (23C71). After upgrading to 14.4.1 I'm able to reproduce... now just a matter of working out why.

jamescrosswell commented 7 months ago

If I'm reading the crash report that I'm getting correctly, the error seems to happen as a result of a call to sendAllCachedEnvelopes in the Cocoa SDK.

@bitsandfoxes I'm not sure how we dig into that further though. Are you able to check with the cocoa folks to see if this is something they've seen already (seems to relate to some change that was made with one of the most recent releases of macOS - possibly 14.4.1 but I skipped a few versions so it could have been anything after 14.2.1 afaik).

Here are the frames I'm seeing on the crashed thread:

Error Formulating Crash Report:
PC register does not match crashing frame (0x0 vs 0x7FF8AA436A78)

Thread 0 Crashed:: tid_103 Dispatch queue: com.apple.main-thread
0   ???                                 0x7ff8aa436a78 ???
1   libsystem_kernel.dylib              0x7ff81a1a714a __pthread_kill + 10
2   libsystem_pthread.dylib             0x7ff81a1dfebd pthread_kill + 262
3   libsystem_c.dylib                   0x7ff81a105a39 abort + 126
4   Sentry.reproduce                       0x100d14aed sigabrt_signal_handler.cold.1 + 45 (mini-posix.c:226)
5   Sentry.reproduce                       0x100c30738 sigabrt_signal_handler + 152 (mini-posix.c:224)
6   libsystem_platform.dylib            0x7ff81a20efdd _sigtramp + 29
7   ???                             0xffffaaaaaaaaaaaa ???
8   libsystem_c.dylib                   0x7ff81a105a39 abort + 126
9   libsystem_malloc.dylib              0x7ff81a00a009 malloc_vreport + 857
10  libsystem_malloc.dylib              0x7ff81a00d5da malloc_report + 151
11  libicucore.A.dylib                  0x7ff81d110f05 icu::Locale::setToBogus() + 43
12  libicucore.A.dylib                  0x7ff81d11127e icu::Locale::operator=(icu::Locale const&) + 30
13  libicucore.A.dylib                  0x7ff81d25de22 icu::number::UnlocalizedNumberFormatter::locale(icu::Locale const&) && + 14
14  libicucore.A.dylib                  0x7ff81d2080db icu::DecimalFormat::touch(UErrorCode&) + 257
15  libicucore.A.dylib                  0x7ff81d20880b icu::DecimalFormat::DecimalFormat(icu::UnicodeString const&, icu::DecimalFormatSymbols*, UNumberFormatStyle, UErrorCode&) + 297
16  libicucore.A.dylib                  0x7ff81d27a329 icu::NumberFormat::makeInstance(icu::Locale const&, UNumberFormatStyle, signed char, UErrorCode&) + 1339
17  libicucore.A.dylib                  0x7ff81d279c97 icu::LocaleCacheKey<icu::SharedNumberFormat>::createObject(void const*, UErrorCode&) const + 81
18  libicucore.A.dylib                  0x7ff81d195604 icu::UnifiedCache::_get(icu::CacheKeyBase const&, icu::SharedObject const*&, void const*, UErrorCode&) const + 106
19  libicucore.A.dylib                  0x7ff81d27a862 0x7ff81d0f4000 + 1599586
20  libicucore.A.dylib                  0x7ff81d279d97 0x7ff81d0f4000 + 1596823
21  libicucore.A.dylib                  0x7ff81d2797e6 icu::NumberFormat::createInstance(icu::Locale const&, UNumberFormatStyle, UErrorCode&) + 42
22  libicucore.A.dylib                  0x7ff81d2c2354 icu::SimpleDateFormat::initialize(icu::Locale const&, UErrorCode&) + 656
23  libicucore.A.dylib                  0x7ff81d2c3203 icu::SimpleDateFormat::SimpleDateFormat(icu::Locale const&, UErrorCode&) + 317
24  libicucore.A.dylib                  0x7ff81d1fb344 icu::DateFormat::create(icu::DateFormat::EStyle, icu::DateFormat::EStyle, icu::Locale const&) + 230
25  libicucore.A.dylib                  0x7ff81d2f336e udat_open + 377
26  CoreFoundation                      0x7ff81a2f857b __cficu_udat_open + 48
27  CoreFoundation                      0x7ff81a2f77c5 __ResetUDateFormat + 518
28  CoreFoundation                      0x7ff81a2f758a __CreateCFDateFormatter + 320
29  Foundation                          0x7ff81b1f3ddf -[NSDateFormatter _regenerateFormatter] + 323
30  Foundation                          0x7ff81b1f3b5f -[NSDateFormatter stringForObjectValue:] + 298
31  Sentry                                 0x10ab49516 -[NSDate(SentryExtras) sentry_toIso8601String] + 65
32  Sentry                                 0x10ab03dc3 +[SentrySerialization dataWithEnvelope:error:] + 581
33  Sentry                                 0x10ab210a9 -[SentryNSURLRequestBuilder createEnvelopeRequest:dsn:didFailWithError:] + 96
34  Sentry                                 0x10ab3a7f5 -[SentryHttpTransport sendAllCachedEnvelopes] + 1279
35  Sentry                                 0x10ab391c8 -[SentryHttpTransport initWithOptions:fileManager:requestManager:requestBuilder:rateLimits:envelopeRateLimit:dispatchQueueWrapper:] + 467
36  Sentry                                 0x10ab5a97a +[SentryTransportFactory initTransports:sentryFileManager:] + 547
37  Sentry                                 0x10aaf7b60 -[SentryClient initWithOptions:fileManager:deleteOldEnvelopeItems:] + 84
38  Sentry                                 0x10aaf7ad0 -[SentryClient initWithOptions:dispatchQueue:deleteOldEnvelopeItems:] + 442
39  Sentry                                 0x10aaf78f4 -[SentryClient initWithOptions:] + 72
40  Sentry                                 0x10ab5b4f0 +[SentrySDK startWithOptions:] + 481
41  Sentry.reproduce                       0x1008645b9 xamarin_dyn_objc_msgSend + 217 (trampolines-x86_64-objc_msgSend.s:15)
42  ???                                    0x10a40cca7 ???
43  Sentry.reproduce                       0x100c42aaa ves_pinvoke_method + 474 (interp.c:1730)
44  Sentry.reproduce                       0x100c34cd5 interp_exec_method + 3717 (interp.c:3914)
45  Sentry.reproduce                       0x100c32483 interp_runtime_invoke + 259 (interp.c:2122)
46  Sentry.reproduce                       0x100a9afd8 do_runtime_invoke + 54 (object.c:2399) [inlined]
47  Sentry.reproduce                       0x100a9afd8 mono_runtime_invoke_checked + 136 (object.c:2567)
48  Sentry.reproduce                       0x100a9e8fe mono_runtime_invoke + 142 (object.c:2454)
49  Sentry.reproduce                       0x10085d483 xamarin_invoke_trampoline + 6291 (trampolines-invoke.m:599)
50  Sentry.reproduce                       0x100863259 xamarin_arch_trampoline + 105 (trampolines-x86_64.m:491)
51  Sentry.reproduce                       0x10086443a xamarin_x86_64_common_trampoline + 118 (trampolines-x86_64-asm.s:51)
52  UIKitCore                           0x7ff92b46047b -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 181
53  UIKitCore                           0x7ff92b45f5ac -[UIApplication _callInitializationDelegatesWithActions:forCanvas:payload:fromOriginatingProcess:] + 4215
54  UIKitCore                           0x7ff92b45cf1a -[UIApplication _runWithMainScene:transitionContext:completion:] + 1574
55  UIKitCore                           0x7ff92b45c807 -[_UISceneLifecycleMultiplexer completeApplicationLaunchWithFBSScene:transitionContext:] + 122
56  UIKitCore                           0x7ff92b458986 _UIScenePerformActionsWithLifecycleActionMask + 87
57  UIKitCore                           0x7ff92b45bfc6 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke + 198
58  UIKitCore                           0x7ff92b45bda6 -[_UISceneLifecycleMultiplexer _performBlock:withApplicationOfDeactivationReasons:fromReasons:] + 374
59  UIKitCore                           0x7ff92b45b106 -[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:] + 814
60  UIKitCore                           0x7ff92b45ad20 -[_UISceneLifecycleMultiplexer uiScene:transitionedFromState:withTransitionContext:] + 341
61  UIKitCore                           0x7ff92b458fff __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block_invoke + 174
62  UIKitCore                           0x7ff92bece15f +[BSAnimationSettings(UIKit) tryAnimatingWithSettings:fromCurrentState:actions:completion:] + 846
63  UIKitCore                           0x7ff92bffca41 _UISceneSettingsDiffActionPerformChangesWithTransitionContextAndCompletion + 261
64  UIKitCore                           0x7ff92b458b1c -[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:] + 347
65  UIKitCore                           0x7ff92b818f62 __64-[UIScene scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke.641 + 879
66  UIKitCore                           0x7ff92b457da3 -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 244
67  UIKitCore                           0x7ff92b457bf0 -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 242
68  UIKitCore                           0x7ff92b44b3e1 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 708
69  UIKitCore                           0x7ff92b44b08c -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 353
70  FrontBoardServices                  0x7ff83118b83b -[FBSScene _callOutQueue_didCreateWithTransitionContext:completion:] + 406
71  FrontBoardServices                  0x7ff8311b5c23 __92-[FBSWorkspaceScenesClient createSceneWithIdentity:parameters:transitionContext:completion:]_block_invoke.254 + 279
72  FrontBoardServices                  0x7ff831174538 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 213
73  FrontBoardServices                  0x7ff8311b591d __92-[FBSWorkspaceScenesClient createSceneWithIdentity:parameters:transitionContext:completion:]_block_invoke + 328
74  libdispatch.dylib                   0x7ff81a03edbc _dispatch_client_callout + 8
75  libdispatch.dylib                   0x7ff81a041e39 _dispatch_block_invoke_direct + 282
76  FrontBoardServices                  0x7ff83117444e __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
77  FrontBoardServices                  0x7ff8311d661c -[FBSMainRunLoopSerialQueue _targetQueue_performNextIfPossible] + 190
78  FrontBoardServices                  0x7ff8311d673a -[FBSMainRunLoopSerialQueue _performNextFromRunLoopSource] + 19
79  CoreFoundation                      0x7ff81a2bd226 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
80  CoreFoundation                      0x7ff81a2bd1c9 __CFRunLoopDoSource0 + 157
81  CoreFoundation                      0x7ff81a2bcf98 __CFRunLoopDoSources0 + 215
82  CoreFoundation                      0x7ff81a2bbc08 __CFRunLoopRun + 919
83  CoreFoundation                      0x7ff81a2bb2a9 CFRunLoopRunSpecific + 557
84  HIToolbox                           0x7ff8251a6829 RunCurrentEventLoopInMode + 292
85  HIToolbox                           0x7ff8251a6466 ReceiveNextEventCommon + 201
86  HIToolbox                           0x7ff8251a6381 _BlockUntilNextEventMatchingListInModeWithFilter + 66
87  AppKit                              0x7ff81d884be5 _DPSNextEvent + 880
88  AppKit                              0x7ff81e194fe9 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1273
89  AppKit                              0x7ff81d876005 -[NSApplication run] + 603
90  AppKit                              0x7ff81d849ff1 NSApplicationMain + 816
91  AppKit                              0x7ff81dafd299 _NSApplicationMainWithInfoDictionary + 16
92  UIKitMacHelper                      0x7ff8349ead8f UINSApplicationMain + 1329
93  UIKitCore                           0x7ff92b42f2f9 UIApplicationMain + 144
94  Sentry.reproduce                       0x10083a9fa xamarin_UIApplicationMain + 58 (bindings.m:126)
95  Sentry.reproduce                       0x100c43ca9 do_icall + 345 (interp.c:2321)
96  Sentry.reproduce                       0x100c42783 do_icall_wrapper + 291 (interp.c:2361)
97  Sentry.reproduce                       0x100c34b2f interp_exec_method + 3295
98  Sentry.reproduce                       0x100c32483 interp_runtime_invoke + 259 (interp.c:2122)
99  Sentry.reproduce                       0x100a9afd8 do_runtime_invoke + 54 (object.c:2399) [inlined]
100 Sentry.reproduce                       0x100a9afd8 mono_runtime_invoke_checked + 136 (object.c:2567)
101 Sentry.reproduce                       0x100aa1cdc do_exec_main_checked + 92
102 Sentry.reproduce                       0x100bbd722 mono_jit_exec_internal + 14 (driver.c:1365) [inlined]
103 Sentry.reproduce                       0x100bbd722 mono_jit_exec + 354 (driver.c:1310)
104 Sentry.reproduce                       0x100863143 xamarin_main + 787 (monotouch-main.m:490)
105 Sentry.reproduce                       0x100d14794 main + 52 (main.x86_64.mm:84)
106 dyld                                   0x201572366 start + 1942
bitsandfoxes commented 7 months ago

@philipphofmann, @brustolin could you help us out here?

philipphofmann commented 7 months ago

@jamescrosswell, I haven't seen this specific crash yet, but we have somewhat related crashes in our internal SDK crash detection. The error seems to happen at sentry_toIso8601String. If you can reproduce it, it would be great to set a breakpoint there and see what value the NSDate has. Then we can fix this.

Update We already have an issue for this crash, but can't reproduce it https://github.com/getsentry/sentry-cocoa/issues/3546.

jamescrosswell commented 7 months ago

If you can reproduce it, it would be great to set a breakpoint there and see what value the NSDate has. Then we can fix this.

Hey @philipphofmann, I can reproduce it easily enough... but I've got no idea how I could put a breakpoint in the Cocoa code.

We're building a MAUI application that imports sentry-cocoa as a module via something called ObjectiveSharpie, which generates the marshalling code and some .NET APIs that wrap that. I think essentially we're importing the compiled sentry-cocoa module then - the marshalling code uses header files to work out the relative offsets for functions etc. that it needs to call.

I don't know of any XCode project or anything that I could open where a breakpoint could be set then... about the only way I can think of debugging it is by using logging.

philipphofmann commented 7 months ago

@jamescrosswell, using logging to print the value should be enough.

jamescrosswell commented 7 months ago

@jamescrosswell, using logging to print the value should be enough.

Hey @philipphofmann, sorry this took me a while... I've never written Objective-C before! I got there in the end though:

2024-04-09 19:09:03.064 Sentry.reproduce[34910:1617737] sentry_fromIso8601String called with string: 2024-04-09T05:46:55Z

Looks like a pretty standard date time string (ISO8601 formatted, in fact). I'm guessing this isn't the source of our troubles then...

philipphofmann commented 7 months ago

No worries, @jamescrosswell. Does the code crash after your log message? If yes, that's weird.

You could try to modify the code sentry_toIso8601String to return a fixed date instead of formatting the date to a string and check if it still crashes. If it doesn't then the call to stringFromDate seems to be the culprit, which would be extremely weird.

jamescrosswell commented 7 months ago

No worries, @jamescrosswell. Does the code crash after your log message? If yes, that's weird.

Hey @philipphofmann. So actually it turns out it's coming from SentryCrashReportConverter.

I logged the heck out of that method:

- (SentryEvent *_Nullable)convertReportToEvent
{
    @try {
        NSLog(@"entering convertReportToEvent");

        NSLog(@"convertReportToEvent: Initializing SentryEvent");
        SentryEvent *event = [[SentryEvent alloc] initWithLevel:kSentryLevelFatal];

        NSLog(@"convertReportToEvent: Setting event.timestamp");
        if ([self.report[@"report"][@"timestamp"] isKindOfClass:NSNumber.class]) {
            event.timestamp = [NSDate
                dateWithTimeIntervalSince1970:[self.report[@"report"][@"timestamp"] integerValue]];
        } else {
            NSString *timestampString = self.report[@"report"][@"timestamp"];
            NSLog(@"Timestamp before conversion: %@", timestampString);
            event.timestamp =
                [NSDate sentry_fromIso8601String:self.report[@"report"][@"timestamp"]];
        }
        NSLog(@"convertReportToEvent: Setting event.threads");
        event.threads = [self convertThreads];
        NSLog(@"convertReportToEvent: Setting event.debugMeta");
        event.debugMeta = [self debugMetaForThreads:event.threads];
        NSLog(@"convertReportToEvent: Setting event.exceptions");
        event.exceptions = [self convertExceptions];

        ...<snip>...
}

And here's what pops out on the console:

/usr/bin/open /Users/jamescrosswell/code/Sentry.reproduce/Sentry.reproduce/bin/Debug/net7.0-maccatalyst/maccatalyst-x64/Sentry.reproduce.app
2024-04-11 22:01:59.848 Sentry.reproduce[94200:1236078] entering convertReportToEvent
2024-04-11 22:01:59.849 Sentry.reproduce[94200:1236078] convertReportToEvent: Initializing SentryEvent
2024-04-11 22:01:59.849 Sentry.reproduce[94200:1236078] convertReportToEvent: Setting event.timestamp
2024-04-11 22:01:59.849 Sentry.reproduce[94200:1236078] Timestamp before conversion: 2024-04-11T09:34:17Z
2024-04-11 22:01:59.849 Sentry.reproduce[94200:1236078] sentry_fromIso8601String called with string: 2024-04-11T09:34:17Z
ERROR: SentryCrashMachineContext.c (180): void sentrycrashmc_suspendEnvironment_upToMaxSupportedThreads(thread_act_array_t *, mach_msg_type_number_t *, mach_msg_type_number_t): thread_suspend (00001f03): (ipc/send) invalid destination port
ERROR: SentryCrashCPU.c (59): _Bool sentrycrashcpu_i_fillState(const thread_t, const thread_state_t, const thread_state_flavor_t, const mach_msg_type_number_t): thread_get_state: (ipc/send) invalid destination port
ERROR: SentryCrashCPU.c (59): _Bool sentrycrashcpu_i_fillState(const thread_t, const thread_state_t, const thread_state_flavor_t, const mach_msg_type_number_t): thread_get_state: (ipc/send) invalid destination port
ERROR: SentryCrashCPU.c (59): _Bool sentrycrashcpu_i_fillState(const thread_t, const thread_state_t, const thread_state_flavor_t, const mach_msg_type_number_t): thread_get_state: (os/kern) invalid argument
ERROR: SentryCrashCPU.c (59): _Bool sentrycrashcpu_i_fillState(const thread_t, const thread_state_t, const thread_state_flavor_t, const mach_msg_type_number_t): thread_get_state: (os/kern) invalid argument
ERROR: SentryCrashMachineContext.c (209): void sentrycrashmc_resumeEnvironment(thread_act_array_t, mach_msg_type_number_t): thread_resume (00001f03): (ipc/send) invalid destination port

There's a full Native Crash report with the stack trace from above as well... so it looks like it dies when calling sentry_fromIso8601String (with a perfectly well formatted date/time string). Either that or when assigning the result to event.timestamp but from the stack trace it doesn't look like it gets that far before an exception is thrown.

Very mysterious...

jamescrosswell commented 7 months ago

Hm, actually I wonder if this has anything to do with the native code. The error in the console looks like maybe the thread that the Sentry-Cocoa code is running on was suspended.

In addition to the Native Stack Trace (which is what I've been looking at so far) there's also a managed stack trace (the C# one):

=================================================================
    Managed Stacktrace:
=================================================================
      at <unknown> <0xffffffff>
      at ApiDefinitions.Messaging:void_objc_msgSend_NativeHandle <0x00090>
      at Sentry.CocoaSdk.SentrySDK:StartWithOptions <0x00060>
      at Sentry.SentrySdk:InitSentryCocoaSdk <0x00fe6>
      at Sentry.SentrySdk:InitHub <0x00180>
      at Sentry.SentrySdk:Init <0x00012>
      at Sentry.Maui.Internal.SentryMauiInitializer:Initialize <0x0005c>
      at Microsoft.Maui.Hosting.MauiAppBuilder:Build <0x0014c>
      at Sentry.reproduce.MauiProgram:CreateMauiApp <0x00112>
      at Sentry.reproduce.AppDelegate:CreateMauiApp <0x0000c>
      at Microsoft.Maui.MauiUIApplicationDelegate:WillFinishLaunching <0x0005c>
      at <Module>:runtime_invoke_direct_bool__this___UIApplication_NSDictionary <0x00186>
      at <unknown> <0x00000>
      at <unknown> <0xffffffff>
      at UIKit.UIApplication:xamarin_UIApplicationMain <0x000a6>
      at UIKit.UIApplication:UIApplicationMain <0x00048>
      at UIKit.UIApplication:Main <0x0011c>
      at Sentry.reproduce.Program:Main <0x0001e>
      at <Module>:runtime_invoke_direct_void_string[] <0x00108>
      at <unknown> <0x00000>
=================================================================

Also @Curs3W4ll originally reported this exception (which I'm not seeing but would explain these stack traces):

System.Exception: Could not create an native instance of the type 'Sentry.CocoaSdk.SentryOptions': the native class hasn't been loaded.

Possibly this is an issue with the ObjectiveSharpie wrappers around the sentry-cocoa SDK then (which is the ApiDefinitions).

jamescrosswell commented 7 months ago

Sorry for the monologue, but I've come full circle:

  1. Running through the C# code it definitely fails in some generated code (no source reference) that makes the call to startWithOptions in the Cocoa SDK
  2. However from the logging code I added (and the stack traces) it's apparent that this method does actually get called (no issue with the ObjectiveSharpie wrapper for this)

I figured, without being able to step into that code, I'd go crazy logging that as well and I can see that it calls installIntegrations and then an error is generated by the SentryCrashReportSink:

2024-04-11 23:29:43.474 Sentry.reproduce[10302:1379633] [Sentry] [warning] [SentryCrashReportSink:52] Startup crash: detected.

And then half way through the convertReportToEvent method, immediately after the call to sentry_fromIso8601String it bails out.

Full logs attached: maui-3235.log

@philipphofmann does any of this make sense to you?

philipphofmann commented 7 months ago

@jamescrosswell, thanks for investigating this 😃 . This looks crazily complicated. Could you maybe upload a sample project here for me to reproduce? I think it would be the easiest for me to investigate.

jamescrosswell commented 7 months ago

Hi @philipphofmann , sure @Curs3W4ll already provided one here actually.

To run that in a debugger and be able to add logging code etc., I've:

You should then be able to run that Sentry.reproduce MAUI application, using our source code rather than the compiled NuGet package. I'm doing this in JetBrains Rider personally and targetting macCatalyst (so running it all on macOS).

At this stage you should be able to reproduce the issue in your debugger - it happens as soon as the application launches.

Once you can build/run from our source code, it's then possible to fiddle with the sentry-cocoa souce code. We've included that in the .NET project as a git submodule, so you'll find that in the /modules/sentry-cocoa subdirectory of the solution once you've run git submodule update --recursive).

The Cocoa module itself is built automatically as part of the .NET Build process: https://github.com/getsentry/sentry-dotnet/blob/ea5dddc912e56ee4816a2d65571bee681b99a77d/src/Sentry.Bindings.Cocoa/Sentry.Bindings.Cocoa.csproj#L47-L54

One gotcha is that we only recompile the sentry-cocoa SDK if the commit hash for that submodule has changed. The hash itself is written/cached in modules/sentry-cocoa/Carthage/.built-from-sha so if you make changes to the sentry-cocoa code and you want to rebuild sentry-dotnet to include those changes, you either have to commit those changes to the sentry-cocoa submodule (so you get a new commit hash) or delete that modules/sentry-cocoa/Carthage/.built-from-sha file to force a rebuild (kind of like "cleaning the build cache")... which is what I do.

philipphofmann commented 7 months ago

Thanks. I'm on PTO next week, so I will only look at this around April 22nd.

philipphofmann commented 6 months ago

This is caused by a bug in the .NET runtime; see https://github.com/dotnet/runtime/issues/98941. I tried to use a different date formatter NSISO8601DateFormatter in the Cocoa SDK, but it leads to the same crash. Using Xcode 15.2 and running on an iOS 17.2 simulator or debugging on an actual iOS device works fine. There isn't much we can do except to update the troubleshooting guide and wait for .NET to fix this.

jamescrosswell commented 6 months ago

Fantastic, thanks @philipphofmann !

That's hopefully enough options to unblock SDK customers experiencing this problem while we're waiting for a fix in the dotnet runtime:

I tried that workaround and can confirm it works with Sentry.

Kylar182 commented 6 months ago

Fantastic, thanks @philipphofmann !

That's hopefully enough options to unblock SDK customers experiencing this problem while we're waiting for a fix in the dotnet runtime:

  • Debug on an iOS simulator <= version 17.2 or
  • Debug on a physical device or
  • Disable globalization and make the app link to mono statically (the workaround that Rolf suggested)

I tried that workaround and can confirm it works with Sentry. `

<_LibXamarinLinkMode>static <_LibMonoLinkMode>static

<_MonoRuntimeComponentLinking Remove="dynamic" /> <_MonoRuntimeComponentLinking Include="static" RuntimeIdentifier="ios-arm64" /> <_MonoRuntimeComponentLinking Include="static" RuntimeIdentifier="iossimulator-arm64" /> <_MonoRuntimeComponentLinking Include="static" RuntimeIdentifier="iossimulator-x64" />
<_ReferencesLinkerFlagsBackup Include="@(_ReferencesLinkerFlags)" /> <_ReferencesLinkerFlags Remove="@(_ReferencesLinkerFlags)" /> <_ReferencesLinkerFlags Include="-exported_symbols_list" /> <_ReferencesLinkerFlags Include="$(_MtouchSymbolsList)" /> <_ReferencesLinkerFlags Remove="@(_ReferencesLinkerFlags)" /> <_ReferencesLinkerFlags Include="@(_ReferencesLinkerFlagsBackup)" /> ` So, to confirm, we should put this in our MAUI Project ?
jamescrosswell commented 6 months ago

So, to confirm, we should put this in our MAUI Project ?

@Kylar182 I think the code got mangled when you copied/pasted it but assuming you meant the code sample I linked to in this comment then yes, that would permit you to test on iOS17.4 simulators until this bug gets fixed in the dotnet runtime. This workaround isn't necessary if you're testing on iOS17.2 or on physical devices.

bitsandfoxes commented 6 months ago

Can we put the workaround into the SDK? Sounds hacky if we even should.

bitsandfoxes commented 6 months ago

But hey! Looks like upgrading to .NET 8.0.5 has the fix in there! https://github.com/dotnet/runtime/issues/98941#issuecomment-2111701512

Kylar182 commented 6 months ago

Yeah it's fixed in .NET 8.0.5 but my projects are still on .NET 6 for the time being. Also, the issue posts as being on the iOS simulators but its everything on MacOS including the .NET MAUI MacOS Release Apps so please be aware of that.

bitsandfoxes commented 5 months ago

Closing this as bumping to the most current version of .NET resolves the crashing.

natevarghese commented 4 months ago

Where did you find .NET 8.0.5? I am seeing .NET 8.0.302 as latest. It still crashes in 8.0.302 with the original error

bitsandfoxes commented 4 months ago

Where did you find .NET 8.0.5? I am seeing .NET 8.0.302 as latest. It still crashes in 8.0.302 with the original error

Based on https://github.com/dotnet/runtime/issues/98941#issuecomment-2135136122 this should contain the fix.