Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map iOS Native BeforeSend & OnCrashedLastEvent to SentryOptions.Native #3958

Open
wants to merge 37 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
a1b0cb6
Initial commit for exposing iOS native before send & crashed last run
aritchie Feb 11, 2025
1a8474e
Initial feature set is working
aritchie Feb 11, 2025
c36be94
Format code
getsentry-bot Feb 11, 2025
cd074d4
Update CHANGELOG.md
aritchie Feb 11, 2025
17790c7
Merge branch '2102-ios_beforesend_oncrashedlastrun' of https://github…
aritchie Feb 11, 2025
70a677d
Merge signal abort code before user based BeforeSend
aritchie Feb 12, 2025
4a6462c
Move native BeforeSend & OnCrashedLastRun events to SentryOptions - O…
aritchie Feb 14, 2025
91145ab
Always run NativeOptions.BeforeSend so sig aborts can be filtered
aritchie Feb 14, 2025
fd48026
Update SentrySdk.cs
aritchie Feb 14, 2025
1b3dfdd
Merge branch 'main' into 2102-ios_beforesend_oncrashedlastrun
aritchie Feb 18, 2025
c29a785
Update CHANGELOG.md
aritchie Feb 18, 2025
50a5554
Format code
getsentry-bot Feb 18, 2025
63e3f55
WIP - removing serialization mechanics as they cause a native crash d…
aritchie Feb 18, 2025
5c06eb5
Transferring transformed sentryevent back to original native event in…
aritchie Feb 21, 2025
18a1079
Merge branch 'main' into 2102-ios_beforesend_oncrashedlastrun
aritchie Feb 21, 2025
000b324
Remove unnecessary hacks
aritchie Feb 21, 2025
bdfe3a9
Format code
getsentry-bot Feb 21, 2025
bf4d33d
Add missing bindable option for native iOS sentryoptions
aritchie Feb 21, 2025
52f0699
Update SentrySdk.cs
aritchie Feb 24, 2025
dab118e
Update SentrySdk.cs
aritchie Feb 24, 2025
1f721b8
Update CHANGELOG.md
aritchie Feb 24, 2025
4830f8e
Update CHANGELOG.md
aritchie Feb 24, 2025
b8b08cc
Unit tests mapping checks to/from native iOS
aritchie Feb 24, 2025
a46bd43
Format code
getsentry-bot Feb 24, 2025
5dca9e2
Update NativeSerializationTests.cs
aritchie Feb 24, 2025
00cbc04
Revert "Add missing bindable option for native iOS sentryoptions"
aritchie Feb 24, 2025
d2776e1
Remove iOS native event suppress configuration
aritchie Feb 24, 2025
5e8134a
Update CHANGELOG.md
aritchie Feb 24, 2025
d8ac6ea
Rename tests according to review
aritchie Feb 25, 2025
63326ec
add timestamp for deserialize test
aritchie Feb 25, 2025
d1feffc
Account for fractions of seconds
aritchie Feb 26, 2025
6c10867
Merge branch 'main' into 2102-ios_beforesend_oncrashedlastrun
aritchie Feb 26, 2025
ede88c1
Platforms should not change
aritchie Feb 26, 2025
bbf9da4
Update CocoaExtensionsTests.cs
aritchie Feb 26, 2025
65534f0
Update CocoaExtensionsTests.cs
aritchie Feb 26, 2025
35113e1
Update CocoaExtensionsTests.cs
aritchie Feb 26, 2025
4c6d7a2
Update CocoaExtensionsTests.cs
aritchie Feb 26, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Fixes

- Map iOS native events - OnCrashedLastRun and BeforeSend ([#2102](https://github.com/getsentry/sentry-dotnet/pull/3958))

## 5.1.1

### Fixes
Expand All @@ -8,6 +14,8 @@
- Native SIGSEGV errors resulting from managed NullReferenceExceptions are now suppressed on Android ([#3903](https://github.com/getsentry/sentry-dotnet/pull/3903))
- OTel activities that are marked as not recorded are no longer sent to Sentry ([#3890](https://github.com/getsentry/sentry-dotnet/pull/3890))
- Fixed envelopes with oversized attachments getting stuck in __processing ([#3938](https://github.com/getsentry/sentry-dotnet/pull/3938))
- Unknown stack frames in profiles on .NET 8+ ([#3942](https://github.com/getsentry/sentry-dotnet/pull/3942))
- Deduplicate profiling stack frames ([#3941](https://github.com/getsentry/sentry-dotnet/pull/3941))
- OperatingSystem will now return macOS as OS name instead of 'Darwin' as well as the proper version. ([#2710](https://github.com/getsentry/sentry-dotnet/pull/3956))
- Ignore null value on CocoaScopeObserver.SetTag ([#3948](https://github.com/getsentry/sentry-dotnet/pull/3948))
- Deduplicate profiling stack frames ([#3969](https://github.com/getsentry/sentry-dotnet/pull/3969))
Expand Down
11 changes: 11 additions & 0 deletions samples/Sentry.Samples.Ios/AppDelegate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l
options.Native.EnableAppHangTracking = true;

options.CacheDirectoryPath = Path.GetTempPath();

options.SetBeforeSend((evt, _) =>
{
evt.SetTag("dotnet-iOS-Native-Before", "Hello World");
return evt;
});

options.OnCrashedLastRun = e =>
{
Console.WriteLine(e);
};
});

// create a new window instance based on the screen size
Expand Down
2 changes: 1 addition & 1 deletion samples/Sentry.Samples.Ios/Sentry.Samples.Ios.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0-ios18.0</TargetFramework>
<TargetFramework>net9.0-ios</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>true</ImplicitUsings>
Expand Down
24 changes: 24 additions & 0 deletions src/Sentry/Internal/Extensions/JsonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,30 @@ public static void Deconstruct(this JsonProperty jsonProperty, out string name,
return double.Parse(json.ToString()!, CultureInfo.InvariantCulture);
}

/// <summary>
/// Safety value to deal with native serialization - allows datetimeoffset to come in as a long or string value
/// </summary>
/// <param name="json"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public static DateTimeOffset? GetSafeDateTimeOffset(this JsonElement json, string propertyName)
{
DateTimeOffset? result = null;
var dtRaw = json.GetPropertyOrNull(propertyName);
if (dtRaw != null)
{
if (dtRaw.Value.ValueKind == JsonValueKind.Number)
{
result = DateTimeOffset.FromUnixTimeSeconds(dtRaw.Value.GetInt64());
}
else
{
result = dtRaw.Value.GetDateTimeOffset();
}
}
return result;
}

public static long? GetHexAsLong(this JsonElement json)
{
// If the address is in json as a number, we can just use it.
Expand Down
119 changes: 77 additions & 42 deletions src/Sentry/Platforms/Cocoa/Extensions/SentryEventExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,80 @@
// using Sentry.Extensibility;
// using Sentry.Protocol.Envelopes;
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
using Sentry.Protocol.Envelopes;

namespace Sentry.Cocoa.Extensions;

internal static class SentryEventExtensions
{
/*
* These methods map between a SentryEvent and it's Cocoa counterpart by serializing as JSON into memory on one side,
* then deserializing back to an object on the other side. It is not expected to be performant, as this code is only
* used when a BeforeSend option is set, and then only when an event is captured by the Cocoa SDK (which should be
* relatively rare).
*
* This approach avoids having to write to/from methods for the entire object graph. However, it's also important to
* recognize that there's not necessarily a one-to-one mapping available on all objects (even through serialization)
* between the two SDKs, so some optional details may be lost when roundtripping. That's generally OK, as this is
* still better than nothing. If a specific part of the object graph becomes important to roundtrip, we can consider
* updating the objects on either side.
*/

public static SentryEvent? ToSentryEvent(this CocoaSdk.SentryEvent sentryEvent)
{
using var stream = sentryEvent.ToJsonStream();
if (stream == null)
return null;

using var json = JsonDocument.Parse(stream);
var exception = sentryEvent.Error == null ? null : new NSErrorException(sentryEvent.Error);
var ev = SentryEvent.FromJson(json.RootElement, exception);
return ev;
}

public static CocoaSdk.SentryEvent ToCocoaSentryEvent(this SentryEvent sentryEvent, SentryOptions options)
{
var native = new CocoaSdk.SentryEvent();

native.ServerName = sentryEvent.ServerName;
native.Dist = sentryEvent.Distribution;
native.Logger = sentryEvent.Logger;
native.ReleaseName = sentryEvent.Release;
native.Environment = sentryEvent.Environment;
native.Platform = sentryEvent.Platform!;
native.Transaction = sentryEvent.TransactionName!;
native.Fingerprint = sentryEvent.Fingerprint?.ToArray();
native.Timestamp = sentryEvent.Timestamp.ToNSDate();
native.Modules = sentryEvent.Modules.ToDictionary(kv => kv.Key, kv => kv.Value);

native.Tags = sentryEvent.Tags?.ToDictionary(kv => kv.Key, kv => kv.Value);
native.EventId = sentryEvent.EventId.ToCocoaSentryId();
native.Extra = sentryEvent.Extra?.ToDictionary(kv => kv.Key, kv => kv.Value);
native.Breadcrumbs = sentryEvent.Breadcrumbs?.Select(x => x.ToCocoaBreadcrumb()).ToArray();
native.User = sentryEvent.User?.ToCocoaUser();
// native.Error = NSError.FromDomain() sentryEvent.Exception
//sentryEvent.Request;
// native.Level = sentryEvent.Level;
// native.Sdk = sentryEvent.Sdk
// native.Context = sentryEvent.Contexts;
// sentryEvent.DebugImages
// sentryEvent.SentryExceptions
// native.Type = sentryEvent.T
// native.Message = sentryEvent.Message
// native.Threads = sentryEvent.SentryThreads

return native;
}
}
// var envelope = Envelope.FromEvent(sentryEvent);
// var native = new CocoaSdk.SentryEvent();
//
// namespace Sentry.Cocoa.Extensions;
// using var stream = new MemoryStream();
// envelope.Serialize(stream, options.DiagnosticLogger);
// stream.Seek(0, SeekOrigin.Begin);
//
// internal static class SentryEventExtensions
// {
// /*
// * These methods map between a SentryEvent and it's Cocoa counterpart by serializing as JSON into memory on one side,
// * then deserializing back to an object on the other side. It is not expected to be performant, as this code is only
// * used when a BeforeSend option is set, and then only when an event is captured by the Cocoa SDK (which should be
// * relatively rare).
// *
// * This approach avoids having to write to/from methods for the entire object graph. However, it's also important to
// * recognize that there's not necessarily a one-to-one mapping available on all objects (even through serialization)
// * between the two SDKs, so some optional details may be lost when roundtripping. That's generally OK, as this is
// * still better than nothing. If a specific part of the object graph becomes important to roundtrip, we can consider
// * updating the objects on either side.
// */
// using var data = NSData.FromStream(stream)!;
// var cocoaEnvelope = CocoaSdk.PrivateSentrySDKOnly.EnvelopeWithData(data);
//
// public static SentryEvent ToSentryEvent(this CocoaSdk.SentryEvent sentryEvent, SentryCocoaSdkOptions nativeOptions)
// {
// using var stream = sentryEvent.ToJsonStream()!;
// //stream.Seek(0, SeekOrigin.Begin); ??
//
// using var json = JsonDocument.Parse(stream);
// var exception = sentryEvent.Error == null ? null : new NSErrorException(sentryEvent.Error);
// return SentryEvent.FromJson(json.RootElement, exception);
// }
//
// public static CocoaSdk.SentryEvent ToCocoaSentryEvent(this SentryEvent sentryEvent, SentryOptions options, SentryCocoaSdkOptions nativeOptions)
// {
// var envelope = Envelope.FromEvent(sentryEvent);
//
// using var stream = new MemoryStream();
// envelope.Serialize(stream, options.DiagnosticLogger);
// stream.Seek(0, SeekOrigin.Begin);
//
// using var data = NSData.FromStream(stream)!;
// var cocoaEnvelope = CocoaSdk.PrivateSentrySDKOnly.EnvelopeWithData(data);
//
// var cocoaEvent = (CocoaSdk.SentryEvent) cocoaEnvelope.Items[0];
// return cocoaEvent;
// }
// }
// var cocoaEvent = (CocoaSdk.SentryEvent)cocoaEnvelope.Items.GetItem<CocoaSdk.SentryEvent>(0);
// // this will return a SentryEnvelopeItem which has isCrashEvent that causes native serialization panic
// return cocoaEvent;
141 changes: 81 additions & 60 deletions src/Sentry/Platforms/Cocoa/SentrySdk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ private static void InitSentryCocoaSdk(SentryOptions options)
nativeOptions.SendDefaultPii = options.SendDefaultPii;
nativeOptions.SessionTrackingIntervalMillis = (nuint)options.AutoSessionTrackingInterval.TotalMilliseconds;

// nativeOptions.BeforeSend
if (options.Environment is { } environment)
{
nativeOptions.Environment = environment;
Expand Down Expand Up @@ -86,29 +87,86 @@ private static void InitSentryCocoaSdk(SentryOptions options)
}
}

// 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!;
// };
// }

// if (options.Native.OnCrashedLastRun is { } onCrashedLastRun)
// {
// nativeOptions.OnCrashedLastRun = evt =>
// {
// var sentryEvent = evt.ToSentryEvent(nativeOptions);
// onCrashedLastRun(sentryEvent);
// };
// }
nativeOptions.BeforeSend = evt =>
{
// When we have an unhandled managed exception, we send that to Sentry twice - once managed and once native.
// The managed exception is what a .NET developer would expect, and it is sent by the Sentry.NET SDK
// But we also get a native SIGABRT since it crashed the application, which is sent by the Sentry Cocoa SDK.

// There should only be one exception on the event in this case
if (evt.Exceptions?.Length == 1)
{
// It will match the following characteristics
var ex = evt.Exceptions[0];

// Thankfully, sometimes we can see Xamarin's unhandled exception handler on the stack trace, so we can filter
// them out. Here is the function that calls abort(), which we will use as a filter:
// https://github.com/xamarin/xamarin-macios/blob/c55fbdfef95028ba03d0f7a35aebca03bd76f852/runtime/runtime.m#L1114-L1122
if (ex.Type == "SIGABRT" && ex.Value == "Signal 6, Code 0" &&
ex.Stacktrace?.Frames.Any(f => f.Function == "xamarin_unhandled_exception_handler") is true)
{
// Don't send it
options.LogDebug("Discarded {0} error ({1}). Captured as managed exception instead.", ex.Type,
ex.Value);
return null!;
}

// Similar workaround for NullReferenceExceptions. We don't have any easy way to know whether the
// exception is managed code (compiled to native) or original native code though.
// See: https://github.com/getsentry/sentry-dotnet/issues/3776
if (ex.Type == "EXC_BAD_ACCESS")
{
// Don't send it
options.LogDebug("Discarded {0} error ({1}). Captured as managed exception instead.", ex.Type,
ex.Value);
return null!;
}
}

// we run our SIGABRT checks first before handing over to user events
// because we delegate to user code, we need to protect anything that could happen in this event
try
{
var sentryEvent = evt.ToSentryEvent();
if (sentryEvent != null)
{
var result = options
.BeforeSendInternal?
.Invoke(sentryEvent, null!)?
.ToCocoaSentryEvent(options);

// // Note: Nullable result is allowed but delegate is generated incorrectly
// // See https://github.com/xamarin/xamarin-macios/issues/15299#issuecomment-1201863294
return result!;
}
return evt;
}
catch (Exception ex)
{
options.LogError(ex, "Before Send Error");
return evt;
}
};

if (options.OnCrashedLastRun is { } onCrashedLastRun)
{
nativeOptions.OnCrashedLastRun = evt =>
{
// because we delegate to user code, we need to protect anything that could happen in this event
try
{
var sentryEvent = evt.ToSentryEvent();
if (sentryEvent != null)
{
onCrashedLastRun(sentryEvent);
}
}
catch (Exception ex)
{
options.LogError(ex, "Crashed Last Run Error");
}
};
}

// These options are from Cocoa's SentryOptions
nativeOptions.AttachScreenshot = options.Native.AttachScreenshot;
Expand Down Expand Up @@ -145,43 +203,6 @@ private static void InitSentryCocoaSdk(SentryOptions options)
// nativeOptions.DefaultIntegrations
// nativeOptions.EnableProfiling (deprecated)

// When we have an unhandled managed exception, we send that to Sentry twice - once managed and once native.
// The managed exception is what a .NET developer would expect, and it is sent by the Sentry.NET SDK
// But we also get a native SIGABRT since it crashed the application, which is sent by the Sentry Cocoa SDK.
nativeOptions.BeforeSend = evt =>
{
// There should only be one exception on the event in this case
if (evt.Exceptions?.Length == 1)
{
// It will match the following characteristics
var ex = evt.Exceptions[0];

// Thankfully, sometimes we can see Xamarin's unhandled exception handler on the stack trace, so we can filter
// them out. Here is the function that calls abort(), which we will use as a filter:
// https://github.com/xamarin/xamarin-macios/blob/c55fbdfef95028ba03d0f7a35aebca03bd76f852/runtime/runtime.m#L1114-L1122
if (ex.Type == "SIGABRT" && ex.Value == "Signal 6, Code 0" &&
ex.Stacktrace?.Frames.Any(f => f.Function == "xamarin_unhandled_exception_handler") is true)
{
// Don't send it
options.LogDebug("Discarded {0} error ({1}). Captured as managed exception instead.", ex.Type, ex.Value);
return null!;
}

// Similar workaround for NullReferenceExceptions. We don't have any easy way to know whether the
// exception is managed code (compiled to native) or original native code though.
// See: https://github.com/getsentry/sentry-dotnet/issues/3776
if (ex.Type == "EXC_BAD_ACCESS")
{
// Don't send it
options.LogDebug("Discarded {0} error ({1}). Captured as managed exception instead.", ex.Type, ex.Value);
return null!;
}
}

// Other event, send as normal
return evt;
};

// Set hybrid SDK name
SentryCocoaHybridSdk.SetSdkName("sentry.cocoa.dotnet");

Expand Down
2 changes: 1 addition & 1 deletion src/Sentry/SentryEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ internal static SentryEvent FromJson(JsonElement json, Exception? exception)
{
var modules = json.GetPropertyOrNull("modules")?.GetStringDictionaryOrNull();
var eventId = json.GetPropertyOrNull("event_id")?.Pipe(SentryId.FromJson) ?? SentryId.Empty;
var timestamp = json.GetPropertyOrNull("timestamp")?.GetDateTimeOffset();
var timestamp = json.GetSafeDateTimeOffset("timestamp"); // Native sentryevents are serialized to epoch timestamps
var message = json.GetPropertyOrNull("logentry")?.Pipe(SentryMessage.FromJson);
var logger = json.GetPropertyOrNull("logger")?.GetString();
var platform = json.GetPropertyOrNull("platform")?.GetString();
Expand Down
8 changes: 8 additions & 0 deletions src/Sentry/SentryOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,14 @@ public StackTraceMode StackTraceMode
/// </summary>
public Func<bool>? CrashedLastRun { get; set; }

#if IOS || MACCATALYST
// this event currently isn't being pushed from Android
/// <summary>
/// Delegate which is run with event information if the application crashed during last run.
/// </summary>
public Action<SentryEvent>? OnCrashedLastRun { get; set; }
#endif

/// <summary>
/// <para>
/// Gets the <see cref="Instrumenter"/> used to create spans.
Expand Down