Skip to content

fix: Native layer not closing #1092

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

Merged
merged 10 commits into from
Dec 5, 2022
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Features

- Added missing SDK closing functionality ([#1092](https://github.com/getsentry/sentry-unity/pull/1092))

### Fixes

- Fixed logging for automated debug symbol upload for iOS ([#1091](https://github.com/getsentry/sentry-unity/pull/1091))
Expand Down
9 changes: 9 additions & 0 deletions package-dev/Runtime/SentryInitialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,15 @@ public static void Init()
options.DiagnosticLogger?.LogDebug("Creating '{0}' span.", SubSystemSpanOperation);
SubSystemRegistrationSpan = InitSpan.StartChild(SubSystemSpanOperation, "subsystem registration");
}
#endif
}
else
{
// Closing down the native layer that are set up during build and self-initialize
#if SENTRY_NATIVE_COCOA
SentryNativeCocoa.Close(options.DiagnosticLogger);
#elif SENTRY_NATIVE_ANDROID
SentryNativeAndroid.Close(options.DiagnosticLogger);
#endif
}
}
Expand Down
19 changes: 12 additions & 7 deletions src/Sentry.Unity.Android/SentryNativeAndroid.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using Sentry.Extensibility;
using Sentry.Unity.Integrations;
using Sentry.Unity.NativeUtils;

namespace Sentry.Unity.Android
{
Expand Down Expand Up @@ -53,15 +54,19 @@ public static void Configure(SentryUnityOptions options, ISentryUnityInfo sentry
"Failed to reinstall backend. Captured native crashes will miss scope data and tag.", e);
}

ApplicationAdapter.Instance.Quitting += () =>
{
// Sentry Native is initialized and closed by the Java SDK, no need to call into it directly
options.DiagnosticLogger?.LogDebug("Closing the sentry-java SDK");
SentryJava.Close();
};

options.NativeSupportCloseCallback = () => Close(options.DiagnosticLogger);
options.DefaultUserId = SentryJava.GetInstallationId();
}
}

/// <summary>
/// Closes the native Android support.
/// </summary>
public static void Close(IDiagnosticLogger? logger = null)
{
// Sentry Native is initialized and closed by the Java SDK, no need to call into it directly
logger?.LogDebug("Closing the sentry-java SDK");
SentryJava.Close();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,21 @@ internal static void Configure(SentryUnityOptions options, ISentryUnityInfo sent

return crashedLastRun;
};
ApplicationAdapter.Instance.Quitting += () =>
{
options.DiagnosticLogger?.LogDebug("Closing the sentry-cocoa SDK");
SentryCocoaBridgeProxy.Close();
};

options.NativeSupportCloseCallback += () => Close(options.DiagnosticLogger);
if (sentryUnityInfo.IL2CPP)
{
options.DefaultUserId = SentryCocoaBridgeProxy.GetInstallationId();
}
}

/// <summary>
/// Closes the native Cocoa support.
/// </summary>
public static void Close(IDiagnosticLogger? logger = null)
{
logger?.LogDebug("Closing the sentry-cocoa SDK");
SentryCocoaBridgeProxy.Close();
}
}
}
89 changes: 56 additions & 33 deletions src/Sentry.Unity/SentryUnity.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.IO;
using System.ComponentModel;
using System.Diagnostics.Tracing;
using System.Threading.Tasks;
using System.Xml;
using Sentry.Extensibility;
using Sentry.Unity.Integrations;
using UnityEngine;
Expand All @@ -13,6 +15,9 @@ namespace Sentry.Unity
/// </summary>
public static class SentryUnity
{
private static IDisposable? DotnetSdk;
private static SentryUnityOptions? Options;

private static FileStream? LockFile;

/// <summary>
Expand All @@ -33,75 +38,93 @@ public static void Init(Action<SentryUnityOptions> sentryUnityOptionsConfigure)
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Init(SentryUnityOptions options)
{
options.SetupLogging();
if (options.ShouldInitializeSdk())
Options = options;

Options.SetupLogging();
if (Options.ShouldInitializeSdk())
{
// On Standalone, we disable cache dir in case multiple app instances run over the same path.
// Note: we cannot use a named Mutex, because Unit doesn't support it. Instead, we create a file with `FileShare.None`.
// https://forum.unity.com/threads/unsupported-internal-call-for-il2cpp-mutex-createmutex_internal-named-mutexes-are-not-supported.387334/
if (ApplicationAdapter.Instance.Platform is RuntimePlatform.WindowsPlayer && options.CacheDirectoryPath is not null)
if (ApplicationAdapter.Instance.Platform is RuntimePlatform.WindowsPlayer && Options.CacheDirectoryPath is not null)
{
try
{
LockFile = new FileStream(Path.Combine(options.CacheDirectoryPath, "sentry-unity.lock"), FileMode.OpenOrCreate,
LockFile = new FileStream(Path.Combine(Options.CacheDirectoryPath, "sentry-unity.lock"), FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
}
catch (Exception ex)
{
options.DiagnosticLogger?.LogWarning("An exception was thrown while trying to " +
"acquire a lockfile on the config directory: .NET event cache will be disabled.", ex);
options.CacheDirectoryPath = null;
options.AutoSessionTracking = false;

Options.DiagnosticLogger?.LogWarning("An exception was thrown while trying to " +
"acquire a lockfile on the config directory: .NET event cache will be disabled.", ex);
Options.CacheDirectoryPath = null;
Options.AutoSessionTracking = false;
}
}

var sentryDotNet = SentrySdk.Init(options);
DotnetSdk = SentrySdk.Init(options);

if (options.AttachScreenshot)
if (Options.AttachScreenshot)
{
SentrySdk.ConfigureScope(s =>
s.AddAttachment(new ScreenshotAttachment(
new ScreenshotAttachmentContent(options, SentryMonoBehaviour.Instance))));
}

if (options.NativeContextWriter is { } contextWriter)
if (Options.NativeContextWriter is { } contextWriter)
{
SentrySdk.ConfigureScope((scope) =>
{
var task = Task.Run(() => contextWriter.Write(scope)).ContinueWith(t =>
{
if (t.Exception is not null)
{
options.DiagnosticLogger?.LogWarning(
Options.DiagnosticLogger?.LogWarning(
"Failed to synchronize scope to the native SDK: {0}", t.Exception);
}
});
});
}

ApplicationAdapter.Instance.Quitting += Close;
}
}

/// <summary>
/// Closes the Sentry Unity SDK
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Close()
{
Options?.DiagnosticLogger?.LogDebug("Closing the sentry-dotnet SDK");
try
{
ApplicationAdapter.Instance.Quitting -= Close;

ApplicationAdapter.Instance.Quitting += () =>
if (Options is not null)
{
options.DiagnosticLogger?.LogDebug("Closing the sentry-dotnet SDK");
try
{
sentryDotNet.Dispose();
}
finally
{
try
{
// We don't really need to close, Windows would release the lock anyway, but let's be nice.
LockFile?.Close();
}
catch (Exception ex)
{
options.DiagnosticLogger?.Log(SentryLevel.Warning,
"Exception while releasing the lockfile on the config directory.", ex);
}
}
};
Options.NativeSupportCloseCallback?.Invoke();
Options.NativeSupportCloseCallback = null;
}

DotnetSdk?.Dispose();
DotnetSdk = null;
}
catch (Exception ex)
{
Options?.DiagnosticLogger?.Log(SentryLevel.Warning,
"Exception while closing the .NET SDK.", ex);
}

try
{
// We don't really need to close, Windows would release the lock anyway, but let's be nice.
LockFile?.Close();
}
catch (Exception ex)
{
Options?.DiagnosticLogger?.Log(SentryLevel.Warning,
"Exception while releasing the lockfile on the config directory.", ex);
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/Sentry.Unity/SentryUnityOptions.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -157,6 +158,11 @@ internal string? DefaultUserId
/// </summary>
internal ContextWriter? NativeContextWriter { get; set; } = null;

/// <summary>
/// Used to close down the native SDK
/// </summary>
internal Action? NativeSupportCloseCallback { get; set; } = null;

internal List<string> SdkIntegrationNames { get; set; } = new();

public SentryUnityOptions() : this(false, null, ApplicationAdapter.Instance) { }
Expand Down