This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
appdomain.cpp
7491 lines (6197 loc) · 227 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.
// See the LICENSE file in the project root for more information.
#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 "assemblyname.hpp"
#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 "codeman.h"
#include "comcallablewrapper.h"
#include "apithreadstress.h"
#include "eventtrace.h"
#include "comdelegate.h"
#include "siginfo.hpp"
#include "typekey.h"
#include "caparser.h"
#include "ecall.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#ifdef FEATURE_PREJIT
#include "corcompile.h"
#include "compile.h"
#endif // FEATURE_PREJIT
#ifdef FEATURE_COMINTEROP
#include "comtoclrcall.h"
#include "runtimecallablewrapper.h"
#include "mngstdinterfaces.h"
#include "olevariant.h"
#include "rcwrefcache.h"
#include "olecontexthelpers.h"
#endif // FEATURE_COMINTEROP
#include "typeequivalencehash.hpp"
#include "appdomain.inl"
#include "typeparse.h"
#include "mdaassistants.h"
#include "threadpoolrequest.h"
#include "nativeoverlapped.h"
#ifndef FEATURE_PAL
#include "dwreport.h"
#endif // !FEATURE_PAL
#include "stringarraylist.h"
#include "../binder/inc/clrprivbindercoreclr.h"
#include "clrprivtypecachewinrt.h"
// 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");
static const WCHAR OTHER_DOMAIN_FRIENDLY_NAME_PREFIX[] = W("Domain");
#define STATIC_OBJECT_TABLE_BUCKET_SIZE 1020
// Statics
SPTR_IMPL(AppDomain, AppDomain, m_pTheAppDomain);
SPTR_IMPL(SystemDomain, SystemDomain, m_pSystemDomain);
SVAL_IMPL(BOOL, SystemDomain, s_fForceDebug);
SVAL_IMPL(BOOL, SystemDomain, s_fForceProfiling);
SVAL_IMPL(BOOL, SystemDomain, s_fForceInstrument);
#ifndef DACCESS_COMPILE
// Base Domain Statics
CrstStatic BaseDomain::m_SpecialStaticsCrst;
int BaseDomain::m_iNumberOfProcessors = 0;
// System Domain Statics
GlobalStringLiteralMap* SystemDomain::m_pGlobalStringLiteralMap = NULL;
DECLSPEC_ALIGN(16)
static BYTE g_pSystemDomainMemory[sizeof(SystemDomain)];
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
size_t SystemDomain::m_totalSurvivedBytes = 0;
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
CrstStatic SystemDomain::m_SystemDomainCrst;
CrstStatic SystemDomain::m_DelayedUnloadCrst;
ULONG SystemDomain::s_dNumAppDomains = 0;
DWORD SystemDomain::m_dwLowestFreeIndex = 0;
// comparison function to be used for matching clsids in our clsid hash table
BOOL CompareCLSID(UPTR u1, UPTR u2)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
GUID *pguid = (GUID *)(u1 << 1);
_ASSERTE(pguid != NULL);
MethodTable *pMT= (MethodTable *)u2;
_ASSERTE(pMT!= NULL);
GUID guid;
pMT->GetGuid(&guid, TRUE);
if (!IsEqualIID(guid, *pguid))
return FALSE;
return TRUE;
}
#ifndef CROSSGEN_COMPILE
// Constructor for the LargeHeapHandleBucket class.
LargeHeapHandleBucket::LargeHeapHandleBucket(LargeHeapHandleBucket *pNext, DWORD Size, BaseDomain *pDomain, BOOL bCrossAD)
: 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_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pDomain));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
PTRARRAYREF HandleArrayObj;
// Allocate the array in the large object heap.
if (!bCrossAD)
{
OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, TRUE);
}
else
{
// During AD creation we don't want to assign the handle array to the currently running AD but
// to the AD being created. Ensure that AllocateArrayEx doesn't set the AD and then set it here.
AppDomain *pAD = pDomain->AsAppDomain();
_ASSERTE(pAD);
_ASSERTE(pAD->IsBeingCreated());
OBJECTREF array;
{
OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
array = AllocateArrayEx(
ClassLoader::LoadArrayTypeThrowing(g_pObjectClass),
(INT32 *)(&Size),
1,
TRUE);
}
HandleArrayObj = (PTRARRAYREF)array;
}
// Retrieve the pointer to the data inside the array. This is legal since the array
// is located in the large object heap and is guaranteed not to move.
m_pArrayDataPtr = (OBJECTREF *)HandleArrayObj->GetDataPtr();
// Store the array in a strong handle to keep it alive.
m_hndHandleArray = pDomain->CreatePinningHandle((OBJECTREF)HandleArrayObj);
}
// Destructor for the LargeHeapHandleBucket class.
LargeHeapHandleBucket::~LargeHeapHandleBucket()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_hndHandleArray)
{
DestroyPinningHandle(m_hndHandleArray);
m_hndHandleArray = NULL;
}
}
// Allocate handles from the bucket.
OBJECTREF *LargeHeapHandleBucket::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 *LargeHeapHandleBucket::TryAllocateEmbeddedFreeHandle()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
_ASSERTE(pPreallocatedSentinalObject != NULL);
for (int i = m_CurrentEmbeddedFreePos; i < m_CurrentPos; i++)
{
if (m_pArrayDataPtr[i] == pPreallocatedSentinalObject)
{
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;
}
// 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 LargeHeapHandleTable class.
LargeHeapHandleTable::LargeHeapHandleTable(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;
#ifdef _DEBUG
m_pCrstDebug = NULL;
#endif
}
// Destructor for the LargeHeapHandleTable class.
LargeHeapHandleTable::~LargeHeapHandleTable()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
// Delete the buckets.
while (m_pHead)
{
LargeHeapHandleBucket *pOld = m_pHead;
m_pHead = pOld->GetNext();
delete pOld;
}
}
//*****************************************************************************
//
// LOCKING RULES FOR AllocateHandles() and ReleaseHandles() 12/08/2004
//
//
// These functions are not protected by any locking in this location but rather the callers are
// assumed to be doing suitable locking for the handle table. The handle table itself is
// behaving rather like a thread-agnostic collection class -- it doesn't want to know
// much about the outside world and so it is just doing its job with no awareness of
// thread notions.
//
// The instance in question is
// There are two locations you can find a LargeHeapHandleTable
// 1) there is one in every BaseDomain, it is used to keep track of the static members
// in that domain
// 2) there is one in the System Domain that is used for the GlobalStringLiteralMap
//
// the one in (2) is not the same as the one that is in the BaseDomain object that corresponds
// to the SystemDomain -- that one is basically stilborn because the string literals don't go
// there and of course the System Domain has no code loaded into it -- only regular
// AppDomains (like Domain 0) actually execute code. As a result handle tables are in
// practice used either for string literals or for static members but never for both.
// At least not at this writing.
//
// Now it's useful to consider what the locking discipline is for these classes.
//
// ---------
//
// First case: (easiest) is the statics members
//
// Each BaseDomain has its own critical section
//
// BaseDomain::AllocateObjRefPtrsInLargeTable takes a lock with
// CrstHolder ch(&m_LargeHeapHandleTableCrst);
//
// it does this before it calls AllocateHandles which suffices. It does not call ReleaseHandles
// at any time (although ReleaseHandles may be called via AllocateHandles if the request
// doesn't fit in the current block, the remaining handles at the end of the block are released
// automatically as part of allocation/recycling)
//
// note: Recycled handles are only used during String Literal allocation because we only try
// to recycle handles if the allocation request is for exactly one handle.
//
// The handles in the BaseDomain handle table are released when the Domain is unloaded
// as the GC objects become rootless at that time.
//
// This dispenses with all of the Handle tables except the one that is used for string literals
//
// ---------
//
// Second case: Allocation for use in a string literal
//
// AppDomainStringLiteralMap::GetStringLiteral
// leads to calls to
// LargeHeapHandleBlockHolder constructor
// leads to calls to
// m_Data = pOwner->AllocateHandles(nCount);
//
// before doing this AppDomainStringLiteralMap::GetStringLiteral takes this lock
//
// CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
//
// which is the lock for the hash table that it owns
//
// STRINGREF *AppDomainStringLiteralMap::GetInternedString
//
// has a similar call path and uses the same approach and the same lock
// this covers all the paths which allocate
//
// ---------
//
// Third case: Releases for use in a string literal entry
//
// CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
// taken in the AppDomainStringLiteralMap functions below protects the 4 ways that this can happen
//
// case 3a)
//
// in an appdomain unload case
//
// AppDomainStringLiteralMap::~AppDomainStringLiteralMap() takes the lock then
// leads to calls to
// StringLiteralEntry::Release
// which leads to
// SystemDomain::GetGlobalStringLiteralMapNoCreate()->RemoveStringLiteralEntry(this)
// which leads to
// m_LargeHeapHandleTable.ReleaseHandles((OBJECTREF*)pObjRef, 1);
//
// case 3b)
//
// AppDomainStringLiteralMap::GetStringLiteral() can call StringLiteralEntry::Release in some
// error cases, leading to the same stack as above
//
// case 3c)
//
// AppDomainStringLiteralMap::GetInternedString() can call StringLiteralEntry::Release in some
// error cases, leading to the same stack as above
//
// case 3d)
//
// The same code paths in 3b and 3c and also end up releasing if an exception is thrown
// during their processing. Both these paths use a StringLiteralEntryHolder to assist in cleanup,
// the StaticRelease method of the StringLiteralEntry gets called, which in turn calls the
// Release method.
// Allocate handles from the large heap handle table.
OBJECTREF* LargeHeapHandleTable::AllocateHandles(DWORD nRequested, BOOL bCrossAD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(nRequested > 0);
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
// the lock must be registered and already held by the caller per contract
#ifdef _DEBUG
_ASSERTE(m_pCrstDebug != NULL);
_ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
#endif
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;
// create a new block if this request doesn't fit in the current block
if (nRequested > NumRemainingHandlesInBucket)
{
if (m_pHead != NULL)
{
// mark the handles in that remaining region as available for re-use
ReleaseHandles(m_pHead->CurrentPos(), NumRemainingHandlesInBucket);
// mark what's left as having been used
m_pHead->ConsumeRemaining();
}
// create a new bucket for this allocation
// We need a block big enough to hold the requested handles
DWORD NewBucketSize = max(m_NextBucketSize, nRequested);
m_pHead = new LargeHeapHandleBucket(m_pHead, NewBucketSize, m_pDomain, bCrossAD);
m_NextBucketSize = min(m_NextBucketSize * 2, MAX_BUCKETSIZE);
}
return m_pHead->AllocateHandles(nRequested);
}
//*****************************************************************************
// Release object handles allocated using AllocateHandles().
void LargeHeapHandleTable::ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pObjRef));
}
CONTRACTL_END;
// SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
// the lock must be registered and already held by the caller per contract
#ifdef _DEBUG
_ASSERTE(m_pCrstDebug != NULL);
_ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
#endif
OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
_ASSERTE(pPreallocatedSentinalObject != NULL);
// Add the released handles to the list of available handles.
for (DWORD i = 0; i < nReleased; i++)
{
SetObjectReference(&pObjRef[i], pPreallocatedSentinalObject);
}
m_cEmbeddedFree += nReleased;
}
// Constructor for the ThreadStaticHandleBucket class.
ThreadStaticHandleBucket::ThreadStaticHandleBucket(ThreadStaticHandleBucket *pNext, DWORD Size, BaseDomain *pDomain)
: m_pNext(pNext)
, m_ArraySize(Size)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pDomain));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
PTRARRAYREF HandleArrayObj;
// Allocate the array on the GC heap.
OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, FALSE);
// Store the array in a strong handle to keep it alive.
m_hndHandleArray = pDomain->CreateStrongHandle((OBJECTREF)HandleArrayObj);
}
// Destructor for the ThreadStaticHandleBucket class.
ThreadStaticHandleBucket::~ThreadStaticHandleBucket()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (m_hndHandleArray)
{
DestroyStrongHandle(m_hndHandleArray);
m_hndHandleArray = NULL;
}
}
// Allocate handles from the bucket.
OBJECTHANDLE ThreadStaticHandleBucket::GetHandles()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
return m_hndHandleArray;
}
// Constructor for the ThreadStaticHandleTable class.
ThreadStaticHandleTable::ThreadStaticHandleTable(BaseDomain *pDomain)
: m_pHead(NULL)
, m_pDomain(pDomain)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pDomain));
}
CONTRACTL_END;
}
// Destructor for the ThreadStaticHandleTable class.
ThreadStaticHandleTable::~ThreadStaticHandleTable()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
// Delete the buckets.
while (m_pHead)
{
ThreadStaticHandleBucket *pOld = m_pHead;
m_pHead = pOld->GetNext();
delete pOld;
}
}
// Allocate handles from the large heap handle table.
OBJECTHANDLE ThreadStaticHandleTable::AllocateHandles(DWORD nRequested)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(nRequested > 0);
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// create a new bucket for this allocation
m_pHead = new ThreadStaticHandleBucket(m_pHead, nRequested, m_pDomain);
return m_pHead->GetHandles();
}
#endif // CROSSGEN_COMPILE
//*****************************************************************************
// BaseDomain
//*****************************************************************************
void BaseDomain::Attach()
{
m_SpecialStaticsCrst.Init(CrstSpecialStatics);
}
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_fDisableInterfaceCache = FALSE;
m_pFusionContext = NULL;
m_pTPABinderContext = NULL;
// Make sure the container is set to NULL so that it gets loaded when it is used.
m_pLargeHeapHandleTable = NULL;
#ifndef CROSSGEN_COMPILE
// Note that m_handleStore is overridden by app domains
m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
#else
m_handleStore = NULL;
#endif
#ifdef FEATURE_COMINTEROP
m_pMngStdInterfacesInfo = NULL;
m_pWinRtBinder = NULL;
#endif
m_FileLoadLock.PreInit();
m_JITLock.PreInit();
m_ClassInitLock.PreInit();
m_ILStubGenLock.PreInit();
#ifdef FEATURE_CODE_VERSIONING
m_codeVersionManager.PreInit();
#endif
} //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_DomainLocalBlockCrst.Init(CrstDomainLocalBlock);
m_InteropDataCrst.Init(CrstInteropData, CRST_REENTRANCY);
m_WinRTFactoryCacheCrst.Init(CrstWinRTFactoryCache, CRST_UNSAFE_COOPGC);
// 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);
// Large heap handle table CRST.
m_LargeHeapHandleTableCrst.Init(CrstAppDomainHandleTable);
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();
{
CLRPrivBinderWinRT::NamespaceResolutionKind fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_WindowsAPI;
if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_DesignerNamespaceResolutionEnabled) != FALSE)
{
fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_DesignerResolveEvent;
}
CLRPrivTypeCacheWinRT * pWinRtTypeCache = CLRPrivTypeCacheWinRT::GetOrCreateTypeCache();
m_pWinRtBinder = CLRPrivBinderWinRT::GetOrCreateBinder(pWinRtTypeCache, fNamespaceResolutionKind);
}
#endif // FEATURE_COMINTEROP
// Init the COM Interop data hash
{
LockOwner lock = {&m_InteropDataCrst, IsOwnerOfCrst};
m_interopDataHash.Init(0, NULL, false, &lock);
}
m_dwSizedRefHandles = 0;
if (!m_iNumberOfProcessors)
{
m_iNumberOfProcessors = GetCurrentProcessCpuCount();
}
}
#undef LOADERHEAP_PROFILE_COUNTER
void BaseDomain::InitVSD()
{
STANDARD_VM_CONTRACT;
// This is a workaround for gcc, since it fails to successfully resolve
// "TypeIDMap::STARTING_SHARED_DOMAIN_ID" when used within the ?: operator.
UINT32 startingId;
if (IsSharedDomain())
{
startingId = TypeIDMap::STARTING_SHARED_DOMAIN_ID;
}
else
{
startingId = TypeIDMap::STARTING_UNSHARED_DOMAIN_ID;
}
// By passing false as the last parameter, interfaces loaded in the
// shared domain will not be given fat type ids if RequiresFatDispatchTokens
// is set. This is correct, as the fat dispatch tokens are only needed to solve
// uniqueness problems involving domain specific types.
m_typeIDMap.Init(startingId, 2, !IsSharedDomain());
#ifndef CROSSGEN_COMPILE
GetLoaderAllocator()->InitVirtualCallStubManager(this);
#endif
}
#ifndef CROSSGEN_COMPILE
void BaseDomain::ClearFusionContext()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
if(m_pFusionContext) {
m_pFusionContext->Release();
m_pFusionContext = NULL;
}
if (m_pTPABinderContext) {
m_pTPABinderContext->Release();
m_pTPABinderContext = 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();
}
}
}
}
void AppDomain::ReleaseFiles()
{
STANDARD_VM_CONTRACT;
// Shutdown assemblies
AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
kIncludeLoaded | kIncludeExecution | kIncludeFailedToLoad | kIncludeLoading));
CollectibleAssemblyHolder<DomainAssembly *> pAsm;
while (i.Next(pAsm.This()))
{
if (pAsm->GetCurrentAssembly() == NULL)
{
// Might be domain neutral or not, but should have no live objects as it has not been
// really loaded yet. Just reset it.
_ASSERTE(FitsIn<DWORD>(i.GetIndex()));
m_Assemblies.Set(this, static_cast<DWORD>(i.GetIndex()), NULL);
delete pAsm.Extract();
}
else
{
pAsm->ReleaseFiles();
}
}
} // AppDomain::ReleaseFiles
OBJECTREF* BaseDomain::AllocateObjRefPtrsInLargeTable(int nRequested, OBJECTREF** ppLazyAllocate, BOOL bCrossAD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION((nRequested > 0));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
if (ppLazyAllocate && *ppLazyAllocate)
{
// Allocation already happened
return *ppLazyAllocate;