Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: 1 addition & 1 deletion src/Sentry/Internal/ReplaySession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public SentryId? ActiveReplayId
return (replayId is { } id && id != SentryId.Empty) ? id : null;
#elif __IOS__
string? nativeId = null;
SentryCocoaSdk.ConfigureScope(scope => nativeId = scope.ReplayId);
Sentry.Cocoa.CocoaScope.Configure(scope => nativeId = scope.ReplayId);
return (nativeId is { } id) ? SentryId.Parse(id) : null;
#else
return null;
Expand Down
32 changes: 32 additions & 0 deletions src/Sentry/Platforms/Cocoa/CocoaScope.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Sentry.CocoaSdk;
using Sentry.Extensibility;

namespace Sentry.Cocoa;

internal static class CocoaScope
{
[ThreadStatic]
private static int t_configureDepth;

internal static bool IsConfiguring => t_configureDepth > 0;

internal static void Configure(
Action<SentryObjCScope> callback,
SentryOptions? options = null,
Action<Action<SentryObjCScope>>? configureNativeScope = null)
{
t_configureDepth++;
try
{
(configureNativeScope ?? SentryCocoaSdk.ConfigureScope)(callback);
}
catch (Exception e)
{
options?.LogError(e, "Failed to configure the native scope.");
}
finally
{
t_configureDepth--;
}
}
}
15 changes: 7 additions & 8 deletions src/Sentry/Platforms/Cocoa/CocoaScopeObserver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public void AddBreadcrumb(Breadcrumb breadcrumb)
try
{
var b = breadcrumb.ToCocoaBreadcrumb();
SentryCocoaSdk.ConfigureScope(scope => scope.AddBreadcrumb(b));
CocoaScope.Configure(scope => scope.AddBreadcrumb(b), _options);
}
finally
{
Expand All @@ -43,16 +43,15 @@ public void SetExtra(string key, object? value)

if (value is string s)
{
SentryCocoaSdk.ConfigureScope(scope =>
scope.SetExtraValue(NSObject.FromObject(s), key));
CocoaScope.Configure(scope => scope.SetExtraValue(NSObject.FromObject(s), key), _options);

return;
}

try
{
var json = value.ToUtf8Json();
SentryCocoaSdk.ConfigureScope(scope => scope.SetExtraValue(NSObject.FromObject(json), key));
CocoaScope.Configure(scope => scope.SetExtraValue(NSObject.FromObject(json), key), _options);
}
catch (Exception ex)
{
Expand All @@ -75,7 +74,7 @@ public void SetTag(string key, string value)

try
{
SentryCocoaSdk.ConfigureScope(scope => scope.SetTagValue(value, key));
CocoaScope.Configure(scope => scope.SetTagValue(value, key), _options);
}
finally
{
Expand All @@ -87,7 +86,7 @@ public void UnsetTag(string key)
{
try
{
SentryCocoaSdk.ConfigureScope(scope => scope.RemoveTagForKey(key));
CocoaScope.Configure(scope => scope.RemoveTagForKey(key), _options);
}
finally
{
Expand All @@ -100,7 +99,7 @@ public void SetUser(SentryUser? user)
try
{
var u = user?.ToCocoaUser();
SentryCocoaSdk.ConfigureScope(scope => scope.SetUser(u));
CocoaScope.Configure(scope => scope.SetUser(u), _options);
}
finally
{
Expand All @@ -124,7 +123,7 @@ public void SetEnvironment(string? environment)
{
try
{
SentryCocoaSdk.ConfigureScope(scope => scope.SetEnvironment(environment));
CocoaScope.Configure(scope => scope.SetEnvironment(environment), _options);
}
finally
{
Expand Down
2 changes: 1 addition & 1 deletion src/Sentry/Platforms/Cocoa/RuntimeAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ private RuntimeAdapter()
public event MarshalManagedExceptionHandler? MarshalManagedException;
public event MarshalObjectiveCExceptionHandler? MarshalObjectiveCException;

public bool IsMono { get; } = Type.GetType("Mono.Runtime") != null;
public bool IsMono { get; } = Type.GetType("Mono.RuntimeStructs") != null;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


public void IgnoreNextSignal(int signal) => SentryCocoaHybridSdk.Internal.IgnoreNextSignal(signal);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,39 @@ public void Register(IHub hub, SentryOptions options)
[SecurityCritical]
internal void Handle(object sender, MarshalManagedExceptionEventArgs e)
{
if (CocoaScope.IsConfiguring)
{
// Return it to CocoaScope.Configure: only Mono can unwind native frames, CoreCLR has to rethrow it as an NSException.
e.ExceptionMode = _runtime.IsMono
? MarshalManagedExceptionMode.UnwindNativeCode
: MarshalManagedExceptionMode.ThrowObjectiveCException;
_options?.LogDebug("Managed exception escaped a native scope callback: {0}", e.Exception?.Message);
return;
}

_options?.LogDebug("Runtime Marshal Managed Exception mode {0}", e.ExceptionMode.ToString("G"));

if (e.Exception is { } ex)
{
ex.SetSentryMechanism(
"Runtime.MarshalManagedException",
"This exception was caught by the .NET Runtime Marshal Managed Exception global error handler. " +
"The application may have crashed as a result of this exception.",
handled: false);
try
{
ex.SetSentryMechanism(
"Runtime.MarshalManagedException",
"This exception was caught by the .NET Runtime Marshal Managed Exception global error handler. " +
"The application may have crashed as a result of this exception.",
handled: false);

// Call the internal implementation, so that we still capture even if the hub has been disabled.
_hub?.CaptureExceptionInternal(ex);
// Call the internal implementation, so that we still capture even if the hub has been disabled.
_hub?.CaptureExceptionInternal(ex);

// This is likely a terminal exception so try to send the crash report before shutting down
_hub?.Flush();
// This is likely a terminal exception so try to send the crash report before shutting down
_hub?.Flush();
}
catch (Exception captureException)
{
_options?.LogError(captureException, "Failed to capture the marshaled managed exception.");
return;
}

// Under Mono, Disable/UnwindNativeCode call mono_raise_exception which can unwind into
// a managed catch and never hit abort(). The thread-local ignore flag would then linger
Expand Down
32 changes: 32 additions & 0 deletions test/Sentry.Tests/Platforms/iOS/CocoaScopeTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#if IOS
using Sentry.Cocoa;

namespace Sentry.Tests.Platforms.iOS;

public class CocoaScopeTests
{
[Fact]
public void Configure_DuringNativeCall_IsConfiguring()
{
var isConfiguring = false;

CocoaScope.Configure(_ => { }, configureNativeScope: _ => isConfiguring = CocoaScope.IsConfiguring);

Assert.True(isConfiguring);
Assert.False(CocoaScope.IsConfiguring);
}

[Fact]
public void Configure_NativeCallThrows_LogsError()
{
var logger = new InMemoryDiagnosticLogger();
var options = new SentryOptions { Debug = true, DiagnosticLogger = logger };
var exception = new InvalidOperationException();

CocoaScope.Configure(_ => { }, options, _ => throw exception);

Assert.Contains(logger.Entries, entry => entry.Level == SentryLevel.Error && entry.Exception == exception);
Assert.False(CocoaScope.IsConfiguring);
}
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,37 @@ public void Handle_CoreCLR_AnyMode_IgnoresSigabrt(MarshalManagedExceptionMode mo
_fixture.Runtime.Received(1).IgnoreNextSignal(6);
}

[Theory]
[InlineData(true, MarshalManagedExceptionMode.UnwindNativeCode)]
[InlineData(false, MarshalManagedExceptionMode.ThrowObjectiveCException)]
public void Handle_EscapedNativeScopeCallback_ReturnsExceptionToCaller(bool isMono, MarshalManagedExceptionMode expectedMode)
{
_fixture.Runtime.IsMono.Returns(isMono);
var sut = _fixture.GetSut();
sut.Register(_fixture.Hub, SentryOptions);
var args = new MarshalManagedExceptionEventArgs { Exception = new Exception(), ExceptionMode = MarshalManagedExceptionMode.Default };

CocoaScope.Configure(_ => { }, configureNativeScope: _ => sut.Handle(this, args));

_fixture.Hub.DidNotReceive().CaptureEvent(Arg.Any<SentryEvent>());
Assert.Equal(expectedMode, args.ExceptionMode);
_fixture.Runtime.DidNotReceive().IgnoreNextSignal(Arg.Any<int>());
}

[Fact]
public void Handle_CaptureThrows_LeavesModeUnchanged()
{
_fixture.Hub.When(hub => hub.CaptureEvent(Arg.Any<SentryEvent>())).Do(_ => throw new InvalidOperationException());
var sut = _fixture.GetSut();
sut.Register(_fixture.Hub, SentryOptions);
var args = new MarshalManagedExceptionEventArgs { Exception = new Exception(), ExceptionMode = MarshalManagedExceptionMode.Default };

sut.Handle(this, args);

Assert.Equal(MarshalManagedExceptionMode.Default, args.ExceptionMode);
_fixture.Runtime.DidNotReceive().IgnoreNextSignal(Arg.Any<int>());
}

[Fact]
public void Handle_NoException_DoesNotIgnoreSigabrt()
{
Expand Down
Loading