1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
8 #include "appdomain.hpp"
9 #include "peimagelayout.inl"
11 #include "strongnameinternal.h"
14 #include "gcheaputilities.h"
15 #include "eventtrace.h"
16 #include "perfcounters.h"
17 #include "assemblyname.hpp"
18 #include "eeprofinterfaces.h"
19 #include "dbginterface.h"
20 #ifndef DACCESS_COMPILE
21 #include "eedbginterfaceimpl.h"
23 #include "comdynamic.h"
25 #include "posterror.h"
26 #include "assemblynative.hpp"
28 #include "stringliteralmap.h"
30 #include "comcallablewrapper.h"
31 #include "apithreadstress.h"
32 #include "eventtrace.h"
33 #include "comdelegate.h"
34 #include "siginfo.hpp"
39 #include "finalizerthread.h"
40 #include "threadsuspend.h"
43 #include "corcompile.h"
45 #endif // FEATURE_PREJIT
47 #ifdef FEATURE_COMINTEROP
48 #include "comtoclrcall.h"
49 #include "runtimecallablewrapper.h"
50 #include "mngstdinterfaces.h"
51 #include "olevariant.h"
52 #include "rcwrefcache.h"
53 #include "olecontexthelpers.h"
54 #endif // FEATURE_COMINTEROP
55 #ifdef FEATURE_TYPEEQUIVALENCE
56 #include "typeequivalencehash.hpp"
59 #include "appdomain.inl"
60 #include "typeparse.h"
61 #include "mdaassistants.h"
62 #include "threadpoolrequest.h"
64 #include "nativeoverlapped.h"
68 #endif // !FEATURE_PAL
70 #include "stringarraylist.h"
72 #include "../binder/inc/clrprivbindercoreclr.h"
75 #include "clrprivtypecachewinrt.h"
79 #pragma warning(disable:4324)
83 // this file handles string conversion errors for itself
84 #undef MAKE_TRANSLATIONFAILED
86 // Define these macro's to do strict validation for jit lock and class
87 // init entry leaks. This defines determine if the asserts that
88 // verify for these leaks are defined or not. These asserts can
89 // sometimes go off even if no entries have been leaked so this
90 // defines should be used with caution.
92 // If we are inside a .cctor when the application shut's down then the
93 // class init lock's head will be set and this will cause the assert
96 // If we are jitting a method when the application shut's down then
97 // the jit lock's head will be set causing the assert to go off.
99 //#define STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
101 static const WCHAR DEFAULT_DOMAIN_FRIENDLY_NAME[] = W("DefaultDomain");
102 static const WCHAR OTHER_DOMAIN_FRIENDLY_NAME_PREFIX[] = W("Domain");
104 #define STATIC_OBJECT_TABLE_BUCKET_SIZE 1020
106 #define MAX_URL_LENGTH 2084 // same as INTERNET_MAX_URL_LENGTH
108 //#define _DEBUG_ADUNLOAD 1
110 HRESULT RunDllMain(MethodDesc *pMD, HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved); // clsload.cpp
118 SPTR_IMPL(SystemDomain, SystemDomain, m_pSystemDomain);
119 SVAL_IMPL(ArrayListStatic, SystemDomain, m_appDomainIndexList);
120 SPTR_IMPL(SharedDomain, SharedDomain, m_pSharedDomain);
121 SVAL_IMPL(BOOL, SystemDomain, s_fForceDebug);
122 SVAL_IMPL(BOOL, SystemDomain, s_fForceProfiling);
123 SVAL_IMPL(BOOL, SystemDomain, s_fForceInstrument);
125 #ifndef DACCESS_COMPILE
127 // Base Domain Statics
128 CrstStatic BaseDomain::m_SpecialStaticsCrst;
130 int BaseDomain::m_iNumberOfProcessors = 0;
132 // Shared Domain Statics
134 static BYTE g_pSharedDomainMemory[sizeof(SharedDomain)];
136 // System Domain Statics
137 GlobalStringLiteralMap* SystemDomain::m_pGlobalStringLiteralMap = NULL;
140 static BYTE g_pSystemDomainMemory[sizeof(SystemDomain)];
142 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
143 size_t SystemDomain::m_totalSurvivedBytes = 0;
144 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
146 CrstStatic SystemDomain::m_SystemDomainCrst;
147 CrstStatic SystemDomain::m_DelayedUnloadCrst;
149 ULONG SystemDomain::s_dNumAppDomains = 0;
151 AppDomain * SystemDomain::m_pAppDomainBeingUnloaded = NULL;
152 ADIndex SystemDomain::m_dwIndexOfAppDomainBeingUnloaded;
153 Thread *SystemDomain::m_pAppDomainUnloadRequestingThread = 0;
154 Thread *SystemDomain::m_pAppDomainUnloadingThread = 0;
156 ArrayListStatic SystemDomain::m_appDomainIdList;
158 DWORD SystemDomain::m_dwLowestFreeIndex = 0;
162 // comparison function to be used for matching clsids in our clsid hash table
163 BOOL CompareCLSID(UPTR u1, UPTR u2)
171 INJECT_FAULT(COMPlusThrowOM(););
175 GUID *pguid = (GUID *)(u1 << 1);
176 _ASSERTE(pguid != NULL);
178 MethodTable *pMT= (MethodTable *)u2;
179 _ASSERTE(pMT!= NULL);
182 pMT->GetGuid(&guid, TRUE);
183 if (!IsEqualIID(guid, *pguid))
189 #ifndef CROSSGEN_COMPILE
190 // Constructor for the LargeHeapHandleBucket class.
191 LargeHeapHandleBucket::LargeHeapHandleBucket(LargeHeapHandleBucket *pNext, DWORD Size, BaseDomain *pDomain, BOOL bCrossAD)
195 , m_CurrentEmbeddedFreePos(0) // hint for where to start a search for an embedded free item
202 PRECONDITION(CheckPointer(pDomain));
203 INJECT_FAULT(COMPlusThrowOM(););
207 PTRARRAYREF HandleArrayObj;
209 // Allocate the array in the large object heap.
212 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
213 HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, TRUE);
217 // During AD creation we don't want to assign the handle array to the currently running AD but
218 // to the AD being created. Ensure that AllocateArrayEx doesn't set the AD and then set it here.
219 AppDomain *pAD = pDomain->AsAppDomain();
221 _ASSERTE(pAD->IsBeingCreated());
225 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
226 array = AllocateArrayEx(
227 ClassLoader::LoadArrayTypeThrowing(g_pObjectClass),
234 array->SetAppDomain(pAD);
236 HandleArrayObj = (PTRARRAYREF)array;
239 // Retrieve the pointer to the data inside the array. This is legal since the array
240 // is located in the large object heap and is guaranteed not to move.
241 m_pArrayDataPtr = (OBJECTREF *)HandleArrayObj->GetDataPtr();
243 // Store the array in a strong handle to keep it alive.
244 m_hndHandleArray = pDomain->CreatePinningHandle((OBJECTREF)HandleArrayObj);
248 // Destructor for the LargeHeapHandleBucket class.
249 LargeHeapHandleBucket::~LargeHeapHandleBucket()
258 if (m_hndHandleArray)
260 DestroyPinningHandle(m_hndHandleArray);
261 m_hndHandleArray = NULL;
266 // Allocate handles from the bucket.
267 OBJECTREF *LargeHeapHandleBucket::AllocateHandles(DWORD nRequested)
277 _ASSERTE(nRequested > 0 && nRequested <= GetNumRemainingHandles());
278 _ASSERTE(m_pArrayDataPtr == (OBJECTREF*)((PTRARRAYREF)ObjectFromHandle(m_hndHandleArray))->GetDataPtr());
280 // Store the handles in the buffer that was passed in
281 OBJECTREF* ret = &m_pArrayDataPtr[m_CurrentPos];
282 m_CurrentPos += nRequested;
287 // look for a free item embedded in the table
288 OBJECTREF *LargeHeapHandleBucket::TryAllocateEmbeddedFreeHandle()
298 OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
299 _ASSERTE(pPreallocatedSentinalObject != NULL);
301 for (int i = m_CurrentEmbeddedFreePos; i < m_CurrentPos; i++)
303 if (m_pArrayDataPtr[i] == pPreallocatedSentinalObject)
305 m_CurrentEmbeddedFreePos = i;
306 m_pArrayDataPtr[i] = NULL;
307 return &m_pArrayDataPtr[i];
311 // 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)
313 m_CurrentEmbeddedFreePos = 0;
318 // Maximum bucket size will be 64K on 32-bit and 128K on 64-bit.
319 // We subtract out a small amount to leave room for the object
320 // header and length of the array.
322 #define MAX_BUCKETSIZE (16384 - 4)
324 // Constructor for the LargeHeapHandleTable class.
325 LargeHeapHandleTable::LargeHeapHandleTable(BaseDomain *pDomain, DWORD InitialBucketSize)
328 , m_NextBucketSize(InitialBucketSize)
329 , m_pFreeSearchHint(NULL)
337 PRECONDITION(CheckPointer(pDomain));
338 INJECT_FAULT(COMPlusThrowOM(););
348 // Destructor for the LargeHeapHandleTable class.
349 LargeHeapHandleTable::~LargeHeapHandleTable()
358 // Delete the buckets.
361 LargeHeapHandleBucket *pOld = m_pHead;
362 m_pHead = pOld->GetNext();
367 //*****************************************************************************
369 // LOCKING RULES FOR AllocateHandles() and ReleaseHandles() 12/08/2004
372 // These functions are not protected by any locking in this location but rather the callers are
373 // assumed to be doing suitable locking for the handle table. The handle table itself is
374 // behaving rather like a thread-agnostic collection class -- it doesn't want to know
375 // much about the outside world and so it is just doing its job with no awareness of
378 // The instance in question is
379 // There are two locations you can find a LargeHeapHandleTable
380 // 1) there is one in every BaseDomain, it is used to keep track of the static members
382 // 2) there is one in the System Domain that is used for the GlobalStringLiteralMap
384 // the one in (2) is not the same as the one that is in the BaseDomain object that corresponds
385 // to the SystemDomain -- that one is basically stilborn because the string literals don't go
386 // there and of course the System Domain has no code loaded into it -- only regular
387 // AppDomains (like Domain 0) actually execute code. As a result handle tables are in
388 // practice used either for string literals or for static members but never for both.
389 // At least not at this writing.
391 // Now it's useful to consider what the locking discipline is for these classes.
395 // First case: (easiest) is the statics members
397 // Each BaseDomain has its own critical section
399 // BaseDomain::AllocateObjRefPtrsInLargeTable takes a lock with
400 // CrstHolder ch(&m_LargeHeapHandleTableCrst);
402 // it does this before it calls AllocateHandles which suffices. It does not call ReleaseHandles
403 // at any time (although ReleaseHandles may be called via AllocateHandles if the request
404 // doesn't fit in the current block, the remaining handles at the end of the block are released
405 // automatically as part of allocation/recycling)
407 // note: Recycled handles are only used during String Literal allocation because we only try
408 // to recycle handles if the allocation request is for exactly one handle.
410 // The handles in the BaseDomain handle table are released when the Domain is unloaded
411 // as the GC objects become rootless at that time.
413 // This dispenses with all of the Handle tables except the one that is used for string literals
417 // Second case: Allocation for use in a string literal
419 // AppDomainStringLiteralMap::GetStringLiteral
421 // LargeHeapHandleBlockHolder constructor
423 // m_Data = pOwner->AllocateHandles(nCount);
425 // before doing this AppDomainStringLiteralMap::GetStringLiteral takes this lock
427 // CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
429 // which is the lock for the hash table that it owns
431 // STRINGREF *AppDomainStringLiteralMap::GetInternedString
433 // has a similar call path and uses the same approach and the same lock
434 // this covers all the paths which allocate
438 // Third case: Releases for use in a string literal entry
440 // CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
441 // taken in the AppDomainStringLiteralMap functions below protects the 4 ways that this can happen
445 // in an appdomain unload case
447 // AppDomainStringLiteralMap::~AppDomainStringLiteralMap() takes the lock then
449 // StringLiteralEntry::Release
451 // SystemDomain::GetGlobalStringLiteralMapNoCreate()->RemoveStringLiteralEntry(this)
453 // m_LargeHeapHandleTable.ReleaseHandles((OBJECTREF*)pObjRef, 1);
457 // AppDomainStringLiteralMap::GetStringLiteral() can call StringLiteralEntry::Release in some
458 // error cases, leading to the same stack as above
462 // AppDomainStringLiteralMap::GetInternedString() can call StringLiteralEntry::Release in some
463 // error cases, leading to the same stack as above
467 // The same code paths in 3b and 3c and also end up releasing if an exception is thrown
468 // during their processing. Both these paths use a StringLiteralEntryHolder to assist in cleanup,
469 // the StaticRelease method of the StringLiteralEntry gets called, which in turn calls the
473 // Allocate handles from the large heap handle table.
474 OBJECTREF* LargeHeapHandleTable::AllocateHandles(DWORD nRequested, BOOL bCrossAD)
481 PRECONDITION(nRequested > 0);
482 INJECT_FAULT(COMPlusThrowOM(););
486 // SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
488 // the lock must be registered and already held by the caller per contract
490 _ASSERTE(m_pCrstDebug != NULL);
491 _ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
494 if (nRequested == 1 && m_cEmbeddedFree != 0)
496 // special casing singleton requests to look for slots that can be re-used
498 // we need to do this because string literals are allocated one at a time and then sometimes
499 // released. we do not wish for the number of handles consumed by string literals to
500 // increase forever as assemblies are loaded and unloaded
502 if (m_pFreeSearchHint == NULL)
503 m_pFreeSearchHint = m_pHead;
505 while (m_pFreeSearchHint)
507 OBJECTREF* pObjRef = m_pFreeSearchHint->TryAllocateEmbeddedFreeHandle();
510 // the slot is to have been prepared with a null ready to go
511 _ASSERTE(*pObjRef == NULL);
515 m_pFreeSearchHint = m_pFreeSearchHint->GetNext();
518 // the search doesn't wrap around so it's possible that we might have embedded free items
519 // and not find them but that's ok, we'll get them on the next alloc... all we're trying to do
520 // is to not have big leaks over time.
524 // Retrieve the remaining number of handles in the bucket.
525 DWORD NumRemainingHandlesInBucket = (m_pHead != NULL) ? m_pHead->GetNumRemainingHandles() : 0;
527 // create a new block if this request doesn't fit in the current block
528 if (nRequested > NumRemainingHandlesInBucket)
532 // mark the handles in that remaining region as available for re-use
533 ReleaseHandles(m_pHead->CurrentPos(), NumRemainingHandlesInBucket);
535 // mark what's left as having been used
536 m_pHead->ConsumeRemaining();
539 // create a new bucket for this allocation
541 // We need a block big enough to hold the requested handles
542 DWORD NewBucketSize = max(m_NextBucketSize, nRequested);
544 m_pHead = new LargeHeapHandleBucket(m_pHead, NewBucketSize, m_pDomain, bCrossAD);
546 m_NextBucketSize = min(m_NextBucketSize * 2, MAX_BUCKETSIZE);
549 return m_pHead->AllocateHandles(nRequested);
552 //*****************************************************************************
553 // Release object handles allocated using AllocateHandles().
554 void LargeHeapHandleTable::ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased)
561 PRECONDITION(CheckPointer(pObjRef));
565 // SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
567 // the lock must be registered and already held by the caller per contract
569 _ASSERTE(m_pCrstDebug != NULL);
570 _ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
573 OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
574 _ASSERTE(pPreallocatedSentinalObject != NULL);
577 // Add the released handles to the list of available handles.
578 for (DWORD i = 0; i < nReleased; i++)
580 SetObjectReference(&pObjRef[i], pPreallocatedSentinalObject, NULL);
583 m_cEmbeddedFree += nReleased;
589 // Constructor for the ThreadStaticHandleBucket class.
590 ThreadStaticHandleBucket::ThreadStaticHandleBucket(ThreadStaticHandleBucket *pNext, DWORD Size, BaseDomain *pDomain)
599 PRECONDITION(CheckPointer(pDomain));
600 INJECT_FAULT(COMPlusThrowOM(););
604 PTRARRAYREF HandleArrayObj;
606 // Allocate the array on the GC heap.
607 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
608 HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, FALSE);
610 // Store the array in a strong handle to keep it alive.
611 m_hndHandleArray = pDomain->CreateStrongHandle((OBJECTREF)HandleArrayObj);
614 // Destructor for the ThreadStaticHandleBucket class.
615 ThreadStaticHandleBucket::~ThreadStaticHandleBucket()
625 if (m_hndHandleArray)
627 DestroyStrongHandle(m_hndHandleArray);
628 m_hndHandleArray = NULL;
632 // Allocate handles from the bucket.
633 OBJECTHANDLE ThreadStaticHandleBucket::GetHandles()
643 return m_hndHandleArray;
646 // Constructor for the ThreadStaticHandleTable class.
647 ThreadStaticHandleTable::ThreadStaticHandleTable(BaseDomain *pDomain)
656 PRECONDITION(CheckPointer(pDomain));
661 // Destructor for the ThreadStaticHandleTable class.
662 ThreadStaticHandleTable::~ThreadStaticHandleTable()
671 // Delete the buckets.
674 ThreadStaticHandleBucket *pOld = m_pHead;
675 m_pHead = pOld->GetNext();
680 // Allocate handles from the large heap handle table.
681 OBJECTHANDLE ThreadStaticHandleTable::AllocateHandles(DWORD nRequested)
688 PRECONDITION(nRequested > 0);
689 INJECT_FAULT(COMPlusThrowOM(););
693 // create a new bucket for this allocation
694 m_pHead = new ThreadStaticHandleBucket(m_pHead, nRequested, m_pDomain);
696 return m_pHead->GetHandles();
699 #endif // CROSSGEN_COMPILE
702 //*****************************************************************************
704 //*****************************************************************************
705 void BaseDomain::Attach()
707 m_SpecialStaticsCrst.Init(CrstSpecialStatics);
710 BaseDomain::BaseDomain()
712 // initialize fields so the domain can be safely destructed
713 // shouldn't call anything that can fail here - use ::Init instead
723 m_fDisableInterfaceCache = FALSE;
725 m_pFusionContext = NULL;
726 m_pTPABinderContext = NULL;
728 // Make sure the container is set to NULL so that it gets loaded when it is used.
729 m_pLargeHeapHandleTable = NULL;
731 #ifndef CROSSGEN_COMPILE
732 // Note that m_handleStore is overridden by app domains
733 m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
735 m_handleStore = NULL;
738 m_pMarshalingData = NULL;
740 m_dwContextStatics = 0;
741 #ifdef FEATURE_COMINTEROP
742 m_pMngStdInterfacesInfo = NULL;
743 m_pWinRtBinder = NULL;
745 m_FileLoadLock.PreInit();
747 m_ClassInitLock.PreInit();
748 m_ILStubGenLock.PreInit();
750 #ifdef FEATURE_CODE_VERSIONING
751 m_codeVersionManager.PreInit(this == (BaseDomain *)g_pSharedDomainMemory);
754 } //BaseDomain::BaseDomain
756 //*****************************************************************************
757 void BaseDomain::Init()
764 INJECT_FAULT(COMPlusThrowOM(););
769 // Initialize the domain locks
772 if (this == reinterpret_cast<BaseDomain*>(&g_pSharedDomainMemory[0]))
773 m_DomainCrst.Init(CrstSharedBaseDomain);
774 else if (this == reinterpret_cast<BaseDomain*>(&g_pSystemDomainMemory[0]))
775 m_DomainCrst.Init(CrstSystemBaseDomain);
777 m_DomainCrst.Init(CrstBaseDomain);
779 m_DomainCacheCrst.Init(CrstAppDomainCache);
780 m_DomainLocalBlockCrst.Init(CrstDomainLocalBlock);
782 m_InteropDataCrst.Init(CrstInteropData, CRST_REENTRANCY);
784 m_WinRTFactoryCacheCrst.Init(CrstWinRTFactoryCache, CRST_UNSAFE_COOPGC);
786 // NOTE: CRST_UNSAFE_COOPGC prevents a GC mode switch to preemptive when entering this crst.
787 // If you remove this flag, we will switch to preemptive mode when entering
788 // m_FileLoadLock, which means all functions that enter it will become
789 // GC_TRIGGERS. (This includes all uses of PEFileListLockHolder, LoadLockHolder, etc.) So be sure
790 // to update the contracts if you remove this flag.
791 m_FileLoadLock.Init(CrstAssemblyLoader,
792 CrstFlags(CRST_HOST_BREAKABLE), TRUE);
795 // The JIT lock and the CCtor locks are at the same level (and marked as
796 // UNSAFE_SAME_LEVEL) because they are all part of the same deadlock detection mechanism. We
797 // see through cycles of JITting and .cctor execution and then explicitly allow the cycle to
798 // be broken by giving access to uninitialized classes. If there is no cycle or if the cycle
799 // involves other locks that arent part of this special deadlock-breaking semantics, then
800 // we continue to block.
802 m_JITLock.Init(CrstJit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
803 m_ClassInitLock.Init(CrstClassInit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
805 m_ILStubGenLock.Init(CrstILStubGen, CrstFlags(CRST_REENTRANCY), TRUE);
807 // Large heap handle table CRST.
808 m_LargeHeapHandleTableCrst.Init(CrstAppDomainHandleTable);
810 m_crstLoaderAllocatorReferences.Init(CrstLoaderAllocatorReferences);
811 // Has to switch thread to GC_NOTRIGGER while being held (see code:BaseDomain#AssemblyListLock)
812 m_crstAssemblyList.Init(CrstAssemblyList, CrstFlags(
813 CRST_GC_NOTRIGGER_WHEN_TAKEN | CRST_DEBUGGER_THREAD | CRST_TAKEN_DURING_SHUTDOWN));
815 // Initialize the EE marshaling data to NULL.
816 m_pMarshalingData = NULL;
818 #ifdef FEATURE_COMINTEROP
819 // Allocate the managed standard interfaces information.
820 m_pMngStdInterfacesInfo = new MngStdInterfacesInfo();
823 CLRPrivBinderWinRT::NamespaceResolutionKind fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_WindowsAPI;
824 if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_DesignerNamespaceResolutionEnabled) != FALSE)
826 fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_DesignerResolveEvent;
828 CLRPrivTypeCacheWinRT * pWinRtTypeCache = CLRPrivTypeCacheWinRT::GetOrCreateTypeCache();
829 m_pWinRtBinder = CLRPrivBinderWinRT::GetOrCreateBinder(pWinRtTypeCache, fNamespaceResolutionKind);
831 #endif // FEATURE_COMINTEROP
833 // Init the COM Interop data hash
835 LockOwner lock = {&m_InteropDataCrst, IsOwnerOfCrst};
836 m_interopDataHash.Init(0, NULL, false, &lock);
839 m_dwSizedRefHandles = 0;
840 if (!m_iNumberOfProcessors)
842 m_iNumberOfProcessors = GetCurrentProcessCpuCount();
846 #undef LOADERHEAP_PROFILE_COUNTER
848 #ifndef CROSSGEN_COMPILE
849 //*****************************************************************************
850 void BaseDomain::Terminate()
860 m_crstLoaderAllocatorReferences.Destroy();
861 m_DomainCrst.Destroy();
862 m_DomainCacheCrst.Destroy();
863 m_DomainLocalBlockCrst.Destroy();
864 m_InteropDataCrst.Destroy();
866 JitListLockEntry* pJitElement;
867 ListLockEntry* pElement;
869 // All the threads that are in this domain had better be stopped by this
872 // We might be jitting or running a .cctor so we need to empty that queue.
873 pJitElement = m_JITLock.Pop(TRUE);
876 #ifdef STRICT_JITLOCK_ENTRY_LEAK_DETECTION
877 _ASSERTE ((m_JITLock.m_pHead->m_dwRefCount == 1
878 && m_JITLock.m_pHead->m_hrResultCode == E_FAIL) ||
879 dbg_fDrasticShutdown || g_fInControlC);
880 #endif // STRICT_JITLOCK_ENTRY_LEAK_DETECTION
882 pJitElement = m_JITLock.Pop(TRUE);
887 pElement = m_ClassInitLock.Pop(TRUE);
890 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
891 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
894 pElement = m_ClassInitLock.Pop(TRUE);
896 m_ClassInitLock.Destroy();
898 FileLoadLock* pFileElement;
899 pFileElement = (FileLoadLock*) m_FileLoadLock.Pop(TRUE);
902 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
903 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
905 pFileElement->Release();
906 pFileElement = (FileLoadLock*) m_FileLoadLock.Pop(TRUE);
908 m_FileLoadLock.Destroy();
910 pElement = m_ILStubGenLock.Pop(TRUE);
913 #ifdef STRICT_JITLOCK_ENTRY_LEAK_DETECTION
914 _ASSERTE ((m_ILStubGenLock.m_pHead->m_dwRefCount == 1
915 && m_ILStubGenLock.m_pHead->m_hrResultCode == E_FAIL) ||
916 dbg_fDrasticShutdown || g_fInControlC);
917 #endif // STRICT_JITLOCK_ENTRY_LEAK_DETECTION
919 pElement = m_ILStubGenLock.Pop(TRUE);
921 m_ILStubGenLock.Destroy();
923 m_LargeHeapHandleTableCrst.Destroy();
925 if (m_pLargeHeapHandleTable != NULL)
927 delete m_pLargeHeapHandleTable;
928 m_pLargeHeapHandleTable = NULL;
933 // Kind of a workaround - during unloading, we need to have an EE halt
934 // around deleting this stuff. So it gets deleted in AppDomain::Terminate()
935 // for those things (because there is a convenient place there.)
936 GetLoaderAllocator()->CleanupStringLiteralMap();
939 #ifdef FEATURE_COMINTEROP
940 if (m_pMngStdInterfacesInfo)
942 delete m_pMngStdInterfacesInfo;
943 m_pMngStdInterfacesInfo = NULL;
946 if (m_pWinRtBinder != NULL)
948 m_pWinRtBinder->Release();
950 #endif // FEATURE_COMINTEROP
952 ClearFusionContext();
954 m_dwSizedRefHandles = 0;
956 #endif // CROSSGEN_COMPILE
958 void BaseDomain::InitVSD()
960 STANDARD_VM_CONTRACT;
962 // This is a workaround for gcc, since it fails to successfully resolve
963 // "TypeIDMap::STARTING_SHARED_DOMAIN_ID" when used within the ?: operator.
965 if (IsSharedDomain())
967 startingId = TypeIDMap::STARTING_SHARED_DOMAIN_ID;
971 startingId = TypeIDMap::STARTING_UNSHARED_DOMAIN_ID;
974 // By passing false as the last parameter, interfaces loaded in the
975 // shared domain will not be given fat type ids if RequiresFatDispatchTokens
976 // is set. This is correct, as the fat dispatch tokens are only needed to solve
977 // uniqueness problems involving domain specific types.
978 m_typeIDMap.Init(startingId, 2, !IsSharedDomain());
980 #ifndef CROSSGEN_COMPILE
981 GetLoaderAllocator()->InitVirtualCallStubManager(this);
985 #ifndef CROSSGEN_COMPILE
987 DWORD BaseDomain::AllocateContextStaticsOffset(DWORD* pOffsetSlot)
996 CrstHolder ch(&m_SpecialStaticsCrst);
998 DWORD dwOffset = *pOffsetSlot;
1000 if (dwOffset == (DWORD)-1)
1002 // Allocate the slot
1003 dwOffset = m_dwContextStatics++;
1004 *pOffsetSlot = dwOffset;
1010 void BaseDomain::ClearFusionContext()
1020 if(m_pFusionContext) {
1021 m_pFusionContext->Release();
1022 m_pFusionContext = NULL;
1024 if (m_pTPABinderContext) {
1025 m_pTPABinderContext->Release();
1026 m_pTPABinderContext = NULL;
1030 #ifdef FEATURE_PREJIT
1031 void AppDomain::DeleteNativeCodeRanges()
1042 // Fast path to skip using the assembly iterator when the appdomain has not yet completely been initialized
1043 // and yet we are destroying it. (This is the case if we OOM during AppDomain creation.)
1044 if (m_Assemblies.IsEmpty())
1047 // Shutdown assemblies
1048 AssemblyIterator i = IterateAssembliesEx( (AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad) );
1049 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1051 while (i.Next(pDomainAssembly.This()))
1053 Assembly * assembly = pDomainAssembly->m_pAssembly;
1054 if ((assembly != NULL) && !assembly->IsDomainNeutral())
1055 assembly->DeleteNativeCodeRanges();
1060 void AppDomain::ShutdownAssemblies()
1070 // Fast path to skip using the assembly iterator when the appdomain has not yet completely been initialized
1071 // and yet we are destroying it. (This is the case if we OOM during AppDomain creation.)
1072 if (m_Assemblies.IsEmpty())
1075 // Shutdown assemblies
1076 // has two stages because Terminate needs info from the Assembly's dependencies
1078 // Stage 1: call code:Assembly::Terminate
1079 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
1080 kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
1081 DomainAssembly * pDomainAssembly = NULL;
1083 while (i.Next_UnsafeNoAddRef(&pDomainAssembly))
1085 // Note: cannot use DomainAssembly::GetAssembly() here as it asserts that the assembly has been
1086 // loaded to at least the FILE_LOAD_ALLOCATE level. Since domain shutdown can take place
1087 // asynchronously this property cannot be guaranteed. Access the m_pAssembly field directly instead.
1088 Assembly * assembly = pDomainAssembly->m_pAssembly;
1089 if (assembly && !assembly->IsDomainNeutral())
1090 assembly->Terminate();
1093 // Stage 2: Clear the list of assemblies
1094 i = IterateAssembliesEx((AssemblyIterationFlags)(
1095 kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
1096 while (i.Next_UnsafeNoAddRef(&pDomainAssembly))
1098 // We are in shutdown path, no one else can get to the list anymore
1099 delete pDomainAssembly;
1101 m_Assemblies.Clear(this);
1103 // Stage 2: Clear the loader allocators registered for deletion from code:Assembly:Terminate calls in
1105 // Note: It is not clear to me why we cannot delete the loader allocator from within
1106 // code:DomainAssembly::~DomainAssembly
1107 ShutdownFreeLoaderAllocators(FALSE);
1108 } // AppDomain::ShutdownAssemblies
1110 void AppDomain::ShutdownFreeLoaderAllocators(BOOL bFromManagedCode)
1112 // If we're called from managed code (i.e. the finalizer thread) we take a lock in
1113 // LoaderAllocator::CleanupFailedTypeInit, which may throw. Otherwise we're called
1114 // from the app-domain shutdown path in which we can avoid taking the lock.
1118 if (bFromManagedCode) THROWS; else NOTHROW;
1124 CrstHolder ch(GetLoaderAllocatorReferencesLock());
1126 // Shutdown the LoaderAllocators associated with collectible assemblies
1127 while (m_pDelayedLoaderAllocatorUnloadList != NULL)
1129 LoaderAllocator * pCurrentLoaderAllocator = m_pDelayedLoaderAllocatorUnloadList;
1130 // Remove next loader allocator from the list
1131 m_pDelayedLoaderAllocatorUnloadList = m_pDelayedLoaderAllocatorUnloadList->m_pLoaderAllocatorDestroyNext;
1133 if (bFromManagedCode)
1135 // For loader allocator finalization, we need to be careful about cleaning up per-appdomain allocations
1136 // and synchronizing with GC using delay unload list. We need to wait for next Gen2 GC to finish to ensure
1137 // that GC heap does not have any references to the MethodTables being unloaded.
1139 pCurrentLoaderAllocator->CleanupFailedTypeInit();
1141 pCurrentLoaderAllocator->CleanupHandles();
1144 SystemDomain::System()->AddToDelayedUnloadList(pCurrentLoaderAllocator);
1148 // For appdomain unload, delete the loader allocator right away
1149 delete pCurrentLoaderAllocator;
1152 } // AppDomain::ShutdownFreeLoaderAllocators
1154 //---------------------------------------------------------------------------------------
1156 // Register the loader allocator for deletion in code:AppDomain::ShutdownFreeLoaderAllocators.
1158 void AppDomain::RegisterLoaderAllocatorForDeletion(LoaderAllocator * pLoaderAllocator)
1169 CrstHolder ch(GetLoaderAllocatorReferencesLock());
1171 pLoaderAllocator->m_pLoaderAllocatorDestroyNext = m_pDelayedLoaderAllocatorUnloadList;
1172 m_pDelayedLoaderAllocatorUnloadList = pLoaderAllocator;
1175 void AppDomain::ShutdownNativeDllSearchDirectories()
1177 LIMITED_METHOD_CONTRACT;
1178 // Shutdown assemblies
1179 PathIterator i = IterateNativeDllSearchDirectories();
1186 m_NativeDllSearchDirectories.Clear();
1189 void AppDomain::ReleaseDomainBoundInfo()
1198 // Shutdown assemblies
1199 m_AssemblyCache.OnAppDomainUnload();
1201 AssemblyIterator i = IterateAssembliesEx( (AssemblyIterationFlags)(kIncludeFailedToLoad) );
1202 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1204 while (i.Next(pDomainAssembly.This()))
1206 pDomainAssembly->ReleaseManagedData();
1210 void AppDomain::ReleaseFiles()
1212 STANDARD_VM_CONTRACT;
1214 // Shutdown assemblies
1215 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
1216 kIncludeLoaded | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeLoading));
1217 CollectibleAssemblyHolder<DomainAssembly *> pAsm;
1219 while (i.Next(pAsm.This()))
1221 if (pAsm->GetCurrentAssembly() == NULL)
1223 // Might be domain neutral or not, but should have no live objects as it has not been
1224 // really loaded yet. Just reset it.
1225 _ASSERTE(FitsIn<DWORD>(i.GetIndex()));
1226 m_Assemblies.Set(this, static_cast<DWORD>(i.GetIndex()), NULL);
1227 delete pAsm.Extract();
1231 if (!pAsm->GetCurrentAssembly()->IsDomainNeutral())
1232 pAsm->ReleaseFiles();
1235 } // AppDomain::ReleaseFiles
1238 OBJECTREF* BaseDomain::AllocateObjRefPtrsInLargeTable(int nRequested, OBJECTREF** ppLazyAllocate, BOOL bCrossAD)
1245 PRECONDITION((nRequested > 0));
1246 INJECT_FAULT(COMPlusThrowOM(););
1250 if (ppLazyAllocate && *ppLazyAllocate)
1252 // Allocation already happened
1253 return *ppLazyAllocate;
1256 // Enter preemptive state, take the lock and go back to cooperative mode.
1258 CrstHolder ch(&m_LargeHeapHandleTableCrst);
1261 if (ppLazyAllocate && *ppLazyAllocate)
1263 // Allocation already happened
1264 return *ppLazyAllocate;
1267 // Make sure the large heap handle table is initialized.
1268 if (!m_pLargeHeapHandleTable)
1269 InitLargeHeapHandleTable();
1271 // Allocate the handles.
1272 OBJECTREF* result = m_pLargeHeapHandleTable->AllocateHandles(nRequested, bCrossAD);
1276 *ppLazyAllocate = result;
1282 #endif // CROSSGEN_COMPILE
1284 #endif // !DACCESS_COMPILE
1287 PTR_BaseDomain BaseDomain::ComputeBaseDomain(
1288 BaseDomain * pGenericDefinitionDomain, // the domain that owns the generic type or method
1289 Instantiation classInst, // the type arguments to the type (if any)
1290 Instantiation methodInst) // the type arguments to the method (if any)
1292 CONTRACT(PTR_BaseDomain)
1298 POSTCONDITION(CheckPointer(RETVAL));
1304 if (pGenericDefinitionDomain && pGenericDefinitionDomain->IsAppDomain())
1305 RETURN PTR_BaseDomain(pGenericDefinitionDomain);
1307 for (DWORD i = 0; i < classInst.GetNumArgs(); i++)
1309 PTR_BaseDomain pArgDomain = classInst[i].GetDomain();
1310 if (pArgDomain->IsAppDomain())
1314 for (DWORD i = 0; i < methodInst.GetNumArgs(); i++)
1316 PTR_BaseDomain pArgDomain = methodInst[i].GetDomain();
1317 if (pArgDomain->IsAppDomain())
1320 RETURN (pGenericDefinitionDomain ?
1321 PTR_BaseDomain(pGenericDefinitionDomain) :
1322 PTR_BaseDomain(SystemDomain::System()));
1325 PTR_BaseDomain BaseDomain::ComputeBaseDomain(TypeKey * pKey)
1337 if (pKey->GetKind() == ELEMENT_TYPE_CLASS)
1338 return BaseDomain::ComputeBaseDomain(pKey->GetModule()->GetDomain(),
1339 pKey->GetInstantiation());
1340 else if (pKey->GetKind() != ELEMENT_TYPE_FNPTR)
1341 return pKey->GetElementType().GetDomain();
1343 return BaseDomain::ComputeBaseDomain(NULL,Instantiation(pKey->GetRetAndArgTypes(), pKey->GetNumArgs()+1));
1350 #ifndef DACCESS_COMPILE
1352 // Insert class in the hash table
1353 void AppDomain::InsertClassForCLSID(MethodTable* pMT, BOOL fForceInsert /*=FALSE*/)
1360 INJECT_FAULT(COMPlusThrowOM(););
1366 // Ensure that registered classes are activated for allocation
1367 pMT->EnsureInstanceActive();
1369 // Note that it is possible for multiple classes to claim the same CLSID, and in such a
1370 // case it is arbitrary which one we will return for a future query for a given app domain.
1372 pMT->GetGuid(&cvid, fForceInsert);
1374 if (!IsEqualIID(cvid, GUID_NULL))
1376 //<TODO>@todo get a better key</TODO>
1377 LPVOID val = (LPVOID)pMT;
1379 LockHolder lh(this);
1381 if (LookupClass(cvid) != pMT)
1383 m_clsidHash.InsertValue(GetKeyFromGUID(&cvid), val);
1389 void AppDomain::InsertClassForCLSID(MethodTable* pMT, GUID *pGuid)
1394 PRECONDITION(CheckPointer(pMT));
1395 PRECONDITION(CheckPointer(pGuid));
1399 LPVOID val = (LPVOID)pMT;
1401 LockHolder lh(this);
1404 if (LookupClass(*cvid) != pMT)
1406 m_clsidHash.InsertValue(GetKeyFromGUID(pGuid), val);
1412 #endif // DACCESS_COMPILE
1414 #ifdef FEATURE_COMINTEROP
1416 #ifndef DACCESS_COMPILE
1417 void AppDomain::CacheTypeByName(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/)
1419 WRAPPER_NO_CONTRACT;
1420 LockHolder lh(this);
1421 CacheTypeByNameWorker(ssClassName, vCacheVersion, typeHandle, bFlags, bReplaceExisting);
1424 void AppDomain::CacheTypeByNameWorker(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/)
1430 PRECONDITION(!typeHandle.IsNull());
1434 NewArrayHolder<WCHAR> wzClassName(DuplicateStringThrowing(ssClassName.GetUnicode()));
1436 if (m_vNameToTypeMapVersion != vCacheVersion)
1439 if (m_pNameToTypeMap == nullptr)
1441 m_pNameToTypeMap = new NameToTypeMapTable();
1444 NameToTypeMapEntry e;
1445 e.m_key.m_wzName = wzClassName;
1446 e.m_key.m_cchName = ssClassName.GetCount();
1447 e.m_typeHandle = typeHandle;
1448 e.m_nEpoch = this->m_nEpoch;
1449 e.m_bFlags = bFlags;
1450 if (!bReplaceExisting)
1451 m_pNameToTypeMap->Add(e);
1453 m_pNameToTypeMap->AddOrReplace(e);
1455 wzClassName.SuppressRelease();
1457 #endif // DACCESS_COMPILE
1459 TypeHandle AppDomain::LookupTypeByName(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags)
1461 WRAPPER_NO_CONTRACT;
1462 LockHolder lh(this);
1463 return LookupTypeByNameWorker(ssClassName, pvCacheVersion, pbFlags);
1466 TypeHandle AppDomain::LookupTypeByNameWorker(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags)
1473 PRECONDITION(CheckPointer(pbFlags, NULL_OK));
1477 *pvCacheVersion = m_vNameToTypeMapVersion;
1479 if (m_pNameToTypeMap == nullptr)
1480 return TypeHandle(); // a null TypeHandle
1482 NameToTypeMapEntry::Key key;
1483 key.m_cchName = ssClassName.GetCount();
1484 key.m_wzName = ssClassName.GetUnicode();
1486 const NameToTypeMapEntry * pEntry = m_pNameToTypeMap->LookupPtr(key);
1488 return TypeHandle(); // a null TypeHandle
1490 if (pbFlags != NULL)
1491 *pbFlags = pEntry->m_bFlags;
1493 return pEntry->m_typeHandle;
1496 PTR_MethodTable AppDomain::LookupTypeByGuid(const GUID & guid)
1510 GuidToLPWSTR(guid, wszGuid, _countof(wszGuid));
1511 sGuid.Append(wszGuid);
1514 TypeHandle th = LookupTypeByName(sGuid, &ver, NULL);
1518 _ASSERTE(!th.IsTypeDesc());
1519 return th.AsMethodTable();
1522 #ifdef FEATURE_PREJIT
1525 // Next look in each ngen'ed image in turn
1526 AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)(
1527 kIncludeLoaded | kIncludeExecution));
1528 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1529 while (assemblyIterator.Next(pDomainAssembly.This()))
1531 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
1533 DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded);
1536 Module * pModule = i.GetLoadedModule();
1537 if (!pModule->HasNativeImage())
1539 _ASSERTE(!pModule->IsCollectible());
1540 PTR_MethodTable pMT = pModule->LookupTypeByGuid(guid);
1548 #endif // FEATURE_PREJIT
1552 #ifndef DACCESS_COMPILE
1553 void AppDomain::CacheWinRTTypeByGuid(TypeHandle typeHandle)
1560 PRECONDITION(!typeHandle.IsTypeDesc());
1561 PRECONDITION(CanCacheWinRTTypeByGuid(typeHandle));
1565 PTR_MethodTable pMT = typeHandle.AsMethodTable();
1568 if (pMT->GetGuidForWinRT(&guid))
1574 GuidToLPWSTR(guid, wszGuid, _countof(wszGuid));
1575 sGuid.Append(wszGuid);
1582 LockHolder lh(this);
1583 th = LookupTypeByNameWorker(sGuid, &vCacheVersion, &bFlags);
1587 // no other entry with the same GUID exists in the cache
1588 CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags);
1590 else if (typeHandle.AsMethodTable() != th.AsMethodTable() && th.IsProjectedFromWinRT())
1592 // If we found a native WinRT type cached with the same GUID, replace it.
1593 // Otherwise simply add the new mapping to the cache.
1594 CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags, TRUE);
1599 #endif // DACCESS_COMPILE
1601 void AppDomain::GetCachedWinRTTypes(
1602 SArray<PTR_MethodTable> * pTypes,
1603 SArray<GUID> * pGuids,
1616 LockHolder lh(this);
1618 for (auto it = m_pNameToTypeMap->Begin(), end = m_pNameToTypeMap->End();
1622 NameToTypeMapEntry entry = (NameToTypeMapEntry)(*it);
1623 TypeHandle th = entry.m_typeHandle;
1624 if (th.AsMethodTable() != NULL &&
1625 entry.m_key.m_wzName[0] == W('{') &&
1626 entry.m_nEpoch >= minEpoch)
1628 _ASSERTE(!th.IsTypeDesc());
1629 PTR_MethodTable pMT = th.AsMethodTable();
1630 // we're parsing the GUID value from the cache, because projected types do not cache the
1631 // COM GUID in their GetGuid() but rather the legacy GUID
1633 if (LPWSTRToGuid(&iid, entry.m_key.m_wzName, 38) && iid != GUID_NULL)
1635 pTypes->Append(pMT);
1636 pGuids->Append(iid);
1641 #ifdef FEATURE_PREJIT
1642 // Next look in each ngen'ed image in turn
1643 AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)(
1644 kIncludeLoaded | kIncludeExecution));
1645 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1646 while (assemblyIterator.Next(pDomainAssembly.This()))
1648 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
1650 DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded);
1653 Module * pModule = i.GetLoadedModule();
1654 if (!pModule->HasNativeImage())
1656 _ASSERTE(!pModule->IsCollectible());
1658 pModule->GetCachedWinRTTypes(pTypes, pGuids);
1661 #endif // FEATURE_PREJIT
1663 if (pCurEpoch != NULL)
1664 *pCurEpoch = m_nEpoch;
1668 #ifndef CROSSGEN_COMPILE
1669 #ifndef DACCESS_COMPILE
1671 void WinRTFactoryCacheTraits::OnDestructPerEntryCleanupAction(const WinRTFactoryCacheEntry& e)
1673 WRAPPER_NO_CONTRACT;
1674 if (e.m_pCtxEntry != NULL)
1676 e.m_pCtxEntry->Release();
1678 // the AD is going away, no need to destroy the OBJECTHANDLE
1681 void AppDomain::CacheWinRTFactoryObject(MethodTable *pClassMT, OBJECTREF *refFactory, LPVOID lpCtxCookie)
1688 PRECONDITION(CheckPointer(pClassMT));
1692 CtxEntryHolder pNewCtxEntry;
1693 if (lpCtxCookie != NULL)
1695 // We don't want to insert the context cookie in the cache because it's just an address
1696 // of an internal COM data structure which will be freed when the apartment is torn down.
1697 // What's worse, if another apartment is later created, its context cookie may have exactly
1698 // the same value leading to incorrect cache hits. We'll use our CtxEntry instead which
1699 // is ref-counted and keeps the COM data structure alive even after the apartment ceases
1701 pNewCtxEntry = CtxEntryCache::GetCtxEntryCache()->FindCtxEntry(lpCtxCookie, GetThread());
1704 WinRTFactoryCacheLockHolder lh(this);
1706 if (m_pWinRTFactoryCache == nullptr)
1708 m_pWinRTFactoryCache = new WinRTFactoryCache();
1711 WinRTFactoryCacheEntry *pEntry = const_cast<WinRTFactoryCacheEntry*>(m_pWinRTFactoryCache->LookupPtr(pClassMT));
1715 // No existing entry for this cache
1718 WinRTFactoryCacheEntry e;
1720 OBJECTHANDLEHolder ohNewHandle(CreateHandle(*refFactory));
1723 e.m_pCtxEntry = pNewCtxEntry;
1724 e.m_ohFactoryObject = ohNewHandle;
1726 m_pWinRTFactoryCache->Add(e);
1728 // suppress release of the CtxEntry and handle after we successfully inserted the new entry
1729 pNewCtxEntry.SuppressRelease();
1730 ohNewHandle.SuppressRelease();
1737 // release the old CtxEntry and update the entry
1738 CtxEntry *pTemp = pNewCtxEntry.Extract();
1739 pNewCtxEntry = pEntry->m_pCtxEntry;
1740 pEntry->m_pCtxEntry = pTemp;
1742 IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
1743 mgr->StoreObjectInHandle(pEntry->m_ohFactoryObject, OBJECTREFToObject(*refFactory));
1747 OBJECTREF AppDomain::LookupWinRTFactoryObject(MethodTable *pClassMT, LPVOID lpCtxCookie)
1754 PRECONDITION(CheckPointer(pClassMT));
1755 PRECONDITION(CheckPointer(m_pWinRTFactoryCache, NULL_OK));
1760 if (m_pWinRTFactoryCache == nullptr)
1764 // Retrieve cached factory
1766 WinRTFactoryCacheLockHolder lh(this);
1768 const WinRTFactoryCacheEntry *pEntry = m_pWinRTFactoryCache->LookupPtr(pClassMT);
1773 // Ignore factories from a different context, unless lpCtxCookie == NULL,
1774 // which means the factory is free-threaded
1775 // Note that we cannot touch the RCW to retrieve cookie at this point
1776 // because the RCW might belong to a STA thread and that STA thread might die
1777 // and take the RCW with it. Therefore we have to save cookie in this cache
1779 if (pEntry->m_pCtxEntry == NULL || pEntry->m_pCtxEntry->GetCtxCookie() == lpCtxCookie)
1780 return ObjectFromHandle(pEntry->m_ohFactoryObject);
1785 void AppDomain::RemoveWinRTFactoryObjects(LPVOID pCtxCookie)
1795 if (m_pWinRTFactoryCache == nullptr)
1798 // helper class for delayed CtxEntry cleanup
1799 class CtxEntryListReleaseHolder
1802 CQuickArrayList<CtxEntry *> m_list;
1804 ~CtxEntryListReleaseHolder()
1814 for (SIZE_T i = 0; i < m_list.Size(); i++)
1816 m_list[i]->Release();
1819 } ctxEntryListReleaseHolder;
1823 WinRTFactoryCacheLockHolder lh(this);
1825 // Go through the hash table and remove items in the given context
1826 for (WinRTFactoryCache::Iterator it = m_pWinRTFactoryCache->Begin(); it != m_pWinRTFactoryCache->End(); it++)
1828 if (it->m_pCtxEntry != NULL && it->m_pCtxEntry->GetCtxCookie() == pCtxCookie)
1830 // Releasing the CtxEntry may trigger GC which we can't do under the lock so we push
1831 // it on our local list and release them all after we're done iterating the hashtable.
1832 ctxEntryListReleaseHolder.m_list.Push(it->m_pCtxEntry);
1834 DestroyHandle(it->m_ohFactoryObject);
1835 m_pWinRTFactoryCache->Remove(it);
1841 OBJECTREF AppDomain::GetMissingObject()
1854 FieldDesc *pValueFD = MscorlibBinder::GetField(FIELD__MISSING__VALUE);
1856 pValueFD->CheckRunClassInitThrowing();
1858 // Retrieve the value static field and store it.
1859 OBJECTHANDLE hndMissing = CreateHandle(pValueFD->GetStaticOBJECTREF());
1861 if (FastInterlockCompareExchangePointer(&m_hndMissing, hndMissing, NULL) != NULL)
1863 // Exchanged failed. The m_hndMissing did not equal NULL and was returned.
1864 DestroyHandle(hndMissing);
1868 return ObjectFromHandle(m_hndMissing);
1871 #endif // DACCESS_COMPILE
1872 #endif //CROSSGEN_COMPILE
1873 #endif // FEATURE_COMINTEROP
1875 #ifndef DACCESS_COMPILE
1877 EEMarshalingData *BaseDomain::GetMarshalingData()
1879 CONTRACT (EEMarshalingData*)
1884 INJECT_FAULT(COMPlusThrowOM());
1885 POSTCONDITION(CheckPointer(m_pMarshalingData));
1889 if (!m_pMarshalingData)
1892 CrstHolder holder(&m_InteropDataCrst);
1894 if (!m_pMarshalingData)
1896 LoaderHeap* pHeap = GetLoaderAllocator()->GetLowFrequencyHeap();
1897 m_pMarshalingData = new (pHeap) EEMarshalingData(this, pHeap, &m_DomainCrst);
1901 RETURN m_pMarshalingData;
1904 void BaseDomain::DeleteMarshalingData()
1914 // We are in shutdown - no need to take any lock
1915 if (m_pMarshalingData)
1917 delete m_pMarshalingData;
1918 m_pMarshalingData = NULL;
1922 #ifndef CROSSGEN_COMPILE
1924 STRINGREF *BaseDomain::IsStringInterned(STRINGREF *pString)
1931 PRECONDITION(CheckPointer(pString));
1932 INJECT_FAULT(COMPlusThrowOM(););
1936 return GetLoaderAllocator()->IsStringInterned(pString);
1939 STRINGREF *BaseDomain::GetOrInternString(STRINGREF *pString)
1946 PRECONDITION(CheckPointer(pString));
1947 INJECT_FAULT(COMPlusThrowOM(););
1951 return GetLoaderAllocator()->GetOrInternString(pString);
1954 void BaseDomain::InitLargeHeapHandleTable()
1961 PRECONDITION(m_pLargeHeapHandleTable==NULL);
1962 INJECT_FAULT(COMPlusThrowOM(););
1966 m_pLargeHeapHandleTable = new LargeHeapHandleTable(this, STATIC_OBJECT_TABLE_BUCKET_SIZE);
1969 m_pLargeHeapHandleTable->RegisterCrstDebug(&m_LargeHeapHandleTableCrst);
1973 #ifdef FEATURE_COMINTEROP
1974 MethodTable* AppDomain::GetLicenseInteropHelperMethodTable()
1983 if(m_pLicenseInteropHelperMT == NULL)
1985 // Do this work outside of the lock so we don't have an unbreakable lock condition
1987 TypeHandle licenseMgrTypeHnd;
1988 MethodDescCallSite loadLM(METHOD__MARSHAL__LOAD_LICENSE_MANAGER);
1990 licenseMgrTypeHnd = (MethodTable*) loadLM.Call_RetLPVOID((ARG_SLOT*)NULL);
1993 // Look up this method by name, because the type is actually declared in System.dll. <TODO>@todo: why?</TODO>
1996 MethodDesc *pGetLIHMD = MemberLoader::FindMethod(licenseMgrTypeHnd.AsMethodTable(),
1997 "GetLicenseInteropHelperType", &gsig_SM_Void_RetIntPtr);
1998 _ASSERTE(pGetLIHMD);
2000 TypeHandle lihTypeHnd;
2002 MethodDescCallSite getLIH(pGetLIHMD);
2003 lihTypeHnd = (MethodTable*) getLIH.Call_RetLPVOID((ARG_SLOT*)NULL);
2005 BaseDomain::LockHolder lh(this);
2007 if(m_pLicenseInteropHelperMT == NULL)
2008 m_pLicenseInteropHelperMT = lihTypeHnd.AsMethodTable();
2010 return m_pLicenseInteropHelperMT;
2013 COMorRemotingFlag AppDomain::GetComOrRemotingFlag()
2023 // 0. check if the value is already been set
2024 if (m_COMorRemotingFlag != COMorRemoting_NotInitialized)
2025 return m_COMorRemotingFlag;
2027 // 1. check whether the process is AppX
2028 if (AppX::IsAppXProcess())
2030 // do not use Remoting in AppX
2031 m_COMorRemotingFlag = COMorRemoting_COM;
2032 return m_COMorRemotingFlag;
2035 // 2. check the xml file
2036 m_COMorRemotingFlag = GetPreferComInsteadOfManagedRemotingFromConfigFile();
2037 if (m_COMorRemotingFlag != COMorRemoting_NotInitialized)
2039 return m_COMorRemotingFlag;
2042 // 3. check the global setting
2043 if (NULL != g_pConfig && g_pConfig->ComInsteadOfManagedRemoting())
2045 m_COMorRemotingFlag = COMorRemoting_COM;
2049 m_COMorRemotingFlag = COMorRemoting_Remoting;
2052 return m_COMorRemotingFlag;
2055 BOOL AppDomain::GetPreferComInsteadOfManagedRemoting()
2057 WRAPPER_NO_CONTRACT;
2059 return (GetComOrRemotingFlag() == COMorRemoting_COM);
2062 COMorRemotingFlag AppDomain::GetPreferComInsteadOfManagedRemotingFromConfigFile()
2072 return COMorRemoting_COM;
2074 #endif // FEATURE_COMINTEROP
2076 #endif // CROSSGEN_COMPILE
2078 //*****************************************************************************
2079 //*****************************************************************************
2080 //*****************************************************************************
2082 void *SystemDomain::operator new(size_t size, void *pInPlace)
2084 LIMITED_METHOD_CONTRACT;
2089 void SystemDomain::operator delete(void *pMem)
2091 LIMITED_METHOD_CONTRACT;
2092 // Do nothing - new() was in-place
2096 void SystemDomain::SetCompilationOverrides(BOOL fForceDebug,
2097 BOOL fForceProfiling,
2098 BOOL fForceInstrument)
2100 LIMITED_METHOD_CONTRACT;
2101 s_fForceDebug = fForceDebug;
2102 s_fForceProfiling = fForceProfiling;
2103 s_fForceInstrument = fForceInstrument;
2106 #endif //!DACCESS_COMPILE
2108 void SystemDomain::GetCompilationOverrides(BOOL * fForceDebug,
2109 BOOL * fForceProfiling,
2110 BOOL * fForceInstrument)
2112 LIMITED_METHOD_DAC_CONTRACT;
2113 *fForceDebug = s_fForceDebug;
2114 *fForceProfiling = s_fForceProfiling;
2115 *fForceInstrument = s_fForceInstrument;
2118 #ifndef DACCESS_COMPILE
2120 void SystemDomain::Attach()
2127 PRECONDITION(m_pSystemDomain == NULL);
2128 INJECT_FAULT(COMPlusThrowOM(););
2132 #ifndef CROSSGEN_COMPILE
2133 // Initialize stub managers
2134 PrecodeStubManager::Init();
2135 DelegateInvokeStubManager::Init();
2136 JumpStubStubManager::Init();
2137 RangeSectionStubManager::Init();
2138 ILStubManager::Init();
2139 InteropDispatchStubManager::Init();
2140 StubLinkStubManager::Init();
2142 ThunkHeapStubManager::Init();
2144 TailCallStubManager::Init();
2146 PerAppDomainTPCountList::InitAppDomainIndexList();
2147 #endif // CROSSGEN_COMPILE
2149 m_appDomainIndexList.Init();
2150 m_appDomainIdList.Init();
2152 m_SystemDomainCrst.Init(CrstSystemDomain, (CrstFlags)(CRST_REENTRANCY | CRST_TAKEN_DURING_SHUTDOWN));
2153 m_DelayedUnloadCrst.Init(CrstSystemDomainDelayedUnloadList, CRST_UNSAFE_COOPGC);
2155 // Initialize the ID dispenser that is used for domain neutral module IDs
2156 g_pModuleIndexDispenser = new IdDispenser();
2158 // Create the global SystemDomain and initialize it.
2159 m_pSystemDomain = new (&g_pSystemDomainMemory[0]) SystemDomain();
2160 // No way it can fail since g_pSystemDomainMemory is a static array.
2161 CONSISTENCY_CHECK(CheckPointer(m_pSystemDomain));
2163 LOG((LF_CLASSLOADER,
2165 "Created system domain at %p\n",
2168 // We need to initialize the memory pools etc. for the system domain.
2169 m_pSystemDomain->BaseDomain::Init(); // Setup the memory heaps
2171 // Create the default domain
2172 m_pSystemDomain->CreateDefaultDomain();
2173 SharedDomain::Attach();
2175 // Each domain gets its own ReJitManager, and ReJitManager has its own static
2176 // initialization to run
2177 ReJitManager::InitStatic();
2180 #ifndef CROSSGEN_COMPILE
2182 void SystemDomain::DetachBegin()
2184 WRAPPER_NO_CONTRACT;
2185 // Shut down the domain and its children (but don't deallocate anything just
2188 // TODO: we should really not running managed DLLMain during process detach.
2189 if (GetThread() == NULL)
2195 m_pSystemDomain->Stop();
2198 void SystemDomain::DetachEnd()
2207 // Shut down the domain and its children (but don't deallocate anything just
2212 m_pSystemDomain->ClearFusionContext();
2213 if (m_pSystemDomain->m_pDefaultDomain)
2214 m_pSystemDomain->m_pDefaultDomain->ClearFusionContext();
2218 void SystemDomain::Stop()
2220 WRAPPER_NO_CONTRACT;
2221 AppDomainIterator i(TRUE);
2224 if (i.GetDomain()->m_Stage < AppDomain::STAGE_CLEARED)
2225 i.GetDomain()->Stop();
2229 void SystemDomain::Terminate() // bNotifyProfiler is ignored
2239 // This ignores the refences and terminates the appdomains
2240 AppDomainIterator i(FALSE);
2244 delete i.GetDomain();
2245 // Keep the iterator from Releasing the current domain
2246 i.m_pCurrent = NULL;
2249 if (m_pSystemFile != NULL) {
2250 m_pSystemFile->Release();
2251 m_pSystemFile = NULL;
2254 m_pSystemAssembly = NULL;
2257 delete[] m_pwDevpath;
2263 if (m_pGlobalStringLiteralMap) {
2264 delete m_pGlobalStringLiteralMap;
2265 m_pGlobalStringLiteralMap = NULL;
2269 SharedDomain::Detach();
2271 BaseDomain::Terminate();
2273 #ifdef FEATURE_COMINTEROP
2274 if (g_pRCWCleanupList != NULL)
2275 delete g_pRCWCleanupList;
2276 #endif // FEATURE_COMINTEROP
2277 m_GlobalAllocator.Terminate();
2281 void SystemDomain::PreallocateSpecialObjects()
2288 INJECT_FAULT(COMPlusThrowOM(););
2292 _ASSERTE(g_pPreallocatedSentinelObject == NULL);
2294 OBJECTREF pPreallocatedSentinalObject = AllocateObject(g_pObjectClass);
2295 #if CHECK_APP_DOMAIN_LEAKS
2296 pPreallocatedSentinalObject->SetSyncBlockAppDomainAgile();
2298 g_pPreallocatedSentinelObject = CreatePinningHandle( pPreallocatedSentinalObject );
2300 #ifdef FEATURE_PREJIT
2301 if (SystemModule()->HasNativeImage())
2303 CORCOMPILE_EE_INFO_TABLE *pEEInfo = SystemModule()->GetNativeImage()->GetNativeEEInfoTable();
2304 pEEInfo->emptyString = (CORINFO_Object **)StringObject::GetEmptyStringRefPtr();
2309 void SystemDomain::CreatePreallocatedExceptions()
2316 INJECT_FAULT(COMPlusThrowOM(););
2320 EXCEPTIONREF pBaseException = (EXCEPTIONREF)AllocateObject(g_pExceptionClass);
2321 pBaseException->SetHResult(COR_E_EXCEPTION);
2322 pBaseException->SetXCode(EXCEPTION_COMPLUS);
2323 _ASSERTE(g_pPreallocatedBaseException == NULL);
2324 g_pPreallocatedBaseException = CreateHandle(pBaseException);
2327 EXCEPTIONREF pOutOfMemory = (EXCEPTIONREF)AllocateObject(g_pOutOfMemoryExceptionClass);
2328 pOutOfMemory->SetHResult(COR_E_OUTOFMEMORY);
2329 pOutOfMemory->SetXCode(EXCEPTION_COMPLUS);
2330 _ASSERTE(g_pPreallocatedOutOfMemoryException == NULL);
2331 g_pPreallocatedOutOfMemoryException = CreateHandle(pOutOfMemory);
2334 EXCEPTIONREF pStackOverflow = (EXCEPTIONREF)AllocateObject(g_pStackOverflowExceptionClass);
2335 pStackOverflow->SetHResult(COR_E_STACKOVERFLOW);
2336 pStackOverflow->SetXCode(EXCEPTION_COMPLUS);
2337 _ASSERTE(g_pPreallocatedStackOverflowException == NULL);
2338 g_pPreallocatedStackOverflowException = CreateHandle(pStackOverflow);
2341 EXCEPTIONREF pExecutionEngine = (EXCEPTIONREF)AllocateObject(g_pExecutionEngineExceptionClass);
2342 pExecutionEngine->SetHResult(COR_E_EXECUTIONENGINE);
2343 pExecutionEngine->SetXCode(EXCEPTION_COMPLUS);
2344 _ASSERTE(g_pPreallocatedExecutionEngineException == NULL);
2345 g_pPreallocatedExecutionEngineException = CreateHandle(pExecutionEngine);
2348 EXCEPTIONREF pRudeAbortException = (EXCEPTIONREF)AllocateObject(g_pThreadAbortExceptionClass);
2349 #if CHECK_APP_DOMAIN_LEAKS
2350 pRudeAbortException->SetSyncBlockAppDomainAgile();
2352 pRudeAbortException->SetHResult(COR_E_THREADABORTED);
2353 pRudeAbortException->SetXCode(EXCEPTION_COMPLUS);
2354 _ASSERTE(g_pPreallocatedRudeThreadAbortException == NULL);
2355 g_pPreallocatedRudeThreadAbortException = CreateHandle(pRudeAbortException);
2358 EXCEPTIONREF pAbortException = (EXCEPTIONREF)AllocateObject(g_pThreadAbortExceptionClass);
2359 #if CHECK_APP_DOMAIN_LEAKS
2360 pAbortException->SetSyncBlockAppDomainAgile();
2362 pAbortException->SetHResult(COR_E_THREADABORTED);
2363 pAbortException->SetXCode(EXCEPTION_COMPLUS);
2364 _ASSERTE(g_pPreallocatedThreadAbortException == NULL);
2365 g_pPreallocatedThreadAbortException = CreateHandle( pAbortException );
2367 #endif // CROSSGEN_COMPILE
2369 void SystemDomain::Init()
2371 STANDARD_VM_CONTRACT;
2379 "sizeof(EEClass) = %d\n"
2380 "sizeof(MethodTable) = %d\n"
2381 "sizeof(MethodDesc)= %d\n"
2382 "sizeof(FieldDesc) = %d\n"
2383 "sizeof(Module) = %d\n",
2385 sizeof(MethodTable),
2392 // The base domain is initialized in SystemDomain::Attach()
2393 // to allow stub caches to use the memory pool. Do not
2394 // initialze it here!
2396 #ifndef CROSSGEN_COMPILE
2398 Context *curCtx = GetCurrentContext();
2401 _ASSERTE(curCtx->GetDomain() != NULL);
2404 #ifdef FEATURE_PREJIT
2405 if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_ZapDisable) != 0)
2406 g_fAllowNativeImages = false;
2409 m_pSystemFile = NULL;
2410 m_pSystemAssembly = NULL;
2415 // Get the install directory so we can find mscorlib
2416 hr = GetInternalSystemDirectory(NULL, &size);
2417 if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
2420 // GetInternalSystemDirectory returns a size, including the null!
2421 WCHAR *buffer = m_SystemDirectory.OpenUnicodeBuffer(size-1);
2422 IfFailThrow(GetInternalSystemDirectory(buffer, &size));
2423 m_SystemDirectory.CloseBuffer();
2424 m_SystemDirectory.Normalize();
2426 // At this point m_SystemDirectory should already be canonicalized
2429 m_BaseLibrary.Append(m_SystemDirectory);
2430 if (!m_BaseLibrary.EndsWith(DIRECTORY_SEPARATOR_CHAR_W))
2432 m_BaseLibrary.Append(DIRECTORY_SEPARATOR_CHAR_W);
2434 m_BaseLibrary.Append(g_pwBaseLibrary);
2435 m_BaseLibrary.Normalize();
2437 LoadBaseSystemClasses();
2440 // We are about to start allocating objects, so we must be in cooperative mode.
2441 // However, many of the entrypoints to the system (DllGetClassObject and all
2442 // N/Direct exports) get called multiple times. Sometimes they initialize the EE,
2443 // but generally they remain in preemptive mode. So we really want to push/pop
2447 #ifndef CROSSGEN_COMPILE
2448 if (!NingenEnabled())
2450 CreatePreallocatedExceptions();
2452 PreallocateSpecialObjects();
2456 // Finish loading mscorlib now.
2457 m_pSystemAssembly->GetDomainAssembly()->EnsureActive();
2461 BOOL fPause = EEConfig::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_PauseOnLoad, FALSE);
2465 ClrSleepEx(20, TRUE);
2470 #ifndef CROSSGEN_COMPILE
2471 void SystemDomain::LazyInitGlobalStringLiteralMap()
2478 INJECT_FAULT(COMPlusThrowOM(););
2482 // Allocate the global string literal map.
2483 NewHolder<GlobalStringLiteralMap> pGlobalStringLiteralMap(new GlobalStringLiteralMap());
2485 // Initialize the global string literal map.
2486 pGlobalStringLiteralMap->Init();
2488 if (InterlockedCompareExchangeT<GlobalStringLiteralMap *>(&m_pGlobalStringLiteralMap, pGlobalStringLiteralMap, NULL) == NULL)
2490 pGlobalStringLiteralMap.SuppressRelease();
2494 void AppDomain::CreateADUnloadStartEvent()
2505 g_pUnloadStartEvent = new CLREvent();
2506 g_pUnloadStartEvent->CreateAutoEvent(FALSE);
2509 /*static*/ void SystemDomain::EnumAllStaticGCRefs(promote_func* fn, ScanContext* sc)
2519 // We don't do a normal AppDomainIterator because we can't take the SystemDomain lock from
2521 // We're only supposed to call this from a Server GC. We're walking here m_appDomainIdList
2522 // m_appDomainIdList will have an AppDomain* or will be NULL. So the only danger is if we
2523 // Fetch an AppDomain and then in some other thread the AppDomain is deleted.
2525 // If the thread deleting the AppDomain (AppDomain::~AppDomain)was in Preemptive mode
2526 // while doing SystemDomain::EnumAllStaticGCRefs we will issue a GCX_COOP(), which will wait
2527 // for the GC to finish, so we are safe
2529 // If the thread is in cooperative mode, it must have been suspended for the GC so a delete
2532 _ASSERTE(GCHeapUtilities::IsGCInProgress() &&
2533 GCHeapUtilities::IsServerHeap() &&
2534 IsGCSpecialThread());
2536 SystemDomain* sysDomain = SystemDomain::System();
2540 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2541 for (i = 0 ; i < count ; i++)
2543 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2544 if (pAppDomain && pAppDomain->IsActive() && !pAppDomain->IsUnloading())
2546 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
2549 sc->pCurrentDomain = pAppDomain;
2551 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
2552 pAppDomain->EnumStaticGCRefs(fn, sc);
2560 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
2561 void SystemDomain::ResetADSurvivedBytes()
2571 _ASSERTE(GCHeapUtilities::IsGCInProgress());
2573 SystemDomain* sysDomain = SystemDomain::System();
2577 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2578 for (i = 0 ; i < count ; i++)
2580 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2581 if (pAppDomain && pAppDomain->IsUserActive())
2583 pAppDomain->ResetSurvivedBytes();
2591 ULONGLONG SystemDomain::GetADSurvivedBytes()
2601 SystemDomain* sysDomain = SystemDomain::System();
2602 ULONGLONG ullTotalADSurvived = 0;
2606 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2607 for (i = 0 ; i < count ; i++)
2609 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2610 if (pAppDomain && pAppDomain->IsUserActive())
2612 ULONGLONG ullSurvived = pAppDomain->GetSurvivedBytes();
2613 ullTotalADSurvived += ullSurvived;
2618 return ullTotalADSurvived;
2621 void SystemDomain::RecordTotalSurvivedBytes(size_t totalSurvivedBytes)
2631 m_totalSurvivedBytes = totalSurvivedBytes;
2633 SystemDomain* sysDomain = SystemDomain::System();
2637 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2638 for (i = 0 ; i < count ; i++)
2640 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2641 if (pAppDomain && pAppDomain->IsUserActive())
2643 FireEtwAppDomainMemSurvived((ULONGLONG)pAppDomain, pAppDomain->GetSurvivedBytes(), totalSurvivedBytes, GetClrInstanceId());
2650 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
2652 // Only called when EE is suspended.
2653 DWORD SystemDomain::GetTotalNumSizedRefHandles()
2663 SystemDomain* sysDomain = SystemDomain::System();
2664 DWORD dwTotalNumSizedRefHandles = 0;
2668 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2669 for (i = 0 ; i < count ; i++)
2671 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2672 if (pAppDomain && pAppDomain->IsActive() && !pAppDomain->IsUnloading())
2674 dwTotalNumSizedRefHandles += pAppDomain->GetNumSizedRefHandles();
2679 return dwTotalNumSizedRefHandles;
2681 #endif // CROSSGEN_COMPILE
2683 void SystemDomain::LoadBaseSystemClasses()
2685 STANDARD_VM_CONTRACT;
2687 ETWOnStartup(LdSysBases_V1, LdSysBasesEnd_V1);
2690 m_pSystemFile = PEAssembly::OpenSystem(NULL);
2692 // Only partially load the system assembly. Other parts of the code will want to access
2693 // the globals in this function before finishing the load.
2694 m_pSystemAssembly = DefaultDomain()->LoadDomainAssembly(NULL, m_pSystemFile, FILE_LOAD_POST_LOADLIBRARY)->GetCurrentAssembly();
2696 // Set up binder for mscorlib
2697 MscorlibBinder::AttachModule(m_pSystemAssembly->GetManifestModule());
2700 g_pObjectClass = MscorlibBinder::GetClass(CLASS__OBJECT);
2702 // Now that ObjectClass is loaded, we can set up
2703 // the system for finalizers. There is no point in deferring this, since we need
2704 // to know this before we allocate our first object.
2705 g_pObjectFinalizerMD = MscorlibBinder::GetMethod(METHOD__OBJECT__FINALIZE);
2708 g_pCanonMethodTableClass = MscorlibBinder::GetClass(CLASS____CANON);
2710 // NOTE: !!!IMPORTANT!!! ValueType and Enum MUST be loaded one immediately after
2711 // the other, because we have coded MethodTable::IsChildValueType
2712 // in such a way that it depends on this behaviour.
2713 // Load the ValueType class
2714 g_pValueTypeClass = MscorlibBinder::GetClass(CLASS__VALUE_TYPE);
2716 // Load the enum class
2717 g_pEnumClass = MscorlibBinder::GetClass(CLASS__ENUM);
2718 _ASSERTE(!g_pEnumClass->IsValueType());
2720 // Load System.RuntimeType
2721 g_pRuntimeTypeClass = MscorlibBinder::GetClass(CLASS__CLASS);
2722 _ASSERTE(g_pRuntimeTypeClass->IsFullyLoaded());
2725 g_pArrayClass = MscorlibBinder::GetClass(CLASS__ARRAY);
2727 // Calling a method on IList<T> for an array requires redirection to a method on
2728 // the SZArrayHelper class. Retrieving such methods means calling
2729 // GetActualImplementationForArrayGenericIListMethod, which calls FetchMethod for
2730 // the corresponding method on SZArrayHelper. This basically results in a class
2731 // load due to a method call, which the debugger cannot handle, so we pre-load
2732 // the SZArrayHelper class here.
2733 g_pSZArrayHelperClass = MscorlibBinder::GetClass(CLASS__SZARRAYHELPER);
2735 // Load ByReference class
2737 // NOTE: ByReference<T> must be the first by-ref-like system type to be loaded,
2738 // because MethodTable::ClassifyEightBytesWithManagedLayout depends on it.
2739 g_pByReferenceClass = MscorlibBinder::GetClass(CLASS__BYREFERENCE);
2741 // Load Nullable class
2742 g_pNullableClass = MscorlibBinder::GetClass(CLASS__NULLABLE);
2744 // Load the Object array class.
2745 g_pPredefinedArrayTypes[ELEMENT_TYPE_OBJECT] = ClassLoader::LoadArrayTypeThrowing(TypeHandle(g_pObjectClass)).AsArray();
2747 // We have delayed allocation of mscorlib's static handles until we load the object class
2748 MscorlibBinder::GetModule()->AllocateRegularStaticHandles(DefaultDomain());
2750 g_TypedReferenceMT = MscorlibBinder::GetClass(CLASS__TYPED_REFERENCE);
2752 // Make sure all primitive types are loaded
2753 for (int et = ELEMENT_TYPE_VOID; et <= ELEMENT_TYPE_R8; et++)
2754 MscorlibBinder::LoadPrimitiveType((CorElementType)et);
2756 MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_I);
2757 MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_U);
2759 // unfortunately, the following cannot be delay loaded since the jit
2760 // uses it to compute method attributes within a function that cannot
2761 // handle Complus exception and the following call goes through a path
2762 // where a complus exception can be thrown. It is unfortunate, because
2763 // we know that the delegate class and multidelegate class are always
2764 // guaranteed to be found.
2765 g_pDelegateClass = MscorlibBinder::GetClass(CLASS__DELEGATE);
2766 g_pMulticastDelegateClass = MscorlibBinder::GetClass(CLASS__MULTICAST_DELEGATE);
2768 // used by IsImplicitInterfaceOfSZArray
2769 MscorlibBinder::GetClass(CLASS__IENUMERABLEGENERIC);
2770 MscorlibBinder::GetClass(CLASS__ICOLLECTIONGENERIC);
2771 MscorlibBinder::GetClass(CLASS__ILISTGENERIC);
2772 MscorlibBinder::GetClass(CLASS__IREADONLYCOLLECTIONGENERIC);
2773 MscorlibBinder::GetClass(CLASS__IREADONLYLISTGENERIC);
2776 g_pStringClass = MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_STRING);
2777 _ASSERTE(g_pStringClass->GetBaseSize() == ObjSizeOf(StringObject)+sizeof(WCHAR));
2778 _ASSERTE(g_pStringClass->GetComponentSize() == 2);
2780 // Used by Buffer::BlockCopy
2781 g_pByteArrayMT = ClassLoader::LoadArrayTypeThrowing(
2782 TypeHandle(MscorlibBinder::GetElementType(ELEMENT_TYPE_U1))).AsArray()->GetMethodTable();
2784 #ifndef CROSSGEN_COMPILE
2785 ECall::PopulateManagedStringConstructors();
2786 #endif // CROSSGEN_COMPILE
2788 g_pExceptionClass = MscorlibBinder::GetClass(CLASS__EXCEPTION);
2789 g_pOutOfMemoryExceptionClass = MscorlibBinder::GetException(kOutOfMemoryException);
2790 g_pStackOverflowExceptionClass = MscorlibBinder::GetException(kStackOverflowException);
2791 g_pExecutionEngineExceptionClass = MscorlibBinder::GetException(kExecutionEngineException);
2792 g_pThreadAbortExceptionClass = MscorlibBinder::GetException(kThreadAbortException);
2795 // used by gc to handle predefined agility checking
2796 g_pThreadClass = MscorlibBinder::GetClass(CLASS__THREAD);
2798 #ifdef FEATURE_COMINTEROP
2799 g_pBaseCOMObject = MscorlibBinder::GetClass(CLASS__COM_OBJECT);
2800 g_pBaseRuntimeClass = MscorlibBinder::GetClass(CLASS__RUNTIME_CLASS);
2802 MscorlibBinder::GetClass(CLASS__IDICTIONARYGENERIC);
2803 MscorlibBinder::GetClass(CLASS__IREADONLYDICTIONARYGENERIC);
2804 MscorlibBinder::GetClass(CLASS__ATTRIBUTE);
2805 MscorlibBinder::GetClass(CLASS__EVENT_HANDLERGENERIC);
2807 MscorlibBinder::GetClass(CLASS__IENUMERABLE);
2808 MscorlibBinder::GetClass(CLASS__ICOLLECTION);
2809 MscorlibBinder::GetClass(CLASS__ILIST);
2810 MscorlibBinder::GetClass(CLASS__IDISPOSABLE);
2813 WinRTInterfaceRedirector::VerifyRedirectedInterfaceStubs();
2817 #ifdef FEATURE_ICASTABLE
2818 g_pICastableInterface = MscorlibBinder::GetClass(CLASS__ICASTABLE);
2819 #endif // FEATURE_ICASTABLE
2821 // Load a special marker method used to detect Constrained Execution Regions
2823 g_pExecuteBackoutCodeHelperMethod = MscorlibBinder::GetMethod(METHOD__RUNTIME_HELPERS__EXECUTE_BACKOUT_CODE_HELPER);
2825 // Make sure that FCall mapping for Monitor.Enter is initialized. We need it in case Monitor.Enter is used only as JIT helper.
2826 // For more details, see comment in code:JITutil_MonEnterWorker around "__me = GetEEFuncEntryPointMacro(JIT_MonEnter)".
2827 ECall::GetFCallImpl(MscorlibBinder::GetMethod(METHOD__MONITOR__ENTER));
2829 #ifdef PROFILING_SUPPORTED
2830 // Note that g_profControlBlock.fBaseSystemClassesLoaded must be set to TRUE only after
2831 // all base system classes are loaded. Profilers are not allowed to call any type-loading
2832 // APIs until g_profControlBlock.fBaseSystemClassesLoaded is TRUE. It is important that
2833 // all base system classes need to be loaded before profilers can trigger the type loading.
2834 g_profControlBlock.fBaseSystemClassesLoaded = TRUE;
2835 #endif // PROFILING_SUPPORTED
2837 #if defined(_DEBUG) && !defined(CROSSGEN_COMPILE)
2838 if (!NingenEnabled())
2844 #if defined(HAVE_GCCOVER) && defined(FEATURE_PREJIT)
2845 if (GCStress<cfg_instr_ngen>::IsEnabled())
2847 // Setting up gc coverage requires the base system classes
2848 // to be initialized. So we have deferred it until now for mscorlib.
2849 Module *pModule = MscorlibBinder::GetModule();
2850 _ASSERTE(pModule->IsSystem());
2851 if(pModule->HasNativeImage())
2853 SetupGcCoverageForNativeImage(pModule);
2856 #endif // defined(HAVE_GCCOVER) && !defined(FEATURE_PREJIT)
2860 void SystemDomain::LoadDomain(AppDomain *pDomain)
2867 PRECONDITION(CheckPointer(System()));
2868 INJECT_FAULT(COMPlusThrowOM(););
2872 pDomain->SetCanUnload(); // by default can unload any domain
2873 SystemDomain::System()->AddDomain(pDomain);
2876 ADIndex SystemDomain::GetNewAppDomainIndex(AppDomain *pAppDomain)
2878 STANDARD_VM_CONTRACT;
2880 DWORD count = m_appDomainIndexList.GetCount();
2886 // So that we can keep AD index inside object header.
2887 // We do not want to create syncblock unless needed.
2894 // Look for an unused index. Note that in a checked build,
2895 // we never reuse indexes - this makes it easier to tell
2896 // when we are looking at a stale app domain.
2899 i = m_appDomainIndexList.FindElement(m_dwLowestFreeIndex, NULL);
2900 if (i == (DWORD) ArrayList::NOT_FOUND)
2902 m_dwLowestFreeIndex = i+1;
2904 if (m_dwLowestFreeIndex >= 2000)
2906 m_dwLowestFreeIndex = 0;
2912 IfFailThrow(m_appDomainIndexList.Append(pAppDomain));
2914 m_appDomainIndexList.Set(i, pAppDomain);
2916 _ASSERTE(i < m_appDomainIndexList.GetCount());
2918 // Note that index 0 means domain agile.
2919 return ADIndex(i+1);
2922 void SystemDomain::ReleaseAppDomainIndex(ADIndex index)
2924 WRAPPER_NO_CONTRACT;
2925 SystemDomain::LockHolder lh;
2926 // Note that index 0 means domain agile.
2929 _ASSERTE(m_appDomainIndexList.Get(index.m_dwIndex) != NULL);
2931 m_appDomainIndexList.Set(index.m_dwIndex, NULL);
2934 if (index.m_dwIndex < m_dwLowestFreeIndex)
2935 m_dwLowestFreeIndex = index.m_dwIndex;
2939 #endif // !DACCESS_COMPILE
2941 PTR_AppDomain SystemDomain::GetAppDomainAtIndex(ADIndex index)
2943 LIMITED_METHOD_CONTRACT;
2945 _ASSERTE(index.m_dwIndex != 0);
2947 PTR_AppDomain pAppDomain = TestGetAppDomainAtIndex(index);
2949 _ASSERTE(pAppDomain || !"Attempt to access unloaded app domain");
2954 PTR_AppDomain SystemDomain::TestGetAppDomainAtIndex(ADIndex index)
2956 LIMITED_METHOD_CONTRACT;
2958 _ASSERTE(index.m_dwIndex != 0);
2961 #ifndef DACCESS_COMPILE
2962 _ASSERTE(index.m_dwIndex < (DWORD)m_appDomainIndexList.GetCount());
2963 AppDomain *pAppDomain = (AppDomain*) m_appDomainIndexList.Get(index.m_dwIndex);
2964 #else // DACCESS_COMPILE
2965 PTR_ArrayListStatic pList = &m_appDomainIndexList;
2966 AppDomain *pAppDomain = dac_cast<PTR_AppDomain>(pList->Get(index.m_dwIndex));
2967 #endif // DACCESS_COMPILE
2968 return PTR_AppDomain(pAppDomain);
2971 #ifndef DACCESS_COMPILE
2973 // See also code:SystemDomain::ReleaseAppDomainId
2974 ADID SystemDomain::GetNewAppDomainId(AppDomain *pAppDomain)
2981 INJECT_FAULT(COMPlusThrowOM(););
2985 DWORD i = m_appDomainIdList.GetCount();
2987 IfFailThrow(m_appDomainIdList.Append(pAppDomain));
2989 _ASSERTE(i < m_appDomainIdList.GetCount());
2994 AppDomain *SystemDomain::GetAppDomainAtId(ADID index)
2999 if (!SystemDomain::IsUnderDomainLock() && !IsGCThread()) { MODE_COOPERATIVE;} else { DISABLED(MODE_ANY);}
3007 if(index.m_dwId == 0)
3009 DWORD requestedID = index.m_dwId - 1;
3011 if(requestedID >= (DWORD)m_appDomainIdList.GetCount())
3014 AppDomain * result = (AppDomain *)m_appDomainIdList.Get(requestedID);
3016 #ifndef CROSSGEN_COMPILE
3017 if(result==NULL && GetThread() == FinalizerThread::GetFinalizerThread() &&
3018 SystemDomain::System()->AppDomainBeingUnloaded()!=NULL &&
3019 SystemDomain::System()->AppDomainBeingUnloaded()->GetId()==index)
3020 result=SystemDomain::System()->AppDomainBeingUnloaded();
3021 // If the current thread can't enter the AppDomain, then don't return it.
3022 if (!result || !result->CanThreadEnter(GetThread()))
3024 #endif // CROSSGEN_COMPILE
3029 // Releases an appdomain index. Note that today we have code that depends on these
3030 // indexes not being recycled, so we don't actually shrink m_appDomainIdList, but
3031 // simply zero out an entry. THus we 'leak' the memory associated the slot in
3032 // m_appDomainIdList.
3034 // TODO make this a sparse structure so that we avoid that leak.
3036 void SystemDomain::ReleaseAppDomainId(ADID index)
3038 LIMITED_METHOD_CONTRACT;
3041 _ASSERTE(index.m_dwId < (DWORD)m_appDomainIdList.GetCount());
3043 m_appDomainIdList.Set(index.m_dwId, NULL);
3046 #if defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
3049 int g_fMainThreadApartmentStateSet = 0;
3052 Thread::ApartmentState SystemDomain::GetEntryPointThreadAptState(IMDInternalImport* pScope, mdMethodDef mdMethod)
3054 STANDARD_VM_CONTRACT;
3057 IfFailThrow(hr = pScope->GetCustomAttributeByName(mdMethod,
3058 DEFAULTDOMAIN_MTA_TYPE,
3061 BOOL fIsMTA = FALSE;
3065 IfFailThrow(hr = pScope->GetCustomAttributeByName(mdMethod,
3066 DEFAULTDOMAIN_STA_TYPE,
3069 BOOL fIsSTA = FALSE;
3073 if (fIsSTA && fIsMTA)
3074 COMPlusThrowHR(COR_E_CUSTOMATTRIBUTEFORMAT);
3077 return Thread::AS_InSTA;
3079 return Thread::AS_InMTA;
3081 return Thread::AS_Unknown;
3084 void SystemDomain::SetThreadAptState (Thread::ApartmentState state)
3086 STANDARD_VM_CONTRACT;
3088 Thread* pThread = GetThread();
3091 if(state == Thread::AS_InSTA)
3093 Thread::ApartmentState pState = pThread->SetApartment(Thread::AS_InSTA, TRUE);
3094 _ASSERTE(pState == Thread::AS_InSTA);
3096 else if (state == Thread::AS_InMTA)
3098 Thread::ApartmentState pState = pThread->SetApartment(Thread::AS_InMTA, TRUE);
3099 _ASSERTE(pState == Thread::AS_InMTA);
3103 g_fMainThreadApartmentStateSet++;
3106 #endif // defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
3108 // Looks in all the modules for the DefaultDomain attribute
3109 // The order is assembly and then the modules. It is first
3110 // come, first serve.
3111 BOOL SystemDomain::SetGlobalSharePolicyUsingAttribute(IMDInternalImport* pScope, mdMethodDef mdMethod)
3113 STANDARD_VM_CONTRACT;
3119 void SystemDomain::SetupDefaultDomain()
3126 INJECT_FAULT(COMPlusThrowOM(););
3131 Thread *pThread = GetThread();
3135 pDomain = pThread->GetDomain();
3140 ENTER_DOMAIN_PTR(SystemDomain::System()->DefaultDomain(),ADV_DEFAULTAD)
3142 // Push this frame around loading the main assembly to ensure the
3143 // debugger can properly recgonize any managed code that gets run
3144 // as "class initializaion" code.
3145 FrameWithCookie<DebuggerClassInitMarkFrame> __dcimf;
3149 InitializeDefaultDomain(TRUE);
3154 END_DOMAIN_TRANSITION;
3159 HRESULT SystemDomain::SetupDefaultDomainNoThrow()
3172 SystemDomain::SetupDefaultDomain();
3174 EX_CATCH_HRESULT(hr);
3180 int g_fInitializingInitialAD = 0;
3183 // This routine completes the initialization of the default domaine.
3184 // After this call mananged code can be executed.
3185 void SystemDomain::InitializeDefaultDomain(
3186 BOOL allowRedirects,
3187 ICLRPrivBinder * pBinder)
3189 STANDARD_VM_CONTRACT;
3191 WCHAR* pwsConfig = NULL;
3192 WCHAR* pwsPath = NULL;
3194 ETWOnStartup (InitDefaultDomain_V1, InitDefaultDomainEnd_V1);
3197 // Setup the default AppDomain.
3200 g_fInitializingInitialAD++;
3203 AppDomain* pDefaultDomain = SystemDomain::System()->DefaultDomain();
3205 if (pBinder != nullptr)
3207 pDefaultDomain->SetLoadContextHostBinder(pBinder);
3213 pDefaultDomain->InitializeDomainContext(allowRedirects, pwsPath, pwsConfig);
3215 #ifndef CROSSGEN_COMPILE
3216 if (!NingenEnabled())
3219 if (!IsSingleAppDomain())
3221 pDefaultDomain->InitializeDefaultDomainManager();
3224 #endif // CROSSGEN_COMPILE
3227 // DefaultDomain Load event
3228 ETW::LoaderLog::DomainLoad(pDefaultDomain);
3231 g_fInitializingInitialAD--;
3234 TESTHOOKCALL(RuntimeStarted(RTS_DEFAULTADREADY));
3239 #ifndef CROSSGEN_COMPILE
3242 Volatile<LONG> g_fInExecuteMainMethod = 0;
3248 #endif // CROSSGEN_COMPILE
3252 // Helper function to load an assembly. This is called from LoadCOMClass.
3255 Assembly *AppDomain::LoadAssemblyHelper(LPCWSTR wszAssembly,
3256 LPCWSTR wszCodeBase)
3258 CONTRACT(Assembly *)
3261 POSTCONDITION(CheckPointer(RETVAL));
3262 PRECONDITION(wszAssembly || wszCodeBase);
3263 INJECT_FAULT(COMPlusThrowOM(););
3269 #define MAKE_TRANSLATIONFAILED { ThrowOutOfMemory(); }
3270 MAKE_UTF8PTR_FROMWIDE(szAssembly,wszAssembly);
3271 #undef MAKE_TRANSLATIONFAILED
3273 IfFailThrow(spec.Init(szAssembly));
3277 spec.SetCodeBase(wszCodeBase);
3279 RETURN spec.LoadAssembly(FILE_LOADED);
3282 #if defined(FEATURE_CLASSIC_COMINTEROP) && !defined(CROSSGEN_COMPILE)
3284 MethodTable *AppDomain::LoadCOMClass(GUID clsid,
3285 BOOL bLoadRecord/*=FALSE*/,
3286 BOOL* pfAssemblyInReg/*=NULL*/)
3288 // @CORESYSTODO: what to do here?
3292 #endif // FEATURE_CLASSIC_COMINTEROP && !CROSSGEN_COMPILE
3296 bool SystemDomain::IsReflectionInvocationMethod(MethodDesc* pMeth)
3306 MethodTable* pCaller = pMeth->GetMethodTable();
3308 // All Reflection Invocation methods are defined in mscorlib.dll
3309 if (!pCaller->GetModule()->IsSystem())
3312 /* List of types that should be skipped to identify true caller */
3313 static const BinderClassID reflectionInvocationTypes[] = {
3318 CLASS__CONSTRUCTOR_INFO,
3321 CLASS__METHOD_HANDLE,
3322 CLASS__FIELD_HANDLE,
3325 CLASS__RT_FIELD_INFO,
3330 CLASS__PROPERTY_INFO,
3333 CLASS__ASSEMBLYBASE,
3335 CLASS__TYPE_DELEGATOR,
3336 CLASS__RUNTIME_HELPERS,
3337 CLASS__LAZY_INITIALIZER,
3338 CLASS__DYNAMICMETHOD,
3340 CLASS__MULTICAST_DELEGATE,
3344 static const BinderClassID genericReflectionInvocationTypes[] = {
3348 static mdTypeDef genericReflectionInvocationTypeDefs[NumItems(genericReflectionInvocationTypes)];
3350 static bool fInited = false;
3352 if (!VolatileLoad(&fInited))
3354 // Make sure all types are loaded so that we can use faster GetExistingClass()
3355 for (unsigned i = 0; i < NumItems(reflectionInvocationTypes); i++)
3357 MscorlibBinder::GetClass(reflectionInvocationTypes[i]);
3360 // Make sure all types are loaded so that we can use faster GetExistingClass()
3361 for (unsigned i = 0; i < NumItems(genericReflectionInvocationTypes); i++)
3363 genericReflectionInvocationTypeDefs[i] = MscorlibBinder::GetClass(genericReflectionInvocationTypes[i])->GetCl();
3366 MscorlibBinder::GetClass(CLASS__APP_DOMAIN);
3368 VolatileStore(&fInited, true);
3371 if (pCaller->HasInstantiation())
3373 // For generic types, pCaller will be an instantiated type and never equal to the type definition.
3374 // So we compare their TypeDef tokens instead.
3375 for (unsigned i = 0; i < NumItems(genericReflectionInvocationTypeDefs); i++)
3377 if (pCaller->GetCl() == genericReflectionInvocationTypeDefs[i])
3383 for (unsigned i = 0; i < NumItems(reflectionInvocationTypes); i++)
3385 if (MscorlibBinder::GetExistingClass(reflectionInvocationTypes[i]) == pCaller)
3393 #ifndef CROSSGEN_COMPILE
3394 struct CallersDataWithStackMark
3396 StackCrawlMark* stackMark;
3398 MethodDesc* pFoundMethod;
3399 MethodDesc* pPrevMethod;
3400 AppDomain* pAppDomain;
3404 MethodDesc* SystemDomain::GetCallersMethod(StackCrawlMark* stackMark,
3405 AppDomain **ppAppDomain/*=NULL*/)
3413 INJECT_FAULT(COMPlusThrowOM(););
3419 CallersDataWithStackMark cdata;
3420 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3421 cdata.stackMark = stackMark;
3423 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3425 if(cdata.pFoundMethod) {
3427 *ppAppDomain = cdata.pAppDomain;
3428 return cdata.pFoundMethod;
3434 MethodTable* SystemDomain::GetCallersType(StackCrawlMark* stackMark,
3435 AppDomain **ppAppDomain/*=NULL*/)
3443 INJECT_FAULT(COMPlusThrowOM(););
3447 CallersDataWithStackMark cdata;
3448 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3449 cdata.stackMark = stackMark;
3451 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3453 if(cdata.pFoundMethod) {
3455 *ppAppDomain = cdata.pAppDomain;
3456 return cdata.pFoundMethod->GetMethodTable();
3462 Module* SystemDomain::GetCallersModule(StackCrawlMark* stackMark,
3463 AppDomain **ppAppDomain/*=NULL*/)
3471 INJECT_FAULT(COMPlusThrowOM(););
3477 CallersDataWithStackMark cdata;
3478 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3479 cdata.stackMark = stackMark;
3481 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3483 if(cdata.pFoundMethod) {
3485 *ppAppDomain = cdata.pAppDomain;
3486 return cdata.pFoundMethod->GetModule();
3494 MethodDesc* pMethod;
3498 Assembly* SystemDomain::GetCallersAssembly(StackCrawlMark *stackMark,
3499 AppDomain **ppAppDomain/*=NULL*/)
3501 WRAPPER_NO_CONTRACT;
3502 Module* mod = GetCallersModule(stackMark, ppAppDomain);
3504 return mod->GetAssembly();
3509 Module* SystemDomain::GetCallersModule(int skip)
3516 INJECT_FAULT(COMPlusThrowOM(););
3523 ZeroMemory(&cdata, sizeof(CallersData));
3526 StackWalkFunctions(GetThread(), CallersMethodCallback, &cdata);
3529 return cdata.pMethod->GetModule();
3535 StackWalkAction SystemDomain::CallersMethodCallbackWithStackMark(CrawlFrame* pCf, VOID* data)
3543 INJECT_FAULT(COMPlusThrowOM(););
3548 MethodDesc *pFunc = pCf->GetFunction();
3550 /* We asked to be called back only for functions */
3553 CallersDataWithStackMark* pCaller = (CallersDataWithStackMark*) data;
3554 if (pCaller->stackMark)
3556 if (!pCf->IsInCalleesFrames(pCaller->stackMark))
3558 // save the current in case it is the one we want
3559 pCaller->pPrevMethod = pFunc;
3560 pCaller->pAppDomain = pCf->GetAppDomain();
3561 return SWA_CONTINUE;
3564 // LookForMe stack crawl marks needn't worry about reflection or
3565 // remoting frames on the stack. Each frame above (newer than) the
3566 // target will be captured by the logic above. Once we transition to
3567 // finding the stack mark below the AofRA, we know that we hit the
3568 // target last time round and immediately exit with the cached result.
3570 if (*(pCaller->stackMark) == LookForMe)
3572 pCaller->pFoundMethod = pCaller->pPrevMethod;
3577 // Skip reflection and remoting frames that could lie between a stack marked
3578 // method and its true caller (or that caller and its own caller). These
3579 // frames are infrastructure and logically transparent to the stack crawling
3582 // Skipping remoting frames. We always skip entire client to server spans
3583 // (though we see them in the order server then client during a stack crawl
3586 // We spot the server dispatcher end because all calls are dispatched
3587 // through a single method: StackBuilderSink._PrivateProcessMessage.
3589 Frame* frame = pCf->GetFrame();
3590 _ASSERTE(pCf->IsFrameless() || frame);
3594 // Skipping reflection frames. We don't need to be quite as exhaustive here
3595 // as the security or reflection stack walking code since we know this logic
3596 // is only invoked for selected methods in mscorlib itself. So we're
3597 // reasonably sure we won't have any sensitive methods late bound invoked on
3598 // constructors, properties or events. This leaves being invoked via
3599 // MethodInfo, Type or Delegate (and depending on which invoke overload is
3600 // being used, several different reflection classes may be involved).
3602 g_IBCLogger.LogMethodDescAccess(pFunc);
3604 if (SystemDomain::IsReflectionInvocationMethod(pFunc))
3605 return SWA_CONTINUE;
3607 if (frame && frame->GetFrameType() == Frame::TYPE_MULTICAST)
3609 // This must be either a secure delegate frame or a true multicast delegate invocation.
3611 _ASSERTE(pFunc->GetMethodTable()->IsDelegate());
3613 DELEGATEREF del = (DELEGATEREF)((SecureDelegateFrame*)frame)->GetThis(); // This can throw.
3615 if (COMDelegate::IsSecureDelegate(del))
3617 if (del->IsWrapperDelegate())
3619 // On ARM, we use secure delegate infrastructure to preserve R4 register.
3620 return SWA_CONTINUE;
3622 // For a secure delegate frame, we should return the delegate creator instead
3623 // of the delegate method itself.
3624 pFunc = (MethodDesc*) del->GetMethodPtrAux();
3628 _ASSERTE(COMDelegate::IsTrueMulticastDelegate(del));
3629 return SWA_CONTINUE;
3633 // Return the first non-reflection/remoting frame if no stack mark was
3635 if (!pCaller->stackMark)
3637 pCaller->pFoundMethod = pFunc;
3638 pCaller->pAppDomain = pCf->GetAppDomain();
3642 // If we got here, we must already be in the frame containing the stack mark and we are not looking for "me".
3643 _ASSERTE(pCaller->stackMark &&
3644 pCf->IsInCalleesFrames(pCaller->stackMark) &&
3645 *(pCaller->stackMark) != LookForMe);
3647 // When looking for caller's caller, we delay returning results for another
3648 // round (the way this is structured, we will still be able to skip
3649 // reflection and remoting frames between the caller and the caller's
3652 if ((*(pCaller->stackMark) == LookForMyCallersCaller) &&
3653 (pCaller->pFoundMethod == NULL))
3655 pCaller->pFoundMethod = pFunc;
3656 return SWA_CONTINUE;
3659 // If remoting is not available, we only set the caller if the crawlframe is from the same domain.
3660 // Why? Because if the callerdomain is different from current domain,
3661 // there have to be interop/native frames in between.
3662 // For example, in the CORECLR, if we find the caller to be in a different domain, then the
3663 // call into reflection is due to an unmanaged call into mscorlib. For that
3664 // case, the caller really is an INTEROP method.
3665 // In general, if the caller is INTEROP, we set the caller/callerdomain to be NULL
3666 // (To be precise: they are already NULL and we don't change them).
3667 if (pCf->GetAppDomain() == GetAppDomain())
3668 // We must either be looking for the caller, or the caller's caller when
3669 // we've already found the caller (we used a non-null value in pFoundMethod
3670 // simply as a flag, the correct method to return in both case is the
3673 pCaller->pFoundMethod = pFunc;
3674 pCaller->pAppDomain = pCf->GetAppDomain();
3681 StackWalkAction SystemDomain::CallersMethodCallback(CrawlFrame* pCf, VOID* data)
3683 LIMITED_METHOD_CONTRACT;
3684 STATIC_CONTRACT_SO_TOLERANT;
3685 MethodDesc *pFunc = pCf->GetFunction();
3687 /* We asked to be called back only for functions */
3690 CallersData* pCaller = (CallersData*) data;
3691 if(pCaller->skip == 0) {
3692 pCaller->pMethod = pFunc;
3697 return SWA_CONTINUE;
3701 #endif // CROSSGEN_COMPILE
3703 #ifdef CROSSGEN_COMPILE
3704 // defined in compile.cpp
3705 extern CompilationDomain * theDomain;
3708 void SystemDomain::CreateDefaultDomain()
3710 STANDARD_VM_CONTRACT;
3712 #ifdef CROSSGEN_COMPILE
3713 AppDomainRefHolder pDomain(theDomain);
3715 AppDomainRefHolder pDomain(new AppDomain());
3718 SystemDomain::LockHolder lh;
3721 // need to make this assignment here since we'll be releasing
3722 // the lock before calling AddDomain. So any other thread
3723 // grabbing this lock after we release it will find that
3724 // the COM Domain has already been created
3725 m_pDefaultDomain = pDomain;
3726 _ASSERTE (pDomain->GetId().m_dwId == DefaultADID);
3728 // allocate a Virtual Call Stub Manager for the default domain
3729 m_pDefaultDomain->InitVSD();
3731 pDomain->SetStage(AppDomain::STAGE_OPEN);
3732 pDomain.SuppressRelease();
3734 LOG((LF_CLASSLOADER | LF_CORDB,
3736 "Created default domain at %p\n", m_pDefaultDomain));
3739 #ifdef DEBUGGING_SUPPORTED
3741 void SystemDomain::PublishAppDomainAndInformDebugger (AppDomain *pDomain)
3745 if(!g_fEEInit) {THROWS;} else {DISABLED(NOTHROW);};
3746 if(!g_fEEInit) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);};
3751 LOG((LF_CORDB, LL_INFO100, "SD::PADAID: Adding 0x%x\n", pDomain));
3753 // Call the publisher API to add this appdomain entry to the list
3754 // The publisher will handle failures, so we don't care if this succeeds or fails.
3755 if (g_pDebugInterface != NULL)
3757 g_pDebugInterface->AddAppDomainToIPC(pDomain);
3761 #endif // DEBUGGING_SUPPORTED
3763 void SystemDomain::AddDomain(AppDomain* pDomain)
3770 PRECONDITION(CheckPointer((pDomain)));
3777 _ASSERTE (pDomain->m_Stage != AppDomain::STAGE_CREATING);
3778 if (pDomain->m_Stage == AppDomain::STAGE_READYFORMANAGEDCODE ||
3779 pDomain->m_Stage == AppDomain::STAGE_ACTIVE)
3781 pDomain->SetStage(AppDomain::STAGE_OPEN);
3782 IncrementNumAppDomains(); // Maintain a count of app domains added to the list.
3786 // Note that if you add another path that can reach here without calling
3787 // PublishAppDomainAndInformDebugger, then you should go back & make sure
3788 // that PADAID gets called. Right after this call, if not sooner.
3789 LOG((LF_CORDB, LL_INFO1000, "SD::AD:Would have added domain here! 0x%x\n",
3793 BOOL SystemDomain::RemoveDomain(AppDomain* pDomain)
3800 PRECONDITION(CheckPointer(pDomain));
3801 PRECONDITION(!pDomain->IsDefaultDomain());
3805 // You can not remove the default domain.
3808 if (!pDomain->IsActive())
3817 #ifdef PROFILING_SUPPORTED
3818 void SystemDomain::NotifyProfilerStartup()
3829 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3831 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) System());
3836 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3838 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) System(), S_OK);
3843 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3844 _ASSERTE(System()->DefaultDomain());
3845 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) System()->DefaultDomain());
3850 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3851 _ASSERTE(System()->DefaultDomain());
3852 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) System()->DefaultDomain(), S_OK);
3857 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3858 _ASSERTE(SharedDomain::GetDomain());
3859 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) SharedDomain::GetDomain());
3864 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3865 _ASSERTE(SharedDomain::GetDomain());
3866 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) SharedDomain::GetDomain(), S_OK);
3871 HRESULT SystemDomain::NotifyProfilerShutdown()
3882 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3884 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) System());
3889 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3891 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) System(), S_OK);
3896 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3897 _ASSERTE(System()->DefaultDomain());
3898 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) System()->DefaultDomain());
3903 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3904 _ASSERTE(System()->DefaultDomain());
3905 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) System()->DefaultDomain(), S_OK);
3910 #endif // PROFILING_SUPPORTED
3914 struct AppDomain::ThreadTrackInfo {
3916 CDynArray<Frame *> frameStack;
3920 AppDomain::AppDomain()
3922 // initialize fields so the appdomain can be safely destructed
3923 // shouldn't call anything that can fail here - use ::Init instead
3934 m_pNextInDelayedUnloadList = NULL;
3935 m_fRudeUnload = FALSE;
3936 m_pUnloadRequestThread = NULL;
3937 m_ADUnloadSink=NULL;
3940 // Initialize Shared state. Assemblies are loaded
3941 // into each domain by default.
3942 #ifdef FEATURE_LOADER_OPTIMIZATION
3943 m_SharePolicy = SHARE_POLICY_UNSPECIFIED;
3946 m_pRootAssembly = NULL;
3948 m_pwDynamicDir = NULL;
3951 m_pDefaultContext = NULL;
3952 #ifdef FEATURE_COMINTEROP
3953 m_pComCallWrapperCache = NULL;
3955 m_pRCWRefCache = NULL;
3956 m_pLicenseInteropHelperMT = NULL;
3957 m_COMorRemotingFlag = COMorRemoting_NotInitialized;
3958 memset(m_rpCLRTypes, 0, sizeof(m_rpCLRTypes));
3959 #endif // FEATURE_COMINTEROP
3961 m_pUMEntryThunkCache = NULL;
3963 m_pAsyncPool = NULL;
3964 m_handleStore = NULL;
3966 m_ExposedObject = NULL;
3967 m_pComIPForExposedObject = NULL;
3970 m_pThreadTrackInfoList = NULL;
3971 m_TrackSpinLock = 0;
3972 m_Assemblies.Debug_SetAppDomain(this);
3975 m_dwThreadEnterCount = 0;
3976 m_dwThreadsStillInAppDomain = (ULONG)-1;
3978 #ifdef FEATURE_COMINTEROP
3979 m_pRefDispIDCache = NULL;
3980 m_hndMissing = NULL;
3983 m_pRefClassFactHash = NULL;
3984 m_anonymouslyHostedDynamicMethodsAssembly = NULL;
3986 m_ReversePInvokeCanEnter=TRUE;
3987 m_ForceTrivialWaitOperations = false;
3988 m_Stage=STAGE_CREATING;
3990 m_bForceGCOnUnload=FALSE;
3991 m_bUnloadingFromUnloadEvent=FALSE;
3995 m_dwCreationHolders=0;
3998 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
3999 m_ullTotalProcessorUsage = 0;
4000 m_pullAllocBytes = NULL;
4001 m_pullSurvivedBytes = NULL;
4002 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4004 #ifdef FEATURE_TYPEEQUIVALENCE
4005 m_pTypeEquivalenceTable = NULL;
4006 #endif // FEATURE_TYPEEQUIVALENCE
4008 #ifdef FEATURE_COMINTEROP
4009 m_pNameToTypeMap = NULL;
4010 m_vNameToTypeMapVersion = 0;
4012 m_pWinRTFactoryCache = NULL;
4013 #endif // FEATURE_COMINTEROP
4015 #ifdef FEATURE_PREJIT
4016 m_pDomainFileWithNativeImageList = NULL;
4019 m_fIsBindingModelLocked.Store(FALSE);
4021 } // AppDomain::AppDomain
4023 AppDomain::~AppDomain()
4033 #ifndef CROSSGEN_COMPILE
4035 _ASSERTE(m_dwCreationHolders == 0);
4037 // release the TPIndex. note that since TPIndex values are recycled the TPIndex
4038 // can only be released once all threads in the AppDomain have exited.
4039 if (GetTPIndex().m_dwIndex != 0)
4040 PerAppDomainTPCountList::ResetAppDomainIndex(GetTPIndex());
4042 if (m_dwId.m_dwId!=0)
4043 SystemDomain::ReleaseAppDomainId(m_dwId);
4045 m_AssemblyCache.Clear();
4048 m_ADUnloadSink->Release();
4056 #ifdef FEATURE_COMINTEROP
4057 if (m_pNameToTypeMap != nullptr)
4059 delete m_pNameToTypeMap;
4060 m_pNameToTypeMap = nullptr;
4062 if (m_pWinRTFactoryCache != nullptr)
4064 delete m_pWinRTFactoryCache;
4065 m_pWinRTFactoryCache = nullptr;
4067 #endif //FEATURE_COMINTEROP
4070 // If we were tracking thread AD transitions, cleanup the list on shutdown
4071 if (m_pThreadTrackInfoList)
4073 while (m_pThreadTrackInfoList->Count() > 0)
4075 // Get the very last element
4076 ThreadTrackInfo *pElem = *(m_pThreadTrackInfoList->Get(m_pThreadTrackInfoList->Count() - 1));
4082 // Remove pointer entry from the list
4083 m_pThreadTrackInfoList->Delete(m_pThreadTrackInfoList->Count() - 1);
4086 // Now delete the list itself
4087 delete m_pThreadTrackInfoList;
4088 m_pThreadTrackInfoList = NULL;
4092 #endif // CROSSGEN_COMPILE
4095 //*****************************************************************************
4096 //*****************************************************************************
4097 //*****************************************************************************
4098 void AppDomain::Init()
4103 PRECONDITION(SystemDomain::IsUnderDomainLock());
4107 m_pDelayedLoaderAllocatorUnloadList = NULL;
4109 SetStage( STAGE_CREATING);
4112 // The lock is taken also during stack walking (GC or profiler)
4113 // - To prevent deadlock with GC thread, we cannot trigger GC while holding the lock
4114 // - To prevent deadlock with profiler thread, we cannot allow thread suspension
4115 m_crstHostAssemblyMap.Init(
4116 CrstHostAssemblyMap,
4117 (CrstFlags)(CRST_GC_NOTRIGGER_WHEN_TAKEN
4118 | CRST_DEBUGGER_THREAD
4119 INDEBUG(| CRST_DEBUG_ONLY_CHECK_FORBID_SUSPEND_THREAD)));
4120 m_crstHostAssemblyMapAdd.Init(CrstHostAssemblyMapAdd);
4122 m_dwId = SystemDomain::GetNewAppDomainId(this);
4124 m_LoaderAllocator.Init(this);
4126 #ifndef CROSSGEN_COMPILE
4127 //Allocate the threadpool entry before the appdomin id list. Otherwise,
4128 //the thread pool list will be out of sync if insertion of id in
4129 //the appdomain fails.
4130 m_tpIndex = PerAppDomainTPCountList::AddNewTPIndex();
4131 #endif // CROSSGEN_COMPILE
4133 m_dwIndex = SystemDomain::GetNewAppDomainIndex(this);
4135 #ifndef CROSSGEN_COMPILE
4136 PerAppDomainTPCountList::SetAppDomainId(m_tpIndex, m_dwId);
4138 m_ADUnloadSink=new ADUnloadSink();
4143 // Set up the IL stub cache
4144 m_ILStubCache.Init(GetLoaderAllocator()->GetHighFrequencyHeap());
4146 // Set up the binding caches
4147 m_AssemblyCache.Init(&m_DomainCacheCrst, GetHighFrequencyHeap());
4148 m_UnmanagedCache.InitializeTable(this, &m_DomainCacheCrst);
4150 m_MemoryPressure = 0;
4152 m_sDomainLocalBlock.Init(this);
4154 #ifndef CROSSGEN_COMPILE
4156 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4157 // NOTE: it's important that we initialize ARM data structures before calling
4158 // Ref_CreateHandleTableBucket, this is because AD::Init() can race with GC
4159 // and once we add ourselves to the handle table map the GC can start walking
4160 // our handles and calling AD::RecordSurvivedBytes() which touches ARM data.
4161 if (GCHeapUtilities::IsServerHeap())
4162 m_dwNumHeaps = CPUGroupInfo::CanEnableGCCPUGroups() ?
4163 CPUGroupInfo::GetNumActiveProcessors() :
4164 GetCurrentProcessCpuCount();
4167 m_pullAllocBytes = new ULONGLONG [m_dwNumHeaps * ARM_CACHE_LINE_SIZE_ULL];
4168 m_pullSurvivedBytes = new ULONGLONG [m_dwNumHeaps * ARM_CACHE_LINE_SIZE_ULL];
4169 for (DWORD i = 0; i < m_dwNumHeaps; i++)
4171 m_pullAllocBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
4172 m_pullSurvivedBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
4174 m_ullLastEtwAllocBytes = 0;
4175 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4177 // Default domain reuses the handletablemap that was created during EEStartup since
4178 // default domain cannot be unloaded.
4179 if (GetId().m_dwId == DefaultADID)
4181 m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
4185 m_handleStore = GCHandleUtilities::GetGCHandleManager()->CreateHandleStore((void*)(uintptr_t)m_dwIndex.m_dwIndex);
4193 #endif // CROSSGEN_COMPILE
4195 #ifdef FEATURE_TYPEEQUIVALENCE
4196 m_TypeEquivalenceCrst.Init(CrstTypeEquivalenceMap);
4199 m_ReflectionCrst.Init(CrstReflection, CRST_UNSAFE_ANYMODE);
4200 m_RefClassFactCrst.Init(CrstClassFactInfoHash);
4203 LockOwner lock = {&m_DomainCrst, IsOwnerOfCrst};
4204 m_clsidHash.Init(0,&CompareCLSID,true, &lock); // init hash table
4207 SetStage(STAGE_READYFORMANAGEDCODE);
4209 #ifndef CROSSGEN_COMPILE
4210 m_pDefaultContext = new Context(this);
4212 m_ExposedObject = CreateHandle(NULL);
4214 // Create the Application Security Descriptor
4216 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomains++);
4218 #ifdef FEATURE_COMINTEROP
4219 if (!AppX::IsAppXProcess())
4222 #endif //FEATURE_COMINTEROP
4224 #ifdef FEATURE_TIERED_COMPILATION
4225 m_tieredCompilationManager.Init(GetId());
4227 #endif // CROSSGEN_COMPILE
4228 } // AppDomain::Init
4231 /*********************************************************************/
4233 BOOL AppDomain::IsCompilationDomain()
4235 LIMITED_METHOD_CONTRACT;
4237 BOOL isCompilationDomain = (m_dwFlags & COMPILATION_DOMAIN) != 0;
4238 #ifdef FEATURE_PREJIT
4239 _ASSERTE(!isCompilationDomain ||
4240 (IsCompilationProcess() && IsPassiveDomain()));
4241 #endif // FEATURE_PREJIT
4242 return isCompilationDomain;
4245 #ifndef CROSSGEN_COMPILE
4247 extern int g_fADUnloadWorkerOK;
4250 // This helper will send the AppDomain creation notifications for profiler / debugger.
4251 // If it throws, its backout code will also send a notification.
4252 // If it succeeds, then we still need to send a AppDomainCreateFinished notification.
4253 void AppDomain::CreateUnmanagedObject(AppDomainCreationHolder<AppDomain>& pDomain)
4260 INJECT_FAULT(COMPlusThrowOM(););
4266 pDomain.Assign(new AppDomain());
4267 if (g_fADUnloadWorkerOK<0)
4269 AppDomain::CreateADUnloadWorker();
4273 // We addref Appdomain object here and notify a profiler that appdomain
4274 // creation has started, then return to managed code which will call
4275 // the function that releases the appdomain and notifies a profiler that we finished
4276 // creating the appdomain. If an exception is raised while we're in that managed code
4277 // we will leak memory and the profiler will not be notified about the failure
4279 #ifdef PROFILING_SUPPORTED
4280 // Signal profile if present.
4282 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
4283 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) (AppDomain*) pDomain);
4287 #endif // PROFILING_SUPPORTED
4290 SystemDomain::LockHolder lh;
4292 // allocate a Virtual Call Stub Manager for this domain
4296 pDomain->SetCanUnload(); // by default can unload any domain
4298 #ifdef DEBUGGING_SUPPORTED
4299 // Notify the debugger here, before the thread transitions into the
4300 // AD to finish the setup, and before any assemblies are loaded into it.
4301 SystemDomain::PublishAppDomainAndInformDebugger(pDomain);
4302 #endif // DEBUGGING_SUPPORTED
4304 STRESS_LOG2 (LF_APPDOMAIN, LL_INFO100, "Create domain [%d] %p\n", pDomain->GetId().m_dwId, (AppDomain*)pDomain);
4305 pDomain->LoadSystemAssemblies();
4306 pDomain->SetupSharedStatics();
4308 pDomain->SetStage(AppDomain::STAGE_ACTIVE);
4310 #ifdef PROFILING_SUPPORTED
4313 // Need the first assembly loaded in to get any data on an app domain.
4315 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
4316 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID)(AppDomain*) pDomain, GET_EXCEPTION()->GetHR());
4322 // On success, caller must still send the AppDomainCreationFinished notification.
4323 #endif // PROFILING_SUPPORTED
4326 void AppDomain::Stop()
4336 #ifdef FEATURE_MULTICOREJIT
4337 GetMulticoreJitManager().StopProfile(true);
4340 // Set the unloaded flag before notifying the debugger
4341 GetLoaderAllocator()->SetIsUnloaded();
4343 #ifdef DEBUGGING_SUPPORTED
4344 if (IsDebuggerAttached())
4345 NotifyDebuggerUnload();
4346 #endif // DEBUGGING_SUPPORTED
4348 m_pRootAssembly = NULL; // This assembly is in the assembly list;
4350 #ifdef DEBUGGING_SUPPORTED
4351 if (NULL != g_pDebugInterface)
4353 // Call the publisher API to delete this appdomain entry from the list
4354 CONTRACT_VIOLATION(ThrowsViolation);
4355 g_pDebugInterface->RemoveAppDomainFromIPC (this);
4357 #endif // DEBUGGING_SUPPORTED
4360 void AppDomain::Terminate()
4373 _ASSERTE(m_dwThreadEnterCount == 0 || IsDefaultDomain());
4375 if (m_pComIPForExposedObject)
4377 m_pComIPForExposedObject->Release();
4378 m_pComIPForExposedObject = NULL;
4381 delete m_pDefaultContext;
4382 m_pDefaultContext = NULL;
4384 if (m_pUMEntryThunkCache)
4386 delete m_pUMEntryThunkCache;
4387 m_pUMEntryThunkCache = NULL;
4390 #ifdef FEATURE_COMINTEROP
4399 delete m_pRCWRefCache;
4400 m_pRCWRefCache = NULL;
4403 if (m_pComCallWrapperCache)
4405 m_pComCallWrapperCache->Neuter();
4406 m_pComCallWrapperCache->Release();
4409 // if the above released the wrapper cache, then it will call back and reset our
4410 // m_pComCallWrapperCache to null. If not null, then need to set it's domain pointer to
4412 if (! m_pComCallWrapperCache)
4414 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::Terminate ComCallWrapperCache released\n"));
4419 m_pComCallWrapperCache = NULL;
4420 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::Terminate ComCallWrapperCache not released\n"));
4424 #endif // FEATURE_COMINTEROP
4427 if (!IsAtProcessExit())
4429 // if we're not shutting down everything then clean up the string literals associated
4430 // with this appdomain -- note that is no longer needs to happen while suspended
4431 // because the appropriate locks are taken in the GlobalStringLiteralMap
4432 // this is important as this locks have a higher lock number than does the
4433 // thread-store lock which is taken when we suspend.
4434 GetLoaderAllocator()->CleanupStringLiteralMap();
4436 // Suspend the EE to do some clean up that can only occur
4437 // while no threads are running.
4438 GCX_COOP (); // SuspendEE may require current thread to be in Coop mode
4439 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
4442 // Note that this must be performed before restarting the EE. It will clean
4443 // the cache and prevent others from using stale cache entries.
4444 //@TODO: Would be nice to get this back to BaseDomain, but need larger fix for that.
4445 // NOTE: Must have the runtime suspended to unlink managers
4446 // NOTE: May be NULL due to OOM during initialization. Can skip in that case.
4447 GetLoaderAllocator()->UninitVirtualCallStubManager();
4448 MethodTable::ClearMethodDataCache();
4449 ClearJitGenericHandleCache(this);
4451 // @TODO s_TPMethodTableCrst prevents us from from keeping the whole
4452 // assembly shutdown logic here. See if we can do better in the next milestone
4453 #ifdef FEATURE_PREJIT
4454 DeleteNativeCodeRanges();
4457 if (!IsAtProcessExit())
4460 ThreadSuspend::RestartEE(FALSE, TRUE);
4463 ShutdownAssemblies();
4464 ShutdownNativeDllSearchDirectories();
4466 if (m_pRefClassFactHash)
4468 m_pRefClassFactHash->Destroy();
4469 // storage for m_pRefClassFactHash itself is allocated on the loader heap
4472 #ifdef FEATURE_TYPEEQUIVALENCE
4473 m_TypeEquivalenceCrst.Destroy();
4476 m_ReflectionCrst.Destroy();
4477 m_RefClassFactCrst.Destroy();
4479 m_LoaderAllocator.Terminate();
4481 BaseDomain::Terminate();
4485 GCHandleUtilities::GetGCHandleManager()->DestroyHandleStore(m_handleStore);
4486 m_handleStore = NULL;
4489 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4490 if (m_pullAllocBytes)
4492 delete [] m_pullAllocBytes;
4494 if (m_pullSurvivedBytes)
4496 delete [] m_pullSurvivedBytes;
4498 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4500 if(m_dwIndex.m_dwIndex != 0)
4501 SystemDomain::ReleaseAppDomainIndex(m_dwIndex);
4502 } // AppDomain::Terminate
4504 void AppDomain::CloseDomain()
4515 BOOL bADRemoved=FALSE;;
4517 AddRef(); // Hold a reference
4518 AppDomainRefHolder AdHolder(this);
4520 SystemDomain::LockHolder lh;
4522 SystemDomain::System()->DecrementNumAppDomains(); // Maintain a count of app domains added to the list.
4523 bADRemoved = SystemDomain::System()->RemoveDomain(this);
4530 /*********************************************************************/
4532 struct GetExposedObject_Args
4538 static void GetExposedObject_Wrapper(LPVOID ptr)
4547 GetExposedObject_Args *args = (GetExposedObject_Args *) ptr;
4548 *(args->ref) = args->pDomain->GetExposedObject();
4552 OBJECTREF AppDomain::GetExposedObject()
4559 INJECT_FAULT(COMPlusThrowOM(););
4563 OBJECTREF ref = GetRawExposedObject();
4566 APPDOMAINREF obj = NULL;
4568 Thread *pThread = GetThread();
4569 if (pThread->GetDomain() != this)
4571 GCPROTECT_BEGIN(ref);
4572 GetExposedObject_Args args = {this, &ref};
4573 // call through DoCallBack with a domain transition
4574 pThread->DoADCallBack(this,GetExposedObject_Wrapper, &args,ADV_CREATING|ADV_RUNNINGIN);
4578 MethodTable *pMT = MscorlibBinder::GetClass(CLASS__APP_DOMAIN);
4580 // Create the module object
4581 obj = (APPDOMAINREF) AllocateObject(pMT);
4582 obj->SetDomain(this);
4584 if (!StoreFirstObjectInHandle(m_ExposedObject, (OBJECTREF) obj))
4586 obj = (APPDOMAINREF) GetRawExposedObject();
4590 return (OBJECTREF) obj;
4598 OBJECTREF AppDomain::DoSetup(OBJECTREF* setupInfo)
4605 INJECT_FAULT(COMPlusThrowOM(););
4609 ADID adid=GetAppDomain()->GetId();
4611 OBJECTREF retval=NULL;
4612 GCPROTECT_BEGIN(retval);
4614 ENTER_DOMAIN_PTR(this,ADV_CREATING);
4616 MethodDescCallSite setup(METHOD__APP_DOMAIN__SETUP);
4620 args[0]=ObjToArgSlot(*setupInfo);
4622 OBJECTREF activator;
4623 activator=setup.Call_RetOBJECTREF(args);
4624 _ASSERTE(activator==NULL);
4626 #if defined(FEATURE_MULTICOREJIT)
4627 // Disable AutoStartProfile in default domain from this code path.
4628 // It's called from SystemDomain::ExecuteMainMethod for normal program, not needed for SL and Asp.Net
4629 if (! IsDefaultDomain())
4633 GetMulticoreJitManager().AutoStartProfile(this);
4637 END_DOMAIN_TRANSITION;
4642 #endif // !CROSSGEN_COMPILE
4644 #ifdef FEATURE_COMINTEROP
4645 #ifndef CROSSGEN_COMPILE
4646 HRESULT AppDomain::GetComIPForExposedObject(IUnknown **pComIP)
4648 // Assumption: This function is called for AppDomain's that the current
4649 // thread is in or has entered, or the AppDomain is kept alive.
4651 // Assumption: This function can now throw. The caller is responsible for any
4652 // BEGIN_EXTERNAL_ENTRYPOINT, EX_TRY, or other
4653 // techniques to convert to a COM HRESULT protocol.
4663 Thread *pThread = GetThread();
4664 if (m_pComIPForExposedObject)
4666 GCX_PREEMP_THREAD_EXISTS(pThread);
4667 m_pComIPForExposedObject->AddRef();
4668 *pComIP = m_pComIPForExposedObject;
4672 IUnknown* punk = NULL;
4674 OBJECTREF ref = NULL;
4675 GCPROTECT_BEGIN(ref);
4679 ENTER_DOMAIN_PTR(this,ADV_DEFAULTAD)
4681 ref = GetExposedObject();
4682 punk = GetComIPFromObjectRef(&ref);
4683 if (FastInterlockCompareExchangePointer(&m_pComIPForExposedObject, punk, NULL) == NULL)
4685 GCX_PREEMP_THREAD_EXISTS(pThread);
4686 m_pComIPForExposedObject->AddRef();
4689 END_DOMAIN_TRANSITION;
4695 *pComIP = m_pComIPForExposedObject;
4700 #endif //#ifndef CROSSGEN_COMPILE
4702 MethodTable *AppDomain::GetRedirectedType(WinMDAdapter::RedirectedTypeIndex index)
4712 // If we have the type loaded already, use that
4713 if (m_rpCLRTypes[index] != nullptr)
4715 return m_rpCLRTypes[index];
4718 WinMDAdapter::FrameworkAssemblyIndex frameworkAssemblyIndex;
4719 WinMDAdapter::GetRedirectedTypeInfo(index, nullptr, nullptr, nullptr, &frameworkAssemblyIndex, nullptr, nullptr);
4720 MethodTable * pMT = LoadRedirectedType(index, frameworkAssemblyIndex);
4721 m_rpCLRTypes[index] = pMT;
4725 MethodTable* AppDomain::LoadRedirectedType(WinMDAdapter::RedirectedTypeIndex index, WinMDAdapter::FrameworkAssemblyIndex assembly)
4732 PRECONDITION(index < WinMDAdapter::RedirectedTypeIndex_Count);
4736 LPCSTR szClrNamespace;
4738 LPCSTR szFullWinRTName;
4739 WinMDAdapter::FrameworkAssemblyIndex nFrameworkAssemblyIndex;
4741 WinMDAdapter::GetRedirectedTypeInfo(index, &szClrNamespace, &szClrName, &szFullWinRTName, &nFrameworkAssemblyIndex, nullptr, nullptr);
4743 _ASSERTE(nFrameworkAssemblyIndex >= WinMDAdapter::FrameworkAssembly_Mscorlib &&
4744 nFrameworkAssemblyIndex < WinMDAdapter::FrameworkAssembly_Count);
4746 if (assembly != nFrameworkAssemblyIndex)
4748 // The framework type does not live in the assembly we were requested to load redirected types from
4751 else if (nFrameworkAssemblyIndex == WinMDAdapter::FrameworkAssembly_Mscorlib)
4753 return ClassLoader::LoadTypeByNameThrowing(MscorlibBinder::GetModule()->GetAssembly(),
4756 ClassLoader::ThrowIfNotFound,
4757 ClassLoader::LoadTypes,
4758 CLASS_LOAD_EXACTPARENTS).GetMethodTable();
4763 AssemblyMetaDataInternal context;
4764 const BYTE * pbKeyToken;
4765 DWORD cbKeyTokenLength;
4768 WinMDAdapter::GetExtraAssemblyRefProps(nFrameworkAssemblyIndex,
4775 Assembly* pAssembly = AssemblySpec::LoadAssembly(pSimpleName,
4781 return ClassLoader::LoadTypeByNameThrowing(
4785 ClassLoader::ThrowIfNotFound,
4786 ClassLoader::LoadTypes,
4787 CLASS_LOAD_EXACTPARENTS).GetMethodTable();
4790 #endif //FEATURE_COMINTEROP
4792 #endif //!DACCESS_COMPILE
4794 #ifndef DACCESS_COMPILE
4796 bool IsPlatformAssembly(LPCSTR szName, DomainAssembly *pDomainAssembly)
4803 PRECONDITION(CheckPointer(szName));
4804 PRECONDITION(CheckPointer(pDomainAssembly));
4808 PEAssembly *pPEAssembly = pDomainAssembly->GetFile();
4810 if (strcmp(szName, pPEAssembly->GetSimpleName()) != 0)
4816 const BYTE *pbPublicKey = static_cast<const BYTE *>(pPEAssembly->GetPublicKey(&cbPublicKey));
4817 if (pbPublicKey == nullptr)
4822 return StrongNameIsSilverlightPlatformKey(pbPublicKey, cbPublicKey);
4825 void AppDomain::AddAssembly(DomainAssembly * assem)
4832 INJECT_FAULT(COMPlusThrowOM(););
4837 CrstHolder ch(GetAssemblyListLock());
4839 // Attempt to find empty space in assemblies list
4840 DWORD asmCount = m_Assemblies.GetCount_Unlocked();
4841 for (DWORD i = 0; i < asmCount; ++i)
4843 if (m_Assemblies.Get_UnlockedNoReference(i) == NULL)
4845 m_Assemblies.Set_Unlocked(i, assem);
4850 // If empty space not found, simply add to end of list
4851 IfFailThrow(m_Assemblies.Append_Unlocked(assem));
4855 void AppDomain::RemoveAssembly_Unlocked(DomainAssembly * pAsm)
4864 _ASSERTE(GetAssemblyListLock()->OwnedByCurrentThread());
4866 DWORD asmCount = m_Assemblies.GetCount_Unlocked();
4867 for (DWORD i = 0; i < asmCount; ++i)
4869 if (m_Assemblies.Get_UnlockedNoReference(i) == pAsm)
4871 m_Assemblies.Set_Unlocked(i, NULL);
4876 _ASSERTE(!"Unreachable");
4879 BOOL AppDomain::ContainsAssembly(Assembly * assem)
4881 WRAPPER_NO_CONTRACT;
4882 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
4884 (assem->IsIntrospectionOnly() ? kIncludeIntrospection : kIncludeExecution)));
4885 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
4887 while (i.Next(pDomainAssembly.This()))
4889 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
4890 if (pAssembly == assem)
4897 EEClassFactoryInfoHashTable* AppDomain::SetupClassFactHash()
4904 INJECT_FAULT(COMPlusThrowOM(););
4908 CrstHolder ch(&m_ReflectionCrst);
4910 if (m_pRefClassFactHash == NULL)
4912 AllocMemHolder<void> pCache(GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof (EEClassFactoryInfoHashTable))));
4913 EEClassFactoryInfoHashTable *tmp = new (pCache) EEClassFactoryInfoHashTable;
4914 LockOwner lock = {&m_RefClassFactCrst,IsOwnerOfCrst};
4915 if (!tmp->Init(20, &lock))
4917 pCache.SuppressRelease();
4918 m_pRefClassFactHash = tmp;
4921 return m_pRefClassFactHash;
4924 #ifdef FEATURE_COMINTEROP
4925 DispIDCache* AppDomain::SetupRefDispIDCache()
4932 INJECT_FAULT(COMPlusThrowOM(););
4936 CrstHolder ch(&m_ReflectionCrst);
4938 if (m_pRefDispIDCache == NULL)
4940 AllocMemHolder<void> pCache = GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof (DispIDCache)));
4942 DispIDCache *tmp = new (pCache) DispIDCache;
4945 pCache.SuppressRelease();
4946 m_pRefDispIDCache = tmp;
4949 return m_pRefDispIDCache;
4952 #endif // FEATURE_COMINTEROP
4954 FileLoadLock *FileLoadLock::Create(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile)
4961 PRECONDITION(pLock->HasLock());
4962 PRECONDITION(pLock->FindFileLock(pFile) == NULL);
4963 INJECT_FAULT(COMPlusThrowOM(););
4967 NewHolder<FileLoadLock> result(new FileLoadLock(pLock, pFile, pDomainFile));
4969 pLock->AddElement(result);
4970 result->AddRef(); // Add one ref on behalf of the ListLock's reference. The corresponding Release() happens in FileLoadLock::CompleteLoadLevel.
4971 return result.Extract();
4974 FileLoadLock::~FileLoadLock()
4984 ((PEFile *) m_data)->Release();
4987 DomainFile *FileLoadLock::GetDomainFile()
4989 LIMITED_METHOD_CONTRACT;
4990 return m_pDomainFile;
4993 FileLoadLevel FileLoadLock::GetLoadLevel()
4995 LIMITED_METHOD_CONTRACT;
4999 ADID FileLoadLock::GetAppDomainId()
5001 LIMITED_METHOD_CONTRACT;
5002 return m_AppDomainId;
5005 // Acquire will return FALSE and not take the lock if the file
5006 // has already been loaded to the target level. Otherwise,
5007 // it will return TRUE and take the lock.
5009 // Note that the taker must release the lock via IncrementLoadLevel.
5011 BOOL FileLoadLock::Acquire(FileLoadLevel targetLevel)
5013 WRAPPER_NO_CONTRACT;
5015 // If we are already loaded to the desired level, the lock is "free".
5016 if (m_level >= targetLevel)
5019 if (!DeadlockAwareEnter())
5021 // We failed to get the lock due to a deadlock.
5025 if (m_level >= targetLevel)
5034 BOOL FileLoadLock::CanAcquire(FileLoadLevel targetLevel)
5036 // If we are already loaded to the desired level, the lock is "free".
5037 if (m_level >= targetLevel)
5040 return CanDeadlockAwareEnter();
5043 #if !defined(DACCESS_COMPILE) && (defined(LOGGING) || defined(STRESS_LOG))
5044 static const char *fileLoadLevelName[] =
5046 "CREATE", // FILE_LOAD_CREATE
5047 "BEGIN", // FILE_LOAD_BEGIN
5048 "FIND_NATIVE_IMAGE", // FILE_LOAD_FIND_NATIVE_IMAGE
5049 "VERIFY_NATIVE_IMAGE_DEPENDENCIES", // FILE_LOAD_VERIFY_NATIVE_IMAGE_DEPENDENCIES
5050 "ALLOCATE", // FILE_LOAD_ALLOCATE
5051 "ADD_DEPENDENCIES", // FILE_LOAD_ADD_DEPENDENCIES
5052 "PRE_LOADLIBRARY", // FILE_LOAD_PRE_LOADLIBRARY
5053 "LOADLIBRARY", // FILE_LOAD_LOADLIBRARY
5054 "POST_LOADLIBRARY", // FILE_LOAD_POST_LOADLIBRARY
5055 "EAGER_FIXUPS", // FILE_LOAD_EAGER_FIXUPS
5056 "VTABLE FIXUPS", // FILE_LOAD_VTABLE_FIXUPS
5057 "DELIVER_EVENTS", // FILE_LOAD_DELIVER_EVENTS
5058 "LOADED", // FILE_LOADED
5059 "VERIFY_EXECUTION", // FILE_LOAD_VERIFY_EXECUTION
5060 "ACTIVE", // FILE_ACTIVE
5062 #endif // !DACCESS_COMPILE && (LOGGING || STRESS_LOG)
5064 BOOL FileLoadLock::CompleteLoadLevel(FileLoadLevel level, BOOL success)
5071 PRECONDITION(HasLock());
5075 // Increment may happen more than once if reentrancy occurs (e.g. LoadLibrary)
5076 if (level > m_level)
5078 // Must complete each level in turn, unless we have an error
5079 CONSISTENCY_CHECK(m_pDomainFile->IsError() || (level == (m_level+1)));
5080 // Remove the lock from the list if the load is completed
5081 if (level >= FILE_ACTIVE)
5085 PEFileListLockHolder lock((PEFileListLock*)m_pList);
5088 BOOL fDbgOnly_SuccessfulUnlink =
5090 m_pList->Unlink(this);
5091 _ASSERTE(fDbgOnly_SuccessfulUnlink);
5093 m_pDomainFile->ClearLoading();
5095 CONSISTENCY_CHECK(m_dwRefCount >= 2); // Caller (LoadDomainFile) should have 1 refcount and m_pList should have another which was acquired in FileLoadLock::Create.
5097 m_level = (FileLoadLevel)level;
5100 // In AppDomain::IsLoading, if the lock is taken on m_pList and then FindFileLock returns NULL,
5101 // we depend on the DomainFile's load level being up to date. Hence we must update the load
5102 // level while the m_pList lock is held.
5104 m_pDomainFile->SetLoadLevel(level);
5108 Release(); // Release m_pList's refcount on this lock, which was acquired in FileLoadLock::Create
5113 m_level = (FileLoadLevel)level;
5116 m_pDomainFile->SetLoadLevel(level);
5119 #ifndef DACCESS_COMPILE
5122 case FILE_LOAD_ALLOCATE:
5123 case FILE_LOAD_ADD_DEPENDENCIES:
5124 case FILE_LOAD_DELIVER_EVENTS:
5126 case FILE_ACTIVE: // The timing of stress logs is not critical, so even for the FILE_ACTIVE stage we need not do it while the m_pList lock is held.
5127 STRESS_LOG4(LF_CLASSLOADER, LL_INFO100, "Completed Load Level %s for DomainFile %p in AD %i - success = %i\n", fileLoadLevelName[level], m_pDomainFile, m_AppDomainId.m_dwId, success);
5140 void FileLoadLock::SetError(Exception *ex)
5147 PRECONDITION(CheckPointer(ex));
5148 PRECONDITION(HasLock());
5149 INJECT_FAULT(COMPlusThrowOM(););
5153 m_cachedHR = ex->GetHR();
5155 LOG((LF_LOADER, LL_WARNING, "LOADER: %x:***%s*\t!!!Non-transient error 0x%x\n",
5156 m_pDomainFile->GetAppDomain(), m_pDomainFile->GetSimpleName(), m_cachedHR));
5158 m_pDomainFile->SetError(ex);
5160 CompleteLoadLevel(FILE_ACTIVE, FALSE);
5163 void FileLoadLock::AddRef()
5165 LIMITED_METHOD_CONTRACT;
5166 FastInterlockIncrement((LONG *) &m_dwRefCount);
5169 UINT32 FileLoadLock::Release()
5179 LONG count = FastInterlockDecrement((LONG *) &m_dwRefCount);
5186 FileLoadLock::FileLoadLock(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile)
5187 : ListLockEntry(pLock, pFile, "File load lock"),
5188 m_level((FileLoadLevel) (FILE_LOAD_CREATE)),
5189 m_pDomainFile(pDomainFile),
5191 m_AppDomainId(pDomainFile->GetAppDomain()->GetId())
5193 WRAPPER_NO_CONTRACT;
5197 void FileLoadLock::HolderLeave(FileLoadLock *pThis)
5199 LIMITED_METHOD_CONTRACT;
5209 // Assembly loading:
5211 // Assembly loading is carefully layered to avoid deadlocks in the
5212 // presence of circular loading dependencies.
5213 // A LoadLevel is associated with each assembly as it is being loaded. During the
5214 // act of loading (abstractly, increasing its load level), its lock is
5215 // held, and the current load level is stored on the thread. Any
5216 // recursive loads during that period are automatically restricted to
5217 // only partially load the dependent assembly to the same level as the
5218 // caller (or to one short of that level in the presence of a deadlock
5221 // Each loading stage must be carfully constructed so that
5222 // this constraint is expected and can be dealt with.
5224 // Note that there is one case where this still doesn't handle recursion, and that is the
5225 // security subsytem. The security system runs managed code, and thus must typically fully
5226 // initialize assemblies of permission sets it is trying to use. (And of course, these may be used
5227 // while those assemblies are initializing.) This is dealt with in the historical manner - namely
5228 // the security system passes in a special flag which says that it will deal with null return values
5229 // in the case where a load cannot be safely completed due to such issues.
5232 void AppDomain::LoadSystemAssemblies()
5234 STANDARD_VM_CONTRACT;
5236 // The only reason to make an assembly a "system assembly" is if the EE is caching
5237 // pointers to stuff in the assembly. Because this is going on, we need to preserve
5238 // the invariant that the assembly is loaded into every app domain.
5240 // Right now we have only one system assembly. We shouldn't need to add any more.
5242 LoadAssembly(NULL, SystemDomain::System()->SystemFile(), FILE_ACTIVE);
5245 FileLoadLevel AppDomain::GetDomainFileLoadLevel(DomainFile *pFile)
5255 LoadLockHolder lock(this);
5257 FileLoadLock* pLockEntry = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5259 if (pLockEntry == NULL)
5260 return pFile->GetLoadLevel();
5262 return pLockEntry->GetLoadLevel();
5265 // This checks if the thread has initiated (or completed) loading at the given level. A false guarantees that
5266 // (a) The current thread (or a thread blocking on the current thread) has not started loading the file
5267 // at the given level, and
5268 // (b) No other thread had started loading the file at this level at the start of this function call.
5270 // Note that another thread may start loading the file at that level in a race with the completion of
5271 // this function. However, the caller still has the guarantee that such a load started after this
5272 // function was called (and e.g. any state in place before the function call will be seen by the other thread.)
5274 // Conversely, a true guarantees that either the current thread has started the load step, or another
5275 // thread has completed the load step.
5278 BOOL AppDomain::IsLoading(DomainFile *pFile, FileLoadLevel level)
5281 if (pFile->GetLoadLevel() < level)
5283 FileLoadLock *pLock = NULL;
5285 LoadLockHolder lock(this);
5287 pLock = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5291 // No thread involved with loading
5292 return pFile->GetLoadLevel() >= level;
5298 FileLoadLockRefHolder lockRef(pLock);
5300 if (pLock->Acquire(level))
5302 // We got the lock - therefore no other thread has started this loading step yet.
5307 // We didn't get the lock - either this thread is already doing the load,
5308 // or else the load has already finished.
5313 // CheckLoading is a weaker form of IsLoading, which will not block on
5314 // other threads waiting for their status. This is appropriate for asserts.
5315 CHECK AppDomain::CheckLoading(DomainFile *pFile, FileLoadLevel level)
5318 if (pFile->GetLoadLevel() < level)
5320 FileLoadLock *pLock = NULL;
5322 LoadLockHolder lock(this);
5324 pLock = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5327 && pLock->CanAcquire(level))
5329 // We can get the lock - therefore no other thread has started this loading step yet.
5330 CHECK_FAILF(("Loading step %d has not been initiated yet", level));
5333 // We didn't get the lock - either this thread is already doing the load,
5334 // or else the load has already finished.
5340 CHECK AppDomain::CheckCanLoadTypes(Assembly *pAssembly)
5349 CHECK_MSG(CheckValidModule(pAssembly->GetManifestModule()),
5350 "Type loading can occur only when executing in the assembly's app domain");
5354 CHECK AppDomain::CheckCanExecuteManagedCode(MethodDesc* pMD)
5364 Module* pModule=pMD->GetModule();
5366 CHECK_MSG(CheckValidModule(pModule),
5367 "Managed code can only run when executing in the module's app domain");
5369 if (!pMD->IsInterface() || pMD->IsStatic()) //interfaces require no activation for instance methods
5371 //cctor could have been interupted by ADU
5372 CHECK_MSG(HasUnloadStarted() || pModule->CheckActivated(),
5373 "Managed code can only run when its module has been activated in the current app domain");
5376 CHECK_MSG(!IsPassiveDomain() || pModule->CanExecuteCode(),
5377 "Executing managed code from an unsafe assembly in a Passive AppDomain");
5382 #endif // !DACCESS_COMPILE
5384 void AppDomain::LoadDomainFile(DomainFile *pFile,
5385 FileLoadLevel targetLevel)
5389 if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
5390 if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
5391 if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM();); }
5392 INJECT_FAULT(COMPlusThrowOM(););
5396 // Quick exit if finished
5397 if (pFile->GetLoadLevel() >= targetLevel)
5400 // Handle the error case
5401 pFile->ThrowIfError(targetLevel);
5404 #ifndef DACCESS_COMPILE
5406 if (pFile->IsLoading())
5410 // Load some more if appropriate
5411 LoadLockHolder lock(this);
5413 FileLoadLock* pLockEntry = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5414 if (pLockEntry == NULL)
5416 _ASSERTE (!pFile->IsLoading());
5420 pLockEntry->AddRef();
5424 LoadDomainFile(pLockEntry, targetLevel);
5427 #else // DACCESS_COMPILE
5429 #endif // DACCESS_COMPILE
5432 #ifndef DACCESS_COMPILE
5434 FileLoadLevel AppDomain::GetThreadFileLoadLevel()
5436 WRAPPER_NO_CONTRACT;
5437 if (GetThread()->GetLoadLevelLimiter() == NULL)
5440 return (FileLoadLevel)(GetThread()->GetLoadLevelLimiter()->GetLoadLevel()-1);
5444 Assembly *AppDomain::LoadAssembly(AssemblySpec* pIdentity,
5446 FileLoadLevel targetLevel)
5448 CONTRACT(Assembly *)
5453 PRECONDITION(CheckPointer(pFile));
5454 POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); // May be NULL in recursive load case
5455 INJECT_FAULT(COMPlusThrowOM(););
5459 DomainAssembly *pAssembly = LoadDomainAssembly(pIdentity, pFile, targetLevel);
5460 PREFIX_ASSUME(pAssembly != NULL);
5462 RETURN pAssembly->GetAssembly();
5465 #ifndef CROSSGEN_COMPILE
5467 class LoadDomainAssemblyStress : APIThreadStress
5471 AssemblySpec* pSpec;
5473 FileLoadLevel targetLevel;
5475 LoadDomainAssemblyStress(AppDomain *pThis, AssemblySpec* pSpec, PEAssembly *pFile, FileLoadLevel targetLevel)
5476 : pThis(pThis), pSpec(pSpec), pFile(pFile), targetLevel(targetLevel) {LIMITED_METHOD_CONTRACT;}
5480 WRAPPER_NO_CONTRACT;
5481 STATIC_CONTRACT_SO_INTOLERANT;
5483 pThis->LoadDomainAssembly(pSpec, pFile, targetLevel);
5486 #endif // CROSSGEN_COMPILE
5488 extern BOOL AreSameBinderInstance(ICLRPrivBinder *pBinderA, ICLRPrivBinder *pBinderB);
5490 DomainAssembly* AppDomain::LoadDomainAssembly( AssemblySpec* pSpec,
5492 FileLoadLevel targetLevel)
5494 STATIC_CONTRACT_THROWS;
5496 if (pSpec == nullptr)
5498 // skip caching, since we don't have anything to base it on
5499 return LoadDomainAssemblyInternal(pSpec, pFile, targetLevel);
5502 DomainAssembly* pRetVal = NULL;
5505 pRetVal = LoadDomainAssemblyInternal(pSpec, pFile, targetLevel);
5509 Exception* pEx=GET_EXCEPTION();
5510 if (!pEx->IsTransient())
5512 // Setup the binder reference in AssemblySpec from the PEAssembly if one is not already set.
5513 ICLRPrivBinder* pCurrentBindingContext = pSpec->GetBindingContext();
5514 ICLRPrivBinder* pBindingContextFromPEAssembly = pFile->GetBindingContext();
5516 if (pCurrentBindingContext == NULL)
5518 // Set the binding context we got from the PEAssembly if AssemblySpec does not
5519 // have that information
5520 _ASSERTE(pBindingContextFromPEAssembly != NULL);
5521 pSpec->SetBindingContext(pBindingContextFromPEAssembly);
5526 // Binding context in the spec should be the same as the binding context in the PEAssembly
5527 _ASSERTE(AreSameBinderInstance(pCurrentBindingContext, pBindingContextFromPEAssembly));
5531 if (!EEFileLoadException::CheckType(pEx))
5534 pSpec->GetFileOrDisplayName(0, name);
5535 pEx=new EEFileLoadException(name, pEx->GetHR(), NULL, pEx);
5536 AddExceptionToCache(pSpec, pEx);
5537 PAL_CPP_THROW(Exception *, pEx);
5540 AddExceptionToCache(pSpec, pEx);
5549 DomainAssembly *AppDomain::LoadDomainAssemblyInternal(AssemblySpec* pIdentity,
5551 FileLoadLevel targetLevel)
5553 CONTRACT(DomainAssembly *)
5558 PRECONDITION(CheckPointer(pFile));
5559 PRECONDITION(pFile->IsSystem() || ::GetAppDomain()==this);
5560 POSTCONDITION(CheckPointer(RETVAL));
5561 POSTCONDITION(RETVAL->GetLoadLevel() >= GetThreadFileLoadLevel()
5562 || RETVAL->GetLoadLevel() >= targetLevel);
5563 POSTCONDITION(RETVAL->CheckNoError(targetLevel));
5564 INJECT_FAULT(COMPlusThrowOM(););
5569 DomainAssembly * result;
5571 #ifndef CROSSGEN_COMPILE
5572 LoadDomainAssemblyStress ts (this, pIdentity, pFile, targetLevel);
5575 // Go into preemptive mode since this may take a while.
5578 // Check for existing fully loaded assembly, or for an assembly which has failed during the loading process.
5579 result = FindAssembly(pFile, FindAssemblyOptions_IncludeFailedToLoad);
5583 // Allocate the DomainAssembly a bit early to avoid GC mode problems. We could potentially avoid
5584 // a rare redundant allocation by moving this closer to FileLoadLock::Create, but it's not worth it.
5586 NewHolder<DomainAssembly> pDomainAssembly;
5587 pDomainAssembly = new DomainAssembly(this, pFile, this->GetLoaderAllocator());
5589 LoadLockHolder lock(this);
5591 // Find the list lock entry
5592 FileLoadLock * fileLock = (FileLoadLock *)lock->FindFileLock(pFile);
5593 if (fileLock == NULL)
5595 // Check again in case we were racing
5596 result = FindAssembly(pFile, FindAssemblyOptions_IncludeFailedToLoad);
5599 // We are the first one in - create the DomainAssembly
5600 fileLock = FileLoadLock::Create(lock, pFile, pDomainAssembly);
5601 pDomainAssembly.SuppressRelease();
5613 // We pass our ref on fileLock to LoadDomainFile to release.
5615 // Note that if we throw here, we will poison fileLock with an error condition,
5616 // so it will not be removed until app domain unload. So there is no need
5617 // to release our ref count.
5618 result = (DomainAssembly *)LoadDomainFile(fileLock, targetLevel);
5622 result->EnsureLoadLevel(targetLevel);
5626 result->EnsureLoadLevel(targetLevel);
5628 // Malformed metadata may contain a Module reference to what is actually
5629 // an Assembly. In this case we need to throw an exception, since returning
5630 // a DomainModule as a DomainAssembly is a type safety violation.
5631 if (!result->IsAssembly())
5633 ThrowHR(COR_E_ASSEMBLYEXPECTED);
5636 // Cache result in all cases, since found pFile could be from a different AssemblyRef than pIdentity
5637 // Do not cache WindowsRuntime assemblies, they are cached in code:CLRPrivTypeCacheWinRT
5638 if ((pIdentity != NULL) && (pIdentity->CanUseWithBindingCache()) && (result->CanUseWithBindingCache()))
5639 GetAppDomain()->AddAssemblyToCache(pIdentity, result);
5642 } // AppDomain::LoadDomainAssembly
5647 FileLoadLock *pLock;
5648 FileLoadLevel targetLevel;
5652 #ifndef CROSSGEN_COMPILE
5653 static void LoadDomainFile_Wrapper(void *ptr)
5655 WRAPPER_NO_CONTRACT;
5656 STATIC_CONTRACT_SO_INTOLERANT;
5658 LoadFileArgs *args = (LoadFileArgs *) ptr;
5659 args->result = GetAppDomain()->LoadDomainFile(args->pLock, args->targetLevel);
5661 #endif // !CROSSGEN_COMPILE
5663 DomainFile *AppDomain::LoadDomainFile(FileLoadLock *pLock, FileLoadLevel targetLevel)
5665 CONTRACT(DomainFile *)
5668 PRECONDITION(CheckPointer(pLock));
5669 PRECONDITION(pLock->GetDomainFile()->GetAppDomain() == this);
5670 POSTCONDITION(RETVAL->GetLoadLevel() >= GetThreadFileLoadLevel()
5671 || RETVAL->GetLoadLevel() >= targetLevel);
5672 POSTCONDITION(RETVAL->CheckNoError(targetLevel));
5678 COMPlusThrow(kAppDomainUnloadedException);
5681 APIThreadStress::SyncThreadStress();
5683 DomainFile *pFile = pLock->GetDomainFile();
5685 // Make sure we release the lock on exit
5686 FileLoadLockRefHolder lockRef(pLock);
5688 // We need to perform the early steps of loading mscorlib without a domain transition. This is
5689 // important for bootstrapping purposes - we need to get mscorlib at least partially loaded
5690 // into a domain before we can run serialization code to do the transition.
5692 // Note that we cannot do this in general for all assemblies, because some of the security computations
5693 // require the managed exposed object, which must be created in the correct app domain.
5695 if (this != GetAppDomain()
5696 && pFile->GetFile()->IsSystem()
5697 && targetLevel > FILE_LOAD_ALLOCATE)
5699 // Re-call the routine with a limited load level. This will cause the first part of the load to
5700 // get performed in the current app domain.
5703 LoadDomainFile(pLock, targetLevel > FILE_LOAD_ALLOCATE ? FILE_LOAD_ALLOCATE : targetLevel);
5705 // Now continue on to complete the rest of the load, if any.
5708 // Do a quick out check for the already loaded case.
5709 if (pLock->GetLoadLevel() >= targetLevel)
5711 pFile->ThrowIfError(targetLevel);
5716 #ifndef CROSSGEN_COMPILE
5717 // Make sure we are in the right domain. Many of the load operations require the target domain
5718 // to be the current app domain, most notably anything involving managed code or managed object
5720 if (this != GetAppDomain()
5721 && (!pFile->GetFile()->IsSystem() || targetLevel > FILE_LOAD_ALLOCATE))
5723 // Transition to the correct app domain and perform the load there.
5726 // we will release the lock in the other app domain
5727 lockRef.SuppressRelease();
5729 if(!CanLoadCode() || GetDefaultContext() ==NULL)
5730 COMPlusThrow(kAppDomainUnloadedException);
5731 LoadFileArgs args = {pLock, targetLevel, NULL};
5732 GetThread()->DoADCallBack(this, LoadDomainFile_Wrapper, (void *) &args, ADV_CREATING);
5736 #endif // CROSSGEN_COMPILE
5738 // Initialize a loading queue. This will hold any loads which are triggered recursively but
5739 // which cannot be immediately satisfied due to anti-deadlock constraints.
5741 // PendingLoadQueues are allocated on the stack during a load, and
5742 // shared with all nested loads on the same thread. (Note that we won't use
5743 // "candidate" if we are in a recursive load; that's OK since they are cheap to
5745 FileLoadLevel immediateTargetLevel = targetLevel;
5747 LoadLevelLimiter limit;
5750 // We cannot set a target level higher than that allowed by the limiter currently.
5751 // This is because of anti-deadlock constraints.
5752 if (immediateTargetLevel > limit.GetLoadLevel())
5753 immediateTargetLevel = limit.GetLoadLevel();
5755 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t>>>Load initiated, %s/%s\n",
5756 pFile->GetAppDomain(), pFile->GetSimpleName(),
5757 fileLoadLevelName[immediateTargetLevel], fileLoadLevelName[targetLevel]));
5759 // Now loop and do the load incrementally to the target level.
5760 if (pLock->GetLoadLevel() < immediateTargetLevel)
5763 APIThreadStress::SyncThreadStress();
5765 while (pLock->Acquire(immediateTargetLevel))
5767 FileLoadLevel workLevel;
5769 FileLoadLockHolder fileLock(pLock);
5771 // Work level is next step to do
5772 workLevel = (FileLoadLevel)(fileLock->GetLoadLevel()+1);
5774 // Set up the anti-deadlock constraint: we cannot safely recursively load any assemblies
5775 // on this thread to a higher level than this assembly is being loaded now.
5776 // Note that we do allow work at a parallel level; any deadlocks caused here will
5777 // be resolved by the deadlock detection in the FileLoadLocks.
5778 limit.SetLoadLevel(workLevel);
5781 (workLevel == FILE_LOAD_BEGIN
5782 || workLevel == FILE_LOADED
5783 || workLevel == FILE_ACTIVE)
5784 ? LL_INFO10 : LL_INFO1000,
5785 "LOADER: %p:***%s*\t loading at level %s\n",
5786 this, pFile->GetSimpleName(), fileLoadLevelName[workLevel]));
5788 TryIncrementalLoad(pFile, workLevel, fileLock);
5790 TESTHOOKCALL(CompletedFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5793 if (pLock->GetLoadLevel() == immediateTargetLevel-1)
5795 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t<<<Load limited due to detected deadlock, %s\n",
5796 pFile->GetAppDomain(), pFile->GetSimpleName(),
5797 fileLoadLevelName[immediateTargetLevel-1]));
5801 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t<<<Load completed, %s\n",
5802 pFile->GetAppDomain(), pFile->GetSimpleName(),
5803 fileLoadLevelName[pLock->GetLoadLevel()]));
5807 // There may have been an error stored on the domain file by another thread, or from a previous load
5808 pFile->ThrowIfError(targetLevel);
5810 // There are two normal results from the above loop.
5812 // 1. We succeeded in loading the file to the current thread's load level.
5813 // 2. We succeeded in loading the file to the current thread's load level - 1, due
5814 // to deadlock condition with another thread loading the same assembly.
5816 // Either of these are considered satisfactory results, as code inside a load must expect
5817 // a parial load result.
5819 // However, if load level elevation has occurred, then it is possible for a deadlock to
5820 // prevent us from loading an assembly which was loading before the elevation at a radically
5821 // lower level. In such a case, we throw an exception which transiently fails the current
5822 // load, since it is likely we have not satisfied the caller.
5823 // (An alternate, and possibly preferable, strategy here would be for all callers to explicitly
5824 // identify the minimum load level acceptable via CheckLoadDomainFile and throw from there.)
5826 pFile->RequireLoadLevel((FileLoadLevel)(immediateTargetLevel-1));
5832 void AppDomain::TryIncrementalLoad(DomainFile *pFile, FileLoadLevel workLevel, FileLoadLockHolder &lockHolder)
5834 STANDARD_VM_CONTRACT;
5836 // This is factored out so we don't call EX_TRY in a loop (EX_TRY can _alloca)
5838 BOOL released = FALSE;
5839 FileLoadLock* pLoadLock = lockHolder.GetValue();
5844 // Special case: for LoadLibrary, we cannot hold the lock during the
5845 // actual LoadLibrary call, because we might get a callback from _CorDllMain on any
5846 // other thread. (Note that this requires DomainFile's LoadLibrary to be independently threadsafe.)
5848 if (workLevel == FILE_LOAD_LOADLIBRARY)
5850 lockHolder.Release();
5855 TESTHOOKCALL(NextFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5856 BOOL success = pFile->DoIncrementalLoad(workLevel);
5857 TESTHOOKCALL(CompletingFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5860 // Reobtain lock to increment level. (Note that another thread may
5861 // have already done it which is OK.
5862 if (pLoadLock->Acquire(workLevel))
5864 // note lockHolder.Acquire isn't wired up to actually take the lock
5865 lockHolder = pLoadLock;
5872 // Complete the level.
5873 if (pLoadLock->CompleteLoadLevel(workLevel, success) &&
5874 pLoadLock->GetLoadLevel()==FILE_LOAD_DELIVER_EVENTS)
5876 lockHolder.Release();
5878 pFile->DeliverAsyncEvents();
5884 Exception *pEx = GET_EXCEPTION();
5887 //We will cache this error and wire this load to forever fail,
5888 // unless the exception is transient or the file is loaded OK but just cannot execute
5889 if (!pEx->IsTransient() && !pFile->IsLoaded())
5894 // Reobtain lock to increment level. (Note that another thread may
5895 // have already done it which is OK.
5896 if (pLoadLock->Acquire(workLevel)) // note pLockHolder->Acquire isn't wired up to actually take the lock
5898 // note lockHolder.Acquire isn't wired up to actually take the lock
5899 lockHolder = pLoadLock;
5906 // Report the error in the lock
5907 pLoadLock->SetError(pEx);
5910 if (!EEFileLoadException::CheckType(pEx))
5911 EEFileLoadException::Throw(pFile->GetFile(), pEx->GetHR(), pEx);
5914 // Otherwise, we simply abort this load, and can retry later on.
5915 // @todo cleanup: make sure that each level is restartable after an exception, and
5916 // leaves no bad side effects
5921 // Checks whether the module is valid to be in the given app domain (need not be yet loaded)
5922 CHECK AppDomain::CheckValidModule(Module * pModule)
5932 if (pModule->FindDomainFile(this) != NULL)
5937 Assembly * pAssembly = pModule->GetAssembly();
5939 CCHECK(pAssembly->IsDomainNeutral());
5940 #ifdef FEATURE_LOADER_OPTIMIZATION
5941 Assembly * pSharedAssembly = NULL;
5942 _ASSERTE(this == ::GetAppDomain());
5944 SharedAssemblyLocator locator(pAssembly->GetManifestFile());
5945 pSharedAssembly = SharedDomain::GetDomain()->FindShareableAssembly(&locator);
5948 CCHECK(pAssembly == pSharedAssembly);
5956 #ifdef FEATURE_LOADER_OPTIMIZATION
5957 // Loads an existing Module into an AppDomain
5958 // WARNING: this can only be done in a very limited scenario - the Module must be an unloaded domain neutral
5959 // dependency in the app domain in question. Normal code should not call this!
5960 DomainFile *AppDomain::LoadDomainNeutralModuleDependency(Module *pModule, FileLoadLevel targetLevel)
5962 CONTRACT(DomainFile *)
5967 PRECONDITION(::GetAppDomain()==this);
5968 PRECONDITION(CheckPointer(pModule));
5969 POSTCONDITION(CheckValidModule(pModule));
5970 POSTCONDITION(CheckPointer(RETVAL));
5971 POSTCONDITION(RETVAL->GetModule() == pModule);
5975 DomainFile *pDomainFile = pModule->FindDomainFile(this);
5977 STRESS_LOG3(LF_CLASSLOADER, LL_INFO100,"LDNMD: DomainFile %p for module %p in AppDomain %i\n",pDomainFile,pModule,GetId().m_dwId);
5979 if (pDomainFile == NULL)
5983 Assembly *pAssembly = pModule->GetAssembly();
5985 DomainAssembly *pDomainAssembly = pAssembly->FindDomainAssembly(this);
5986 if (pDomainAssembly == NULL)
5988 AssemblySpec spec(this);
5989 spec.InitializeSpec(pAssembly->GetManifestFile());
5991 pDomainAssembly = spec.LoadDomainAssembly(targetLevel);
5995 //if the domain assembly already exists, we need to load it to the target level
5996 pDomainAssembly->EnsureLoadLevel (targetLevel);
5999 if(pAssembly != pDomainAssembly->GetAssembly())
6001 ThrowHR(SECURITY_E_INCOMPATIBLE_SHARE);
6004 _ASSERTE (pModule == pAssembly->GetManifestModule());
6005 pDomainFile = pDomainAssembly;
6009 // If the DomainFile already exists, we need to load it to the target level.
6010 pDomainFile->EnsureLoadLevel (targetLevel);
6016 AppDomain::SharePolicy AppDomain::GetSharePolicy()
6018 LIMITED_METHOD_CONTRACT;
6020 return SHARE_POLICY_NEVER;
6022 #endif // FEATURE_LOADER_OPTIMIZATION
6025 void AppDomain::CheckForMismatchedNativeImages(AssemblySpec * pSpec, const GUID * pGuid)
6027 STANDARD_VM_CONTRACT;
6030 // The native images are ever used only for trusted images in CoreCLR.
6031 // We don't wish to open the IL file at runtime so we just forgo any
6032 // eager consistency checking. But we still want to prevent mistmatched
6033 // NGen images from being used. We record all mappings between assembly
6034 // names and MVID, and fail once we detect mismatch.
6037 if (pSpec->IsStrongNamed() && pSpec->HasPublicKey())
6039 pSpec->ConvertPublicKeyToToken();
6043 // CoreCLR binder unifies assembly versions. Ignore assembly version here to
6044 // detect more types of potential mismatches.
6046 AssemblyMetaDataInternal * pContext = pSpec->GetContext();
6047 pContext->usMajorVersion = (USHORT)-1;
6048 pContext->usMinorVersion = (USHORT)-1;
6049 pContext->usBuildNumber = (USHORT)-1;
6050 pContext->usRevisionNumber = (USHORT)-1;
6052 // Ignore the WinRT type while considering if two assemblies have the same identity.
6053 pSpec->SetWindowsRuntimeType(NULL, NULL);
6055 CrstHolder ch(&m_DomainCrst);
6057 const NativeImageDependenciesEntry * pEntry = m_NativeImageDependencies.Lookup(pSpec);
6061 if (*pGuid != pEntry->m_guidMVID)
6064 msg.Printf("ERROR: Native images generated against multiple versions of assembly %s. ", pSpec->GetName());
6065 WszOutputDebugString(msg.GetUnicode());
6066 COMPlusThrowNonLocalized(kFileLoadException, msg.GetUnicode());
6072 // No entry yet - create one
6074 AllocMemTracker amTracker;
6075 AllocMemTracker *pamTracker = &amTracker;
6077 NativeImageDependenciesEntry * pNewEntry =
6078 new (pamTracker->Track(GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(NativeImageDependenciesEntry)))))
6079 NativeImageDependenciesEntry();
6081 pNewEntry->m_AssemblySpec.CopyFrom(pSpec);
6082 pNewEntry->m_AssemblySpec.CloneFieldsToLoaderHeap(AssemblySpec::ALL_OWNED, GetLowFrequencyHeap(), pamTracker);
6084 pNewEntry->m_guidMVID = *pGuid;
6086 m_NativeImageDependencies.Add(pNewEntry);
6087 amTracker.SuppressRelease();
6092 void AppDomain::SetupSharedStatics()
6099 INJECT_FAULT(COMPlusThrowOM(););
6103 #ifndef CROSSGEN_COMPILE
6104 if (NingenEnabled())
6107 LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: SetupSharedStatics()"));
6109 // don't do any work in init stage. If not init only do work in non-shared case if are default domain
6110 _ASSERTE(!g_fEEInit);
6112 // Because we are allocating/referencing objects, need to be in cooperative mode
6115 static OBJECTHANDLE hSharedStaticsHandle = NULL;
6117 if (hSharedStaticsHandle == NULL) {
6118 // Note that there is no race here since the default domain is always set up first
6119 _ASSERTE(IsDefaultDomain());
6121 MethodTable *pMT = MscorlibBinder::GetClass(CLASS__SHARED_STATICS);
6122 _ASSERTE(pMT->IsClassPreInited());
6124 hSharedStaticsHandle = CreateGlobalHandle(AllocateObject(pMT));
6127 DomainLocalModule *pLocalModule;
6129 if (IsSingleAppDomain())
6131 pLocalModule = MscorlibBinder::GetModule()->GetDomainLocalModule();
6135 pLocalModule = GetDomainLocalBlock()->GetModuleSlot(
6136 MscorlibBinder::GetModule()->GetModuleIndex());
6139 FieldDesc *pFD = MscorlibBinder::GetField(FIELD__SHARED_STATICS__SHARED_STATICS);
6141 OBJECTREF* pHandle = (OBJECTREF*)
6142 ((TADDR)pLocalModule->GetPrecomputedGCStaticsBasePointer()+pFD->GetOffset());
6143 SetObjectReference( pHandle, ObjectFromHandle(hSharedStaticsHandle), this );
6145 // This is a convenient place to initialize String.Empty.
6146 // It is treated as intrinsic by the JIT as so the static constructor would never run.
6147 // Leaving it uninitialized would confuse debuggers.
6149 // String should not have any static constructors.
6150 _ASSERTE(g_pStringClass->IsClassPreInited());
6152 FieldDesc * pEmptyStringFD = MscorlibBinder::GetField(FIELD__STRING__EMPTY);
6153 OBJECTREF* pEmptyStringHandle = (OBJECTREF*)
6154 ((TADDR)pLocalModule->GetPrecomputedGCStaticsBasePointer()+pEmptyStringFD->GetOffset());
6155 SetObjectReference( pEmptyStringHandle, StringObject::GetEmptyString(), this );
6156 #endif // CROSSGEN_COMPILE
6159 DomainAssembly * AppDomain::FindAssembly(PEAssembly * pFile, FindAssemblyOptions options/* = FindAssemblyOptions_None*/)
6166 INJECT_FAULT(COMPlusThrowOM(););
6170 const bool includeFailedToLoad = (options & FindAssemblyOptions_IncludeFailedToLoad) != 0;
6172 if (pFile->HasHostAssembly())
6174 DomainAssembly * pDA = FindAssembly(pFile->GetHostAssembly());
6175 if (pDA != nullptr && (pDA->IsLoaded() || (includeFailedToLoad && pDA->IsError())))
6182 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
6184 (includeFailedToLoad ? kIncludeFailedToLoad : 0) |
6185 (pFile->IsIntrospectionOnly() ? kIncludeIntrospection : kIncludeExecution)));
6186 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
6188 while (i.Next(pDomainAssembly.This()))
6190 PEFile * pManifestFile = pDomainAssembly->GetFile();
6191 if (pManifestFile &&
6192 !pManifestFile->IsResource() &&
6193 pManifestFile->Equals(pFile))
6195 // Caller already has PEAssembly, so we can give DomainAssembly away freely without AddRef
6196 return pDomainAssembly.Extract();
6202 static const AssemblyIterationFlags STANDARD_IJW_ITERATOR_FLAGS =
6203 (AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution | kExcludeCollectible);
6206 void AppDomain::SetFriendlyName(LPCWSTR pwzFriendlyName, BOOL fDebuggerCares/*=TRUE*/)
6211 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6213 INJECT_FAULT(COMPlusThrowOM(););
6217 // Do all computations into a temporary until we're ensured of success
6218 SString tmpFriendlyName;
6221 if (pwzFriendlyName)
6222 tmpFriendlyName.Set(pwzFriendlyName);
6225 // If there is an assembly, try to get the name from it.
6226 // If no assembly, but if it's the DefaultDomain, then give it a name
6228 if (m_pRootAssembly)
6230 tmpFriendlyName.SetUTF8(m_pRootAssembly->GetSimpleName());
6232 SString::Iterator i = tmpFriendlyName.End();
6233 if (tmpFriendlyName.FindBack(i, '.'))
6234 tmpFriendlyName.Truncate(i);
6238 if (IsDefaultDomain())
6239 tmpFriendlyName.Set(DEFAULT_DOMAIN_FRIENDLY_NAME);
6241 // This is for the profiler - if they call GetFriendlyName on an AppdomainCreateStarted
6242 // event, then we want to give them a temporary name they can use.
6243 else if (GetId().m_dwId != 0)
6245 tmpFriendlyName.Clear();
6246 tmpFriendlyName.Printf(W("%s %d"), OTHER_DOMAIN_FRIENDLY_NAME_PREFIX, GetId().m_dwId);
6252 tmpFriendlyName.Normalize();
6255 m_friendlyName = tmpFriendlyName;
6256 m_friendlyName.Normalize();
6258 if(g_pDebugInterface)
6260 // update the name in the IPC publishing block
6261 if (SUCCEEDED(g_pDebugInterface->UpdateAppDomainEntryInIPC(this)))
6263 // inform the attached debugger that the name of this appdomain has changed.
6264 if (IsDebuggerAttached() && fDebuggerCares)
6265 g_pDebugInterface->NameChangeEvent(this, NULL);
6270 void AppDomain::ResetFriendlyName(BOOL fDebuggerCares/*=TRUE*/)
6272 WRAPPER_NO_CONTRACT;
6273 SetFriendlyName(NULL, fDebuggerCares);
6276 LPCWSTR AppDomain::GetFriendlyName(BOOL fDebuggerCares/*=TRUE*/)
6281 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6283 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
6284 INJECT_FAULT(COMPlusThrowOM(););
6289 // Handle NULL this pointer - this happens sometimes when printing log messages
6290 // but in general shouldn't occur in real code
6295 if (m_friendlyName.IsEmpty())
6296 SetFriendlyName(NULL, fDebuggerCares);
6298 RETURN m_friendlyName;
6301 LPCWSTR AppDomain::GetFriendlyNameForLogging()
6308 POSTCONDITION(CheckPointer(RETVAL,NULL_OK));
6312 // Handle NULL this pointer - this happens sometimes when printing log messages
6313 // but in general shouldn't occur in real code
6317 RETURN (m_friendlyName.IsEmpty() ?W(""):(LPCWSTR)m_friendlyName);
6320 LPCWSTR AppDomain::GetFriendlyNameForDebugger()
6325 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6327 POSTCONDITION(CheckPointer(RETVAL));
6332 if (m_friendlyName.IsEmpty())
6334 BOOL fSuccess = FALSE;
6338 SetFriendlyName(NULL);
6344 // Gobble all exceptions.
6346 EX_END_CATCH(SwallowAllExceptions);
6354 RETURN m_friendlyName;
6358 #endif // !DACCESS_COMPILE
6360 #ifdef DACCESS_COMPILE
6362 PVOID AppDomain::GetFriendlyNameNoSet(bool* isUtf8)
6366 if (!m_friendlyName.IsEmpty())
6369 return m_friendlyName.DacGetRawContent();
6371 else if (m_pRootAssembly)
6374 return (PVOID)m_pRootAssembly->GetSimpleName();
6376 else if (dac_cast<TADDR>(this) ==
6377 dac_cast<TADDR>(SystemDomain::System()->DefaultDomain()))
6380 return (PVOID)DEFAULT_DOMAIN_FRIENDLY_NAME;
6388 #endif // DACCESS_COMPILE
6390 #ifndef DACCESS_COMPILE
6392 BOOL AppDomain::AddFileToCache(AssemblySpec* pSpec, PEAssembly *pFile, BOOL fAllowFailure)
6399 PRECONDITION(CheckPointer(pSpec));
6400 // Hosted fusion binder makes an exception here, so we cannot assert.
6401 //PRECONDITION(pSpec->CanUseWithBindingCache());
6402 //PRECONDITION(pFile->CanUseWithBindingCache());
6403 INJECT_FAULT(COMPlusThrowOM(););
6407 CrstHolder holder(&m_DomainCacheCrst);
6408 // !!! suppress exceptions
6409 if(!m_AssemblyCache.StoreFile(pSpec, pFile) && !fAllowFailure)
6411 // TODO: Disabling the below assertion as currently we experience
6412 // inconsistency on resolving the Microsoft.Office.Interop.MSProject.dll
6413 // This causes below assertion to fire and crashes the VS. This issue
6414 // is being tracked with Dev10 Bug 658555. Brought back it when this bug
6418 EEFileLoadException::Throw(pSpec, FUSION_E_CACHEFILE_FAILED, NULL);
6424 BOOL AppDomain::AddAssemblyToCache(AssemblySpec* pSpec, DomainAssembly *pAssembly)
6431 PRECONDITION(CheckPointer(pSpec));
6432 PRECONDITION(CheckPointer(pAssembly));
6433 PRECONDITION(pSpec->CanUseWithBindingCache());
6434 PRECONDITION(pAssembly->CanUseWithBindingCache());
6435 INJECT_FAULT(COMPlusThrowOM(););
6439 CrstHolder holder(&m_DomainCacheCrst);
6440 // !!! suppress exceptions
6441 BOOL bRetVal = m_AssemblyCache.StoreAssembly(pSpec, pAssembly);
6445 BOOL AppDomain::AddExceptionToCache(AssemblySpec* pSpec, Exception *ex)
6452 PRECONDITION(CheckPointer(pSpec));
6453 PRECONDITION(pSpec->CanUseWithBindingCache());
6454 INJECT_FAULT(COMPlusThrowOM(););
6458 if (ex->IsTransient())
6461 CrstHolder holder(&m_DomainCacheCrst);
6462 // !!! suppress exceptions
6463 return m_AssemblyCache.StoreException(pSpec, ex);
6466 void AppDomain::AddUnmanagedImageToCache(LPCWSTR libraryName, HMODULE hMod)
6473 PRECONDITION(CheckPointer(libraryName));
6474 INJECT_FAULT(COMPlusThrowOM(););
6480 spec.SetCodeBase(libraryName);
6481 m_UnmanagedCache.InsertEntry(&spec, hMod);
6487 HMODULE AppDomain::FindUnmanagedImageInCache(LPCWSTR libraryName)
6494 PRECONDITION(CheckPointer(libraryName,NULL_OK));
6495 POSTCONDITION(CheckPointer(RETVAL,NULL_OK));
6496 INJECT_FAULT(COMPlusThrowOM(););
6499 if(libraryName == NULL) RETURN NULL;
6502 spec.SetCodeBase(libraryName);
6503 RETURN (HMODULE) m_UnmanagedCache.LookupEntry(&spec, 0);
6507 BOOL AppDomain::IsCached(AssemblySpec *pSpec)
6509 WRAPPER_NO_CONTRACT;
6511 // Check to see if this fits our rather loose idea of a reference to mscorlib.
6512 // If so, don't use fusion to bind it - do it ourselves.
6513 if (pSpec->IsMscorlib())
6516 return m_AssemblyCache.Contains(pSpec);
6519 void AppDomain::GetCacheAssemblyList(SetSHash<PTR_DomainAssembly>& assemblyList)
6521 CrstHolder holder(&m_DomainCacheCrst);
6522 m_AssemblyCache.GetAllAssemblies(assemblyList);
6525 PEAssembly* AppDomain::FindCachedFile(AssemblySpec* pSpec, BOOL fThrow /*=TRUE*/)
6541 // Check to see if this fits our rather loose idea of a reference to mscorlib.
6542 // If so, don't use fusion to bind it - do it ourselves.
6543 if (fThrow && pSpec->IsMscorlib())
6545 CONSISTENCY_CHECK(SystemDomain::System()->SystemAssembly() != NULL);
6546 PEAssembly *pFile = SystemDomain::System()->SystemFile();
6551 return m_AssemblyCache.LookupFile(pSpec, fThrow);
6555 BOOL AppDomain::PostBindResolveAssembly(AssemblySpec *pPrePolicySpec,
6556 AssemblySpec *pPostPolicySpec,
6557 HRESULT hrBindResult,
6558 AssemblySpec **ppFailedSpec)
6560 STATIC_CONTRACT_THROWS;
6561 STATIC_CONTRACT_GC_TRIGGERS;
6562 PRECONDITION(CheckPointer(pPrePolicySpec));
6563 PRECONDITION(CheckPointer(pPostPolicySpec));
6564 PRECONDITION(CheckPointer(ppFailedSpec));
6566 BOOL fFailure = TRUE;
6567 *ppFailedSpec = pPrePolicySpec;
6570 PEAssemblyHolder result;
6572 if ((EEFileLoadException::GetFileLoadKind(hrBindResult) == kFileNotFoundException) ||
6573 (hrBindResult == FUSION_E_REF_DEF_MISMATCH) ||
6574 (hrBindResult == FUSION_E_INVALID_NAME))
6576 result = TryResolveAssembly(*ppFailedSpec, FALSE /* fPreBind */);
6578 if (result != NULL && pPrePolicySpec->CanUseWithBindingCache() && result->CanUseWithBindingCache())
6582 // Given the post-policy resolve event construction of the CLR binder,
6583 // chained managed resolve events can race with each other, therefore we do allow
6584 // the adding of the result to fail. Checking for already chached specs
6585 // is not an option as it would introduce another race window.
6586 // The binder does a re-fetch of the
6587 // orignal binding spec and therefore will not cause inconsistency here.
6588 // For the purposes of the resolve event, failure to add to the cache still is a success.
6589 AddFileToCache(pPrePolicySpec, result, TRUE /* fAllowFailure */);
6590 if (*ppFailedSpec != pPrePolicySpec && pPostPolicySpec->CanUseWithBindingCache())
6592 AddFileToCache(pPostPolicySpec, result, TRUE /* fAllowFailure */ );
6600 //----------------------------------------------------------------------------------------
6601 // Helper class for hosted binder
6603 class PEAssemblyAsPrivAssemblyInfo : public IUnknownCommon<ICLRPrivAssemblyInfo>
6606 //------------------------------------------------------------------------------------
6609 PEAssemblyAsPrivAssemblyInfo(PEAssembly *pPEAssembly)
6611 LIMITED_METHOD_CONTRACT;
6612 STATIC_CONTRACT_THROWS;
6614 if (pPEAssembly == nullptr)
6615 ThrowHR(E_UNEXPECTED);
6617 pPEAssembly->AddRef();
6618 m_pPEAssembly = pPEAssembly;
6621 //------------------------------------------------------------------------------------
6622 // ICLRPrivAssemblyInfo methods
6624 //------------------------------------------------------------------------------------
6625 STDMETHOD(GetAssemblyName)(
6626 __in DWORD cchBuffer,
6627 __out_opt LPDWORD pcchBuffer,
6628 __out_ecount_part_opt(cchBuffer, *pcchBuffer) LPWSTR wzBuffer)
6640 if ((cchBuffer == 0) != (wzBuffer == nullptr))
6642 return E_INVALIDARG;
6645 LPCUTF8 szName = m_pPEAssembly->GetSimpleName();
6649 IfFailRet(FString::Utf8_Unicode_Length(szName, &bIsAscii, &cchName));
6651 if (cchBuffer < cchName + 1)
6653 if (pcchBuffer != nullptr)
6655 *pcchBuffer = cchName + 1;
6657 return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
6661 IfFailRet(FString::Utf8_Unicode(szName, bIsAscii, wzBuffer, cchName));
6662 if (pcchBuffer != nullptr)
6664 *pcchBuffer = cchName;
6670 //------------------------------------------------------------------------------------
6671 STDMETHOD(GetAssemblyVersion)(
6677 WRAPPER_NO_CONTRACT;
6678 return m_pPEAssembly->GetVersion(pMajor, pMinor, pBuild, pRevision);
6681 //------------------------------------------------------------------------------------
6682 STDMETHOD(GetAssemblyPublicKey)(
6687 STATIC_CONTRACT_LIMITED_METHOD;
6688 STATIC_CONTRACT_CAN_TAKE_LOCK;
6690 VALIDATE_PTR_RET(pcbBuffer);
6691 VALIDATE_CONDITION((pbBuffer == nullptr) == (cbBuffer == 0), return E_INVALIDARG);
6697 // Note: PEAssembly::GetPublicKey will return bogus data pointer when *pcbBuffer == 0
6698 LPCVOID pbKey = m_pPEAssembly->GetPublicKey(pcbBuffer);
6700 if (*pcbBuffer != 0)
6702 if (pbBuffer != nullptr && cbBuffer >= *pcbBuffer)
6704 memcpy(pbBuffer, pbKey, *pcbBuffer);
6709 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
6714 hr = S_FALSE; // ==> No public key
6717 EX_CATCH_HRESULT(hr);
6723 ReleaseHolder<PEAssembly> m_pPEAssembly;
6726 //-----------------------------------------------------------------------------------------------------------------
6727 static HRESULT VerifyBindHelper(
6728 ICLRPrivAssembly *pPrivAssembly,
6729 IAssemblyName *pAssemblyName,
6730 PEAssembly *pPEAssembly)
6732 STATIC_CONTRACT_THROWS;
6733 STATIC_CONTRACT_GC_TRIGGERS;
6736 // Create an ICLRPrivAssemblyInfo to call to ICLRPrivAssembly::VerifyBind
6737 NewHolder<PEAssemblyAsPrivAssemblyInfo> pPrivAssemblyInfoImpl = new PEAssemblyAsPrivAssemblyInfo(pPEAssembly);
6738 ReleaseHolder<ICLRPrivAssemblyInfo> pPrivAssemblyInfo;
6739 IfFailRet(pPrivAssemblyInfoImpl->QueryInterface(__uuidof(ICLRPrivAssemblyInfo), (LPVOID *)&pPrivAssemblyInfo));
6740 pPrivAssemblyInfoImpl.SuppressRelease();
6742 // Call VerifyBind to give the host a chance to reject the bind based on assembly image contents.
6743 IfFailRet(pPrivAssembly->VerifyBind(pAssemblyName, pPrivAssembly, pPrivAssemblyInfo));
6748 //-----------------------------------------------------------------------------------------------------------------
6749 HRESULT AppDomain::BindAssemblySpecForHostedBinder(
6750 AssemblySpec * pSpec,
6751 IAssemblyName * pAssemblyName,
6752 ICLRPrivBinder * pBinder,
6753 PEAssembly ** ppAssembly)
6755 STANDARD_VM_CONTRACT;
6757 PRECONDITION(CheckPointer(pSpec));
6758 PRECONDITION(pSpec->GetAppDomain() == this);
6759 PRECONDITION(CheckPointer(ppAssembly));
6760 PRECONDITION(pSpec->GetCodeBase() == nullptr);
6765 // The Fusion binder can throw (to preserve compat, since it will actually perform an assembly
6766 // load as part of it's bind), so we need to be careful here to catch any FileNotFoundException
6767 // objects if fThrowIfNotFound is false.
6768 ReleaseHolder<ICLRPrivAssembly> pPrivAssembly;
6770 // We return HRESULTs here on failure instead of throwing as failures here are not necessarily indicative
6771 // of an actual application problem. Returning an error code is substantially faster than throwing, and
6772 // should be used when possible.
6773 IfFailRet(pBinder->BindAssemblyByName(pAssemblyName, &pPrivAssembly));
6775 IfFailRet(BindHostedPrivAssembly(nullptr, pPrivAssembly, pAssemblyName, ppAssembly));
6781 //-----------------------------------------------------------------------------------------------------------------
6783 AppDomain::BindHostedPrivAssembly(
6784 PEAssembly * pParentAssembly,
6785 ICLRPrivAssembly * pPrivAssembly,
6786 IAssemblyName * pAssemblyName,
6787 PEAssembly ** ppAssembly,
6788 BOOL fIsIntrospectionOnly) // = FALSE
6790 STANDARD_VM_CONTRACT;
6792 PRECONDITION(CheckPointer(pPrivAssembly));
6793 PRECONDITION(CheckPointer(ppAssembly));
6797 *ppAssembly = nullptr;
6799 // See if result has been previously loaded.
6801 DomainAssembly* pDomainAssembly = FindAssembly(pPrivAssembly);
6802 if (pDomainAssembly != nullptr)
6804 *ppAssembly = clr::SafeAddRef(pDomainAssembly->GetFile());
6808 if (*ppAssembly != nullptr)
6809 { // Already exists: ask the binder to verify and return the assembly.
6810 return VerifyBindHelper(pPrivAssembly, pAssemblyName, *ppAssembly);
6813 // Get the IL PEFile.
6814 PEImageHolder pPEImageIL;
6816 // Does not already exist, so get the resource for the assembly and load it.
6818 ReleaseHolder<ICLRPrivResource> pIResourceIL;
6820 IfFailRet(pPrivAssembly->GetImageResource(ASSEMBLY_IMAGE_TYPE_IL, &dwImageType, &pIResourceIL));
6821 _ASSERTE(dwImageType == ASSEMBLY_IMAGE_TYPE_IL);
6823 pPEImageIL = PEImage::OpenImage(pIResourceIL, MDInternalImport_Default);
6826 // See if an NI is available.
6827 DWORD dwAvailableImages;
6828 IfFailRet(pPrivAssembly->GetAvailableImageTypes(&dwAvailableImages));
6829 _ASSERTE(dwAvailableImages & ASSEMBLY_IMAGE_TYPE_IL); // Just double checking that IL bit is always set.
6831 // Get the NI PEFile if available.
6832 PEImageHolder pPEImageNI;
6833 if (dwAvailableImages & ASSEMBLY_IMAGE_TYPE_NATIVE)
6836 ReleaseHolder<ICLRPrivResource> pIResourceNI;
6838 IfFailRet(pPrivAssembly->GetImageResource(ASSEMBLY_IMAGE_TYPE_NATIVE, &dwImageType, &pIResourceNI));
6839 _ASSERTE(dwImageType == ASSEMBLY_IMAGE_TYPE_NATIVE || FAILED(hr));
6841 pPEImageNI = PEImage::OpenImage(pIResourceNI, MDInternalImport_TrustedNativeImage);
6843 _ASSERTE(pPEImageIL != nullptr);
6845 // Create a PEAssembly using the IL and NI images.
6846 PEAssemblyHolder pPEAssembly = PEAssembly::Open(pParentAssembly, pPEImageIL, pPEImageNI, pPrivAssembly, fIsIntrospectionOnly);
6849 // Ask the binder to verify.
6850 IfFailRet(VerifyBindHelper(pPrivAssembly, pAssemblyName, pPEAssembly));
6853 *ppAssembly = pPEAssembly.Extract();
6856 } // AppDomain::BindHostedPrivAssembly
6858 //---------------------------------------------------------------------------------------------------------------------
6859 PEAssembly * AppDomain::BindAssemblySpec(
6860 AssemblySpec * pSpec,
6861 BOOL fThrowOnFileNotFound,
6862 BOOL fRaisePrebindEvents,
6863 StackCrawlMark * pCallerStackMark,
6864 BOOL fUseHostBinderIfAvailable)
6866 STATIC_CONTRACT_THROWS;
6867 STATIC_CONTRACT_GC_TRIGGERS;
6868 PRECONDITION(CheckPointer(pSpec));
6869 PRECONDITION(pSpec->GetAppDomain() == this);
6870 PRECONDITION(this==::GetAppDomain());
6874 BOOL fForceReThrow = FALSE;
6876 #if defined(FEATURE_COMINTEROP)
6877 // Handle WinRT assemblies in the classic/hybrid scenario. If this is an AppX process,
6878 // then this case will be handled by the previous block as part of the full set of
6879 // available binding hosts.
6880 if (pSpec->IsContentType_WindowsRuntime())
6884 // Get the assembly display name.
6885 ReleaseHolder<IAssemblyName> pAssemblyName;
6887 IfFailThrow(pSpec->CreateFusionName(&pAssemblyName, TRUE, TRUE));
6890 PEAssemblyHolder pAssembly;
6894 hr = BindAssemblySpecForHostedBinder(pSpec, pAssemblyName, m_pWinRtBinder, &pAssembly);
6896 goto EndTry2; // Goto end of try block.
6899 // The combination of this conditional catch/ the following if statement which will throw reduces the count of exceptions
6900 // thrown in scenarios where the exception does not escape the method. We cannot get rid of the try/catch block, as
6901 // there are cases within some of the clrpriv binder's which throw.
6902 // Note: In theory, FileNotFound should always come here as HRESULT, never as exception.
6903 EX_CATCH_HRESULT_IF(hr,
6904 !fThrowOnFileNotFound && Assembly::FileNotFound(hr))
6906 if (FAILED(hr) && (fThrowOnFileNotFound || !Assembly::FileNotFound(hr)))
6908 if (Assembly::FileNotFound(hr))
6910 _ASSERTE(fThrowOnFileNotFound);
6911 // Uses defaultScope
6912 EEFileLoadException::Throw(pSpec, hr);
6915 // WinRT type bind failures
6916 _ASSERTE(pSpec->IsContentType_WindowsRuntime());
6917 if (hr == HRESULT_FROM_WIN32(APPMODEL_ERROR_NO_PACKAGE)) // Returned by RoResolveNamespace when using 3rd party WinRT types in classic process
6919 if (fThrowOnFileNotFound)
6920 { // Throw NotSupportedException (with custom message) wrapped by TypeLoadException to give user type name for diagnostics
6921 // Note: TypeLoadException is equivalent of FileNotFound in WinRT world
6922 EEMessageException ex(kNotSupportedException, IDS_EE_WINRT_THIRDPARTY_NOTSUPPORTED);
6923 EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex);
6926 else if ((hr == CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT) || // Returned e.g. for WinRT type name without namespace
6927 (hr == COR_E_PLATFORMNOTSUPPORTED)) // Using WinRT on pre-Win8 OS
6929 if (fThrowOnFileNotFound)
6930 { // Throw ArgumentException/PlatformNotSupportedException wrapped by TypeLoadException to give user type name for diagnostics
6931 // Note: TypeLoadException is equivalent of FileNotFound in WinRT world
6932 EEMessageException ex(hr);
6933 EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex);
6941 _ASSERTE((FAILED(hr) && !fThrowOnFileNotFound) || pAssembly != nullptr);
6943 return pAssembly.Extract();
6946 #endif // FEATURE_COMINTEROP
6947 if (pSpec->HasUniqueIdentity())
6949 HRESULT hrBindResult = S_OK;
6950 PEAssemblyHolder result;
6955 if (!IsCached(pSpec))
6959 bool fAddFileToCache = false;
6961 BOOL fIsWellKnown = FALSE;
6963 // Use CoreClr's fusion alternative
6964 CoreBindResult bindResult;
6966 pSpec->Bind(this, fThrowOnFileNotFound, &bindResult, FALSE /* fNgenExplicitBind */, FALSE /* fExplicitBindToNativeImage */, pCallerStackMark);
6967 hrBindResult = bindResult.GetHRBindResult();
6969 if (bindResult.Found())
6971 if (SystemDomain::SystemFile() && bindResult.IsMscorlib())
6973 // Avoid rebinding to another copy of mscorlib
6974 result = SystemDomain::SystemFile();
6975 result.SuppressRelease(); // Didn't get a refcount
6979 // IsSystem on the PEFile should be false, even for mscorlib satellites
6980 result = PEAssembly::Open(&bindResult,
6981 FALSE, pSpec->IsIntrospectionOnly());
6983 fAddFileToCache = true;
6985 // Setup the reference to the binder, which performed the bind, into the AssemblySpec
6986 ICLRPrivBinder* pBinder = result->GetBindingContext();
6987 _ASSERTE(pBinder != NULL);
6988 pSpec->SetBindingContext(pBinder);
6992 if (fAddFileToCache)
6996 if (pSpec->CanUseWithBindingCache() && result->CanUseWithBindingCache())
6998 // Failure to add simply means someone else beat us to it. In that case
6999 // the FindCachedFile call below (after catch block) will update result
7000 // to the cached value.
7001 AddFileToCache(pSpec, result, TRUE /*fAllowFailure*/);
7004 else if (!fIsWellKnown)
7006 _ASSERTE(fThrowOnFileNotFound == FALSE);
7008 // Don't trigger the resolve event for the CoreLib satellite assembly. A misbehaving resolve event may
7009 // return an assembly that does not match, and this can cause recursive resource lookups during error
7010 // reporting. The CoreLib satellite assembly is loaded from relative locations based on the culture, see
7011 // AssemblySpec::Bind().
7012 if (!pSpec->IsMscorlibSatellite())
7014 // Trigger the resolve event also for non-throw situation.
7015 // However, this code path will behave as if the resolve handler has thrown,
7016 // that is, not trigger an MDA.
7018 AssemblySpec NewSpec(this);
7019 AssemblySpec *pFailedSpec = NULL;
7021 fForceReThrow = TRUE; // Managed resolve event handler can throw
7023 // Purposly ignore return value
7024 PostBindResolveAssembly(pSpec, &NewSpec, hrBindResult, &pFailedSpec);
7032 Exception *ex = GET_EXCEPTION();
7034 AssemblySpec NewSpec(this);
7035 AssemblySpec *pFailedSpec = NULL;
7037 // Let transient exceptions or managed resolve event handler exceptions propagate
7038 if (ex->IsTransient() || fForceReThrow)
7044 // This is not executed for SO exceptions so we need to disable the backout
7045 // stack validation to prevent false violations from being reported.
7046 DISABLE_BACKOUT_STACK_VALIDATION;
7048 BOOL fFailure = PostBindResolveAssembly(pSpec, &NewSpec, ex->GetHR(), &pFailedSpec);
7051 BOOL bFileNotFoundException =
7052 (EEFileLoadException::GetFileLoadKind(ex->GetHR()) == kFileNotFoundException);
7054 if (!bFileNotFoundException)
7056 fFailure = AddExceptionToCache(pFailedSpec, ex);
7057 } // else, fFailure stays TRUE
7058 // Effectively, fFailure == bFileNotFoundException || AddExceptionToCache(pFailedSpec, ex)
7060 // Only throw this exception if we are the first in the cache
7064 // If the BindingFailure MDA is enabled, trigger one for this failure
7065 // Note: TryResolveAssembly() can also throw if an AssemblyResolve event subscriber throws
7066 // and the MDA isn't sent in this case (or for transient failure cases)
7068 #ifdef MDA_SUPPORTED
7069 MdaBindingFailure* pProbe = MDA_GET_ASSISTANT(BindingFailure);
7072 // Transition to cooperative GC mode before using any OBJECTREFs.
7075 OBJECTREF exceptionObj = GET_THROWABLE();
7076 GCPROTECT_BEGIN(exceptionObj)
7078 pProbe->BindFailed(pFailedSpec, &exceptionObj);
7084 // In the same cases as for the MDA, store the failure information for DAC to read
7085 if (IsDebuggerAttached()) {
7086 FailedAssembly *pFailed = new FailedAssembly();
7087 pFailed->Initialize(pFailedSpec, ex);
7088 IfFailThrow(m_failedAssemblies.Append(pFailed));
7091 if (!bFileNotFoundException || fThrowOnFileNotFound)
7094 // V1.1 App-compatibility workaround. See VSW530166 if you want to whine about it.
7096 // In Everett, if we failed to download an assembly because of a broken network cable,
7097 // we returned a FileNotFoundException with a COR_E_FILENOTFOUND hr embedded inside
7098 // (which would be exposed when marshaled to native.)
7100 // In Whidbey, we now set the more appropriate INET_E_RESOURCE_NOT_FOUND hr. But
7101 // the online/offline switch code in VSTO for Everett hardcoded a check for
7102 // COR_E_FILENOTFOUND.
7104 // So now, to keep that code from breaking, we have to remap INET_E_RESOURCE_NOT_FOUND
7105 // back to COR_E_FILENOTFOUND. We're doing it here rather down in Fusion so as to affect
7106 // the least number of callers.
7108 if (ex->GetHR() == INET_E_RESOURCE_NOT_FOUND)
7110 EEFileLoadException::Throw(pFailedSpec, COR_E_FILENOTFOUND, ex);
7113 if (EEFileLoadException::CheckType(ex))
7115 if (pFailedSpec == pSpec)
7117 EX_RETHROW; //preserve the information
7121 StackSString exceptionDisplayName, failedSpecDisplayName;
7123 ((EEFileLoadException*)ex)->GetName(exceptionDisplayName);
7124 pFailedSpec->GetFileOrDisplayName(0, failedSpecDisplayName);
7126 if (exceptionDisplayName.CompareCaseInsensitive(failedSpecDisplayName) == 0)
7128 EX_RETHROW; // Throw the original exception. Otherwise, we'd throw an exception that contains the same message twice.
7133 EEFileLoadException::Throw(pFailedSpec, ex->GetHR(), ex);
7140 EX_END_CATCH(RethrowTerminalExceptions);
7142 // Now, if it's a cacheable bind we need to re-fetch the result from the cache, as we may have been racing with another
7143 // thread to store our result. Note that we may throw from here, if there is a cached exception.
7144 // This will release the refcount of the current result holder (if any), and will replace
7145 // it with a non-addref'ed result
7146 if (pSpec->CanUseWithBindingCache() && (result== NULL || result->CanUseWithBindingCache()))
7148 result = FindCachedFile(pSpec);
7154 return result.Extract();
7158 // Unsupported content type
7159 if (fThrowOnFileNotFound)
7161 ThrowHR(COR_E_BADIMAGEFORMAT);
7165 } // AppDomain::BindAssemblySpec
7169 PEAssembly *AppDomain::TryResolveAssembly(AssemblySpec *pSpec, BOOL fPreBind)
7171 STATIC_CONTRACT_THROWS;
7172 STATIC_CONTRACT_GC_TRIGGERS;
7173 STATIC_CONTRACT_MODE_ANY;
7175 PEAssembly *result = NULL;
7179 result = pSpec->ResolveAssemblyFile(this, fPreBind);
7183 Exception *pEx = GET_EXCEPTION();
7185 if (!pEx->IsTransient())
7187 AddExceptionToCache(pSpec, pEx);
7188 if (!EEFileLoadException::CheckType(pEx))
7189 EEFileLoadException::Throw(pSpec, pEx->GetHR(), pEx);
7198 ULONG AppDomain::AddRef()
7200 LIMITED_METHOD_CONTRACT;
7201 return InterlockedIncrement(&m_cRef);
7204 ULONG AppDomain::Release()
7211 PRECONDITION(m_cRef > 0);
7215 ULONG cRef = InterlockedDecrement(&m_cRef);
7218 _ASSERTE (m_Stage == STAGE_CREATING || m_Stage == STAGE_CLOSED);
7221 TESTHOOKCALL(AppDomainDestroyed(adid.m_dwId));
7227 AppDomain* AppDomain::s_pAppDomainToRaiseUnloadEvent;
7228 BOOL AppDomain::s_fProcessUnloadDomainEvent = FALSE;
7230 #ifndef CROSSGEN_COMPILE
7232 void AppDomain::RaiseUnloadDomainEvent_Wrapper(LPVOID ptr)
7239 INJECT_FAULT(COMPlusThrowOM(););
7244 AppDomain* pDomain = (AppDomain *) ptr;
7245 pDomain->RaiseUnloadDomainEvent();
7248 void AppDomain::ProcessUnloadDomainEventOnFinalizeThread()
7257 Thread *pThread = GetThread();
7258 _ASSERTE (pThread && IsFinalizerThread());
7260 // if we are not unloading domain now, do not process the event
7261 if (SystemDomain::AppDomainBeingUnloaded() == NULL)
7263 s_pAppDomainToRaiseUnloadEvent->SetStage(STAGE_UNLOAD_REQUESTED);
7264 s_pAppDomainToRaiseUnloadEvent->EnableADUnloadWorker(
7265 s_pAppDomainToRaiseUnloadEvent->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7266 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, NULL);
7269 FastInterlockExchange((LONG*)&s_fProcessUnloadDomainEvent, TRUE);
7270 AppDomain::EnableADUnloadWorkerForFinalizer();
7271 pThread->SetThreadStateNC(Thread::TSNC_RaiseUnloadEvent);
7272 s_pAppDomainToRaiseUnloadEvent->RaiseUnloadDomainEvent();
7273 pThread->ResetThreadStateNC(Thread::TSNC_RaiseUnloadEvent);
7274 s_pAppDomainToRaiseUnloadEvent->EnableADUnloadWorker(
7275 s_pAppDomainToRaiseUnloadEvent->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7276 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, NULL);
7277 FastInterlockExchange((LONG*)&s_fProcessUnloadDomainEvent, FALSE);
7279 if (pThread->IsAbortRequested())
7281 pThread->UnmarkThreadForAbort(Thread::TAR_Thread);
7285 void AppDomain::RaiseUnloadDomainEvent()
7296 Thread *pThread = GetThread();
7297 if (this != pThread->GetDomain())
7299 pThread->DoADCallBack(this, AppDomain::RaiseUnloadDomainEvent_Wrapper, this,ADV_FINALIZER|ADV_COMPILATION);
7305 APPDOMAINREF Domain;
7308 ZeroMemory(&gc, sizeof(gc));
7310 GCPROTECT_BEGIN(gc);
7311 gc.Domain = (APPDOMAINREF) GetRawExposedObject();
7312 if (gc.Domain != NULL)
7314 gc.Delegate = gc.Domain->m_pDomainUnloadEventHandler;
7315 if (gc.Delegate != NULL)
7316 DistributeEvent(&gc.Delegate, (OBJECTREF *) &gc.Domain);
7322 void AppDomain::RaiseLoadingAssemblyEvent(DomainAssembly *pAssembly)
7328 PRECONDITION(this == GetAppDomain());
7335 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
7340 APPDOMAINREF AppDomainRef;
7343 ZeroMemory(&gc, sizeof(gc));
7345 if ((gc.AppDomainRef = (APPDOMAINREF) GetRawExposedObject()) != NULL) {
7346 if (gc.AppDomainRef->m_pAssemblyEventHandler != NULL)
7349 GCPROTECT_BEGIN(gc);
7351 gc.orThis = pAssembly->GetExposedAssemblyObject();
7353 MethodDescCallSite onAssemblyLoad(METHOD__APP_DOMAIN__ON_ASSEMBLY_LOAD, &gc.orThis);
7355 // GetExposedAssemblyObject may cause a gc, so call this before filling args[0]
7356 args[1] = ObjToArgSlot(gc.orThis);
7357 args[0] = ObjToArgSlot(gc.AppDomainRef);
7359 onAssemblyLoad.Call(args);
7368 EX_END_CATCH(SwallowAllExceptions);
7372 BOOL AppDomain::OnUnhandledException(OBJECTREF *pThrowable, BOOL isTerminating/*=TRUE*/)
7374 STATIC_CONTRACT_NOTHROW;
7375 STATIC_CONTRACT_GC_TRIGGERS;
7376 STATIC_CONTRACT_MODE_ANY;
7382 // The Everett behavior was to send the unhandled exception event only to the Default
7383 // AppDomain (since that's the only place that exceptions actually went unhandled).
7385 // During Whidbey development, we broadcast the event to all AppDomains in the process.
7387 // But the official shipping Whidbey behavior is that the unhandled exception event is
7388 // sent to the Default AppDomain and to whatever AppDomain the exception went unhandled
7389 // in. To achieve this, we declare the exception to be unhandled *BEFORE* we marshal
7390 // it back to the Default AppDomain at the base of the Finalizer, threadpool and managed
7393 // The rationale for sending the event to the Default AppDomain as well as the one the
7394 // exception went unhandled in is:
7396 // 1) This is compatible with the pre-Whidbey behavior, where only the Default AppDomain
7397 // received the notification.
7399 // 2) This is convenient for hosts, which don't want to bother injecting listeners into
7400 // every single AppDomain.
7402 AppDomain *pAppDomain = GetAppDomain();
7403 OBJECTREF orSender = 0;
7405 GCPROTECT_BEGIN(orSender);
7407 orSender = pAppDomain->GetRawExposedObject();
7409 retVal = pAppDomain->RaiseUnhandledExceptionEventNoThrow(&orSender, pThrowable, isTerminating);
7417 // Move outside of the AppDomain iteration, to avoid issues with the GC Frames being outside
7418 // the domain transition. This is a chronic issue that causes us to report roots for an AppDomain
7419 // after we have left it. This causes problems with AppDomain unloading that we only find
7420 // with stress coverage..
7421 void AppDomain::RaiseOneExitProcessEvent()
7433 APPDOMAINREF Domain;
7436 ZeroMemory(&gc, sizeof(gc));
7438 GCPROTECT_BEGIN(gc);
7439 gc.Domain = (APPDOMAINREF) SystemDomain::GetCurrentDomain()->GetRawExposedObject();
7440 if (gc.Domain != NULL)
7442 gc.Delegate = gc.Domain->m_pProcessExitEventHandler;
7443 if (gc.Delegate != NULL)
7444 DistributeEvent(&gc.Delegate, (OBJECTREF *) &gc.Domain);
7449 // Local wrapper used in AppDomain::RaiseExitProcessEvent,
7450 // introduced solely to avoid stack overflow because of _alloca in the loop.
7451 // It's just factored out body of the loop, but it has to be a member method of AppDomain,
7452 // because it calls private RaiseOneExitProcessEvent
7453 /*static*/ void AppDomain::RaiseOneExitProcessEvent_Wrapper(AppDomainIterator* pi)
7455 STATIC_CONTRACT_MODE_COOPERATIVE;
7456 STATIC_CONTRACT_THROWS;
7457 STATIC_CONTRACT_GC_TRIGGERS;
7459 ENTER_DOMAIN_PTR(pi->GetDomain(), ADV_ITERATOR)
7460 AppDomain::RaiseOneExitProcessEvent();
7461 END_DOMAIN_TRANSITION;
7464 static LONG s_ProcessedExitProcessEventCount = 0;
7466 LONG GetProcessedExitProcessEventCount()
7468 LIMITED_METHOD_CONTRACT;
7469 return s_ProcessedExitProcessEventCount;
7472 void AppDomain::RaiseExitProcessEvent()
7477 STATIC_CONTRACT_MODE_COOPERATIVE;
7478 STATIC_CONTRACT_THROWS;
7479 STATIC_CONTRACT_GC_TRIGGERS;
7481 // Only finalizer thread during shutdown can call this function.
7482 _ASSERTE ((g_fEEShutDown&ShutDown_Finalize1) && GetThread() == FinalizerThread::GetFinalizerThread());
7484 _ASSERTE (GetThread()->PreemptiveGCDisabled());
7486 _ASSERTE (GetThread()->GetDomain()->IsDefaultDomain());
7488 AppDomainIterator i(TRUE);
7491 RaiseOneExitProcessEvent_Wrapper(&i);
7492 FastInterlockIncrement(&s_ProcessedExitProcessEventCount);
7498 AppDomain::RaiseUnhandledExceptionEventNoThrow(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating)
7511 bRetVal = RaiseUnhandledExceptionEvent(pSender, pThrowable, isTerminating);
7516 EX_END_CATCH(SwallowAllExceptions) // Swallow any errors.
7522 AppDomain::HasUnhandledExceptionEventHandler()
7527 GC_NOTRIGGER; //essential
7531 if (!CanThreadEnter(GetThread()))
7533 if (GetRawExposedObject()==NULL)
7535 return (((APPDOMAINREF)GetRawExposedObject())->m_pUnhandledExceptionEventHandler!=NULL);
7539 AppDomain::RaiseUnhandledExceptionEvent(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating)
7546 INJECT_FAULT(COMPlusThrowOM(););
7550 if (!HasUnhandledExceptionEventHandler())
7553 BOOL result = FALSE;
7555 _ASSERTE(pThrowable != NULL && IsProtectedByGCFrame(pThrowable));
7556 _ASSERTE(pSender != NULL && IsProtectedByGCFrame(pSender));
7558 _ASSERTE(this == GetThread()->GetDomain());
7561 OBJECTREF orDelegate = NULL;
7563 GCPROTECT_BEGIN(orDelegate);
7565 APPDOMAINREF orAD = (APPDOMAINREF) GetAppDomain()->GetRawExposedObject();
7569 orDelegate = orAD->m_pUnhandledExceptionEventHandler;
7570 if (orDelegate != NULL)
7573 DistributeUnhandledExceptionReliably(&orDelegate, pSender, pThrowable, isTerminating);
7582 #endif // CROSSGEN_COMPILE
7584 // You must be in the correct context before calling this
7585 // routine. Therefore, it is only good for initializing the
7587 void AppDomain::InitializeDomainContext(BOOL allowRedirects,
7596 INJECT_FAULT(COMPlusThrowOM(););
7600 if (NingenEnabled())
7603 CreateFusionContext();
7608 #ifndef CROSSGEN_COMPILE
7610 STRINGREF pFilePath;
7613 PTRARRAYREF propertyNames;
7614 PTRARRAYREF propertyValues;
7616 ZeroMemory(&gc, sizeof(gc));
7618 GCPROTECT_BEGIN(gc);
7621 gc.pFilePath = StringObject::NewString(pwszPath);
7626 gc.pConfig = StringObject::NewString(pwszConfig);
7630 if ((gc.ref = GetExposedObject()) != NULL)
7632 MethodDescCallSite setupDomain(METHOD__APP_DOMAIN__SETUP_DOMAIN);
7636 ObjToArgSlot(gc.ref),
7637 BoolToArgSlot(allowRedirects),
7638 ObjToArgSlot(gc.pFilePath),
7639 ObjToArgSlot(gc.pConfig),
7640 ObjToArgSlot(gc.propertyNames),
7641 ObjToArgSlot(gc.propertyValues)
7643 setupDomain.Call(args);
7646 #endif // CROSSGEN_COMPILE
7650 IUnknown *AppDomain::CreateFusionContext()
7652 CONTRACT(IUnknown *)
7657 POSTCONDITION(CheckPointer(RETVAL));
7658 INJECT_FAULT(COMPlusThrowOM(););
7662 if (!m_pFusionContext)
7664 ETWOnStartup (FusionAppCtx_V1, FusionAppCtxEnd_V1);
7665 CLRPrivBinderCoreCLR *pTPABinder = NULL;
7669 // Initialize the assembly binder for the default context loads for CoreCLR.
7670 IfFailThrow(CCoreCLRBinderHelper::DefaultBinderSetupContext(GetId().m_dwId, &pTPABinder));
7671 m_pFusionContext = reinterpret_cast<IUnknown *>(pTPABinder);
7673 // By default, initial binding context setup for CoreCLR is also the TPABinding context
7674 (m_pTPABinderContext = pTPABinder)->AddRef();
7678 RETURN m_pFusionContext;
7683 //---------------------------------------------------------------------------------------
7685 // AppDomain::IsDebuggerAttached - is a debugger attached to this process
7691 // TRUE if a debugger is attached to this process, FALSE otherwise.
7694 // This is identical to CORDebuggerAttached. This exists idependantly for legacy reasons - we used to
7695 // support attaching to individual AppDomains. This should probably go away eventually.
7698 BOOL AppDomain::IsDebuggerAttached()
7700 LIMITED_METHOD_CONTRACT;
7702 if (CORDebuggerAttached())
7712 #ifdef DEBUGGING_SUPPORTED
7714 // This is called from the debugger to request notification events from
7715 // Assemblies, Modules, Types in this appdomain.
7716 BOOL AppDomain::NotifyDebuggerLoad(int flags, BOOL attaching)
7718 WRAPPER_NO_CONTRACT;
7719 BOOL result = FALSE;
7721 if (!attaching && !IsDebuggerAttached())
7726 // Attach to our assemblies
7727 LOG((LF_CORDB, LL_INFO100, "AD::NDA: Iterating assemblies\n"));
7728 i = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution));
7729 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
7730 while (i.Next(pDomainAssembly.This()))
7732 result = (pDomainAssembly->NotifyDebuggerLoad(flags, attaching) ||
7739 void AppDomain::NotifyDebuggerUnload()
7741 WRAPPER_NO_CONTRACT;
7742 if (!IsDebuggerAttached())
7745 LOG((LF_CORDB, LL_INFO10, "AD::NDD domain [%d] %#08x %ls\n",
7746 GetId().m_dwId, this, GetFriendlyNameForLogging()));
7748 LOG((LF_CORDB, LL_INFO100, "AD::NDD: Interating domain bound assemblies\n"));
7749 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution));
7750 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
7752 // Detach from our assemblies
7753 while (i.Next(pDomainAssembly.This()))
7755 LOG((LF_CORDB, LL_INFO100, "AD::NDD: Iterating assemblies\n"));
7756 pDomainAssembly->NotifyDebuggerUnload();
7759 #endif // DEBUGGING_SUPPORTED
7761 void AppDomain::SetSystemAssemblyLoadEventSent(BOOL fFlag)
7763 LIMITED_METHOD_CONTRACT;
7765 m_dwFlags |= LOAD_SYSTEM_ASSEMBLY_EVENT_SENT;
7767 m_dwFlags &= ~LOAD_SYSTEM_ASSEMBLY_EVENT_SENT;
7770 BOOL AppDomain::WasSystemAssemblyLoadEventSent(void)
7772 LIMITED_METHOD_CONTRACT;
7773 return ((m_dwFlags & LOAD_SYSTEM_ASSEMBLY_EVENT_SENT) == 0) ? FALSE : TRUE;
7776 #ifndef CROSSGEN_COMPILE
7777 // U->M thunks created in this domain and not associated with a delegate.
7778 UMEntryThunkCache *AppDomain::GetUMEntryThunkCache()
7785 INJECT_FAULT(COMPlusThrowOM(););
7789 if (!m_pUMEntryThunkCache)
7791 UMEntryThunkCache *pUMEntryThunkCache = new UMEntryThunkCache(this);
7793 if (FastInterlockCompareExchangePointer(&m_pUMEntryThunkCache, pUMEntryThunkCache, NULL) != NULL)
7795 // some thread swooped in and set the field
7796 delete pUMEntryThunkCache;
7799 _ASSERTE(m_pUMEntryThunkCache);
7800 return m_pUMEntryThunkCache;
7803 #ifdef FEATURE_COMINTEROP
7805 ComCallWrapperCache *AppDomain::GetComCallWrapperCache()
7812 INJECT_FAULT(COMPlusThrowOM(););
7816 if (! m_pComCallWrapperCache)
7818 BaseDomain::LockHolder lh(this);
7820 if (! m_pComCallWrapperCache)
7821 m_pComCallWrapperCache = ComCallWrapperCache::Create(this);
7823 _ASSERTE(m_pComCallWrapperCache);
7824 return m_pComCallWrapperCache;
7827 RCWRefCache *AppDomain::GetRCWRefCache()
7829 CONTRACT(RCWRefCache*)
7834 POSTCONDITION(CheckPointer(RETVAL));
7838 if (!m_pRCWRefCache) {
7839 NewHolder<RCWRefCache> pRCWRefCache = new RCWRefCache(this);
7840 if (FastInterlockCompareExchangePointer(&m_pRCWRefCache, (RCWRefCache *)pRCWRefCache, NULL) == NULL)
7842 pRCWRefCache.SuppressRelease();
7845 RETURN m_pRCWRefCache;
7848 RCWCache *AppDomain::CreateRCWCache()
7855 INJECT_FAULT(COMPlusThrowOM(););
7856 POSTCONDITION(CheckPointer(RETVAL));
7860 // Initialize the global RCW cleanup list here as well. This is so that it
7861 // it guaranteed to exist if any RCW's are created, but it is not created
7863 if (!g_pRCWCleanupList)
7865 SystemDomain::LockHolder lh;
7867 if (!g_pRCWCleanupList)
7868 g_pRCWCleanupList = new RCWCleanupList();
7870 _ASSERTE(g_pRCWCleanupList);
7873 BaseDomain::LockHolder lh(this);
7876 m_pRCWCache = new RCWCache(this);
7882 void AppDomain::ReleaseRCWs(LPVOID pCtxCookie)
7884 WRAPPER_NO_CONTRACT;
7886 m_pRCWCache->ReleaseWrappersWorker(pCtxCookie);
7888 RemoveWinRTFactoryObjects(pCtxCookie);
7891 void AppDomain::DetachRCWs()
7893 WRAPPER_NO_CONTRACT;
7895 m_pRCWCache->DetachWrappersWorker();
7898 #endif // FEATURE_COMINTEROP
7900 BOOL AppDomain::CanThreadEnter(Thread *pThread)
7902 WRAPPER_NO_CONTRACT;
7904 if (m_Stage < STAGE_EXITED)
7907 if (pThread == SystemDomain::System()->GetUnloadingThread())
7908 return m_Stage < STAGE_FINALIZING;
7909 if (pThread == FinalizerThread::GetFinalizerThread())
7910 return m_Stage < STAGE_FINALIZED;
7915 void AppDomain::AllowThreadEntrance(AppDomain * pApp)
7923 PRECONDITION(CheckPointer(pApp));
7927 if (pApp->GetUnloadRequestThread() == NULL)
7929 // This is asynchonous unload, either by a host, or by AppDomain.Unload from AD unload event.
7930 if (!pApp->IsUnloadingFromUnloadEvent())
7932 pApp->SetStage(STAGE_UNLOAD_REQUESTED);
7933 pApp->EnableADUnloadWorker(
7934 pApp->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7939 SystemDomain::LockHolder lh; // we don't want to reopen appdomain if other thread can be preparing to unload it
7941 #ifdef FEATURE_COMINTEROP
7942 if (pApp->m_pComCallWrapperCache)
7943 pApp->m_pComCallWrapperCache->ResetDomainIsUnloading();
7944 #endif // FEATURE_COMINTEROP
7946 pApp->SetStage(STAGE_OPEN);
7949 void AppDomain::RestrictThreadEntrance(AppDomain * pApp)
7954 DISABLED(GC_TRIGGERS);
7956 DISABLED(FORBID_FAULT);
7957 PRECONDITION(CheckPointer(pApp));
7961 #ifdef FEATURE_COMINTEROP
7962 // Set the flag on our CCW cache so stubs won't enter
7963 if (pApp->m_pComCallWrapperCache)
7964 pApp->m_pComCallWrapperCache->SetDomainIsUnloading();
7965 #endif // FEATURE_COMINTEROP
7967 SystemDomain::LockHolder lh; // we don't want to reopen appdomain if other thread can be preparing to unload it
7968 // Release our ID so remoting and thread pool won't enter
7969 pApp->SetStage(STAGE_EXITED);
7972 void AppDomain::Exit(BOOL fRunFinalizers, BOOL fAsyncExit)
7982 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Exiting domain [%d] %#08x %ls\n",
7983 GetId().m_dwId, this, GetFriendlyNameForLogging()));
7985 RestrictEnterHolder RestrictEnter(this);
7988 SystemDomain::LockHolder lh; // we don't want to close appdomain if other thread can be preparing to unload it
7989 SetStage(STAGE_EXITING); // Note that we're trying to exit
7992 // Raise the event indicating the domain is being unloaded.
7993 if (GetDefaultContext())
7995 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, this);
7997 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
7998 //if (timeout == INFINITE)
8000 // timeout = 20000; // 20 seconds
8002 DWORD timeoutForFinalizer = GetEEPolicy()->GetTimeout(OPR_FinalizerRun);
8003 ULONGLONG curTime = CLRGetTickCount64();
8004 ULONGLONG endTime = 0;
8005 if (timeout != INFINITE)
8007 endTime = curTime + timeout;
8008 // We will try to kill AD unload event if it takes too long, and then we move on to the next registered caller.
8012 while (s_pAppDomainToRaiseUnloadEvent != NULL)
8014 FinalizerThread::FinalizerThreadWait(s_fProcessUnloadDomainEvent?timeout:timeoutForFinalizer);
8015 if (endTime != 0 && s_pAppDomainToRaiseUnloadEvent != NULL)
8017 if (CLRGetTickCount64() >= endTime)
8020 sThreadId.Printf(W("%x"), FinalizerThread::GetFinalizerThread()->GetThreadId());
8021 COMPlusThrow(kCannotUnloadAppDomainException,
8022 IDS_EE_ADUNLOAD_CANT_UNWIND_THREAD,
8029 // Tell the tiered compilation manager to stop initiating any new work for background
8030 // jit optimization. Its possible the standard thread unwind mechanisms would pre-emptively
8031 // evacuate the jit threadpool worker threads from the domain on their own, but I see no reason
8032 // to take the risk of relying on them when we can easily augment with a cooperative
8033 // shutdown check. This notification only initiates the process of evacuating the threads
8034 // and then the UnwindThreads() call below is where blocking will occur to ensure the threads
8035 // have exited the domain.
8037 #ifdef FEATURE_TIERED_COMPILATION
8038 m_tieredCompilationManager.Shutdown(FALSE);
8042 // Set up blocks so no threads can enter except for the finalizer and the thread
8043 // doing the unload.
8046 RestrictThreadEntrance(this);
8048 // Cause existing threads to abort out of this domain. This should ensure all
8049 // normal threads are outside the domain, and we've already ensured that no new threads
8052 PerAppDomainTPCountList::AppDomainUnloadingHolder tpAdUnloadHolder(GetTPIndex());
8055 if (!NingenEnabled())
8060 TESTHOOKCALL(UnwoundThreads(GetId().m_dwId)) ;
8061 ProcessEventForHost(Event_DomainUnload, (PVOID)(UINT_PTR)GetId().m_dwId);
8063 RestrictEnter.SuppressRelease(); //after this point we don't guarantee appdomain consistency
8064 #ifdef PROFILING_SUPPORTED
8065 // Signal profile if present.
8067 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
8069 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) this);
8072 #endif // PROFILING_SUPPORTED
8073 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomains--);
8074 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomainsUnloaded++);
8076 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is exited.\n",
8077 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8079 // Send ETW events for this domain's unload and potentially iterate through this
8080 // domain's modules & assemblies to send events for their unloads as well. This
8081 // needs to occur before STAGE_FINALIZED (to ensure everything is there), so we do
8082 // this before any finalization occurs at all.
8083 ETW::LoaderLog::DomainUnload(this);
8085 CodeVersionManager::OnAppDomainExit(this);
8088 // Spin running finalizers until we flush them all. We need to make multiple passes
8089 // in case the finalizers create more finalizable objects. This is important to clear
8090 // the finalizable objects as roots, as well as to actually execute the finalizers. This
8091 // will only finalize instances instances of types that aren't potentially agile becuase we can't
8092 // risk finalizing agile objects. So we will be left with instances of potentially agile types
8093 // in handles or statics.
8095 // <TODO>@todo: Need to ensure this will terminate in a reasonable amount of time. Eventually
8096 // we should probably start passing FALSE for fRunFinalizers. Also I'm not sure we
8097 // guarantee that FinalizerThreadWait will ever terminate in general.</TODO>
8100 SetStage(STAGE_FINALIZING);
8102 // Flush finalizers now.
8103 FinalizerThread::UnloadAppDomain(this, fRunFinalizers);
8105 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8106 ULONGLONG startTime = CLRGetTickCount64();
8107 ULONGLONG elapsedTime = 0;
8108 DWORD finalizerWait = 0;
8110 while (FinalizerThread::GetUnloadingAppDomain() != NULL)
8113 if (timeout != INFINITE)
8115 elapsedTime = CLRGetTickCount64() - startTime;
8117 if (timeout > elapsedTime)
8119 finalizerWait = timeout - static_cast<DWORD>(elapsedTime);
8121 FinalizerThread::FinalizerThreadWait(finalizerWait); //will set stage to finalized
8122 if (timeout != INFINITE && FinalizerThread::GetUnloadingAppDomain() != NULL)
8124 elapsedTime = CLRGetTickCount64() - startTime;
8125 if (timeout <= elapsedTime)
8128 // TODO: Consider escalation from RudeAppDomain
8134 tpAdUnloadHolder.SuppressRelease();
8135 PerAppDomainTPCountList::ResetAppDomainTPCounts(GetTPIndex());
8137 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is finalized.\n",
8138 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8141 AppDomainRefHolder This(this);
8142 AddRef(); // Hold a reference so CloseDomain won't delete us yet
8143 CloseDomain(); // Remove ourself from the list of app domains
8145 // This needs to be done prior to destroying the handle tables below.
8146 ReleaseDomainBoundInfo();
8149 // It should be impossible to run non-mscorlib code in this domain now.
8150 // Cleanup all of our roots except the handles. We do this to allow as many
8151 // finalizers as possible to run correctly. If we delete the handles, they
8154 if (!NingenEnabled())
8161 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is cleared.\n",
8162 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8164 if (fAsyncExit && fRunFinalizers)
8167 m_AssemblyCache.Clear();
8168 ClearFusionContext();
8170 if (!NingenEnabled())
8172 AddMemoryPressure();
8175 SystemDomain::System()->AddToDelayedUnloadList(this, fAsyncExit);
8176 SystemDomain::SetUnloadDomainCleared();
8177 if (m_dwId.m_dwId!=0)
8178 SystemDomain::ReleaseAppDomainId(m_dwId);
8179 #ifdef PROFILING_SUPPORTED
8180 // Always signal profile if present, even when failed.
8182 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
8184 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) this, S_OK);
8187 #endif // PROFILING_SUPPORTED
8191 void AppDomain::Close()
8200 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is collected.\n",
8201 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8204 #if CHECK_APP_DOMAIN_LEAKS
8205 if (g_pConfig->AppDomainLeaks())
8206 // at this point shouldn't have any non-agile objects in the heap because we finalized all the non-agile ones.
8207 SyncBlockCache::GetSyncBlockCache()->CheckForUnloadedInstances(GetIndex());
8208 #endif // CHECK_APP_DOMAIN_LEAKS
8211 RemoveMemoryPressure();
8213 _ASSERTE(m_cRef>0); //should be alive at this point otherwise iterator can revive us and crash
8215 SystemDomain::LockHolder lh; // Avoid races with AppDomainIterator
8216 SetStage(STAGE_CLOSED);
8219 // CONSIDER: move releasing remoting cache from managed code to here.
8223 void AppDomain::ResetUnloadRequestThread(ADID Id)
8229 PRECONDITION(!IsADUnloadHelperThread());
8234 AppDomainFromIDHolder ad(Id, TRUE);
8235 if(!ad.IsUnloaded() && ad->m_Stage < STAGE_UNLOAD_REQUESTED)
8237 Thread *pThread = ad->GetUnloadRequestThread();
8238 if(pThread==GetThread())
8240 ad->m_dwThreadsStillInAppDomain=(ULONG)-1;
8244 if (pThread->GetUnloadBoundaryFrame() && pThread->IsBeingAbortedForADUnload())
8246 pThread->UnmarkThreadForAbort(Thread::TAR_ADUnload);
8248 ad->GetUnloadRequestThread()->ResetUnloadBoundaryFrame();
8249 pThread->ResetBeginAbortedForADUnload();
8252 ad->SetUnloadRequestThread(NULL);
8258 int g_fADUnloadWorkerOK = -1;
8260 HRESULT AppDomain::UnloadById(ADID dwId, BOOL fSync,BOOL fExceptionsPassThrough)
8264 if(fExceptionsPassThrough) {THROWS;} else {NOTHROW;}
8266 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_TRIGGERS);}
8271 if (dwId==(ADID)DefaultADID)
8272 return COR_E_CANNOTUNLOADAPPDOMAIN;
8274 Thread *pThread = GetThread();
8276 // Finalizer thread can not wait until AD unload is done,
8277 // because AD unload is going to wait for Finalizer Thread.
8278 if (fSync && pThread == FinalizerThread::GetFinalizerThread() &&
8279 !pThread->HasThreadStateNC(Thread::TSNC_RaiseUnloadEvent))
8280 return COR_E_CANNOTUNLOADAPPDOMAIN;
8283 // AD unload helper thread should have been created.
8284 _ASSERTE (g_fADUnloadWorkerOK == 1);
8286 _ASSERTE (!IsADUnloadHelperThread());
8288 BOOL fIsRaisingUnloadEvent = (pThread != NULL && pThread->HasThreadStateNC(Thread::TSNC_RaiseUnloadEvent));
8290 if (fIsRaisingUnloadEvent)
8292 AppDomainFromIDHolder pApp(dwId, TRUE, AppDomainFromIDHolder::SyncType_GC);
8294 if (pApp.IsUnloaded() || ! pApp->CanLoadCode() || pApp->GetId().m_dwId == 0)
8295 return COR_E_APPDOMAINUNLOADED;
8297 pApp->EnableADUnloadWorker();
8303 ADUnloadSinkHolder pSink;
8306 SystemDomain::LockHolder ulh;
8308 AppDomainFromIDHolder pApp(dwId, TRUE, AppDomainFromIDHolder::SyncType_ADLock);
8310 if (pApp.IsUnloaded() || ! pApp->CanLoadCode() || pApp->GetId().m_dwId == 0)
8311 return COR_E_APPDOMAINUNLOADED;
8313 if (g_fADUnloadWorkerOK != 1)
8316 return E_UNEXPECTED;
8321 pApp->EnableADUnloadWorker();
8325 pSink = pApp->PrepareForWaitUnloadCompletion();
8327 pApp->EnableADUnloadWorker();
8329 // release the holders - we don't care anymore if the appdomain is gone
8332 #ifdef FEATURE_TESTHOOKS
8333 if (fExceptionsPassThrough)
8335 CONTRACT_VIOLATION(FaultViolation);
8336 return UnloadWaitNoCatch(dwId,pSink);
8340 return UnloadWait(dwId,pSink);
8343 HRESULT AppDomain::UnloadWait(ADID Id, ADUnloadSink * pSink)
8349 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_TRIGGERS);}
8356 // IF you ever try to change this to something not using events, please address the fact that
8357 // AppDomain::StopEEAndUnwindThreads relies on that events are used.
8359 pSink->WaitUnloadCompletion();
8361 EX_CATCH_HRESULT(hr);
8364 hr=pSink->GetUnloadResult();
8368 ResetUnloadRequestThread(Id);
8373 #ifdef FEATURE_TESTHOOKS
8374 HRESULT AppDomain::UnloadWaitNoCatch(ADID Id, ADUnloadSink * pSink)
8376 STATIC_CONTRACT_THROWS;
8377 STATIC_CONTRACT_MODE_ANY;
8379 Holder<ADID, DoNothing<ADID>, AppDomain::ResetUnloadRequestThread> resetUnloadHolder(Id);
8381 // IF you ever try to change this to something not using events, please address the fact that
8382 // AppDomain::StopEEAndUnwindThreads relies on that events are used.
8383 pSink->WaitUnloadCompletion();
8385 HRESULT hr = pSink->GetUnloadResult();
8388 resetUnloadHolder.SuppressRelease();
8394 void AppDomain::Unload(BOOL fForceUnload)
8401 INJECT_FAULT(COMPlusThrowOM(););
8405 #ifdef FEATURE_MULTICOREJIT
8407 // Avoid profiling file is partially written in ASP.net scenarios, call it earlier
8408 GetMulticoreJitManager().StopProfile(true);
8412 Thread *pThread = GetThread();
8415 if (! fForceUnload && !g_pConfig->AppDomainUnload())
8418 EPolicyAction action;
8419 EClrOperation operation;
8420 if (!IsRudeUnload())
8422 operation = OPR_AppDomainUnload;
8426 operation = OPR_AppDomainRudeUnload;
8428 action = GetEEPolicy()->GetDefaultAction(operation,NULL);
8429 GetEEPolicy()->NotifyHostOnDefaultAction(operation,action);
8433 case eUnloadAppDomain:
8435 case eRudeUnloadAppDomain:
8439 case eFastExitProcess:
8440 case eRudeExitProcess:
8441 case eDisableRuntime:
8442 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_ADUNLOAD);
8443 _ASSERTE (!"Should not get here");
8449 #if (defined(_DEBUG) || defined(BREAK_ON_UNLOAD) || defined(AD_LOG_MEMORY) || defined(AD_SNAPSHOT))
8450 static int unloadCount = 0;
8453 #ifdef AD_LOG_MEMORY
8456 static int logMemory = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADLogMemory);
8457 typedef void (__cdecl *LogItFcn) ( int );
8458 static LogItFcn pLogIt = NULL;
8460 if (logMemory && ! pLogIt)
8462 HMODULE hMod = CLRLoadLibrary(W("mpdh.dll"));
8465 pLogIt = (LogItFcn)GetProcAddress(hMod, "logIt");
8474 #endif // AD_LOG_MEMORY
8476 if (IsDefaultDomain() && !IsSingleAppDomain())
8477 COMPlusThrow(kCannotUnloadAppDomainException, IDS_EE_ADUNLOAD_DEFAULT);
8479 _ASSERTE(CanUnload());
8481 if (pThread == FinalizerThread::GetFinalizerThread() || GetUnloadRequestThread() == FinalizerThread::GetFinalizerThread())
8482 COMPlusThrow(kCannotUnloadAppDomainException, IDS_EE_ADUNLOAD_IN_FINALIZER);
8484 _ASSERTE(! SystemDomain::AppDomainBeingUnloaded());
8486 // should not be running in this AD because unload spawned thread in default domain
8487 if (!NingenEnabled())
8489 _ASSERTE(!pThread->IsRunningIn(this, NULL));
8493 #ifdef APPDOMAIN_STATE
8494 _ASSERTE_ALL_BUILDS("clr/src/VM/AppDomain.cpp", pThread->GetDomain()->IsDefaultDomain());
8497 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Unloading domain [%d] %#08x %ls\n", GetId().m_dwId, this, GetFriendlyName()));
8499 STRESS_LOG3 (LF_APPDOMAIN, LL_INFO100, "Unload domain [%d, %d] %p\n", GetId().m_dwId, GetIndex().m_dwIndex, this);
8501 UnloadHolder hold(this);
8503 SystemDomain::System()->SetUnloadRequestingThread(GetUnloadRequestThread());
8504 SystemDomain::System()->SetUnloadingThread(pThread);
8508 static int dumpSB = -1;
8511 dumpSB = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADDumpSB);
8515 LogSpewAlways("Starting unload %3.3d\n", unloadCount);
8516 DumpSyncBlockCache();
8520 BOOL bForceGC=m_bForceGCOnUnload;
8522 #ifdef AD_LOG_MEMORY
8525 #endif // AD_LOG_MEMORY
8528 static int takeSnapShot = -1;
8530 if (takeSnapShot == -1)
8531 takeSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeSnapShot);
8535 #endif // AD_SNAPSHOT
8541 static int cfgForceGC = -1;
8543 if (cfgForceGC == -1)
8544 cfgForceGC =!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_ADULazyMemoryRelease);
8546 bForceGC=bForceGC||cfgForceGC;
8547 AppDomainRefHolder This(this);
8550 // Do the actual unloading
8552 // We do not want other threads to abort the current one.
8553 ThreadPreventAsyncHolder preventAsync;
8554 Exit(TRUE, !bForceGC);
8558 GCHeapUtilities::GetGCHeap()->GarbageCollect();
8559 FinalizerThread::FinalizerThreadWait();
8560 SetStage(STAGE_COLLECTED);
8564 #ifdef AD_LOG_MEMORY
8568 pLogIt(unloadCount);
8570 #endif // AD_LOG_MEMORY
8576 sprintf_s(buffer, _countof(buffer), "vadump -p %d -o > vadump.%d", GetCurrentProcessId(), unloadCount);
8578 sprintf_s(buffer, _countof(buffer), "umdh -p:%d -d -i:1 -f:umdh.%d", GetCurrentProcessId(), unloadCount);
8580 int takeDHSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeDHSnapShot);
8583 sprintf_s(buffer, _countof(buffer), "dh -p %d -s -g -h -b -f dh.%d", GetCurrentProcessId(), unloadCount);
8587 #endif // AD_SNAPSHOT
8592 // do extra finalizer wait to remove any leftover sb entries
8593 FinalizerThread::FinalizerThreadWait();
8594 GCHeapUtilities::GetGCHeap()->GarbageCollect();
8595 FinalizerThread::FinalizerThreadWait();
8596 LogSpewAlways("Done unload %3.3d\n", unloadCount);
8597 DumpSyncBlockCache();
8600 swprintf_s(buffer, NumItems(buffer), W("DumpSB.%d"), unloadCount);
8601 _ASSERTE(WszMoveFileEx(W("COMPLUS.LOG"), buffer, MOVEFILE_REPLACE_EXISTING));
8602 // this will open a new file
8608 void AppDomain::ExceptionUnwind(Frame *pFrame)
8612 DISABLED(GC_TRIGGERS); // EEResourceException
8613 DISABLED(THROWS); // EEResourceException
8618 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind for %8.8x\n", pFrame));
8620 printf("%x AppDomain::ExceptionUnwind for %8.8p\n", GetThread()->GetThreadId(), pFrame);
8622 Thread *pThread = GetThread();
8625 if (! pThread->ShouldChangeAbortToUnload(pFrame))
8627 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind: not first transition or abort\n"));
8631 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind: changing to unload\n"));
8634 OBJECTREF throwable = NULL;
8635 EEResourceException e(kAppDomainUnloadedException, W("Remoting_AppDomainUnloaded_ThreadUnwound"));
8636 throwable = e.GetThrowable();
8638 // reset the exception to an AppDomainUnloadedException
8639 if (throwable != NULL)
8641 GetThread()->SafeSetThrowables(throwable);
8645 BOOL AppDomain::StopEEAndUnwindThreads(unsigned int retryCount, BOOL *pFMarkUnloadRequestThread)
8656 Thread *pThread = NULL;
8657 DWORD nThreadsNeedMoreWork=0;
8658 if (retryCount != (unsigned int)-1 && retryCount < g_pConfig->AppDomainUnloadRetryCount())
8660 Thread *pCurThread = GetThread();
8661 if (pCurThread->CatchAtSafePoint())
8662 pCurThread->PulseGCMode();
8665 // We know which thread is not in the domain now. We just need to
8666 // work on those threads. We do not need to suspend the runtime.
8667 ThreadStoreLockHolder tsl;
8669 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8671 if (pThread == pCurThread)
8676 if (pThread == FinalizerThread::GetFinalizerThread())
8681 if (pThread->GetUnloadBoundaryFrame() == NULL)
8686 // A thread may have UnloadBoundaryFrame set if
8687 // 1. Being unloaded by AD unload helper thread
8688 // 2. Escalation from OOM or SO triggers AD unload
8689 // Here we only need to work on threads that are in the domain. If we work on other threads,
8690 // those threads may be stucked in a finally, and we will not be able to escalate for them,
8691 // therefore AD unload is blocked.
8692 if (pThread->IsBeingAbortedForADUnload() ||
8693 pThread == SystemDomain::System()->GetUnloadRequestingThread())
8695 nThreadsNeedMoreWork++;
8698 if (!(IsRudeUnload() ||
8699 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft())))
8704 if ((pThread == SystemDomain::System()->GetUnloadRequestingThread()) && *pFMarkUnloadRequestThread)
8706 // Mark thread for abortion only once; later on interrupt only
8707 *pFMarkUnloadRequestThread = FALSE;
8708 pThread->SetAbortRequest(m_fRudeUnload? EEPolicy::TA_Rude : EEPolicy::TA_V1Compatible);
8712 if (pThread->m_State & Thread::TS_Interruptible)
8714 pThread->UserInterrupt(Thread::TI_Abort);
8718 if (pThread->PreemptiveGCDisabledOther())
8720 #if defined(FEATURE_HIJACK) && !defined(PLATFORM_UNIX)
8721 Thread::SuspendThreadResult str = pThread->SuspendThread();
8722 if (str == Thread::STR_Success)
8724 if (pThread->PreemptiveGCDisabledOther() &&
8725 (!pThread->IsAbortInitiated() || pThread->IsRudeAbort()))
8727 pThread->HandleJITCaseForAbort();
8729 pThread->ResumeThread();
8734 } // ThreadStoreLockHolder
8736 m_dwThreadsStillInAppDomain=nThreadsNeedMoreWork;
8737 return !nThreadsNeedMoreWork;
8740 // For now piggyback on the GC's suspend EE mechanism
8741 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
8743 // <TODO>@todo: what to do with any threads that didn't stop?</TODO>
8744 _ASSERTE(ThreadStore::s_pThreadStore->DbgBackgroundThreadCount() > 0);
8747 int totalADCount = 0;
8748 int finalizerADCount = 0;
8751 RuntimeExceptionKind reKind = kLastException;
8753 SmallStackSString ssThreadId;
8755 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8757 // we already checked that we're not running in the unload domain
8758 if (pThread == GetThread())
8764 void PrintStackTraceWithADToLog(Thread *pThread);
8765 if (LoggingOn(LF_APPDOMAIN, LL_INFO100)) {
8766 LOG((LF_APPDOMAIN, LL_INFO100, "\nStackTrace for %x\n", pThread->GetThreadId()));
8767 PrintStackTraceWithADToLog(pThread);
8771 Frame *pFrame = pThread->GetFirstTransitionInto(this, &count);
8773 _ASSERTE(count == 0);
8774 if (pThread->IsBeingAbortedForADUnload())
8776 pThread->ResetBeginAbortedForADUnload();
8781 if (pThread != FinalizerThread::GetFinalizerThread())
8783 totalADCount += count;
8784 nThreadsNeedMoreWork++;
8785 pThread->SetUnloadBoundaryFrame(pFrame);
8789 finalizerADCount = count;
8792 // don't setup the exception info for the unloading thread unless it's the last one in
8793 if (retryCount != ((unsigned int) -1) && retryCount > g_pConfig->AppDomainUnloadRetryCount() && reKind == kLastException &&
8794 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft()))
8796 #ifdef AD_BREAK_ON_CANNOT_UNLOAD
8797 static int breakOnCannotUnload = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADBreakOnCannotUnload);
8798 if (breakOnCannotUnload)
8799 _ASSERTE(!"Cannot unload AD");
8800 #endif // AD_BREAK_ON_CANNOT_UNLOAD
8801 reKind = kCannotUnloadAppDomainException;
8802 resId = IDS_EE_ADUNLOAD_CANT_UNWIND_THREAD;
8803 ssThreadId.Printf(W("%x"), pThread->GetThreadId());
8804 STRESS_LOG2(LF_APPDOMAIN, LL_INFO10, "AppDomain::UnwindThreads cannot stop thread %x with %d transitions\n", pThread->GetThreadId(), count);
8805 // don't break out of this early or the assert totalADCount == (int)m_dwThreadEnterCount below will fire
8806 // it's better to chew a little extra time here and make sure our counts are consistent
8808 // only abort the thread requesting the unload if it's the last one in, that way it will get
8809 // notification that the unload failed for some other thread not being aborted. And don't abort
8810 // the finalizer thread - let it finish it's work as it's allowed to be in there. If it won't finish,
8811 // then we will eventually get a CannotUnloadException on it.
8813 if (pThread != FinalizerThread::GetFinalizerThread() &&
8814 // If the domain is rudely unloaded, we will unwind the requesting thread out
8815 // Rude unload is going to succeed, or escalated to disable runtime or higher.
8817 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft())
8822 STRESS_LOG2(LF_APPDOMAIN, LL_INFO100, "AppDomain::UnwindThreads stopping %x with %d transitions\n", pThread->GetThreadId(), count);
8823 LOG((LF_APPDOMAIN, LL_INFO100, "AppDomain::UnwindThreads stopping %x with %d transitions\n", pThread->GetThreadId(), count));
8825 printf("AppDomain::UnwindThreads %x stopping %x with first frame %8.8p\n", GetThread()->GetThreadId(), pThread->GetThreadId(), pFrame);
8827 if (pThread == SystemDomain::System()->GetUnloadRequestingThread())
8829 // Mark thread for abortion only once; later on interrupt only
8830 *pFMarkUnloadRequestThread = FALSE;
8832 pThread->SetAbortRequest(m_fRudeUnload? EEPolicy::TA_Rude : EEPolicy::TA_V1Compatible);
8834 TESTHOOKCALL(UnwindingThreads(GetId().m_dwId)) ;
8836 _ASSERTE(totalADCount + finalizerADCount == (int)m_dwThreadEnterCount);
8838 //@TODO: This is intended to catch a stress bug. Remove when no longer needed.
8839 if (totalADCount + finalizerADCount != (int)m_dwThreadEnterCount)
8840 FreeBuildDebugBreak();
8842 // if our count did get messed up, set it to whatever count we actually found in the domain to avoid looping
8843 // or other problems related to incorrect count. This is very much a bug if this happens - a thread should always
8844 // exit the domain gracefully.
8845 // m_dwThreadEnterCount = totalADCount;
8847 if (reKind != kLastException)
8850 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8852 if (pThread->IsBeingAbortedForADUnload())
8854 pThread->ResetBeginAbortedForADUnload();
8859 // CommonTripThread will handle the abort for any threads that we've marked
8860 ThreadSuspend::RestartEE(FALSE, TRUE);
8861 if (reKind != kLastException)
8862 COMPlusThrow(reKind, resId, ssThreadId.GetUnicode());
8864 _ASSERTE((totalADCount==0 && nThreadsNeedMoreWork==0) ||(totalADCount!=0 && nThreadsNeedMoreWork!=0));
8866 m_dwThreadsStillInAppDomain=nThreadsNeedMoreWork;
8867 return (totalADCount == 0);
8870 void AppDomain::UnwindThreads()
8872 // This function should guarantee appdomain
8873 // consistency even if it fails. Everything that is going
8874 // to make the appdomain impossible to reenter
8875 // should be factored out
8877 // <TODO>@todo: need real synchronization here!!!</TODO>
8886 int retryCount = -1;
8887 m_dwThreadsStillInAppDomain=(ULONG)-1;
8888 ULONGLONG startTime = CLRGetTickCount64();
8890 if (GetEEPolicy()->GetDefaultAction(OPR_AppDomainUnload, NULL) == eRudeUnloadAppDomain &&
8893 GetEEPolicy()->NotifyHostOnDefaultAction(OPR_AppDomainUnload, eRudeUnloadAppDomain);
8897 // Force threads to go through slow path during AD unload.
8898 TSSuspendHolder shTrap;
8900 BOOL fCurrentUnloadMode = IsRudeUnload();
8901 BOOL fMarkUnloadRequestThread = TRUE;
8903 // now wait for all the threads running in our AD to get out
8906 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8907 EPolicyAction action = GetEEPolicy()->GetActionOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, NULL);
8908 if (timeout != INFINITE && action > eUnloadAppDomain) {
8909 // Escalation policy specified.
8910 ULONGLONG curTime = CLRGetTickCount64();
8911 ULONGLONG elapseTime = curTime - startTime;
8912 if (elapseTime > timeout)
8917 case eRudeUnloadAppDomain:
8918 GetEEPolicy()->NotifyHostOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, action);
8920 STRESS_LOG1(LF_APPDOMAIN, LL_INFO100,"Escalating to RADU, adid=%d",GetId().m_dwId);
8923 case eFastExitProcess:
8924 case eRudeExitProcess:
8925 case eDisableRuntime:
8926 GetEEPolicy()->NotifyHostOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, action);
8927 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_TIMEOUT);
8928 _ASSERTE (!"Should not reach here");
8936 if (LoggingOn(LF_APPDOMAIN, LL_INFO100))
8937 DumpADThreadTrack();
8939 BOOL fNextUnloadMode = IsRudeUnload();
8940 if (fCurrentUnloadMode != fNextUnloadMode)
8942 // We have changed from normal unload to rude unload. We need to mark the thread
8943 // with RudeAbort, but we can only do this safely if the runtime is suspended.
8944 fCurrentUnloadMode = fNextUnloadMode;
8947 if (StopEEAndUnwindThreads(retryCount, &fMarkUnloadRequestThread))
8949 if (timeout != INFINITE)
8951 // Turn off the timeout used by AD.
8956 // GCStress takes a long time to unwind, due to expensive creation of
8957 // a threadabort exception.
8958 if (!GCStress<cfg_any>::IsEnabled())
8960 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::UnwindThreads iteration %d waiting on thread count %d\n", retryCount, m_dwThreadEnterCount));
8962 printf("AppDomain::UnwindThreads iteration %d waiting on thread count %d\n", retryCount, m_dwThreadEnterCount);
8966 if (m_dwThreadEnterCount != 0)
8969 GetThread()->UserSleep(20);
8971 GetThread()->UserSleep(10);
8978 void AppDomain::ClearGCHandles()
8988 SetStage(STAGE_HANDLETABLE_NOACCESS);
8990 GCHeapUtilities::GetGCHeap()->WaitUntilConcurrentGCComplete();
8992 // Keep async pin handles alive by moving them to default domain
8993 HandleAsyncPinHandles();
8995 // Remove our handle store as a source of GC roots
8996 m_handleStore->Uproot();
8999 // When an AD is unloaded, we will release all objects in this AD.
9000 // If a future asynchronous operation, like io completion port function,
9001 // we need to keep the memory space fixed so that the gc heap is not corrupted.
9002 void AppDomain::HandleAsyncPinHandles()
9012 IGCHandleStore *pBucket = m_handleStore;
9014 // IO completion port picks IO job using FIFO. Here is how we know which AsyncPinHandle can be freed.
9015 // 1. We mark all non-pending AsyncPinHandle with READYTOCLEAN.
9016 // 2. We queue a dump Overlapped to the IO completion as a marker.
9017 // 3. When the Overlapped is picked up by completion port, we wait until all previous IO jobs are processed.
9018 // 4. Then we can delete all AsyncPinHandle marked with READYTOCLEAN.
9019 IGCHandleStore *pBucketInDefault = SystemDomain::System()->DefaultDomain()->m_handleStore;
9021 auto clearIfComplete = [](Object* object)
9023 LIMITED_METHOD_CONTRACT;
9025 assert(object != nullptr);
9026 if (object->GetGCSafeMethodTable() != g_pOverlappedDataClass)
9031 OVERLAPPEDDATAREF overlapped = (OVERLAPPEDDATAREF)(ObjectToOBJECTREF((Object*)object));
9032 if (overlapped->HasCompleted())
9034 // IO has finished. We don't need to pin the user buffer any longer.
9035 overlapped->m_userObject = NULL;
9038 BashMTForPinnedObject(ObjectToOBJECTREF(object));
9041 auto setHandle = [](Object* object, OBJECTHANDLE handle)
9043 LIMITED_METHOD_CONTRACT;
9045 assert(object != nullptr);
9048 if (object->GetGCSafeMethodTable() != g_pOverlappedDataClass)
9053 OverlappedDataObject* overlapped = (OverlappedDataObject*)object;
9054 overlapped->m_pinSelf = handle;
9057 pBucket->RelocateAsyncPinnedHandles(pBucketInDefault, clearIfComplete, setHandle);
9059 OverlappedDataObject::RequestCleanup();
9062 void AppDomain::ClearGCRoots()
9072 Thread *pThread = NULL;
9073 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
9075 // Tell the JIT managers to delete any entries in their structures. All the cooperative mode threads are stopped at
9076 // this point, so only need to synchronize the preemptive mode threads.
9077 ExecutionManager::Unload(GetLoaderAllocator());
9079 while ((pThread = ThreadStore::GetAllThreadList(pThread, 0, 0)) != NULL)
9081 // Delete the thread local static store
9082 pThread->DeleteThreadStaticData(this);
9084 // <TODO>@TODO: A pre-allocated AppDomainUnloaded exception might be better.</TODO>
9085 if (m_handleStore->ContainsHandle(pThread->m_LastThrownObjectHandle))
9087 // Never delete a handle to a preallocated exception object.
9088 if (!CLRException::IsPreallocatedExceptionHandle(pThread->m_LastThrownObjectHandle))
9090 DestroyHandle(pThread->m_LastThrownObjectHandle);
9093 pThread->m_LastThrownObjectHandle = NULL;
9096 // Clear out the exceptions objects held by a thread.
9097 pThread->GetExceptionState()->ClearThrowablesForUnload(m_handleStore);
9100 //delete them while we still have the runtime suspended
9101 // This must be deleted before the loader heaps are deleted.
9102 if (m_pMarshalingData != NULL)
9104 delete m_pMarshalingData;
9105 m_pMarshalingData = NULL;
9108 if (m_pLargeHeapHandleTable != NULL)
9110 delete m_pLargeHeapHandleTable;
9111 m_pLargeHeapHandleTable = NULL;
9114 ThreadSuspend::RestartEE(FALSE, TRUE);
9119 void AppDomain::TrackADThreadEnter(Thread *pThread, Frame *pFrame)
9126 PRECONDITION(CheckPointer(pThread));
9127 PRECONDITION(pFrame != (Frame*)(size_t) INVALID_POINTER_CD);
9131 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9133 if (m_pThreadTrackInfoList == NULL)
9134 m_pThreadTrackInfoList = new (nothrow) ThreadTrackInfoList;
9135 // If we don't assert here, we will AV in the for loop below
9136 _ASSERTE(m_pThreadTrackInfoList);
9138 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9140 ThreadTrackInfo *pTrack = NULL;
9142 for (i=0; i < pTrackList->Count(); i++) {
9143 if ((*(pTrackList->Get(i)))->pThread == pThread) {
9144 pTrack = *(pTrackList->Get(i));
9149 pTrack = new (nothrow) ThreadTrackInfo;
9150 // If we don't assert here, we will AV in the for loop below.
9152 pTrack->pThread = pThread;
9153 ThreadTrackInfo **pSlot = pTrackList->Append();
9157 InterlockedIncrement((LONG*)&m_dwThreadEnterCount);
9161 pSlot = pTrack->frameStack.Insert(0);
9165 for (i=0; i < pTrackList->Count(); i++)
9166 totThreads += (*(pTrackList->Get(i)))->frameStack.Count();
9167 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9169 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9173 void AppDomain::TrackADThreadExit(Thread *pThread, Frame *pFrame)
9177 if (GetThread()) {MODE_COOPERATIVE;}
9183 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9185 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9186 _ASSERTE(pTrackList);
9187 ThreadTrackInfo *pTrack = NULL;
9189 for (i=0; i < pTrackList->Count(); i++)
9191 if ((*(pTrackList->Get(i)))->pThread == pThread)
9193 pTrack = *(pTrackList->Get(i));
9198 _ASSERTE(*(pTrack->frameStack.Get(0)) == pFrame);
9199 pTrack->frameStack.Delete(0);
9200 InterlockedDecrement((LONG*)&m_dwThreadEnterCount);
9203 for (i=0; i < pTrackList->Count(); i++)
9204 totThreads += (*(pTrackList->Get(i)))->frameStack.Count();
9205 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9207 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9210 void AppDomain::DumpADThreadTrack()
9220 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9222 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9227 LOG((LF_APPDOMAIN, LL_INFO10000, "\nThread dump of %d threads for [%d] %#08x %S\n",
9228 m_dwThreadEnterCount, GetId().m_dwId, this, GetFriendlyNameForLogging()));
9230 for (int i=0; i < pTrackList->Count(); i++)
9232 ThreadTrackInfo *pTrack = *(pTrackList->Get(i));
9233 if (pTrack->frameStack.Count()==0)
9235 LOG((LF_APPDOMAIN, LL_INFO100, " ADEnterCount for %x is %d\n", pTrack->pThread->GetThreadId(), pTrack->frameStack.Count()));
9236 totThreads += pTrack->frameStack.Count();
9237 for (int j=0; j < pTrack->frameStack.Count(); j++)
9238 LOG((LF_APPDOMAIN, LL_INFO100, " frame %8.8x\n", *(pTrack->frameStack.Get(j))));
9240 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9243 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9248 #endif // CROSSGEN_COMPILE
9250 void *SharedDomain::operator new(size_t size, void *pInPlace)
9252 LIMITED_METHOD_CONTRACT;
9256 void SharedDomain::operator delete(void *pMem)
9258 LIMITED_METHOD_CONTRACT;
9259 // Do nothing - new() was in-place
9263 void SharedDomain::Attach()
9270 INJECT_FAULT(COMPlusThrowOM(););
9274 // Create the global SharedDomain and initialize it.
9275 m_pSharedDomain = new (&g_pSharedDomainMemory[0]) SharedDomain();
9276 SystemDomain::GetGlobalLoaderAllocator()->m_pDomain = m_pSharedDomain;
9277 // This cannot fail since g_pSharedDomainMemory is a static array.
9278 CONSISTENCY_CHECK(CheckPointer(m_pSharedDomain));
9280 LOG((LF_CLASSLOADER,
9282 "Created shared domain at %p\n",
9285 // We need to initialize the memory pools etc. for the system domain.
9286 m_pSharedDomain->Init(); // Setup the memory heaps
9288 // allocate a Virtual Call Stub Manager for the shared domain
9289 m_pSharedDomain->InitVSD();
9292 #ifndef CROSSGEN_COMPILE
9293 void SharedDomain::Detach()
9295 if (m_pSharedDomain)
9297 m_pSharedDomain->Terminate();
9298 delete m_pSharedDomain;
9299 m_pSharedDomain = NULL;
9302 #endif // CROSSGEN_COMPILE
9304 #endif // !DACCESS_COMPILE
9306 SharedDomain *SharedDomain::GetDomain()
9308 LIMITED_METHOD_DAC_CONTRACT;
9310 return m_pSharedDomain;
9313 #ifndef DACCESS_COMPILE
9315 #define INITIAL_ASSEMBLY_MAP_SIZE 17
9316 void SharedDomain::Init()
9323 INJECT_FAULT(COMPlusThrowOM(););
9329 #ifdef FEATURE_LOADER_OPTIMIZATION
9330 m_FileCreateLock.Init(CrstSharedAssemblyCreate, CRST_DEFAULT,TRUE);
9332 LockOwner lock = { &m_DomainCrst, IsOwnerOfCrst };
9333 m_assemblyMap.Init(INITIAL_ASSEMBLY_MAP_SIZE, CompareSharedAssembly, TRUE, &lock);
9334 #endif // FEATURE_LOADER_OPTIMIZATION
9336 ETW::LoaderLog::DomainLoad(this);
9339 #ifndef CROSSGEN_COMPILE
9340 void SharedDomain::Terminate()
9342 // make sure we delete the StringLiteralMap before unloading
9343 // the asemblies since the string literal map entries can
9344 // point to metadata string literals.
9345 GetLoaderAllocator()->CleanupStringLiteralMap();
9347 #ifdef FEATURE_LOADER_OPTIMIZATION
9348 PtrHashMap::PtrIterator i = m_assemblyMap.begin();
9352 Assembly *pAssembly = (Assembly*) i.GetValue();
9357 ListLockEntry* pElement;
9358 pElement = m_FileCreateLock.Pop(TRUE);
9361 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
9362 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
9365 pElement = (FileLoadLock*) m_FileCreateLock.Pop(TRUE);
9367 m_FileCreateLock.Destroy();
9368 #endif // FEATURE_LOADER_OPTIMIZATION
9369 BaseDomain::Terminate();
9371 #endif // CROSSGEN_COMPILE
9375 #ifdef FEATURE_LOADER_OPTIMIZATION
9377 BOOL SharedDomain::CompareSharedAssembly(UPTR u1, UPTR u2)
9387 // This is the input to the lookup
9388 SharedAssemblyLocator *pLocator = (SharedAssemblyLocator *) (u1<<1);
9390 // This is the value stored in the table
9391 Assembly *pAssembly = (Assembly *) u2;
9392 if (pLocator->GetType()==SharedAssemblyLocator::DOMAINASSEMBLY)
9394 if (!pAssembly->GetManifestFile()->Equals(pLocator->GetDomainAssembly()->GetFile()))
9397 return pAssembly->CanBeShared(pLocator->GetDomainAssembly());
9400 if (pLocator->GetType()==SharedAssemblyLocator::PEASSEMBLY)
9401 return pAssembly->GetManifestFile()->Equals(pLocator->GetPEAssembly());
9403 if (pLocator->GetType()==SharedAssemblyLocator::PEASSEMBLYEXACT)
9404 return pAssembly->GetManifestFile() == pLocator->GetPEAssembly();
9405 _ASSERTE(!"Unexpected type of assembly locator");
9409 DWORD SharedAssemblyLocator::Hash()
9416 INJECT_FAULT(COMPlusThrowOM(););
9419 if (m_type==DOMAINASSEMBLY)
9420 return GetDomainAssembly()->HashIdentity();
9421 if (m_type==PEASSEMBLY||m_type==PEASSEMBLYEXACT)
9422 return GetPEAssembly()->HashIdentity();
9423 _ASSERTE(!"Unexpected type of assembly locator");
9427 Assembly * SharedDomain::FindShareableAssembly(SharedAssemblyLocator * pLocator)
9434 INJECT_FAULT(COMPlusThrowOM(););
9438 Assembly * match= (Assembly *) m_assemblyMap.LookupValue(pLocator->Hash(), pLocator);
9439 if (match != (Assembly *) INVALIDENTRY)
9445 SIZE_T SharedDomain::GetShareableAssemblyCount()
9447 LIMITED_METHOD_CONTRACT;
9449 return m_assemblyMap.GetCount();
9452 void SharedDomain::AddShareableAssembly(Assembly * pAssembly)
9459 INJECT_FAULT(COMPlusThrowOM(););
9463 // We have a lock on the file. There should be no races to add the same assembly.
9466 LockHolder holder(this);
9470 pAssembly->SetIsTenured();
9471 m_assemblyMap.InsertValue(pAssembly->HashIdentity(), pAssembly);
9475 // There was an error adding the assembly to the assembly hash (probably an OOM),
9476 // so we need to unset the tenured bit so that correct cleanup can happen.
9477 pAssembly->UnsetIsTenured();
9482 LOG((LF_CODESHARING,
9484 "Successfully added shareable assembly \"%s\".\n",
9485 pAssembly->GetManifestFile()->GetSimpleName()));
9488 #endif // FEATURE_LOADER_OPTIMIZATION
9489 #endif // !DACCESS_COMPILE
9491 DWORD DomainLocalModule::GetClassFlags(MethodTable* pMT, DWORD iClassIndex /*=(DWORD)-1*/)
9499 { // SO tolerance exception for debug-only assertion.
9500 CONTRACT_VIOLATION(SOToleranceViolation);
9501 CONSISTENCY_CHECK(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9504 if (pMT->IsDynamicStatics())
9506 _ASSERTE(!pMT->ContainsGenericVariables());
9507 DWORD dynamicClassID = pMT->GetModuleDynamicEntryID();
9508 if(m_aDynamicEntries <= dynamicClassID)
9510 return (m_pDynamicClassTable[dynamicClassID].m_dwFlags);
9514 if (iClassIndex == (DWORD)-1)
9515 iClassIndex = pMT->GetClassIndex();
9516 return GetPrecomputedStaticsClassData()[iClassIndex];
9520 #ifndef DACCESS_COMPILE
9522 void DomainLocalModule::SetClassInitialized(MethodTable* pMT)
9532 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9534 _ASSERTE(!IsClassInitialized(pMT));
9535 _ASSERTE(!IsClassInitError(pMT));
9537 SetClassFlags(pMT, ClassInitFlags::INITIALIZED_FLAG);
9540 void DomainLocalModule::SetClassInitError(MethodTable* pMT)
9542 WRAPPER_NO_CONTRACT;
9544 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9546 SetClassFlags(pMT, ClassInitFlags::ERROR_FLAG);
9549 void DomainLocalModule::SetClassFlags(MethodTable* pMT, DWORD dwFlags)
9554 PRECONDITION(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9555 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9556 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9559 if (pMT->IsDynamicStatics())
9561 _ASSERTE(!pMT->ContainsGenericVariables());
9562 DWORD dwID = pMT->GetModuleDynamicEntryID();
9563 EnsureDynamicClassIndex(dwID);
9564 m_pDynamicClassTable[dwID].m_dwFlags |= dwFlags;
9568 GetPrecomputedStaticsClassData()[pMT->GetClassIndex()] |= dwFlags;
9572 void DomainLocalModule::EnsureDynamicClassIndex(DWORD dwID)
9579 INJECT_FAULT(COMPlusThrowOM(););
9580 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9581 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9585 if (dwID < m_aDynamicEntries)
9587 _ASSERTE(m_pDynamicClassTable.Load() != NULL);
9591 SIZE_T aDynamicEntries = max(16, m_aDynamicEntries.Load());
9592 while (aDynamicEntries <= dwID)
9594 aDynamicEntries *= 2;
9597 DynamicClassInfo* pNewDynamicClassTable;
9598 pNewDynamicClassTable = (DynamicClassInfo*)
9599 (void*)GetDomainFile()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(
9600 S_SIZE_T(sizeof(DynamicClassInfo)) * S_SIZE_T(aDynamicEntries));
9602 memcpy(pNewDynamicClassTable, m_pDynamicClassTable, sizeof(DynamicClassInfo) * m_aDynamicEntries);
9604 // Note: Memory allocated on loader heap is zero filled
9605 // memset(pNewDynamicClassTable + m_aDynamicEntries, 0, (aDynamicEntries - m_aDynamicEntries) * sizeof(DynamicClassInfo));
9607 _ASSERTE(m_aDynamicEntries%2 == 0);
9609 // Commit new dynamic table. The lock-free helpers depend on the order.
9611 m_pDynamicClassTable = pNewDynamicClassTable;
9613 m_aDynamicEntries = aDynamicEntries;
9616 #ifndef CROSSGEN_COMPILE
9617 void DomainLocalModule::AllocateDynamicClass(MethodTable *pMT)
9623 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9624 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9628 _ASSERTE(!pMT->ContainsGenericVariables());
9629 _ASSERTE(!pMT->IsSharedByGenericInstantiations());
9630 _ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9631 _ASSERTE(pMT->IsDynamicStatics());
9633 DWORD dynamicEntryIDIndex = pMT->GetModuleDynamicEntryID();
9635 EnsureDynamicClassIndex(dynamicEntryIDIndex);
9637 _ASSERTE(m_aDynamicEntries > dynamicEntryIDIndex);
9639 EEClass *pClass = pMT->GetClass();
9641 DWORD dwStaticBytes = pClass->GetNonGCRegularStaticFieldBytes();
9642 DWORD dwNumHandleStatics = pClass->GetNumHandleRegularStatics();
9644 _ASSERTE(!IsClassAllocated(pMT));
9645 _ASSERTE(!IsClassInitialized(pMT));
9646 _ASSERTE(!IsClassInitError(pMT));
9648 DynamicEntry *pDynamicStatics = m_pDynamicClassTable[dynamicEntryIDIndex].m_pDynamicEntry;
9650 // We need this check because maybe a class had a cctor but no statics
9651 if (dwStaticBytes > 0 || dwNumHandleStatics > 0)
9653 if (pDynamicStatics == NULL)
9655 LoaderHeap * pLoaderAllocator = GetDomainFile()->GetLoaderAllocator()->GetHighFrequencyHeap();
9657 if (pMT->Collectible())
9659 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocMem(S_SIZE_T(sizeof(CollectibleDynamicEntry)));
9663 SIZE_T dynamicEntrySize = DynamicEntry::GetOffsetOfDataBlob() + dwStaticBytes;
9665 #ifdef FEATURE_64BIT_ALIGNMENT
9666 // Allocate memory with extra alignment only if it is really necessary
9667 if (dwStaticBytes >= MAX_PRIMITIVE_FIELD_SIZE)
9669 static_assert_no_msg(sizeof(NormalDynamicEntry) % MAX_PRIMITIVE_FIELD_SIZE == 0);
9670 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocAlignedMem(dynamicEntrySize, MAX_PRIMITIVE_FIELD_SIZE);
9674 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocMem(S_SIZE_T(dynamicEntrySize));
9677 // Note: Memory allocated on loader heap is zero filled
9679 m_pDynamicClassTable[dynamicEntryIDIndex].m_pDynamicEntry = pDynamicStatics;
9682 if (pMT->Collectible() && (dwStaticBytes != 0))
9685 OBJECTREF nongcStaticsArray = NULL;
9686 GCPROTECT_BEGIN(nongcStaticsArray);
9687 #ifdef FEATURE_64BIT_ALIGNMENT
9688 // Allocate memory with extra alignment only if it is really necessary
9689 if (dwStaticBytes >= MAX_PRIMITIVE_FIELD_SIZE)
9690 nongcStaticsArray = AllocatePrimitiveArray(ELEMENT_TYPE_I8, (dwStaticBytes + (sizeof(CLR_I8)-1)) / (sizeof(CLR_I8)));
9693 nongcStaticsArray = AllocatePrimitiveArray(ELEMENT_TYPE_U1, dwStaticBytes);
9694 ((CollectibleDynamicEntry *)pDynamicStatics)->m_hNonGCStatics = GetDomainFile()->GetModule()->GetLoaderAllocator()->AllocateHandle(nongcStaticsArray);
9697 if (dwNumHandleStatics > 0)
9699 if (!pMT->Collectible())
9701 GetAppDomain()->AllocateStaticFieldObjRefPtrs(dwNumHandleStatics,
9702 &((NormalDynamicEntry *)pDynamicStatics)->m_pGCStatics);
9707 OBJECTREF gcStaticsArray = NULL;
9708 GCPROTECT_BEGIN(gcStaticsArray);
9709 gcStaticsArray = AllocateObjectArray(dwNumHandleStatics, g_pObjectClass);
9710 ((CollectibleDynamicEntry *)pDynamicStatics)->m_hGCStatics = GetDomainFile()->GetModule()->GetLoaderAllocator()->AllocateHandle(gcStaticsArray);
9718 void DomainLocalModule::PopulateClass(MethodTable *pMT)
9727 _ASSERTE(!pMT->ContainsGenericVariables());
9729 // <todo> the only work actually done here for non-dynamics is the freezing related work.
9730 // See if we can eliminate this and make this a dynamic-only path </todo>
9731 DWORD iClassIndex = pMT->GetClassIndex();
9733 if (!IsClassAllocated(pMT, iClassIndex))
9735 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9737 if (!IsClassAllocated(pMT, iClassIndex))
9739 // Allocate dynamic space if necessary
9740 if (pMT->IsDynamicStatics())
9741 AllocateDynamicClass(pMT);
9743 // determine flags to set on the statics block
9744 DWORD dwFlags = ClassInitFlags::ALLOCATECLASS_FLAG;
9746 if (!pMT->HasClassConstructor() && !pMT->HasBoxedRegularStatics())
9748 _ASSERTE(!IsClassInitialized(pMT));
9749 _ASSERTE(!IsClassInitError(pMT));
9750 dwFlags |= ClassInitFlags::INITIALIZED_FLAG;
9753 if (pMT->Collectible())
9755 dwFlags |= ClassInitFlags::COLLECTIBLE_FLAG;
9758 // Set all flags at the same time to avoid races
9759 SetClassFlags(pMT, dwFlags);
9765 #endif // CROSSGEN_COMPILE
9767 void DomainLocalBlock::EnsureModuleIndex(ModuleIndex index)
9774 INJECT_FAULT(COMPlusThrowOM(););
9775 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9776 PRECONDITION(m_pDomain->OwnDomainLocalBlockLock());
9780 if (m_aModuleIndices > index.m_dwIndex)
9782 _ASSERTE(m_pModuleSlots != NULL);
9786 SIZE_T aModuleIndices = max(16, m_aModuleIndices);
9787 while (aModuleIndices <= index.m_dwIndex)
9789 aModuleIndices *= 2;
9792 PTR_DomainLocalModule* pNewModuleSlots = (PTR_DomainLocalModule*) (void*)m_pDomain->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(PTR_DomainLocalModule)) * S_SIZE_T(aModuleIndices));
9794 memcpy(pNewModuleSlots, m_pModuleSlots, sizeof(SIZE_T)*m_aModuleIndices);
9796 // Note: Memory allocated on loader heap is zero filled
9797 // memset(pNewModuleSlots + m_aModuleIndices, 0 , (aModuleIndices - m_aModuleIndices)*sizeof(PTR_DomainLocalModule) );
9799 // Commit new table. The lock-free helpers depend on the order.
9801 m_pModuleSlots = pNewModuleSlots;
9803 m_aModuleIndices = aModuleIndices;
9807 void DomainLocalBlock::SetModuleSlot(ModuleIndex index, PTR_DomainLocalModule pLocalModule)
9809 // Need to synchronize with table growth in this domain
9810 BaseDomain::DomainLocalBlockLockHolder lh(m_pDomain);
9812 EnsureModuleIndex(index);
9814 _ASSERTE(index.m_dwIndex < m_aModuleIndices);
9816 // We would like this assert here, unfortunately, loading a module in this appdomain can fail
9817 // after here and we will keep the module around and reuse the slot when we retry (if
9818 // the failure happened due to a transient error, such as OOM). In that case the slot wont
9820 //_ASSERTE(m_pModuleSlots[index.m_dwIndex] == 0);
9822 m_pModuleSlots[index.m_dwIndex] = pLocalModule;
9825 #ifndef CROSSGEN_COMPILE
9827 DomainAssembly* AppDomain::RaiseTypeResolveEventThrowing(DomainAssembly* pAssembly, LPCSTR szName, ASSEMBLYREF *pResultingAssemblyRef)
9834 INJECT_FAULT(COMPlusThrowOM(););
9838 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
9841 DomainAssembly* pResolvedAssembly = NULL;
9842 _ASSERTE(strcmp(szName, g_AppDomainClassName));
9847 OBJECTREF AppDomainRef;
9848 OBJECTREF AssemblyRef;
9851 ZeroMemory(&gc, sizeof(gc));
9853 GCPROTECT_BEGIN(gc);
9854 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
9856 if (pAssembly != NULL)
9857 gc.AssemblyRef = pAssembly->GetExposedAssemblyObject();
9859 MethodDescCallSite onTypeResolve(METHOD__APP_DOMAIN__ON_TYPE_RESOLVE, &gc.AppDomainRef);
9861 gc.str = StringObject::NewString(szName);
9864 ObjToArgSlot(gc.AppDomainRef),
9865 ObjToArgSlot(gc.AssemblyRef),
9866 ObjToArgSlot(gc.str)
9868 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onTypeResolve.Call_RetOBJECTREF(args);
9870 if (ResultingAssemblyRef != NULL)
9872 pResolvedAssembly = ResultingAssemblyRef->GetDomainAssembly();
9874 if (pResultingAssemblyRef)
9875 *pResultingAssemblyRef = ResultingAssemblyRef;
9878 if (pResolvedAssembly->IsCollectible())
9880 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleBoundNonCollectible"));
9887 return pResolvedAssembly;
9891 Assembly* AppDomain::RaiseResourceResolveEvent(DomainAssembly* pAssembly, LPCSTR szName)
9898 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
9899 INJECT_FAULT(COMPlusThrowOM(););
9903 Assembly* pResolvedAssembly = NULL;
9908 OBJECTREF AppDomainRef;
9909 OBJECTREF AssemblyRef;
9912 ZeroMemory(&gc, sizeof(gc));
9914 GCPROTECT_BEGIN(gc);
9915 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
9917 if (pAssembly != NULL)
9918 gc.AssemblyRef=pAssembly->GetExposedAssemblyObject();
9920 MethodDescCallSite onResourceResolve(METHOD__APP_DOMAIN__ON_RESOURCE_RESOLVE, &gc.AppDomainRef);
9921 gc.str = StringObject::NewString(szName);
9924 ObjToArgSlot(gc.AppDomainRef),
9925 ObjToArgSlot(gc.AssemblyRef),
9926 ObjToArgSlot(gc.str)
9928 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onResourceResolve.Call_RetOBJECTREF(args);
9929 if (ResultingAssemblyRef != NULL)
9931 pResolvedAssembly = ResultingAssemblyRef->GetAssembly();
9932 if (pResolvedAssembly->IsCollectible())
9934 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleAssemblyResolve"));
9940 RETURN pResolvedAssembly;
9945 AppDomain::RaiseAssemblyResolveEvent(
9946 AssemblySpec * pSpec,
9947 BOOL fIntrospection,
9955 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
9956 INJECT_FAULT(COMPlusThrowOM(););
9960 BinderMethodID methodId;
9961 StackSString ssName;
9962 pSpec->GetFileOrDisplayName(0, ssName);
9966 methodId = METHOD__APP_DOMAIN__ON_ASSEMBLY_RESOLVE; // post-bind execution event (the classic V1.0 event)
9974 // Elevate threads allowed loading level. This allows the host to load an assembly even in a restricted
9975 // condition. Note, however, that this exposes us to possible recursion failures, if the host tries to
9976 // load the assemblies currently being loaded. (Such cases would then throw an exception.)
9978 OVERRIDE_LOAD_LEVEL_LIMIT(FILE_ACTIVE);
9979 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
9983 Assembly* pAssembly = NULL;
9986 OBJECTREF AppDomainRef;
9987 OBJECTREF AssemblyRef;
9990 ZeroMemory(&gc, sizeof(gc));
9992 GCPROTECT_BEGIN(gc);
9993 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
9995 if (pSpec->GetParentAssembly() != NULL)
9998 gc.AssemblyRef=pSpec->GetParentAssembly()->GetExposedAssemblyObject();
10001 MethodDescCallSite onAssemblyResolve(methodId, &gc.AppDomainRef);
10003 gc.str = StringObject::NewString(ssName);
10004 ARG_SLOT args[3] = {
10005 ObjToArgSlot(gc.AppDomainRef),
10006 ObjToArgSlot(gc.AssemblyRef),
10007 ObjToArgSlot(gc.str)
10010 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onAssemblyResolve.Call_RetOBJECTREF(args);
10012 if (ResultingAssemblyRef != NULL)
10014 pAssembly = ResultingAssemblyRef->GetAssembly();
10015 if (pAssembly->IsCollectible())
10017 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleAssemblyResolve"));
10023 if (pAssembly != NULL)
10025 if ((!(pAssembly->IsIntrospectionOnly())) != (!fIntrospection))
10027 // Cannot return an introspection assembly from an execution callback or vice-versa
10028 COMPlusThrow(kFileLoadException, pAssembly->IsIntrospectionOnly() ? IDS_CLASSLOAD_ASSEMBLY_RESOLVE_RETURNED_INTROSPECTION : IDS_CLASSLOAD_ASSEMBLY_RESOLVE_RETURNED_EXECUTION);
10031 // Check that the public key token matches the one specified in the spec
10032 // MatchPublicKeys throws as appropriate
10033 pSpec->MatchPublicKeys(pAssembly);
10037 } // AppDomain::RaiseAssemblyResolveEvent
10040 //---------------------------------------------------------------------------------------
10042 // Determine the type of AppDomainManager to use for the default AppDomain
10045 // v2.0 of the CLR used environment variables APPDOMAIN_MANAGER_ASM and APPDOMAIN_MANAGER_TYPE to set the
10046 // domain manager. For compatibility these are still supported, along with appDomainManagerAsm and
10047 // appDomainManagerType config file switches. If the config switches are supplied, the entry point must be
10051 void AppDomain::InitializeDefaultDomainManager()
10058 INJECT_FAULT(COMPlusThrowOM(););
10059 PRECONDITION(GetId().m_dwId == DefaultADID);
10063 OBJECTREF orThis = GetExposedObject();
10064 GCPROTECT_BEGIN(orThis);
10066 MethodDescCallSite initCompatFlags(METHOD__APP_DOMAIN__INITIALIZE_COMPATIBILITY_FLAGS);
10069 ObjToArgSlot(orThis)
10072 initCompatFlags.Call(args);
10077 CLREvent * AppDomain::g_pUnloadStartEvent;
10079 void AppDomain::CreateADUnloadWorker()
10081 STANDARD_VM_CONTRACT;
10083 // Do not create adUnload thread if there is only default domain
10084 if(IsSingleAppDomain())
10088 BOOL fCreator = FALSE;
10089 if (FastInterlockCompareExchange((LONG *)&g_fADUnloadWorkerOK,-2,-1)==-1) //we're first
10091 #ifdef _TARGET_X86_ // use the smallest possible stack on X86
10092 DWORD stackSize = 128 * 1024;
10094 DWORD stackSize = 512 * 1024; // leave X64 unchanged since we have plenty of VM
10096 Thread *pThread = SetupUnstartedThread();
10097 if (pThread->CreateNewThread(stackSize, ADUnloadThreadStart, pThread))
10101 dwRet = pThread->StartThread();
10103 // When running under a user mode native debugger there is a race
10104 // between the moment we've created the thread (in CreateNewThread) and
10105 // the moment we resume it (in StartThread); the debugger may receive
10106 // the "ct" (create thread) notification, and it will attempt to
10107 // suspend/resume all threads in the process. Now imagine the debugger
10108 // resumes this thread first, and only later does it try to resume the
10109 // newly created thread (the ADU worker thread). In these conditions our
10110 // call to ResumeThread may come before the debugger's call to ResumeThread
10111 // actually causing dwRet to equal 2.
10112 // We cannot use IsDebuggerPresent() in the condition below because the
10113 // debugger may have been detached between the time it got the notification
10114 // and the moment we execute the test below.
10115 _ASSERTE(dwRet == 1 || dwRet == 2);
10119 pThread->DecExternalCount(FALSE);
10120 FastInterlockExchange((LONG *)&g_fADUnloadWorkerOK, -1);
10121 ThrowOutOfMemory();
10125 YIELD_WHILE (g_fADUnloadWorkerOK == -2);
10127 if (g_fADUnloadWorkerOK == -1) {
10130 ThrowOutOfMemory();
10139 /*static*/ void AppDomain::ADUnloadWorkerHelper(AppDomain *pDomain)
10141 STATIC_CONTRACT_NOTHROW;
10142 STATIC_CONTRACT_GC_TRIGGERS;
10143 STATIC_CONTRACT_MODE_COOPERATIVE;
10144 ADUnloadSink* pADUnloadSink=pDomain->GetADUnloadSinkForUnload();
10149 pDomain->Unload(FALSE);
10151 EX_CATCH_HRESULT(hr);
10155 SystemDomain::LockHolder lh;
10156 pADUnloadSink->ReportUnloadResult(hr,NULL);
10157 pADUnloadSink->Release();
10161 void AppDomain::DoADUnloadWork()
10168 INJECT_FAULT(COMPlusThrowOM(););
10175 AppDomain *pDomainToUnload = NULL;
10178 // Take the lock so that no domain can be added or removed from the system domain
10179 SystemDomain::LockHolder lh;
10181 DWORD numDomain = SystemDomain::GetCurrentAppDomainMaxIndex();
10182 for (; i <= numDomain; i ++) {
10183 AppDomain * pDomain = SystemDomain::TestGetAppDomainAtIndex(ADIndex(i));
10185 // @todo: We used to also select a domain if pDomain->IsUnload() returned true. But that causes
10186 // problems when we've failed to completely unload the AD in the past. If we've reached the CLEARED
10187 // stage, for instance, then there will be no default context and AppDomain::Exit() will simply crash.
10189 if (pDomain && pDomain->IsUnloadRequested())
10191 pDomainToUnload = pDomain;
10198 if (!pDomainToUnload) {
10202 // We are the only thread that can unload domains so no one else can delete the appdomain
10203 ADUnloadWorkerHelper(pDomainToUnload);
10207 static void DoADUnloadWorkHelper()
10209 STATIC_CONTRACT_NOTHROW;
10210 STATIC_CONTRACT_GC_TRIGGERS;
10211 STATIC_CONTRACT_MODE_COOPERATIVE;
10214 AppDomain::DoADUnloadWork();
10219 EX_END_CATCH(SwallowAllExceptions);
10222 ULONGLONG g_ObjFinalizeStartTime = 0;
10223 Volatile<BOOL> g_FinalizerIsRunning = FALSE;
10224 Volatile<ULONG> g_FinalizerLoopCount = 0;
10226 ULONGLONG GetObjFinalizeStartTime()
10228 LIMITED_METHOD_CONTRACT;
10229 return g_ObjFinalizeStartTime;
10232 void FinalizerThreadAbortOnTimeout()
10234 STATIC_CONTRACT_NOTHROW;
10235 STATIC_CONTRACT_MODE_COOPERATIVE;
10236 STATIC_CONTRACT_GC_TRIGGERS;
10239 // If finalizer thread is blocked because scheduler is running another task,
10240 // or it is waiting for another thread, we first see if we get finalizer thread
10242 Thread::ThreadAbortWatchDog();
10247 Thread *pFinalizerThread = FinalizerThread::GetFinalizerThread();
10248 EPolicyAction action = GetEEPolicy()->GetActionOnTimeout(OPR_FinalizerRun, pFinalizerThread);
10252 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10253 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10256 Thread::UAC_FinalizerTimeout);
10258 case eRudeAbortThread:
10259 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10260 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10263 Thread::UAC_FinalizerTimeout);
10265 case eUnloadAppDomain:
10267 AppDomain *pDomain = pFinalizerThread->GetDomain();
10268 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10271 Thread::UAC_FinalizerTimeout);
10272 if (!pDomain->IsDefaultDomain())
10274 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10275 pDomain->EnableADUnloadWorker(EEPolicy::ADU_Safe);
10279 case eRudeUnloadAppDomain:
10281 AppDomain *pDomain = pFinalizerThread->GetDomain();
10282 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10285 Thread::UAC_FinalizerTimeout);
10286 if (!pDomain->IsDefaultDomain())
10288 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10289 pDomain->EnableADUnloadWorker(EEPolicy::ADU_Rude);
10294 case eFastExitProcess:
10295 case eRudeExitProcess:
10296 case eDisableRuntime:
10297 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10298 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_TIMEOUT);
10299 _ASSERTE (!"Should not get here");
10308 EX_END_CATCH(SwallowAllExceptions);
10313 WT_UnloadDomain = 0x1,
10314 WT_ThreadAbort = 0x2,
10315 WT_FinalizerThread = 0x4,
10316 WT_ClearCollectedDomains=0x8
10319 static Volatile<DWORD> s_WorkType = 0;
10322 DWORD WINAPI AppDomain::ADUnloadThreadStart(void *args)
10327 DISABLED(GC_TRIGGERS);
10329 // This function will always be at the very bottom of the stack. The only
10330 // user code it calls is the AppDomainUnload notifications which we will
10331 // not be hardenning for Whidbey.
10337 BEGIN_ENTRYPOINT_NOTHROW;
10339 ClrFlsSetThreadType (ThreadType_ADUnloadHelper);
10341 Thread *pThread = (Thread*)args;
10342 bool fOK = (pThread->HasStarted() != 0);
10345 GCX_MAYBE_PREEMP(fOK);
10347 _ASSERTE (g_fADUnloadWorkerOK == -2);
10349 FastInterlockExchange((LONG *)&g_fADUnloadWorkerOK,fOK?1:-1);
10353 DestroyThread(pThread);
10357 pThread->SetBackground(TRUE);
10359 pThread->SetThreadStateNC(Thread::TSNC_ADUnloadHelper);
10362 DWORD TAtimeout = INFINITE;
10363 ULONGLONG endTime = Thread::GetNextSelfAbortEndTime();
10364 ULONGLONG curTime = CLRGetTickCount64();
10365 if (endTime <= curTime) {
10370 ULONGLONG diff = endTime - curTime;
10371 if (diff < MAXULONG)
10373 TAtimeout = (DWORD)diff;
10376 ULONGLONG finalizeStartTime = GetObjFinalizeStartTime();
10377 DWORD finalizeTimeout = INFINITE;
10378 DWORD finalizeTimeoutSetting = GetEEPolicy()->GetTimeout(OPR_FinalizerRun);
10379 if (finalizeTimeoutSetting != INFINITE && g_FinalizerIsRunning)
10381 if (finalizeStartTime == 0)
10383 finalizeTimeout = finalizeTimeoutSetting;
10387 endTime = finalizeStartTime + finalizeTimeoutSetting;
10388 if (endTime <= curTime) {
10389 finalizeTimeout = 0;
10393 ULONGLONG diff = endTime - curTime;
10394 if (diff < MAXULONG)
10396 finalizeTimeout = (DWORD)diff;
10402 if (AppDomain::HasWorkForFinalizerThread())
10404 if (finalizeTimeout > finalizeTimeoutSetting)
10406 finalizeTimeout = finalizeTimeoutSetting;
10410 DWORD timeout = INFINITE;
10411 if (finalizeTimeout <= TAtimeout)
10413 timeout = finalizeTimeout;
10417 timeout = TAtimeout;
10422 LOG((LF_APPDOMAIN, LL_INFO10, "Waiting to start unload\n"));
10423 g_pUnloadStartEvent->Wait(timeout,FALSE);
10426 if (finalizeTimeout != INFINITE || (s_WorkType & WT_FinalizerThread) != 0)
10428 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for Finalizer thread\n");
10429 FastInterlockAnd(&s_WorkType, ~WT_FinalizerThread);
10430 // only watch finalizer thread is finalizer method or unloadevent is being processed
10431 if (GetObjFinalizeStartTime() == finalizeStartTime && finalizeStartTime != 0 && g_FinalizerIsRunning)
10433 if (CLRGetTickCount64() >= finalizeStartTime+finalizeTimeoutSetting)
10436 FinalizerThreadAbortOnTimeout();
10439 if (s_fProcessUnloadDomainEvent && g_FinalizerIsRunning)
10442 FinalizerThreadAbortOnTimeout();
10446 if (TAtimeout != INFINITE || (s_WorkType & WT_ThreadAbort) != 0)
10448 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for thread abort\n");
10449 FastInterlockAnd(&s_WorkType, ~WT_ThreadAbort);
10451 Thread::ThreadAbortWatchDog();
10454 if ((s_WorkType & WT_UnloadDomain) != 0 && !AppDomain::HasWorkForFinalizerThread())
10456 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for AD unload\n");
10457 FastInterlockAnd(&s_WorkType, ~WT_UnloadDomain);
10459 DoADUnloadWorkHelper();
10462 if ((s_WorkType & WT_ClearCollectedDomains) != 0)
10464 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for AD cleanup\n");
10465 FastInterlockAnd(&s_WorkType, ~WT_ClearCollectedDomains);
10467 SystemDomain::System()->ClearCollectedDomains();
10474 END_ENTRYPOINT_NOTHROW;
10479 void AppDomain::EnableADUnloadWorker()
10485 SO_TOLERANT; // Called during a SO
10489 EEPolicy::AppDomainUnloadTypes type = EEPolicy::ADU_Safe;
10492 DWORD hostTestADUnload = g_pConfig->GetHostTestADUnload();
10493 if (hostTestADUnload == 2) {
10494 type = EEPolicy::ADU_Rude;
10498 EnableADUnloadWorker(type);
10501 void AppDomain::EnableADUnloadWorker(EEPolicy::AppDomainUnloadTypes type, BOOL fHasStack)
10507 SO_TOLERANT; // Called during a SO
10511 FastInterlockOr (&s_WorkType, WT_UnloadDomain);
10513 LONG stage = m_Stage;
10514 static_assert_no_msg(sizeof(m_Stage) == sizeof(int));
10516 _ASSERTE(!IsDefaultDomain());
10518 // Mark unload requested.
10519 if (type == EEPolicy::ADU_Rude) {
10522 while (stage < STAGE_UNLOAD_REQUESTED) {
10523 stage = FastInterlockCompareExchange((LONG*)&m_Stage,STAGE_UNLOAD_REQUESTED,stage);
10528 // Can not call Set due to limited stack.
10531 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker\n"));
10532 g_pUnloadStartEvent->Set();
10535 void AppDomain::EnableADUnloadWorkerForThreadAbort()
10537 LIMITED_METHOD_CONTRACT;
10538 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "Enabling unload worker for thread abort\n");
10539 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for thread abort\n"));
10540 FastInterlockOr (&s_WorkType, WT_ThreadAbort);
10541 g_pUnloadStartEvent->Set();
10545 void AppDomain::EnableADUnloadWorkerForFinalizer()
10547 LIMITED_METHOD_CONTRACT;
10548 if (GetEEPolicy()->GetTimeout(OPR_FinalizerRun) != INFINITE)
10550 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for Finalizer Thread\n"));
10551 FastInterlockOr (&s_WorkType, WT_FinalizerThread);
10552 g_pUnloadStartEvent->Set();
10556 void AppDomain::EnableADUnloadWorkerForCollectedADCleanup()
10558 LIMITED_METHOD_CONTRACT;
10559 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for collected domains\n"));
10560 FastInterlockOr (&s_WorkType, WT_ClearCollectedDomains);
10561 g_pUnloadStartEvent->Set();
10565 void SystemDomain::ClearCollectedDomains()
10575 AppDomain* pDomainsToClear=NULL;
10577 CrstHolder lh(&m_DelayedUnloadCrst);
10578 for (AppDomain** ppDomain=&m_pDelayedUnloadList;(*ppDomain)!=NULL; )
10580 if ((*ppDomain)->m_Stage==AppDomain::STAGE_COLLECTED)
10582 AppDomain* pAppDomain=*ppDomain;
10583 *ppDomain=(*ppDomain)->m_pNextInDelayedUnloadList;
10584 pAppDomain->m_pNextInDelayedUnloadList=pDomainsToClear;
10585 pDomainsToClear=pAppDomain;
10588 ppDomain=&((*ppDomain)->m_pNextInDelayedUnloadList);
10592 for (AppDomain* pDomain=pDomainsToClear;pDomain!=NULL;)
10594 AppDomain* pNext=pDomain->m_pNextInDelayedUnloadList;
10595 pDomain->Close(); //NOTHROW!
10596 pDomain->Release();
10601 void SystemDomain::ProcessClearingDomains()
10610 CrstHolder lh(&m_DelayedUnloadCrst);
10612 for (AppDomain** ppDomain=&m_pDelayedUnloadList;(*ppDomain)!=NULL; )
10614 if ((*ppDomain)->m_Stage==AppDomain::STAGE_HANDLETABLE_NOACCESS)
10616 AppDomain* pAppDomain=*ppDomain;
10617 pAppDomain->SetStage(AppDomain::STAGE_CLEARED);
10619 ppDomain=&((*ppDomain)->m_pNextInDelayedUnloadList);
10622 if (!m_UnloadIsAsync)
10624 // For synchronous mode, we are now done with the list.
10625 m_pDelayedUnloadList = NULL;
10629 void SystemDomain::ProcessDelayedUnloadDomains()
10639 int iGCRefPoint=GCHeapUtilities::GetGCHeap()->CollectionCount(GCHeapUtilities::GetGCHeap()->GetMaxGeneration());
10640 if (GCHeapUtilities::GetGCHeap()->IsConcurrentGCInProgress())
10643 BOOL bAppDomainToCleanup = FALSE;
10644 LoaderAllocator * pAllocatorsToDelete = NULL;
10647 CrstHolder lh(&m_DelayedUnloadCrst);
10649 for (AppDomain* pDomain=m_pDelayedUnloadList; pDomain!=NULL; pDomain=pDomain->m_pNextInDelayedUnloadList)
10651 if (pDomain->m_Stage==AppDomain::STAGE_CLEARED)
10653 // Compare with 0 to handle overflows gracefully
10654 if (0 < iGCRefPoint - pDomain->GetGCRefPoint())
10656 bAppDomainToCleanup=TRUE;
10657 pDomain->SetStage(AppDomain::STAGE_COLLECTED);
10662 LoaderAllocator ** ppAllocator=&m_pDelayedUnloadListOfLoaderAllocators;
10663 while (*ppAllocator!= NULL)
10665 LoaderAllocator * pAllocator = *ppAllocator;
10666 if (0 < iGCRefPoint - pAllocator->GetGCRefPoint())
10668 *ppAllocator = pAllocator->m_pLoaderAllocatorDestroyNext;
10670 pAllocator->m_pLoaderAllocatorDestroyNext = pAllocatorsToDelete;
10671 pAllocatorsToDelete = pAllocator;
10675 ppAllocator = &pAllocator->m_pLoaderAllocatorDestroyNext;
10680 if (bAppDomainToCleanup)
10681 AppDomain::EnableADUnloadWorkerForCollectedADCleanup();
10683 // Delete collected loader allocators on the finalizer thread. We cannot offload it to appdomain unload thread because of
10684 // there is not guaranteed to be one, and it is not that expensive operation anyway.
10685 while (pAllocatorsToDelete != NULL)
10687 LoaderAllocator * pAllocator = pAllocatorsToDelete;
10688 pAllocatorsToDelete = pAllocator->m_pLoaderAllocatorDestroyNext;
10693 #endif // CROSSGEN_COMPILE
10695 AppDomainFromIDHolder::AppDomainFromIDHolder(ADID adId, BOOL bUnsafePoint, SyncType synctype)
10697 WRAPPER_NO_CONTRACT;
10698 ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
10705 Assign(adId, bUnsafePoint);
10708 AppDomainFromIDHolder::AppDomainFromIDHolder(SyncType synctype)
10710 LIMITED_METHOD_CONTRACT;
10711 ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
10720 #ifndef CROSSGEN_COMPILE
10721 void ADUnloadSink::ReportUnloadResult (HRESULT hr, OBJECTREF* pException)
10727 PRECONDITION(CheckPointer(this));
10728 PRECONDITION(m_UnloadCompleteEvent.IsValid());
10732 //pException is unused;
10734 m_UnloadCompleteEvent.Set();
10737 void ADUnloadSink::WaitUnloadCompletion()
10743 PRECONDITION(CheckPointer(this));
10744 PRECONDITION(m_UnloadCompleteEvent.IsValid());
10748 CONTRACT_VIOLATION(FaultViolation);
10749 m_UnloadCompleteEvent.WaitEx(INFINITE, (WaitMode)(WaitMode_Alertable | WaitMode_ADUnload));
10752 ADUnloadSink* AppDomain::PrepareForWaitUnloadCompletion()
10758 PRECONDITION(SystemDomain::IsUnderDomainLock());
10763 ADUnloadSink* pADSink=GetADUnloadSink();
10764 PREFIX_ASSUME(pADSink!=NULL);
10765 if (m_Stage < AppDomain::STAGE_UNLOAD_REQUESTED) //we're first
10768 SetUnloadRequestThread(GetThread());
10773 ADUnloadSink::ADUnloadSink()
10781 INJECT_FAULT(COMPlusThrowOM(););
10786 m_UnloadCompleteEvent.CreateManualEvent(FALSE);
10787 m_UnloadResult=S_OK;
10790 ADUnloadSink::~ADUnloadSink()
10800 m_UnloadCompleteEvent.CloseEvent();
10805 ULONG ADUnloadSink::AddRef()
10807 LIMITED_METHOD_CONTRACT;
10808 return InterlockedIncrement(&m_cRef);
10811 ULONG ADUnloadSink::Release()
10813 LIMITED_METHOD_CONTRACT;
10814 ULONG ulRef = InterlockedDecrement(&m_cRef);
10822 void ADUnloadSink::Reset()
10824 LIMITED_METHOD_CONTRACT;
10825 m_UnloadResult=S_OK;
10826 m_UnloadCompleteEvent.Reset();
10829 ADUnloadSink* AppDomain::GetADUnloadSink()
10831 LIMITED_METHOD_CONTRACT;
10832 _ASSERTE(SystemDomain::IsUnderDomainLock());
10834 m_ADUnloadSink->AddRef();
10835 return m_ADUnloadSink;
10838 ADUnloadSink* AppDomain::GetADUnloadSinkForUnload()
10840 // unload thread only. Doesn't need to have AD lock
10841 LIMITED_METHOD_CONTRACT;
10843 m_ADUnloadSink->AddRef();
10844 return m_ADUnloadSink;
10846 #endif // CROSSGEN_COMPILE
10848 void AppDomain::EnumStaticGCRefs(promote_func* fn, ScanContext* sc)
10857 _ASSERTE(GCHeapUtilities::IsGCInProgress() &&
10858 GCHeapUtilities::IsServerHeap() &&
10859 IsGCSpecialThread());
10861 AppDomain::AssemblyIterator asmIterator = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution));
10862 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
10863 while (asmIterator.Next(pDomainAssembly.This()))
10865 // @TODO: Review when DomainAssemblies get added.
10866 _ASSERTE(pDomainAssembly != NULL);
10867 pDomainAssembly->EnumStaticGCRefs(fn, sc);
10873 #endif // !DACCESS_COMPILE
10875 //------------------------------------------------------------------------
10876 UINT32 BaseDomain::GetTypeID(PTR_MethodTable pMT) {
10880 PRECONDITION(pMT->GetDomain() == this);
10883 return m_typeIDMap.GetTypeID(pMT);
10886 //------------------------------------------------------------------------
10887 // Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
10888 UINT32 BaseDomain::LookupTypeID(PTR_MethodTable pMT)
10893 WRAPPER(GC_TRIGGERS);
10894 PRECONDITION(pMT->GetDomain() == this);
10897 return m_typeIDMap.LookupTypeID(pMT);
10900 //------------------------------------------------------------------------
10901 PTR_MethodTable BaseDomain::LookupType(UINT32 id) {
10905 WRAPPER(GC_TRIGGERS);
10906 CONSISTENCY_CHECK(id != TYPE_ID_THIS_CLASS);
10909 PTR_MethodTable pMT = m_typeIDMap.LookupType(id);
10910 if (pMT == NULL && !IsSharedDomain()) {
10911 pMT = SharedDomain::GetDomain()->LookupType(id);
10914 CONSISTENCY_CHECK(CheckPointer(pMT));
10915 CONSISTENCY_CHECK(pMT->IsInterface());
10919 //---------------------------------------------------------------------------------------
10922 AppDomain::AssemblyIterator::Next(
10923 CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder)
10927 WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
10931 CrstHolder ch(m_pAppDomain->GetAssemblyListLock());
10932 return Next_Unlocked(pDomainAssemblyHolder);
10935 //---------------------------------------------------------------------------------------
10937 // Note: Does not lock the assembly list, but locks collectible assemblies for adding references.
10940 AppDomain::AssemblyIterator::Next_Unlocked(
10941 CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder)
10949 #ifndef DACCESS_COMPILE
10950 _ASSERTE(m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
10953 while (m_Iterator.Next())
10955 // Get element from the list/iterator (without adding reference to the assembly)
10956 DomainAssembly * pDomainAssembly = dac_cast<PTR_DomainAssembly>(m_Iterator.GetElement());
10957 if (pDomainAssembly == NULL)
10962 if (pDomainAssembly->IsError())
10964 if (m_assemblyIterationFlags & kIncludeFailedToLoad)
10966 *pDomainAssemblyHolder = pDomainAssembly;
10969 continue; // reject
10972 // First, reject DomainAssemblies whose load status is not to be included in
10975 if (pDomainAssembly->IsAvailableToProfilers() &&
10976 (m_assemblyIterationFlags & kIncludeAvailableToProfilers))
10978 // The assembly has reached the state at which we would notify profilers,
10979 // and we're supposed to include such assemblies in the enumeration. So
10980 // don't reject it (i.e., noop here, and don't bother with the rest of
10981 // the load status checks). Check for this first, since
10982 // kIncludeAvailableToProfilers contains some loaded AND loading
10985 else if (pDomainAssembly->IsLoaded())
10987 // A loaded assembly
10988 if (!(m_assemblyIterationFlags & kIncludeLoaded))
10990 continue; // reject
10995 // A loading assembly
10996 if (!(m_assemblyIterationFlags & kIncludeLoading))
10998 continue; // reject
11002 // Next, reject DomainAssemblies whose execution / introspection status is
11003 // not to be included in the enumeration
11005 if (pDomainAssembly->IsIntrospectionOnly())
11007 // introspection assembly
11008 if (!(m_assemblyIterationFlags & kIncludeIntrospection))
11010 continue; // reject
11015 // execution assembly
11016 if (!(m_assemblyIterationFlags & kIncludeExecution))
11018 continue; // reject
11022 // Next, reject collectible assemblies
11023 if (pDomainAssembly->IsCollectible())
11025 if (m_assemblyIterationFlags & kExcludeCollectible)
11027 _ASSERTE(!(m_assemblyIterationFlags & kIncludeCollected));
11028 continue; // reject
11031 // Un-tenured collectible assemblies should not be returned. (This can only happen in a brief
11032 // window during collectible assembly creation. No thread should need to have a pointer
11033 // to the just allocated DomainAssembly at this stage.)
11034 if (!pDomainAssembly->GetAssembly()->GetManifestModule()->IsTenured())
11036 continue; // reject
11039 if (pDomainAssembly->GetLoaderAllocator()->AddReferenceIfAlive())
11040 { // The assembly is alive
11042 // Set the holder value (incl. increasing ref-count)
11043 *pDomainAssemblyHolder = pDomainAssembly;
11045 // Now release the reference we took in the if-condition
11046 pDomainAssembly->GetLoaderAllocator()->Release();
11049 // The assembly is not alive anymore (and we didn't increase its ref-count in the
11052 if (!(m_assemblyIterationFlags & kIncludeCollected))
11054 continue; // reject
11056 // Set the holder value to assembly with 0 ref-count without increasing the ref-count (won't
11057 // call Release either)
11058 pDomainAssemblyHolder->Assign(pDomainAssembly, FALSE);
11062 *pDomainAssemblyHolder = pDomainAssembly;
11066 *pDomainAssemblyHolder = NULL;
11068 } // AppDomain::AssemblyIterator::Next_Unlocked
11070 #ifndef DACCESS_COMPILE
11072 //---------------------------------------------------------------------------------------
11074 // Can be called only from AppDomain shutdown code:AppDomain::ShutdownAssemblies.
11075 // Does not add-ref collectible assemblies (as the LoaderAllocator might not be reachable from the
11076 // DomainAssembly anymore).
11079 AppDomain::AssemblyIterator::Next_UnsafeNoAddRef(
11080 DomainAssembly ** ppDomainAssembly)
11088 // Make sure we are iterating all assemblies (see the only caller code:AppDomain::ShutdownAssemblies)
11089 _ASSERTE(m_assemblyIterationFlags ==
11090 (kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
11091 // It also means that we do not exclude anything
11092 _ASSERTE((m_assemblyIterationFlags & kExcludeCollectible) == 0);
11094 // We are on shutdown path, so lock shouldn't be neccessary, but all _Unlocked methods on AssemblyList
11095 // have asserts that the lock is held, so why not to take it ...
11096 CrstHolder ch(m_pAppDomain->GetAssemblyListLock());
11098 while (m_Iterator.Next())
11100 // Get element from the list/iterator (without adding reference to the assembly)
11101 *ppDomainAssembly = dac_cast<PTR_DomainAssembly>(m_Iterator.GetElement());
11102 if (*ppDomainAssembly == NULL)
11110 *ppDomainAssembly = NULL;
11112 } // AppDomain::AssemblyIterator::Next_UnsafeNoAddRef
11115 //---------------------------------------------------------------------------------------
11117 BOOL AppDomain::IsImageFromTrustedPath(PEImage* pPEImage)
11124 PRECONDITION(CheckPointer(pPEImage));
11128 const SString &sImagePath = pPEImage->GetPath();
11130 return !sImagePath.IsEmpty();
11133 #endif //!DACCESS_COMPILE
11135 #if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
11137 // Returns a BOOL indicating if the binding model has been locked for the AppDomain
11138 BOOL AppDomain::IsBindingModelLocked()
11148 return m_fIsBindingModelLocked.Load();
11151 // Marks the binding model locked for AppDomain
11152 BOOL AppDomain::LockBindingModel()
11154 LIMITED_METHOD_CONTRACT;
11156 BOOL fDidWeLockBindingModel = FALSE;
11158 if (InterlockedCompareExchangeT<BOOL>(&m_fIsBindingModelLocked, TRUE, FALSE) == FALSE)
11160 fDidWeLockBindingModel = TRUE;
11163 return fDidWeLockBindingModel;
11166 BOOL AppDomain::IsHostAssemblyResolverInUse()
11168 LIMITED_METHOD_CONTRACT;
11170 return (GetFusionContext() != GetTPABinderContext());
11173 // Helper used by the assembly binder to check if the specified AppDomain can use apppath assembly resolver
11174 BOOL RuntimeCanUseAppPathAssemblyResolver(DWORD adid)
11178 NOTHROW; // Cannot throw since it is invoked by the Binder that expects to get a hresult
11186 // We need to be in COOP mode to get the AppDomain*
11189 AppDomain *pTargetDomain = SystemDomain::GetAppDomainFromId(id, ADV_CURRENTAD);
11190 _ASSERTE(pTargetDomain != NULL);
11192 pTargetDomain->LockBindingModel();
11194 return !pTargetDomain->IsHostAssemblyResolverInUse();
11197 // Returns S_OK if the assembly was successfully loaded
11198 HRESULT RuntimeInvokeHostAssemblyResolver(INT_PTR pManagedAssemblyLoadContextToBindWithin, IAssemblyName *pIAssemblyName, CLRPrivBinderCoreCLR *pTPABinder, BINDER_SPACE::AssemblyName *pAssemblyName, ICLRPrivAssembly **ppLoadedAssembly)
11205 PRECONDITION(ppLoadedAssembly != NULL);
11209 HRESULT hr = E_FAIL;
11211 // DevDiv #933506: Exceptions thrown during AssemblyLoadContext.Load should propagate
11214 // Switch to COOP mode since we are going to work with managed references
11219 ASSEMBLYNAMEREF oRefAssemblyName;
11220 ASSEMBLYREF oRefLoadedAssembly;
11223 ZeroMemory(&_gcRefs, sizeof(_gcRefs));
11225 GCPROTECT_BEGIN(_gcRefs);
11227 ICLRPrivAssembly *pAssemblyBindingContext = NULL;
11229 bool fInvokedForTPABinder = (pTPABinder == NULL)?true:false;
11231 // Prepare to invoke System.Runtime.Loader.AssemblyLoadContext.Resolve method.
11233 // First, initialize an assembly spec for the requested assembly
11236 hr = spec.Init(pIAssemblyName);
11239 bool fResolvedAssembly = false;
11240 bool fResolvedAssemblyViaTPALoadContext = false;
11242 // Allocate an AssemblyName managed object
11243 _gcRefs.oRefAssemblyName = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME));
11245 // Initialize the AssemblyName object from the AssemblySpec
11246 spec.AssemblyNameInit(&_gcRefs.oRefAssemblyName, NULL);
11248 if (!fInvokedForTPABinder)
11250 // Step 2 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName) - Invoke Load method
11251 // This is not invoked for TPA Binder since it always returns NULL.
11253 // Finally, setup arguments for invocation
11254 BinderMethodID idHAR_Resolve = METHOD__ASSEMBLYLOADCONTEXT__RESOLVE;
11255 MethodDescCallSite methLoadAssembly(idHAR_Resolve);
11257 // Setup the arguments for the call
11260 PtrToArgSlot(pManagedAssemblyLoadContextToBindWithin), // IntPtr for managed assembly load context instance
11261 ObjToArgSlot(_gcRefs.oRefAssemblyName), // AssemblyName instance
11265 _gcRefs.oRefLoadedAssembly = (ASSEMBLYREF) methLoadAssembly.Call_RetOBJECTREF(args);
11266 if (_gcRefs.oRefLoadedAssembly != NULL)
11268 fResolvedAssembly = true;
11271 // Step 3 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName)
11272 if (!fResolvedAssembly)
11274 // If we could not resolve the assembly using Load method, then attempt fallback with TPA Binder.
11275 // Since TPA binder cannot fallback to itself, this fallback does not happen for binds within TPA binder.
11277 // Switch to pre-emp mode before calling into the binder
11279 ICLRPrivAssembly *pCoreCLRFoundAssembly = NULL;
11280 hr = pTPABinder->BindAssemblyByName(pIAssemblyName, &pCoreCLRFoundAssembly);
11283 pAssemblyBindingContext = pCoreCLRFoundAssembly;
11284 fResolvedAssembly = true;
11285 fResolvedAssemblyViaTPALoadContext = true;
11290 if (!fResolvedAssembly)
11292 // Step 4 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName)
11294 // If we couldnt resolve the assembly using TPA LoadContext as well, then
11295 // attempt to resolve it using the Resolving event.
11296 // Finally, setup arguments for invocation
11297 BinderMethodID idHAR_ResolveUsingEvent = METHOD__ASSEMBLYLOADCONTEXT__RESOLVEUSINGEVENT;
11298 MethodDescCallSite methLoadAssembly(idHAR_ResolveUsingEvent);
11300 // Setup the arguments for the call
11303 PtrToArgSlot(pManagedAssemblyLoadContextToBindWithin), // IntPtr for managed assembly load context instance
11304 ObjToArgSlot(_gcRefs.oRefAssemblyName), // AssemblyName instance
11308 _gcRefs.oRefLoadedAssembly = (ASSEMBLYREF) methLoadAssembly.Call_RetOBJECTREF(args);
11309 if (_gcRefs.oRefLoadedAssembly != NULL)
11311 // Set the flag indicating we found the assembly
11312 fResolvedAssembly = true;
11316 if (fResolvedAssembly && !fResolvedAssemblyViaTPALoadContext)
11318 // If we are here, assembly was successfully resolved via Load or Resolving events.
11319 _ASSERTE(_gcRefs.oRefLoadedAssembly != NULL);
11321 // We were able to get the assembly loaded. Now, get its name since the host could have
11322 // performed the resolution using an assembly with different name.
11323 DomainAssembly *pDomainAssembly = _gcRefs.oRefLoadedAssembly->GetDomainAssembly();
11324 PEAssembly *pLoadedPEAssembly = NULL;
11325 bool fFailLoad = false;
11326 if (!pDomainAssembly)
11328 // Reflection emitted assemblies will not have a domain assembly.
11333 pLoadedPEAssembly = pDomainAssembly->GetFile();
11334 if (pLoadedPEAssembly->HasHostAssembly() != true)
11336 // Reflection emitted assemblies will not have a domain assembly.
11341 // The loaded assembly's ICLRPrivAssembly* is saved as HostAssembly in PEAssembly
11345 spec.GetFileOrDisplayName(0, name);
11346 COMPlusThrowHR(COR_E_INVALIDOPERATION, IDS_HOST_ASSEMBLY_RESOLVER_DYNAMICALLY_EMITTED_ASSEMBLIES_UNSUPPORTED, name);
11349 // Is the assembly already bound using a binding context that will be incompatible?
11350 // An example is attempting to consume an assembly bound to WinRT binder.
11351 pAssemblyBindingContext = pLoadedPEAssembly->GetHostAssembly();
11354 #ifdef FEATURE_COMINTEROP
11355 if (AreSameBinderInstance(pAssemblyBindingContext, GetAppDomain()->GetWinRtBinder()))
11357 // It is invalid to return an assembly bound to an incompatible binder
11358 *ppLoadedAssembly = NULL;
11360 spec.GetFileOrDisplayName(0, name);
11361 COMPlusThrowHR(COR_E_INVALIDOPERATION, IDS_HOST_ASSEMBLY_RESOLVER_INCOMPATIBLE_BINDING_CONTEXT, name);
11363 #endif // FEATURE_COMINTEROP
11365 // Get the ICLRPrivAssembly reference to return back to.
11366 *ppLoadedAssembly = clr::SafeAddRef(pAssemblyBindingContext);
11372 // EX_CATCH_HRESULT(hr);
11377 #endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
11379 //approximate size of loader data
11380 //maintained for each assembly
11381 #define APPROX_LOADER_DATA_PER_ASSEMBLY 8196
11383 size_t AppDomain::EstimateSize()
11393 size_t retval = sizeof(AppDomain);
11394 retval += GetLoaderAllocator()->EstimateSize();
11395 //very rough estimate
11396 retval += GetAssemblyCount() * APPROX_LOADER_DATA_PER_ASSEMBLY;
11400 #ifdef DACCESS_COMPILE
11403 DomainLocalModule::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
11407 // Enumerate the DomainLocalModule itself. DLMs are allocated to be larger than
11408 // sizeof(DomainLocalModule) to make room for ClassInit flags and non-GC statics.
11409 // "DAC_ENUM_DTHIS()" probably does not account for this, so we might not enumerate
11410 // all of the ClassInit flags and non-GC statics.
11411 // sizeof(DomainLocalModule) == 0x28
11414 if (m_pDomainFile.IsValid())
11416 m_pDomainFile->EnumMemoryRegions(flags);
11419 if (m_pDynamicClassTable.Load().IsValid())
11421 DacEnumMemoryRegion(dac_cast<TADDR>(m_pDynamicClassTable.Load()),
11422 m_aDynamicEntries * sizeof(DynamicClassInfo));
11424 for (SIZE_T i = 0; i < m_aDynamicEntries; i++)
11426 PTR_DynamicEntry entry = dac_cast<PTR_DynamicEntry>(m_pDynamicClassTable[i].m_pDynamicEntry.Load());
11427 if (entry.IsValid())
11429 // sizeof(DomainLocalModule::DynamicEntry) == 8
11437 DomainLocalBlock::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
11440 // Block is contained in AppDomain, don't enum this.
11442 if (m_pModuleSlots.IsValid())
11444 DacEnumMemoryRegion(dac_cast<TADDR>(m_pModuleSlots),
11445 m_aModuleIndices * sizeof(TADDR));
11447 for (SIZE_T i = 0; i < m_aModuleIndices; i++)
11449 PTR_DomainLocalModule domMod = m_pModuleSlots[i];
11450 if (domMod.IsValid())
11452 domMod->EnumMemoryRegions(flags);
11459 BaseDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11465 // This is wrong. Don't do it.
11466 // BaseDomain cannot be instantiated.
11467 // The only thing this code can hope to accomplish is to potentially break
11468 // memory enumeration walking through the derived class if we
11469 // explicitly call the base class enum first.
11470 // DAC_ENUM_VTHIS();
11473 EMEM_OUT(("MEM: %p BaseDomain\n", dac_cast<TADDR>(this)));
11477 AppDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11484 //sizeof(AppDomain) == 0xeb0
11487 BaseDomain::EnumMemoryRegions(flags, false);
11489 // We don't need AppDomain name in triage dumps.
11490 if (flags != CLRDATA_ENUM_MEM_TRIAGE)
11492 m_friendlyName.EnumMemoryRegions(flags);
11495 m_Assemblies.EnumMemoryRegions(flags);
11496 AssemblyIterator assem = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution | kIncludeIntrospection));
11497 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
11499 while (assem.Next(pDomainAssembly.This()))
11501 pDomainAssembly->EnumMemoryRegions(flags);
11504 m_sDomainLocalBlock.EnumMemoryRegions(flags);
11506 m_LoaderAllocator.EnumMemoryRegions(flags);
11510 SystemDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11518 BaseDomain::EnumMemoryRegions(flags, false);
11520 if (m_pSystemFile.IsValid())
11522 m_pSystemFile->EnumMemoryRegions(flags);
11524 if (m_pSystemAssembly.IsValid())
11526 m_pSystemAssembly->EnumMemoryRegions(flags);
11528 if (m_pDefaultDomain.IsValid())
11530 m_pDefaultDomain->EnumMemoryRegions(flags, true);
11533 m_appDomainIndexList.EnumMem();
11534 (&m_appDomainIndexList)->EnumMemoryRegions(flags);
11538 SharedDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11546 BaseDomain::EnumMemoryRegions(flags, false);
11547 #ifdef FEATURE_LOADER_OPTIMIZATION
11548 m_assemblyMap.EnumMemoryRegions(flags);
11549 SharedAssemblyIterator assem;
11550 while (assem.Next())
11552 assem.GetAssembly()->EnumMemoryRegions(flags);
11557 #endif //DACCESS_COMPILE
11560 PTR_LoaderAllocator SystemDomain::GetGlobalLoaderAllocator()
11562 return PTR_LoaderAllocator(PTR_HOST_MEMBER_TADDR(SystemDomain,System(),m_GlobalAllocator));
11565 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
11567 #ifndef CROSSGEN_COMPILE
11568 // Return the total processor time (user and kernel) used by threads executing in this AppDomain so far. The
11569 // result is in 100ns units.
11570 ULONGLONG AppDomain::QueryProcessorUsage()
11580 #ifndef DACCESS_COMPILE
11581 Thread *pThread = NULL;
11583 // Need to update our accumulated processor time count with current values from each thread that is
11584 // currently executing in this domain.
11586 // Take the thread store lock while we enumerate threads.
11587 ThreadStoreLockHolder tsl;
11588 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
11590 // Skip unstarted and dead threads and those that are currently executing in a different AppDomain.
11591 if (pThread->IsUnstarted() || pThread->IsDead() || pThread->GetDomain(INDEBUG(TRUE)) != this)
11594 // Add the amount of time spent by the thread in the AppDomain since the last time we asked (calling
11595 // Thread::QueryThreadProcessorUsage() will reset the thread's counter).
11596 UpdateProcessorUsage(pThread->QueryThreadProcessorUsage());
11598 #endif // !DACCESS_COMPILE
11600 // Return the updated total.
11601 return m_ullTotalProcessorUsage;
11604 // Add to the current count of processor time used by threads within this AppDomain. This API is called by
11605 // threads transitioning between AppDomains.
11606 void AppDomain::UpdateProcessorUsage(ULONGLONG ullAdditionalUsage)
11608 LIMITED_METHOD_CONTRACT;
11610 // Need to be careful to synchronize here, multiple threads could be racing to update this count.
11611 ULONGLONG ullOldValue;
11612 ULONGLONG ullNewValue;
11615 ullOldValue = m_ullTotalProcessorUsage;
11616 ullNewValue = ullOldValue + ullAdditionalUsage;
11617 } while (InterlockedCompareExchange64((LONGLONG*)&m_ullTotalProcessorUsage,
11618 (LONGLONG)ullNewValue,
11619 (LONGLONG)ullOldValue) != (LONGLONG)ullOldValue);
11621 #endif // CROSSGEN_COMPILE
11623 #endif // FEATURE_APPDOMAIN_RESOURCE_MONITORING
11625 #if defined(FEATURE_TYPEEQUIVALENCE)
11627 #ifndef DACCESS_COMPILE
11628 TypeEquivalenceHashTable * AppDomain::GetTypeEquivalenceCache()
11634 INJECT_FAULT(COMPlusThrowOM());
11639 // Take the critical section all of the time in debug builds to ensure that it is safe to take
11640 // the critical section in the unusual times when it may actually be needed in retail builds
11642 CrstHolder ch(&m_TypeEquivalenceCrst);
11645 if (m_pTypeEquivalenceTable.Load() == NULL)
11648 CrstHolder ch(&m_TypeEquivalenceCrst);
11650 if (m_pTypeEquivalenceTable.Load() == NULL)
11652 m_pTypeEquivalenceTable = TypeEquivalenceHashTable::Create(this, 12, &m_TypeEquivalenceCrst);
11655 return m_pTypeEquivalenceTable;
11657 #endif //!DACCESS_COMPILE
11659 #endif //FEATURE_TYPEEQUIVALENCE
11661 #if !defined(DACCESS_COMPILE)
11663 //---------------------------------------------------------------------------------------------------------------------
11664 void AppDomain::PublishHostedAssembly(
11665 DomainAssembly * pDomainAssembly)
11675 if (pDomainAssembly->GetFile()->HasHostAssembly())
11677 // We have to serialize all Add operations
11678 CrstHolder lockAdd(&m_crstHostAssemblyMapAdd);
11679 _ASSERTE(m_hostAssemblyMap.Lookup(pDomainAssembly->GetFile()->GetHostAssembly()) == nullptr);
11681 // Wrapper for m_hostAssemblyMap.Add that avoids call out into host
11682 HostAssemblyMap::AddPhases addCall;
11684 // 1. Preallocate one element
11685 addCall.PreallocateForAdd(&m_hostAssemblyMap);
11687 // 2. Take the reader lock which can be taken during stack walking
11688 // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations)
11689 ForbidSuspendThreadHolder suspend;
11691 CrstHolder lock(&m_crstHostAssemblyMap);
11692 // 3. Add the element to the hash table (no call out into host)
11693 addCall.Add(pDomainAssembly);
11696 // 4. Cleanup the old memory (if any)
11697 addCall.DeleteOldTable();
11704 //---------------------------------------------------------------------------------------------------------------------
11705 void AppDomain::UpdatePublishHostedAssembly(
11706 DomainAssembly * pAssembly,
11718 if (pAssembly->GetFile()->HasHostAssembly())
11720 // We have to serialize all Add operations
11721 CrstHolder lockAdd(&m_crstHostAssemblyMapAdd);
11723 // Wrapper for m_hostAssemblyMap.Add that avoids call out into host
11724 OriginalFileHostAssemblyMap::AddPhases addCall;
11725 bool fAddOrigFile = false;
11727 // For cases where the pefile is being updated
11728 // 1. Preallocate one element
11729 if (pFile != pAssembly->GetFile())
11731 addCall.PreallocateForAdd(&m_hostAssemblyMapForOrigFile);
11732 fAddOrigFile = true;
11736 // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations)
11737 ForbidSuspendThreadHolder suspend;
11739 CrstHolder lock(&m_crstHostAssemblyMap);
11741 // Remove from hash table.
11742 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) != nullptr);
11743 m_hostAssemblyMap.Remove(pAssembly->GetFile()->GetHostAssembly());
11745 // Update PEFile on DomainAssembly. (This may cause the key for the hash to change, which is why we need this function)
11746 pAssembly->UpdatePEFileWorker(pFile);
11748 _ASSERTE(fAddOrigFile == (pAssembly->GetOriginalFile() != pAssembly->GetFile()));
11751 // Add to the orig file hash table if we might be in a case where we've cached the original pefile and not the final pe file (for use during GetAssemblyIfLoaded)
11752 addCall.Add(pAssembly);
11755 // Add back to the hashtable (the call to Remove above guarantees that we will not call into host for table reallocation)
11756 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) == nullptr);
11757 m_hostAssemblyMap.Add(pAssembly);
11761 // 4. Cleanup the old memory (if any)
11763 addCall.DeleteOldTable();
11769 pAssembly->UpdatePEFileWorker(pFile);
11773 //---------------------------------------------------------------------------------------------------------------------
11774 void AppDomain::UnPublishHostedAssembly(
11775 DomainAssembly * pAssembly)
11786 if (pAssembly->GetFile()->HasHostAssembly())
11788 ForbidSuspendThreadHolder suspend;
11790 CrstHolder lock(&m_crstHostAssemblyMap);
11791 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) != nullptr);
11792 m_hostAssemblyMap.Remove(pAssembly->GetFile()->GetHostAssembly());
11794 // We also have an entry in m_hostAssemblyMapForOrigFile. Handle that case.
11795 if (pAssembly->GetOriginalFile() != pAssembly->GetFile())
11797 m_hostAssemblyMapForOrigFile.Remove(pAssembly->GetOriginalFile()->GetHostAssembly());
11803 // In AppX processes, all PEAssemblies that are reach this stage should have host binders.
11804 _ASSERTE(!AppX::IsAppXProcess());
11808 #if defined(FEATURE_COMINTEROP)
11809 HRESULT AppDomain::SetWinrtApplicationContext(SString &appLocalWinMD)
11811 STANDARD_VM_CONTRACT;
11813 _ASSERTE(WinRTSupported());
11814 _ASSERTE(m_pWinRtBinder != nullptr);
11816 _ASSERTE(GetTPABinderContext() != NULL);
11817 BINDER_SPACE::ApplicationContext *pApplicationContext = GetTPABinderContext()->GetAppContext();
11818 _ASSERTE(pApplicationContext != NULL);
11820 return m_pWinRtBinder->SetApplicationContext(pApplicationContext, appLocalWinMD);
11823 #endif // FEATURE_COMINTEROP
11825 #endif //!DACCESS_COMPILE
11827 //---------------------------------------------------------------------------------------------------------------------
11828 PTR_DomainAssembly AppDomain::FindAssembly(PTR_ICLRPrivAssembly pHostAssembly)
11839 if (pHostAssembly == nullptr)
11843 ForbidSuspendThreadHolder suspend;
11845 CrstHolder lock(&m_crstHostAssemblyMap);
11846 PTR_DomainAssembly returnValue = m_hostAssemblyMap.Lookup(pHostAssembly);
11847 if (returnValue == NULL)
11849 // If not found in the m_hostAssemblyMap, look in the m_hostAssemblyMapForOrigFile
11850 // This is necessary as it may happen during in a second AppDomain that the PEFile
11851 // first discovered in the AppDomain may not be used by the DomainFile, but the CLRPrivBinderFusion
11852 // will in some cases find the pHostAssembly associated with this no longer used PEFile
11853 // instead of the PEFile that was finally decided upon.
11854 returnValue = m_hostAssemblyMapForOrigFile.Lookup(pHostAssembly);
11857 return returnValue;
11862 #if !defined(DACCESS_COMPILE) && defined(FEATURE_NATIVE_IMAGE_GENERATION)
11864 void ZapperSetBindingPaths(ICorCompilationDomain *pDomain, SString &trustedPlatformAssemblies, SString &platformResourceRoots, SString &appPaths, SString &appNiPaths)
11866 CLRPrivBinderCoreCLR *pBinder = static_cast<CLRPrivBinderCoreCLR*>(((CompilationDomain *)pDomain)->GetFusionContext());
11867 _ASSERTE(pBinder != NULL);
11868 pBinder->SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths);
11869 #ifdef FEATURE_COMINTEROP
11870 SString emptString;
11871 ((CompilationDomain*)pDomain)->SetWinrtApplicationContext(emptString);