This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
loaderallocator.cpp
1670 lines (1383 loc) · 50.1 KB
/
loaderallocator.cpp
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.
// See the LICENSE file in the project root for more information.
#include "common.h"
#include "stringliteralmap.h"
#include "virtualcallstub.h"
//*****************************************************************************
// Used by LoaderAllocator::Init for easier readability.
#ifdef ENABLE_PERF_COUNTERS
#define LOADERHEAP_PROFILE_COUNTER (&(GetPerfCounters().m_Loading.cbLoaderHeapSize))
#else
#define LOADERHEAP_PROFILE_COUNTER (NULL)
#endif
#ifndef CROSSGEN_COMPILE
#define STUBMANAGER_RANGELIST(stubManager) (stubManager::g_pManager->GetRangeList())
#else
#define STUBMANAGER_RANGELIST(stubManager) (NULL)
#endif
UINT64 LoaderAllocator::cLoaderAllocatorsCreated = 1;
LoaderAllocator::LoaderAllocator()
{
LIMITED_METHOD_CONTRACT;
// initialize all members up front to NULL so that short-circuit failure won't cause invalid values
m_InitialReservedMemForLoaderHeaps = NULL;
m_pLowFrequencyHeap = NULL;
m_pHighFrequencyHeap = NULL;
m_pStubHeap = NULL;
m_pPrecodeHeap = NULL;
m_pExecutableHeap = NULL;
#ifdef FEATURE_READYTORUN
m_pDynamicHelpersHeap = NULL;
#endif
m_pFuncPtrStubs = NULL;
m_hLoaderAllocatorObjectHandle = NULL;
m_pStringLiteralMap = NULL;
m_cReferences = (UINT32)-1;
m_pDomainAssemblyToDelete = NULL;
#ifdef FAT_DISPATCH_TOKENS
// DispatchTokenFat pointer table for token overflow scenarios. Lazily allocated.
m_pFatTokenSetLock = NULL;
m_pFatTokenSet = NULL;
#endif
#ifndef CROSSGEN_COMPILE
m_pVirtualCallStubManager = NULL;
#endif
m_fGCPressure = false;
m_fTerminated = false;
m_fUnloaded = false;
m_fMarked = false;
m_pLoaderAllocatorDestroyNext = NULL;
m_pDomain = NULL;
m_pCodeHeapInitialAlloc = NULL;
m_pVSDHeapInitialAlloc = NULL;
m_pLastUsedCodeHeap = NULL;
m_pLastUsedDynamicCodeHeap = NULL;
m_pJumpStubCache = NULL;
m_nLoaderAllocator = InterlockedIncrement64((LONGLONG *)&LoaderAllocator::cLoaderAllocatorsCreated);
}
LoaderAllocator::~LoaderAllocator()
{
CONTRACTL
{
DESTRUCTOR_CHECK;
}
CONTRACTL_END;
#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
Terminate();
// Assert that VSD is not still active when the destructor is called.
_ASSERTE(m_pVirtualCallStubManager == NULL);
// Code manager is responsible for cleaning up.
_ASSERTE(m_pJumpStubCache == NULL);
#endif
}
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
void LoaderAllocator::AddReference()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE((m_cReferences > (UINT32)0) && (m_cReferences != (UINT32)-1));
FastInterlockIncrement((LONG *)&m_cReferences);
}
#endif //!DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
// Adds reference if the native object is alive - code:LoaderAllocator#AssemblyPhases.
// Returns TRUE if the reference was added.
//
BOOL LoaderAllocator::AddReferenceIfAlive()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
for (;;)
{
// Local snaphost of ref-count
UINT32 cReferencesLocalSnapshot = m_cReferences;
_ASSERTE(cReferencesLocalSnapshot != (UINT32)-1);
if (cReferencesLocalSnapshot == 0)
{ // Ref-count was 0, do not AddRef
return FALSE;
}
UINT32 cOriginalReferences = FastInterlockCompareExchange(
(LONG *)&m_cReferences,
cReferencesLocalSnapshot + 1,
cReferencesLocalSnapshot);
if (cOriginalReferences == cReferencesLocalSnapshot)
{ // The exchange happened
return TRUE;
}
// Let's spin till we are the only thread to modify this value
}
#else //DACCESS_COMPILE
// DAC won't AddRef
return IsAlive();
#endif //DACCESS_COMPILE
} // LoaderAllocator::AddReferenceIfAlive
//---------------------------------------------------------------------------------------
//
BOOL LoaderAllocator::Release()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Only actually destroy the domain assembly when all references to it are gone.
// This should preserve behavior in the debugger such that an UnloadModule event
// will occur before the underlying data structure cease functioning.
#ifndef DACCESS_COMPILE
_ASSERTE((m_cReferences > (UINT32)0) && (m_cReferences != (UINT32)-1));
LONG cNewReferences = FastInterlockDecrement((LONG *)&m_cReferences);
return (cNewReferences == 0);
#else //DACCESS_COMPILE
return (m_cReferences == (UINT32)0);
#endif //DACCESS_COMPILE
} // LoaderAllocator::Release
#ifndef DACCESS_COMPILE
#ifndef CROSSGEN_COMPILE
//---------------------------------------------------------------------------------------
//
BOOL LoaderAllocator::CheckAddReference_Unlocked(LoaderAllocator *pOtherLA)
{
CONTRACTL
{
THROWS;
SO_INTOLERANT;
MODE_ANY;
}
CONTRACTL_END;
// This must be checked before calling this function
_ASSERTE(pOtherLA != this);
// This function requires the that loader allocator lock have been taken.
_ASSERTE(GetDomain()->GetLoaderAllocatorReferencesLock()->OwnedByCurrentThread());
if (m_LoaderAllocatorReferences.Lookup(pOtherLA) == NULL)
{
GCX_COOP();
// Build a managed reference to keep the target object live
AllocateHandle(pOtherLA->GetExposedObject());
// Keep track of the references that have already been made
m_LoaderAllocatorReferences.Add(pOtherLA);
// Notify the other LoaderAllocator that a reference exists
pOtherLA->AddReference();
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------------------
//
BOOL LoaderAllocator::EnsureReference(LoaderAllocator *pOtherLA)
{
CONTRACTL
{
THROWS;
SO_INTOLERANT;
MODE_ANY;
}
CONTRACTL_END;
// Check if this lock can be taken in all places that the function is called
_ASSERTE(GetDomain()->GetLoaderAllocatorReferencesLock()->Debug_CanTake());
if (!IsCollectible())
return FALSE;
if (this == pOtherLA)
return FALSE;
if (!pOtherLA->IsCollectible())
return FALSE;
CrstHolder ch(GetDomain()->GetLoaderAllocatorReferencesLock());
return CheckAddReference_Unlocked(pOtherLA);
}
BOOL LoaderAllocator::EnsureInstantiation(Module *pDefiningModule, Instantiation inst)
{
CONTRACTL
{
THROWS;
SO_INTOLERANT;
MODE_ANY;
}
CONTRACTL_END;
BOOL fNewReferenceNeeded = FALSE;
// Check if this lock can be taken in all places that the function is called
_ASSERTE(GetDomain()->GetLoaderAllocatorReferencesLock()->Debug_CanTake());
if (!IsCollectible())
return FALSE;
CrstHolder ch(GetDomain()->GetLoaderAllocatorReferencesLock());
if (pDefiningModule != NULL)
{
LoaderAllocator *pDefiningLoaderAllocator = pDefiningModule->GetLoaderAllocator();
if (pDefiningLoaderAllocator->IsCollectible())
{
if (pDefiningLoaderAllocator != this)
{
fNewReferenceNeeded = CheckAddReference_Unlocked(pDefiningLoaderAllocator) || fNewReferenceNeeded;
}
}
}
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle arg = inst[i];
_ASSERTE(!arg.IsEncodedFixup());
LoaderAllocator *pOtherLA = arg.GetLoaderModule()->GetLoaderAllocator();
if (pOtherLA == this)
continue;
if (!pOtherLA->IsCollectible())
continue;
fNewReferenceNeeded = CheckAddReference_Unlocked(pOtherLA) || fNewReferenceNeeded;
}
return fNewReferenceNeeded;
}
#else // CROSSGEN_COMPILE
BOOL LoaderAllocator::EnsureReference(LoaderAllocator *pOtherLA)
{
return FALSE;
}
BOOL LoaderAllocator::EnsureInstantiation(Module *pDefiningModule, Instantiation inst)
{
return FALSE;
}
#endif // !CROSSGEN_COMPILE
#ifndef CROSSGEN_COMPILE
bool LoaderAllocator::Marked()
{
LIMITED_METHOD_CONTRACT;
return m_fMarked;
}
void LoaderAllocator::ClearMark()
{
LIMITED_METHOD_CONTRACT;
m_fMarked = false;
}
void LoaderAllocator::Mark()
{
WRAPPER_NO_CONTRACT;
if (!m_fMarked)
{
m_fMarked = true;
LoaderAllocatorSet::Iterator iter = m_LoaderAllocatorReferences.Begin();
while (iter != m_LoaderAllocatorReferences.End())
{
LoaderAllocator *pAllocator = *iter;
pAllocator->Mark();
iter++;
}
}
}
//---------------------------------------------------------------------------------------
//
// Collect unreferenced assemblies, remove them from the assembly list and return their loader allocator
// list.
//
//static
LoaderAllocator * LoaderAllocator::GCLoaderAllocators_RemoveAssemblies(AppDomain * pAppDomain)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER; // Because we are holding assembly list lock code:BaseDomain#AssemblyListLock
MODE_PREEMPTIVE;
SO_INTOLERANT;
}
CONTRACTL_END;
_ASSERTE(pAppDomain->GetLoaderAllocatorReferencesLock()->OwnedByCurrentThread());
_ASSERTE(pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
// List of LoaderAllocators being deleted
LoaderAllocator * pFirstDestroyedLoaderAllocator = NULL;
#if 0
// Debug logic for debugging the loader allocator gc.
{
/* Iterate through every loader allocator, and print its current state */
AppDomain::AssemblyIterator iData;
iData = pAppDomain->IterateAssembliesEx((AssemblyIterationFlags)(
kIncludeExecution | kIncludeLoaded | kIncludeCollected));
CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
while (iData.Next_Unlocked(pDomainAssembly.This()))
{
// The assembly could be collected (ref-count = 0), do not use holder which calls add-ref
Assembly * pAssembly = pDomainAssembly->GetLoadedAssembly();
if (pAssembly != NULL)
{
LoaderAllocator * pLoaderAllocator = pAssembly->GetLoaderAllocator();
if (pLoaderAllocator->IsCollectible())
{
printf("LA %p ReferencesTo %d\n", pLoaderAllocator, pLoaderAllocator->m_cReferences);
LoaderAllocatorSet::Iterator iter = pLoaderAllocator->m_LoaderAllocatorReferences.Begin();
while (iter != pLoaderAllocator->m_LoaderAllocatorReferences.End())
{
LoaderAllocator * pAllocator = *iter;
printf("LARefTo: %p\n", pAllocator);
iter++;
}
}
}
}
}
#endif //0
AppDomain::AssemblyIterator i;
// Iterate through every loader allocator, marking as we go
{
i = pAppDomain->IterateAssembliesEx((AssemblyIterationFlags)(
kIncludeExecution | kIncludeLoaded | kIncludeCollected));
CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
while (i.Next_Unlocked(pDomainAssembly.This()))
{
// The assembly could be collected (ref-count = 0), do not use holder which calls add-ref
Assembly * pAssembly = pDomainAssembly->GetLoadedAssembly();
if (pAssembly != NULL)
{
LoaderAllocator * pLoaderAllocator = pAssembly->GetLoaderAllocator();
if (pLoaderAllocator->IsCollectible())
{
if (pLoaderAllocator->IsAlive())
pLoaderAllocator->Mark();
}
}
}
}
// Iterate through every loader allocator, unmarking marked loaderallocators, and
// build a free list of unmarked ones
{
i = pAppDomain->IterateAssembliesEx((AssemblyIterationFlags)(
kIncludeExecution | kIncludeLoaded | kIncludeCollected));
CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
while (i.Next_Unlocked(pDomainAssembly.This()))
{
// The assembly could be collected (ref-count = 0), do not use holder which calls add-ref
Assembly * pAssembly = pDomainAssembly->GetLoadedAssembly();
if (pAssembly != NULL)
{
LoaderAllocator * pLoaderAllocator = pAssembly->GetLoaderAllocator();
if (pLoaderAllocator->IsCollectible())
{
if (pLoaderAllocator->Marked())
{
pLoaderAllocator->ClearMark();
}
else if (!pLoaderAllocator->IsAlive())
{
pLoaderAllocator->m_pLoaderAllocatorDestroyNext = pFirstDestroyedLoaderAllocator;
// We will store a reference to this assembly, and use it later in this function
pFirstDestroyedLoaderAllocator = pLoaderAllocator;
_ASSERTE(pLoaderAllocator->m_pDomainAssemblyToDelete != NULL);
}
}
}
}
}
// Iterate through free list, removing from Assembly list
LoaderAllocator * pDomainLoaderAllocatorDestroyIterator = pFirstDestroyedLoaderAllocator;
while (pDomainLoaderAllocatorDestroyIterator != NULL)
{
_ASSERTE(!pDomainLoaderAllocatorDestroyIterator->IsAlive());
_ASSERTE(pDomainLoaderAllocatorDestroyIterator->m_pDomainAssemblyToDelete != NULL);
pAppDomain->RemoveAssembly_Unlocked(pDomainLoaderAllocatorDestroyIterator->m_pDomainAssemblyToDelete);
pDomainLoaderAllocatorDestroyIterator = pDomainLoaderAllocatorDestroyIterator->m_pLoaderAllocatorDestroyNext;
}
return pFirstDestroyedLoaderAllocator;
} // LoaderAllocator::GCLoaderAllocators_RemoveAssemblies
//---------------------------------------------------------------------------------------
//
// Collect unreferenced assemblies, delete all their remaining resources.
//
//static
void LoaderAllocator::GCLoaderAllocators(AppDomain * pAppDomain)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_PREEMPTIVE;
SO_INTOLERANT;
}
CONTRACTL_END;
// List of LoaderAllocators being deleted
LoaderAllocator * pFirstDestroyedLoaderAllocator = NULL;
{
CrstHolder chLoaderAllocatorReferencesLock(pAppDomain->GetLoaderAllocatorReferencesLock());
// We will lock the assembly list, so no other thread can delete items from it while we are deleting
// them.
// Note: Because of the previously taken lock we could just lock during every enumeration, but this
// is more robust for the future.
// This lock switches thread to GC_NOTRIGGER (see code:BaseDomain#AssemblyListLock).
CrstHolder chAssemblyListLock(pAppDomain->GetAssemblyListLock());
pFirstDestroyedLoaderAllocator = GCLoaderAllocators_RemoveAssemblies(pAppDomain);
}
// Note: The removed LoaderAllocators are not reachable outside of this function anymore, because we
// removed them from the assembly list
// Iterate through free list, firing ETW events and notifying the debugger
LoaderAllocator * pDomainLoaderAllocatorDestroyIterator = pFirstDestroyedLoaderAllocator;
while (pDomainLoaderAllocatorDestroyIterator != NULL)
{
_ASSERTE(!pDomainLoaderAllocatorDestroyIterator->IsAlive());
// Fire ETW event
ETW::LoaderLog::CollectibleLoaderAllocatorUnload((AssemblyLoaderAllocator *)pDomainLoaderAllocatorDestroyIterator);
// Set the unloaded flag before notifying the debugger
pDomainLoaderAllocatorDestroyIterator->SetIsUnloaded();
DomainAssembly * pDomainAssembly = pDomainLoaderAllocatorDestroyIterator->m_pDomainAssemblyToDelete;
_ASSERTE(pDomainAssembly != NULL);
// Notify the debugger
pDomainAssembly->NotifyDebuggerUnload();
pDomainLoaderAllocatorDestroyIterator = pDomainLoaderAllocatorDestroyIterator->m_pLoaderAllocatorDestroyNext;
}
// Iterate through free list, deleting DomainAssemblies
pDomainLoaderAllocatorDestroyIterator = pFirstDestroyedLoaderAllocator;
while (pDomainLoaderAllocatorDestroyIterator != NULL)
{
_ASSERTE(!pDomainLoaderAllocatorDestroyIterator->IsAlive());
_ASSERTE(pDomainLoaderAllocatorDestroyIterator->m_pDomainAssemblyToDelete != NULL);
delete pDomainLoaderAllocatorDestroyIterator->m_pDomainAssemblyToDelete;
// We really don't have to set it to NULL as the assembly is not reachable anymore, but just in case ...
// (Also debugging NULL AVs if someone uses it accidentaly is so much easier)
pDomainLoaderAllocatorDestroyIterator->m_pDomainAssemblyToDelete = NULL;
pDomainLoaderAllocatorDestroyIterator = pDomainLoaderAllocatorDestroyIterator->m_pLoaderAllocatorDestroyNext;
}
// Deleting the DomainAssemblies will have created a list of LoaderAllocator's on the AppDomain
// Call this shutdown function to clean those up.
pAppDomain->ShutdownFreeLoaderAllocators(TRUE);
} // LoaderAllocator::GCLoaderAllocators
//---------------------------------------------------------------------------------------
//
//static
BOOL QCALLTYPE LoaderAllocator::Destroy(QCall::LoaderAllocatorHandle pLoaderAllocator)
{
QCALL_CONTRACT;
BOOL ret = FALSE;
BEGIN_QCALL;
if (ObjectHandleIsNull(pLoaderAllocator->GetLoaderAllocatorObjectHandle()))
{
STRESS_LOG1(LF_CLASSLOADER, LL_INFO100, "Begin LoaderAllocator::Destroy for loader allocator %p\n", reinterpret_cast<void *>(static_cast<PTR_LoaderAllocator>(pLoaderAllocator)));
LoaderAllocatorID *pID = pLoaderAllocator->Id();
// This will probably change for shared code unloading
_ASSERTE(pID->GetType() == LAT_Assembly);
Assembly *pAssembly = pID->GetDomainAssembly()->GetCurrentAssembly();
//if not fully loaded, it is still domain specific, so just get one from DomainAssembly
BaseDomain *pDomain = pAssembly ? pAssembly->Parent() : pID->GetDomainAssembly()->GetAppDomain();
pLoaderAllocator->CleanupStringLiteralMap();
// This will probably change for shared code unloading
_ASSERTE(pDomain->IsAppDomain());
AppDomain *pAppDomain = pDomain->AsAppDomain();
pLoaderAllocator->m_pDomainAssemblyToDelete = pAssembly->GetDomainAssembly(pAppDomain);
// Iterate through all references to other loader allocators and decrement their reference
// count
LoaderAllocatorSet::Iterator iter = pLoaderAllocator->m_LoaderAllocatorReferences.Begin();
while (iter != pLoaderAllocator->m_LoaderAllocatorReferences.End())
{
LoaderAllocator *pAllocator = *iter;
pAllocator->Release();
iter++;
}
// Release this loader allocator
BOOL fIsLastReferenceReleased = pLoaderAllocator->Release();
// If the reference count on this assembly got to 0, then a LoaderAllocator may
// be able to be collected, thus, perform a garbage collection.
// The reference count is setup such that in the case of non-trivial graphs, the reference count
// may hit zero early.
if (fIsLastReferenceReleased)
{
LoaderAllocator::GCLoaderAllocators(pAppDomain);
}
STRESS_LOG1(LF_CLASSLOADER, LL_INFO100, "End LoaderAllocator::Destroy for loader allocator %p\n", reinterpret_cast<void *>(static_cast<PTR_LoaderAllocator>(pLoaderAllocator)));
ret = TRUE;
}
END_QCALL;
return ret;
} // LoaderAllocator::Destroy
// Returns NULL if the managed LoaderAllocator object was already collected.
LOADERHANDLE LoaderAllocator::AllocateHandle(OBJECTREF value)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
LOADERHANDLE retVal;
GCPROTECT_BEGIN(value);
CrstHolder ch(&m_crstLoaderAllocator);
retVal = AllocateHandle_Unlocked(value);
GCPROTECT_END();
return retVal;
}
#define MAX_LOADERALLOCATOR_HANDLE 0x40000000
// Returns NULL if the managed LoaderAllocator object was already collected.
LOADERHANDLE LoaderAllocator::AllocateHandle_Unlocked(OBJECTREF valueUNSAFE)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
_ASSERTE(m_crstLoaderAllocator.OwnedByCurrentThread());
UINT_PTR retVal;
struct _gc
{
OBJECTREF value;
LOADERALLOCATORREF loaderAllocator;
PTRARRAYREF handleTable;
PTRARRAYREF handleTableOld;
} gc;
ZeroMemory(&gc, sizeof(gc));
GCPROTECT_BEGIN(gc);
gc.value = valueUNSAFE;
{
// The handle table is read locklessly, be careful
if (IsCollectible())
{
gc.loaderAllocator = (LOADERALLOCATORREF)ObjectFromHandle(m_hLoaderAllocatorObjectHandle);
if (gc.loaderAllocator == NULL)
{ // The managed LoaderAllocator is already collected, we cannot allocate any exposed managed objects for it
retVal = NULL;
}
else
{
DWORD slotsUsed = gc.loaderAllocator->GetSlotsUsed();
if (slotsUsed > MAX_LOADERALLOCATOR_HANDLE)
{
COMPlusThrowOM();
}
gc.handleTable = gc.loaderAllocator->GetHandleTable();
/* If we need to enlarge the table, do it now. */
if (slotsUsed >= gc.handleTable->GetNumComponents())
{
gc.handleTableOld = gc.handleTable;
DWORD newSize = gc.handleTable->GetNumComponents() * 2;
gc.handleTable = (PTRARRAYREF)AllocateObjectArray(newSize, g_pObjectClass);
/* Copy out of old array */
memmoveGCRefs(gc.handleTable->GetDataPtr(), gc.handleTableOld->GetDataPtr(), slotsUsed * sizeof(Object *));
gc.loaderAllocator->SetHandleTable(gc.handleTable);
}
gc.handleTable->SetAt(slotsUsed, gc.value);
gc.loaderAllocator->SetSlotsUsed(slotsUsed + 1);
retVal = (UINT_PTR)((slotsUsed + 1) << 1);
}
}
else
{
OBJECTREF* pRef = GetDomain()->AllocateObjRefPtrsInLargeTable(1);
SetObjectReference(pRef, gc.value, IsDomainNeutral() ? NULL : GetDomain()->AsAppDomain());
retVal = (((UINT_PTR)pRef) + 1);
}
}
GCPROTECT_END();
return (LOADERHANDLE)retVal;
} // LoaderAllocator::AllocateHandle_Unlocked
OBJECTREF LoaderAllocator::GetHandleValue(LOADERHANDLE handle)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
OBJECTREF objRet = NULL;
GET_LOADERHANDLE_VALUE_FAST(this, handle, &objRet);
return objRet;
}
void LoaderAllocator::ClearHandle(LOADERHANDLE handle)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(handle != NULL);
}
CONTRACTL_END;
SetHandleValue(handle, NULL);
}
OBJECTREF LoaderAllocator::CompareExchangeValueInHandle(LOADERHANDLE handle, OBJECTREF valueUNSAFE, OBJECTREF compareUNSAFE)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(handle != NULL);
}
CONTRACTL_END;
OBJECTREF retVal;
struct _gc
{
OBJECTREF value;
OBJECTREF compare;
OBJECTREF previous;
} gc;
ZeroMemory(&gc, sizeof(gc));
GCPROTECT_BEGIN(gc);
gc.value = valueUNSAFE;
gc.compare = compareUNSAFE;
/* The handle table is read locklessly, be careful */
{
CrstHolder ch(&m_crstLoaderAllocator);
if ((((UINT_PTR)handle) & 1) != 0)
{
OBJECTREF *ptr = (OBJECTREF *)(((UINT_PTR)handle) - 1);
gc.previous = *ptr;
if ((*ptr) == gc.compare)
{
SetObjectReference(ptr, gc.value, IsDomainNeutral() ? NULL : GetDomain()->AsAppDomain());
}
}
else
{
_ASSERTE(!ObjectHandleIsNull(m_hLoaderAllocatorObjectHandle));
UINT_PTR index = (((UINT_PTR)handle) >> 1) - 1;
LOADERALLOCATORREF loaderAllocator = (LOADERALLOCATORREF)ObjectFromHandle(m_hLoaderAllocatorObjectHandle);
PTRARRAYREF handleTable = loaderAllocator->GetHandleTable();
gc.previous = handleTable->GetAt(index);
if (gc.previous == gc.compare)
{
handleTable->SetAt(index, gc.value);
}
}
} // End critical section
retVal = gc.previous;
GCPROTECT_END();
return retVal;
}
void LoaderAllocator::SetHandleValue(LOADERHANDLE handle, OBJECTREF value)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(handle != NULL);
}
CONTRACTL_END;
GCPROTECT_BEGIN(value);
// The handle table is read locklessly, be careful
{
CrstHolder ch(&m_crstLoaderAllocator);
// If the slot value does have the low bit set, then it is a simple pointer to the value
// Otherwise, we will need a more complicated operation to clear the value.
if ((((UINT_PTR)handle) & 1) != 0)
{
OBJECTREF *ptr = (OBJECTREF *)(((UINT_PTR)handle) - 1);
SetObjectReference(ptr, value, IsDomainNeutral() ? NULL : GetDomain()->AsAppDomain());
}
else
{
_ASSERTE(!ObjectHandleIsNull(m_hLoaderAllocatorObjectHandle));
UINT_PTR index = (((UINT_PTR)handle) >> 1) - 1;
LOADERALLOCATORREF loaderAllocator = (LOADERALLOCATORREF)ObjectFromHandle(m_hLoaderAllocatorObjectHandle);
PTRARRAYREF handleTable = loaderAllocator->GetHandleTable();
handleTable->SetAt(index, value);
}
}
GCPROTECT_END();
return;
}
void LoaderAllocator::SetupManagedTracking(LOADERALLOCATORREF * pKeepLoaderAllocatorAlive)
{
STANDARD_VM_CONTRACT;
GCInterface::AddMemoryPressure(30000);
m_fGCPressure = true;
GCX_COOP();
//
// Initialize managed loader allocator reference holder
//
MethodTable *pMT = MscorlibBinder::GetClass(CLASS__LOADERALLOCATOR);
*pKeepLoaderAllocatorAlive = (LOADERALLOCATORREF)AllocateObject(pMT);
MethodDescCallSite initLoaderAllocator(METHOD__LOADERALLOCATOR__CTOR, (OBJECTREF *)pKeepLoaderAllocatorAlive);
ARG_SLOT args[] = {
ObjToArgSlot(*pKeepLoaderAllocatorAlive)
};
initLoaderAllocator.Call(args);
m_hLoaderAllocatorObjectHandle = GetDomain()->CreateLongWeakHandle(*pKeepLoaderAllocatorAlive);
RegisterHandleForCleanup(m_hLoaderAllocatorObjectHandle);
}
void LoaderAllocator::ActivateManagedTracking()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
MODE_ANY;
}
CONTRACTL_END
GCX_COOP();
// There is now one external reference to this LoaderAllocator (the managed scout)
_ASSERTE(m_cReferences == (UINT32)-1);
m_cReferences = (UINT32)1;
LOADERALLOCATORREF loaderAllocator = (LOADERALLOCATORREF)ObjectFromHandle(m_hLoaderAllocatorObjectHandle);
loaderAllocator->SetNativeLoaderAllocator(this);
}
#endif // !CROSSGEN_COMPILE
// We don't actually allocate a low frequency heap for collectible types
#define COLLECTIBLE_LOW_FREQUENCY_HEAP_SIZE (0 * GetOsPageSize())
#define COLLECTIBLE_HIGH_FREQUENCY_HEAP_SIZE (3 * GetOsPageSize())
#define COLLECTIBLE_STUB_HEAP_SIZE GetOsPageSize()
#define COLLECTIBLE_CODEHEAP_SIZE (7 * GetOsPageSize())
#define COLLECTIBLE_VIRTUALSTUBDISPATCH_HEAP_SPACE (5 * GetOsPageSize())
void LoaderAllocator::Init(BaseDomain *pDomain, BYTE *pExecutableHeapMemory)
{
STANDARD_VM_CONTRACT;
m_pDomain = pDomain;
m_crstLoaderAllocator.Init(CrstLoaderAllocator);
//
// Initialize the heaps
//
DWORD dwLowFrequencyHeapReserveSize;
DWORD dwHighFrequencyHeapReserveSize;
DWORD dwStubHeapReserveSize;
DWORD dwExecutableHeapReserveSize;
DWORD dwCodeHeapReserveSize;
DWORD dwVSDHeapReserveSize;
dwExecutableHeapReserveSize = 0;
if (IsCollectible())
{
dwLowFrequencyHeapReserveSize = COLLECTIBLE_LOW_FREQUENCY_HEAP_SIZE;
dwHighFrequencyHeapReserveSize = COLLECTIBLE_HIGH_FREQUENCY_HEAP_SIZE;
dwStubHeapReserveSize = COLLECTIBLE_STUB_HEAP_SIZE;
dwCodeHeapReserveSize = COLLECTIBLE_CODEHEAP_SIZE;
dwVSDHeapReserveSize = COLLECTIBLE_VIRTUALSTUBDISPATCH_HEAP_SPACE;
}
else
{
dwLowFrequencyHeapReserveSize = LOW_FREQUENCY_HEAP_RESERVE_SIZE;
dwHighFrequencyHeapReserveSize = HIGH_FREQUENCY_HEAP_RESERVE_SIZE;
dwStubHeapReserveSize = STUB_HEAP_RESERVE_SIZE;
// Non-collectible assemblies do not reserve space for these heaps.
dwCodeHeapReserveSize = 0;
dwVSDHeapReserveSize = 0;
}
// The global heap needs a bit of space for executable memory that is not associated with a rangelist.
// Take a page from the high-frequency heap for this.
if (pExecutableHeapMemory != NULL)
{
#ifdef FEATURE_WINDOWSPHONE
// code:UMEntryThunk::CreateUMEntryThunk allocates memory on executable loader heap for phone.
// Reserve enough for a typical phone app to fit.
dwExecutableHeapReserveSize = 3 * GetOsPageSize();
#else
dwExecutableHeapReserveSize = GetOsPageSize();
#endif
_ASSERTE(dwExecutableHeapReserveSize < dwHighFrequencyHeapReserveSize);
dwHighFrequencyHeapReserveSize -= dwExecutableHeapReserveSize;
}
DWORD dwTotalReserveMemSize = dwLowFrequencyHeapReserveSize
+ dwHighFrequencyHeapReserveSize
+ dwStubHeapReserveSize
+ dwCodeHeapReserveSize
+ dwVSDHeapReserveSize
+ dwExecutableHeapReserveSize;
dwTotalReserveMemSize = (DWORD) ALIGN_UP(dwTotalReserveMemSize, VIRTUAL_ALLOC_RESERVE_GRANULARITY);
#if !defined(_WIN64)
// Make sure that we reserve as little as possible on 32-bit to save address space
_ASSERTE(dwTotalReserveMemSize <= VIRTUAL_ALLOC_RESERVE_GRANULARITY);
#endif
BYTE * initReservedMem = ClrVirtualAllocExecutable(dwTotalReserveMemSize, MEM_RESERVE, PAGE_NOACCESS);
m_InitialReservedMemForLoaderHeaps = initReservedMem;
if (initReservedMem == NULL)
COMPlusThrowOM();
if (IsCollectible())
{
m_pCodeHeapInitialAlloc = initReservedMem;
initReservedMem += dwCodeHeapReserveSize;
m_pVSDHeapInitialAlloc = initReservedMem;
initReservedMem += dwVSDHeapReserveSize;
}
else
{
_ASSERTE((dwCodeHeapReserveSize == 0) && (m_pCodeHeapInitialAlloc == NULL));
_ASSERTE((dwVSDHeapReserveSize == 0) && (m_pVSDHeapInitialAlloc == NULL));
}
if (dwLowFrequencyHeapReserveSize != 0)
{
_ASSERTE(!IsCollectible());
m_pLowFrequencyHeap = new (&m_LowFreqHeapInstance) LoaderHeap(LOW_FREQUENCY_HEAP_RESERVE_SIZE,
LOW_FREQUENCY_HEAP_COMMIT_SIZE,
initReservedMem,
dwLowFrequencyHeapReserveSize,
LOADERHEAP_PROFILE_COUNTER);
initReservedMem += dwLowFrequencyHeapReserveSize;
}
if (dwExecutableHeapReserveSize != 0)
{
_ASSERTE(!IsCollectible());