-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
appdomain.cpp
4773 lines (3930 loc) · 143 KB
/
appdomain.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.
#include "common.h"
#include "appdomain.hpp"
#include "peimagelayout.inl"
#include "field.h"
#include "strongnameinternal.h"
#include "excep.h"
#include "eeconfig.h"
#include "gcheaputilities.h"
#include "eventtrace.h"
#include "eeprofinterfaces.h"
#include "dbginterface.h"
#ifndef DACCESS_COMPILE
#include "eedbginterfaceimpl.h"
#endif
#include "comdynamic.h"
#include "mlinfo.h"
#include "posterror.h"
#include "assemblynative.hpp"
#include "shimload.h"
#include "stringliteralmap.h"
#include "frozenobjectheap.h"
#include "codeman.h"
#include "comcallablewrapper.h"
#include "eventtrace.h"
#include "comdelegate.h"
#include "siginfo.hpp"
#include "typekey.h"
#include "castcache.h"
#include "caparser.h"
#include "ecall.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#ifdef FEATURE_COMINTEROP
#include "comtoclrcall.h"
#include "runtimecallablewrapper.h"
#include "mngstdinterfaces.h"
#include "olevariant.h"
#include "olecontexthelpers.h"
#endif // FEATURE_COMINTEROP
#if defined(FEATURE_COMWRAPPERS)
#include "rcwrefcache.h"
#endif // FEATURE_COMWRAPPERS
#include "typeequivalencehash.hpp"
#include "appdomain.inl"
#ifndef TARGET_UNIX
#include "dwreport.h"
#endif // !TARGET_UNIX
#include "stringarraylist.h"
#include "../binder/inc/bindertracing.h"
#include "../binder/inc/defaultassemblybinder.h"
#include "../binder/inc/assemblybindercommon.hpp"
// this file handles string conversion errors for itself
#undef MAKE_TRANSLATIONFAILED
// Define these macro's to do strict validation for jit lock and class
// init entry leaks. This defines determine if the asserts that
// verify for these leaks are defined or not. These asserts can
// sometimes go off even if no entries have been leaked so this
// defines should be used with caution.
//
// If we are inside a .cctor when the application shut's down then the
// class init lock's head will be set and this will cause the assert
// to go off.
//
// If we are jitting a method when the application shut's down then
// the jit lock's head will be set causing the assert to go off.
//#define STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
static const WCHAR DEFAULT_DOMAIN_FRIENDLY_NAME[] = W("DefaultDomain");
#define STATIC_OBJECT_TABLE_BUCKET_SIZE 1020
// Statics
SPTR_IMPL(AppDomain, AppDomain, m_pTheAppDomain);
SPTR_IMPL(SystemDomain, SystemDomain, m_pSystemDomain);
#ifndef DACCESS_COMPILE
// Base Domain Statics
CrstStatic BaseDomain::m_MethodTableExposedClassObjectCrst;
int BaseDomain::m_iNumberOfProcessors = 0;
// System Domain Statics
GlobalStringLiteralMap* SystemDomain::m_pGlobalStringLiteralMap = NULL;
FrozenObjectHeapManager* SystemDomain::m_FrozenObjectHeapManager = NULL;
DECLSPEC_ALIGN(16)
static BYTE g_pSystemDomainMemory[sizeof(SystemDomain)];
CrstStatic SystemDomain::m_SystemDomainCrst;
CrstStatic SystemDomain::m_DelayedUnloadCrst;
// Constructor for the PinnedHeapHandleBucket class.
PinnedHeapHandleBucket::PinnedHeapHandleBucket(PinnedHeapHandleBucket *pNext, PTRARRAYREF pinnedHandleArrayObj, DWORD size, BaseDomain *pDomain)
: m_pNext(pNext)
, m_ArraySize(size)
, m_CurrentPos(0)
, m_CurrentEmbeddedFreePos(0) // hint for where to start a search for an embedded free item
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pDomain));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// Retrieve the pointer to the data inside the array. This is legal since the array
// is located in the pinned object heap and is guaranteed not to move.
m_pArrayDataPtr = (OBJECTREF *)pinnedHandleArrayObj->GetDataPtr();
// Store the array in a strong handle to keep it alive.
m_hndHandleArray = pDomain->CreateStrongHandle((OBJECTREF)pinnedHandleArrayObj);
}
// Destructor for the PinnedHeapHandleBucket class.
PinnedHeapHandleBucket::~PinnedHeapHandleBucket()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_hndHandleArray)
{
DestroyStrongHandle(m_hndHandleArray);
m_hndHandleArray = NULL;
}
}
// Allocate handles from the bucket.
OBJECTREF *PinnedHeapHandleBucket::AllocateHandles(DWORD nRequested)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
_ASSERTE(nRequested > 0 && nRequested <= GetNumRemainingHandles());
_ASSERTE(m_pArrayDataPtr == (OBJECTREF*)((PTRARRAYREF)ObjectFromHandle(m_hndHandleArray))->GetDataPtr());
// Store the handles in the buffer that was passed in
OBJECTREF* ret = &m_pArrayDataPtr[m_CurrentPos];
m_CurrentPos += nRequested;
return ret;
}
// look for a free item embedded in the table
OBJECTREF *PinnedHeapHandleBucket::TryAllocateEmbeddedFreeHandle()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
OBJECTREF pPreallocatedSentinelObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
_ASSERTE(pPreallocatedSentinelObject != NULL);
for (int i = m_CurrentEmbeddedFreePos; i < m_CurrentPos; i++)
{
if (m_pArrayDataPtr[i] == pPreallocatedSentinelObject)
{
m_CurrentEmbeddedFreePos = i;
m_pArrayDataPtr[i] = NULL;
return &m_pArrayDataPtr[i];
}
}
// didn't find it (we don't bother wrapping around for a full search, it's not worth it to try that hard, we'll get it next time)
m_CurrentEmbeddedFreePos = 0;
return NULL;
}
// enumerate the handles in the bucket
void PinnedHeapHandleBucket::EnumStaticGCRefs(promote_func* fn, ScanContext* sc)
{
for (int i = 0; i < m_CurrentPos; i++)
{
fn((Object**)&m_pArrayDataPtr[i], sc, 0);
}
}
// Maximum bucket size will be 64K on 32-bit and 128K on 64-bit.
// We subtract out a small amount to leave room for the object
// header and length of the array.
#define MAX_BUCKETSIZE (16384 - 4)
// Constructor for the PinnedHeapHandleTable class.
PinnedHeapHandleTable::PinnedHeapHandleTable(BaseDomain *pDomain, DWORD InitialBucketSize)
: m_pHead(NULL)
, m_pDomain(pDomain)
, m_NextBucketSize(InitialBucketSize)
, m_pFreeSearchHint(NULL)
, m_cEmbeddedFree(0)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pDomain));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
m_Crst.Init(CrstPinnedHeapHandleTable, CRST_UNSAFE_COOPGC);
}
// Destructor for the PinnedHeapHandleTable class.
PinnedHeapHandleTable::~PinnedHeapHandleTable()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
// Delete the buckets.
while (m_pHead)
{
PinnedHeapHandleBucket *pOld = m_pHead;
m_pHead = pOld->GetNext();
delete pOld;
}
}
// Allocate handles from the large heap handle table.
// This function is thread-safe for concurrent invocation by multiple callers
OBJECTREF* PinnedHeapHandleTable::AllocateHandles(DWORD nRequested)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(nRequested > 0);
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
#ifdef _DEBUG
_ASSERTE(!m_Crst.OwnedByCurrentThread());
#endif
// beware: we leave and re-enter this lock below in this method
CrstHolderWithState lockHolder(&m_Crst);
if (nRequested == 1 && m_cEmbeddedFree != 0)
{
// special casing singleton requests to look for slots that can be re-used
// we need to do this because string literals are allocated one at a time and then sometimes
// released. we do not wish for the number of handles consumed by string literals to
// increase forever as assemblies are loaded and unloaded
if (m_pFreeSearchHint == NULL)
m_pFreeSearchHint = m_pHead;
while (m_pFreeSearchHint)
{
OBJECTREF* pObjRef = m_pFreeSearchHint->TryAllocateEmbeddedFreeHandle();
if (pObjRef != NULL)
{
// the slot is to have been prepared with a null ready to go
_ASSERTE(*pObjRef == NULL);
m_cEmbeddedFree--;
return pObjRef;
}
m_pFreeSearchHint = m_pFreeSearchHint->GetNext();
}
// the search doesn't wrap around so it's possible that we might have embedded free items
// and not find them but that's ok, we'll get them on the next alloc... all we're trying to do
// is to not have big leaks over time.
}
// Retrieve the remaining number of handles in the bucket.
DWORD numRemainingHandlesInBucket = (m_pHead != NULL) ? m_pHead->GetNumRemainingHandles() : 0;
PTRARRAYREF pinnedHandleArrayObj = NULL;
DWORD nextBucketSize = min<DWORD>(m_NextBucketSize * 2, MAX_BUCKETSIZE);
// create a new block if this request doesn't fit in the current block
if (nRequested > numRemainingHandlesInBucket)
{
// create a new bucket for this allocation
// We need a block big enough to hold the requested handles
DWORD newBucketSize = max(m_NextBucketSize, nRequested);
// Leave the lock temporarily to do the GC allocation
//
// Why do we need to do certain work outside the lock? Because if we didn't this can happen:
// 1. AllocateHandles needs the GC to allocate
// 2. Anything which invokes the GC might also get suspended by the managed debugger which
// will block the thread inside the lock
// 3. The managed debugger can run function-evaluation on any thread
// 4. Those func-evals might need to allocate handles
// 5. The func-eval can't acquire the lock to allocate handles because the thread in
// step (3) still holds the lock. The thread in step (3) won't release the lock until the
// debugger allows it to resume. The debugger won't resume until the funceval completes.
// 6. This either creates a deadlock or forces the debugger to abort the func-eval with a bad
// user experience.
//
// This is only a partial fix to the func-eval problem. Some of the callers to AllocateHandles()
// are holding their own different locks farther up the stack. To address this more completely
// we probably need to change the fundamental invariant that all GC suspend points are also valid
// debugger suspend points. Changes in that area have proven to be error-prone in the past and we
// don't yet have the appropriate testing to validate that a future attempt gets it correct.
lockHolder.Release();
{
OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
pinnedHandleArrayObj = (PTRARRAYREF)AllocateObjectArray(newBucketSize, g_pObjectClass, /* bAllocateInPinnedHeap = */TRUE);
}
lockHolder.Acquire();
// after leaving and re-entering the lock anything we verified or computed above using internal state could
// have changed. We need to retest if we still need the new allocation.
numRemainingHandlesInBucket = (m_pHead != NULL) ? m_pHead->GetNumRemainingHandles() : 0;
if (nRequested > numRemainingHandlesInBucket)
{
if (m_pHead != NULL)
{
// mark the handles in that remaining region as available for re-use
ReleaseHandlesLocked(m_pHead->CurrentPos(), numRemainingHandlesInBucket);
// mark what's left as having been used
m_pHead->ConsumeRemaining();
}
m_pHead = new PinnedHeapHandleBucket(m_pHead, pinnedHandleArrayObj, newBucketSize, m_pDomain);
// we already computed nextBucketSize to be double the previous size above, but it is possible that
// other threads increased m_NextBucketSize while the lock was unheld. We want to ensure
// m_NextBucketSize never shrinks even if nextBucketSize is no longer m_NextBucketSize*2.
m_NextBucketSize = max(m_NextBucketSize, nextBucketSize);
}
else
{
// we didn't need the allocation after all
// no handle has been created to root this so the GC may be able to reclaim and reuse it
pinnedHandleArrayObj = NULL;
}
}
return m_pHead->AllocateHandles(nRequested);
}
//*****************************************************************************
// Release object handles allocated using AllocateHandles().
// This function is thread-safe for concurrent invocation by multiple callers
void PinnedHeapHandleTable::ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pObjRef));
}
CONTRACTL_END;
#ifdef _DEBUG
_ASSERTE(!m_Crst.OwnedByCurrentThread());
#endif
CrstHolder ch(&m_Crst);
ReleaseHandlesLocked(pObjRef, nReleased);
}
void PinnedHeapHandleTable::ReleaseHandlesLocked(OBJECTREF *pObjRef, DWORD nReleased)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pObjRef));
}
CONTRACTL_END;
#ifdef _DEBUG
_ASSERTE(m_Crst.OwnedByCurrentThread());
#endif
OBJECTREF pPreallocatedSentinelObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
_ASSERTE(pPreallocatedSentinelObject != NULL);
// Add the released handles to the list of available handles.
for (DWORD i = 0; i < nReleased; i++)
{
SetObjectReference(&pObjRef[i], pPreallocatedSentinelObject);
}
m_cEmbeddedFree += nReleased;
}
// enumerate the handles in the handle table
void PinnedHeapHandleTable::EnumStaticGCRefs(promote_func* fn, ScanContext* sc)
{
for (PinnedHeapHandleBucket *pBucket = m_pHead; pBucket != nullptr; pBucket = pBucket->GetNext())
{
pBucket->EnumStaticGCRefs(fn, sc);
}
}
//*****************************************************************************
// BaseDomain
//*****************************************************************************
void BaseDomain::Attach()
{
m_MethodTableExposedClassObjectCrst.Init(CrstMethodTableExposedObject);
}
BaseDomain::BaseDomain()
{
// initialize fields so the domain can be safely destructed
// shouldn't call anything that can fail here - use ::Init instead
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END;
m_pDefaultBinder = NULL;
// Make sure the container is set to NULL so that it gets loaded when it is used.
m_pPinnedHeapHandleTable = NULL;
// Note that m_handleStore is overridden by app domains
m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
#ifdef FEATURE_COMINTEROP
m_pMngStdInterfacesInfo = NULL;
#endif
m_FileLoadLock.PreInit();
m_JITLock.PreInit();
m_ClassInitLock.PreInit();
m_ILStubGenLock.PreInit();
m_NativeTypeLoadLock.PreInit();
} //BaseDomain::BaseDomain
//*****************************************************************************
void BaseDomain::Init()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
//
// Initialize the domain locks
//
if (this == reinterpret_cast<BaseDomain*>(&g_pSystemDomainMemory[0]))
m_DomainCrst.Init(CrstSystemBaseDomain);
else
m_DomainCrst.Init(CrstBaseDomain);
m_DomainCacheCrst.Init(CrstAppDomainCache);
m_crstGenericDictionaryExpansionLock.Init(CrstGenericDictionaryExpansion);
// NOTE: CRST_UNSAFE_COOPGC prevents a GC mode switch to preemptive when entering this crst.
// If you remove this flag, we will switch to preemptive mode when entering
// m_FileLoadLock, which means all functions that enter it will become
// GC_TRIGGERS. (This includes all uses of PEFileListLockHolder, LoadLockHolder, etc.) So be sure
// to update the contracts if you remove this flag.
m_FileLoadLock.Init(CrstAssemblyLoader,
CrstFlags(CRST_HOST_BREAKABLE), TRUE);
//
// The JIT lock and the CCtor locks are at the same level (and marked as
// UNSAFE_SAME_LEVEL) because they are all part of the same deadlock detection mechanism. We
// see through cycles of JITting and .cctor execution and then explicitly allow the cycle to
// be broken by giving access to uninitialized classes. If there is no cycle or if the cycle
// involves other locks that arent part of this special deadlock-breaking semantics, then
// we continue to block.
//
m_JITLock.Init(CrstJit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
m_ClassInitLock.Init(CrstClassInit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
m_ILStubGenLock.Init(CrstILStubGen, CrstFlags(CRST_REENTRANCY), TRUE);
m_NativeTypeLoadLock.Init(CrstInteropData, CrstFlags(CRST_REENTRANCY), TRUE);
m_crstLoaderAllocatorReferences.Init(CrstLoaderAllocatorReferences);
// Has to switch thread to GC_NOTRIGGER while being held (see code:BaseDomain#AssemblyListLock)
m_crstAssemblyList.Init(CrstAssemblyList, CrstFlags(
CRST_GC_NOTRIGGER_WHEN_TAKEN | CRST_DEBUGGER_THREAD | CRST_TAKEN_DURING_SHUTDOWN));
#ifdef FEATURE_COMINTEROP
// Allocate the managed standard interfaces information.
m_pMngStdInterfacesInfo = new MngStdInterfacesInfo();
#endif // FEATURE_COMINTEROP
m_dwSizedRefHandles = 0;
// For server GC this value indicates the number of GC heaps used in circular order to allocate sized
// ref handles. It must not exceed the array size allocated by the handle table (see getNumberOfSlots
// in objecthandle.cpp). We might want to use GetNumberOfHeaps if it were accessible here.
m_iNumberOfProcessors = min(GetCurrentProcessCpuCount(), GetTotalProcessorCount());
}
#undef LOADERHEAP_PROFILE_COUNTER
void BaseDomain::InitVSD()
{
STANDARD_VM_CONTRACT;
m_typeIDMap.Init();
GetLoaderAllocator()->InitVirtualCallStubManager(this);
}
void BaseDomain::ClearBinderContext()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
if (m_pDefaultBinder)
{
delete m_pDefaultBinder;
m_pDefaultBinder = NULL;
}
}
void AppDomain::ShutdownFreeLoaderAllocators()
{
// If we're called from managed code (i.e. the finalizer thread) we take a lock in
// LoaderAllocator::CleanupFailedTypeInit, which may throw. Otherwise we're called
// from the app-domain shutdown path in which we can avoid taking the lock.
CONTRACTL
{
GC_TRIGGERS;
THROWS;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
CrstHolder ch(GetLoaderAllocatorReferencesLock());
// Shutdown the LoaderAllocators associated with collectible assemblies
while (m_pDelayedLoaderAllocatorUnloadList != NULL)
{
LoaderAllocator * pCurrentLoaderAllocator = m_pDelayedLoaderAllocatorUnloadList;
// Remove next loader allocator from the list
m_pDelayedLoaderAllocatorUnloadList = m_pDelayedLoaderAllocatorUnloadList->m_pLoaderAllocatorDestroyNext;
// For loader allocator finalization, we need to be careful about cleaning up per-appdomain allocations
// and synchronizing with GC using delay unload list. We need to wait for next Gen2 GC to finish to ensure
// that GC heap does not have any references to the MethodTables being unloaded.
pCurrentLoaderAllocator->CleanupFailedTypeInit();
pCurrentLoaderAllocator->CleanupHandles();
GCX_COOP();
SystemDomain::System()->AddToDelayedUnloadList(pCurrentLoaderAllocator);
}
} // AppDomain::ShutdownFreeLoaderAllocators
//---------------------------------------------------------------------------------------
//
// Register the loader allocator for deletion in code:AppDomain::ShutdownFreeLoaderAllocators.
//
void AppDomain::RegisterLoaderAllocatorForDeletion(LoaderAllocator * pLoaderAllocator)
{
CONTRACTL
{
GC_TRIGGERS;
NOTHROW;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
CrstHolder ch(GetLoaderAllocatorReferencesLock());
pLoaderAllocator->m_pLoaderAllocatorDestroyNext = m_pDelayedLoaderAllocatorUnloadList;
m_pDelayedLoaderAllocatorUnloadList = pLoaderAllocator;
}
void AppDomain::SetNativeDllSearchDirectories(LPCWSTR wszNativeDllSearchDirectories)
{
STANDARD_VM_CONTRACT;
SString sDirectories(wszNativeDllSearchDirectories);
if (sDirectories.GetCount() > 0)
{
SString::CIterator start = sDirectories.Begin();
SString::CIterator itr = sDirectories.Begin();
SString::CIterator end = sDirectories.End();
SString qualifiedPath;
while (itr != end)
{
start = itr;
BOOL found = sDirectories.Find(itr, PATH_SEPARATOR_CHAR_W);
if (!found)
{
itr = end;
}
SString qualifiedPath(sDirectories, start, itr);
if (found)
{
itr++;
}
unsigned len = qualifiedPath.GetCount();
if (len > 0)
{
if (qualifiedPath[len - 1] != DIRECTORY_SEPARATOR_CHAR_W)
{
qualifiedPath.Append(DIRECTORY_SEPARATOR_CHAR_W);
}
NewHolder<SString> stringHolder(new SString(qualifiedPath));
IfFailThrow(m_NativeDllSearchDirectories.Append(stringHolder.GetValue()));
stringHolder.SuppressRelease();
}
}
}
}
OBJECTREF* BaseDomain::AllocateObjRefPtrsInLargeTable(int nRequested, DynamicStaticsInfo* pStaticsInfo, MethodTable *pMTToFillWithStaticBoxes, bool isClassInitdeByUpdatingStaticPointer)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION((nRequested > 0));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
if (pStaticsInfo && pStaticsInfo->GetGCStaticsPointer() != NULL)
{
// Allocation already happened
return pStaticsInfo->GetGCStaticsPointer();
}
GCX_COOP();
// Make sure the large heap handle table is initialized.
if (!m_pPinnedHeapHandleTable)
InitPinnedHeapHandleTable();
// Allocate the handles.
OBJECTREF* result = m_pPinnedHeapHandleTable->AllocateHandles(nRequested);
if (pMTToFillWithStaticBoxes != NULL)
{
GCPROTECT_BEGININTERIOR(result);
pMTToFillWithStaticBoxes->AllocateRegularStaticBoxes(&result);
GCPROTECT_END();
}
if (pStaticsInfo)
{
// race with other threads that might be doing the same concurrent allocation
if (!pStaticsInfo->InterlockedUpdateStaticsPointer(/*isGCPointer*/ true, (TADDR)result, isClassInitdeByUpdatingStaticPointer))
{
// we lost the race, release our handles and use the handles from the
// winning thread
m_pPinnedHeapHandleTable->ReleaseHandles(result, nRequested);
result = pStaticsInfo->GetGCStaticsPointer();
}
}
return result;
}
#endif // !DACCESS_COMPILE
#ifdef FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
OBJECTREF AppDomain::GetMissingObject()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (!m_hndMissing)
{
// Get the field
FieldDesc *pValueFD = CoreLibBinder::GetField(FIELD__MISSING__VALUE);
pValueFD->CheckRunClassInitThrowing();
// Retrieve the value static field and store it.
OBJECTHANDLE hndMissing = CreateHandle(pValueFD->GetStaticOBJECTREF());
if (InterlockedCompareExchangeT(&m_hndMissing, hndMissing, NULL) != NULL)
{
// Exchanged failed. The m_hndMissing did not equal NULL and was returned.
DestroyHandle(hndMissing);
}
}
return ObjectFromHandle(m_hndMissing);
}
#endif // DACCESS_COMPILE
#endif // FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
STRINGREF *BaseDomain::IsStringInterned(STRINGREF *pString)
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pString));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
return GetLoaderAllocator()->IsStringInterned(pString);
}
STRINGREF *BaseDomain::GetOrInternString(STRINGREF *pString)
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pString));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
return GetLoaderAllocator()->GetOrInternString(pString);
}
void BaseDomain::InitPinnedHeapHandleTable()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
PinnedHeapHandleTable* pTable = new PinnedHeapHandleTable(this, STATIC_OBJECT_TABLE_BUCKET_SIZE);
if(InterlockedCompareExchangeT<PinnedHeapHandleTable*>(&m_pPinnedHeapHandleTable, pTable, NULL) != NULL)
{
// another thread beat us to initializing the field, delete our copy
delete pTable;
}
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
void *SystemDomain::operator new(size_t size, void *pInPlace)
{
LIMITED_METHOD_CONTRACT;
return pInPlace;
}
void SystemDomain::operator delete(void *pMem)
{
LIMITED_METHOD_CONTRACT;
// Do nothing - new() was in-place
}
void SystemDomain::Attach()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(m_pSystemDomain == NULL);
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// Initialize stub managers
PrecodeStubManager::Init();
JumpStubStubManager::Init();
RangeSectionStubManager::Init();
ILStubManager::Init();
InteropDispatchStubManager::Init();
StubLinkStubManager::Init();
ThunkHeapStubManager::Init();
TailCallStubManager::Init();
#ifdef FEATURE_TIERED_COMPILATION
CallCountingStubManager::Init();
#endif
m_SystemDomainCrst.Init(CrstSystemDomain, (CrstFlags)(CRST_REENTRANCY | CRST_TAKEN_DURING_SHUTDOWN));
m_DelayedUnloadCrst.Init(CrstSystemDomainDelayedUnloadList, CRST_UNSAFE_COOPGC);
// Create the global SystemDomain and initialize it.
m_pSystemDomain = new (&g_pSystemDomainMemory[0]) SystemDomain();
// No way it can fail since g_pSystemDomainMemory is a static array.
CONSISTENCY_CHECK(CheckPointer(m_pSystemDomain));
LOG((LF_CLASSLOADER,
LL_INFO10,
"Created system domain at %p\n",
m_pSystemDomain));
// We need to initialize the memory pools etc. for the system domain.
m_pSystemDomain->BaseDomain::Init(); // Setup the memory heaps
// Create the one and only app domain
AppDomain::Create();
// Each domain gets its own ReJitManager, and ReJitManager has its own static
// initialization to run
ReJitManager::InitStatic();
#ifdef FEATURE_READYTORUN
InitReadyToRunStandaloneMethodMetadata();
#endif // FEATURE_READYTORUN
}
void SystemDomain::DetachBegin()
{
WRAPPER_NO_CONTRACT;
// Shut down the domain and its children (but don't deallocate anything just
// yet).
// TODO: we should really not running managed DLLMain during process detach.
if (GetThreadNULLOk() == NULL)
{
return;
}
if(m_pSystemDomain)
m_pSystemDomain->Stop();
}
void SystemDomain::DetachEnd()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
// Shut down the domain and its children (but don't deallocate anything just
// yet).
if(m_pSystemDomain)
{
GCX_PREEMP();
m_pSystemDomain->ClearBinderContext();
AppDomain* pAppDomain = GetAppDomain();
if (pAppDomain)
pAppDomain->ClearBinderContext();
}
}
void SystemDomain::Stop()
{
WRAPPER_NO_CONTRACT;
AppDomain::GetCurrentDomain()->Stop();
}
void SystemDomain::PreallocateSpecialObjects()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
_ASSERTE(g_pPreallocatedSentinelObject == NULL);
OBJECTREF pPreallocatedSentinelObject = AllocateObject(g_pObjectClass);
g_pPreallocatedSentinelObject = CreatePinningHandle( pPreallocatedSentinelObject );
}
void SystemDomain::CreatePreallocatedExceptions()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
EXCEPTIONREF pOutOfMemory = (EXCEPTIONREF)AllocateObject(g_pOutOfMemoryExceptionClass);
pOutOfMemory->SetHResult(COR_E_OUTOFMEMORY);
pOutOfMemory->SetXCode(EXCEPTION_COMPLUS);
_ASSERTE(g_pPreallocatedOutOfMemoryException == NULL);
g_pPreallocatedOutOfMemoryException = CreateHandle(pOutOfMemory);
EXCEPTIONREF pStackOverflow = (EXCEPTIONREF)AllocateObject(g_pStackOverflowExceptionClass);
pStackOverflow->SetHResult(COR_E_STACKOVERFLOW);
pStackOverflow->SetXCode(EXCEPTION_COMPLUS);
_ASSERTE(g_pPreallocatedStackOverflowException == NULL);
g_pPreallocatedStackOverflowException = CreateHandle(pStackOverflow);
EXCEPTIONREF pExecutionEngine = (EXCEPTIONREF)AllocateObject(g_pExecutionEngineExceptionClass);
pExecutionEngine->SetHResult(COR_E_EXECUTIONENGINE);
pExecutionEngine->SetXCode(EXCEPTION_COMPLUS);
_ASSERTE(g_pPreallocatedExecutionEngineException == NULL);
g_pPreallocatedExecutionEngineException = CreateHandle(pExecutionEngine);
}
void SystemDomain::Init()
{
STANDARD_VM_CONTRACT;
HRESULT hr = S_OK;
#ifdef _DEBUG
LOG((
LF_EEMEM,
LL_INFO10,
"sizeof(EEClass) = %d\n"
"sizeof(MethodTable) = %d\n"
"sizeof(MethodDesc)= %d\n"
"sizeof(FieldDesc) = %d\n"
"sizeof(Module) = %d\n",
sizeof(EEClass),
sizeof(MethodTable),
sizeof(MethodDesc),
sizeof(FieldDesc),
sizeof(Module)
));
#endif // _DEBUG
// The base domain is initialized in SystemDomain::Attach()
// to allow stub caches to use the memory pool. Do not