-
-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathSentryNativeBridge.cs
More file actions
336 lines (280 loc) · 11.9 KB
/
SentryNativeBridge.cs
File metadata and controls
336 lines (280 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
using System;
using System.IO;
using System.Runtime.InteropServices;
using Sentry.Extensibility;
using Sentry.Unity.Integrations;
using UnityEngine;
using AOT;
namespace Sentry.Unity.Native;
/// <summary>
/// P/Invoke to `sentry-native` functions.
/// </summary>
/// <see href="https://github.com/getsentry/sentry-native"/>
internal static class SentryNativeBridge
{
#if SENTRY_NATIVE_SWITCH
private const string SentryLib = "__Internal";
#else
private const string SentryLib = "sentry";
#endif
private static IDiagnosticLogger? Logger; // This is also the logger we're forwarding native messages to.
private static bool UseLibC;
private static bool IsWindows;
public static bool Init(SentryUnityOptions options)
{
Logger = options.DiagnosticLogger;
UseLibC = Application.platform
is RuntimePlatform.LinuxPlayer or RuntimePlatform.LinuxServer
or RuntimePlatform.PS5 or RuntimePlatform.Switch;
IsWindows = Application.platform
is RuntimePlatform.WindowsPlayer or RuntimePlatform.WindowsServer
or RuntimePlatform.GameCoreXboxSeries or RuntimePlatform.GameCoreXboxOne;
var cOptions = sentry_options_new();
// Note: DSN is not null because options.IsValid() must have returned true for this to be called.
sentry_options_set_dsn(cOptions, options.Dsn!);
if (options.Release is not null)
{
Logger?.LogDebug("Setting Release: {0}", options.Release);
sentry_options_set_release(cOptions, options.Release);
}
if (options.Environment is not null)
{
Logger?.LogDebug("Setting Environment: {0}", options.Environment);
sentry_options_set_environment(cOptions, options.Environment);
}
Logger?.LogDebug("Setting Debug: {0}", options.Debug);
sentry_options_set_debug(cOptions, options.Debug ? 1 : 0);
if (options.SampleRate.HasValue)
{
Logger?.LogDebug("Setting Sample Rate: {0}", options.SampleRate.Value);
sentry_options_set_sample_rate(cOptions, options.SampleRate.Value);
}
// Disabling the native in favor of the C# layer for now
Logger?.LogDebug("Disabling native auto session tracking");
sentry_options_set_auto_session_tracking(cOptions, 0);
if (IsWindows)
{
Logger?.LogDebug("Setting AttachScreenshot: {0}", options.AttachScreenshot);
sentry_options_set_attach_screenshot(cOptions, options.AttachScreenshot ? 1 : 0);
}
#if SENTRY_NATIVE_XBOX
SentryNativeXbox.ResolveStoragePath(options, Logger);
#endif
var databasePath = GetDatabasePath(options);
#if SENTRY_NATIVE_SWITCH
Logger?.LogDebug("Setting DatabasePath: {0}", databasePath);
sentry_options_set_database_path(cOptions, databasePath);
#else
// Note: don't use RuntimeInformation.IsOSPlatform - it will report windows on WSL.
if (IsWindows)
{
Logger?.LogDebug("Setting DatabasePath on Windows: {0}", databasePath);
sentry_options_set_database_pathw(cOptions, databasePath);
}
else
{
Logger?.LogDebug("Setting DatabasePath: {0}", databasePath);
sentry_options_set_database_path(cOptions, databasePath);
}
#endif
Logger?.LogDebug("Setting EnableMetrics: {0}", options.EnableMetrics);
sentry_options_set_enable_metrics(cOptions, options.EnableMetrics ? 1 : 0);
if (options.UnityInfo.IL2CPP)
{
Logger?.LogDebug("Setting the native logger");
sentry_options_set_logger(cOptions, new sentry_logger_function_t(nativeLog), IntPtr.Zero);
}
else
{
Logger?.LogInfo("Passing the native logs back to the C# layer is not supported on Mono - skipping native logger.");
}
Logger?.LogDebug("Initializing sentry native");
return 0 == sentry_init(cOptions);
}
public static void Close() => sentry_close();
// Call after native init() to check if the application has crashed in the previous run and clear the status.
// Because the file is removed, the result will change on subsequent calls so it must be cached for the current runtime.
internal static bool HandleCrashedLastRun(SentryUnityOptions options)
{
var result = sentry_get_crashed_last_run() == 1;
sentry_clear_crashed_last_run();
return result;
}
internal static string GetDatabasePath(SentryUnityOptions options, IApplication? application = null)
{
if (options.CacheDirectoryPath is not null)
{
return Path.Combine(options.CacheDirectoryPath, ".sentry-native");
}
// This is a fallback attempting to provide native crash support in case of CacheDirectoryPath not being set.
// Xbox and Switch rely on their own mechanisms to resolve storage, see SentryNativeXbox and SentryNativeSwitch.
application ??= ApplicationAdapter.Instance;
return Path.Combine(application.PersistentDataPath, ".sentry-native");
}
internal static void ReinstallBackend() => sentry_reinstall_backend();
// libsentry.so
[DllImport(SentryLib)]
private static extern IntPtr sentry_options_new();
[DllImport(SentryLib)]
private static extern void sentry_options_set_dsn(IntPtr options, string dsn);
[DllImport(SentryLib)]
private static extern void sentry_options_set_release(IntPtr options, string release);
[DllImport(SentryLib)]
private static extern void sentry_options_set_debug(IntPtr options, int debug);
[DllImport(SentryLib)]
private static extern void sentry_options_set_environment(IntPtr options, string environment);
[DllImport(SentryLib)]
private static extern void sentry_options_set_sample_rate(IntPtr options, double rate);
[DllImport(SentryLib)]
private static extern void sentry_options_set_database_path(IntPtr options, string path);
#if !SENTRY_NATIVE_SWITCH
[DllImport(SentryLib)]
private static extern void sentry_options_set_database_pathw(IntPtr options, [MarshalAs(UnmanagedType.LPWStr)] string path);
#endif
[DllImport(SentryLib)]
private static extern void sentry_options_set_auto_session_tracking(IntPtr options, int debug);
[DllImport(SentryLib)]
private static extern void sentry_options_set_attach_screenshot(IntPtr options, int attachScreenshot);
[DllImport(SentryLib)]
private static extern void sentry_options_set_enable_metrics(IntPtr options, int enable_metrics);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, SetLastError = true)]
private delegate void sentry_logger_function_t(int level, IntPtr message, IntPtr argsAddress, IntPtr userData);
[DllImport(SentryLib)]
private static extern void sentry_options_set_logger(IntPtr options, sentry_logger_function_t logger, IntPtr userData);
// This method is called from the C library and forwards incoming messages to the currently set _logger.
[MonoPInvokeCallback(typeof(sentry_logger_function_t))]
private static void nativeLog(int cLevel, IntPtr format, IntPtr args, IntPtr userData)
{
try
{
nativeLogImpl(cLevel, format, args, userData);
}
catch
{
// never allow an exception back to native code - it would crash the app
}
}
private static void nativeLogImpl(int cLevel, IntPtr format, IntPtr args, IntPtr userData)
{
var logger = Logger;
if (logger is null || format == IntPtr.Zero || args == IntPtr.Zero)
{
return;
}
// see sentry.h: sentry_level_e
var level = cLevel switch
{
-1 => SentryLevel.Debug,
0 => SentryLevel.Info,
1 => SentryLevel.Warning,
2 => SentryLevel.Error,
3 => SentryLevel.Fatal,
_ => SentryLevel.Info,
};
if (!logger.IsEnabled(level))
{
return;
}
string? message = null;
try
{
// We cannot access C var-arg (va_list) in c# thus we pass it back to vsnprintf to do the formatting.
// For Linux and PlayStation, we must make a copy of the VaList to be able to pass it back...
if (UseLibC)
{
var argsStruct = Marshal.PtrToStructure<VaListLinux64>(args);
var formattedLength = 0;
WithMarshalledStruct(argsStruct, argsPtr =>
{
formattedLength = 1 + vsnprintf(IntPtr.Zero, UIntPtr.Zero, format, argsPtr);
});
WithAllocatedPtr(formattedLength, buffer =>
WithMarshalledStruct(argsStruct, argsPtr =>
{
vsnprintf(buffer, (UIntPtr)formattedLength, format, argsPtr);
message = Marshal.PtrToStringAnsi(buffer);
}));
}
else
{
var formattedLength = 1 + vsnprintf(IntPtr.Zero, UIntPtr.Zero, format, args);
WithAllocatedPtr(formattedLength, buffer =>
{
vsnprintf(buffer, (UIntPtr)formattedLength, format, args);
message = Marshal.PtrToStringAnsi(buffer);
});
}
}
catch (Exception err)
{
logger.LogError(err, "Exception in native log forwarder.");
}
if (message == null)
{
// try to at least print the unreplaced message pattern
message = Marshal.PtrToStringAnsi(format);
}
if (message != null)
{
logger.Log(level, $"Native: {message}");
}
}
#if SENTRY_NATIVE_PLAYSTATION || SENTRY_NATIVE_SWITCH
[DllImport("__Internal", EntryPoint = "vsnprintf_sentry")]
private static extern int vsnprintf_sentry(IntPtr buffer, UIntPtr bufferSize, IntPtr format, IntPtr args);
#else
// For Windows/Linux: use platform's native C library directly
[DllImport("msvcrt", EntryPoint = "vsnprintf")]
private static extern int vsnprintf_windows(IntPtr buffer, UIntPtr bufferSize, IntPtr format, IntPtr args);
[DllImport("libc", EntryPoint = "vsnprintf")]
private static extern int vsnprintf_linux(IntPtr buffer, UIntPtr bufferSize, IntPtr format, IntPtr args);
#endif
private static int vsnprintf(IntPtr buffer, UIntPtr bufferSize, IntPtr format, IntPtr args)
{
#if SENTRY_NATIVE_PLAYSTATION || SENTRY_NATIVE_SWITCH
return vsnprintf_sentry(buffer, bufferSize, format, args);
#else
return IsWindows
? vsnprintf_windows(buffer, bufferSize, format, args)
: vsnprintf_linux(buffer, bufferSize, format, args);
#endif
}
// https://stackoverflow.com/a/4958507/2386130
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct VaListLinux64
{
uint gp_offset;
uint fp_offset;
IntPtr overflow_arg_area;
IntPtr reg_save_area;
}
private static void WithAllocatedPtr(int size, Action<IntPtr> action)
{
var ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocHGlobal(size);
action(ptr);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
private static void WithMarshalledStruct<T>(T structure, Action<IntPtr> action) where T : notnull =>
WithAllocatedPtr(Marshal.SizeOf(structure), ptr =>
{
Marshal.StructureToPtr(structure, ptr, false);
action(ptr);
});
[DllImport(SentryLib)]
private static extern int sentry_init(IntPtr options);
[DllImport(SentryLib)]
private static extern int sentry_close();
[DllImport(SentryLib)]
private static extern int sentry_get_crashed_last_run();
[DllImport(SentryLib)]
private static extern int sentry_clear_crashed_last_run();
[DllImport(SentryLib)]
private static extern void sentry_reinstall_backend();
}