-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
Program.cs
456 lines (387 loc) · 15.9 KB
/
Program.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace ObjectiveCMarshalAPI
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ObjectiveC;
using System.Threading;
using Xunit;
class NativeObjCMarshalTests
{
[DllImport(nameof(NativeObjCMarshalTests))]
public static extern unsafe void GetExports(
out delegate* unmanaged<void> beginEndCallback,
out delegate* unmanaged<IntPtr, int> isReferencedCallback,
out delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization);
[DllImport(nameof(NativeObjCMarshalTests))]
public static extern unsafe void SetImports(
delegate* unmanaged<void> beforeThrowNativeExceptionCallback);
[DllImport(nameof(NativeObjCMarshalTests))]
public static extern int CallAndCatch(IntPtr fptr, int a);
[DllImport(nameof(NativeObjCMarshalTests))]
public static extern IntPtr GetThrowInt();
[DllImport(nameof(NativeObjCMarshalTests))]
public static extern IntPtr GetThrowException();
}
unsafe class Program
{
static void Validate_ReferenceTrackingAPIs_InvalidArgs()
{
Console.WriteLine($"Running {nameof(Validate_ReferenceTrackingAPIs_InvalidArgs)}...");
delegate* unmanaged<void> beginEndCallback;
delegate* unmanaged<IntPtr, int> isReferencedCallback;
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization;
NativeObjCMarshalTests.GetExports(out beginEndCallback, out isReferencedCallback, out trackedObjectEnteredFinalization);
Assert.Throws<ArgumentNullException>(
() =>
{
ObjectiveCMarshal.Initialize(null, isReferencedCallback, trackedObjectEnteredFinalization, OnUnhandledExceptionPropagationHandler);
});
Assert.Throws<ArgumentNullException>(
() =>
{
ObjectiveCMarshal.Initialize(beginEndCallback, null, trackedObjectEnteredFinalization, OnUnhandledExceptionPropagationHandler);
});
Assert.Throws<ArgumentNullException>(
() =>
{
ObjectiveCMarshal.Initialize(beginEndCallback, isReferencedCallback, null, OnUnhandledExceptionPropagationHandler);
});
Assert.Throws<ArgumentNullException>(
() =>
{
ObjectiveCMarshal.Initialize(beginEndCallback, isReferencedCallback, trackedObjectEnteredFinalization, null);
});
Assert.Throws<ArgumentNullException>(
() =>
{
ObjectiveCMarshal.CreateReferenceTrackingHandle(null , out _);
});
}
// The expectation here is during reference tracking handle creation
// the RefCountDown will be set to some non-negative number and RefCountUp
// will remain zero. The values will be incremented and decremented respectively
// during the "is referenced" callback. When the object enters the finalizer queue
// the RefCountDown will then be set to nuint.MaxValue, see the EnteredFinalizerCb
// callback. In the object's finalizer the RefCountUp can be checked to ensure
// the count down value was respected.
struct Contract
{
public nuint RefCountDown;
public nuint RefCountUp;
};
[ObjectiveCTrackedTypeAttribute]
class Base
{
public static int AllocCount = 0;
public static int FinalizeCount = 0;
private nuint _expectedCount = 0;
private Contract* _contract;
public Base()
{
AllocCount++;
}
~Base()
{
if (_contract != null)
{
Assert.Equal(nuint.MaxValue, _contract->RefCountDown); // Validate finalizer queue callback
Assert.Equal(_expectedCount, _contract->RefCountUp); // Validate "is referenced" callback
}
FinalizeCount++;
}
public IntPtr Contract { get => (IntPtr)_contract; }
public void SetContractMemory(IntPtr mem, uint count)
{
_contract = (Contract*)mem;
// Contract should be 0 initialized when supplied.
Assert.Equal((nuint)0, _contract->RefCountDown);
Assert.Equal((nuint)0, _contract->RefCountUp);
_expectedCount = (nuint)count;
_contract->RefCountDown = _expectedCount;
}
}
class Derived : Base { }
class DerivedWithFinalizer : Base
{
~DerivedWithFinalizer() { }
}
[ObjectiveCTrackedTypeAttribute]
class AttributedNoFinalizer { }
class HasNoHashCode : Base
{
}
class HasHashCode : Base
{
public HasHashCode()
{
// this will write a hash code into the object header.
RuntimeHelpers.GetHashCode(this);
}
}
class HasThinLockHeld : Base
{
public HasThinLockHeld()
{
// This will write lock information into the object header.
// An attempt to generate a hash code for this object will cause the lock to be
// upgrade to a thick lock.
Monitor.Enter(this);
}
}
class HasSyncBlock : Base
{
public HasSyncBlock()
{
RuntimeHelpers.GetHashCode(this);
Monitor.Enter(this);
}
}
static void InitializeObjectiveCMarshal()
{
delegate* unmanaged<void> beginEndCallback;
delegate* unmanaged<IntPtr, int> isReferencedCallback;
delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization;
NativeObjCMarshalTests.GetExports(out beginEndCallback, out isReferencedCallback, out trackedObjectEnteredFinalization);
delegate* unmanaged<void> beforeThrow = &BeforeThrowNativeException;
NativeObjCMarshalTests.SetImports(beforeThrow);
ObjectiveCMarshal.Initialize(beginEndCallback, isReferencedCallback, trackedObjectEnteredFinalization, OnUnhandledExceptionPropagationHandler);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static GCHandle AllocAndTrackObject<T>(uint count) where T : Base, new()
{
var obj = new T();
GCHandle h = ObjectiveCMarshal.CreateReferenceTrackingHandle(obj, out Span<IntPtr> s);
// Validate contract length for tagged memory.
Assert.Equal(2, s.Length);
// Make the "is referenced" callback run at least 'count' number of times.
fixed (void* p = s)
obj.SetContractMemory((IntPtr)p, count);
return h;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void Validate_AllocAndFreeAnotherHandle<T>(GCHandle handle) where T : Base, new()
{
var obj = (T)handle.Target;
GCHandle h = ObjectiveCMarshal.CreateReferenceTrackingHandle(obj, out Span<IntPtr> s);
// Validate the memory is the same but the GCHandles are distinct.
fixed (void* p = s)
Assert.Equal(obj.Contract, new IntPtr(p));
Assert.NotEqual(handle, h);
h.Free();
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void AllocUntrackedObject<T>() where T : Base, new()
{
new T();
}
static unsafe void Validate_ReferenceTracking_Scenario()
{
Console.WriteLine($"Running {nameof(Validate_ReferenceTracking_Scenario)}...");
var handles = new List<GCHandle>();
// Attempting to create handle prior to initialization.
Assert.Throws<InvalidOperationException>(
() =>
{
ObjectiveCMarshal.CreateReferenceTrackingHandle(new Base(), out _);
});
InitializeObjectiveCMarshal();
// Type attributed but no finalizer.
Assert.Throws<InvalidOperationException>(
() =>
{
ObjectiveCMarshal.CreateReferenceTrackingHandle(new AttributedNoFinalizer(), out _);
});
// Ensure objects who have no tagged memory allocated are handled when they enter the
// finalization queue. The NativeAOT implementation looks up objects in a hash table,
// so we exercise the various ways a hash code can be stored.
AllocUntrackedObject<HasNoHashCode>();
AllocUntrackedObject<HasHashCode>();
AllocUntrackedObject<HasThinLockHeld>();
AllocUntrackedObject<HasSyncBlock>();
// Provide the minimum number of times the reference callback should run.
// See IsRefCb() in NativeObjCMarshalTests.cpp for usage logic.
const uint callbackCount = 3;
{
GCHandle h = AllocAndTrackObject<Base>(callbackCount);
handles.Add(h);
Validate_AllocAndFreeAnotherHandle<Base>(h);
}
{
GCHandle h = AllocAndTrackObject<Derived>(callbackCount);
handles.Add(h);
Validate_AllocAndFreeAnotherHandle<Derived>(h);
}
{
GCHandle h = AllocAndTrackObject<DerivedWithFinalizer>(callbackCount);
handles.Add(h);
Validate_AllocAndFreeAnotherHandle<DerivedWithFinalizer>(h);
}
// Trigger the GC
for (int i = 0; i < (callbackCount + 2); ++i)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
// Validate we finalized all the objects we allocated.
// It is important to validate the count prior to freeing
// the handles to verify they are not keeping objects alive.
Assert.Equal(Base.FinalizeCount, Base.AllocCount);
// Clean up all allocated handles that are no longer needed.
foreach (var h in handles)
{
h.Free();
}
// Validate the exception propagation logic.
_Validate_ExceptionPropagation();
}
[UnmanagedCallersOnly]
private static void BeforeThrowNativeException()
{
// This function is called from the exception propagation callback.
// It ensures that the thread was transitioned to preemptive mode.
GC.Collect();
}
private class IntException : Exception
{
public int Value { get; }
public IntException(int value) { this.Value = value; }
}
private class ExceptionException : Exception
{
public ExceptionException() {}
}
static bool s_finallyExecuted;
[UnmanagedCallersOnly]
static void UCO_ThrowIntException(int a)
{
try
{
throw new IntException(a);
}
finally
{
s_finallyExecuted = true;
}
}
[UnmanagedCallersOnly]
static void UCO_ThrowExceptionException(int _)
{
try
{
throw new ExceptionException();
}
finally
{
s_finallyExecuted = true;
}
}
delegate void ThrowExceptionDelegate(int a);
static void DEL_ThrowIntException(int a)
{
try
{
throw new IntException(a);
}
finally
{
s_finallyExecuted = true;
}
}
static void DEL_ThrowExceptionException(int _)
{
try
{
throw new ExceptionException();
}
finally
{
s_finallyExecuted = true;
}
}
static unsafe delegate* unmanaged<IntPtr, void> OnUnhandledExceptionPropagationHandler(
Exception e,
RuntimeMethodHandle lastMethodHandle,
out IntPtr context)
{
// Not yet implemented For NativeAOT.
// https://github.com/dotnet/runtime/issues/80985
if (!TestLibrary.Utilities.IsNativeAot)
{
var lastMethod = (MethodInfo)MethodBase.GetMethodFromHandle(lastMethodHandle);
Assert.True(lastMethod != null);
}
context = IntPtr.Zero;
if (e is IntException ie)
{
context = new IntPtr(ie.Value);
return (delegate* unmanaged<IntPtr, void>)NativeObjCMarshalTests.GetThrowInt();
}
else if (e is ExceptionException)
{
return (delegate* unmanaged<IntPtr, void>)NativeObjCMarshalTests.GetThrowException();
}
Assert.True(false, "Unknown exception type");
throw new UnreachableException();
}
class Scenario
{
public Scenario(delegate* unmanaged<int, void> fptr, int expected) { Fptr = fptr; Expected = expected; }
public delegate* unmanaged<int, void> Fptr;
public int Expected;
}
// Do not call this method from Main as it depends on a previous test for set up.
static void _Validate_ExceptionPropagation()
{
Console.WriteLine($"Running {nameof(_Validate_ExceptionPropagation)}");
var delThrowInt = new ThrowExceptionDelegate(DEL_ThrowIntException);
var delThrowException = new ThrowExceptionDelegate(DEL_ThrowExceptionException);
var scenarios = new[]
{
new Scenario((delegate* unmanaged<int, void>)&UCO_ThrowIntException, 3423),
new Scenario((delegate* unmanaged<int, void>)&UCO_ThrowExceptionException, 5432),
new Scenario((delegate* unmanaged<int, void>)Marshal.GetFunctionPointerForDelegate(delThrowInt), 6453),
new Scenario((delegate* unmanaged<int, void>)Marshal.GetFunctionPointerForDelegate(delThrowException), 5343)
};
foreach (var scen in scenarios)
{
s_finallyExecuted = false;
delegate* unmanaged<int, void> testNativeMethod = scen.Fptr;
int ret = NativeObjCMarshalTests.CallAndCatch((IntPtr)testNativeMethod, scen.Expected);
Assert.Equal(scen.Expected, ret);
Assert.True(s_finallyExecuted, "Finally block not executed.");
}
GC.KeepAlive(delThrowInt);
GC.KeepAlive(delThrowException);
}
static void Validate_Initialize_FailsOnSecondAttempt()
{
Console.WriteLine($"Running {nameof(Validate_Initialize_FailsOnSecondAttempt)}...");
Assert.Throws<InvalidOperationException>(
() =>
{
InitializeObjectiveCMarshal();
});
}
static int Main()
{
try
{
Validate_ReferenceTrackingAPIs_InvalidArgs();
Validate_ReferenceTracking_Scenario();
Validate_Initialize_FailsOnSecondAttempt();
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
return 100;
}
}
}