Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

### Fixes

- iOS native crashes now come with a screenshot when `AttachScreenshot` is enabled. Screenshots captured during a crash skip `SetBeforeCaptureScreenshot` and `SetBeforeSendScreenshot` because these callbacks can't run during a crash. To make sure a screenshot you'd skip or redact isn't sent unredacted, setting either callback turns crash screenshots off. Events that sentry-cocoa captures itself, such as failed HTTP requests, no longer get a screenshot ([#2941](https://github.com/getsentry/sentry-unity/pull/2941))
- On iOS and macOS, native crashes now respect the Event Sample Rate (`SampleRate`). Unity passes it to the Cocoa SDK with both runtime and build-time initialization, so native crashes are no longer always sent. ([#2940](https://github.com/getsentry/sentry-unity/pull/2940))
- Values set in a `SentryCliOptionsConfiguration`, such as an auth token read from an environment variable, no longer get saved into `SentryCliOptions.asset` by the Sentry window after a build. The configuration now runs on a copy of the options. ([#2938](https://github.com/getsentry/sentry-unity/pull/2938))
- The configuration window's tooltips and help boxes and the option docs describe the SDK's defaults and requirements correctly: `Auto Set UserName` is disabled by default, `Attach Screenshots` also attaches screenshots to events on background threads, `Org Slug` is required unless the Auth Token is an organization token, `Scene Traces` has no Unity version requirement, and `IosWatchdogTerminationIntegrationEnabled` turns on reporting of watchdog terminations on iOS. ([#2933](https://github.com/getsentry/sentry-unity/pull/2933))
Expand Down
3 changes: 3 additions & 0 deletions package-dev/Plugins/iOS/SentryNativeBridge.m
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@
dictOptions[@"sdk"] = @ { @"name" : @"sentry.cocoa.unity" };
dictOptions[@"enableAutoSessionTracking"] = @NO;
dictOptions[@"enableAppHangTracking"] = @NO;
// Screenshots for C# events come from the Unity SDK. With `attachScreenshot`, sentry-cocoa attaches one
// only to native crashes: the crash-time screenshot doesn't call this block.
dictOptions[@"beforeCaptureScreenshot"] = ^BOOL(id event) { return NO; };
Comment thread
bitsandfoxes marked this conversation as resolved.
Resolved
return CFBridgingRetain(dictOptions);
}

Expand Down
5 changes: 4 additions & 1 deletion src/Sentry.Unity.Editor.iOS/NativeOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ internal static string Generate(SentryUnityOptions options)
@""failedRequestStatusCodes"" : @[{failedRequestStatusCodesArray}],
{GetSampleRateEntry(options.SampleRate)}
@""sendDefaultPii"" : @{ToObjCString(options.SendDefaultPii)},
@""attachScreenshot"" : @{ToObjCString(options.AttachScreenshot)},
@""attachScreenshot"" : @{ToObjCString(options.AttachNativeCrashScreenshot)},
// Screenshots for C# events come from the Unity SDK. sentry-cocoa attaches one only to native crashes,
// as its crash-time screenshot doesn't call this block.
@""beforeCaptureScreenshot"" : ^BOOL(id event) {{ return NO; }},
@""release"" : @""{options.Release}"",
@""environment"" : @""{options.Environment}"",
@""enableNetworkBreadcrumbs"" : @NO,
Expand Down
18 changes: 13 additions & 5 deletions src/Sentry.Unity.iOS/SentryCocoaBridgeProxy.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Runtime.InteropServices;
using Sentry.Extensibility;
using UnityEngine;

namespace Sentry.Unity.iOS;

Expand All @@ -16,7 +17,7 @@ internal static class SentryCocoaBridgeProxy
private static IDiagnosticLogger? Logger;
public static bool IsEnabled() => SentryNativeBridgeIsEnabled() == 1;

public static bool Init(SentryUnityOptions options)
public static bool Init(SentryUnityOptions options, RuntimePlatform platform)
{
if (LoadLibrary() != 1)
{
Expand Down Expand Up @@ -58,10 +59,13 @@ public static bool Init(SentryUnityOptions options)
Logger?.LogDebug("Setting SendDefaultPii: {0}", options.SendDefaultPii);
OptionsSetInt(cOptions, "sendDefaultPii", options.SendDefaultPii ? 1 : 0);

// macOS screenshots currently don't work, because there's no UIKit. Cocoa logs: "Sentry - info:: NO UIKit"
// Logger?.LogDebug("Setting AttachScreenshot: {0}", options.AttachScreenshot);
// OptionsSetInt(cOptions, "attachScreenshot", options.AttachScreenshot ? 1 : 0);
OptionsSetInt(cOptions, "attachScreenshot", 0);
var attachScreenshot = ShouldAttachScreenshot(options, platform);
if (options.AttachScreenshot && platform == RuntimePlatform.IPhonePlayer && !attachScreenshot)
{
Logger?.LogDebug("Not attaching screenshots to native crashes: a screenshot callback is set, and it can't run during a crash.");
}
Logger?.LogDebug("Setting AttachScreenshot: {0}", attachScreenshot);
OptionsSetInt(cOptions, "attachScreenshot", attachScreenshot ? 1 : 0);

Logger?.LogDebug("Setting MaxBreadcrumbs: {0}", options.MaxBreadcrumbs);
OptionsSetInt(cOptions, "maxBreadcrumbs", options.MaxBreadcrumbs);
Expand Down Expand Up @@ -97,6 +101,10 @@ public static bool Init(SentryUnityOptions options)
return result is 1;
}

// sentry-cocoa takes screenshots through UIKit, which macOS doesn't have.
internal static bool ShouldAttachScreenshot(SentryUnityOptions options, RuntimePlatform platform) =>
platform == RuntimePlatform.IPhonePlayer && options.AttachNativeCrashScreenshot;

[DllImport("__Internal", EntryPoint = "SentryNativeBridgeLoadLibrary")]
private static extern int LoadLibrary();

Expand Down
4 changes: 2 additions & 2 deletions src/Sentry.Unity.iOS/SentryNativeCocoa.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal static void Configure(SentryUnityOptions options, RuntimePlatform platf
"Make sure the app initializes Sentry before the game starts. Skipping native support.");
return;
}
else if (!SentryCocoaBridgeProxy.Init(options))
else if (!SentryCocoaBridgeProxy.Init(options, platform))
{
Logger?.LogWarning("Failed to initialize the native SDK");
return;
Expand All @@ -72,7 +72,7 @@ internal static void Configure(SentryUnityOptions options, RuntimePlatform platf
}
else
{
if (!SentryCocoaBridgeProxy.Init(options))
if (!SentryCocoaBridgeProxy.Init(options, platform))
{
Logger?.LogWarning("Failed to initialize the native SDK");
return;
Expand Down
6 changes: 6 additions & 0 deletions src/Sentry.Unity/SentryUnityOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -410,12 +410,17 @@ internal bool NativeAppHangTrackingEnabled

internal Func<SentryEvent, bool>? BeforeCaptureScreenshotInternal { get; private set; }

// The native SDKs take native-crash screenshots in their crash handler, where these C# callbacks can't run.
internal bool AttachNativeCrashScreenshot =>
AttachScreenshot && BeforeCaptureScreenshotInternal is null && BeforeSendScreenshotInternal is null;

/// <summary>
/// Configures a callback function to be invoked before capturing and attaching a screenshot to an event.
/// </summary>
/// <remarks>
/// This callback will get invoked when the event gets captured, possibly off the main thread, so don't use the Unity
/// API in it. If the screenshot should not be taken return `false`.
/// Setting it turns off screenshots for native crashes on iOS, as the callback can't run during a crash.
/// </remarks>
public void SetBeforeCaptureScreenshot(Func<SentryEvent, bool> beforeAttachScreenshot)
{
Expand All @@ -432,6 +437,7 @@ public void SetBeforeCaptureScreenshot(Func<SentryEvent, bool> beforeAttachScree
/// You can modify the texture (blur areas, redact PII, etc.) and return it, or return null to discard.
/// It runs once per screenshot. Events captured together share one, and the callback receives the first of them
/// that didn't get dropped.
/// Setting it turns off screenshots for native crashes on iOS, as the callback can't run during a crash.
/// </remarks>
/// <param name="beforeSendScreenshot">The callback function to invoke before sending screenshots.</param>
public void SetBeforeSendScreenshot(Func<Texture2D, SentryEvent, Texture2D?> beforeSendScreenshot)
Expand Down
27 changes: 27 additions & 0 deletions test/Sentry.Unity.Editor.iOS.Tests/NativeOptionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,33 @@ public void CreateOptionsFile_AppHangTimeout_WrittenAsSeconds()
StringAssert.Contains("@\"appHangTimeoutInterval\": @7.5", nativeOptions);
}

[Test]
public void CreateOptionsFile_AttachScreenshot_SetsYes()
{
var nativeOptions = NativeOptions.Generate(new SentryUnityOptions { AttachScreenshot = true });

StringAssert.Contains("@\"attachScreenshot\" : @YES", nativeOptions);
}

[Test]
public void CreateOptionsFile_AttachScreenshotWithScreenshotCallback_SetsNo()
{
var options = new SentryUnityOptions { AttachScreenshot = true };
options.SetBeforeCaptureScreenshot(_ => true);

var nativeOptions = NativeOptions.Generate(options);

StringAssert.Contains("@\"attachScreenshot\" : @NO", nativeOptions);
}

[Test]
public void CreateOptionsFile_BeforeCaptureScreenshot_SkipsNonFatalEvents()
{
var nativeOptions = NativeOptions.Generate(new SentryUnityOptions { AttachScreenshot = true });

StringAssert.Contains("@\"beforeCaptureScreenshot\" : ^BOOL(id event) { return NO; }", nativeOptions);
}

[Test]
public void CreateOptionsFile_FilterBadGatewayEnabled_AddsFiltering()
{
Expand Down
29 changes: 29 additions & 0 deletions test/Sentry.Unity.iOS.Tests/SentryNativeIosTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,33 @@ public void Configure_NativeSupportDisabled_macOS()
Assert.Null(options.CrashedLastRun);
Assert.False(options.EnableScopeSync);
}

[TestCase(RuntimePlatform.IPhonePlayer, true, true)]
[TestCase(RuntimePlatform.IPhonePlayer, false, false)]
[TestCase(RuntimePlatform.OSXPlayer, true, false)]
[TestCase(RuntimePlatform.OSXPlayer, false, false)]
public void ShouldAttachScreenshot_FollowsOptionOnIosOnly(RuntimePlatform platform, bool attachScreenshot, bool expected)
{
var options = new SentryUnityOptions { AttachScreenshot = attachScreenshot };

Assert.AreEqual(expected, SentryCocoaBridgeProxy.ShouldAttachScreenshot(options, platform));
}

[Test]
public void ShouldAttachScreenshot_BeforeCaptureScreenshotSet_False()
{
var options = new SentryUnityOptions { AttachScreenshot = true };
options.SetBeforeCaptureScreenshot(_ => true);

Assert.IsFalse(SentryCocoaBridgeProxy.ShouldAttachScreenshot(options, RuntimePlatform.IPhonePlayer));
}

[Test]
public void ShouldAttachScreenshot_BeforeSendScreenshotSet_False()
{
var options = new SentryUnityOptions { AttachScreenshot = true };
options.SetBeforeSendScreenshot((screenshot, _) => screenshot);

Assert.IsFalse(SentryCocoaBridgeProxy.ShouldAttachScreenshot(options, RuntimePlatform.IPhonePlayer));
}
}
Loading