-
-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathCFunctions.cs
More file actions
588 lines (493 loc) · 21.5 KB
/
CFunctions.cs
File metadata and controls
588 lines (493 loc) · 21.5 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
using Sentry.Protocol;
namespace Sentry.Native;
/// <summary>
/// P/Invoke to `sentry-native` functions.
/// </summary>
/// <see href="https://github.com/getsentry/sentry-native"/>
internal static class C
{
internal static void SetValueIfNotNull(sentry_value_t obj, string key, string? value)
{
if (value is not null)
{
_ = sentry_value_set_by_key(obj, key, sentry_value_new_string(value));
}
}
internal static void SetValueIfNotNull(sentry_value_t obj, string key, int? value)
{
if (value.HasValue)
{
_ = sentry_value_set_by_key(obj, key, sentry_value_new_int32(value.Value));
}
}
internal static void SetValueIfNotNull(sentry_value_t obj, string key, bool? value)
{
if (value.HasValue)
{
_ = sentry_value_set_by_key(obj, key, sentry_value_new_bool(value.Value ? 1 : 0));
}
}
internal static void SetValueIfNotNull(sentry_value_t obj, string key, double? value)
{
if (value.HasValue)
{
_ = sentry_value_set_by_key(obj, key, sentry_value_new_double(value.Value));
}
}
internal static sentry_value_t? GetValueOrNul(sentry_value_t obj, string key)
{
var cValue = sentry_value_get_by_key(obj, key);
return sentry_value_is_null(cValue) == 0 ? cValue : null;
}
internal static string? GetValueString(sentry_value_t obj, string key)
{
if (GetValueOrNul(obj, key) is { } cValue)
{
var cString = sentry_value_as_string(cValue);
if (cString != IntPtr.Zero)
{
return Marshal.PtrToStringAnsi(cString);
}
}
return null;
}
internal static int? GetValueInt(sentry_value_t obj, string key)
{
if (GetValueOrNul(obj, key) is { } cValue)
{
return sentry_value_as_int32(cValue);
}
return null;
}
internal static double? GetValueDouble(sentry_value_t obj, string key)
{
if (GetValueOrNul(obj, key) is { } cValue)
{
return sentry_value_as_double(cValue);
}
return null;
}
public static bool Init(SentryOptions options)
{
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)
{
options.DiagnosticLogger?.LogDebug("Setting Release: {0}", options.Release);
sentry_options_set_release(cOptions, options.Release);
}
if (options.Environment is not null)
{
options.DiagnosticLogger?.LogDebug("Setting Environment: {0}", options.Environment);
sentry_options_set_environment(cOptions, options.Environment);
}
options.DiagnosticLogger?.LogDebug("Setting Debug: {0}", options.Debug);
sentry_options_set_debug(cOptions, options.Debug ? 1 : 0);
if (options.SampleRate.HasValue)
{
options.DiagnosticLogger?.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
options.DiagnosticLogger?.LogDebug("Disabling native auto session tracking");
sentry_options_set_auto_session_tracking(cOptions, 0);
var dir = GetCacheDirectory(options);
if (System.OperatingSystem.IsWindows())
{
options.DiagnosticLogger?.LogDebug("Setting native CacheDirectoryPath on Windows: {0}", dir);
sentry_options_set_database_pathw(cOptions, dir);
}
else
{
options.DiagnosticLogger?.LogDebug("Setting native CacheDirectoryPath: {0}", dir);
sentry_options_set_database_path(cOptions, dir);
}
if (options.DiagnosticLogger is null)
{
_logger?.LogDebug("Unsetting the current native logger");
_logger = null;
}
else
{
options.DiagnosticLogger.LogDebug($"{(_logger is null ? "Setting a" : "Replacing the")} native logger");
_logger = options.DiagnosticLogger;
unsafe
{
sentry_options_set_logger(cOptions, &nativeLog, IntPtr.Zero);
}
}
unsafe
{
var cTransport = sentry_transport_new(&nativeTransport);
sentry_transport_set_state(cTransport, GCHandle.ToIntPtr(GCHandle.Alloc(options)));
sentry_transport_set_free_func(cTransport, &nativeTransportFree);
sentry_options_set_transport(cOptions, cTransport);
}
options.DiagnosticLogger?.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(SentryOptions options)
{
var result = sentry_get_crashed_last_run() == 1;
sentry_clear_crashed_last_run();
return result;
}
internal static string GetCacheDirectory(SentryOptions options)
{
if (options.CacheDirectoryPath is null)
{
// Allow direct file system usage - Not application for Nintendo Switch
#pragma warning disable SN0001
// same as the default of sentry-native
return Path.Combine(Directory.GetCurrentDirectory(), ".sentry-native");
#pragma warning restore SN0001
}
else
{
return Path.Combine(options.CacheDirectoryPath, "SentryNative");
}
}
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_new_object();
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_new_null();
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_new_bool(int value);
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_new_double(double value);
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_new_int32(int value);
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_new_string(string value);
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_new_breadcrumb(string? type, string? message);
[DllImport("sentry-native")]
internal static extern int sentry_value_set_by_key(sentry_value_t value, string k, sentry_value_t v);
internal static bool IsNull(sentry_value_t value) => sentry_value_is_null(value) != 0;
[DllImport("sentry-native")]
internal static extern int sentry_value_is_null(sentry_value_t value);
[DllImport("sentry-native")]
internal static extern int sentry_value_as_int32(sentry_value_t value);
[DllImport("sentry-native")]
internal static extern double sentry_value_as_double(sentry_value_t value);
[DllImport("sentry-native")]
internal static extern IntPtr sentry_value_as_string(sentry_value_t value);
[DllImport("sentry-native")]
internal static extern UIntPtr sentry_value_get_length(sentry_value_t value);
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_get_by_index(sentry_value_t value, UIntPtr index);
[DllImport("sentry-native")]
internal static extern sentry_value_t sentry_value_get_by_key(sentry_value_t value, string key);
[DllImport("sentry-native")]
internal static extern void sentry_set_context(string key, sentry_value_t value);
[DllImport("sentry-native")]
internal static extern void sentry_add_breadcrumb(sentry_value_t breadcrumb);
[DllImport("sentry-native")]
internal static extern void sentry_set_tag(string key, string value);
[DllImport("sentry-native")]
internal static extern void sentry_remove_tag(string key);
[DllImport("sentry-native")]
internal static extern void sentry_set_user(sentry_value_t user);
[DllImport("sentry-native")]
internal static extern void sentry_remove_user();
[DllImport("sentry-native")]
internal static extern void sentry_set_extra(string key, sentry_value_t value);
[DllImport("sentry-native")]
internal static extern void sentry_remove_extra(string key);
[DllImport("sentry-native")]
internal static extern void sentry_set_trace(string traceId, string parentSpanId);
internal static Dictionary<long, DebugImage> LoadDebugImages(IDiagnosticLogger? logger)
{
// It only makes sense to load them once because they're cached on the native side anyway. We could force
// native to reload the list by calling sentry_clear_modulecache() when a dynamic library is loaded, but
// there's currently no way for us to know when that should happen.
DebugImages ??= LoadDebugImagesOnce(logger);
return DebugImages;
}
private static Dictionary<long, DebugImage>? DebugImages;
private static Dictionary<long, DebugImage> LoadDebugImagesOnce(IDiagnosticLogger? logger)
{
logger?.LogDebug("Collecting a list of native debug images.");
var result = new Dictionary<long, DebugImage>();
try
{
var cList = sentry_get_modules_list();
try
{
if (!IsNull(cList))
{
var len = sentry_value_get_length(cList).ToUInt32();
logger?.LogDebug("There are {0} native debug images, parsing the information.", len);
for (uint i = 0; i < len; i++)
{
var cItem = sentry_value_get_by_index(cList, (UIntPtr)i);
if (!IsNull(cItem))
{
// See possible values present in `cItem` in the following files (or their latest versions)
// * https://github.com/getsentry/sentry-native/blob/8faa78298da68d68043f0c3bd694f756c0e95dfa/src/modulefinder/sentry_modulefinder_windows.c#L81
// * https://github.com/getsentry/sentry-native/blob/8faa78298da68d68043f0c3bd694f756c0e95dfa/src/modulefinder/sentry_modulefinder_windows.c#L24
// * https://github.com/getsentry/sentry-native/blob/c5c31e56d36bed37fa5422750a591f44502edb41/src/modulefinder/sentry_modulefinder_linux.c#L465
if (GetValueString(cItem, "image_addr") is { } imageAddr && imageAddr.Length > 0)
{
var imageAddress = imageAddr.ParseHexAsLong();
result.Add(imageAddress, new DebugImage()
{
CodeFile = GetValueString(cItem, "code_file"),
ImageAddress = imageAddress,
ImageSize = GetValueInt(cItem, "image_size"),
DebugFile = GetValueString(cItem, "debug_file"),
DebugId = GetValueString(cItem, "debug_id"),
CodeId = GetValueString(cItem, "code_id"),
Type = GetValueString(cItem, "type"),
});
}
}
}
}
}
finally
{
sentry_value_decref(cList);
}
}
catch (Exception e)
{
logger?.LogWarning(e, "Error loading the list of debug images");
}
return result;
}
// Returns a new reference to an immutable, frozen list.
// The reference must be released with `sentry_value_decref`.
[DllImport("sentry-native")]
private static extern sentry_value_t sentry_get_modules_list();
[DllImport("sentry-native")]
internal static extern void sentry_value_decref(sentry_value_t value);
// native union sentry_value_u/t
[StructLayout(LayoutKind.Explicit)]
internal struct sentry_value_t
{
[FieldOffset(0)]
internal ulong _bits;
[FieldOffset(0)]
internal double _double;
}
[DllImport("sentry-native")]
private static extern int sentry_init(IntPtr options);
[DllImport("sentry-native")]
private static extern int sentry_close();
[DllImport("sentry-native")]
private static extern int sentry_get_crashed_last_run();
[DllImport("sentry-native")]
private static extern int sentry_clear_crashed_last_run();
[DllImport("sentry-native")]
private static extern IntPtr sentry_options_new();
[DllImport("sentry-native")]
private static extern void sentry_options_set_dsn(IntPtr options, string dsn);
[DllImport("sentry-native")]
private static extern void sentry_options_set_release(IntPtr options, string release);
[DllImport("sentry-native")]
private static extern void sentry_options_set_debug(IntPtr options, int debug);
[DllImport("sentry-native")]
private static extern void sentry_options_set_environment(IntPtr options, string environment);
[DllImport("sentry-native")]
private static extern void sentry_options_set_sample_rate(IntPtr options, double rate);
[DllImport("sentry-native")]
private static extern void sentry_options_set_database_path(IntPtr options, string path);
[DllImport("sentry-native")]
private static extern void sentry_options_set_database_pathw(IntPtr options, [MarshalAs(UnmanagedType.LPWStr)] string path);
[DllImport("sentry-native")]
private static extern void sentry_options_set_auto_session_tracking(IntPtr options, int debug);
[DllImport("sentry-native")]
private static extern void sentry_options_set_transport(IntPtr options, IntPtr transport);
[DllImport("sentry-native")]
private static extern unsafe IntPtr sentry_transport_new(delegate* unmanaged<IntPtr, IntPtr, void> sendFunc);
[DllImport("sentry-native")]
private static extern void sentry_transport_set_state(IntPtr transport, IntPtr state);
[DllImport("sentry-native")]
private static extern unsafe void sentry_transport_set_free_func(IntPtr transport, delegate* unmanaged<IntPtr, void> freeFunc);
[DllImport("sentry-native")]
private static extern IntPtr sentry_envelope_serialize(IntPtr envelope, out UIntPtr sizeOut);
[DllImport("sentry-native")]
private static extern void sentry_envelope_free(IntPtr envelope);
[DllImport("sentry-native")]
internal static extern void sentry_free(IntPtr ptr);
[UnmanagedCallersOnly]
private static void nativeTransport(IntPtr envelope, IntPtr state)
{
var options = GCHandle.FromIntPtr(state).Target as SentryOptions;
try
{
if (options is not null)
{
var data = sentry_envelope_serialize(envelope, out var size);
using var content = new UnmanagedHttpContent(data, (int)size, options.DiagnosticLogger);
using var client = options.GetHttpClient();
using var request = options.CreateHttpRequest(content);
#if NET5_0_OR_GREATER
var response = client.Send(request);
#else
var response = client.SendAsync(request).GetAwaiter().GetResult();
#endif
response.EnsureSuccessStatusCode();
}
}
catch (HttpRequestException e)
{
options?.DiagnosticLogger?.LogError(e, "Failed to send native envelope.");
}
catch (Exception e)
{
// never allow an exception back to native code - it would crash the app
options?.DiagnosticLogger?.LogError(e, "Exception in native transport callback. The native envelope will not be sent.");
}
finally
{
sentry_envelope_free(envelope);
}
}
[UnmanagedCallersOnly]
private static void nativeTransportFree(IntPtr state)
{
var handle = GCHandle.FromIntPtr(state);
handle.Free();
}
[DllImport("sentry-native")]
private static extern unsafe void sentry_options_set_logger(IntPtr options, delegate* unmanaged/*[Cdecl]*/<int, IntPtr, IntPtr, IntPtr, void> logger, IntPtr userData);
// The logger we should forward native messages to. This is referenced by nativeLog() which in turn for.
private static IDiagnosticLogger? _logger;
private static bool _isWindows = System.OperatingSystem.IsWindows();
private static bool _isArm64 = RuntimeInformation.OSArchitecture == Architecture.Arm64;
// This method is called from the C library and forwards incoming messages to the currently set _logger.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] // error CS3016: Arrays as attribute arguments is not CLS-complian
[UnmanagedCallersOnly]
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.
if (_isWindows)
{
var formattedLength = 1 + vsnprintf_windows(IntPtr.Zero, UIntPtr.Zero, format, args);
WithAllocatedPtr(formattedLength, buffer =>
{
vsnprintf_windows(buffer, (UIntPtr)formattedLength, format, args);
message = Marshal.PtrToStringAnsi(buffer);
});
}
// For Linux/macOS, we must make a copy of the VaList to be able to pass it back...
else if (_isArm64)
{
message = FormatWithVaList<VaListArm64>(format, args);
}
else
{
message = FormatWithVaList<VaListX64>(format, args);
}
}
catch (Exception err)
{
logger.LogError(err, "Exception in native log forwarder.");
}
// If previous failed, try to at least print the unreplaced message pattern
message ??= Marshal.PtrToStringAnsi(format);
if (message != null)
{
logger.Log(level, $"[native] {message}");
}
}
[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);
// https://stackoverflow.com/a/4958507/2386130
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct VaListX64
{
private uint _gp_offset;
private uint _fp_offset;
private IntPtr _overflow_arg_area;
private IntPtr _reg_save_area;
}
// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#definition-of-va-list
[StructLayout(LayoutKind.Sequential)]
private struct VaListArm64
{
private IntPtr __stack;
private IntPtr __gr_top;
private IntPtr __vr_top;
private int __gr_offs;
private int __vr_offs;
}
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);
});
private static string? FormatWithVaList<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(IntPtr format, IntPtr args) where T : struct
{
string? message = null;
var argsStruct = Marshal.PtrToStructure<T>(args);
var formattedLength = 0;
WithMarshalledStruct(argsStruct, argsPtr =>
formattedLength = 1 + vsnprintf_linux(IntPtr.Zero, UIntPtr.Zero, format, argsPtr)
);
WithAllocatedPtr(formattedLength, buffer =>
WithMarshalledStruct(argsStruct, argsPtr =>
{
vsnprintf_linux(buffer, (UIntPtr)formattedLength, format, argsPtr);
message = Marshal.PtrToStringAnsi(buffer);
}));
return message;
}
}