Skip to content

[Sentry.Maui][Android & iOS]: Native Crashes Bypass EventProcesor & BeforeSend Hook #3549

Closed

Description

@phunkeler

Package

Sentry.Maui

.NET Flavor

.NET

.NET Version

8.0.8

OS

Android

SDK Version

4.10.2

Self-Hosted Sentry Version

No response

Steps to Reproduce

  1. Clone the public reproduction repository phunkeler/sentry.maui-bug-eventprocessor
  2. Edit MauiProgram.cs, to include your DSN
  3. Deploy to Android or iOS device
  4. Launch app
  5. Trigger a Native crash
public static class MauiProgram
{
    public static MauiApp CreateMauiApp() =>
        MauiApp.CreateBuilder()
            .UseMauiApp<App>()
            .UseMauiCommunityToolkit()
            .UseSentry(options =>
            {
                options.Dsn = "[YOUR_SENTRY_DSN_HERE]";
                options.Debug = true;
                options.TracesSampleRate = 1.0;
                options.AttachScreenshot = true;

                // Native crashes seem to bypass the following mechanisms
                options.AddEventProcessors([new MySentryEventProcessorWithHint(), new MySentryEventProcessor()]);
                options.SetBeforeSend(EnrichEvent);
                options.ConfigureScope(scope => scope.AddEventProcessors([new MySentryEventProcessorWithHint(), new MySentryEventProcessor()]));
            })
            .Build();

    class MySentryEventProcessorWithHint : ISentryEventProcessorWithHint
    {
        public SentryEvent? Process(SentryEvent @event, SentryHint hint) => Process(@event);
        public SentryEvent? Process(SentryEvent @event) => EnrichEvent(@event);
    }

    class MySentryEventProcessor : ISentryEventProcessor
    {
        public SentryEvent? Process(SentryEvent @event) => EnrichEvent(@event);
    }

    public static SentryEvent EnrichEvent(SentryEvent sentryEvent)
    {
        sentryEvent.Release = "0.0.1";
        sentryEvent.Environment = "DEV";

        for (var i = 1; i <= 5; i++)
        {
            sentryEvent.SetTag($"Tag_{i}", i.ToString());
            sentryEvent.Contexts[$"Context_{i}"] = Enumerable.Range(1, 5).ToDictionary(i => $"Key_{i}", i => i.ToString());
        }

        return sentryEvent;
    }
}

Image

Expected Result

If the problem does not exist, a new issue in sentry.io will be created for the native crash that includes all of the contextual info. we added via an EventProcessor or in the BeforeSend callback.

Expected Tags

Image

Expected Contexts

Image

Results from triggering a Managed or ManagedBackgroundThread crash type are as expected.

Perhaps this is by design and I just misunderstood the EventProcessor documentation where it says:

"Processors run on every event sent once they've been added. While there are multiple ways of doing this, adding processors to the options ensures that they run with every event after initialization."

Actual Result

If the problem exists, a new issue in sentry.io will be created for the native crash but lack the contextual info. we attempted to add via an EventProcessor or the BeforeSend callback.

Actual Tags
{
    "tags": [
	[
		"device",
		"SM-G991U1"
	],
	[
		"device.class",
		"3"
	],
	[
		"device.family",
		"SM-G991U1"
	],
	[
		"environment",
		"production"
	],
	[
		"handled",
		"no"
	],
	[
		"isSideLoaded",
		"true"
	],
	[
		"level",
		"fatal"
	],
	[
		"mechanism",
		"signalhandler"
	],
	[
		"os",
		"Android 14"
	],
	[
		"os.name",
		"Android"
	],
	[
		"os.rooted",
		"no"
	],
	[
		"dist",
		"1"
	],
	[
		"release",
		"[email protected]+1"
	],
	[
		"user",
		"id:22b33c55-7aaf-4bc9-99bf-b5f1c271b948"
	]
    ]
}
Actual Contexts
{
    "contexts": {
	"device": {
		"name": "Galaxy S21 5G",
		"family": "SM-G991U1",
		"model": "SM-G991U1",
		"model_id": "UP1A.231005.007",
		"battery_level": 79.0,
		"orientation": "portrait",
		"manufacturer": "samsung",
		"brand": "samsung",
		"screen_width_pixels": 1080,
		"screen_height_pixels": 2176,
		"screen_density": 3.0,
		"screen_dpi": 480,
		"online": true,
		"charging": true,
		"simulator": false,
		"memory_size": 7720587264,
		"storage_size": 112626462720,
		"free_storage": 101994582016,
		"boot_time": "2024-08-05T23:46:10.904Z",
		"timezone": "America/New_York",
		"locale": "en_US",
		"processor_count": 8,
		"processor_frequency": 2841,
		"archs": [
			"arm64-v8a",
			"armeabi-v7a",
			"armeabi"
		],
		"battery_temperature": 27.8,
		"connection_type": "wifi",
		"id": "22b33c55-7aaf-4bc9-99bf-b5f1c271b948",
		"language": "en",
		"type": "device"
	},
	"os": {
		"name": "Android",
		"version": "14",
		"build": "UP1A.231005.007.G991U1UESCGXF3",
		"kernel_version": "5.4.254-qgki-28582291-abG991U1UESCGXF3",
		"rooted": false,
		"type": "os"
	},
	"os_linux": {
		"build": "qgki-28582291-abG991U1UESCGXF3",
		"name": "Linux",
		"type": "os_linux",
		"version": "5.4.254"
	}
    }
}

Activity

  1. moved this to Waiting for: Product Owner in GitHub Issues with 👀 3on Aug 21, 2024
  2. jamescrosswell commented on Aug 22, 2024

    @jamescrosswell
    Collaborator

    Hi @phunkeler,

    Thank you for the very detailed report and example code to reproduce this.

    @bruno-garcia @vaind do you know if this is by design?

    It looks like the Native crash results in a Seg Fault and the error only gets reported to Sentry the next time the application runs (not before it exits). I assume that's because we can't rely on network communication at that point so a dump is written when the crash occurs and only read/sent when the app restarts.

    If that's the case, is there something preventing us from providing callbacks to the .NET BeforeSend handler or EventProcessors from the native libraries (similar to what we do with Java crashes)? It seems like once the application has restarted, all of that machinery could/would be back in place again.

  3. moved this from Waiting for: Product Owner to No status in GitHub Issues with 👀 3on Aug 22, 2024
  4. vaind commented on Aug 23, 2024

    @vaind
    Contributor

    Before-send is normally called in the same app run that the event occurs. .NET Sentry SDK is a hybrid SDK that combines c# handlers as well as other native SDKs for respective platforms, e.g. sentry-cocoa, sentry-native, sentry-java, etc. For native events, the native SDK handles events and sends them when the event occurs. Some hybrid SDKs go out of their way to try and set up these callbacks for native events, e.g. any before-send callback would either need to be set up on the native SDK or it would require changing who sends events - let native SDK create the event on disk and then let c# SDK pick it up and send.

    Either way, it takes quite a bit of work, so as anything else, it's a question of priorities, which are influenced by many factors. One of those factors is demand, so having this issue here is a good thing so at the very least, we can gauge and track user interest.

  5. jamescrosswell commented on Aug 25, 2024

    @jamescrosswell
    Collaborator

    Ah, @phunkeler I just stumbled across this:

    /// <summary>
    /// Gets or sets a value that indicates if the <c>BeforeSend</c> callback set in <see cref="o:SetBeforeSend"/>
    /// will be invoked for events that originate from the embedded Android SDK. The default value is <c>false</c> (disabled).
    /// </summary>
    /// <remarks>
    /// This is an experimental feature and is imperfect, as the .NET SDK and the embedded Android SDK don't
    /// implement all of the same features that may be present in the event graph. Some optional elements may
    /// be stripped away during the round-tripping between the two SDKs. Use with caution.
    /// </remarks>
    public bool EnableBeforeSend { get; set; } = false;

    You could try enabling that hook then. As the comment indicates, it's experimental, but it may enable you to do what you want.

    If you're also deploying to iOS however, this hasn't yet been implemented:

    // TODO: Finish SentryEventExtensions to enable these
    // if (options.Native.EnableBeforeSend && options.BeforeSend is { } beforeSend)
    // {
    // nativeOptions.BeforeSend = evt =>
    // {
    // var sentryEvent = evt.ToSentryEvent(nativeOptions);
    // var result = beforeSend(sentryEvent)?.ToCocoaSentryEvent(options, nativeOptions);
    //
    // // Note: Nullable result is allowed but delegate is generated incorrectly
    // // See https://github.com/xamarin/xamarin-macios/issues/15299#issuecomment-1201863294
    // return result!;
    // };
    // }

  6. added
    Bug
    on Aug 26, 2024
  7. phunkeler commented on Aug 27, 2024

    @phunkeler
    ContributorAuthor

    Thanks for the info, guys! It's definitely helped fill some gaps in my understanding of Sentry as I migrate from AppCenter.

    I was hoping to use custom event processors (or secondarily, the BeforeSend hook) as an alternative to making a bunch of SentrySdk.ConfigureScope calls. However ConfigureScope appears to be the more reliable approach in the case of native crashes, which are quite common in our MAUI app (Android & iOS).

    @jamescrosswell - I tried enabling the EnableBeforeSend Android option but was met by the following exception that seemed to prevent other events from reaching Sentry.

    C# Code
    #if ANDROID
    options.Native.EnableBeforeSend = true;
    #endif
    
    options.SetBeforeSend((sentryEvent, sentryHint) =>
    {
        if (sentryAttachmentProvider.GetLogAttachment() is LogAttachment logAttachment)
        {
            sentryHint.Attachments.Add(logAttachment);
        }
        return sentryEvent;
    });
    Sentry Exception
    System.FormatException: One of the identified items was in an invalid format.
      File "ThrowHelper.cs", line 594, in void ThrowHelper.ThrowFormatException()
        throw new FormatException { Source = ExceptionSourceValueToRethrowAsJsonException };
      File "JsonElement.cs", line 660, in int JsonElement.GetInt32()
        ThrowHelper.ThrowFormatException();
      File "Device.cs", line 459, in Device Device.FromJson(JsonElement json)
        var processorFrequency = json.GetPropertyOrNull("processor_frequency")?.GetInt32();
      File "SentryContexts.cs", line 148, in SentryContexts SentryContexts.FromJson(JsonElement json)
        result[name] = Device.FromJson(value);
      File "MiscExtensions.cs", line 5, in SentryContexts MiscExtensions.Pipe<JsonElement, SentryContexts>(JsonElement input, Func<JsonElement, SentryContexts> pipe)
        public static TOut Pipe<TIn, TOut>(this TIn input, Func<TIn, TOut> pipe) => pipe(input);
      File "SentryEvent.cs", line 305, in SentryEvent SentryEvent.FromJson(JsonElement json, Exception exception)
        var contexts = json.GetPropertyOrNull("contexts")?.Pipe(SentryContexts.FromJson);
      File "SentryEventExtensions.cs", line 29, in SentryEvent SentryEventExtensions.ToSentryEvent(SentryEvent sentryEvent, SentryOptions javaOptions)
        return SentryEvent.FromJson(json.RootElement, sentryEvent.Throwable);
      File "BeforeSendCallback.cs", line 26, in SentryEvent BeforeSendCallback.Execute(SentryEvent e, Hint h)
        var evnt = e.ToSentryEvent(_javaOptions);
      ?, in IntPtr IBeforeSendCallbackInvoker.n_Execute_Lio_sentry_SentryEvent_Lio_sentry_Hint_(IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
      File "/Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs", line 231, col 5, in IntPtr JNINativeWrapper.Wrap_JniMarshal_PPLL_L(_JniMarshal_PPLL_L callback, IntPtr jnienv, IntPtr klazz, IntPtr p0, IntPtr p1)
    
  8. moved this to Waiting for: Product Owner in GitHub Issues with 👀 3on Aug 27, 2024
  9. jamescrosswell commented on Aug 27, 2024

    @jamescrosswell
    Collaborator

    @jamescrosswell - I tried enabling the EnableBeforeSend Android option but was met by the following exception

    Thanks @phunkeler, I've created #3572 to track that issue and I'll close this issue since it seems we got to the bottom of it (this functionality is experimental in Android and hasn't yet been implemented for iOS).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugFramework: MAUI

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions