Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
46 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
4be3abb
Ability to suppress native errors
aritchie Feb 24, 2025
fc85bce
Update CHANGELOG.md
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
b7f28d9
Merge branch '2102-ios_beforesend_oncrashedlastrun' into 3944-ios_nat…
aritchie Feb 26, 2025
9270d50
Add unit tests for suppress segfaults and beforesend
aritchie Feb 26, 2025
941e671
Merge branch 'main' into 3944-ios_native_error_suppression
aritchie Feb 26, 2025
92d38b6
Format code
getsentry-bot Feb 26, 2025
30b3bd3
Update SentrySdkTests.cs
aritchie Feb 26, 2025
8903a56
Merge branch 'main' into 3944-ios_native_error_suppression
aritchie Mar 3, 2025
de9afa5
Update CHANGELOG.md
aritchie Mar 3, 2025
599185f
Update SentrySdkTests.cs
aritchie Mar 4, 2025
3da967a
Updating additional changes requested from code review
aritchie Mar 4, 2025
0f159b7
Test fixes
aritchie Mar 4, 2025
dd37709
Update SentrySdkTests.cs
aritchie Mar 4, 2025
925a632
Merge branch 'main' into 3944-ios_native_error_suppression
aritchie Mar 4, 2025
a4ba982
Update CHANGELOG.md
aritchie Mar 4, 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
2 changes: 0 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
- 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
3 changes: 2 additions & 1 deletion src/Sentry/Internal/Extensions/JsonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ public static void Deconstruct(this JsonProperty jsonProperty, out string name,
{
if (dtRaw.Value.ValueKind == JsonValueKind.Number)
{
result = DateTimeOffset.FromUnixTimeSeconds(dtRaw.Value.GetInt64());
var epoch = Convert.ToInt64(dtRaw.Value.GetDouble());
result = DateTimeOffset.FromUnixTimeSeconds(epoch);
}
else
{
Expand Down
131 changes: 67 additions & 64 deletions src/Sentry/Platforms/Cocoa/SentrySdk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,70 +86,8 @@ private static void InitSentryCocoaSdk(SentryOptions options)
}
}

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 (options.Native.SuppressSegfaults && 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
if (options.BeforeSendInternal == null)
return evt;

try
{
var sentryEvent = evt.ToSentryEvent();
if (sentryEvent == null)
return evt;

var result = options.BeforeSendInternal(sentryEvent, null!);
if (result == null)
return null!;

// we only support a subset of mutated data to be passed back to the native SDK at this time
result.CopyToCocoaSentryEvent(evt);

// Note: Nullable result is allowed but delegate is generated incorrectly
// See https://github.com/xamarin/xamarin-macios/issues/15299#issuecomment-1201863294
return evt!;
}
catch (Exception ex)
{
options.LogError(ex, "Before Send Error");
return evt;
}
};
// HACK: generated native binding does not set nullable, but null is an acceptable return value here
nativeOptions.BeforeSend = evt => ProcessOnBeforeSend(options, evt)!;

if (options.OnCrashedLastRun is { } onCrashedLastRun)
{
Expand Down Expand Up @@ -250,4 +188,69 @@ private static CocoaSdk.SentryHttpStatusCodeRange[] GetFailedRequestStatusCodes(

return nativeRanges;
}

internal static CocoaSdk.SentryEvent? ProcessOnBeforeSend(SentryOptions options, CocoaSdk.SentryEvent 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 (options.Native.SuppressSegfaults && 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
if (options.BeforeSendInternal == null)
return evt;

try
{
var sentryEvent = evt.ToSentryEvent();
if (sentryEvent == null)
return evt;

var result = options.BeforeSendInternal(sentryEvent, null!);
if (result == null)
return null!;

// we only support a subset of mutated data to be passed back to the native SDK at this time
result.CopyToCocoaSentryEvent(evt);

// Note: Nullable result is allowed but delegate is generated incorrectly
// See https://github.com/xamarin/xamarin-macios/issues/15299#issuecomment-1201863294
return evt!;
}
catch (Exception ex)
{
options.LogError(ex, "Before Send Error");
return evt;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@

namespace Sentry.Tests.Platforms.iOS;

public class NativeSerializationTests
public class CocoaExtensionsTests
{
[Fact]
public void Managed_To_Native()
public void CopyToCocoaSentryEvent_CopiesProperties()
{
var evt = new SentryEvent(new Exception("Test Exception"));

Expand Down Expand Up @@ -42,10 +42,11 @@ public void Managed_To_Native()


[Fact]
public void Native_To_Managed()
public void ToSentryEvent_ConvertToManaged()
{
var native = new CocoaSdk.SentryEvent();

native.Timestamp = DateTimeOffset.UtcNow.ToNSDate();
native.ServerName = "native server name";
native.Dist = "native dist";
native.Logger = "native logger";
Expand Down
88 changes: 88 additions & 0 deletions test/Sentry.Tests/SentrySdkTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using Sentry.Extensibility;
using Sentry.Internal;
using Sentry.Internal.Http;
using Sentry.Internal.ScopeStack;
using Sentry.Protocol.Envelopes;
using Sentry.Testing;
using Xunit;
using Xunit.Abstractions;
using static Sentry.Internal.Constants;

namespace Sentry.Tests;
Expand Down Expand Up @@ -831,6 +843,82 @@ public void InitHub_DebugEnabled_DebugLogsLogged()
Arg.Any<object[]>());
}

#if __IOS__
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ProcessOnBeforeSend_SegfaultsSuppressed(bool suppressSegfaults)
{
var options = new SentryOptions
{
Dsn = ValidDsn,
DiagnosticLogger = _logger,
IsGlobalModeEnabled = true,
Debug = true,
AutoSessionTracking = false,
BackgroundWorker = Substitute.For<IBackgroundWorker>(),
InitNativeSdks = false
};
options.Native.SuppressSegfaults = suppressSegfaults;

var evt = new Sentry.CocoaSdk.SentryEvent();
var ex = new Sentry.CocoaSdk.SentryException("Signal 6, Code 0", "SIGABRT");
var st = new Sentry.CocoaSdk.SentryStacktrace(
[new Sentry.CocoaSdk.SentryFrame
{
Function = "xamarin_unhandled_exception_handler"
}],
new Foundation.NSDictionary<Foundation.NSString, Foundation.NSString>()
);
ex.Stacktrace = st;
evt.Exceptions = [ex];
var result = SentrySdk.ProcessOnBeforeSend(options, evt);

if (suppressSegfaults)
{
result.Should().BeNull();
}
else
{
result.Should().NotBeNull();
result.Should.Exceptions.First().Type.Should().Be("SIGABRT");
}
}

[Fact]
public void ProcessOnBeforeSend_OptionsBeforeOnSendRuns()
{
var options = new SentryOptions
{
Dsn = ValidDsn,
DiagnosticLogger = _logger,
IsGlobalModeEnabled = true,
Debug = true,
AutoSessionTracking = false,
BackgroundWorker = Substitute.For<IBackgroundWorker>(),
InitNativeSdks = false
};

var native = new Sentry.CocoaSdk.SentryEvent();
native.ServerName = "server name";
native.Dist = "dist";
native.Logger = "logger";
native.ReleaseName = "release name";
native.Environment = "environment";
native.Platform = "platform";
native.Transaction = "transaction name";

options.SetBeforeSend(e =>
{
e.Platform = "dotnet";
return e;
});
var result = SentrySdk.ProcessOnBeforeSend(options, native);
result.Should().NotBeNull();
result.Platform.Should().Be("dotnet");
}
#endif

public void Dispose()
{
SentrySdk.Close();
Expand Down