-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathGCTests.cs
More file actions
1291 lines (1094 loc) · 48.4 KB
/
Copy pathGCTests.cs
File metadata and controls
1291 lines (1094 loc) · 48.4 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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Tests
{
public static class GCTests
{
private static bool s_is32Bits = IntPtr.Size == 4; // Skip IntPtr tests on 32-bit platforms
[Fact]
public static void AddMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[Fact]
public static void Collect_Int()
{
for (int i = 0; i < GC.MaxGeneration + 10; i++)
{
GC.Collect(i);
}
// Also, expect GC.Collect(int.MaxValue) to work without exception since int.MaxValue represents
// a nongc heap generation (that is exactly what GC.GetGeneration returns for a non-gc heap object)
GC.Collect(int.MaxValue);
}
[Fact]
public static void Collect_Int_NegativeGeneration_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1)); // Generation < 0
}
[Theory]
[InlineData(GCCollectionMode.Default)]
[InlineData(GCCollectionMode.Forced)]
public static void Collect_Int_GCCollectionMode(GCCollectionMode mode)
{
for (int gen = 0; gen <= 2; gen++)
{
var b = new byte[1024 * 1024 * 10];
int oldCollectionCount = GC.CollectionCount(gen);
b = null;
GC.Collect(gen, mode);
Assert.True(GC.CollectionCount(gen) > oldCollectionCount);
}
}
[Fact]
public static void Collect_NegativeGenerationCount_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default, false));
}
[Theory]
[InlineData(GCCollectionMode.Default - 1)]
[InlineData(GCCollectionMode.Aggressive + 1)]
public static void Collection_InvalidCollectionMode_ThrowsArgumentOutOfRangeException(GCCollectionMode mode)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", null, () => GC.Collect(2, mode));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", null, () => GC.Collect(2, mode, false));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void Collect_CallsFinalizer()
{
FinalizerTest.Run();
}
private class FinalizerTest
{
[MethodImpl(MethodImplOptions.NoInlining)]
private static void MakeAndDropTest()
{
new TestObject();
}
public static void Run()
{
MakeAndDropTest();
GC.Collect();
// Make sure Finalize() is called
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void ExpensiveFinalizerDoesNotBlockShutdown()
{
RemoteExecutor.Invoke(() =>
{
for (int i = 0; i < 100000; i++)
GC.KeepAlive(new ObjectWithExpensiveFinalizer());
GC.Collect();
Thread.Sleep(100); // Give the finalizer thread a chance to start running
}).Dispose();
}
private class ObjectWithExpensiveFinalizer
{
~ObjectWithExpensiveFinalizer()
{
Thread.Sleep(100);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void KeepAlive()
{
KeepAliveTest.Run();
}
private class KeepAliveTest
{
[MethodImpl(MethodImplOptions.NoInlining)]
private static void MakeAndDropDNKA()
{
new DoNotKeepAliveObject();
}
public static void Run()
{
var keepAlive = new KeepAliveObject();
MakeAndDropDNKA();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(DoNotKeepAliveObject.Finalized);
Assert.False(KeepAliveObject.Finalized);
GC.KeepAlive(keepAlive);
}
private class KeepAliveObject
{
public static bool Finalized { get; private set; }
~KeepAliveObject()
{
Finalized = true;
}
}
private class DoNotKeepAliveObject
{
public static bool Finalized { get; private set; }
~DoNotKeepAliveObject()
{
Finalized = true;
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void KeepAlive_Null()
{
KeepAliveNullTest.Run();
}
private class KeepAliveNullTest
{
[MethodImpl(MethodImplOptions.NoInlining)]
private static void MakeAndNull()
{
var obj = new TestObject();
obj = null;
}
public static void Run()
{
MakeAndNull();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive_Recursive()
{
KeepAliveRecursiveTest.Run();
}
private class KeepAliveRecursiveTest
{
public static void Run()
{
int recursionCount = 0;
RunWorker(new TestObject(), ref recursionCount);
}
private static void RunWorker(object obj, ref int recursionCount)
{
if (recursionCount++ == 10)
return;
GC.Collect();
GC.WaitForPendingFinalizers();
RunWorker(obj, ref recursionCount);
Assert.False(TestObject.Finalized);
GC.KeepAlive(obj);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void SuppressFinalizer()
{
SuppressFinalizerTest.Run();
}
private class SuppressFinalizerTest
{
public static void Run()
{
var obj = new TestObject();
GC.SuppressFinalize(obj);
obj = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[OuterLoop]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported), nameof(PlatformDetection.IsMultithreadingSupported))] // Races finalization across threads; meaningless on single-threaded platforms.
public static void WaitForPendingFinalizersRaces()
{
Task.Run(Test);
Task.Run(Test);
Task.Run(Test);
Task.Run(Test);
Task.Run(Test);
Task.Run(Test);
Test();
static void Test()
{
for (int i = 0; i < 20000; i++)
{
BoxedFinalized flag = new BoxedFinalized();
MakeAndNull(flag);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(flag.finalized);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void MakeAndNull(BoxedFinalized flag)
{
var deadObj = new TestObjectWithFinalizer(flag);
// it's dead here
};
}
class BoxedFinalized
{
public bool finalized;
}
class TestObjectWithFinalizer
{
BoxedFinalized _flag;
public TestObjectWithFinalizer(BoxedFinalized flag)
{
_flag = flag;
}
~TestObjectWithFinalizer() => _flag.finalized = true;
}
[Fact]
public static void SuppressFinalizer_NullObject_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => GC.SuppressFinalize(null)); // Obj is null
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void ReRegisterForFinalize()
{
ReRegisterForFinalizeTest.Run();
}
[Fact]
public static void ReRegisterFoFinalize_NullObject_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => GC.ReRegisterForFinalize(null)); // Obj is null
}
private class ReRegisterForFinalizeTest
{
public static void Run()
{
TestObject.Finalized = false;
CreateObject();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CreateObject()
{
using (var obj = new TestObject())
{
GC.SuppressFinalize(obj);
}
}
private class TestObject : IDisposable
{
public static bool Finalized { get; set; }
~TestObject()
{
Finalized = true;
}
public void Dispose()
{
GC.ReRegisterForFinalize(this);
}
}
}
[Fact]
public static void CollectionCount_NegativeGeneration_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.CollectionCount(-1)); // Generation < 0
}
[Fact]
public static void RemoveMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void GetTotalMemoryTest_ForceCollection()
{
// We don't test GetTotalMemory(false) at all because a collection
// could still occur even if not due to the GetTotalMemory call,
// and as such there's no way to validate the behavior. We also
// don't verify a tighter bound for the result of GetTotalMemory
// because collections could cause significant fluctuations.
GC.Collect();
int gen0 = GC.CollectionCount(0);
int gen1 = GC.CollectionCount(1);
int gen2 = GC.CollectionCount(2);
Assert.InRange(GC.GetTotalMemory(true), 1, long.MaxValue);
Assert.InRange(GC.CollectionCount(0), gen0 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(1), gen1 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(2), gen2 + 1, int.MaxValue);
}
[Fact]
public static void GetGeneration()
{
// We don't test a tighter bound on GetGeneration as objects
// can actually get demoted or stay in the same generation
// across collections.
GC.Collect();
var obj = new object();
for (int i = 0; i <= GC.MaxGeneration + 1; i++)
{
Assert.InRange(GC.GetGeneration(obj), 0, GC.MaxGeneration);
GC.Collect();
}
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
[InlineData(GCLargeObjectHeapCompactionMode.CompactOnce)]
[InlineData(GCLargeObjectHeapCompactionMode.Default)]
public static void LargeObjectHeapCompactionModeRoundTrips(GCLargeObjectHeapCompactionMode value)
{
GCLargeObjectHeapCompactionMode orig = GCSettings.LargeObjectHeapCompactionMode;
try
{
GCSettings.LargeObjectHeapCompactionMode = value;
Assert.Equal(value, GCSettings.LargeObjectHeapCompactionMode);
}
finally
{
GCSettings.LargeObjectHeapCompactionMode = orig;
Assert.Equal(orig, GCSettings.LargeObjectHeapCompactionMode);
}
}
[Theory]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[InlineData(GCLatencyMode.Batch)]
[InlineData(GCLatencyMode.Interactive)]
// LowLatency does not roundtrip for server GC
// [InlineData(GCLatencyMode.LowLatency)]
// SustainedLowLatency does not roundtrip without background GC
// [InlineData(GCLatencyMode.SustainedLowLatency)]
public static void LatencyRoundtrips(GCLatencyMode value)
{
GCLatencyMode orig = GCSettings.LatencyMode;
try
{
GCSettings.LatencyMode = value;
Assert.Equal(value, GCSettings.LatencyMode);
}
finally
{
GCSettings.LatencyMode = orig;
Assert.Equal(orig, GCSettings.LatencyMode);
}
}
}
public class GCExtendedTests
{
private const int TimeoutMilliseconds = 10 * 30 * 1000; //if full GC is triggered it may take a while
/// <summary>
/// NoGC regions will be automatically exited if more than the requested budget
/// is allocated while still in the region. In order to avoid this, the budget is set
/// to be higher than what the test should be allocating to compensate for allocations
/// made internally by the runtime.
///
/// This budget should be high enough to avoid exiting no-gc regions when doing normal unit
/// tests, regardless of the runtime.
/// </summary>
private const int NoGCRequestedBudget = 8192;
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void GetGeneration_WeakReference()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Func<WeakReference> getweakref = delegate ()
{
Version myobj = new Version();
var wkref = new WeakReference(myobj);
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.True(GC.GetGeneration(wkref) >= 0);
Assert.Equal(GC.GetGeneration(wkref), GC.GetGeneration(myobj));
GC.EndNoGCRegion();
myobj = null;
return wkref;
};
WeakReference weakref = getweakref();
Assert.True(weakref != null);
#if !DEBUG
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
Assert.Throws<ArgumentNullException>(() => GC.GetGeneration(weakref));
#endif
}, options).Dispose();
}
[Fact]
public static void GCNotificationNegTests()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 100));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 10));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, 10));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, 100));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCApproach(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCComplete(-2));
}
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[InlineData(true, -1)]
[InlineData(false, -1)]
[InlineData(true, 0)]
[InlineData(false, 0)]
[InlineData(true, 100)]
[InlineData(false, 100)]
[InlineData(true, int.MaxValue)]
[InlineData(false, int.MaxValue)]
[OuterLoop]
public static void GCNotificationTests(bool approach, int timeout)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke((approachString, timeoutString) =>
{
TestWait(bool.Parse(approachString), int.Parse(timeoutString));
}, approach.ToString(), timeout.ToString(), options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_EndNoGCRegion_ThrowsInvalidOperationException()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
}, options).Dispose();
}
[MethodImpl(MethodImplOptions.NoOptimization)]
private static void AllocateALot()
{
for (int i = 0; i < 10000; i++)
{
var array = new long[NoGCRequestedBudget];
GC.KeepAlive(array);
}
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_ExitThroughAllocation()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(1024));
AllocateALot();
// at this point, the GC should have booted us out of the no GC region
// since we allocated too much.
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_LargeObjectHeapSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollectionAndLOH()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_SettingLatencyMode_ThrowsInvalidOperationException()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
// The budget for this test is 4mb, because the act of throwing an exception with a message
// contained in a System.Private.CoreLib resource file has to potential to allocate a lot.
//
// In addition to this, the Assert.Throws xunit combinator tends to also allocate a lot.
Assert.True(GC.TryStartNoGCRegion(4000 * 1024, true));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
Assert.Throws<InvalidOperationException>(() => GCSettings.LatencyMode = GCLatencyMode.LowLatency);
GC.EndNoGCRegion();
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_LOHSize()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
}, options).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
public static void TryStartNoGCRegion_SOHSize_LOHSize_BlockingCollection()
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
}, options).Dispose();
}
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
[InlineData(0)]
[InlineData(-1)]
public static void TryStartNoGCRegion_TotalSizeOutOfRange(long size)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(sizeString =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("totalSize", () => GC.TryStartNoGCRegion(long.Parse(sizeString)));
}, size.ToString(), options).Dispose();
}
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[OuterLoop]
[InlineData(0)] // invalid because lohSize ==
[InlineData(-1)] // invalid because lohSize < 0
[InlineData(1152921504606846976)] // invalid because lohSize > totalSize
public static void TryStartNoGCRegion_LOHSizeInvalid(long size)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(sizeString =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("lohSize", () => GC.TryStartNoGCRegion(1024, long.Parse(sizeString)));
}, size.ToString(), options).Dispose();
}
private static void TestWait(bool approach, int timeout)
{
GCNotificationStatus result = GCNotificationStatus.Failed;
Thread cancelProc = null;
// Since we need to test an infinite (or very large) wait but the API won't return, spawn off a thread which
// will cancel the wait after a few seconds
//
bool cancelTimeout = (timeout == -1) || (timeout > 10000);
GC.RegisterForFullGCNotification(20, 20);
try
{
if (cancelTimeout)
{
cancelProc = new Thread(new ThreadStart(CancelProc));
cancelProc.Start();
}
if (approach)
result = GC.WaitForFullGCApproach(timeout);
else
result = GC.WaitForFullGCComplete(timeout);
}
catch (Exception e)
{
Assert.Fail($"({approach}, {timeout}) Error - Unexpected exception received: {e.ToString()}");
}
finally
{
if (cancelProc != null)
cancelProc.Join();
}
if (cancelTimeout)
{
Assert.True(result == GCNotificationStatus.Canceled, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Cancelled");
}
else
{
Assert.True(result == GCNotificationStatus.Timeout, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Timeout");
}
}
private static void CancelProc()
{
Thread.Sleep(500);
GC.CancelFullGCNotification();
}
[Theory]
[InlineData(1000)]
[InlineData(100000)]
public static void GetAllocatedBytesForCurrentThread(int size)
{
long start = GC.GetAllocatedBytesForCurrentThread();
GC.KeepAlive(new string('a', size));
long end = GC.GetAllocatedBytesForCurrentThread();
Assert.True((end - start) > size, $"Allocated too little: start: {start} end: {end} size: {size}");
Assert.True((end - start) < 5 * size, $"Allocated too much: start: {start} end: {end} size: {size}");
}
private static bool IsNotArmProcessAndRemoteExecutorSupported => PlatformDetection.IsNotArmProcess && RemoteExecutor.IsSupported;
[ActiveIssue("https://github.com/dotnet/runtime/issues/73167", TestRuntimes.Mono)]
[ConditionalFact(typeof(GCExtendedTests), nameof(IsNotArmProcessAndRemoteExecutorSupported))] // [ActiveIssue("https://github.com/dotnet/runtime/issues/29434")]
public static void GetGCMemoryInfo()
{
RemoteExecutor.Invoke(() =>
{
// Allows to update the value returned by GC.GetGCMemoryInfo
GC.Collect();
GCMemoryInfo memoryInfo1 = GC.GetGCMemoryInfo();
long maxVirtualSpaceSize = (IntPtr.Size == 4) ? uint.MaxValue : long.MaxValue;
Assert.InRange(memoryInfo1.HighMemoryLoadThresholdBytes, 1, maxVirtualSpaceSize);
Assert.InRange(memoryInfo1.MemoryLoadBytes, 1, maxVirtualSpaceSize);
Assert.InRange(memoryInfo1.TotalAvailableMemoryBytes, 1, maxVirtualSpaceSize);
Assert.InRange(memoryInfo1.HeapSizeBytes, 1, maxVirtualSpaceSize);
Assert.InRange(memoryInfo1.FragmentedBytes, 0, maxVirtualSpaceSize);
GCHandle[] gch = new GCHandle[64 * 1024];
for (int i = 0; i < gch.Length * 2; ++i)
{
byte[] arr = new byte[64];
if (i % 2 == 0)
{
gch[i / 2] = GCHandle.Alloc(arr, GCHandleType.Pinned);
}
}
// Allows to update the value returned by GC.GetGCMemoryInfo
GC.Collect();
GCMemoryInfo memoryInfo2 = GC.GetGCMemoryInfo();
string scenario = null;
try
{
scenario = nameof(memoryInfo2.HighMemoryLoadThresholdBytes);
Assert.Equal(memoryInfo2.HighMemoryLoadThresholdBytes, memoryInfo1.HighMemoryLoadThresholdBytes);
// Even though we have allocated, the overall load may decrease or increase depending what other processes are doing.
// It cannot go above total available though.
scenario = nameof(memoryInfo2.MemoryLoadBytes);
Assert.InRange(memoryInfo2.MemoryLoadBytes, 1, memoryInfo1.TotalAvailableMemoryBytes);
scenario = nameof(memoryInfo2.TotalAvailableMemoryBytes);
Assert.Equal(memoryInfo2.TotalAvailableMemoryBytes, memoryInfo1.TotalAvailableMemoryBytes);
scenario = nameof(memoryInfo2.HeapSizeBytes);
Assert.InRange(memoryInfo2.HeapSizeBytes, memoryInfo1.HeapSizeBytes + 1, maxVirtualSpaceSize);
scenario = nameof(memoryInfo2.FragmentedBytes);
Assert.InRange(memoryInfo2.FragmentedBytes, memoryInfo1.FragmentedBytes + 1, maxVirtualSpaceSize);
scenario = null;
}
finally
{
if (scenario != null)
{
System.Console.WriteLine("FAILED: " + scenario);
}
}
}).Dispose();
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/42883", TestRuntimes.Mono)]
public static void GetTotalAllocatedBytes()
{
byte[] stash;
long CallGetTotalAllocatedBytesAndCheck(long previous, out long differenceBetweenPreciseAndImprecise)
{
long precise = GC.GetTotalAllocatedBytes(true);
long imprecise = GC.GetTotalAllocatedBytes(false);
if (precise <= 0)
{
throw new Exception($"Bytes allocated is not positive, this is unlikely. precise = {precise}");
}
if (imprecise < precise)
{
throw new Exception($"Imprecise total bytes allocated less than precise, imprecise is required to be a conservative estimate (that estimates high). imprecise = {imprecise}, precise = {precise}");
}
if (previous > precise)
{
throw new Exception($"Expected more memory to be allocated. previous = {previous}, precise = {precise}, difference = {previous - precise}");
}
differenceBetweenPreciseAndImprecise = imprecise - precise;
return precise;
}
long CallGetTotalAllocatedBytes(long previous)
{
long differenceBetweenPreciseAndImprecise;
previous = CallGetTotalAllocatedBytesAndCheck(previous, out differenceBetweenPreciseAndImprecise);
stash = new byte[differenceBetweenPreciseAndImprecise];
previous = CallGetTotalAllocatedBytesAndCheck(previous, out differenceBetweenPreciseAndImprecise);
return previous;
}
long previous = 0;
for (int i = 0; i < 1000; ++i)
{
stash = new byte[1234];
previous = CallGetTotalAllocatedBytes(previous);
}
}
[Fact]
[OuterLoop]
private static void AllocateUninitializedArray()
{
// allocate a bunch of SOH byte arrays and touch them.
var r = new Random(1234);
for (int i = 0; i < 10000; i++)
{
int size = r.Next(10000);
var arr = GC.AllocateUninitializedArray<byte>(size, pinned: i % 2 == 1);
if (size > 1)
{
arr[0] = 5;
arr[size - 1] = 17;