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 "sxshelpers.h"
50 #include "runtimecallablewrapper.h"
51 #include "mngstdinterfaces.h"
52 #include "olevariant.h"
53 #include "rcwrefcache.h"
54 #include "olecontexthelpers.h"
55 #endif // FEATURE_COMINTEROP
56 #ifdef FEATURE_TYPEEQUIVALENCE
57 #include "typeequivalencehash.hpp"
60 #include "appdomain.inl"
61 #include "typeparse.h"
62 #include "mdaassistants.h"
63 #include "threadpoolrequest.h"
65 #include "nativeoverlapped.h"
67 #include "compatibilityflags.h"
71 #endif // !FEATURE_PAL
73 #include "stringarraylist.h"
75 #include "../binder/inc/clrprivbindercoreclr.h"
78 #include "clrprivtypecachewinrt.h"
82 #pragma warning(disable:4324)
86 // this file handles string conversion errors for itself
87 #undef MAKE_TRANSLATIONFAILED
89 // Define these macro's to do strict validation for jit lock and class
90 // init entry leaks. This defines determine if the asserts that
91 // verify for these leaks are defined or not. These asserts can
92 // sometimes go off even if no entries have been leaked so this
93 // defines should be used with caution.
95 // If we are inside a .cctor when the application shut's down then the
96 // class init lock's head will be set and this will cause the assert
99 // If we are jitting a method when the application shut's down then
100 // the jit lock's head will be set causing the assert to go off.
102 //#define STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
104 static const WCHAR DEFAULT_DOMAIN_FRIENDLY_NAME[] = W("DefaultDomain");
105 static const WCHAR OTHER_DOMAIN_FRIENDLY_NAME_PREFIX[] = W("Domain");
107 #define STATIC_OBJECT_TABLE_BUCKET_SIZE 1020
109 #define MAX_URL_LENGTH 2084 // same as INTERNET_MAX_URL_LENGTH
111 //#define _DEBUG_ADUNLOAD 1
113 HRESULT RunDllMain(MethodDesc *pMD, HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved); // clsload.cpp
121 SPTR_IMPL(SystemDomain, SystemDomain, m_pSystemDomain);
122 SVAL_IMPL(ArrayListStatic, SystemDomain, m_appDomainIndexList);
123 SPTR_IMPL(SharedDomain, SharedDomain, m_pSharedDomain);
124 SVAL_IMPL(BOOL, SystemDomain, s_fForceDebug);
125 SVAL_IMPL(BOOL, SystemDomain, s_fForceProfiling);
126 SVAL_IMPL(BOOL, SystemDomain, s_fForceInstrument);
128 #ifndef DACCESS_COMPILE
130 // Base Domain Statics
131 CrstStatic BaseDomain::m_SpecialStaticsCrst;
133 int BaseDomain::m_iNumberOfProcessors = 0;
135 // Shared Domain Statics
137 static BYTE g_pSharedDomainMemory[sizeof(SharedDomain)];
139 // System Domain Statics
140 GlobalStringLiteralMap* SystemDomain::m_pGlobalStringLiteralMap = NULL;
143 static BYTE g_pSystemDomainMemory[sizeof(SystemDomain)];
145 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
146 size_t SystemDomain::m_totalSurvivedBytes = 0;
147 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
149 CrstStatic SystemDomain::m_SystemDomainCrst;
150 CrstStatic SystemDomain::m_DelayedUnloadCrst;
152 ULONG SystemDomain::s_dNumAppDomains = 0;
154 AppDomain * SystemDomain::m_pAppDomainBeingUnloaded = NULL;
155 ADIndex SystemDomain::m_dwIndexOfAppDomainBeingUnloaded;
156 Thread *SystemDomain::m_pAppDomainUnloadRequestingThread = 0;
157 Thread *SystemDomain::m_pAppDomainUnloadingThread = 0;
159 ArrayListStatic SystemDomain::m_appDomainIdList;
161 DWORD SystemDomain::m_dwLowestFreeIndex = 0;
165 // comparison function to be used for matching clsids in our clsid hash table
166 BOOL CompareCLSID(UPTR u1, UPTR u2)
174 INJECT_FAULT(COMPlusThrowOM(););
178 GUID *pguid = (GUID *)(u1 << 1);
179 _ASSERTE(pguid != NULL);
181 MethodTable *pMT= (MethodTable *)u2;
182 _ASSERTE(pMT!= NULL);
185 pMT->GetGuid(&guid, TRUE);
186 if (!IsEqualIID(guid, *pguid))
192 #ifndef CROSSGEN_COMPILE
193 // Constructor for the LargeHeapHandleBucket class.
194 LargeHeapHandleBucket::LargeHeapHandleBucket(LargeHeapHandleBucket *pNext, DWORD Size, BaseDomain *pDomain, BOOL bCrossAD)
198 , m_CurrentEmbeddedFreePos(0) // hint for where to start a search for an embedded free item
205 PRECONDITION(CheckPointer(pDomain));
206 INJECT_FAULT(COMPlusThrowOM(););
210 PTRARRAYREF HandleArrayObj;
212 // Allocate the array in the large object heap.
215 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
216 HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, TRUE);
220 // During AD creation we don't want to assign the handle array to the currently running AD but
221 // to the AD being created. Ensure that AllocateArrayEx doesn't set the AD and then set it here.
222 AppDomain *pAD = pDomain->AsAppDomain();
224 _ASSERTE(pAD->IsBeingCreated());
228 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
229 array = AllocateArrayEx(
230 ClassLoader::LoadArrayTypeThrowing(g_pObjectClass),
237 array->SetAppDomain(pAD);
239 HandleArrayObj = (PTRARRAYREF)array;
242 // Retrieve the pointer to the data inside the array. This is legal since the array
243 // is located in the large object heap and is guaranteed not to move.
244 m_pArrayDataPtr = (OBJECTREF *)HandleArrayObj->GetDataPtr();
246 // Store the array in a strong handle to keep it alive.
247 m_hndHandleArray = pDomain->CreatePinningHandle((OBJECTREF)HandleArrayObj);
251 // Destructor for the LargeHeapHandleBucket class.
252 LargeHeapHandleBucket::~LargeHeapHandleBucket()
261 if (m_hndHandleArray)
263 DestroyPinningHandle(m_hndHandleArray);
264 m_hndHandleArray = NULL;
269 // Allocate handles from the bucket.
270 OBJECTREF *LargeHeapHandleBucket::AllocateHandles(DWORD nRequested)
280 _ASSERTE(nRequested > 0 && nRequested <= GetNumRemainingHandles());
281 _ASSERTE(m_pArrayDataPtr == (OBJECTREF*)((PTRARRAYREF)ObjectFromHandle(m_hndHandleArray))->GetDataPtr());
283 // Store the handles in the buffer that was passed in
284 OBJECTREF* ret = &m_pArrayDataPtr[m_CurrentPos];
285 m_CurrentPos += nRequested;
290 // look for a free item embedded in the table
291 OBJECTREF *LargeHeapHandleBucket::TryAllocateEmbeddedFreeHandle()
301 OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
302 _ASSERTE(pPreallocatedSentinalObject != NULL);
304 for (int i = m_CurrentEmbeddedFreePos; i < m_CurrentPos; i++)
306 if (m_pArrayDataPtr[i] == pPreallocatedSentinalObject)
308 m_CurrentEmbeddedFreePos = i;
309 m_pArrayDataPtr[i] = NULL;
310 return &m_pArrayDataPtr[i];
314 // 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)
316 m_CurrentEmbeddedFreePos = 0;
321 // Maximum bucket size will be 64K on 32-bit and 128K on 64-bit.
322 // We subtract out a small amount to leave room for the object
323 // header and length of the array.
325 #define MAX_BUCKETSIZE (16384 - 4)
327 // Constructor for the LargeHeapHandleTable class.
328 LargeHeapHandleTable::LargeHeapHandleTable(BaseDomain *pDomain, DWORD InitialBucketSize)
331 , m_NextBucketSize(InitialBucketSize)
332 , m_pFreeSearchHint(NULL)
340 PRECONDITION(CheckPointer(pDomain));
341 INJECT_FAULT(COMPlusThrowOM(););
351 // Destructor for the LargeHeapHandleTable class.
352 LargeHeapHandleTable::~LargeHeapHandleTable()
361 // Delete the buckets.
364 LargeHeapHandleBucket *pOld = m_pHead;
365 m_pHead = pOld->GetNext();
370 //*****************************************************************************
372 // LOCKING RULES FOR AllocateHandles() and ReleaseHandles() 12/08/2004
375 // These functions are not protected by any locking in this location but rather the callers are
376 // assumed to be doing suitable locking for the handle table. The handle table itself is
377 // behaving rather like a thread-agnostic collection class -- it doesn't want to know
378 // much about the outside world and so it is just doing its job with no awareness of
381 // The instance in question is
382 // There are two locations you can find a LargeHeapHandleTable
383 // 1) there is one in every BaseDomain, it is used to keep track of the static members
385 // 2) there is one in the System Domain that is used for the GlobalStringLiteralMap
387 // the one in (2) is not the same as the one that is in the BaseDomain object that corresponds
388 // to the SystemDomain -- that one is basically stilborn because the string literals don't go
389 // there and of course the System Domain has no code loaded into it -- only regular
390 // AppDomains (like Domain 0) actually execute code. As a result handle tables are in
391 // practice used either for string literals or for static members but never for both.
392 // At least not at this writing.
394 // Now it's useful to consider what the locking discipline is for these classes.
398 // First case: (easiest) is the statics members
400 // Each BaseDomain has its own critical section
402 // BaseDomain::AllocateObjRefPtrsInLargeTable takes a lock with
403 // CrstHolder ch(&m_LargeHeapHandleTableCrst);
405 // it does this before it calls AllocateHandles which suffices. It does not call ReleaseHandles
406 // at any time (although ReleaseHandles may be called via AllocateHandles if the request
407 // doesn't fit in the current block, the remaining handles at the end of the block are released
408 // automatically as part of allocation/recycling)
410 // note: Recycled handles are only used during String Literal allocation because we only try
411 // to recycle handles if the allocation request is for exactly one handle.
413 // The handles in the BaseDomain handle table are released when the Domain is unloaded
414 // as the GC objects become rootless at that time.
416 // This dispenses with all of the Handle tables except the one that is used for string literals
420 // Second case: Allocation for use in a string literal
422 // AppDomainStringLiteralMap::GetStringLiteral
424 // LargeHeapHandleBlockHolder constructor
426 // m_Data = pOwner->AllocateHandles(nCount);
428 // before doing this AppDomainStringLiteralMap::GetStringLiteral takes this lock
430 // CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
432 // which is the lock for the hash table that it owns
434 // STRINGREF *AppDomainStringLiteralMap::GetInternedString
436 // has a similar call path and uses the same approach and the same lock
437 // this covers all the paths which allocate
441 // Third case: Releases for use in a string literal entry
443 // CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
444 // taken in the AppDomainStringLiteralMap functions below protects the 4 ways that this can happen
448 // in an appdomain unload case
450 // AppDomainStringLiteralMap::~AppDomainStringLiteralMap() takes the lock then
452 // StringLiteralEntry::Release
454 // SystemDomain::GetGlobalStringLiteralMapNoCreate()->RemoveStringLiteralEntry(this)
456 // m_LargeHeapHandleTable.ReleaseHandles((OBJECTREF*)pObjRef, 1);
460 // AppDomainStringLiteralMap::GetStringLiteral() can call StringLiteralEntry::Release in some
461 // error cases, leading to the same stack as above
465 // AppDomainStringLiteralMap::GetInternedString() can call StringLiteralEntry::Release in some
466 // error cases, leading to the same stack as above
470 // The same code paths in 3b and 3c and also end up releasing if an exception is thrown
471 // during their processing. Both these paths use a StringLiteralEntryHolder to assist in cleanup,
472 // the StaticRelease method of the StringLiteralEntry gets called, which in turn calls the
476 // Allocate handles from the large heap handle table.
477 OBJECTREF* LargeHeapHandleTable::AllocateHandles(DWORD nRequested, BOOL bCrossAD)
484 PRECONDITION(nRequested > 0);
485 INJECT_FAULT(COMPlusThrowOM(););
489 // SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
491 // the lock must be registered and already held by the caller per contract
493 _ASSERTE(m_pCrstDebug != NULL);
494 _ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
497 if (nRequested == 1 && m_cEmbeddedFree != 0)
499 // special casing singleton requests to look for slots that can be re-used
501 // we need to do this because string literals are allocated one at a time and then sometimes
502 // released. we do not wish for the number of handles consumed by string literals to
503 // increase forever as assemblies are loaded and unloaded
505 if (m_pFreeSearchHint == NULL)
506 m_pFreeSearchHint = m_pHead;
508 while (m_pFreeSearchHint)
510 OBJECTREF* pObjRef = m_pFreeSearchHint->TryAllocateEmbeddedFreeHandle();
513 // the slot is to have been prepared with a null ready to go
514 _ASSERTE(*pObjRef == NULL);
518 m_pFreeSearchHint = m_pFreeSearchHint->GetNext();
521 // the search doesn't wrap around so it's possible that we might have embedded free items
522 // and not find them but that's ok, we'll get them on the next alloc... all we're trying to do
523 // is to not have big leaks over time.
527 // Retrieve the remaining number of handles in the bucket.
528 DWORD NumRemainingHandlesInBucket = (m_pHead != NULL) ? m_pHead->GetNumRemainingHandles() : 0;
530 // create a new block if this request doesn't fit in the current block
531 if (nRequested > NumRemainingHandlesInBucket)
535 // mark the handles in that remaining region as available for re-use
536 ReleaseHandles(m_pHead->CurrentPos(), NumRemainingHandlesInBucket);
538 // mark what's left as having been used
539 m_pHead->ConsumeRemaining();
542 // create a new bucket for this allocation
544 // We need a block big enough to hold the requested handles
545 DWORD NewBucketSize = max(m_NextBucketSize, nRequested);
547 m_pHead = new LargeHeapHandleBucket(m_pHead, NewBucketSize, m_pDomain, bCrossAD);
549 m_NextBucketSize = min(m_NextBucketSize * 2, MAX_BUCKETSIZE);
552 return m_pHead->AllocateHandles(nRequested);
555 //*****************************************************************************
556 // Release object handles allocated using AllocateHandles().
557 void LargeHeapHandleTable::ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased)
564 PRECONDITION(CheckPointer(pObjRef));
568 // SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
570 // the lock must be registered and already held by the caller per contract
572 _ASSERTE(m_pCrstDebug != NULL);
573 _ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
576 OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
577 _ASSERTE(pPreallocatedSentinalObject != NULL);
580 // Add the released handles to the list of available handles.
581 for (DWORD i = 0; i < nReleased; i++)
583 SetObjectReference(&pObjRef[i], pPreallocatedSentinalObject, NULL);
586 m_cEmbeddedFree += nReleased;
592 // Constructor for the ThreadStaticHandleBucket class.
593 ThreadStaticHandleBucket::ThreadStaticHandleBucket(ThreadStaticHandleBucket *pNext, DWORD Size, BaseDomain *pDomain)
602 PRECONDITION(CheckPointer(pDomain));
603 INJECT_FAULT(COMPlusThrowOM(););
607 PTRARRAYREF HandleArrayObj;
609 // Allocate the array on the GC heap.
610 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
611 HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, FALSE);
613 // Store the array in a strong handle to keep it alive.
614 m_hndHandleArray = pDomain->CreateStrongHandle((OBJECTREF)HandleArrayObj);
617 // Destructor for the ThreadStaticHandleBucket class.
618 ThreadStaticHandleBucket::~ThreadStaticHandleBucket()
628 if (m_hndHandleArray)
630 DestroyStrongHandle(m_hndHandleArray);
631 m_hndHandleArray = NULL;
635 // Allocate handles from the bucket.
636 OBJECTHANDLE ThreadStaticHandleBucket::GetHandles()
646 return m_hndHandleArray;
649 // Constructor for the ThreadStaticHandleTable class.
650 ThreadStaticHandleTable::ThreadStaticHandleTable(BaseDomain *pDomain)
659 PRECONDITION(CheckPointer(pDomain));
664 // Destructor for the ThreadStaticHandleTable class.
665 ThreadStaticHandleTable::~ThreadStaticHandleTable()
674 // Delete the buckets.
677 ThreadStaticHandleBucket *pOld = m_pHead;
678 m_pHead = pOld->GetNext();
683 // Allocate handles from the large heap handle table.
684 OBJECTHANDLE ThreadStaticHandleTable::AllocateHandles(DWORD nRequested)
691 PRECONDITION(nRequested > 0);
692 INJECT_FAULT(COMPlusThrowOM(););
696 // create a new bucket for this allocation
697 m_pHead = new ThreadStaticHandleBucket(m_pHead, nRequested, m_pDomain);
699 return m_pHead->GetHandles();
702 #endif // CROSSGEN_COMPILE
705 //*****************************************************************************
707 //*****************************************************************************
708 void BaseDomain::Attach()
710 m_SpecialStaticsCrst.Init(CrstSpecialStatics);
713 BaseDomain::BaseDomain()
715 // initialize fields so the domain can be safely destructed
716 // shouldn't call anything that can fail here - use ::Init instead
726 m_fDisableInterfaceCache = FALSE;
728 m_pFusionContext = NULL;
729 m_pTPABinderContext = NULL;
731 // Make sure the container is set to NULL so that it gets loaded when it is used.
732 m_pLargeHeapHandleTable = NULL;
734 #ifndef CROSSGEN_COMPILE
735 // Note that m_handleStore is overridden by app domains
736 m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
738 m_handleStore = NULL;
741 m_pMarshalingData = NULL;
743 m_dwContextStatics = 0;
744 #ifdef FEATURE_COMINTEROP
745 m_pMngStdInterfacesInfo = NULL;
746 m_pWinRtBinder = NULL;
748 m_FileLoadLock.PreInit();
750 m_ClassInitLock.PreInit();
751 m_ILStubGenLock.PreInit();
753 #ifdef FEATURE_CODE_VERSIONING
754 m_codeVersionManager.PreInit(this == (BaseDomain *)g_pSharedDomainMemory);
757 } //BaseDomain::BaseDomain
759 //*****************************************************************************
760 void BaseDomain::Init()
767 INJECT_FAULT(COMPlusThrowOM(););
772 // Initialize the domain locks
775 if (this == reinterpret_cast<BaseDomain*>(&g_pSharedDomainMemory[0]))
776 m_DomainCrst.Init(CrstSharedBaseDomain);
777 else if (this == reinterpret_cast<BaseDomain*>(&g_pSystemDomainMemory[0]))
778 m_DomainCrst.Init(CrstSystemBaseDomain);
780 m_DomainCrst.Init(CrstBaseDomain);
782 m_DomainCacheCrst.Init(CrstAppDomainCache);
783 m_DomainLocalBlockCrst.Init(CrstDomainLocalBlock);
785 m_InteropDataCrst.Init(CrstInteropData, CRST_REENTRANCY);
787 m_WinRTFactoryCacheCrst.Init(CrstWinRTFactoryCache, CRST_UNSAFE_COOPGC);
789 // NOTE: CRST_UNSAFE_COOPGC prevents a GC mode switch to preemptive when entering this crst.
790 // If you remove this flag, we will switch to preemptive mode when entering
791 // m_FileLoadLock, which means all functions that enter it will become
792 // GC_TRIGGERS. (This includes all uses of PEFileListLockHolder, LoadLockHolder, etc.) So be sure
793 // to update the contracts if you remove this flag.
794 m_FileLoadLock.Init(CrstAssemblyLoader,
795 CrstFlags(CRST_HOST_BREAKABLE), TRUE);
798 // The JIT lock and the CCtor locks are at the same level (and marked as
799 // UNSAFE_SAME_LEVEL) because they are all part of the same deadlock detection mechanism. We
800 // see through cycles of JITting and .cctor execution and then explicitly allow the cycle to
801 // be broken by giving access to uninitialized classes. If there is no cycle or if the cycle
802 // involves other locks that arent part of this special deadlock-breaking semantics, then
803 // we continue to block.
805 m_JITLock.Init(CrstJit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
806 m_ClassInitLock.Init(CrstClassInit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
808 m_ILStubGenLock.Init(CrstILStubGen, CrstFlags(CRST_REENTRANCY), TRUE);
810 // Large heap handle table CRST.
811 m_LargeHeapHandleTableCrst.Init(CrstAppDomainHandleTable);
813 m_crstLoaderAllocatorReferences.Init(CrstLoaderAllocatorReferences);
814 // Has to switch thread to GC_NOTRIGGER while being held (see code:BaseDomain#AssemblyListLock)
815 m_crstAssemblyList.Init(CrstAssemblyList, CrstFlags(
816 CRST_GC_NOTRIGGER_WHEN_TAKEN | CRST_DEBUGGER_THREAD | CRST_TAKEN_DURING_SHUTDOWN));
818 // Initialize the EE marshaling data to NULL.
819 m_pMarshalingData = NULL;
821 #ifdef FEATURE_COMINTEROP
822 // Allocate the managed standard interfaces information.
823 m_pMngStdInterfacesInfo = new MngStdInterfacesInfo();
826 CLRPrivBinderWinRT::NamespaceResolutionKind fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_WindowsAPI;
827 if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_DesignerNamespaceResolutionEnabled) != FALSE)
829 fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_DesignerResolveEvent;
831 CLRPrivTypeCacheWinRT * pWinRtTypeCache = CLRPrivTypeCacheWinRT::GetOrCreateTypeCache();
832 m_pWinRtBinder = CLRPrivBinderWinRT::GetOrCreateBinder(pWinRtTypeCache, fNamespaceResolutionKind);
834 #endif // FEATURE_COMINTEROP
836 // Init the COM Interop data hash
838 LockOwner lock = {&m_InteropDataCrst, IsOwnerOfCrst};
839 m_interopDataHash.Init(0, NULL, false, &lock);
842 m_dwSizedRefHandles = 0;
843 if (!m_iNumberOfProcessors)
845 m_iNumberOfProcessors = GetCurrentProcessCpuCount();
849 #undef LOADERHEAP_PROFILE_COUNTER
851 #ifndef CROSSGEN_COMPILE
852 //*****************************************************************************
853 void BaseDomain::Terminate()
863 m_crstLoaderAllocatorReferences.Destroy();
864 m_DomainCrst.Destroy();
865 m_DomainCacheCrst.Destroy();
866 m_DomainLocalBlockCrst.Destroy();
867 m_InteropDataCrst.Destroy();
869 JitListLockEntry* pJitElement;
870 ListLockEntry* pElement;
872 // All the threads that are in this domain had better be stopped by this
875 // We might be jitting or running a .cctor so we need to empty that queue.
876 pJitElement = m_JITLock.Pop(TRUE);
879 #ifdef STRICT_JITLOCK_ENTRY_LEAK_DETECTION
880 _ASSERTE ((m_JITLock.m_pHead->m_dwRefCount == 1
881 && m_JITLock.m_pHead->m_hrResultCode == E_FAIL) ||
882 dbg_fDrasticShutdown || g_fInControlC);
883 #endif // STRICT_JITLOCK_ENTRY_LEAK_DETECTION
885 pJitElement = m_JITLock.Pop(TRUE);
890 pElement = m_ClassInitLock.Pop(TRUE);
893 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
894 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
897 pElement = m_ClassInitLock.Pop(TRUE);
899 m_ClassInitLock.Destroy();
901 FileLoadLock* pFileElement;
902 pFileElement = (FileLoadLock*) m_FileLoadLock.Pop(TRUE);
905 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
906 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
908 pFileElement->Release();
909 pFileElement = (FileLoadLock*) m_FileLoadLock.Pop(TRUE);
911 m_FileLoadLock.Destroy();
913 pElement = m_ILStubGenLock.Pop(TRUE);
916 #ifdef STRICT_JITLOCK_ENTRY_LEAK_DETECTION
917 _ASSERTE ((m_ILStubGenLock.m_pHead->m_dwRefCount == 1
918 && m_ILStubGenLock.m_pHead->m_hrResultCode == E_FAIL) ||
919 dbg_fDrasticShutdown || g_fInControlC);
920 #endif // STRICT_JITLOCK_ENTRY_LEAK_DETECTION
922 pElement = m_ILStubGenLock.Pop(TRUE);
924 m_ILStubGenLock.Destroy();
926 m_LargeHeapHandleTableCrst.Destroy();
928 if (m_pLargeHeapHandleTable != NULL)
930 delete m_pLargeHeapHandleTable;
931 m_pLargeHeapHandleTable = NULL;
936 // Kind of a workaround - during unloading, we need to have an EE halt
937 // around deleting this stuff. So it gets deleted in AppDomain::Terminate()
938 // for those things (because there is a convenient place there.)
939 GetLoaderAllocator()->CleanupStringLiteralMap();
942 #ifdef FEATURE_COMINTEROP
943 if (m_pMngStdInterfacesInfo)
945 delete m_pMngStdInterfacesInfo;
946 m_pMngStdInterfacesInfo = NULL;
949 if (m_pWinRtBinder != NULL)
951 m_pWinRtBinder->Release();
953 #endif // FEATURE_COMINTEROP
955 ClearFusionContext();
957 m_dwSizedRefHandles = 0;
959 #endif // CROSSGEN_COMPILE
961 void BaseDomain::InitVSD()
963 STANDARD_VM_CONTRACT;
965 // This is a workaround for gcc, since it fails to successfully resolve
966 // "TypeIDMap::STARTING_SHARED_DOMAIN_ID" when used within the ?: operator.
968 if (IsSharedDomain())
970 startingId = TypeIDMap::STARTING_SHARED_DOMAIN_ID;
974 startingId = TypeIDMap::STARTING_UNSHARED_DOMAIN_ID;
977 // By passing false as the last parameter, interfaces loaded in the
978 // shared domain will not be given fat type ids if RequiresFatDispatchTokens
979 // is set. This is correct, as the fat dispatch tokens are only needed to solve
980 // uniqueness problems involving domain specific types.
981 m_typeIDMap.Init(startingId, 2, !IsSharedDomain());
983 #ifndef CROSSGEN_COMPILE
984 GetLoaderAllocator()->InitVirtualCallStubManager(this);
988 #ifndef CROSSGEN_COMPILE
990 DWORD BaseDomain::AllocateContextStaticsOffset(DWORD* pOffsetSlot)
999 CrstHolder ch(&m_SpecialStaticsCrst);
1001 DWORD dwOffset = *pOffsetSlot;
1003 if (dwOffset == (DWORD)-1)
1005 // Allocate the slot
1006 dwOffset = m_dwContextStatics++;
1007 *pOffsetSlot = dwOffset;
1013 void BaseDomain::ClearFusionContext()
1023 if(m_pFusionContext) {
1024 m_pFusionContext->Release();
1025 m_pFusionContext = NULL;
1027 if (m_pTPABinderContext) {
1028 m_pTPABinderContext->Release();
1029 m_pTPABinderContext = NULL;
1033 #ifdef FEATURE_PREJIT
1034 void AppDomain::DeleteNativeCodeRanges()
1045 // Fast path to skip using the assembly iterator when the appdomain has not yet completely been initialized
1046 // and yet we are destroying it. (This is the case if we OOM during AppDomain creation.)
1047 if (m_Assemblies.IsEmpty())
1050 // Shutdown assemblies
1051 AssemblyIterator i = IterateAssembliesEx( (AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad) );
1052 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1054 while (i.Next(pDomainAssembly.This()))
1056 Assembly * assembly = pDomainAssembly->m_pAssembly;
1057 if ((assembly != NULL) && !assembly->IsDomainNeutral())
1058 assembly->DeleteNativeCodeRanges();
1063 void AppDomain::ShutdownAssemblies()
1073 // Fast path to skip using the assembly iterator when the appdomain has not yet completely been initialized
1074 // and yet we are destroying it. (This is the case if we OOM during AppDomain creation.)
1075 if (m_Assemblies.IsEmpty())
1078 // Shutdown assemblies
1079 // has two stages because Terminate needs info from the Assembly's dependencies
1081 // Stage 1: call code:Assembly::Terminate
1082 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
1083 kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
1084 DomainAssembly * pDomainAssembly = NULL;
1086 while (i.Next_UnsafeNoAddRef(&pDomainAssembly))
1088 // Note: cannot use DomainAssembly::GetAssembly() here as it asserts that the assembly has been
1089 // loaded to at least the FILE_LOAD_ALLOCATE level. Since domain shutdown can take place
1090 // asynchronously this property cannot be guaranteed. Access the m_pAssembly field directly instead.
1091 Assembly * assembly = pDomainAssembly->m_pAssembly;
1092 if (assembly && !assembly->IsDomainNeutral())
1093 assembly->Terminate();
1096 // Stage 2: Clear the list of assemblies
1097 i = IterateAssembliesEx((AssemblyIterationFlags)(
1098 kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
1099 while (i.Next_UnsafeNoAddRef(&pDomainAssembly))
1101 // We are in shutdown path, no one else can get to the list anymore
1102 delete pDomainAssembly;
1104 m_Assemblies.Clear(this);
1106 // Stage 2: Clear the loader allocators registered for deletion from code:Assembly:Terminate calls in
1108 // Note: It is not clear to me why we cannot delete the loader allocator from within
1109 // code:DomainAssembly::~DomainAssembly
1110 ShutdownFreeLoaderAllocators(FALSE);
1111 } // AppDomain::ShutdownAssemblies
1113 void AppDomain::ShutdownFreeLoaderAllocators(BOOL bFromManagedCode)
1115 // If we're called from managed code (i.e. the finalizer thread) we take a lock in
1116 // LoaderAllocator::CleanupFailedTypeInit, which may throw. Otherwise we're called
1117 // from the app-domain shutdown path in which we can avoid taking the lock.
1121 if (bFromManagedCode) THROWS; else NOTHROW;
1127 CrstHolder ch(GetLoaderAllocatorReferencesLock());
1129 // Shutdown the LoaderAllocators associated with collectible assemblies
1130 while (m_pDelayedLoaderAllocatorUnloadList != NULL)
1132 LoaderAllocator * pCurrentLoaderAllocator = m_pDelayedLoaderAllocatorUnloadList;
1133 // Remove next loader allocator from the list
1134 m_pDelayedLoaderAllocatorUnloadList = m_pDelayedLoaderAllocatorUnloadList->m_pLoaderAllocatorDestroyNext;
1136 if (bFromManagedCode)
1138 // For loader allocator finalization, we need to be careful about cleaning up per-appdomain allocations
1139 // and synchronizing with GC using delay unload list. We need to wait for next Gen2 GC to finish to ensure
1140 // that GC heap does not have any references to the MethodTables being unloaded.
1142 pCurrentLoaderAllocator->CleanupFailedTypeInit();
1144 pCurrentLoaderAllocator->CleanupHandles();
1147 SystemDomain::System()->AddToDelayedUnloadList(pCurrentLoaderAllocator);
1151 // For appdomain unload, delete the loader allocator right away
1152 delete pCurrentLoaderAllocator;
1155 } // AppDomain::ShutdownFreeLoaderAllocators
1157 //---------------------------------------------------------------------------------------
1159 // Register the loader allocator for deletion in code:AppDomain::ShutdownFreeLoaderAllocators.
1161 void AppDomain::RegisterLoaderAllocatorForDeletion(LoaderAllocator * pLoaderAllocator)
1172 CrstHolder ch(GetLoaderAllocatorReferencesLock());
1174 pLoaderAllocator->m_pLoaderAllocatorDestroyNext = m_pDelayedLoaderAllocatorUnloadList;
1175 m_pDelayedLoaderAllocatorUnloadList = pLoaderAllocator;
1178 void AppDomain::ShutdownNativeDllSearchDirectories()
1180 LIMITED_METHOD_CONTRACT;
1181 // Shutdown assemblies
1182 PathIterator i = IterateNativeDllSearchDirectories();
1189 m_NativeDllSearchDirectories.Clear();
1192 void AppDomain::ReleaseDomainBoundInfo()
1201 // Shutdown assemblies
1202 m_AssemblyCache.OnAppDomainUnload();
1204 AssemblyIterator i = IterateAssembliesEx( (AssemblyIterationFlags)(kIncludeFailedToLoad) );
1205 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1207 while (i.Next(pDomainAssembly.This()))
1209 pDomainAssembly->ReleaseManagedData();
1213 void AppDomain::ReleaseFiles()
1215 STANDARD_VM_CONTRACT;
1217 // Shutdown assemblies
1218 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
1219 kIncludeLoaded | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeLoading));
1220 CollectibleAssemblyHolder<DomainAssembly *> pAsm;
1222 while (i.Next(pAsm.This()))
1224 if (pAsm->GetCurrentAssembly() == NULL)
1226 // Might be domain neutral or not, but should have no live objects as it has not been
1227 // really loaded yet. Just reset it.
1228 _ASSERTE(FitsIn<DWORD>(i.GetIndex()));
1229 m_Assemblies.Set(this, static_cast<DWORD>(i.GetIndex()), NULL);
1230 delete pAsm.Extract();
1234 if (!pAsm->GetCurrentAssembly()->IsDomainNeutral())
1235 pAsm->ReleaseFiles();
1238 } // AppDomain::ReleaseFiles
1241 OBJECTREF* BaseDomain::AllocateObjRefPtrsInLargeTable(int nRequested, OBJECTREF** ppLazyAllocate, BOOL bCrossAD)
1248 PRECONDITION((nRequested > 0));
1249 INJECT_FAULT(COMPlusThrowOM(););
1253 if (ppLazyAllocate && *ppLazyAllocate)
1255 // Allocation already happened
1256 return *ppLazyAllocate;
1259 // Enter preemptive state, take the lock and go back to cooperative mode.
1261 CrstHolder ch(&m_LargeHeapHandleTableCrst);
1264 if (ppLazyAllocate && *ppLazyAllocate)
1266 // Allocation already happened
1267 return *ppLazyAllocate;
1270 // Make sure the large heap handle table is initialized.
1271 if (!m_pLargeHeapHandleTable)
1272 InitLargeHeapHandleTable();
1274 // Allocate the handles.
1275 OBJECTREF* result = m_pLargeHeapHandleTable->AllocateHandles(nRequested, bCrossAD);
1279 *ppLazyAllocate = result;
1285 #endif // CROSSGEN_COMPILE
1287 #endif // !DACCESS_COMPILE
1290 PTR_BaseDomain BaseDomain::ComputeBaseDomain(
1291 BaseDomain * pGenericDefinitionDomain, // the domain that owns the generic type or method
1292 Instantiation classInst, // the type arguments to the type (if any)
1293 Instantiation methodInst) // the type arguments to the method (if any)
1295 CONTRACT(PTR_BaseDomain)
1301 POSTCONDITION(CheckPointer(RETVAL));
1307 if (pGenericDefinitionDomain && pGenericDefinitionDomain->IsAppDomain())
1308 RETURN PTR_BaseDomain(pGenericDefinitionDomain);
1310 for (DWORD i = 0; i < classInst.GetNumArgs(); i++)
1312 PTR_BaseDomain pArgDomain = classInst[i].GetDomain();
1313 if (pArgDomain->IsAppDomain())
1317 for (DWORD i = 0; i < methodInst.GetNumArgs(); i++)
1319 PTR_BaseDomain pArgDomain = methodInst[i].GetDomain();
1320 if (pArgDomain->IsAppDomain())
1323 RETURN (pGenericDefinitionDomain ?
1324 PTR_BaseDomain(pGenericDefinitionDomain) :
1325 PTR_BaseDomain(SystemDomain::System()));
1328 PTR_BaseDomain BaseDomain::ComputeBaseDomain(TypeKey * pKey)
1340 if (pKey->GetKind() == ELEMENT_TYPE_CLASS)
1341 return BaseDomain::ComputeBaseDomain(pKey->GetModule()->GetDomain(),
1342 pKey->GetInstantiation());
1343 else if (pKey->GetKind() != ELEMENT_TYPE_FNPTR)
1344 return pKey->GetElementType().GetDomain();
1346 return BaseDomain::ComputeBaseDomain(NULL,Instantiation(pKey->GetRetAndArgTypes(), pKey->GetNumArgs()+1));
1353 #ifndef DACCESS_COMPILE
1355 // Insert class in the hash table
1356 void AppDomain::InsertClassForCLSID(MethodTable* pMT, BOOL fForceInsert /*=FALSE*/)
1363 INJECT_FAULT(COMPlusThrowOM(););
1369 // Ensure that registered classes are activated for allocation
1370 pMT->EnsureInstanceActive();
1372 // Note that it is possible for multiple classes to claim the same CLSID, and in such a
1373 // case it is arbitrary which one we will return for a future query for a given app domain.
1375 pMT->GetGuid(&cvid, fForceInsert);
1377 if (!IsEqualIID(cvid, GUID_NULL))
1379 //<TODO>@todo get a better key</TODO>
1380 LPVOID val = (LPVOID)pMT;
1382 LockHolder lh(this);
1384 if (LookupClass(cvid) != pMT)
1386 m_clsidHash.InsertValue(GetKeyFromGUID(&cvid), val);
1392 void AppDomain::InsertClassForCLSID(MethodTable* pMT, GUID *pGuid)
1397 PRECONDITION(CheckPointer(pMT));
1398 PRECONDITION(CheckPointer(pGuid));
1402 LPVOID val = (LPVOID)pMT;
1404 LockHolder lh(this);
1407 if (LookupClass(*cvid) != pMT)
1409 m_clsidHash.InsertValue(GetKeyFromGUID(pGuid), val);
1415 #endif // DACCESS_COMPILE
1417 #ifdef FEATURE_COMINTEROP
1419 #ifndef DACCESS_COMPILE
1420 void AppDomain::CacheTypeByName(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/)
1422 WRAPPER_NO_CONTRACT;
1423 LockHolder lh(this);
1424 CacheTypeByNameWorker(ssClassName, vCacheVersion, typeHandle, bFlags, bReplaceExisting);
1427 void AppDomain::CacheTypeByNameWorker(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/)
1433 PRECONDITION(!typeHandle.IsNull());
1437 NewArrayHolder<WCHAR> wzClassName(DuplicateStringThrowing(ssClassName.GetUnicode()));
1439 if (m_vNameToTypeMapVersion != vCacheVersion)
1442 if (m_pNameToTypeMap == nullptr)
1444 m_pNameToTypeMap = new NameToTypeMapTable();
1447 NameToTypeMapEntry e;
1448 e.m_key.m_wzName = wzClassName;
1449 e.m_key.m_cchName = ssClassName.GetCount();
1450 e.m_typeHandle = typeHandle;
1451 e.m_nEpoch = this->m_nEpoch;
1452 e.m_bFlags = bFlags;
1453 if (!bReplaceExisting)
1454 m_pNameToTypeMap->Add(e);
1456 m_pNameToTypeMap->AddOrReplace(e);
1458 wzClassName.SuppressRelease();
1460 #endif // DACCESS_COMPILE
1462 TypeHandle AppDomain::LookupTypeByName(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags)
1464 WRAPPER_NO_CONTRACT;
1465 LockHolder lh(this);
1466 return LookupTypeByNameWorker(ssClassName, pvCacheVersion, pbFlags);
1469 TypeHandle AppDomain::LookupTypeByNameWorker(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags)
1476 PRECONDITION(CheckPointer(pbFlags, NULL_OK));
1480 *pvCacheVersion = m_vNameToTypeMapVersion;
1482 if (m_pNameToTypeMap == nullptr)
1483 return TypeHandle(); // a null TypeHandle
1485 NameToTypeMapEntry::Key key;
1486 key.m_cchName = ssClassName.GetCount();
1487 key.m_wzName = ssClassName.GetUnicode();
1489 const NameToTypeMapEntry * pEntry = m_pNameToTypeMap->LookupPtr(key);
1491 return TypeHandle(); // a null TypeHandle
1493 if (pbFlags != NULL)
1494 *pbFlags = pEntry->m_bFlags;
1496 return pEntry->m_typeHandle;
1499 PTR_MethodTable AppDomain::LookupTypeByGuid(const GUID & guid)
1513 GuidToLPWSTR(guid, wszGuid, _countof(wszGuid));
1514 sGuid.Append(wszGuid);
1517 TypeHandle th = LookupTypeByName(sGuid, &ver, NULL);
1521 _ASSERTE(!th.IsTypeDesc());
1522 return th.AsMethodTable();
1525 #ifdef FEATURE_PREJIT
1528 // Next look in each ngen'ed image in turn
1529 AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)(
1530 kIncludeLoaded | kIncludeExecution));
1531 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1532 while (assemblyIterator.Next(pDomainAssembly.This()))
1534 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
1536 DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded);
1539 Module * pModule = i.GetLoadedModule();
1540 if (!pModule->HasNativeImage())
1542 _ASSERTE(!pModule->IsCollectible());
1543 PTR_MethodTable pMT = pModule->LookupTypeByGuid(guid);
1551 #endif // FEATURE_PREJIT
1555 #ifndef DACCESS_COMPILE
1556 void AppDomain::CacheWinRTTypeByGuid(TypeHandle typeHandle)
1563 PRECONDITION(!typeHandle.IsTypeDesc());
1564 PRECONDITION(CanCacheWinRTTypeByGuid(typeHandle));
1568 PTR_MethodTable pMT = typeHandle.AsMethodTable();
1571 if (pMT->GetGuidForWinRT(&guid))
1577 GuidToLPWSTR(guid, wszGuid, _countof(wszGuid));
1578 sGuid.Append(wszGuid);
1585 LockHolder lh(this);
1586 th = LookupTypeByNameWorker(sGuid, &vCacheVersion, &bFlags);
1590 // no other entry with the same GUID exists in the cache
1591 CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags);
1593 else if (typeHandle.AsMethodTable() != th.AsMethodTable() && th.IsProjectedFromWinRT())
1595 // If we found a native WinRT type cached with the same GUID, replace it.
1596 // Otherwise simply add the new mapping to the cache.
1597 CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags, TRUE);
1602 #endif // DACCESS_COMPILE
1604 void AppDomain::GetCachedWinRTTypes(
1605 SArray<PTR_MethodTable> * pTypes,
1606 SArray<GUID> * pGuids,
1619 LockHolder lh(this);
1621 for (auto it = m_pNameToTypeMap->Begin(), end = m_pNameToTypeMap->End();
1625 NameToTypeMapEntry entry = (NameToTypeMapEntry)(*it);
1626 TypeHandle th = entry.m_typeHandle;
1627 if (th.AsMethodTable() != NULL &&
1628 entry.m_key.m_wzName[0] == W('{') &&
1629 entry.m_nEpoch >= minEpoch)
1631 _ASSERTE(!th.IsTypeDesc());
1632 PTR_MethodTable pMT = th.AsMethodTable();
1633 // we're parsing the GUID value from the cache, because projected types do not cache the
1634 // COM GUID in their GetGuid() but rather the legacy GUID
1636 if (LPWSTRToGuid(&iid, entry.m_key.m_wzName, 38) && iid != GUID_NULL)
1638 pTypes->Append(pMT);
1639 pGuids->Append(iid);
1644 #ifdef FEATURE_PREJIT
1645 // Next look in each ngen'ed image in turn
1646 AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)(
1647 kIncludeLoaded | kIncludeExecution));
1648 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1649 while (assemblyIterator.Next(pDomainAssembly.This()))
1651 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
1653 DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded);
1656 Module * pModule = i.GetLoadedModule();
1657 if (!pModule->HasNativeImage())
1659 _ASSERTE(!pModule->IsCollectible());
1661 pModule->GetCachedWinRTTypes(pTypes, pGuids);
1664 #endif // FEATURE_PREJIT
1666 if (pCurEpoch != NULL)
1667 *pCurEpoch = m_nEpoch;
1671 #ifndef CROSSGEN_COMPILE
1672 #ifndef DACCESS_COMPILE
1674 void WinRTFactoryCacheTraits::OnDestructPerEntryCleanupAction(const WinRTFactoryCacheEntry& e)
1676 WRAPPER_NO_CONTRACT;
1677 if (e.m_pCtxEntry != NULL)
1679 e.m_pCtxEntry->Release();
1681 // the AD is going away, no need to destroy the OBJECTHANDLE
1684 void AppDomain::CacheWinRTFactoryObject(MethodTable *pClassMT, OBJECTREF *refFactory, LPVOID lpCtxCookie)
1691 PRECONDITION(CheckPointer(pClassMT));
1695 CtxEntryHolder pNewCtxEntry;
1696 if (lpCtxCookie != NULL)
1698 // We don't want to insert the context cookie in the cache because it's just an address
1699 // of an internal COM data structure which will be freed when the apartment is torn down.
1700 // What's worse, if another apartment is later created, its context cookie may have exactly
1701 // the same value leading to incorrect cache hits. We'll use our CtxEntry instead which
1702 // is ref-counted and keeps the COM data structure alive even after the apartment ceases
1704 pNewCtxEntry = CtxEntryCache::GetCtxEntryCache()->FindCtxEntry(lpCtxCookie, GetThread());
1707 WinRTFactoryCacheLockHolder lh(this);
1709 if (m_pWinRTFactoryCache == nullptr)
1711 m_pWinRTFactoryCache = new WinRTFactoryCache();
1714 WinRTFactoryCacheEntry *pEntry = const_cast<WinRTFactoryCacheEntry*>(m_pWinRTFactoryCache->LookupPtr(pClassMT));
1718 // No existing entry for this cache
1721 WinRTFactoryCacheEntry e;
1723 OBJECTHANDLEHolder ohNewHandle(CreateHandle(*refFactory));
1726 e.m_pCtxEntry = pNewCtxEntry;
1727 e.m_ohFactoryObject = ohNewHandle;
1729 m_pWinRTFactoryCache->Add(e);
1731 // suppress release of the CtxEntry and handle after we successfully inserted the new entry
1732 pNewCtxEntry.SuppressRelease();
1733 ohNewHandle.SuppressRelease();
1740 // release the old CtxEntry and update the entry
1741 CtxEntry *pTemp = pNewCtxEntry.Extract();
1742 pNewCtxEntry = pEntry->m_pCtxEntry;
1743 pEntry->m_pCtxEntry = pTemp;
1745 IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
1746 mgr->StoreObjectInHandle(pEntry->m_ohFactoryObject, OBJECTREFToObject(*refFactory));
1750 OBJECTREF AppDomain::LookupWinRTFactoryObject(MethodTable *pClassMT, LPVOID lpCtxCookie)
1757 PRECONDITION(CheckPointer(pClassMT));
1758 PRECONDITION(CheckPointer(m_pWinRTFactoryCache, NULL_OK));
1763 if (m_pWinRTFactoryCache == nullptr)
1767 // Retrieve cached factory
1769 WinRTFactoryCacheLockHolder lh(this);
1771 const WinRTFactoryCacheEntry *pEntry = m_pWinRTFactoryCache->LookupPtr(pClassMT);
1776 // Ignore factories from a different context, unless lpCtxCookie == NULL,
1777 // which means the factory is free-threaded
1778 // Note that we cannot touch the RCW to retrieve cookie at this point
1779 // because the RCW might belong to a STA thread and that STA thread might die
1780 // and take the RCW with it. Therefore we have to save cookie in this cache
1782 if (pEntry->m_pCtxEntry == NULL || pEntry->m_pCtxEntry->GetCtxCookie() == lpCtxCookie)
1783 return ObjectFromHandle(pEntry->m_ohFactoryObject);
1788 void AppDomain::RemoveWinRTFactoryObjects(LPVOID pCtxCookie)
1798 if (m_pWinRTFactoryCache == nullptr)
1801 // helper class for delayed CtxEntry cleanup
1802 class CtxEntryListReleaseHolder
1805 CQuickArrayList<CtxEntry *> m_list;
1807 ~CtxEntryListReleaseHolder()
1817 for (SIZE_T i = 0; i < m_list.Size(); i++)
1819 m_list[i]->Release();
1822 } ctxEntryListReleaseHolder;
1826 WinRTFactoryCacheLockHolder lh(this);
1828 // Go through the hash table and remove items in the given context
1829 for (WinRTFactoryCache::Iterator it = m_pWinRTFactoryCache->Begin(); it != m_pWinRTFactoryCache->End(); it++)
1831 if (it->m_pCtxEntry != NULL && it->m_pCtxEntry->GetCtxCookie() == pCtxCookie)
1833 // Releasing the CtxEntry may trigger GC which we can't do under the lock so we push
1834 // it on our local list and release them all after we're done iterating the hashtable.
1835 ctxEntryListReleaseHolder.m_list.Push(it->m_pCtxEntry);
1837 DestroyHandle(it->m_ohFactoryObject);
1838 m_pWinRTFactoryCache->Remove(it);
1844 OBJECTREF AppDomain::GetMissingObject()
1857 FieldDesc *pValueFD = MscorlibBinder::GetField(FIELD__MISSING__VALUE);
1859 pValueFD->CheckRunClassInitThrowing();
1861 // Retrieve the value static field and store it.
1862 OBJECTHANDLE hndMissing = CreateHandle(pValueFD->GetStaticOBJECTREF());
1864 if (FastInterlockCompareExchangePointer(&m_hndMissing, hndMissing, NULL) != NULL)
1866 // Exchanged failed. The m_hndMissing did not equal NULL and was returned.
1867 DestroyHandle(hndMissing);
1871 return ObjectFromHandle(m_hndMissing);
1874 #endif // DACCESS_COMPILE
1875 #endif //CROSSGEN_COMPILE
1876 #endif // FEATURE_COMINTEROP
1878 #ifndef DACCESS_COMPILE
1880 EEMarshalingData *BaseDomain::GetMarshalingData()
1882 CONTRACT (EEMarshalingData*)
1887 INJECT_FAULT(COMPlusThrowOM());
1888 POSTCONDITION(CheckPointer(m_pMarshalingData));
1892 if (!m_pMarshalingData)
1895 CrstHolder holder(&m_InteropDataCrst);
1897 if (!m_pMarshalingData)
1899 LoaderHeap* pHeap = GetLoaderAllocator()->GetLowFrequencyHeap();
1900 m_pMarshalingData = new (pHeap) EEMarshalingData(this, pHeap, &m_DomainCrst);
1904 RETURN m_pMarshalingData;
1907 void BaseDomain::DeleteMarshalingData()
1917 // We are in shutdown - no need to take any lock
1918 if (m_pMarshalingData)
1920 delete m_pMarshalingData;
1921 m_pMarshalingData = NULL;
1925 #ifndef CROSSGEN_COMPILE
1927 STRINGREF *BaseDomain::IsStringInterned(STRINGREF *pString)
1934 PRECONDITION(CheckPointer(pString));
1935 INJECT_FAULT(COMPlusThrowOM(););
1939 return GetLoaderAllocator()->IsStringInterned(pString);
1942 STRINGREF *BaseDomain::GetOrInternString(STRINGREF *pString)
1949 PRECONDITION(CheckPointer(pString));
1950 INJECT_FAULT(COMPlusThrowOM(););
1954 return GetLoaderAllocator()->GetOrInternString(pString);
1957 void BaseDomain::InitLargeHeapHandleTable()
1964 PRECONDITION(m_pLargeHeapHandleTable==NULL);
1965 INJECT_FAULT(COMPlusThrowOM(););
1969 m_pLargeHeapHandleTable = new LargeHeapHandleTable(this, STATIC_OBJECT_TABLE_BUCKET_SIZE);
1972 m_pLargeHeapHandleTable->RegisterCrstDebug(&m_LargeHeapHandleTableCrst);
1976 #ifdef FEATURE_COMINTEROP
1977 MethodTable* AppDomain::GetLicenseInteropHelperMethodTable()
1986 if(m_pLicenseInteropHelperMT == NULL)
1988 // Do this work outside of the lock so we don't have an unbreakable lock condition
1990 TypeHandle licenseMgrTypeHnd;
1991 MethodDescCallSite loadLM(METHOD__MARSHAL__LOAD_LICENSE_MANAGER);
1993 licenseMgrTypeHnd = (MethodTable*) loadLM.Call_RetLPVOID((ARG_SLOT*)NULL);
1996 // Look up this method by name, because the type is actually declared in System.dll. <TODO>@todo: why?</TODO>
1999 MethodDesc *pGetLIHMD = MemberLoader::FindMethod(licenseMgrTypeHnd.AsMethodTable(),
2000 "GetLicenseInteropHelperType", &gsig_SM_Void_RetIntPtr);
2001 _ASSERTE(pGetLIHMD);
2003 TypeHandle lihTypeHnd;
2005 MethodDescCallSite getLIH(pGetLIHMD);
2006 lihTypeHnd = (MethodTable*) getLIH.Call_RetLPVOID((ARG_SLOT*)NULL);
2008 BaseDomain::LockHolder lh(this);
2010 if(m_pLicenseInteropHelperMT == NULL)
2011 m_pLicenseInteropHelperMT = lihTypeHnd.AsMethodTable();
2013 return m_pLicenseInteropHelperMT;
2016 COMorRemotingFlag AppDomain::GetComOrRemotingFlag()
2026 // 0. check if the value is already been set
2027 if (m_COMorRemotingFlag != COMorRemoting_NotInitialized)
2028 return m_COMorRemotingFlag;
2030 // 1. check whether the process is AppX
2031 if (AppX::IsAppXProcess())
2033 // do not use Remoting in AppX
2034 m_COMorRemotingFlag = COMorRemoting_COM;
2035 return m_COMorRemotingFlag;
2038 // 2. check the xml file
2039 m_COMorRemotingFlag = GetPreferComInsteadOfManagedRemotingFromConfigFile();
2040 if (m_COMorRemotingFlag != COMorRemoting_NotInitialized)
2042 return m_COMorRemotingFlag;
2045 // 3. check the global setting
2046 if (NULL != g_pConfig && g_pConfig->ComInsteadOfManagedRemoting())
2048 m_COMorRemotingFlag = COMorRemoting_COM;
2052 m_COMorRemotingFlag = COMorRemoting_Remoting;
2055 return m_COMorRemotingFlag;
2058 BOOL AppDomain::GetPreferComInsteadOfManagedRemoting()
2060 WRAPPER_NO_CONTRACT;
2062 return (GetComOrRemotingFlag() == COMorRemoting_COM);
2065 STDAPI GetXMLObjectEx(IXMLParser **ppv);
2067 COMorRemotingFlag AppDomain::GetPreferComInsteadOfManagedRemotingFromConfigFile()
2077 return COMorRemoting_COM;
2079 #endif // FEATURE_COMINTEROP
2081 #endif // CROSSGEN_COMPILE
2083 //*****************************************************************************
2084 //*****************************************************************************
2085 //*****************************************************************************
2087 void *SystemDomain::operator new(size_t size, void *pInPlace)
2089 LIMITED_METHOD_CONTRACT;
2094 void SystemDomain::operator delete(void *pMem)
2096 LIMITED_METHOD_CONTRACT;
2097 // Do nothing - new() was in-place
2101 void SystemDomain::SetCompilationOverrides(BOOL fForceDebug,
2102 BOOL fForceProfiling,
2103 BOOL fForceInstrument)
2105 LIMITED_METHOD_CONTRACT;
2106 s_fForceDebug = fForceDebug;
2107 s_fForceProfiling = fForceProfiling;
2108 s_fForceInstrument = fForceInstrument;
2111 #endif //!DACCESS_COMPILE
2113 void SystemDomain::GetCompilationOverrides(BOOL * fForceDebug,
2114 BOOL * fForceProfiling,
2115 BOOL * fForceInstrument)
2117 LIMITED_METHOD_DAC_CONTRACT;
2118 *fForceDebug = s_fForceDebug;
2119 *fForceProfiling = s_fForceProfiling;
2120 *fForceInstrument = s_fForceInstrument;
2123 #ifndef DACCESS_COMPILE
2125 void SystemDomain::Attach()
2132 PRECONDITION(m_pSystemDomain == NULL);
2133 INJECT_FAULT(COMPlusThrowOM(););
2137 #ifndef CROSSGEN_COMPILE
2138 // Initialize stub managers
2139 PrecodeStubManager::Init();
2140 DelegateInvokeStubManager::Init();
2141 JumpStubStubManager::Init();
2142 RangeSectionStubManager::Init();
2143 ILStubManager::Init();
2144 InteropDispatchStubManager::Init();
2145 StubLinkStubManager::Init();
2147 ThunkHeapStubManager::Init();
2149 TailCallStubManager::Init();
2151 PerAppDomainTPCountList::InitAppDomainIndexList();
2152 #endif // CROSSGEN_COMPILE
2154 m_appDomainIndexList.Init();
2155 m_appDomainIdList.Init();
2157 m_SystemDomainCrst.Init(CrstSystemDomain, (CrstFlags)(CRST_REENTRANCY | CRST_TAKEN_DURING_SHUTDOWN));
2158 m_DelayedUnloadCrst.Init(CrstSystemDomainDelayedUnloadList, CRST_UNSAFE_COOPGC);
2160 // Initialize the ID dispenser that is used for domain neutral module IDs
2161 g_pModuleIndexDispenser = new IdDispenser();
2163 // Create the global SystemDomain and initialize it.
2164 m_pSystemDomain = new (&g_pSystemDomainMemory[0]) SystemDomain();
2165 // No way it can fail since g_pSystemDomainMemory is a static array.
2166 CONSISTENCY_CHECK(CheckPointer(m_pSystemDomain));
2168 LOG((LF_CLASSLOADER,
2170 "Created system domain at %p\n",
2173 // We need to initialize the memory pools etc. for the system domain.
2174 m_pSystemDomain->BaseDomain::Init(); // Setup the memory heaps
2176 // Create the default domain
2177 m_pSystemDomain->CreateDefaultDomain();
2178 SharedDomain::Attach();
2180 // Each domain gets its own ReJitManager, and ReJitManager has its own static
2181 // initialization to run
2182 ReJitManager::InitStatic();
2185 #ifndef CROSSGEN_COMPILE
2187 void SystemDomain::DetachBegin()
2189 WRAPPER_NO_CONTRACT;
2190 // Shut down the domain and its children (but don't deallocate anything just
2193 // TODO: we should really not running managed DLLMain during process detach.
2194 if (GetThread() == NULL)
2200 m_pSystemDomain->Stop();
2203 void SystemDomain::DetachEnd()
2212 // Shut down the domain and its children (but don't deallocate anything just
2217 m_pSystemDomain->ClearFusionContext();
2218 if (m_pSystemDomain->m_pDefaultDomain)
2219 m_pSystemDomain->m_pDefaultDomain->ClearFusionContext();
2223 void SystemDomain::Stop()
2225 WRAPPER_NO_CONTRACT;
2226 AppDomainIterator i(TRUE);
2229 if (i.GetDomain()->m_Stage < AppDomain::STAGE_CLEARED)
2230 i.GetDomain()->Stop();
2234 void SystemDomain::Terminate() // bNotifyProfiler is ignored
2244 // This ignores the refences and terminates the appdomains
2245 AppDomainIterator i(FALSE);
2249 delete i.GetDomain();
2250 // Keep the iterator from Releasing the current domain
2251 i.m_pCurrent = NULL;
2254 if (m_pSystemFile != NULL) {
2255 m_pSystemFile->Release();
2256 m_pSystemFile = NULL;
2259 m_pSystemAssembly = NULL;
2262 delete[] m_pwDevpath;
2268 if (m_pGlobalStringLiteralMap) {
2269 delete m_pGlobalStringLiteralMap;
2270 m_pGlobalStringLiteralMap = NULL;
2274 SharedDomain::Detach();
2276 BaseDomain::Terminate();
2278 #ifdef FEATURE_COMINTEROP
2279 if (g_pRCWCleanupList != NULL)
2280 delete g_pRCWCleanupList;
2281 #endif // FEATURE_COMINTEROP
2282 m_GlobalAllocator.Terminate();
2286 void SystemDomain::PreallocateSpecialObjects()
2293 INJECT_FAULT(COMPlusThrowOM(););
2297 _ASSERTE(g_pPreallocatedSentinelObject == NULL);
2299 OBJECTREF pPreallocatedSentinalObject = AllocateObject(g_pObjectClass);
2300 #if CHECK_APP_DOMAIN_LEAKS
2301 pPreallocatedSentinalObject->SetSyncBlockAppDomainAgile();
2303 g_pPreallocatedSentinelObject = CreatePinningHandle( pPreallocatedSentinalObject );
2305 #ifdef FEATURE_PREJIT
2306 if (SystemModule()->HasNativeImage())
2308 CORCOMPILE_EE_INFO_TABLE *pEEInfo = SystemModule()->GetNativeImage()->GetNativeEEInfoTable();
2309 pEEInfo->emptyString = (CORINFO_Object **)StringObject::GetEmptyStringRefPtr();
2314 void SystemDomain::CreatePreallocatedExceptions()
2321 INJECT_FAULT(COMPlusThrowOM(););
2325 EXCEPTIONREF pBaseException = (EXCEPTIONREF)AllocateObject(g_pExceptionClass);
2326 pBaseException->SetHResult(COR_E_EXCEPTION);
2327 pBaseException->SetXCode(EXCEPTION_COMPLUS);
2328 _ASSERTE(g_pPreallocatedBaseException == NULL);
2329 g_pPreallocatedBaseException = CreateHandle(pBaseException);
2332 EXCEPTIONREF pOutOfMemory = (EXCEPTIONREF)AllocateObject(g_pOutOfMemoryExceptionClass);
2333 pOutOfMemory->SetHResult(COR_E_OUTOFMEMORY);
2334 pOutOfMemory->SetXCode(EXCEPTION_COMPLUS);
2335 _ASSERTE(g_pPreallocatedOutOfMemoryException == NULL);
2336 g_pPreallocatedOutOfMemoryException = CreateHandle(pOutOfMemory);
2339 EXCEPTIONREF pStackOverflow = (EXCEPTIONREF)AllocateObject(g_pStackOverflowExceptionClass);
2340 pStackOverflow->SetHResult(COR_E_STACKOVERFLOW);
2341 pStackOverflow->SetXCode(EXCEPTION_COMPLUS);
2342 _ASSERTE(g_pPreallocatedStackOverflowException == NULL);
2343 g_pPreallocatedStackOverflowException = CreateHandle(pStackOverflow);
2346 EXCEPTIONREF pExecutionEngine = (EXCEPTIONREF)AllocateObject(g_pExecutionEngineExceptionClass);
2347 pExecutionEngine->SetHResult(COR_E_EXECUTIONENGINE);
2348 pExecutionEngine->SetXCode(EXCEPTION_COMPLUS);
2349 _ASSERTE(g_pPreallocatedExecutionEngineException == NULL);
2350 g_pPreallocatedExecutionEngineException = CreateHandle(pExecutionEngine);
2353 EXCEPTIONREF pRudeAbortException = (EXCEPTIONREF)AllocateObject(g_pThreadAbortExceptionClass);
2354 #if CHECK_APP_DOMAIN_LEAKS
2355 pRudeAbortException->SetSyncBlockAppDomainAgile();
2357 pRudeAbortException->SetHResult(COR_E_THREADABORTED);
2358 pRudeAbortException->SetXCode(EXCEPTION_COMPLUS);
2359 _ASSERTE(g_pPreallocatedRudeThreadAbortException == NULL);
2360 g_pPreallocatedRudeThreadAbortException = CreateHandle(pRudeAbortException);
2363 EXCEPTIONREF pAbortException = (EXCEPTIONREF)AllocateObject(g_pThreadAbortExceptionClass);
2364 #if CHECK_APP_DOMAIN_LEAKS
2365 pAbortException->SetSyncBlockAppDomainAgile();
2367 pAbortException->SetHResult(COR_E_THREADABORTED);
2368 pAbortException->SetXCode(EXCEPTION_COMPLUS);
2369 _ASSERTE(g_pPreallocatedThreadAbortException == NULL);
2370 g_pPreallocatedThreadAbortException = CreateHandle( pAbortException );
2372 #endif // CROSSGEN_COMPILE
2374 void SystemDomain::Init()
2376 STANDARD_VM_CONTRACT;
2384 "sizeof(EEClass) = %d\n"
2385 "sizeof(MethodTable) = %d\n"
2386 "sizeof(MethodDesc)= %d\n"
2387 "sizeof(FieldDesc) = %d\n"
2388 "sizeof(Module) = %d\n",
2390 sizeof(MethodTable),
2397 // The base domain is initialized in SystemDomain::Attach()
2398 // to allow stub caches to use the memory pool. Do not
2399 // initialze it here!
2401 #ifndef CROSSGEN_COMPILE
2403 Context *curCtx = GetCurrentContext();
2406 _ASSERTE(curCtx->GetDomain() != NULL);
2409 #ifdef FEATURE_PREJIT
2410 if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_ZapDisable) != 0)
2411 g_fAllowNativeImages = false;
2414 m_pSystemFile = NULL;
2415 m_pSystemAssembly = NULL;
2420 // Get the install directory so we can find mscorlib
2421 hr = GetInternalSystemDirectory(NULL, &size);
2422 if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
2425 // GetInternalSystemDirectory returns a size, including the null!
2426 WCHAR *buffer = m_SystemDirectory.OpenUnicodeBuffer(size-1);
2427 IfFailThrow(GetInternalSystemDirectory(buffer, &size));
2428 m_SystemDirectory.CloseBuffer();
2429 m_SystemDirectory.Normalize();
2431 // At this point m_SystemDirectory should already be canonicalized
2434 m_BaseLibrary.Append(m_SystemDirectory);
2435 if (!m_BaseLibrary.EndsWith(DIRECTORY_SEPARATOR_CHAR_W))
2437 m_BaseLibrary.Append(DIRECTORY_SEPARATOR_CHAR_W);
2439 m_BaseLibrary.Append(g_pwBaseLibrary);
2440 m_BaseLibrary.Normalize();
2442 LoadBaseSystemClasses();
2445 // We are about to start allocating objects, so we must be in cooperative mode.
2446 // However, many of the entrypoints to the system (DllGetClassObject and all
2447 // N/Direct exports) get called multiple times. Sometimes they initialize the EE,
2448 // but generally they remain in preemptive mode. So we really want to push/pop
2452 #ifndef CROSSGEN_COMPILE
2453 if (!NingenEnabled())
2455 CreatePreallocatedExceptions();
2457 PreallocateSpecialObjects();
2461 // Finish loading mscorlib now.
2462 m_pSystemAssembly->GetDomainAssembly()->EnsureActive();
2466 BOOL fPause = EEConfig::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_PauseOnLoad, FALSE);
2470 ClrSleepEx(20, TRUE);
2475 #ifndef CROSSGEN_COMPILE
2476 void SystemDomain::LazyInitGlobalStringLiteralMap()
2483 INJECT_FAULT(COMPlusThrowOM(););
2487 // Allocate the global string literal map.
2488 NewHolder<GlobalStringLiteralMap> pGlobalStringLiteralMap(new GlobalStringLiteralMap());
2490 // Initialize the global string literal map.
2491 pGlobalStringLiteralMap->Init();
2493 if (InterlockedCompareExchangeT<GlobalStringLiteralMap *>(&m_pGlobalStringLiteralMap, pGlobalStringLiteralMap, NULL) == NULL)
2495 pGlobalStringLiteralMap.SuppressRelease();
2499 void AppDomain::CreateADUnloadStartEvent()
2510 g_pUnloadStartEvent = new CLREvent();
2511 g_pUnloadStartEvent->CreateAutoEvent(FALSE);
2514 /*static*/ void SystemDomain::EnumAllStaticGCRefs(promote_func* fn, ScanContext* sc)
2524 // We don't do a normal AppDomainIterator because we can't take the SystemDomain lock from
2526 // We're only supposed to call this from a Server GC. We're walking here m_appDomainIdList
2527 // m_appDomainIdList will have an AppDomain* or will be NULL. So the only danger is if we
2528 // Fetch an AppDomain and then in some other thread the AppDomain is deleted.
2530 // If the thread deleting the AppDomain (AppDomain::~AppDomain)was in Preemptive mode
2531 // while doing SystemDomain::EnumAllStaticGCRefs we will issue a GCX_COOP(), which will wait
2532 // for the GC to finish, so we are safe
2534 // If the thread is in cooperative mode, it must have been suspended for the GC so a delete
2537 _ASSERTE(GCHeapUtilities::IsGCInProgress() &&
2538 GCHeapUtilities::IsServerHeap() &&
2539 IsGCSpecialThread());
2541 SystemDomain* sysDomain = SystemDomain::System();
2545 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2546 for (i = 0 ; i < count ; i++)
2548 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2549 if (pAppDomain && pAppDomain->IsActive() && !pAppDomain->IsUnloading())
2551 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
2554 sc->pCurrentDomain = pAppDomain;
2556 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
2557 pAppDomain->EnumStaticGCRefs(fn, sc);
2565 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
2566 void SystemDomain::ResetADSurvivedBytes()
2576 _ASSERTE(GCHeapUtilities::IsGCInProgress());
2578 SystemDomain* sysDomain = SystemDomain::System();
2582 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2583 for (i = 0 ; i < count ; i++)
2585 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2586 if (pAppDomain && pAppDomain->IsUserActive())
2588 pAppDomain->ResetSurvivedBytes();
2596 ULONGLONG SystemDomain::GetADSurvivedBytes()
2606 SystemDomain* sysDomain = SystemDomain::System();
2607 ULONGLONG ullTotalADSurvived = 0;
2611 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2612 for (i = 0 ; i < count ; i++)
2614 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2615 if (pAppDomain && pAppDomain->IsUserActive())
2617 ULONGLONG ullSurvived = pAppDomain->GetSurvivedBytes();
2618 ullTotalADSurvived += ullSurvived;
2623 return ullTotalADSurvived;
2626 void SystemDomain::RecordTotalSurvivedBytes(size_t totalSurvivedBytes)
2636 m_totalSurvivedBytes = totalSurvivedBytes;
2638 SystemDomain* sysDomain = SystemDomain::System();
2642 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2643 for (i = 0 ; i < count ; i++)
2645 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2646 if (pAppDomain && pAppDomain->IsUserActive())
2648 FireEtwAppDomainMemSurvived((ULONGLONG)pAppDomain, pAppDomain->GetSurvivedBytes(), totalSurvivedBytes, GetClrInstanceId());
2655 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
2657 // Only called when EE is suspended.
2658 DWORD SystemDomain::GetTotalNumSizedRefHandles()
2668 SystemDomain* sysDomain = SystemDomain::System();
2669 DWORD dwTotalNumSizedRefHandles = 0;
2673 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2674 for (i = 0 ; i < count ; i++)
2676 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2677 if (pAppDomain && pAppDomain->IsActive() && !pAppDomain->IsUnloading())
2679 dwTotalNumSizedRefHandles += pAppDomain->GetNumSizedRefHandles();
2684 return dwTotalNumSizedRefHandles;
2686 #endif // CROSSGEN_COMPILE
2688 void SystemDomain::LoadBaseSystemClasses()
2690 STANDARD_VM_CONTRACT;
2692 ETWOnStartup(LdSysBases_V1, LdSysBasesEnd_V1);
2695 m_pSystemFile = PEAssembly::OpenSystem(NULL);
2697 // Only partially load the system assembly. Other parts of the code will want to access
2698 // the globals in this function before finishing the load.
2699 m_pSystemAssembly = DefaultDomain()->LoadDomainAssembly(NULL, m_pSystemFile, FILE_LOAD_POST_LOADLIBRARY)->GetCurrentAssembly();
2701 // Set up binder for mscorlib
2702 MscorlibBinder::AttachModule(m_pSystemAssembly->GetManifestModule());
2705 g_pObjectClass = MscorlibBinder::GetClass(CLASS__OBJECT);
2707 // Now that ObjectClass is loaded, we can set up
2708 // the system for finalizers. There is no point in deferring this, since we need
2709 // to know this before we allocate our first object.
2710 g_pObjectFinalizerMD = MscorlibBinder::GetMethod(METHOD__OBJECT__FINALIZE);
2713 g_pCanonMethodTableClass = MscorlibBinder::GetClass(CLASS____CANON);
2715 // NOTE: !!!IMPORTANT!!! ValueType and Enum MUST be loaded one immediately after
2716 // the other, because we have coded MethodTable::IsChildValueType
2717 // in such a way that it depends on this behaviour.
2718 // Load the ValueType class
2719 g_pValueTypeClass = MscorlibBinder::GetClass(CLASS__VALUE_TYPE);
2721 // Load the enum class
2722 g_pEnumClass = MscorlibBinder::GetClass(CLASS__ENUM);
2723 _ASSERTE(!g_pEnumClass->IsValueType());
2725 // Load System.RuntimeType
2726 g_pRuntimeTypeClass = MscorlibBinder::GetClass(CLASS__CLASS);
2727 _ASSERTE(g_pRuntimeTypeClass->IsFullyLoaded());
2730 g_pArrayClass = MscorlibBinder::GetClass(CLASS__ARRAY);
2732 // Calling a method on IList<T> for an array requires redirection to a method on
2733 // the SZArrayHelper class. Retrieving such methods means calling
2734 // GetActualImplementationForArrayGenericIListMethod, which calls FetchMethod for
2735 // the corresponding method on SZArrayHelper. This basically results in a class
2736 // load due to a method call, which the debugger cannot handle, so we pre-load
2737 // the SZArrayHelper class here.
2738 g_pSZArrayHelperClass = MscorlibBinder::GetClass(CLASS__SZARRAYHELPER);
2740 // Load ByReference class
2742 // NOTE: ByReference<T> must be the first by-ref-like system type to be loaded,
2743 // because MethodTable::ClassifyEightBytesWithManagedLayout depends on it.
2744 g_pByReferenceClass = MscorlibBinder::GetClass(CLASS__BYREFERENCE);
2746 // Load Nullable class
2747 g_pNullableClass = MscorlibBinder::GetClass(CLASS__NULLABLE);
2749 // Load the Object array class.
2750 g_pPredefinedArrayTypes[ELEMENT_TYPE_OBJECT] = ClassLoader::LoadArrayTypeThrowing(TypeHandle(g_pObjectClass)).AsArray();
2752 // We have delayed allocation of mscorlib's static handles until we load the object class
2753 MscorlibBinder::GetModule()->AllocateRegularStaticHandles(DefaultDomain());
2755 g_TypedReferenceMT = MscorlibBinder::GetClass(CLASS__TYPED_REFERENCE);
2757 // Make sure all primitive types are loaded
2758 for (int et = ELEMENT_TYPE_VOID; et <= ELEMENT_TYPE_R8; et++)
2759 MscorlibBinder::LoadPrimitiveType((CorElementType)et);
2761 MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_I);
2762 MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_U);
2764 // unfortunately, the following cannot be delay loaded since the jit
2765 // uses it to compute method attributes within a function that cannot
2766 // handle Complus exception and the following call goes through a path
2767 // where a complus exception can be thrown. It is unfortunate, because
2768 // we know that the delegate class and multidelegate class are always
2769 // guaranteed to be found.
2770 g_pDelegateClass = MscorlibBinder::GetClass(CLASS__DELEGATE);
2771 g_pMulticastDelegateClass = MscorlibBinder::GetClass(CLASS__MULTICAST_DELEGATE);
2773 // used by IsImplicitInterfaceOfSZArray
2774 MscorlibBinder::GetClass(CLASS__IENUMERABLEGENERIC);
2775 MscorlibBinder::GetClass(CLASS__ICOLLECTIONGENERIC);
2776 MscorlibBinder::GetClass(CLASS__ILISTGENERIC);
2777 MscorlibBinder::GetClass(CLASS__IREADONLYCOLLECTIONGENERIC);
2778 MscorlibBinder::GetClass(CLASS__IREADONLYLISTGENERIC);
2781 g_pStringClass = MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_STRING);
2782 _ASSERTE(g_pStringClass->GetBaseSize() == ObjSizeOf(StringObject)+sizeof(WCHAR));
2783 _ASSERTE(g_pStringClass->GetComponentSize() == 2);
2785 // Used by Buffer::BlockCopy
2786 g_pByteArrayMT = ClassLoader::LoadArrayTypeThrowing(
2787 TypeHandle(MscorlibBinder::GetElementType(ELEMENT_TYPE_U1))).AsArray()->GetMethodTable();
2789 #ifndef CROSSGEN_COMPILE
2790 ECall::PopulateManagedStringConstructors();
2791 #endif // CROSSGEN_COMPILE
2793 g_pExceptionClass = MscorlibBinder::GetClass(CLASS__EXCEPTION);
2794 g_pOutOfMemoryExceptionClass = MscorlibBinder::GetException(kOutOfMemoryException);
2795 g_pStackOverflowExceptionClass = MscorlibBinder::GetException(kStackOverflowException);
2796 g_pExecutionEngineExceptionClass = MscorlibBinder::GetException(kExecutionEngineException);
2797 g_pThreadAbortExceptionClass = MscorlibBinder::GetException(kThreadAbortException);
2800 // used by gc to handle predefined agility checking
2801 g_pThreadClass = MscorlibBinder::GetClass(CLASS__THREAD);
2803 #ifdef FEATURE_COMINTEROP
2804 g_pBaseCOMObject = MscorlibBinder::GetClass(CLASS__COM_OBJECT);
2805 g_pBaseRuntimeClass = MscorlibBinder::GetClass(CLASS__RUNTIME_CLASS);
2807 MscorlibBinder::GetClass(CLASS__IDICTIONARYGENERIC);
2808 MscorlibBinder::GetClass(CLASS__IREADONLYDICTIONARYGENERIC);
2809 MscorlibBinder::GetClass(CLASS__ATTRIBUTE);
2810 MscorlibBinder::GetClass(CLASS__EVENT_HANDLERGENERIC);
2812 MscorlibBinder::GetClass(CLASS__IENUMERABLE);
2813 MscorlibBinder::GetClass(CLASS__ICOLLECTION);
2814 MscorlibBinder::GetClass(CLASS__ILIST);
2815 MscorlibBinder::GetClass(CLASS__IDISPOSABLE);
2818 WinRTInterfaceRedirector::VerifyRedirectedInterfaceStubs();
2822 #ifdef FEATURE_ICASTABLE
2823 g_pICastableInterface = MscorlibBinder::GetClass(CLASS__ICASTABLE);
2824 #endif // FEATURE_ICASTABLE
2826 // Load a special marker method used to detect Constrained Execution Regions
2828 g_pExecuteBackoutCodeHelperMethod = MscorlibBinder::GetMethod(METHOD__RUNTIME_HELPERS__EXECUTE_BACKOUT_CODE_HELPER);
2830 // Make sure that FCall mapping for Monitor.Enter is initialized. We need it in case Monitor.Enter is used only as JIT helper.
2831 // For more details, see comment in code:JITutil_MonEnterWorker around "__me = GetEEFuncEntryPointMacro(JIT_MonEnter)".
2832 ECall::GetFCallImpl(MscorlibBinder::GetMethod(METHOD__MONITOR__ENTER));
2834 #ifdef PROFILING_SUPPORTED
2835 // Note that g_profControlBlock.fBaseSystemClassesLoaded must be set to TRUE only after
2836 // all base system classes are loaded. Profilers are not allowed to call any type-loading
2837 // APIs until g_profControlBlock.fBaseSystemClassesLoaded is TRUE. It is important that
2838 // all base system classes need to be loaded before profilers can trigger the type loading.
2839 g_profControlBlock.fBaseSystemClassesLoaded = TRUE;
2840 #endif // PROFILING_SUPPORTED
2842 #if defined(_DEBUG) && !defined(CROSSGEN_COMPILE)
2843 if (!NingenEnabled())
2849 #if defined(HAVE_GCCOVER) && defined(FEATURE_PREJIT)
2850 if (GCStress<cfg_instr_ngen>::IsEnabled())
2852 // Setting up gc coverage requires the base system classes
2853 // to be initialized. So we have deferred it until now for mscorlib.
2854 Module *pModule = MscorlibBinder::GetModule();
2855 _ASSERTE(pModule->IsSystem());
2856 if(pModule->HasNativeImage())
2858 SetupGcCoverageForNativeImage(pModule);
2861 #endif // defined(HAVE_GCCOVER) && !defined(FEATURE_PREJIT)
2865 void SystemDomain::LoadDomain(AppDomain *pDomain)
2872 PRECONDITION(CheckPointer(System()));
2873 INJECT_FAULT(COMPlusThrowOM(););
2877 pDomain->SetCanUnload(); // by default can unload any domain
2878 SystemDomain::System()->AddDomain(pDomain);
2881 ADIndex SystemDomain::GetNewAppDomainIndex(AppDomain *pAppDomain)
2883 STANDARD_VM_CONTRACT;
2885 DWORD count = m_appDomainIndexList.GetCount();
2891 // So that we can keep AD index inside object header.
2892 // We do not want to create syncblock unless needed.
2899 // Look for an unused index. Note that in a checked build,
2900 // we never reuse indexes - this makes it easier to tell
2901 // when we are looking at a stale app domain.
2904 i = m_appDomainIndexList.FindElement(m_dwLowestFreeIndex, NULL);
2905 if (i == (DWORD) ArrayList::NOT_FOUND)
2907 m_dwLowestFreeIndex = i+1;
2909 if (m_dwLowestFreeIndex >= 2000)
2911 m_dwLowestFreeIndex = 0;
2917 IfFailThrow(m_appDomainIndexList.Append(pAppDomain));
2919 m_appDomainIndexList.Set(i, pAppDomain);
2921 _ASSERTE(i < m_appDomainIndexList.GetCount());
2923 // Note that index 0 means domain agile.
2924 return ADIndex(i+1);
2927 void SystemDomain::ReleaseAppDomainIndex(ADIndex index)
2929 WRAPPER_NO_CONTRACT;
2930 SystemDomain::LockHolder lh;
2931 // Note that index 0 means domain agile.
2934 _ASSERTE(m_appDomainIndexList.Get(index.m_dwIndex) != NULL);
2936 m_appDomainIndexList.Set(index.m_dwIndex, NULL);
2939 if (index.m_dwIndex < m_dwLowestFreeIndex)
2940 m_dwLowestFreeIndex = index.m_dwIndex;
2944 #endif // !DACCESS_COMPILE
2946 PTR_AppDomain SystemDomain::GetAppDomainAtIndex(ADIndex index)
2948 LIMITED_METHOD_CONTRACT;
2950 _ASSERTE(index.m_dwIndex != 0);
2952 PTR_AppDomain pAppDomain = TestGetAppDomainAtIndex(index);
2954 _ASSERTE(pAppDomain || !"Attempt to access unloaded app domain");
2959 PTR_AppDomain SystemDomain::TestGetAppDomainAtIndex(ADIndex index)
2961 LIMITED_METHOD_CONTRACT;
2963 _ASSERTE(index.m_dwIndex != 0);
2966 #ifndef DACCESS_COMPILE
2967 _ASSERTE(index.m_dwIndex < (DWORD)m_appDomainIndexList.GetCount());
2968 AppDomain *pAppDomain = (AppDomain*) m_appDomainIndexList.Get(index.m_dwIndex);
2969 #else // DACCESS_COMPILE
2970 PTR_ArrayListStatic pList = &m_appDomainIndexList;
2971 AppDomain *pAppDomain = dac_cast<PTR_AppDomain>(pList->Get(index.m_dwIndex));
2972 #endif // DACCESS_COMPILE
2973 return PTR_AppDomain(pAppDomain);
2976 #ifndef DACCESS_COMPILE
2978 // See also code:SystemDomain::ReleaseAppDomainId
2979 ADID SystemDomain::GetNewAppDomainId(AppDomain *pAppDomain)
2986 INJECT_FAULT(COMPlusThrowOM(););
2990 DWORD i = m_appDomainIdList.GetCount();
2992 IfFailThrow(m_appDomainIdList.Append(pAppDomain));
2994 _ASSERTE(i < m_appDomainIdList.GetCount());
2999 AppDomain *SystemDomain::GetAppDomainAtId(ADID index)
3004 if (!SystemDomain::IsUnderDomainLock() && !IsGCThread()) { MODE_COOPERATIVE;} else { DISABLED(MODE_ANY);}
3012 if(index.m_dwId == 0)
3014 DWORD requestedID = index.m_dwId - 1;
3016 if(requestedID >= (DWORD)m_appDomainIdList.GetCount())
3019 AppDomain * result = (AppDomain *)m_appDomainIdList.Get(requestedID);
3021 #ifndef CROSSGEN_COMPILE
3022 if(result==NULL && GetThread() == FinalizerThread::GetFinalizerThread() &&
3023 SystemDomain::System()->AppDomainBeingUnloaded()!=NULL &&
3024 SystemDomain::System()->AppDomainBeingUnloaded()->GetId()==index)
3025 result=SystemDomain::System()->AppDomainBeingUnloaded();
3026 // If the current thread can't enter the AppDomain, then don't return it.
3027 if (!result || !result->CanThreadEnter(GetThread()))
3029 #endif // CROSSGEN_COMPILE
3034 // Releases an appdomain index. Note that today we have code that depends on these
3035 // indexes not being recycled, so we don't actually shrink m_appDomainIdList, but
3036 // simply zero out an entry. THus we 'leak' the memory associated the slot in
3037 // m_appDomainIdList.
3039 // TODO make this a sparse structure so that we avoid that leak.
3041 void SystemDomain::ReleaseAppDomainId(ADID index)
3043 LIMITED_METHOD_CONTRACT;
3046 _ASSERTE(index.m_dwId < (DWORD)m_appDomainIdList.GetCount());
3048 m_appDomainIdList.Set(index.m_dwId, NULL);
3051 #if defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
3054 int g_fMainThreadApartmentStateSet = 0;
3057 Thread::ApartmentState SystemDomain::GetEntryPointThreadAptState(IMDInternalImport* pScope, mdMethodDef mdMethod)
3059 STANDARD_VM_CONTRACT;
3062 IfFailThrow(hr = pScope->GetCustomAttributeByName(mdMethod,
3063 DEFAULTDOMAIN_MTA_TYPE,
3066 BOOL fIsMTA = FALSE;
3070 IfFailThrow(hr = pScope->GetCustomAttributeByName(mdMethod,
3071 DEFAULTDOMAIN_STA_TYPE,
3074 BOOL fIsSTA = FALSE;
3078 if (fIsSTA && fIsMTA)
3079 COMPlusThrowHR(COR_E_CUSTOMATTRIBUTEFORMAT);
3082 return Thread::AS_InSTA;
3084 return Thread::AS_InMTA;
3086 return Thread::AS_Unknown;
3089 void SystemDomain::SetThreadAptState (IMDInternalImport* pScope, Thread::ApartmentState state)
3091 STANDARD_VM_CONTRACT;
3093 BOOL fIsLegacy = FALSE;
3095 // Check for legacy behavior regarding COM Apartment state of the main thread.
3097 #define METAMODEL_MAJOR_VER_WITH_NEW_BEHAVIOR 2
3098 #define METAMODEL_MINOR_VER_WITH_NEW_BEHAVIOR 0
3101 IfFailThrow(pScope->GetVersionString(&pVer));
3103 // Does this look like a version?
3106 // Is it 'vN.' where N is a digit?
3107 if ((pVer[0] == 'v' || pVer[0] == 'V') &&
3108 IS_DIGIT(pVer[1]) &&
3111 // Looks like a version. Is it lesser than v2.0 major version where we start using new behavior?
3112 fIsLegacy = DIGIT_TO_INT(pVer[1]) < METAMODEL_MAJOR_VER_WITH_NEW_BEHAVIOR;
3116 if (!fIsLegacy && g_pConfig != NULL)
3118 fIsLegacy = g_pConfig->LegacyApartmentInitPolicy();
3122 Thread* pThread = GetThread();
3125 if(state == Thread::AS_InSTA)
3127 Thread::ApartmentState pState = pThread->SetApartment(Thread::AS_InSTA, TRUE);
3128 _ASSERTE(pState == Thread::AS_InSTA);
3130 else if ((state == Thread::AS_InMTA) || (!fIsLegacy))
3132 // If either MTAThreadAttribute is specified or (if no attribute is specified and we are not
3133 // running in legacy mode), then
3134 // we will set the apartment state to MTA. The reason for this is to ensure the apartment
3135 // state is consistent and reliably set. Without this, the apartment state for the main
3136 // thread would be undefined and would actually be dependent on if the assembly was
3137 // ngen'd, which other type were loaded, etc.
3138 Thread::ApartmentState pState = pThread->SetApartment(Thread::AS_InMTA, TRUE);
3139 _ASSERTE(pState == Thread::AS_InMTA);
3143 g_fMainThreadApartmentStateSet++;
3146 #endif // defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
3148 // Looks in all the modules for the DefaultDomain attribute
3149 // The order is assembly and then the modules. It is first
3150 // come, first serve.
3151 BOOL SystemDomain::SetGlobalSharePolicyUsingAttribute(IMDInternalImport* pScope, mdMethodDef mdMethod)
3153 STANDARD_VM_CONTRACT;
3159 void SystemDomain::SetupDefaultDomain()
3166 INJECT_FAULT(COMPlusThrowOM(););
3171 Thread *pThread = GetThread();
3175 pDomain = pThread->GetDomain();
3180 ENTER_DOMAIN_PTR(SystemDomain::System()->DefaultDomain(),ADV_DEFAULTAD)
3182 // Push this frame around loading the main assembly to ensure the
3183 // debugger can properly recgonize any managed code that gets run
3184 // as "class initializaion" code.
3185 FrameWithCookie<DebuggerClassInitMarkFrame> __dcimf;
3189 InitializeDefaultDomain(TRUE);
3194 END_DOMAIN_TRANSITION;
3199 HRESULT SystemDomain::SetupDefaultDomainNoThrow()
3212 SystemDomain::SetupDefaultDomain();
3214 EX_CATCH_HRESULT(hr);
3220 int g_fInitializingInitialAD = 0;
3223 // This routine completes the initialization of the default domaine.
3224 // After this call mananged code can be executed.
3225 void SystemDomain::InitializeDefaultDomain(
3226 BOOL allowRedirects,
3227 ICLRPrivBinder * pBinder)
3229 STANDARD_VM_CONTRACT;
3231 WCHAR* pwsConfig = NULL;
3232 WCHAR* pwsPath = NULL;
3234 ETWOnStartup (InitDefaultDomain_V1, InitDefaultDomainEnd_V1);
3237 // Setup the default AppDomain.
3240 g_fInitializingInitialAD++;
3243 AppDomain* pDefaultDomain = SystemDomain::System()->DefaultDomain();
3245 if (pBinder != nullptr)
3247 pDefaultDomain->SetLoadContextHostBinder(pBinder);
3253 pDefaultDomain->InitializeDomainContext(allowRedirects, pwsPath, pwsConfig);
3255 #ifndef CROSSGEN_COMPILE
3256 if (!NingenEnabled())
3259 if (!IsSingleAppDomain())
3261 pDefaultDomain->InitializeDefaultDomainManager();
3264 #endif // CROSSGEN_COMPILE
3267 // DefaultDomain Load event
3268 ETW::LoaderLog::DomainLoad(pDefaultDomain);
3271 g_fInitializingInitialAD--;
3274 TESTHOOKCALL(RuntimeStarted(RTS_DEFAULTADREADY));
3279 #ifndef CROSSGEN_COMPILE
3282 Volatile<LONG> g_fInExecuteMainMethod = 0;
3288 #endif // CROSSGEN_COMPILE
3292 // Helper function to load an assembly. This is called from LoadCOMClass.
3295 Assembly *AppDomain::LoadAssemblyHelper(LPCWSTR wszAssembly,
3296 LPCWSTR wszCodeBase)
3298 CONTRACT(Assembly *)
3301 POSTCONDITION(CheckPointer(RETVAL));
3302 PRECONDITION(wszAssembly || wszCodeBase);
3303 INJECT_FAULT(COMPlusThrowOM(););
3309 #define MAKE_TRANSLATIONFAILED { ThrowOutOfMemory(); }
3310 MAKE_UTF8PTR_FROMWIDE(szAssembly,wszAssembly);
3311 #undef MAKE_TRANSLATIONFAILED
3313 IfFailThrow(spec.Init(szAssembly));
3317 spec.SetCodeBase(wszCodeBase);
3319 RETURN spec.LoadAssembly(FILE_LOADED);
3322 #if defined(FEATURE_CLASSIC_COMINTEROP) && !defined(CROSSGEN_COMPILE)
3324 MethodTable *AppDomain::LoadCOMClass(GUID clsid,
3325 BOOL bLoadRecord/*=FALSE*/,
3326 BOOL* pfAssemblyInReg/*=NULL*/)
3328 // @CORESYSTODO: what to do here?
3332 #endif // FEATURE_CLASSIC_COMINTEROP && !CROSSGEN_COMPILE
3336 bool SystemDomain::IsReflectionInvocationMethod(MethodDesc* pMeth)
3346 MethodTable* pCaller = pMeth->GetMethodTable();
3348 // All Reflection Invocation methods are defined in mscorlib.dll
3349 if (!pCaller->GetModule()->IsSystem())
3352 /* List of types that should be skipped to identify true caller */
3353 static const BinderClassID reflectionInvocationTypes[] = {
3358 CLASS__CONSTRUCTOR_INFO,
3361 CLASS__METHOD_HANDLE,
3362 CLASS__FIELD_HANDLE,
3365 CLASS__RT_FIELD_INFO,
3370 CLASS__PROPERTY_INFO,
3373 CLASS__ASSEMBLYBASE,
3375 CLASS__TYPE_DELEGATOR,
3376 CLASS__RUNTIME_HELPERS,
3377 CLASS__LAZY_INITIALIZER,
3378 CLASS__DYNAMICMETHOD,
3380 CLASS__MULTICAST_DELEGATE,
3384 static const BinderClassID genericReflectionInvocationTypes[] = {
3388 static mdTypeDef genericReflectionInvocationTypeDefs[NumItems(genericReflectionInvocationTypes)];
3390 static bool fInited = false;
3392 if (!VolatileLoad(&fInited))
3394 // Make sure all types are loaded so that we can use faster GetExistingClass()
3395 for (unsigned i = 0; i < NumItems(reflectionInvocationTypes); i++)
3397 MscorlibBinder::GetClass(reflectionInvocationTypes[i]);
3400 // Make sure all types are loaded so that we can use faster GetExistingClass()
3401 for (unsigned i = 0; i < NumItems(genericReflectionInvocationTypes); i++)
3403 genericReflectionInvocationTypeDefs[i] = MscorlibBinder::GetClass(genericReflectionInvocationTypes[i])->GetCl();
3406 MscorlibBinder::GetClass(CLASS__APP_DOMAIN);
3408 VolatileStore(&fInited, true);
3411 if (pCaller->HasInstantiation())
3413 // For generic types, pCaller will be an instantiated type and never equal to the type definition.
3414 // So we compare their TypeDef tokens instead.
3415 for (unsigned i = 0; i < NumItems(genericReflectionInvocationTypeDefs); i++)
3417 if (pCaller->GetCl() == genericReflectionInvocationTypeDefs[i])
3423 for (unsigned i = 0; i < NumItems(reflectionInvocationTypes); i++)
3425 if (MscorlibBinder::GetExistingClass(reflectionInvocationTypes[i]) == pCaller)
3433 #ifndef CROSSGEN_COMPILE
3434 struct CallersDataWithStackMark
3436 StackCrawlMark* stackMark;
3438 MethodDesc* pFoundMethod;
3439 MethodDesc* pPrevMethod;
3440 AppDomain* pAppDomain;
3444 MethodDesc* SystemDomain::GetCallersMethod(StackCrawlMark* stackMark,
3445 AppDomain **ppAppDomain/*=NULL*/)
3453 INJECT_FAULT(COMPlusThrowOM(););
3459 CallersDataWithStackMark cdata;
3460 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3461 cdata.stackMark = stackMark;
3463 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3465 if(cdata.pFoundMethod) {
3467 *ppAppDomain = cdata.pAppDomain;
3468 return cdata.pFoundMethod;
3474 MethodTable* SystemDomain::GetCallersType(StackCrawlMark* stackMark,
3475 AppDomain **ppAppDomain/*=NULL*/)
3483 INJECT_FAULT(COMPlusThrowOM(););
3487 CallersDataWithStackMark cdata;
3488 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3489 cdata.stackMark = stackMark;
3491 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3493 if(cdata.pFoundMethod) {
3495 *ppAppDomain = cdata.pAppDomain;
3496 return cdata.pFoundMethod->GetMethodTable();
3502 Module* SystemDomain::GetCallersModule(StackCrawlMark* stackMark,
3503 AppDomain **ppAppDomain/*=NULL*/)
3511 INJECT_FAULT(COMPlusThrowOM(););
3517 CallersDataWithStackMark cdata;
3518 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3519 cdata.stackMark = stackMark;
3521 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3523 if(cdata.pFoundMethod) {
3525 *ppAppDomain = cdata.pAppDomain;
3526 return cdata.pFoundMethod->GetModule();
3534 MethodDesc* pMethod;
3538 Assembly* SystemDomain::GetCallersAssembly(StackCrawlMark *stackMark,
3539 AppDomain **ppAppDomain/*=NULL*/)
3541 WRAPPER_NO_CONTRACT;
3542 Module* mod = GetCallersModule(stackMark, ppAppDomain);
3544 return mod->GetAssembly();
3549 Module* SystemDomain::GetCallersModule(int skip)
3556 INJECT_FAULT(COMPlusThrowOM(););
3563 ZeroMemory(&cdata, sizeof(CallersData));
3566 StackWalkFunctions(GetThread(), CallersMethodCallback, &cdata);
3569 return cdata.pMethod->GetModule();
3575 StackWalkAction SystemDomain::CallersMethodCallbackWithStackMark(CrawlFrame* pCf, VOID* data)
3583 INJECT_FAULT(COMPlusThrowOM(););
3588 MethodDesc *pFunc = pCf->GetFunction();
3590 /* We asked to be called back only for functions */
3593 CallersDataWithStackMark* pCaller = (CallersDataWithStackMark*) data;
3594 if (pCaller->stackMark)
3596 if (!pCf->IsInCalleesFrames(pCaller->stackMark))
3598 // save the current in case it is the one we want
3599 pCaller->pPrevMethod = pFunc;
3600 pCaller->pAppDomain = pCf->GetAppDomain();
3601 return SWA_CONTINUE;
3604 // LookForMe stack crawl marks needn't worry about reflection or
3605 // remoting frames on the stack. Each frame above (newer than) the
3606 // target will be captured by the logic above. Once we transition to
3607 // finding the stack mark below the AofRA, we know that we hit the
3608 // target last time round and immediately exit with the cached result.
3610 if (*(pCaller->stackMark) == LookForMe)
3612 pCaller->pFoundMethod = pCaller->pPrevMethod;
3617 // Skip reflection and remoting frames that could lie between a stack marked
3618 // method and its true caller (or that caller and its own caller). These
3619 // frames are infrastructure and logically transparent to the stack crawling
3622 // Skipping remoting frames. We always skip entire client to server spans
3623 // (though we see them in the order server then client during a stack crawl
3626 // We spot the server dispatcher end because all calls are dispatched
3627 // through a single method: StackBuilderSink._PrivateProcessMessage.
3629 Frame* frame = pCf->GetFrame();
3630 _ASSERTE(pCf->IsFrameless() || frame);
3634 // Skipping reflection frames. We don't need to be quite as exhaustive here
3635 // as the security or reflection stack walking code since we know this logic
3636 // is only invoked for selected methods in mscorlib itself. So we're
3637 // reasonably sure we won't have any sensitive methods late bound invoked on
3638 // constructors, properties or events. This leaves being invoked via
3639 // MethodInfo, Type or Delegate (and depending on which invoke overload is
3640 // being used, several different reflection classes may be involved).
3642 g_IBCLogger.LogMethodDescAccess(pFunc);
3644 if (SystemDomain::IsReflectionInvocationMethod(pFunc))
3645 return SWA_CONTINUE;
3647 if (frame && frame->GetFrameType() == Frame::TYPE_MULTICAST)
3649 // This must be either a secure delegate frame or a true multicast delegate invocation.
3651 _ASSERTE(pFunc->GetMethodTable()->IsDelegate());
3653 DELEGATEREF del = (DELEGATEREF)((SecureDelegateFrame*)frame)->GetThis(); // This can throw.
3655 if (COMDelegate::IsSecureDelegate(del))
3657 if (del->IsWrapperDelegate())
3659 // On ARM, we use secure delegate infrastructure to preserve R4 register.
3660 return SWA_CONTINUE;
3662 // For a secure delegate frame, we should return the delegate creator instead
3663 // of the delegate method itself.
3664 pFunc = (MethodDesc*) del->GetMethodPtrAux();
3668 _ASSERTE(COMDelegate::IsTrueMulticastDelegate(del));
3669 return SWA_CONTINUE;
3673 // Return the first non-reflection/remoting frame if no stack mark was
3675 if (!pCaller->stackMark)
3677 pCaller->pFoundMethod = pFunc;
3678 pCaller->pAppDomain = pCf->GetAppDomain();
3682 // If we got here, we must already be in the frame containing the stack mark and we are not looking for "me".
3683 _ASSERTE(pCaller->stackMark &&
3684 pCf->IsInCalleesFrames(pCaller->stackMark) &&
3685 *(pCaller->stackMark) != LookForMe);
3687 // When looking for caller's caller, we delay returning results for another
3688 // round (the way this is structured, we will still be able to skip
3689 // reflection and remoting frames between the caller and the caller's
3692 if ((*(pCaller->stackMark) == LookForMyCallersCaller) &&
3693 (pCaller->pFoundMethod == NULL))
3695 pCaller->pFoundMethod = pFunc;
3696 return SWA_CONTINUE;
3699 // If remoting is not available, we only set the caller if the crawlframe is from the same domain.
3700 // Why? Because if the callerdomain is different from current domain,
3701 // there have to be interop/native frames in between.
3702 // For example, in the CORECLR, if we find the caller to be in a different domain, then the
3703 // call into reflection is due to an unmanaged call into mscorlib. For that
3704 // case, the caller really is an INTEROP method.
3705 // In general, if the caller is INTEROP, we set the caller/callerdomain to be NULL
3706 // (To be precise: they are already NULL and we don't change them).
3707 if (pCf->GetAppDomain() == GetAppDomain())
3708 // We must either be looking for the caller, or the caller's caller when
3709 // we've already found the caller (we used a non-null value in pFoundMethod
3710 // simply as a flag, the correct method to return in both case is the
3713 pCaller->pFoundMethod = pFunc;
3714 pCaller->pAppDomain = pCf->GetAppDomain();
3721 StackWalkAction SystemDomain::CallersMethodCallback(CrawlFrame* pCf, VOID* data)
3723 LIMITED_METHOD_CONTRACT;
3724 STATIC_CONTRACT_SO_TOLERANT;
3725 MethodDesc *pFunc = pCf->GetFunction();
3727 /* We asked to be called back only for functions */
3730 CallersData* pCaller = (CallersData*) data;
3731 if(pCaller->skip == 0) {
3732 pCaller->pMethod = pFunc;
3737 return SWA_CONTINUE;
3741 #endif // CROSSGEN_COMPILE
3743 #ifdef CROSSGEN_COMPILE
3744 // defined in compile.cpp
3745 extern CompilationDomain * theDomain;
3748 void SystemDomain::CreateDefaultDomain()
3750 STANDARD_VM_CONTRACT;
3752 #ifdef CROSSGEN_COMPILE
3753 AppDomainRefHolder pDomain(theDomain);
3755 AppDomainRefHolder pDomain(new AppDomain());
3758 SystemDomain::LockHolder lh;
3761 // need to make this assignment here since we'll be releasing
3762 // the lock before calling AddDomain. So any other thread
3763 // grabbing this lock after we release it will find that
3764 // the COM Domain has already been created
3765 m_pDefaultDomain = pDomain;
3766 _ASSERTE (pDomain->GetId().m_dwId == DefaultADID);
3768 // allocate a Virtual Call Stub Manager for the default domain
3769 m_pDefaultDomain->InitVSD();
3771 pDomain->SetStage(AppDomain::STAGE_OPEN);
3772 pDomain.SuppressRelease();
3774 LOG((LF_CLASSLOADER | LF_CORDB,
3776 "Created default domain at %p\n", m_pDefaultDomain));
3779 #ifdef DEBUGGING_SUPPORTED
3781 void SystemDomain::PublishAppDomainAndInformDebugger (AppDomain *pDomain)
3785 if(!g_fEEInit) {THROWS;} else {DISABLED(NOTHROW);};
3786 if(!g_fEEInit) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);};
3791 LOG((LF_CORDB, LL_INFO100, "SD::PADAID: Adding 0x%x\n", pDomain));
3793 // Call the publisher API to add this appdomain entry to the list
3794 // The publisher will handle failures, so we don't care if this succeeds or fails.
3795 if (g_pDebugInterface != NULL)
3797 g_pDebugInterface->AddAppDomainToIPC(pDomain);
3801 #endif // DEBUGGING_SUPPORTED
3803 void SystemDomain::AddDomain(AppDomain* pDomain)
3810 PRECONDITION(CheckPointer((pDomain)));
3817 _ASSERTE (pDomain->m_Stage != AppDomain::STAGE_CREATING);
3818 if (pDomain->m_Stage == AppDomain::STAGE_READYFORMANAGEDCODE ||
3819 pDomain->m_Stage == AppDomain::STAGE_ACTIVE)
3821 pDomain->SetStage(AppDomain::STAGE_OPEN);
3822 IncrementNumAppDomains(); // Maintain a count of app domains added to the list.
3826 // Note that if you add another path that can reach here without calling
3827 // PublishAppDomainAndInformDebugger, then you should go back & make sure
3828 // that PADAID gets called. Right after this call, if not sooner.
3829 LOG((LF_CORDB, LL_INFO1000, "SD::AD:Would have added domain here! 0x%x\n",
3833 BOOL SystemDomain::RemoveDomain(AppDomain* pDomain)
3840 PRECONDITION(CheckPointer(pDomain));
3841 PRECONDITION(!pDomain->IsDefaultDomain());
3845 // You can not remove the default domain.
3848 if (!pDomain->IsActive())
3857 #ifdef PROFILING_SUPPORTED
3858 void SystemDomain::NotifyProfilerStartup()
3869 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3871 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) System());
3876 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3878 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) System(), S_OK);
3883 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3884 _ASSERTE(System()->DefaultDomain());
3885 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) System()->DefaultDomain());
3890 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3891 _ASSERTE(System()->DefaultDomain());
3892 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) System()->DefaultDomain(), S_OK);
3897 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3898 _ASSERTE(SharedDomain::GetDomain());
3899 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) SharedDomain::GetDomain());
3904 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3905 _ASSERTE(SharedDomain::GetDomain());
3906 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) SharedDomain::GetDomain(), S_OK);
3911 HRESULT SystemDomain::NotifyProfilerShutdown()
3922 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3924 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) System());
3929 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3931 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) System(), S_OK);
3936 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3937 _ASSERTE(System()->DefaultDomain());
3938 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) System()->DefaultDomain());
3943 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3944 _ASSERTE(System()->DefaultDomain());
3945 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) System()->DefaultDomain(), S_OK);
3950 #endif // PROFILING_SUPPORTED
3954 struct AppDomain::ThreadTrackInfo {
3956 CDynArray<Frame *> frameStack;
3960 AppDomain::AppDomain()
3962 // initialize fields so the appdomain can be safely destructed
3963 // shouldn't call anything that can fail here - use ::Init instead
3974 m_pNextInDelayedUnloadList = NULL;
3975 m_fRudeUnload = FALSE;
3976 m_pUnloadRequestThread = NULL;
3977 m_ADUnloadSink=NULL;
3980 // Initialize Shared state. Assemblies are loaded
3981 // into each domain by default.
3982 #ifdef FEATURE_LOADER_OPTIMIZATION
3983 m_SharePolicy = SHARE_POLICY_UNSPECIFIED;
3986 m_pRootAssembly = NULL;
3988 m_pwDynamicDir = NULL;
3991 m_pDefaultContext = NULL;
3992 #ifdef FEATURE_COMINTEROP
3993 m_pComCallWrapperCache = NULL;
3995 m_pRCWRefCache = NULL;
3996 m_pLicenseInteropHelperMT = NULL;
3997 m_COMorRemotingFlag = COMorRemoting_NotInitialized;
3998 memset(m_rpCLRTypes, 0, sizeof(m_rpCLRTypes));
3999 #endif // FEATURE_COMINTEROP
4001 m_pUMEntryThunkCache = NULL;
4003 m_pAsyncPool = NULL;
4004 m_handleStore = NULL;
4006 m_ExposedObject = NULL;
4007 m_pComIPForExposedObject = NULL;
4010 m_pThreadTrackInfoList = NULL;
4011 m_TrackSpinLock = 0;
4012 m_Assemblies.Debug_SetAppDomain(this);
4015 m_dwThreadEnterCount = 0;
4016 m_dwThreadsStillInAppDomain = (ULONG)-1;
4018 #ifdef FEATURE_COMINTEROP
4019 m_pRefDispIDCache = NULL;
4020 m_hndMissing = NULL;
4023 m_pRefClassFactHash = NULL;
4024 m_anonymouslyHostedDynamicMethodsAssembly = NULL;
4026 m_ReversePInvokeCanEnter=TRUE;
4027 m_ForceTrivialWaitOperations = false;
4028 m_Stage=STAGE_CREATING;
4030 m_bForceGCOnUnload=FALSE;
4031 m_bUnloadingFromUnloadEvent=FALSE;
4035 m_dwCreationHolders=0;
4038 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4039 m_ullTotalProcessorUsage = 0;
4040 m_pullAllocBytes = NULL;
4041 m_pullSurvivedBytes = NULL;
4042 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4044 #ifdef FEATURE_TYPEEQUIVALENCE
4045 m_pTypeEquivalenceTable = NULL;
4046 #endif // FEATURE_TYPEEQUIVALENCE
4048 #ifdef FEATURE_COMINTEROP
4049 m_pNameToTypeMap = NULL;
4050 m_vNameToTypeMapVersion = 0;
4052 m_pWinRTFactoryCache = NULL;
4053 #endif // FEATURE_COMINTEROP
4055 #ifdef FEATURE_PREJIT
4056 m_pDomainFileWithNativeImageList = NULL;
4059 m_fIsBindingModelLocked.Store(FALSE);
4061 } // AppDomain::AppDomain
4063 AppDomain::~AppDomain()
4073 #ifndef CROSSGEN_COMPILE
4075 _ASSERTE(m_dwCreationHolders == 0);
4077 // release the TPIndex. note that since TPIndex values are recycled the TPIndex
4078 // can only be released once all threads in the AppDomain have exited.
4079 if (GetTPIndex().m_dwIndex != 0)
4080 PerAppDomainTPCountList::ResetAppDomainIndex(GetTPIndex());
4082 if (m_dwId.m_dwId!=0)
4083 SystemDomain::ReleaseAppDomainId(m_dwId);
4085 m_AssemblyCache.Clear();
4088 m_ADUnloadSink->Release();
4096 #ifdef FEATURE_COMINTEROP
4097 if (m_pNameToTypeMap != nullptr)
4099 delete m_pNameToTypeMap;
4100 m_pNameToTypeMap = nullptr;
4102 if (m_pWinRTFactoryCache != nullptr)
4104 delete m_pWinRTFactoryCache;
4105 m_pWinRTFactoryCache = nullptr;
4107 #endif //FEATURE_COMINTEROP
4110 // If we were tracking thread AD transitions, cleanup the list on shutdown
4111 if (m_pThreadTrackInfoList)
4113 while (m_pThreadTrackInfoList->Count() > 0)
4115 // Get the very last element
4116 ThreadTrackInfo *pElem = *(m_pThreadTrackInfoList->Get(m_pThreadTrackInfoList->Count() - 1));
4122 // Remove pointer entry from the list
4123 m_pThreadTrackInfoList->Delete(m_pThreadTrackInfoList->Count() - 1);
4126 // Now delete the list itself
4127 delete m_pThreadTrackInfoList;
4128 m_pThreadTrackInfoList = NULL;
4132 #endif // CROSSGEN_COMPILE
4135 //*****************************************************************************
4136 //*****************************************************************************
4137 //*****************************************************************************
4138 void AppDomain::Init()
4143 PRECONDITION(SystemDomain::IsUnderDomainLock());
4147 m_pDelayedLoaderAllocatorUnloadList = NULL;
4149 SetStage( STAGE_CREATING);
4152 // The lock is taken also during stack walking (GC or profiler)
4153 // - To prevent deadlock with GC thread, we cannot trigger GC while holding the lock
4154 // - To prevent deadlock with profiler thread, we cannot allow thread suspension
4155 m_crstHostAssemblyMap.Init(
4156 CrstHostAssemblyMap,
4157 (CrstFlags)(CRST_GC_NOTRIGGER_WHEN_TAKEN
4158 | CRST_DEBUGGER_THREAD
4159 INDEBUG(| CRST_DEBUG_ONLY_CHECK_FORBID_SUSPEND_THREAD)));
4160 m_crstHostAssemblyMapAdd.Init(CrstHostAssemblyMapAdd);
4162 m_dwId = SystemDomain::GetNewAppDomainId(this);
4164 m_LoaderAllocator.Init(this);
4166 #ifndef CROSSGEN_COMPILE
4167 //Allocate the threadpool entry before the appdomin id list. Otherwise,
4168 //the thread pool list will be out of sync if insertion of id in
4169 //the appdomain fails.
4170 m_tpIndex = PerAppDomainTPCountList::AddNewTPIndex();
4171 #endif // CROSSGEN_COMPILE
4173 m_dwIndex = SystemDomain::GetNewAppDomainIndex(this);
4175 #ifndef CROSSGEN_COMPILE
4176 PerAppDomainTPCountList::SetAppDomainId(m_tpIndex, m_dwId);
4178 m_ADUnloadSink=new ADUnloadSink();
4183 // Set up the IL stub cache
4184 m_ILStubCache.Init(GetLoaderAllocator()->GetHighFrequencyHeap());
4186 // Set up the binding caches
4187 m_AssemblyCache.Init(&m_DomainCacheCrst, GetHighFrequencyHeap());
4188 m_UnmanagedCache.InitializeTable(this, &m_DomainCacheCrst);
4190 m_MemoryPressure = 0;
4192 m_sDomainLocalBlock.Init(this);
4194 #ifndef CROSSGEN_COMPILE
4196 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4197 // NOTE: it's important that we initialize ARM data structures before calling
4198 // Ref_CreateHandleTableBucket, this is because AD::Init() can race with GC
4199 // and once we add ourselves to the handle table map the GC can start walking
4200 // our handles and calling AD::RecordSurvivedBytes() which touches ARM data.
4201 if (GCHeapUtilities::IsServerHeap())
4202 m_dwNumHeaps = CPUGroupInfo::CanEnableGCCPUGroups() ?
4203 CPUGroupInfo::GetNumActiveProcessors() :
4204 GetCurrentProcessCpuCount();
4207 m_pullAllocBytes = new ULONGLONG [m_dwNumHeaps * ARM_CACHE_LINE_SIZE_ULL];
4208 m_pullSurvivedBytes = new ULONGLONG [m_dwNumHeaps * ARM_CACHE_LINE_SIZE_ULL];
4209 for (DWORD i = 0; i < m_dwNumHeaps; i++)
4211 m_pullAllocBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
4212 m_pullSurvivedBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
4214 m_ullLastEtwAllocBytes = 0;
4215 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4217 // Default domain reuses the handletablemap that was created during EEStartup since
4218 // default domain cannot be unloaded.
4219 if (GetId().m_dwId == DefaultADID)
4221 m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
4225 m_handleStore = GCHandleUtilities::GetGCHandleManager()->CreateHandleStore((void*)(uintptr_t)m_dwIndex.m_dwIndex);
4233 #endif // CROSSGEN_COMPILE
4235 #ifdef FEATURE_TYPEEQUIVALENCE
4236 m_TypeEquivalenceCrst.Init(CrstTypeEquivalenceMap);
4239 m_ReflectionCrst.Init(CrstReflection, CRST_UNSAFE_ANYMODE);
4240 m_RefClassFactCrst.Init(CrstClassFactInfoHash);
4243 LockOwner lock = {&m_DomainCrst, IsOwnerOfCrst};
4244 m_clsidHash.Init(0,&CompareCLSID,true, &lock); // init hash table
4247 SetStage(STAGE_READYFORMANAGEDCODE);
4249 #ifndef CROSSGEN_COMPILE
4250 m_pDefaultContext = new Context(this);
4252 m_ExposedObject = CreateHandle(NULL);
4254 // Create the Application Security Descriptor
4256 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomains++);
4258 #ifdef FEATURE_COMINTEROP
4259 if (!AppX::IsAppXProcess())
4262 #endif //FEATURE_COMINTEROP
4264 #ifdef FEATURE_TIERED_COMPILATION
4265 m_tieredCompilationManager.Init(GetId());
4267 #endif // CROSSGEN_COMPILE
4268 } // AppDomain::Init
4271 /*********************************************************************/
4273 BOOL AppDomain::IsCompilationDomain()
4275 LIMITED_METHOD_CONTRACT;
4277 BOOL isCompilationDomain = (m_dwFlags & COMPILATION_DOMAIN) != 0;
4278 #ifdef FEATURE_PREJIT
4279 _ASSERTE(!isCompilationDomain ||
4280 (IsCompilationProcess() && IsPassiveDomain()));
4281 #endif // FEATURE_PREJIT
4282 return isCompilationDomain;
4285 #ifndef CROSSGEN_COMPILE
4287 extern int g_fADUnloadWorkerOK;
4290 // This helper will send the AppDomain creation notifications for profiler / debugger.
4291 // If it throws, its backout code will also send a notification.
4292 // If it succeeds, then we still need to send a AppDomainCreateFinished notification.
4293 void AppDomain::CreateUnmanagedObject(AppDomainCreationHolder<AppDomain>& pDomain)
4300 INJECT_FAULT(COMPlusThrowOM(););
4306 pDomain.Assign(new AppDomain());
4307 if (g_fADUnloadWorkerOK<0)
4309 AppDomain::CreateADUnloadWorker();
4313 // We addref Appdomain object here and notify a profiler that appdomain
4314 // creation has started, then return to managed code which will call
4315 // the function that releases the appdomain and notifies a profiler that we finished
4316 // creating the appdomain. If an exception is raised while we're in that managed code
4317 // we will leak memory and the profiler will not be notified about the failure
4319 #ifdef PROFILING_SUPPORTED
4320 // Signal profile if present.
4322 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
4323 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) (AppDomain*) pDomain);
4327 #endif // PROFILING_SUPPORTED
4330 SystemDomain::LockHolder lh;
4332 // allocate a Virtual Call Stub Manager for this domain
4336 pDomain->SetCanUnload(); // by default can unload any domain
4338 #ifdef DEBUGGING_SUPPORTED
4339 // Notify the debugger here, before the thread transitions into the
4340 // AD to finish the setup, and before any assemblies are loaded into it.
4341 SystemDomain::PublishAppDomainAndInformDebugger(pDomain);
4342 #endif // DEBUGGING_SUPPORTED
4344 STRESS_LOG2 (LF_APPDOMAIN, LL_INFO100, "Create domain [%d] %p\n", pDomain->GetId().m_dwId, (AppDomain*)pDomain);
4345 pDomain->LoadSystemAssemblies();
4346 pDomain->SetupSharedStatics();
4348 pDomain->SetStage(AppDomain::STAGE_ACTIVE);
4350 #ifdef PROFILING_SUPPORTED
4353 // Need the first assembly loaded in to get any data on an app domain.
4355 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
4356 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID)(AppDomain*) pDomain, GET_EXCEPTION()->GetHR());
4362 // On success, caller must still send the AppDomainCreationFinished notification.
4363 #endif // PROFILING_SUPPORTED
4366 void AppDomain::Stop()
4376 #ifdef FEATURE_MULTICOREJIT
4377 GetMulticoreJitManager().StopProfile(true);
4380 // Set the unloaded flag before notifying the debugger
4381 GetLoaderAllocator()->SetIsUnloaded();
4383 #ifdef DEBUGGING_SUPPORTED
4384 if (IsDebuggerAttached())
4385 NotifyDebuggerUnload();
4386 #endif // DEBUGGING_SUPPORTED
4388 m_pRootAssembly = NULL; // This assembly is in the assembly list;
4390 #ifdef DEBUGGING_SUPPORTED
4391 if (NULL != g_pDebugInterface)
4393 // Call the publisher API to delete this appdomain entry from the list
4394 CONTRACT_VIOLATION(ThrowsViolation);
4395 g_pDebugInterface->RemoveAppDomainFromIPC (this);
4397 #endif // DEBUGGING_SUPPORTED
4400 void AppDomain::Terminate()
4413 _ASSERTE(m_dwThreadEnterCount == 0 || IsDefaultDomain());
4415 if (m_pComIPForExposedObject)
4417 m_pComIPForExposedObject->Release();
4418 m_pComIPForExposedObject = NULL;
4421 delete m_pDefaultContext;
4422 m_pDefaultContext = NULL;
4424 if (m_pUMEntryThunkCache)
4426 delete m_pUMEntryThunkCache;
4427 m_pUMEntryThunkCache = NULL;
4430 #ifdef FEATURE_COMINTEROP
4439 delete m_pRCWRefCache;
4440 m_pRCWRefCache = NULL;
4443 if (m_pComCallWrapperCache)
4445 m_pComCallWrapperCache->Neuter();
4446 m_pComCallWrapperCache->Release();
4449 // if the above released the wrapper cache, then it will call back and reset our
4450 // m_pComCallWrapperCache to null. If not null, then need to set it's domain pointer to
4452 if (! m_pComCallWrapperCache)
4454 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::Terminate ComCallWrapperCache released\n"));
4459 m_pComCallWrapperCache = NULL;
4460 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::Terminate ComCallWrapperCache not released\n"));
4464 #endif // FEATURE_COMINTEROP
4467 if (!IsAtProcessExit())
4469 // if we're not shutting down everything then clean up the string literals associated
4470 // with this appdomain -- note that is no longer needs to happen while suspended
4471 // because the appropriate locks are taken in the GlobalStringLiteralMap
4472 // this is important as this locks have a higher lock number than does the
4473 // thread-store lock which is taken when we suspend.
4474 GetLoaderAllocator()->CleanupStringLiteralMap();
4476 // Suspend the EE to do some clean up that can only occur
4477 // while no threads are running.
4478 GCX_COOP (); // SuspendEE may require current thread to be in Coop mode
4479 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
4482 // Note that this must be performed before restarting the EE. It will clean
4483 // the cache and prevent others from using stale cache entries.
4484 //@TODO: Would be nice to get this back to BaseDomain, but need larger fix for that.
4485 // NOTE: Must have the runtime suspended to unlink managers
4486 // NOTE: May be NULL due to OOM during initialization. Can skip in that case.
4487 GetLoaderAllocator()->UninitVirtualCallStubManager();
4488 MethodTable::ClearMethodDataCache();
4489 ClearJitGenericHandleCache(this);
4491 // @TODO s_TPMethodTableCrst prevents us from from keeping the whole
4492 // assembly shutdown logic here. See if we can do better in the next milestone
4493 #ifdef FEATURE_PREJIT
4494 DeleteNativeCodeRanges();
4497 if (!IsAtProcessExit())
4500 ThreadSuspend::RestartEE(FALSE, TRUE);
4503 ShutdownAssemblies();
4504 ShutdownNativeDllSearchDirectories();
4506 if (m_pRefClassFactHash)
4508 m_pRefClassFactHash->Destroy();
4509 // storage for m_pRefClassFactHash itself is allocated on the loader heap
4512 #ifdef FEATURE_TYPEEQUIVALENCE
4513 m_TypeEquivalenceCrst.Destroy();
4516 m_ReflectionCrst.Destroy();
4517 m_RefClassFactCrst.Destroy();
4519 m_LoaderAllocator.Terminate();
4521 BaseDomain::Terminate();
4525 GCHandleUtilities::GetGCHandleManager()->DestroyHandleStore(m_handleStore);
4526 m_handleStore = NULL;
4529 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4530 if (m_pullAllocBytes)
4532 delete [] m_pullAllocBytes;
4534 if (m_pullSurvivedBytes)
4536 delete [] m_pullSurvivedBytes;
4538 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4540 if(m_dwIndex.m_dwIndex != 0)
4541 SystemDomain::ReleaseAppDomainIndex(m_dwIndex);
4542 } // AppDomain::Terminate
4544 void AppDomain::CloseDomain()
4555 BOOL bADRemoved=FALSE;;
4557 AddRef(); // Hold a reference
4558 AppDomainRefHolder AdHolder(this);
4560 SystemDomain::LockHolder lh;
4562 SystemDomain::System()->DecrementNumAppDomains(); // Maintain a count of app domains added to the list.
4563 bADRemoved = SystemDomain::System()->RemoveDomain(this);
4570 /*********************************************************************/
4572 struct GetExposedObject_Args
4578 static void GetExposedObject_Wrapper(LPVOID ptr)
4587 GetExposedObject_Args *args = (GetExposedObject_Args *) ptr;
4588 *(args->ref) = args->pDomain->GetExposedObject();
4592 OBJECTREF AppDomain::GetExposedObject()
4599 INJECT_FAULT(COMPlusThrowOM(););
4603 OBJECTREF ref = GetRawExposedObject();
4606 APPDOMAINREF obj = NULL;
4608 Thread *pThread = GetThread();
4609 if (pThread->GetDomain() != this)
4611 GCPROTECT_BEGIN(ref);
4612 GetExposedObject_Args args = {this, &ref};
4613 // call through DoCallBack with a domain transition
4614 pThread->DoADCallBack(this,GetExposedObject_Wrapper, &args,ADV_CREATING|ADV_RUNNINGIN);
4618 MethodTable *pMT = MscorlibBinder::GetClass(CLASS__APP_DOMAIN);
4620 // Create the module object
4621 obj = (APPDOMAINREF) AllocateObject(pMT);
4622 obj->SetDomain(this);
4624 if (!StoreFirstObjectInHandle(m_ExposedObject, (OBJECTREF) obj))
4626 obj = (APPDOMAINREF) GetRawExposedObject();
4630 return (OBJECTREF) obj;
4638 OBJECTREF AppDomain::DoSetup(OBJECTREF* setupInfo)
4645 INJECT_FAULT(COMPlusThrowOM(););
4649 ADID adid=GetAppDomain()->GetId();
4651 OBJECTREF retval=NULL;
4652 GCPROTECT_BEGIN(retval);
4654 ENTER_DOMAIN_PTR(this,ADV_CREATING);
4656 MethodDescCallSite setup(METHOD__APP_DOMAIN__SETUP);
4660 args[0]=ObjToArgSlot(*setupInfo);
4662 OBJECTREF activator;
4663 activator=setup.Call_RetOBJECTREF(args);
4664 _ASSERTE(activator==NULL);
4666 #if defined(FEATURE_MULTICOREJIT)
4667 // Disable AutoStartProfile in default domain from this code path.
4668 // It's called from SystemDomain::ExecuteMainMethod for normal program, not needed for SL and Asp.Net
4669 if (! IsDefaultDomain())
4673 GetMulticoreJitManager().AutoStartProfile(this);
4677 END_DOMAIN_TRANSITION;
4682 #endif // !CROSSGEN_COMPILE
4684 #ifdef FEATURE_COMINTEROP
4685 #ifndef CROSSGEN_COMPILE
4686 HRESULT AppDomain::GetComIPForExposedObject(IUnknown **pComIP)
4688 // Assumption: This function is called for AppDomain's that the current
4689 // thread is in or has entered, or the AppDomain is kept alive.
4691 // Assumption: This function can now throw. The caller is responsible for any
4692 // BEGIN_EXTERNAL_ENTRYPOINT, EX_TRY, or other
4693 // techniques to convert to a COM HRESULT protocol.
4703 Thread *pThread = GetThread();
4704 if (m_pComIPForExposedObject)
4706 GCX_PREEMP_THREAD_EXISTS(pThread);
4707 m_pComIPForExposedObject->AddRef();
4708 *pComIP = m_pComIPForExposedObject;
4712 IUnknown* punk = NULL;
4714 OBJECTREF ref = NULL;
4715 GCPROTECT_BEGIN(ref);
4719 ENTER_DOMAIN_PTR(this,ADV_DEFAULTAD)
4721 ref = GetExposedObject();
4722 punk = GetComIPFromObjectRef(&ref);
4723 if (FastInterlockCompareExchangePointer(&m_pComIPForExposedObject, punk, NULL) == NULL)
4725 GCX_PREEMP_THREAD_EXISTS(pThread);
4726 m_pComIPForExposedObject->AddRef();
4729 END_DOMAIN_TRANSITION;
4735 *pComIP = m_pComIPForExposedObject;
4740 #endif //#ifndef CROSSGEN_COMPILE
4742 MethodTable *AppDomain::GetRedirectedType(WinMDAdapter::RedirectedTypeIndex index)
4752 // If we have the type loaded already, use that
4753 if (m_rpCLRTypes[index] != nullptr)
4755 return m_rpCLRTypes[index];
4758 WinMDAdapter::FrameworkAssemblyIndex frameworkAssemblyIndex;
4759 WinMDAdapter::GetRedirectedTypeInfo(index, nullptr, nullptr, nullptr, &frameworkAssemblyIndex, nullptr, nullptr);
4760 MethodTable * pMT = LoadRedirectedType(index, frameworkAssemblyIndex);
4761 m_rpCLRTypes[index] = pMT;
4765 MethodTable* AppDomain::LoadRedirectedType(WinMDAdapter::RedirectedTypeIndex index, WinMDAdapter::FrameworkAssemblyIndex assembly)
4772 PRECONDITION(index < WinMDAdapter::RedirectedTypeIndex_Count);
4776 LPCSTR szClrNamespace;
4778 LPCSTR szFullWinRTName;
4779 WinMDAdapter::FrameworkAssemblyIndex nFrameworkAssemblyIndex;
4781 WinMDAdapter::GetRedirectedTypeInfo(index, &szClrNamespace, &szClrName, &szFullWinRTName, &nFrameworkAssemblyIndex, nullptr, nullptr);
4783 _ASSERTE(nFrameworkAssemblyIndex >= WinMDAdapter::FrameworkAssembly_Mscorlib &&
4784 nFrameworkAssemblyIndex < WinMDAdapter::FrameworkAssembly_Count);
4786 if (assembly != nFrameworkAssemblyIndex)
4788 // The framework type does not live in the assembly we were requested to load redirected types from
4791 else if (nFrameworkAssemblyIndex == WinMDAdapter::FrameworkAssembly_Mscorlib)
4793 return ClassLoader::LoadTypeByNameThrowing(MscorlibBinder::GetModule()->GetAssembly(),
4796 ClassLoader::ThrowIfNotFound,
4797 ClassLoader::LoadTypes,
4798 CLASS_LOAD_EXACTPARENTS).GetMethodTable();
4803 AssemblyMetaDataInternal context;
4804 const BYTE * pbKeyToken;
4805 DWORD cbKeyTokenLength;
4808 WinMDAdapter::GetExtraAssemblyRefProps(nFrameworkAssemblyIndex,
4815 Assembly* pAssembly = AssemblySpec::LoadAssembly(pSimpleName,
4821 return ClassLoader::LoadTypeByNameThrowing(
4825 ClassLoader::ThrowIfNotFound,
4826 ClassLoader::LoadTypes,
4827 CLASS_LOAD_EXACTPARENTS).GetMethodTable();
4830 #endif //FEATURE_COMINTEROP
4832 #endif //!DACCESS_COMPILE
4834 #ifndef DACCESS_COMPILE
4836 bool IsPlatformAssembly(LPCSTR szName, DomainAssembly *pDomainAssembly)
4843 PRECONDITION(CheckPointer(szName));
4844 PRECONDITION(CheckPointer(pDomainAssembly));
4848 PEAssembly *pPEAssembly = pDomainAssembly->GetFile();
4850 if (strcmp(szName, pPEAssembly->GetSimpleName()) != 0)
4856 const BYTE *pbPublicKey = static_cast<const BYTE *>(pPEAssembly->GetPublicKey(&cbPublicKey));
4857 if (pbPublicKey == nullptr)
4862 return StrongNameIsSilverlightPlatformKey(pbPublicKey, cbPublicKey);
4865 void AppDomain::AddAssembly(DomainAssembly * assem)
4872 INJECT_FAULT(COMPlusThrowOM(););
4877 CrstHolder ch(GetAssemblyListLock());
4879 // Attempt to find empty space in assemblies list
4880 DWORD asmCount = m_Assemblies.GetCount_Unlocked();
4881 for (DWORD i = 0; i < asmCount; ++i)
4883 if (m_Assemblies.Get_UnlockedNoReference(i) == NULL)
4885 m_Assemblies.Set_Unlocked(i, assem);
4890 // If empty space not found, simply add to end of list
4891 IfFailThrow(m_Assemblies.Append_Unlocked(assem));
4895 void AppDomain::RemoveAssembly_Unlocked(DomainAssembly * pAsm)
4904 _ASSERTE(GetAssemblyListLock()->OwnedByCurrentThread());
4906 DWORD asmCount = m_Assemblies.GetCount_Unlocked();
4907 for (DWORD i = 0; i < asmCount; ++i)
4909 if (m_Assemblies.Get_UnlockedNoReference(i) == pAsm)
4911 m_Assemblies.Set_Unlocked(i, NULL);
4916 _ASSERTE(!"Unreachable");
4919 BOOL AppDomain::ContainsAssembly(Assembly * assem)
4921 WRAPPER_NO_CONTRACT;
4922 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
4924 (assem->IsIntrospectionOnly() ? kIncludeIntrospection : kIncludeExecution)));
4925 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
4927 while (i.Next(pDomainAssembly.This()))
4929 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
4930 if (pAssembly == assem)
4937 EEClassFactoryInfoHashTable* AppDomain::SetupClassFactHash()
4944 INJECT_FAULT(COMPlusThrowOM(););
4948 CrstHolder ch(&m_ReflectionCrst);
4950 if (m_pRefClassFactHash == NULL)
4952 AllocMemHolder<void> pCache(GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof (EEClassFactoryInfoHashTable))));
4953 EEClassFactoryInfoHashTable *tmp = new (pCache) EEClassFactoryInfoHashTable;
4954 LockOwner lock = {&m_RefClassFactCrst,IsOwnerOfCrst};
4955 if (!tmp->Init(20, &lock))
4957 pCache.SuppressRelease();
4958 m_pRefClassFactHash = tmp;
4961 return m_pRefClassFactHash;
4964 #ifdef FEATURE_COMINTEROP
4965 DispIDCache* AppDomain::SetupRefDispIDCache()
4972 INJECT_FAULT(COMPlusThrowOM(););
4976 CrstHolder ch(&m_ReflectionCrst);
4978 if (m_pRefDispIDCache == NULL)
4980 AllocMemHolder<void> pCache = GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof (DispIDCache)));
4982 DispIDCache *tmp = new (pCache) DispIDCache;
4985 pCache.SuppressRelease();
4986 m_pRefDispIDCache = tmp;
4989 return m_pRefDispIDCache;
4992 #endif // FEATURE_COMINTEROP
4994 FileLoadLock *FileLoadLock::Create(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile)
5001 PRECONDITION(pLock->HasLock());
5002 PRECONDITION(pLock->FindFileLock(pFile) == NULL);
5003 INJECT_FAULT(COMPlusThrowOM(););
5007 NewHolder<FileLoadLock> result(new FileLoadLock(pLock, pFile, pDomainFile));
5009 pLock->AddElement(result);
5010 result->AddRef(); // Add one ref on behalf of the ListLock's reference. The corresponding Release() happens in FileLoadLock::CompleteLoadLevel.
5011 return result.Extract();
5014 FileLoadLock::~FileLoadLock()
5024 ((PEFile *) m_data)->Release();
5027 DomainFile *FileLoadLock::GetDomainFile()
5029 LIMITED_METHOD_CONTRACT;
5030 return m_pDomainFile;
5033 FileLoadLevel FileLoadLock::GetLoadLevel()
5035 LIMITED_METHOD_CONTRACT;
5039 ADID FileLoadLock::GetAppDomainId()
5041 LIMITED_METHOD_CONTRACT;
5042 return m_AppDomainId;
5045 // Acquire will return FALSE and not take the lock if the file
5046 // has already been loaded to the target level. Otherwise,
5047 // it will return TRUE and take the lock.
5049 // Note that the taker must release the lock via IncrementLoadLevel.
5051 BOOL FileLoadLock::Acquire(FileLoadLevel targetLevel)
5053 WRAPPER_NO_CONTRACT;
5055 // If we are already loaded to the desired level, the lock is "free".
5056 if (m_level >= targetLevel)
5059 if (!DeadlockAwareEnter())
5061 // We failed to get the lock due to a deadlock.
5065 if (m_level >= targetLevel)
5074 BOOL FileLoadLock::CanAcquire(FileLoadLevel targetLevel)
5076 // If we are already loaded to the desired level, the lock is "free".
5077 if (m_level >= targetLevel)
5080 return CanDeadlockAwareEnter();
5083 #if !defined(DACCESS_COMPILE) && (defined(LOGGING) || defined(STRESS_LOG))
5084 static const char *fileLoadLevelName[] =
5086 "CREATE", // FILE_LOAD_CREATE
5087 "BEGIN", // FILE_LOAD_BEGIN
5088 "FIND_NATIVE_IMAGE", // FILE_LOAD_FIND_NATIVE_IMAGE
5089 "VERIFY_NATIVE_IMAGE_DEPENDENCIES", // FILE_LOAD_VERIFY_NATIVE_IMAGE_DEPENDENCIES
5090 "ALLOCATE", // FILE_LOAD_ALLOCATE
5091 "ADD_DEPENDENCIES", // FILE_LOAD_ADD_DEPENDENCIES
5092 "PRE_LOADLIBRARY", // FILE_LOAD_PRE_LOADLIBRARY
5093 "LOADLIBRARY", // FILE_LOAD_LOADLIBRARY
5094 "POST_LOADLIBRARY", // FILE_LOAD_POST_LOADLIBRARY
5095 "EAGER_FIXUPS", // FILE_LOAD_EAGER_FIXUPS
5096 "VTABLE FIXUPS", // FILE_LOAD_VTABLE_FIXUPS
5097 "DELIVER_EVENTS", // FILE_LOAD_DELIVER_EVENTS
5098 "LOADED", // FILE_LOADED
5099 "VERIFY_EXECUTION", // FILE_LOAD_VERIFY_EXECUTION
5100 "ACTIVE", // FILE_ACTIVE
5102 #endif // !DACCESS_COMPILE && (LOGGING || STRESS_LOG)
5104 BOOL FileLoadLock::CompleteLoadLevel(FileLoadLevel level, BOOL success)
5111 PRECONDITION(HasLock());
5115 // Increment may happen more than once if reentrancy occurs (e.g. LoadLibrary)
5116 if (level > m_level)
5118 // Must complete each level in turn, unless we have an error
5119 CONSISTENCY_CHECK(m_pDomainFile->IsError() || (level == (m_level+1)));
5120 // Remove the lock from the list if the load is completed
5121 if (level >= FILE_ACTIVE)
5125 PEFileListLockHolder lock((PEFileListLock*)m_pList);
5128 BOOL fDbgOnly_SuccessfulUnlink =
5130 m_pList->Unlink(this);
5131 _ASSERTE(fDbgOnly_SuccessfulUnlink);
5133 m_pDomainFile->ClearLoading();
5135 CONSISTENCY_CHECK(m_dwRefCount >= 2); // Caller (LoadDomainFile) should have 1 refcount and m_pList should have another which was acquired in FileLoadLock::Create.
5137 m_level = (FileLoadLevel)level;
5140 // In AppDomain::IsLoading, if the lock is taken on m_pList and then FindFileLock returns NULL,
5141 // we depend on the DomainFile's load level being up to date. Hence we must update the load
5142 // level while the m_pList lock is held.
5144 m_pDomainFile->SetLoadLevel(level);
5148 Release(); // Release m_pList's refcount on this lock, which was acquired in FileLoadLock::Create
5153 m_level = (FileLoadLevel)level;
5156 m_pDomainFile->SetLoadLevel(level);
5159 #ifndef DACCESS_COMPILE
5162 case FILE_LOAD_ALLOCATE:
5163 case FILE_LOAD_ADD_DEPENDENCIES:
5164 case FILE_LOAD_DELIVER_EVENTS:
5166 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.
5167 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);
5180 void FileLoadLock::SetError(Exception *ex)
5187 PRECONDITION(CheckPointer(ex));
5188 PRECONDITION(HasLock());
5189 INJECT_FAULT(COMPlusThrowOM(););
5193 m_cachedHR = ex->GetHR();
5195 LOG((LF_LOADER, LL_WARNING, "LOADER: %x:***%s*\t!!!Non-transient error 0x%x\n",
5196 m_pDomainFile->GetAppDomain(), m_pDomainFile->GetSimpleName(), m_cachedHR));
5198 m_pDomainFile->SetError(ex);
5200 CompleteLoadLevel(FILE_ACTIVE, FALSE);
5203 void FileLoadLock::AddRef()
5205 LIMITED_METHOD_CONTRACT;
5206 FastInterlockIncrement((LONG *) &m_dwRefCount);
5209 UINT32 FileLoadLock::Release()
5219 LONG count = FastInterlockDecrement((LONG *) &m_dwRefCount);
5226 FileLoadLock::FileLoadLock(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile)
5227 : ListLockEntry(pLock, pFile, "File load lock"),
5228 m_level((FileLoadLevel) (FILE_LOAD_CREATE)),
5229 m_pDomainFile(pDomainFile),
5231 m_AppDomainId(pDomainFile->GetAppDomain()->GetId())
5233 WRAPPER_NO_CONTRACT;
5237 void FileLoadLock::HolderLeave(FileLoadLock *pThis)
5239 LIMITED_METHOD_CONTRACT;
5249 // Assembly loading:
5251 // Assembly loading is carefully layered to avoid deadlocks in the
5252 // presence of circular loading dependencies.
5253 // A LoadLevel is associated with each assembly as it is being loaded. During the
5254 // act of loading (abstractly, increasing its load level), its lock is
5255 // held, and the current load level is stored on the thread. Any
5256 // recursive loads during that period are automatically restricted to
5257 // only partially load the dependent assembly to the same level as the
5258 // caller (or to one short of that level in the presence of a deadlock
5261 // Each loading stage must be carfully constructed so that
5262 // this constraint is expected and can be dealt with.
5264 // Note that there is one case where this still doesn't handle recursion, and that is the
5265 // security subsytem. The security system runs managed code, and thus must typically fully
5266 // initialize assemblies of permission sets it is trying to use. (And of course, these may be used
5267 // while those assemblies are initializing.) This is dealt with in the historical manner - namely
5268 // the security system passes in a special flag which says that it will deal with null return values
5269 // in the case where a load cannot be safely completed due to such issues.
5272 void AppDomain::LoadSystemAssemblies()
5274 STANDARD_VM_CONTRACT;
5276 // The only reason to make an assembly a "system assembly" is if the EE is caching
5277 // pointers to stuff in the assembly. Because this is going on, we need to preserve
5278 // the invariant that the assembly is loaded into every app domain.
5280 // Right now we have only one system assembly. We shouldn't need to add any more.
5282 LoadAssembly(NULL, SystemDomain::System()->SystemFile(), FILE_ACTIVE);
5285 FileLoadLevel AppDomain::GetDomainFileLoadLevel(DomainFile *pFile)
5295 LoadLockHolder lock(this);
5297 FileLoadLock* pLockEntry = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5299 if (pLockEntry == NULL)
5300 return pFile->GetLoadLevel();
5302 return pLockEntry->GetLoadLevel();
5305 // This checks if the thread has initiated (or completed) loading at the given level. A false guarantees that
5306 // (a) The current thread (or a thread blocking on the current thread) has not started loading the file
5307 // at the given level, and
5308 // (b) No other thread had started loading the file at this level at the start of this function call.
5310 // Note that another thread may start loading the file at that level in a race with the completion of
5311 // this function. However, the caller still has the guarantee that such a load started after this
5312 // function was called (and e.g. any state in place before the function call will be seen by the other thread.)
5314 // Conversely, a true guarantees that either the current thread has started the load step, or another
5315 // thread has completed the load step.
5318 BOOL AppDomain::IsLoading(DomainFile *pFile, FileLoadLevel level)
5321 if (pFile->GetLoadLevel() < level)
5323 FileLoadLock *pLock = NULL;
5325 LoadLockHolder lock(this);
5327 pLock = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5331 // No thread involved with loading
5332 return pFile->GetLoadLevel() >= level;
5338 FileLoadLockRefHolder lockRef(pLock);
5340 if (pLock->Acquire(level))
5342 // We got the lock - therefore no other thread has started this loading step yet.
5347 // We didn't get the lock - either this thread is already doing the load,
5348 // or else the load has already finished.
5353 // CheckLoading is a weaker form of IsLoading, which will not block on
5354 // other threads waiting for their status. This is appropriate for asserts.
5355 CHECK AppDomain::CheckLoading(DomainFile *pFile, FileLoadLevel level)
5358 if (pFile->GetLoadLevel() < level)
5360 FileLoadLock *pLock = NULL;
5362 LoadLockHolder lock(this);
5364 pLock = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5367 && pLock->CanAcquire(level))
5369 // We can get the lock - therefore no other thread has started this loading step yet.
5370 CHECK_FAILF(("Loading step %d has not been initiated yet", level));
5373 // We didn't get the lock - either this thread is already doing the load,
5374 // or else the load has already finished.
5380 CHECK AppDomain::CheckCanLoadTypes(Assembly *pAssembly)
5389 CHECK_MSG(CheckValidModule(pAssembly->GetManifestModule()),
5390 "Type loading can occur only when executing in the assembly's app domain");
5394 CHECK AppDomain::CheckCanExecuteManagedCode(MethodDesc* pMD)
5404 Module* pModule=pMD->GetModule();
5406 CHECK_MSG(CheckValidModule(pModule),
5407 "Managed code can only run when executing in the module's app domain");
5409 if (!pMD->IsInterface() || pMD->IsStatic()) //interfaces require no activation for instance methods
5411 //cctor could have been interupted by ADU
5412 CHECK_MSG(HasUnloadStarted() || pModule->CheckActivated(),
5413 "Managed code can only run when its module has been activated in the current app domain");
5416 CHECK_MSG(!IsPassiveDomain() || pModule->CanExecuteCode(),
5417 "Executing managed code from an unsafe assembly in a Passive AppDomain");
5422 #endif // !DACCESS_COMPILE
5424 void AppDomain::LoadDomainFile(DomainFile *pFile,
5425 FileLoadLevel targetLevel)
5429 if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
5430 if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
5431 if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM();); }
5432 INJECT_FAULT(COMPlusThrowOM(););
5436 // Quick exit if finished
5437 if (pFile->GetLoadLevel() >= targetLevel)
5440 // Handle the error case
5441 pFile->ThrowIfError(targetLevel);
5444 #ifndef DACCESS_COMPILE
5446 if (pFile->IsLoading())
5450 // Load some more if appropriate
5451 LoadLockHolder lock(this);
5453 FileLoadLock* pLockEntry = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5454 if (pLockEntry == NULL)
5456 _ASSERTE (!pFile->IsLoading());
5460 pLockEntry->AddRef();
5464 LoadDomainFile(pLockEntry, targetLevel);
5467 #else // DACCESS_COMPILE
5469 #endif // DACCESS_COMPILE
5472 #ifndef DACCESS_COMPILE
5474 FileLoadLevel AppDomain::GetThreadFileLoadLevel()
5476 WRAPPER_NO_CONTRACT;
5477 if (GetThread()->GetLoadLevelLimiter() == NULL)
5480 return (FileLoadLevel)(GetThread()->GetLoadLevelLimiter()->GetLoadLevel()-1);
5484 Assembly *AppDomain::LoadAssembly(AssemblySpec* pIdentity,
5486 FileLoadLevel targetLevel)
5488 CONTRACT(Assembly *)
5493 PRECONDITION(CheckPointer(pFile));
5494 POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); // May be NULL in recursive load case
5495 INJECT_FAULT(COMPlusThrowOM(););
5499 DomainAssembly *pAssembly = LoadDomainAssembly(pIdentity, pFile, targetLevel);
5500 PREFIX_ASSUME(pAssembly != NULL);
5502 RETURN pAssembly->GetAssembly();
5505 #ifndef CROSSGEN_COMPILE
5507 class LoadDomainAssemblyStress : APIThreadStress
5511 AssemblySpec* pSpec;
5513 FileLoadLevel targetLevel;
5515 LoadDomainAssemblyStress(AppDomain *pThis, AssemblySpec* pSpec, PEAssembly *pFile, FileLoadLevel targetLevel)
5516 : pThis(pThis), pSpec(pSpec), pFile(pFile), targetLevel(targetLevel) {LIMITED_METHOD_CONTRACT;}
5520 WRAPPER_NO_CONTRACT;
5521 STATIC_CONTRACT_SO_INTOLERANT;
5523 pThis->LoadDomainAssembly(pSpec, pFile, targetLevel);
5526 #endif // CROSSGEN_COMPILE
5528 extern BOOL AreSameBinderInstance(ICLRPrivBinder *pBinderA, ICLRPrivBinder *pBinderB);
5530 DomainAssembly* AppDomain::LoadDomainAssembly( AssemblySpec* pSpec,
5532 FileLoadLevel targetLevel)
5534 STATIC_CONTRACT_THROWS;
5536 if (pSpec == nullptr)
5538 // skip caching, since we don't have anything to base it on
5539 return LoadDomainAssemblyInternal(pSpec, pFile, targetLevel);
5542 DomainAssembly* pRetVal = NULL;
5545 pRetVal = LoadDomainAssemblyInternal(pSpec, pFile, targetLevel);
5549 Exception* pEx=GET_EXCEPTION();
5550 if (!pEx->IsTransient())
5552 // Setup the binder reference in AssemblySpec from the PEAssembly if one is not already set.
5553 ICLRPrivBinder* pCurrentBindingContext = pSpec->GetBindingContext();
5554 ICLRPrivBinder* pBindingContextFromPEAssembly = pFile->GetBindingContext();
5556 if (pCurrentBindingContext == NULL)
5558 // Set the binding context we got from the PEAssembly if AssemblySpec does not
5559 // have that information
5560 _ASSERTE(pBindingContextFromPEAssembly != NULL);
5561 pSpec->SetBindingContext(pBindingContextFromPEAssembly);
5566 // Binding context in the spec should be the same as the binding context in the PEAssembly
5567 _ASSERTE(AreSameBinderInstance(pCurrentBindingContext, pBindingContextFromPEAssembly));
5571 if (!EEFileLoadException::CheckType(pEx))
5574 pSpec->GetFileOrDisplayName(0, name);
5575 pEx=new EEFileLoadException(name, pEx->GetHR(), NULL, pEx);
5576 AddExceptionToCache(pSpec, pEx);
5577 PAL_CPP_THROW(Exception *, pEx);
5580 AddExceptionToCache(pSpec, pEx);
5589 DomainAssembly *AppDomain::LoadDomainAssemblyInternal(AssemblySpec* pIdentity,
5591 FileLoadLevel targetLevel)
5593 CONTRACT(DomainAssembly *)
5598 PRECONDITION(CheckPointer(pFile));
5599 PRECONDITION(pFile->IsSystem() || ::GetAppDomain()==this);
5600 POSTCONDITION(CheckPointer(RETVAL));
5601 POSTCONDITION(RETVAL->GetLoadLevel() >= GetThreadFileLoadLevel()
5602 || RETVAL->GetLoadLevel() >= targetLevel);
5603 POSTCONDITION(RETVAL->CheckNoError(targetLevel));
5604 INJECT_FAULT(COMPlusThrowOM(););
5609 DomainAssembly * result;
5611 #ifndef CROSSGEN_COMPILE
5612 LoadDomainAssemblyStress ts (this, pIdentity, pFile, targetLevel);
5615 // Go into preemptive mode since this may take a while.
5618 // Check for existing fully loaded assembly, or for an assembly which has failed during the loading process.
5619 result = FindAssembly(pFile, FindAssemblyOptions_IncludeFailedToLoad);
5623 // Allocate the DomainAssembly a bit early to avoid GC mode problems. We could potentially avoid
5624 // a rare redundant allocation by moving this closer to FileLoadLock::Create, but it's not worth it.
5626 NewHolder<DomainAssembly> pDomainAssembly;
5627 pDomainAssembly = new DomainAssembly(this, pFile, this->GetLoaderAllocator());
5629 LoadLockHolder lock(this);
5631 // Find the list lock entry
5632 FileLoadLock * fileLock = (FileLoadLock *)lock->FindFileLock(pFile);
5633 if (fileLock == NULL)
5635 // Check again in case we were racing
5636 result = FindAssembly(pFile, FindAssemblyOptions_IncludeFailedToLoad);
5639 // We are the first one in - create the DomainAssembly
5640 fileLock = FileLoadLock::Create(lock, pFile, pDomainAssembly);
5641 pDomainAssembly.SuppressRelease();
5653 // We pass our ref on fileLock to LoadDomainFile to release.
5655 // Note that if we throw here, we will poison fileLock with an error condition,
5656 // so it will not be removed until app domain unload. So there is no need
5657 // to release our ref count.
5658 result = (DomainAssembly *)LoadDomainFile(fileLock, targetLevel);
5662 result->EnsureLoadLevel(targetLevel);
5666 result->EnsureLoadLevel(targetLevel);
5668 // Malformed metadata may contain a Module reference to what is actually
5669 // an Assembly. In this case we need to throw an exception, since returning
5670 // a DomainModule as a DomainAssembly is a type safety violation.
5671 if (!result->IsAssembly())
5673 ThrowHR(COR_E_ASSEMBLYEXPECTED);
5676 // Cache result in all cases, since found pFile could be from a different AssemblyRef than pIdentity
5677 // Do not cache WindowsRuntime assemblies, they are cached in code:CLRPrivTypeCacheWinRT
5678 if ((pIdentity != NULL) && (pIdentity->CanUseWithBindingCache()) && (result->CanUseWithBindingCache()))
5679 GetAppDomain()->AddAssemblyToCache(pIdentity, result);
5682 } // AppDomain::LoadDomainAssembly
5687 FileLoadLock *pLock;
5688 FileLoadLevel targetLevel;
5692 #ifndef CROSSGEN_COMPILE
5693 static void LoadDomainFile_Wrapper(void *ptr)
5695 WRAPPER_NO_CONTRACT;
5696 STATIC_CONTRACT_SO_INTOLERANT;
5698 LoadFileArgs *args = (LoadFileArgs *) ptr;
5699 args->result = GetAppDomain()->LoadDomainFile(args->pLock, args->targetLevel);
5701 #endif // !CROSSGEN_COMPILE
5703 DomainFile *AppDomain::LoadDomainFile(FileLoadLock *pLock, FileLoadLevel targetLevel)
5705 CONTRACT(DomainFile *)
5708 PRECONDITION(CheckPointer(pLock));
5709 PRECONDITION(pLock->GetDomainFile()->GetAppDomain() == this);
5710 POSTCONDITION(RETVAL->GetLoadLevel() >= GetThreadFileLoadLevel()
5711 || RETVAL->GetLoadLevel() >= targetLevel);
5712 POSTCONDITION(RETVAL->CheckNoError(targetLevel));
5718 COMPlusThrow(kAppDomainUnloadedException);
5721 APIThreadStress::SyncThreadStress();
5723 DomainFile *pFile = pLock->GetDomainFile();
5725 // Make sure we release the lock on exit
5726 FileLoadLockRefHolder lockRef(pLock);
5728 // We need to perform the early steps of loading mscorlib without a domain transition. This is
5729 // important for bootstrapping purposes - we need to get mscorlib at least partially loaded
5730 // into a domain before we can run serialization code to do the transition.
5732 // Note that we cannot do this in general for all assemblies, because some of the security computations
5733 // require the managed exposed object, which must be created in the correct app domain.
5735 if (this != GetAppDomain()
5736 && pFile->GetFile()->IsSystem()
5737 && targetLevel > FILE_LOAD_ALLOCATE)
5739 // Re-call the routine with a limited load level. This will cause the first part of the load to
5740 // get performed in the current app domain.
5743 LoadDomainFile(pLock, targetLevel > FILE_LOAD_ALLOCATE ? FILE_LOAD_ALLOCATE : targetLevel);
5745 // Now continue on to complete the rest of the load, if any.
5748 // Do a quick out check for the already loaded case.
5749 if (pLock->GetLoadLevel() >= targetLevel)
5751 pFile->ThrowIfError(targetLevel);
5756 #ifndef CROSSGEN_COMPILE
5757 // Make sure we are in the right domain. Many of the load operations require the target domain
5758 // to be the current app domain, most notably anything involving managed code or managed object
5760 if (this != GetAppDomain()
5761 && (!pFile->GetFile()->IsSystem() || targetLevel > FILE_LOAD_ALLOCATE))
5763 // Transition to the correct app domain and perform the load there.
5766 // we will release the lock in the other app domain
5767 lockRef.SuppressRelease();
5769 if(!CanLoadCode() || GetDefaultContext() ==NULL)
5770 COMPlusThrow(kAppDomainUnloadedException);
5771 LoadFileArgs args = {pLock, targetLevel, NULL};
5772 GetThread()->DoADCallBack(this, LoadDomainFile_Wrapper, (void *) &args, ADV_CREATING);
5776 #endif // CROSSGEN_COMPILE
5778 // Initialize a loading queue. This will hold any loads which are triggered recursively but
5779 // which cannot be immediately satisfied due to anti-deadlock constraints.
5781 // PendingLoadQueues are allocated on the stack during a load, and
5782 // shared with all nested loads on the same thread. (Note that we won't use
5783 // "candidate" if we are in a recursive load; that's OK since they are cheap to
5785 FileLoadLevel immediateTargetLevel = targetLevel;
5787 LoadLevelLimiter limit;
5790 // We cannot set a target level higher than that allowed by the limiter currently.
5791 // This is because of anti-deadlock constraints.
5792 if (immediateTargetLevel > limit.GetLoadLevel())
5793 immediateTargetLevel = limit.GetLoadLevel();
5795 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t>>>Load initiated, %s/%s\n",
5796 pFile->GetAppDomain(), pFile->GetSimpleName(),
5797 fileLoadLevelName[immediateTargetLevel], fileLoadLevelName[targetLevel]));
5799 // Now loop and do the load incrementally to the target level.
5800 if (pLock->GetLoadLevel() < immediateTargetLevel)
5803 APIThreadStress::SyncThreadStress();
5805 while (pLock->Acquire(immediateTargetLevel))
5807 FileLoadLevel workLevel;
5809 FileLoadLockHolder fileLock(pLock);
5811 // Work level is next step to do
5812 workLevel = (FileLoadLevel)(fileLock->GetLoadLevel()+1);
5814 // Set up the anti-deadlock constraint: we cannot safely recursively load any assemblies
5815 // on this thread to a higher level than this assembly is being loaded now.
5816 // Note that we do allow work at a parallel level; any deadlocks caused here will
5817 // be resolved by the deadlock detection in the FileLoadLocks.
5818 limit.SetLoadLevel(workLevel);
5821 (workLevel == FILE_LOAD_BEGIN
5822 || workLevel == FILE_LOADED
5823 || workLevel == FILE_ACTIVE)
5824 ? LL_INFO10 : LL_INFO1000,
5825 "LOADER: %p:***%s*\t loading at level %s\n",
5826 this, pFile->GetSimpleName(), fileLoadLevelName[workLevel]));
5828 TryIncrementalLoad(pFile, workLevel, fileLock);
5830 TESTHOOKCALL(CompletedFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5833 if (pLock->GetLoadLevel() == immediateTargetLevel-1)
5835 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t<<<Load limited due to detected deadlock, %s\n",
5836 pFile->GetAppDomain(), pFile->GetSimpleName(),
5837 fileLoadLevelName[immediateTargetLevel-1]));
5841 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t<<<Load completed, %s\n",
5842 pFile->GetAppDomain(), pFile->GetSimpleName(),
5843 fileLoadLevelName[pLock->GetLoadLevel()]));
5847 // There may have been an error stored on the domain file by another thread, or from a previous load
5848 pFile->ThrowIfError(targetLevel);
5850 // There are two normal results from the above loop.
5852 // 1. We succeeded in loading the file to the current thread's load level.
5853 // 2. We succeeded in loading the file to the current thread's load level - 1, due
5854 // to deadlock condition with another thread loading the same assembly.
5856 // Either of these are considered satisfactory results, as code inside a load must expect
5857 // a parial load result.
5859 // However, if load level elevation has occurred, then it is possible for a deadlock to
5860 // prevent us from loading an assembly which was loading before the elevation at a radically
5861 // lower level. In such a case, we throw an exception which transiently fails the current
5862 // load, since it is likely we have not satisfied the caller.
5863 // (An alternate, and possibly preferable, strategy here would be for all callers to explicitly
5864 // identify the minimum load level acceptable via CheckLoadDomainFile and throw from there.)
5866 pFile->RequireLoadLevel((FileLoadLevel)(immediateTargetLevel-1));
5872 void AppDomain::TryIncrementalLoad(DomainFile *pFile, FileLoadLevel workLevel, FileLoadLockHolder &lockHolder)
5874 STANDARD_VM_CONTRACT;
5876 // This is factored out so we don't call EX_TRY in a loop (EX_TRY can _alloca)
5878 BOOL released = FALSE;
5879 FileLoadLock* pLoadLock = lockHolder.GetValue();
5884 // Special case: for LoadLibrary, we cannot hold the lock during the
5885 // actual LoadLibrary call, because we might get a callback from _CorDllMain on any
5886 // other thread. (Note that this requires DomainFile's LoadLibrary to be independently threadsafe.)
5888 if (workLevel == FILE_LOAD_LOADLIBRARY)
5890 lockHolder.Release();
5895 TESTHOOKCALL(NextFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5896 BOOL success = pFile->DoIncrementalLoad(workLevel);
5897 TESTHOOKCALL(CompletingFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5900 // Reobtain lock to increment level. (Note that another thread may
5901 // have already done it which is OK.
5902 if (pLoadLock->Acquire(workLevel))
5904 // note lockHolder.Acquire isn't wired up to actually take the lock
5905 lockHolder = pLoadLock;
5912 // Complete the level.
5913 if (pLoadLock->CompleteLoadLevel(workLevel, success) &&
5914 pLoadLock->GetLoadLevel()==FILE_LOAD_DELIVER_EVENTS)
5916 lockHolder.Release();
5918 pFile->DeliverAsyncEvents();
5924 Exception *pEx = GET_EXCEPTION();
5927 //We will cache this error and wire this load to forever fail,
5928 // unless the exception is transient or the file is loaded OK but just cannot execute
5929 if (!pEx->IsTransient() && !pFile->IsLoaded())
5934 // Reobtain lock to increment level. (Note that another thread may
5935 // have already done it which is OK.
5936 if (pLoadLock->Acquire(workLevel)) // note pLockHolder->Acquire isn't wired up to actually take the lock
5938 // note lockHolder.Acquire isn't wired up to actually take the lock
5939 lockHolder = pLoadLock;
5946 // Report the error in the lock
5947 pLoadLock->SetError(pEx);
5950 if (!EEFileLoadException::CheckType(pEx))
5951 EEFileLoadException::Throw(pFile->GetFile(), pEx->GetHR(), pEx);
5954 // Otherwise, we simply abort this load, and can retry later on.
5955 // @todo cleanup: make sure that each level is restartable after an exception, and
5956 // leaves no bad side effects
5961 // Checks whether the module is valid to be in the given app domain (need not be yet loaded)
5962 CHECK AppDomain::CheckValidModule(Module * pModule)
5972 if (pModule->FindDomainFile(this) != NULL)
5977 Assembly * pAssembly = pModule->GetAssembly();
5979 CCHECK(pAssembly->IsDomainNeutral());
5980 #ifdef FEATURE_LOADER_OPTIMIZATION
5981 Assembly * pSharedAssembly = NULL;
5982 _ASSERTE(this == ::GetAppDomain());
5984 SharedAssemblyLocator locator(pAssembly->GetManifestFile());
5985 pSharedAssembly = SharedDomain::GetDomain()->FindShareableAssembly(&locator);
5988 CCHECK(pAssembly == pSharedAssembly);
5996 #ifdef FEATURE_LOADER_OPTIMIZATION
5997 // Loads an existing Module into an AppDomain
5998 // WARNING: this can only be done in a very limited scenario - the Module must be an unloaded domain neutral
5999 // dependency in the app domain in question. Normal code should not call this!
6000 DomainFile *AppDomain::LoadDomainNeutralModuleDependency(Module *pModule, FileLoadLevel targetLevel)
6002 CONTRACT(DomainFile *)
6007 PRECONDITION(::GetAppDomain()==this);
6008 PRECONDITION(CheckPointer(pModule));
6009 POSTCONDITION(CheckValidModule(pModule));
6010 POSTCONDITION(CheckPointer(RETVAL));
6011 POSTCONDITION(RETVAL->GetModule() == pModule);
6015 DomainFile *pDomainFile = pModule->FindDomainFile(this);
6017 STRESS_LOG3(LF_CLASSLOADER, LL_INFO100,"LDNMD: DomainFile %p for module %p in AppDomain %i\n",pDomainFile,pModule,GetId().m_dwId);
6019 if (pDomainFile == NULL)
6023 Assembly *pAssembly = pModule->GetAssembly();
6025 DomainAssembly *pDomainAssembly = pAssembly->FindDomainAssembly(this);
6026 if (pDomainAssembly == NULL)
6028 AssemblySpec spec(this);
6029 spec.InitializeSpec(pAssembly->GetManifestFile());
6031 pDomainAssembly = spec.LoadDomainAssembly(targetLevel);
6035 //if the domain assembly already exists, we need to load it to the target level
6036 pDomainAssembly->EnsureLoadLevel (targetLevel);
6039 if(pAssembly != pDomainAssembly->GetAssembly())
6041 ThrowHR(SECURITY_E_INCOMPATIBLE_SHARE);
6044 _ASSERTE (pModule == pAssembly->GetManifestModule());
6045 pDomainFile = pDomainAssembly;
6049 // If the DomainFile already exists, we need to load it to the target level.
6050 pDomainFile->EnsureLoadLevel (targetLevel);
6056 AppDomain::SharePolicy AppDomain::GetSharePolicy()
6058 LIMITED_METHOD_CONTRACT;
6060 return SHARE_POLICY_NEVER;
6062 #endif // FEATURE_LOADER_OPTIMIZATION
6065 void AppDomain::CheckForMismatchedNativeImages(AssemblySpec * pSpec, const GUID * pGuid)
6067 STANDARD_VM_CONTRACT;
6070 // The native images are ever used only for trusted images in CoreCLR.
6071 // We don't wish to open the IL file at runtime so we just forgo any
6072 // eager consistency checking. But we still want to prevent mistmatched
6073 // NGen images from being used. We record all mappings between assembly
6074 // names and MVID, and fail once we detect mismatch.
6077 if (pSpec->IsStrongNamed() && pSpec->HasPublicKey())
6079 pSpec->ConvertPublicKeyToToken();
6083 // CoreCLR binder unifies assembly versions. Ignore assembly version here to
6084 // detect more types of potential mismatches.
6086 AssemblyMetaDataInternal * pContext = pSpec->GetContext();
6087 pContext->usMajorVersion = (USHORT)-1;
6088 pContext->usMinorVersion = (USHORT)-1;
6089 pContext->usBuildNumber = (USHORT)-1;
6090 pContext->usRevisionNumber = (USHORT)-1;
6092 // Ignore the WinRT type while considering if two assemblies have the same identity.
6093 pSpec->SetWindowsRuntimeType(NULL, NULL);
6095 CrstHolder ch(&m_DomainCrst);
6097 const NativeImageDependenciesEntry * pEntry = m_NativeImageDependencies.Lookup(pSpec);
6101 if (*pGuid != pEntry->m_guidMVID)
6104 msg.Printf("ERROR: Native images generated against multiple versions of assembly %s. ", pSpec->GetName());
6105 WszOutputDebugString(msg.GetUnicode());
6106 COMPlusThrowNonLocalized(kFileLoadException, msg.GetUnicode());
6112 // No entry yet - create one
6114 AllocMemTracker amTracker;
6115 AllocMemTracker *pamTracker = &amTracker;
6117 NativeImageDependenciesEntry * pNewEntry =
6118 new (pamTracker->Track(GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(NativeImageDependenciesEntry)))))
6119 NativeImageDependenciesEntry();
6121 pNewEntry->m_AssemblySpec.CopyFrom(pSpec);
6122 pNewEntry->m_AssemblySpec.CloneFieldsToLoaderHeap(AssemblySpec::ALL_OWNED, GetLowFrequencyHeap(), pamTracker);
6124 pNewEntry->m_guidMVID = *pGuid;
6126 m_NativeImageDependencies.Add(pNewEntry);
6127 amTracker.SuppressRelease();
6132 void AppDomain::SetupSharedStatics()
6139 INJECT_FAULT(COMPlusThrowOM(););
6143 #ifndef CROSSGEN_COMPILE
6144 if (NingenEnabled())
6147 LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: SetupSharedStatics()"));
6149 // don't do any work in init stage. If not init only do work in non-shared case if are default domain
6150 _ASSERTE(!g_fEEInit);
6152 // Because we are allocating/referencing objects, need to be in cooperative mode
6155 static OBJECTHANDLE hSharedStaticsHandle = NULL;
6157 if (hSharedStaticsHandle == NULL) {
6158 // Note that there is no race here since the default domain is always set up first
6159 _ASSERTE(IsDefaultDomain());
6161 MethodTable *pMT = MscorlibBinder::GetClass(CLASS__SHARED_STATICS);
6162 _ASSERTE(pMT->IsClassPreInited());
6164 hSharedStaticsHandle = CreateGlobalHandle(AllocateObject(pMT));
6167 DomainLocalModule *pLocalModule;
6169 if (IsSingleAppDomain())
6171 pLocalModule = MscorlibBinder::GetModule()->GetDomainLocalModule();
6175 pLocalModule = GetDomainLocalBlock()->GetModuleSlot(
6176 MscorlibBinder::GetModule()->GetModuleIndex());
6179 FieldDesc *pFD = MscorlibBinder::GetField(FIELD__SHARED_STATICS__SHARED_STATICS);
6181 OBJECTREF* pHandle = (OBJECTREF*)
6182 ((TADDR)pLocalModule->GetPrecomputedGCStaticsBasePointer()+pFD->GetOffset());
6183 SetObjectReference( pHandle, ObjectFromHandle(hSharedStaticsHandle), this );
6185 // This is a convenient place to initialize String.Empty.
6186 // It is treated as intrinsic by the JIT as so the static constructor would never run.
6187 // Leaving it uninitialized would confuse debuggers.
6189 // String should not have any static constructors.
6190 _ASSERTE(g_pStringClass->IsClassPreInited());
6192 FieldDesc * pEmptyStringFD = MscorlibBinder::GetField(FIELD__STRING__EMPTY);
6193 OBJECTREF* pEmptyStringHandle = (OBJECTREF*)
6194 ((TADDR)pLocalModule->GetPrecomputedGCStaticsBasePointer()+pEmptyStringFD->GetOffset());
6195 SetObjectReference( pEmptyStringHandle, StringObject::GetEmptyString(), this );
6196 #endif // CROSSGEN_COMPILE
6199 DomainAssembly * AppDomain::FindAssembly(PEAssembly * pFile, FindAssemblyOptions options/* = FindAssemblyOptions_None*/)
6206 INJECT_FAULT(COMPlusThrowOM(););
6210 const bool includeFailedToLoad = (options & FindAssemblyOptions_IncludeFailedToLoad) != 0;
6212 if (pFile->HasHostAssembly())
6214 DomainAssembly * pDA = FindAssembly(pFile->GetHostAssembly());
6215 if (pDA != nullptr && (pDA->IsLoaded() || (includeFailedToLoad && pDA->IsError())))
6222 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
6224 (includeFailedToLoad ? kIncludeFailedToLoad : 0) |
6225 (pFile->IsIntrospectionOnly() ? kIncludeIntrospection : kIncludeExecution)));
6226 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
6228 while (i.Next(pDomainAssembly.This()))
6230 PEFile * pManifestFile = pDomainAssembly->GetFile();
6231 if (pManifestFile &&
6232 !pManifestFile->IsResource() &&
6233 pManifestFile->Equals(pFile))
6235 // Caller already has PEAssembly, so we can give DomainAssembly away freely without AddRef
6236 return pDomainAssembly.Extract();
6242 static const AssemblyIterationFlags STANDARD_IJW_ITERATOR_FLAGS =
6243 (AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution | kExcludeCollectible);
6246 void AppDomain::SetFriendlyName(LPCWSTR pwzFriendlyName, BOOL fDebuggerCares/*=TRUE*/)
6251 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6253 INJECT_FAULT(COMPlusThrowOM(););
6257 // Do all computations into a temporary until we're ensured of success
6258 SString tmpFriendlyName;
6261 if (pwzFriendlyName)
6262 tmpFriendlyName.Set(pwzFriendlyName);
6265 // If there is an assembly, try to get the name from it.
6266 // If no assembly, but if it's the DefaultDomain, then give it a name
6268 if (m_pRootAssembly)
6270 tmpFriendlyName.SetUTF8(m_pRootAssembly->GetSimpleName());
6272 SString::Iterator i = tmpFriendlyName.End();
6273 if (tmpFriendlyName.FindBack(i, '.'))
6274 tmpFriendlyName.Truncate(i);
6278 if (IsDefaultDomain())
6279 tmpFriendlyName.Set(DEFAULT_DOMAIN_FRIENDLY_NAME);
6281 // This is for the profiler - if they call GetFriendlyName on an AppdomainCreateStarted
6282 // event, then we want to give them a temporary name they can use.
6283 else if (GetId().m_dwId != 0)
6285 tmpFriendlyName.Clear();
6286 tmpFriendlyName.Printf(W("%s %d"), OTHER_DOMAIN_FRIENDLY_NAME_PREFIX, GetId().m_dwId);
6292 tmpFriendlyName.Normalize();
6295 m_friendlyName = tmpFriendlyName;
6296 m_friendlyName.Normalize();
6298 if(g_pDebugInterface)
6300 // update the name in the IPC publishing block
6301 if (SUCCEEDED(g_pDebugInterface->UpdateAppDomainEntryInIPC(this)))
6303 // inform the attached debugger that the name of this appdomain has changed.
6304 if (IsDebuggerAttached() && fDebuggerCares)
6305 g_pDebugInterface->NameChangeEvent(this, NULL);
6310 void AppDomain::ResetFriendlyName(BOOL fDebuggerCares/*=TRUE*/)
6312 WRAPPER_NO_CONTRACT;
6313 SetFriendlyName(NULL, fDebuggerCares);
6316 LPCWSTR AppDomain::GetFriendlyName(BOOL fDebuggerCares/*=TRUE*/)
6321 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6323 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
6324 INJECT_FAULT(COMPlusThrowOM(););
6329 // Handle NULL this pointer - this happens sometimes when printing log messages
6330 // but in general shouldn't occur in real code
6335 if (m_friendlyName.IsEmpty())
6336 SetFriendlyName(NULL, fDebuggerCares);
6338 RETURN m_friendlyName;
6341 LPCWSTR AppDomain::GetFriendlyNameForLogging()
6348 POSTCONDITION(CheckPointer(RETVAL,NULL_OK));
6352 // Handle NULL this pointer - this happens sometimes when printing log messages
6353 // but in general shouldn't occur in real code
6357 RETURN (m_friendlyName.IsEmpty() ?W(""):(LPCWSTR)m_friendlyName);
6360 LPCWSTR AppDomain::GetFriendlyNameForDebugger()
6365 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6367 POSTCONDITION(CheckPointer(RETVAL));
6372 if (m_friendlyName.IsEmpty())
6374 BOOL fSuccess = FALSE;
6378 SetFriendlyName(NULL);
6384 // Gobble all exceptions.
6386 EX_END_CATCH(SwallowAllExceptions);
6394 RETURN m_friendlyName;
6398 #endif // !DACCESS_COMPILE
6400 #ifdef DACCESS_COMPILE
6402 PVOID AppDomain::GetFriendlyNameNoSet(bool* isUtf8)
6406 if (!m_friendlyName.IsEmpty())
6409 return m_friendlyName.DacGetRawContent();
6411 else if (m_pRootAssembly)
6414 return (PVOID)m_pRootAssembly->GetSimpleName();
6416 else if (dac_cast<TADDR>(this) ==
6417 dac_cast<TADDR>(SystemDomain::System()->DefaultDomain()))
6420 return (PVOID)DEFAULT_DOMAIN_FRIENDLY_NAME;
6428 #endif // DACCESS_COMPILE
6430 void AppDomain::CacheStringsForDAC()
6441 // If the application base, private bin paths, and configuration file are
6442 // available, cache them so DAC can read them out of memory
6446 #ifndef DACCESS_COMPILE
6448 BOOL AppDomain::AddFileToCache(AssemblySpec* pSpec, PEAssembly *pFile, BOOL fAllowFailure)
6455 PRECONDITION(CheckPointer(pSpec));
6456 // Hosted fusion binder makes an exception here, so we cannot assert.
6457 //PRECONDITION(pSpec->CanUseWithBindingCache());
6458 //PRECONDITION(pFile->CanUseWithBindingCache());
6459 INJECT_FAULT(COMPlusThrowOM(););
6463 CrstHolder holder(&m_DomainCacheCrst);
6464 // !!! suppress exceptions
6465 if(!m_AssemblyCache.StoreFile(pSpec, pFile) && !fAllowFailure)
6467 // TODO: Disabling the below assertion as currently we experience
6468 // inconsistency on resolving the Microsoft.Office.Interop.MSProject.dll
6469 // This causes below assertion to fire and crashes the VS. This issue
6470 // is being tracked with Dev10 Bug 658555. Brought back it when this bug
6474 EEFileLoadException::Throw(pSpec, FUSION_E_CACHEFILE_FAILED, NULL);
6480 BOOL AppDomain::AddAssemblyToCache(AssemblySpec* pSpec, DomainAssembly *pAssembly)
6487 PRECONDITION(CheckPointer(pSpec));
6488 PRECONDITION(CheckPointer(pAssembly));
6489 PRECONDITION(pSpec->CanUseWithBindingCache());
6490 PRECONDITION(pAssembly->CanUseWithBindingCache());
6491 INJECT_FAULT(COMPlusThrowOM(););
6495 CrstHolder holder(&m_DomainCacheCrst);
6496 // !!! suppress exceptions
6497 BOOL bRetVal = m_AssemblyCache.StoreAssembly(pSpec, pAssembly);
6501 BOOL AppDomain::AddExceptionToCache(AssemblySpec* pSpec, Exception *ex)
6508 PRECONDITION(CheckPointer(pSpec));
6509 PRECONDITION(pSpec->CanUseWithBindingCache());
6510 INJECT_FAULT(COMPlusThrowOM(););
6514 if (ex->IsTransient())
6517 CrstHolder holder(&m_DomainCacheCrst);
6518 // !!! suppress exceptions
6519 return m_AssemblyCache.StoreException(pSpec, ex);
6522 void AppDomain::AddUnmanagedImageToCache(LPCWSTR libraryName, HMODULE hMod)
6529 PRECONDITION(CheckPointer(libraryName));
6530 INJECT_FAULT(COMPlusThrowOM(););
6536 spec.SetCodeBase(libraryName);
6537 m_UnmanagedCache.InsertEntry(&spec, hMod);
6543 HMODULE AppDomain::FindUnmanagedImageInCache(LPCWSTR libraryName)
6550 PRECONDITION(CheckPointer(libraryName,NULL_OK));
6551 POSTCONDITION(CheckPointer(RETVAL,NULL_OK));
6552 INJECT_FAULT(COMPlusThrowOM(););
6555 if(libraryName == NULL) RETURN NULL;
6558 spec.SetCodeBase(libraryName);
6559 RETURN (HMODULE) m_UnmanagedCache.LookupEntry(&spec, 0);
6563 BOOL AppDomain::IsCached(AssemblySpec *pSpec)
6565 WRAPPER_NO_CONTRACT;
6567 // Check to see if this fits our rather loose idea of a reference to mscorlib.
6568 // If so, don't use fusion to bind it - do it ourselves.
6569 if (pSpec->IsMscorlib())
6572 return m_AssemblyCache.Contains(pSpec);
6575 void AppDomain::GetCacheAssemblyList(SetSHash<PTR_DomainAssembly>& assemblyList)
6577 CrstHolder holder(&m_DomainCacheCrst);
6578 m_AssemblyCache.GetAllAssemblies(assemblyList);
6581 PEAssembly* AppDomain::FindCachedFile(AssemblySpec* pSpec, BOOL fThrow /*=TRUE*/)
6597 // Check to see if this fits our rather loose idea of a reference to mscorlib.
6598 // If so, don't use fusion to bind it - do it ourselves.
6599 if (fThrow && pSpec->IsMscorlib())
6601 CONSISTENCY_CHECK(SystemDomain::System()->SystemAssembly() != NULL);
6602 PEAssembly *pFile = SystemDomain::System()->SystemFile();
6607 return m_AssemblyCache.LookupFile(pSpec, fThrow);
6611 BOOL AppDomain::PostBindResolveAssembly(AssemblySpec *pPrePolicySpec,
6612 AssemblySpec *pPostPolicySpec,
6613 HRESULT hrBindResult,
6614 AssemblySpec **ppFailedSpec)
6616 STATIC_CONTRACT_THROWS;
6617 STATIC_CONTRACT_GC_TRIGGERS;
6618 PRECONDITION(CheckPointer(pPrePolicySpec));
6619 PRECONDITION(CheckPointer(pPostPolicySpec));
6620 PRECONDITION(CheckPointer(ppFailedSpec));
6622 BOOL fFailure = TRUE;
6623 *ppFailedSpec = pPrePolicySpec;
6626 PEAssemblyHolder result;
6628 if ((EEFileLoadException::GetFileLoadKind(hrBindResult) == kFileNotFoundException) ||
6629 (hrBindResult == FUSION_E_REF_DEF_MISMATCH) ||
6630 (hrBindResult == FUSION_E_INVALID_NAME))
6632 result = TryResolveAssembly(*ppFailedSpec, FALSE /* fPreBind */);
6634 if (result != NULL && pPrePolicySpec->CanUseWithBindingCache() && result->CanUseWithBindingCache())
6638 // Given the post-policy resolve event construction of the CLR binder,
6639 // chained managed resolve events can race with each other, therefore we do allow
6640 // the adding of the result to fail. Checking for already chached specs
6641 // is not an option as it would introduce another race window.
6642 // The binder does a re-fetch of the
6643 // orignal binding spec and therefore will not cause inconsistency here.
6644 // For the purposes of the resolve event, failure to add to the cache still is a success.
6645 AddFileToCache(pPrePolicySpec, result, TRUE /* fAllowFailure */);
6646 if (*ppFailedSpec != pPrePolicySpec && pPostPolicySpec->CanUseWithBindingCache())
6648 AddFileToCache(pPostPolicySpec, result, TRUE /* fAllowFailure */ );
6656 //----------------------------------------------------------------------------------------
6657 // Helper class for hosted binder
6659 class PEAssemblyAsPrivAssemblyInfo : public IUnknownCommon<ICLRPrivAssemblyInfo>
6662 //------------------------------------------------------------------------------------
6665 PEAssemblyAsPrivAssemblyInfo(PEAssembly *pPEAssembly)
6667 LIMITED_METHOD_CONTRACT;
6668 STATIC_CONTRACT_THROWS;
6670 if (pPEAssembly == nullptr)
6671 ThrowHR(E_UNEXPECTED);
6673 pPEAssembly->AddRef();
6674 m_pPEAssembly = pPEAssembly;
6677 //------------------------------------------------------------------------------------
6678 // ICLRPrivAssemblyInfo methods
6680 //------------------------------------------------------------------------------------
6681 STDMETHOD(GetAssemblyName)(
6682 __in DWORD cchBuffer,
6683 __out_opt LPDWORD pcchBuffer,
6684 __out_ecount_part_opt(cchBuffer, *pcchBuffer) LPWSTR wzBuffer)
6696 if ((cchBuffer == 0) != (wzBuffer == nullptr))
6698 return E_INVALIDARG;
6701 LPCUTF8 szName = m_pPEAssembly->GetSimpleName();
6705 IfFailRet(FString::Utf8_Unicode_Length(szName, &bIsAscii, &cchName));
6707 if (cchBuffer < cchName + 1)
6709 if (pcchBuffer != nullptr)
6711 *pcchBuffer = cchName + 1;
6713 return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
6717 IfFailRet(FString::Utf8_Unicode(szName, bIsAscii, wzBuffer, cchName));
6718 if (pcchBuffer != nullptr)
6720 *pcchBuffer = cchName;
6726 //------------------------------------------------------------------------------------
6727 STDMETHOD(GetAssemblyVersion)(
6733 WRAPPER_NO_CONTRACT;
6734 return m_pPEAssembly->GetVersion(pMajor, pMinor, pBuild, pRevision);
6737 //------------------------------------------------------------------------------------
6738 STDMETHOD(GetAssemblyPublicKey)(
6743 STATIC_CONTRACT_LIMITED_METHOD;
6744 STATIC_CONTRACT_CAN_TAKE_LOCK;
6746 VALIDATE_PTR_RET(pcbBuffer);
6747 VALIDATE_CONDITION((pbBuffer == nullptr) == (cbBuffer == 0), return E_INVALIDARG);
6753 // Note: PEAssembly::GetPublicKey will return bogus data pointer when *pcbBuffer == 0
6754 LPCVOID pbKey = m_pPEAssembly->GetPublicKey(pcbBuffer);
6756 if (*pcbBuffer != 0)
6758 if (pbBuffer != nullptr && cbBuffer >= *pcbBuffer)
6760 memcpy(pbBuffer, pbKey, *pcbBuffer);
6765 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
6770 hr = S_FALSE; // ==> No public key
6773 EX_CATCH_HRESULT(hr);
6779 ReleaseHolder<PEAssembly> m_pPEAssembly;
6782 //-----------------------------------------------------------------------------------------------------------------
6783 static HRESULT VerifyBindHelper(
6784 ICLRPrivAssembly *pPrivAssembly,
6785 IAssemblyName *pAssemblyName,
6786 PEAssembly *pPEAssembly)
6788 STATIC_CONTRACT_THROWS;
6789 STATIC_CONTRACT_GC_TRIGGERS;
6792 // Create an ICLRPrivAssemblyInfo to call to ICLRPrivAssembly::VerifyBind
6793 NewHolder<PEAssemblyAsPrivAssemblyInfo> pPrivAssemblyInfoImpl = new PEAssemblyAsPrivAssemblyInfo(pPEAssembly);
6794 ReleaseHolder<ICLRPrivAssemblyInfo> pPrivAssemblyInfo;
6795 IfFailRet(pPrivAssemblyInfoImpl->QueryInterface(__uuidof(ICLRPrivAssemblyInfo), (LPVOID *)&pPrivAssemblyInfo));
6796 pPrivAssemblyInfoImpl.SuppressRelease();
6798 // Call VerifyBind to give the host a chance to reject the bind based on assembly image contents.
6799 IfFailRet(pPrivAssembly->VerifyBind(pAssemblyName, pPrivAssembly, pPrivAssemblyInfo));
6804 //-----------------------------------------------------------------------------------------------------------------
6805 HRESULT AppDomain::BindAssemblySpecForHostedBinder(
6806 AssemblySpec * pSpec,
6807 IAssemblyName * pAssemblyName,
6808 ICLRPrivBinder * pBinder,
6809 PEAssembly ** ppAssembly)
6811 STANDARD_VM_CONTRACT;
6813 PRECONDITION(CheckPointer(pSpec));
6814 PRECONDITION(pSpec->GetAppDomain() == this);
6815 PRECONDITION(CheckPointer(ppAssembly));
6816 PRECONDITION(pSpec->GetCodeBase() == nullptr);
6821 // The Fusion binder can throw (to preserve compat, since it will actually perform an assembly
6822 // load as part of it's bind), so we need to be careful here to catch any FileNotFoundException
6823 // objects if fThrowIfNotFound is false.
6824 ReleaseHolder<ICLRPrivAssembly> pPrivAssembly;
6826 // We return HRESULTs here on failure instead of throwing as failures here are not necessarily indicative
6827 // of an actual application problem. Returning an error code is substantially faster than throwing, and
6828 // should be used when possible.
6829 IfFailRet(pBinder->BindAssemblyByName(pAssemblyName, &pPrivAssembly));
6831 IfFailRet(BindHostedPrivAssembly(nullptr, pPrivAssembly, pAssemblyName, ppAssembly));
6837 //-----------------------------------------------------------------------------------------------------------------
6839 AppDomain::BindHostedPrivAssembly(
6840 PEAssembly * pParentAssembly,
6841 ICLRPrivAssembly * pPrivAssembly,
6842 IAssemblyName * pAssemblyName,
6843 PEAssembly ** ppAssembly,
6844 BOOL fIsIntrospectionOnly) // = FALSE
6846 STANDARD_VM_CONTRACT;
6848 PRECONDITION(CheckPointer(pPrivAssembly));
6849 PRECONDITION(CheckPointer(ppAssembly));
6853 *ppAssembly = nullptr;
6855 // See if result has been previously loaded.
6857 DomainAssembly* pDomainAssembly = FindAssembly(pPrivAssembly);
6858 if (pDomainAssembly != nullptr)
6860 *ppAssembly = clr::SafeAddRef(pDomainAssembly->GetFile());
6864 if (*ppAssembly != nullptr)
6865 { // Already exists: ask the binder to verify and return the assembly.
6866 return VerifyBindHelper(pPrivAssembly, pAssemblyName, *ppAssembly);
6869 // Get the IL PEFile.
6870 PEImageHolder pPEImageIL;
6872 // Does not already exist, so get the resource for the assembly and load it.
6874 ReleaseHolder<ICLRPrivResource> pIResourceIL;
6876 IfFailRet(pPrivAssembly->GetImageResource(ASSEMBLY_IMAGE_TYPE_IL, &dwImageType, &pIResourceIL));
6877 _ASSERTE(dwImageType == ASSEMBLY_IMAGE_TYPE_IL);
6879 pPEImageIL = PEImage::OpenImage(pIResourceIL, MDInternalImport_Default);
6882 // See if an NI is available.
6883 DWORD dwAvailableImages;
6884 IfFailRet(pPrivAssembly->GetAvailableImageTypes(&dwAvailableImages));
6885 _ASSERTE(dwAvailableImages & ASSEMBLY_IMAGE_TYPE_IL); // Just double checking that IL bit is always set.
6887 // Get the NI PEFile if available.
6888 PEImageHolder pPEImageNI;
6889 if (dwAvailableImages & ASSEMBLY_IMAGE_TYPE_NATIVE)
6892 ReleaseHolder<ICLRPrivResource> pIResourceNI;
6894 IfFailRet(pPrivAssembly->GetImageResource(ASSEMBLY_IMAGE_TYPE_NATIVE, &dwImageType, &pIResourceNI));
6895 _ASSERTE(dwImageType == ASSEMBLY_IMAGE_TYPE_NATIVE || FAILED(hr));
6897 pPEImageNI = PEImage::OpenImage(pIResourceNI, MDInternalImport_TrustedNativeImage);
6899 _ASSERTE(pPEImageIL != nullptr);
6901 // Create a PEAssembly using the IL and NI images.
6902 PEAssemblyHolder pPEAssembly = PEAssembly::Open(pParentAssembly, pPEImageIL, pPEImageNI, pPrivAssembly, fIsIntrospectionOnly);
6905 // Ask the binder to verify.
6906 IfFailRet(VerifyBindHelper(pPrivAssembly, pAssemblyName, pPEAssembly));
6909 *ppAssembly = pPEAssembly.Extract();
6912 } // AppDomain::BindHostedPrivAssembly
6914 //---------------------------------------------------------------------------------------------------------------------
6915 PEAssembly * AppDomain::BindAssemblySpec(
6916 AssemblySpec * pSpec,
6917 BOOL fThrowOnFileNotFound,
6918 BOOL fRaisePrebindEvents,
6919 StackCrawlMark * pCallerStackMark,
6920 BOOL fUseHostBinderIfAvailable)
6922 STATIC_CONTRACT_THROWS;
6923 STATIC_CONTRACT_GC_TRIGGERS;
6924 PRECONDITION(CheckPointer(pSpec));
6925 PRECONDITION(pSpec->GetAppDomain() == this);
6926 PRECONDITION(this==::GetAppDomain());
6930 BOOL fForceReThrow = FALSE;
6932 #if defined(FEATURE_COMINTEROP)
6933 // Handle WinRT assemblies in the classic/hybrid scenario. If this is an AppX process,
6934 // then this case will be handled by the previous block as part of the full set of
6935 // available binding hosts.
6936 if (pSpec->IsContentType_WindowsRuntime())
6940 // Get the assembly display name.
6941 ReleaseHolder<IAssemblyName> pAssemblyName;
6943 IfFailThrow(pSpec->CreateFusionName(&pAssemblyName, TRUE, TRUE));
6946 PEAssemblyHolder pAssembly;
6950 hr = BindAssemblySpecForHostedBinder(pSpec, pAssemblyName, m_pWinRtBinder, &pAssembly);
6952 goto EndTry2; // Goto end of try block.
6955 // The combination of this conditional catch/ the following if statement which will throw reduces the count of exceptions
6956 // thrown in scenarios where the exception does not escape the method. We cannot get rid of the try/catch block, as
6957 // there are cases within some of the clrpriv binder's which throw.
6958 // Note: In theory, FileNotFound should always come here as HRESULT, never as exception.
6959 EX_CATCH_HRESULT_IF(hr,
6960 !fThrowOnFileNotFound && Assembly::FileNotFound(hr))
6962 if (FAILED(hr) && (fThrowOnFileNotFound || !Assembly::FileNotFound(hr)))
6964 if (Assembly::FileNotFound(hr))
6966 _ASSERTE(fThrowOnFileNotFound);
6967 // Uses defaultScope
6968 EEFileLoadException::Throw(pSpec, hr);
6971 // WinRT type bind failures
6972 _ASSERTE(pSpec->IsContentType_WindowsRuntime());
6973 if (hr == HRESULT_FROM_WIN32(APPMODEL_ERROR_NO_PACKAGE)) // Returned by RoResolveNamespace when using 3rd party WinRT types in classic process
6975 if (fThrowOnFileNotFound)
6976 { // Throw NotSupportedException (with custom message) wrapped by TypeLoadException to give user type name for diagnostics
6977 // Note: TypeLoadException is equivalent of FileNotFound in WinRT world
6978 EEMessageException ex(kNotSupportedException, IDS_EE_WINRT_THIRDPARTY_NOTSUPPORTED);
6979 EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex);
6982 else if ((hr == CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT) || // Returned e.g. for WinRT type name without namespace
6983 (hr == COR_E_PLATFORMNOTSUPPORTED)) // Using WinRT on pre-Win8 OS
6985 if (fThrowOnFileNotFound)
6986 { // Throw ArgumentException/PlatformNotSupportedException wrapped by TypeLoadException to give user type name for diagnostics
6987 // Note: TypeLoadException is equivalent of FileNotFound in WinRT world
6988 EEMessageException ex(hr);
6989 EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex);
6997 _ASSERTE((FAILED(hr) && !fThrowOnFileNotFound) || pAssembly != nullptr);
6999 return pAssembly.Extract();
7002 #endif // FEATURE_COMINTEROP
7003 if (pSpec->HasUniqueIdentity())
7005 HRESULT hrBindResult = S_OK;
7006 PEAssemblyHolder result;
7011 if (!IsCached(pSpec))
7015 bool fAddFileToCache = false;
7017 BOOL fIsWellKnown = FALSE;
7019 // Use CoreClr's fusion alternative
7020 CoreBindResult bindResult;
7022 pSpec->Bind(this, fThrowOnFileNotFound, &bindResult, FALSE /* fNgenExplicitBind */, FALSE /* fExplicitBindToNativeImage */, pCallerStackMark);
7023 hrBindResult = bindResult.GetHRBindResult();
7025 if (bindResult.Found())
7027 if (SystemDomain::SystemFile() && bindResult.IsMscorlib())
7029 // Avoid rebinding to another copy of mscorlib
7030 result = SystemDomain::SystemFile();
7031 result.SuppressRelease(); // Didn't get a refcount
7035 // IsSystem on the PEFile should be false, even for mscorlib satellites
7036 result = PEAssembly::Open(&bindResult,
7037 FALSE, pSpec->IsIntrospectionOnly());
7039 fAddFileToCache = true;
7041 // Setup the reference to the binder, which performed the bind, into the AssemblySpec
7042 ICLRPrivBinder* pBinder = result->GetBindingContext();
7043 _ASSERTE(pBinder != NULL);
7044 pSpec->SetBindingContext(pBinder);
7048 if (fAddFileToCache)
7052 if (pSpec->CanUseWithBindingCache() && result->CanUseWithBindingCache())
7054 // Failure to add simply means someone else beat us to it. In that case
7055 // the FindCachedFile call below (after catch block) will update result
7056 // to the cached value.
7057 AddFileToCache(pSpec, result, TRUE /*fAllowFailure*/);
7060 else if (!fIsWellKnown)
7062 _ASSERTE(fThrowOnFileNotFound == FALSE);
7064 // Don't trigger the resolve event for the CoreLib satellite assembly. A misbehaving resolve event may
7065 // return an assembly that does not match, and this can cause recursive resource lookups during error
7066 // reporting. The CoreLib satellite assembly is loaded from relative locations based on the culture, see
7067 // AssemblySpec::Bind().
7068 if (!pSpec->IsMscorlibSatellite())
7070 // Trigger the resolve event also for non-throw situation.
7071 // However, this code path will behave as if the resolve handler has thrown,
7072 // that is, not trigger an MDA.
7074 AssemblySpec NewSpec(this);
7075 AssemblySpec *pFailedSpec = NULL;
7077 fForceReThrow = TRUE; // Managed resolve event handler can throw
7079 // Purposly ignore return value
7080 PostBindResolveAssembly(pSpec, &NewSpec, hrBindResult, &pFailedSpec);
7088 Exception *ex = GET_EXCEPTION();
7090 AssemblySpec NewSpec(this);
7091 AssemblySpec *pFailedSpec = NULL;
7093 // Let transient exceptions or managed resolve event handler exceptions propagate
7094 if (ex->IsTransient() || fForceReThrow)
7100 // This is not executed for SO exceptions so we need to disable the backout
7101 // stack validation to prevent false violations from being reported.
7102 DISABLE_BACKOUT_STACK_VALIDATION;
7104 BOOL fFailure = PostBindResolveAssembly(pSpec, &NewSpec, ex->GetHR(), &pFailedSpec);
7107 BOOL bFileNotFoundException =
7108 (EEFileLoadException::GetFileLoadKind(ex->GetHR()) == kFileNotFoundException);
7110 if (!bFileNotFoundException)
7112 fFailure = AddExceptionToCache(pFailedSpec, ex);
7113 } // else, fFailure stays TRUE
7114 // Effectively, fFailure == bFileNotFoundException || AddExceptionToCache(pFailedSpec, ex)
7116 // Only throw this exception if we are the first in the cache
7120 // If the BindingFailure MDA is enabled, trigger one for this failure
7121 // Note: TryResolveAssembly() can also throw if an AssemblyResolve event subscriber throws
7122 // and the MDA isn't sent in this case (or for transient failure cases)
7124 #ifdef MDA_SUPPORTED
7125 MdaBindingFailure* pProbe = MDA_GET_ASSISTANT(BindingFailure);
7128 // Transition to cooperative GC mode before using any OBJECTREFs.
7131 OBJECTREF exceptionObj = GET_THROWABLE();
7132 GCPROTECT_BEGIN(exceptionObj)
7134 pProbe->BindFailed(pFailedSpec, &exceptionObj);
7140 // In the same cases as for the MDA, store the failure information for DAC to read
7141 if (IsDebuggerAttached()) {
7142 FailedAssembly *pFailed = new FailedAssembly();
7143 pFailed->Initialize(pFailedSpec, ex);
7144 IfFailThrow(m_failedAssemblies.Append(pFailed));
7147 if (!bFileNotFoundException || fThrowOnFileNotFound)
7150 // V1.1 App-compatibility workaround. See VSW530166 if you want to whine about it.
7152 // In Everett, if we failed to download an assembly because of a broken network cable,
7153 // we returned a FileNotFoundException with a COR_E_FILENOTFOUND hr embedded inside
7154 // (which would be exposed when marshaled to native.)
7156 // In Whidbey, we now set the more appropriate INET_E_RESOURCE_NOT_FOUND hr. But
7157 // the online/offline switch code in VSTO for Everett hardcoded a check for
7158 // COR_E_FILENOTFOUND.
7160 // So now, to keep that code from breaking, we have to remap INET_E_RESOURCE_NOT_FOUND
7161 // back to COR_E_FILENOTFOUND. We're doing it here rather down in Fusion so as to affect
7162 // the least number of callers.
7164 if (ex->GetHR() == INET_E_RESOURCE_NOT_FOUND)
7166 EEFileLoadException::Throw(pFailedSpec, COR_E_FILENOTFOUND, ex);
7169 if (EEFileLoadException::CheckType(ex))
7171 if (pFailedSpec == pSpec)
7173 EX_RETHROW; //preserve the information
7177 StackSString exceptionDisplayName, failedSpecDisplayName;
7179 ((EEFileLoadException*)ex)->GetName(exceptionDisplayName);
7180 pFailedSpec->GetFileOrDisplayName(0, failedSpecDisplayName);
7182 if (exceptionDisplayName.CompareCaseInsensitive(failedSpecDisplayName) == 0)
7184 EX_RETHROW; // Throw the original exception. Otherwise, we'd throw an exception that contains the same message twice.
7189 EEFileLoadException::Throw(pFailedSpec, ex->GetHR(), ex);
7196 EX_END_CATCH(RethrowTerminalExceptions);
7198 // 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
7199 // thread to store our result. Note that we may throw from here, if there is a cached exception.
7200 // This will release the refcount of the current result holder (if any), and will replace
7201 // it with a non-addref'ed result
7202 if (pSpec->CanUseWithBindingCache() && (result== NULL || result->CanUseWithBindingCache()))
7204 result = FindCachedFile(pSpec);
7210 return result.Extract();
7214 // Unsupported content type
7215 if (fThrowOnFileNotFound)
7217 ThrowHR(COR_E_BADIMAGEFORMAT);
7221 } // AppDomain::BindAssemblySpec
7225 PEAssembly *AppDomain::TryResolveAssembly(AssemblySpec *pSpec, BOOL fPreBind)
7227 STATIC_CONTRACT_THROWS;
7228 STATIC_CONTRACT_GC_TRIGGERS;
7229 STATIC_CONTRACT_MODE_ANY;
7231 PEAssembly *result = NULL;
7235 result = pSpec->ResolveAssemblyFile(this, fPreBind);
7239 Exception *pEx = GET_EXCEPTION();
7241 if (!pEx->IsTransient())
7243 AddExceptionToCache(pSpec, pEx);
7244 if (!EEFileLoadException::CheckType(pEx))
7245 EEFileLoadException::Throw(pSpec, pEx->GetHR(), pEx);
7254 ULONG AppDomain::AddRef()
7256 LIMITED_METHOD_CONTRACT;
7257 return InterlockedIncrement(&m_cRef);
7260 ULONG AppDomain::Release()
7267 PRECONDITION(m_cRef > 0);
7271 ULONG cRef = InterlockedDecrement(&m_cRef);
7274 _ASSERTE (m_Stage == STAGE_CREATING || m_Stage == STAGE_CLOSED);
7277 TESTHOOKCALL(AppDomainDestroyed(adid.m_dwId));
7283 AppDomain* AppDomain::s_pAppDomainToRaiseUnloadEvent;
7284 BOOL AppDomain::s_fProcessUnloadDomainEvent = FALSE;
7286 #ifndef CROSSGEN_COMPILE
7288 void AppDomain::RaiseUnloadDomainEvent_Wrapper(LPVOID ptr)
7295 INJECT_FAULT(COMPlusThrowOM(););
7300 AppDomain* pDomain = (AppDomain *) ptr;
7301 pDomain->RaiseUnloadDomainEvent();
7304 void AppDomain::ProcessUnloadDomainEventOnFinalizeThread()
7313 Thread *pThread = GetThread();
7314 _ASSERTE (pThread && IsFinalizerThread());
7316 // if we are not unloading domain now, do not process the event
7317 if (SystemDomain::AppDomainBeingUnloaded() == NULL)
7319 s_pAppDomainToRaiseUnloadEvent->SetStage(STAGE_UNLOAD_REQUESTED);
7320 s_pAppDomainToRaiseUnloadEvent->EnableADUnloadWorker(
7321 s_pAppDomainToRaiseUnloadEvent->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7322 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, NULL);
7325 FastInterlockExchange((LONG*)&s_fProcessUnloadDomainEvent, TRUE);
7326 AppDomain::EnableADUnloadWorkerForFinalizer();
7327 pThread->SetThreadStateNC(Thread::TSNC_RaiseUnloadEvent);
7328 s_pAppDomainToRaiseUnloadEvent->RaiseUnloadDomainEvent();
7329 pThread->ResetThreadStateNC(Thread::TSNC_RaiseUnloadEvent);
7330 s_pAppDomainToRaiseUnloadEvent->EnableADUnloadWorker(
7331 s_pAppDomainToRaiseUnloadEvent->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7332 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, NULL);
7333 FastInterlockExchange((LONG*)&s_fProcessUnloadDomainEvent, FALSE);
7335 if (pThread->IsAbortRequested())
7337 pThread->UnmarkThreadForAbort(Thread::TAR_Thread);
7341 void AppDomain::RaiseUnloadDomainEvent()
7352 Thread *pThread = GetThread();
7353 if (this != pThread->GetDomain())
7355 pThread->DoADCallBack(this, AppDomain::RaiseUnloadDomainEvent_Wrapper, this,ADV_FINALIZER|ADV_COMPILATION);
7361 APPDOMAINREF Domain;
7364 ZeroMemory(&gc, sizeof(gc));
7366 GCPROTECT_BEGIN(gc);
7367 gc.Domain = (APPDOMAINREF) GetRawExposedObject();
7368 if (gc.Domain != NULL)
7370 gc.Delegate = gc.Domain->m_pDomainUnloadEventHandler;
7371 if (gc.Delegate != NULL)
7372 DistributeEvent(&gc.Delegate, (OBJECTREF *) &gc.Domain);
7378 void AppDomain::RaiseLoadingAssemblyEvent(DomainAssembly *pAssembly)
7384 PRECONDITION(this == GetAppDomain());
7391 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
7396 APPDOMAINREF AppDomainRef;
7399 ZeroMemory(&gc, sizeof(gc));
7401 if ((gc.AppDomainRef = (APPDOMAINREF) GetRawExposedObject()) != NULL) {
7402 if (gc.AppDomainRef->m_pAssemblyEventHandler != NULL)
7405 GCPROTECT_BEGIN(gc);
7407 gc.orThis = pAssembly->GetExposedAssemblyObject();
7409 MethodDescCallSite onAssemblyLoad(METHOD__APP_DOMAIN__ON_ASSEMBLY_LOAD, &gc.orThis);
7411 // GetExposedAssemblyObject may cause a gc, so call this before filling args[0]
7412 args[1] = ObjToArgSlot(gc.orThis);
7413 args[0] = ObjToArgSlot(gc.AppDomainRef);
7415 onAssemblyLoad.Call(args);
7424 EX_END_CATCH(SwallowAllExceptions);
7428 BOOL AppDomain::OnUnhandledException(OBJECTREF *pThrowable, BOOL isTerminating/*=TRUE*/)
7430 STATIC_CONTRACT_NOTHROW;
7431 STATIC_CONTRACT_GC_TRIGGERS;
7432 STATIC_CONTRACT_MODE_ANY;
7438 // The Everett behavior was to send the unhandled exception event only to the Default
7439 // AppDomain (since that's the only place that exceptions actually went unhandled).
7441 // During Whidbey development, we broadcast the event to all AppDomains in the process.
7443 // But the official shipping Whidbey behavior is that the unhandled exception event is
7444 // sent to the Default AppDomain and to whatever AppDomain the exception went unhandled
7445 // in. To achieve this, we declare the exception to be unhandled *BEFORE* we marshal
7446 // it back to the Default AppDomain at the base of the Finalizer, threadpool and managed
7449 // The rationale for sending the event to the Default AppDomain as well as the one the
7450 // exception went unhandled in is:
7452 // 1) This is compatible with the pre-Whidbey behavior, where only the Default AppDomain
7453 // received the notification.
7455 // 2) This is convenient for hosts, which don't want to bother injecting listeners into
7456 // every single AppDomain.
7458 AppDomain *pAppDomain = GetAppDomain();
7459 OBJECTREF orSender = 0;
7461 GCPROTECT_BEGIN(orSender);
7463 orSender = pAppDomain->GetRawExposedObject();
7465 retVal = pAppDomain->RaiseUnhandledExceptionEventNoThrow(&orSender, pThrowable, isTerminating);
7473 // Move outside of the AppDomain iteration, to avoid issues with the GC Frames being outside
7474 // the domain transition. This is a chronic issue that causes us to report roots for an AppDomain
7475 // after we have left it. This causes problems with AppDomain unloading that we only find
7476 // with stress coverage..
7477 void AppDomain::RaiseOneExitProcessEvent()
7489 APPDOMAINREF Domain;
7492 ZeroMemory(&gc, sizeof(gc));
7494 GCPROTECT_BEGIN(gc);
7495 gc.Domain = (APPDOMAINREF) SystemDomain::GetCurrentDomain()->GetRawExposedObject();
7496 if (gc.Domain != NULL)
7498 gc.Delegate = gc.Domain->m_pProcessExitEventHandler;
7499 if (gc.Delegate != NULL)
7500 DistributeEvent(&gc.Delegate, (OBJECTREF *) &gc.Domain);
7505 // Local wrapper used in AppDomain::RaiseExitProcessEvent,
7506 // introduced solely to avoid stack overflow because of _alloca in the loop.
7507 // It's just factored out body of the loop, but it has to be a member method of AppDomain,
7508 // because it calls private RaiseOneExitProcessEvent
7509 /*static*/ void AppDomain::RaiseOneExitProcessEvent_Wrapper(AppDomainIterator* pi)
7511 STATIC_CONTRACT_MODE_COOPERATIVE;
7512 STATIC_CONTRACT_THROWS;
7513 STATIC_CONTRACT_GC_TRIGGERS;
7515 ENTER_DOMAIN_PTR(pi->GetDomain(), ADV_ITERATOR)
7516 AppDomain::RaiseOneExitProcessEvent();
7517 END_DOMAIN_TRANSITION;
7520 static LONG s_ProcessedExitProcessEventCount = 0;
7522 LONG GetProcessedExitProcessEventCount()
7524 LIMITED_METHOD_CONTRACT;
7525 return s_ProcessedExitProcessEventCount;
7528 void AppDomain::RaiseExitProcessEvent()
7533 STATIC_CONTRACT_MODE_COOPERATIVE;
7534 STATIC_CONTRACT_THROWS;
7535 STATIC_CONTRACT_GC_TRIGGERS;
7537 // Only finalizer thread during shutdown can call this function.
7538 _ASSERTE ((g_fEEShutDown&ShutDown_Finalize1) && GetThread() == FinalizerThread::GetFinalizerThread());
7540 _ASSERTE (GetThread()->PreemptiveGCDisabled());
7542 _ASSERTE (GetThread()->GetDomain()->IsDefaultDomain());
7544 AppDomainIterator i(TRUE);
7547 RaiseOneExitProcessEvent_Wrapper(&i);
7548 FastInterlockIncrement(&s_ProcessedExitProcessEventCount);
7554 AppDomain::RaiseUnhandledExceptionEventNoThrow(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating)
7567 bRetVal = RaiseUnhandledExceptionEvent(pSender, pThrowable, isTerminating);
7572 EX_END_CATCH(SwallowAllExceptions) // Swallow any errors.
7578 AppDomain::HasUnhandledExceptionEventHandler()
7583 GC_NOTRIGGER; //essential
7587 if (!CanThreadEnter(GetThread()))
7589 if (GetRawExposedObject()==NULL)
7591 return (((APPDOMAINREF)GetRawExposedObject())->m_pUnhandledExceptionEventHandler!=NULL);
7595 AppDomain::RaiseUnhandledExceptionEvent(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating)
7602 INJECT_FAULT(COMPlusThrowOM(););
7606 if (!HasUnhandledExceptionEventHandler())
7609 BOOL result = FALSE;
7611 _ASSERTE(pThrowable != NULL && IsProtectedByGCFrame(pThrowable));
7612 _ASSERTE(pSender != NULL && IsProtectedByGCFrame(pSender));
7614 _ASSERTE(this == GetThread()->GetDomain());
7617 OBJECTREF orDelegate = NULL;
7619 GCPROTECT_BEGIN(orDelegate);
7621 APPDOMAINREF orAD = (APPDOMAINREF) GetAppDomain()->GetRawExposedObject();
7625 orDelegate = orAD->m_pUnhandledExceptionEventHandler;
7626 if (orDelegate != NULL)
7629 DistributeUnhandledExceptionReliably(&orDelegate, pSender, pThrowable, isTerminating);
7638 #endif // CROSSGEN_COMPILE
7640 // You must be in the correct context before calling this
7641 // routine. Therefore, it is only good for initializing the
7643 void AppDomain::InitializeDomainContext(BOOL allowRedirects,
7652 INJECT_FAULT(COMPlusThrowOM(););
7656 if (NingenEnabled())
7659 CreateFusionContext();
7664 #ifndef CROSSGEN_COMPILE
7666 STRINGREF pFilePath;
7669 PTRARRAYREF propertyNames;
7670 PTRARRAYREF propertyValues;
7672 ZeroMemory(&gc, sizeof(gc));
7674 GCPROTECT_BEGIN(gc);
7677 gc.pFilePath = StringObject::NewString(pwszPath);
7682 gc.pConfig = StringObject::NewString(pwszConfig);
7686 if ((gc.ref = GetExposedObject()) != NULL)
7688 MethodDescCallSite setupDomain(METHOD__APP_DOMAIN__SETUP_DOMAIN);
7692 ObjToArgSlot(gc.ref),
7693 BoolToArgSlot(allowRedirects),
7694 ObjToArgSlot(gc.pFilePath),
7695 ObjToArgSlot(gc.pConfig),
7696 ObjToArgSlot(gc.propertyNames),
7697 ObjToArgSlot(gc.propertyValues)
7699 setupDomain.Call(args);
7703 CacheStringsForDAC();
7704 #endif // CROSSGEN_COMPILE
7708 IUnknown *AppDomain::CreateFusionContext()
7710 CONTRACT(IUnknown *)
7715 POSTCONDITION(CheckPointer(RETVAL));
7716 INJECT_FAULT(COMPlusThrowOM(););
7720 if (!m_pFusionContext)
7722 ETWOnStartup (FusionAppCtx_V1, FusionAppCtxEnd_V1);
7723 CLRPrivBinderCoreCLR *pTPABinder = NULL;
7727 // Initialize the assembly binder for the default context loads for CoreCLR.
7728 IfFailThrow(CCoreCLRBinderHelper::DefaultBinderSetupContext(GetId().m_dwId, &pTPABinder));
7729 m_pFusionContext = reinterpret_cast<IUnknown *>(pTPABinder);
7731 // By default, initial binding context setup for CoreCLR is also the TPABinding context
7732 (m_pTPABinderContext = pTPABinder)->AddRef();
7736 RETURN m_pFusionContext;
7741 //---------------------------------------------------------------------------------------
7743 // AppDomain::IsDebuggerAttached - is a debugger attached to this process
7749 // TRUE if a debugger is attached to this process, FALSE otherwise.
7752 // This is identical to CORDebuggerAttached. This exists idependantly for legacy reasons - we used to
7753 // support attaching to individual AppDomains. This should probably go away eventually.
7756 BOOL AppDomain::IsDebuggerAttached()
7758 LIMITED_METHOD_CONTRACT;
7760 if (CORDebuggerAttached())
7770 #ifdef DEBUGGING_SUPPORTED
7772 // This is called from the debugger to request notification events from
7773 // Assemblies, Modules, Types in this appdomain.
7774 BOOL AppDomain::NotifyDebuggerLoad(int flags, BOOL attaching)
7776 WRAPPER_NO_CONTRACT;
7777 BOOL result = FALSE;
7779 if (!attaching && !IsDebuggerAttached())
7784 // Attach to our assemblies
7785 LOG((LF_CORDB, LL_INFO100, "AD::NDA: Iterating assemblies\n"));
7786 i = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution));
7787 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
7788 while (i.Next(pDomainAssembly.This()))
7790 result = (pDomainAssembly->NotifyDebuggerLoad(flags, attaching) ||
7797 void AppDomain::NotifyDebuggerUnload()
7799 WRAPPER_NO_CONTRACT;
7800 if (!IsDebuggerAttached())
7803 LOG((LF_CORDB, LL_INFO10, "AD::NDD domain [%d] %#08x %ls\n",
7804 GetId().m_dwId, this, GetFriendlyNameForLogging()));
7806 LOG((LF_CORDB, LL_INFO100, "AD::NDD: Interating domain bound assemblies\n"));
7807 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution));
7808 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
7810 // Detach from our assemblies
7811 while (i.Next(pDomainAssembly.This()))
7813 LOG((LF_CORDB, LL_INFO100, "AD::NDD: Iterating assemblies\n"));
7814 pDomainAssembly->NotifyDebuggerUnload();
7817 #endif // DEBUGGING_SUPPORTED
7819 void AppDomain::SetSystemAssemblyLoadEventSent(BOOL fFlag)
7821 LIMITED_METHOD_CONTRACT;
7823 m_dwFlags |= LOAD_SYSTEM_ASSEMBLY_EVENT_SENT;
7825 m_dwFlags &= ~LOAD_SYSTEM_ASSEMBLY_EVENT_SENT;
7828 BOOL AppDomain::WasSystemAssemblyLoadEventSent(void)
7830 LIMITED_METHOD_CONTRACT;
7831 return ((m_dwFlags & LOAD_SYSTEM_ASSEMBLY_EVENT_SENT) == 0) ? FALSE : TRUE;
7834 #ifndef CROSSGEN_COMPILE
7835 // U->M thunks created in this domain and not associated with a delegate.
7836 UMEntryThunkCache *AppDomain::GetUMEntryThunkCache()
7843 INJECT_FAULT(COMPlusThrowOM(););
7847 if (!m_pUMEntryThunkCache)
7849 UMEntryThunkCache *pUMEntryThunkCache = new UMEntryThunkCache(this);
7851 if (FastInterlockCompareExchangePointer(&m_pUMEntryThunkCache, pUMEntryThunkCache, NULL) != NULL)
7853 // some thread swooped in and set the field
7854 delete pUMEntryThunkCache;
7857 _ASSERTE(m_pUMEntryThunkCache);
7858 return m_pUMEntryThunkCache;
7861 #ifdef FEATURE_COMINTEROP
7863 ComCallWrapperCache *AppDomain::GetComCallWrapperCache()
7870 INJECT_FAULT(COMPlusThrowOM(););
7874 if (! m_pComCallWrapperCache)
7876 BaseDomain::LockHolder lh(this);
7878 if (! m_pComCallWrapperCache)
7879 m_pComCallWrapperCache = ComCallWrapperCache::Create(this);
7881 _ASSERTE(m_pComCallWrapperCache);
7882 return m_pComCallWrapperCache;
7885 RCWRefCache *AppDomain::GetRCWRefCache()
7887 CONTRACT(RCWRefCache*)
7892 POSTCONDITION(CheckPointer(RETVAL));
7896 if (!m_pRCWRefCache) {
7897 NewHolder<RCWRefCache> pRCWRefCache = new RCWRefCache(this);
7898 if (FastInterlockCompareExchangePointer(&m_pRCWRefCache, (RCWRefCache *)pRCWRefCache, NULL) == NULL)
7900 pRCWRefCache.SuppressRelease();
7903 RETURN m_pRCWRefCache;
7906 RCWCache *AppDomain::CreateRCWCache()
7913 INJECT_FAULT(COMPlusThrowOM(););
7914 POSTCONDITION(CheckPointer(RETVAL));
7918 // Initialize the global RCW cleanup list here as well. This is so that it
7919 // it guaranteed to exist if any RCW's are created, but it is not created
7921 if (!g_pRCWCleanupList)
7923 SystemDomain::LockHolder lh;
7925 if (!g_pRCWCleanupList)
7926 g_pRCWCleanupList = new RCWCleanupList();
7928 _ASSERTE(g_pRCWCleanupList);
7931 BaseDomain::LockHolder lh(this);
7934 m_pRCWCache = new RCWCache(this);
7940 void AppDomain::ReleaseRCWs(LPVOID pCtxCookie)
7942 WRAPPER_NO_CONTRACT;
7944 m_pRCWCache->ReleaseWrappersWorker(pCtxCookie);
7946 RemoveWinRTFactoryObjects(pCtxCookie);
7949 void AppDomain::DetachRCWs()
7951 WRAPPER_NO_CONTRACT;
7953 m_pRCWCache->DetachWrappersWorker();
7956 #endif // FEATURE_COMINTEROP
7958 BOOL AppDomain::CanThreadEnter(Thread *pThread)
7960 WRAPPER_NO_CONTRACT;
7962 if (m_Stage < STAGE_EXITED)
7965 if (pThread == SystemDomain::System()->GetUnloadingThread())
7966 return m_Stage < STAGE_FINALIZING;
7967 if (pThread == FinalizerThread::GetFinalizerThread())
7968 return m_Stage < STAGE_FINALIZED;
7973 void AppDomain::AllowThreadEntrance(AppDomain * pApp)
7981 PRECONDITION(CheckPointer(pApp));
7985 if (pApp->GetUnloadRequestThread() == NULL)
7987 // This is asynchonous unload, either by a host, or by AppDomain.Unload from AD unload event.
7988 if (!pApp->IsUnloadingFromUnloadEvent())
7990 pApp->SetStage(STAGE_UNLOAD_REQUESTED);
7991 pApp->EnableADUnloadWorker(
7992 pApp->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7997 SystemDomain::LockHolder lh; // we don't want to reopen appdomain if other thread can be preparing to unload it
7999 #ifdef FEATURE_COMINTEROP
8000 if (pApp->m_pComCallWrapperCache)
8001 pApp->m_pComCallWrapperCache->ResetDomainIsUnloading();
8002 #endif // FEATURE_COMINTEROP
8004 pApp->SetStage(STAGE_OPEN);
8007 void AppDomain::RestrictThreadEntrance(AppDomain * pApp)
8012 DISABLED(GC_TRIGGERS);
8014 DISABLED(FORBID_FAULT);
8015 PRECONDITION(CheckPointer(pApp));
8019 #ifdef FEATURE_COMINTEROP
8020 // Set the flag on our CCW cache so stubs won't enter
8021 if (pApp->m_pComCallWrapperCache)
8022 pApp->m_pComCallWrapperCache->SetDomainIsUnloading();
8023 #endif // FEATURE_COMINTEROP
8025 SystemDomain::LockHolder lh; // we don't want to reopen appdomain if other thread can be preparing to unload it
8026 // Release our ID so remoting and thread pool won't enter
8027 pApp->SetStage(STAGE_EXITED);
8030 void AppDomain::Exit(BOOL fRunFinalizers, BOOL fAsyncExit)
8040 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Exiting domain [%d] %#08x %ls\n",
8041 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8043 RestrictEnterHolder RestrictEnter(this);
8046 SystemDomain::LockHolder lh; // we don't want to close appdomain if other thread can be preparing to unload it
8047 SetStage(STAGE_EXITING); // Note that we're trying to exit
8050 // Raise the event indicating the domain is being unloaded.
8051 if (GetDefaultContext())
8053 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, this);
8055 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8056 //if (timeout == INFINITE)
8058 // timeout = 20000; // 20 seconds
8060 DWORD timeoutForFinalizer = GetEEPolicy()->GetTimeout(OPR_FinalizerRun);
8061 ULONGLONG curTime = CLRGetTickCount64();
8062 ULONGLONG endTime = 0;
8063 if (timeout != INFINITE)
8065 endTime = curTime + timeout;
8066 // We will try to kill AD unload event if it takes too long, and then we move on to the next registered caller.
8070 while (s_pAppDomainToRaiseUnloadEvent != NULL)
8072 FinalizerThread::FinalizerThreadWait(s_fProcessUnloadDomainEvent?timeout:timeoutForFinalizer);
8073 if (endTime != 0 && s_pAppDomainToRaiseUnloadEvent != NULL)
8075 if (CLRGetTickCount64() >= endTime)
8078 sThreadId.Printf(W("%x"), FinalizerThread::GetFinalizerThread()->GetThreadId());
8079 COMPlusThrow(kCannotUnloadAppDomainException,
8080 IDS_EE_ADUNLOAD_CANT_UNWIND_THREAD,
8087 // Tell the tiered compilation manager to stop initiating any new work for background
8088 // jit optimization. Its possible the standard thread unwind mechanisms would pre-emptively
8089 // evacuate the jit threadpool worker threads from the domain on their own, but I see no reason
8090 // to take the risk of relying on them when we can easily augment with a cooperative
8091 // shutdown check. This notification only initiates the process of evacuating the threads
8092 // and then the UnwindThreads() call below is where blocking will occur to ensure the threads
8093 // have exited the domain.
8095 #ifdef FEATURE_TIERED_COMPILATION
8096 m_tieredCompilationManager.Shutdown(FALSE);
8100 // Set up blocks so no threads can enter except for the finalizer and the thread
8101 // doing the unload.
8104 RestrictThreadEntrance(this);
8106 // Cause existing threads to abort out of this domain. This should ensure all
8107 // normal threads are outside the domain, and we've already ensured that no new threads
8110 PerAppDomainTPCountList::AppDomainUnloadingHolder tpAdUnloadHolder(GetTPIndex());
8113 if (!NingenEnabled())
8118 TESTHOOKCALL(UnwoundThreads(GetId().m_dwId)) ;
8119 ProcessEventForHost(Event_DomainUnload, (PVOID)(UINT_PTR)GetId().m_dwId);
8121 RestrictEnter.SuppressRelease(); //after this point we don't guarantee appdomain consistency
8122 #ifdef PROFILING_SUPPORTED
8123 // Signal profile if present.
8125 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
8127 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) this);
8130 #endif // PROFILING_SUPPORTED
8131 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomains--);
8132 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomainsUnloaded++);
8134 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is exited.\n",
8135 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8137 // Send ETW events for this domain's unload and potentially iterate through this
8138 // domain's modules & assemblies to send events for their unloads as well. This
8139 // needs to occur before STAGE_FINALIZED (to ensure everything is there), so we do
8140 // this before any finalization occurs at all.
8141 ETW::LoaderLog::DomainUnload(this);
8143 CodeVersionManager::OnAppDomainExit(this);
8146 // Spin running finalizers until we flush them all. We need to make multiple passes
8147 // in case the finalizers create more finalizable objects. This is important to clear
8148 // the finalizable objects as roots, as well as to actually execute the finalizers. This
8149 // will only finalize instances instances of types that aren't potentially agile becuase we can't
8150 // risk finalizing agile objects. So we will be left with instances of potentially agile types
8151 // in handles or statics.
8153 // <TODO>@todo: Need to ensure this will terminate in a reasonable amount of time. Eventually
8154 // we should probably start passing FALSE for fRunFinalizers. Also I'm not sure we
8155 // guarantee that FinalizerThreadWait will ever terminate in general.</TODO>
8158 SetStage(STAGE_FINALIZING);
8160 // Flush finalizers now.
8161 FinalizerThread::UnloadAppDomain(this, fRunFinalizers);
8163 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8164 ULONGLONG startTime = CLRGetTickCount64();
8165 ULONGLONG elapsedTime = 0;
8166 DWORD finalizerWait = 0;
8168 while (FinalizerThread::GetUnloadingAppDomain() != NULL)
8171 if (timeout != INFINITE)
8173 elapsedTime = CLRGetTickCount64() - startTime;
8175 if (timeout > elapsedTime)
8177 finalizerWait = timeout - static_cast<DWORD>(elapsedTime);
8179 FinalizerThread::FinalizerThreadWait(finalizerWait); //will set stage to finalized
8180 if (timeout != INFINITE && FinalizerThread::GetUnloadingAppDomain() != NULL)
8182 elapsedTime = CLRGetTickCount64() - startTime;
8183 if (timeout <= elapsedTime)
8186 // TODO: Consider escalation from RudeAppDomain
8192 tpAdUnloadHolder.SuppressRelease();
8193 PerAppDomainTPCountList::ResetAppDomainTPCounts(GetTPIndex());
8195 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is finalized.\n",
8196 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8199 AppDomainRefHolder This(this);
8200 AddRef(); // Hold a reference so CloseDomain won't delete us yet
8201 CloseDomain(); // Remove ourself from the list of app domains
8203 // This needs to be done prior to destroying the handle tables below.
8204 ReleaseDomainBoundInfo();
8207 // It should be impossible to run non-mscorlib code in this domain now.
8208 // Cleanup all of our roots except the handles. We do this to allow as many
8209 // finalizers as possible to run correctly. If we delete the handles, they
8212 if (!NingenEnabled())
8219 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is cleared.\n",
8220 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8222 if (fAsyncExit && fRunFinalizers)
8225 m_AssemblyCache.Clear();
8226 ClearFusionContext();
8228 if (!NingenEnabled())
8230 AddMemoryPressure();
8233 SystemDomain::System()->AddToDelayedUnloadList(this, fAsyncExit);
8234 SystemDomain::SetUnloadDomainCleared();
8235 if (m_dwId.m_dwId!=0)
8236 SystemDomain::ReleaseAppDomainId(m_dwId);
8237 #ifdef PROFILING_SUPPORTED
8238 // Always signal profile if present, even when failed.
8240 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
8242 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) this, S_OK);
8245 #endif // PROFILING_SUPPORTED
8249 void AppDomain::Close()
8258 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is collected.\n",
8259 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8262 #if CHECK_APP_DOMAIN_LEAKS
8263 if (g_pConfig->AppDomainLeaks())
8264 // at this point shouldn't have any non-agile objects in the heap because we finalized all the non-agile ones.
8265 SyncBlockCache::GetSyncBlockCache()->CheckForUnloadedInstances(GetIndex());
8266 #endif // CHECK_APP_DOMAIN_LEAKS
8269 RemoveMemoryPressure();
8271 _ASSERTE(m_cRef>0); //should be alive at this point otherwise iterator can revive us and crash
8273 SystemDomain::LockHolder lh; // Avoid races with AppDomainIterator
8274 SetStage(STAGE_CLOSED);
8277 // CONSIDER: move releasing remoting cache from managed code to here.
8281 void AppDomain::ResetUnloadRequestThread(ADID Id)
8287 PRECONDITION(!IsADUnloadHelperThread());
8292 AppDomainFromIDHolder ad(Id, TRUE);
8293 if(!ad.IsUnloaded() && ad->m_Stage < STAGE_UNLOAD_REQUESTED)
8295 Thread *pThread = ad->GetUnloadRequestThread();
8296 if(pThread==GetThread())
8298 ad->m_dwThreadsStillInAppDomain=(ULONG)-1;
8302 if (pThread->GetUnloadBoundaryFrame() && pThread->IsBeingAbortedForADUnload())
8304 pThread->UnmarkThreadForAbort(Thread::TAR_ADUnload);
8306 ad->GetUnloadRequestThread()->ResetUnloadBoundaryFrame();
8307 pThread->ResetBeginAbortedForADUnload();
8310 ad->SetUnloadRequestThread(NULL);
8316 int g_fADUnloadWorkerOK = -1;
8318 HRESULT AppDomain::UnloadById(ADID dwId, BOOL fSync,BOOL fExceptionsPassThrough)
8322 if(fExceptionsPassThrough) {THROWS;} else {NOTHROW;}
8324 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_TRIGGERS);}
8329 if (dwId==(ADID)DefaultADID)
8330 return COR_E_CANNOTUNLOADAPPDOMAIN;
8332 Thread *pThread = GetThread();
8334 // Finalizer thread can not wait until AD unload is done,
8335 // because AD unload is going to wait for Finalizer Thread.
8336 if (fSync && pThread == FinalizerThread::GetFinalizerThread() &&
8337 !pThread->HasThreadStateNC(Thread::TSNC_RaiseUnloadEvent))
8338 return COR_E_CANNOTUNLOADAPPDOMAIN;
8341 // AD unload helper thread should have been created.
8342 _ASSERTE (g_fADUnloadWorkerOK == 1);
8344 _ASSERTE (!IsADUnloadHelperThread());
8346 BOOL fIsRaisingUnloadEvent = (pThread != NULL && pThread->HasThreadStateNC(Thread::TSNC_RaiseUnloadEvent));
8348 if (fIsRaisingUnloadEvent)
8350 AppDomainFromIDHolder pApp(dwId, TRUE, AppDomainFromIDHolder::SyncType_GC);
8352 if (pApp.IsUnloaded() || ! pApp->CanLoadCode() || pApp->GetId().m_dwId == 0)
8353 return COR_E_APPDOMAINUNLOADED;
8355 pApp->EnableADUnloadWorker();
8361 ADUnloadSinkHolder pSink;
8364 SystemDomain::LockHolder ulh;
8366 AppDomainFromIDHolder pApp(dwId, TRUE, AppDomainFromIDHolder::SyncType_ADLock);
8368 if (pApp.IsUnloaded() || ! pApp->CanLoadCode() || pApp->GetId().m_dwId == 0)
8369 return COR_E_APPDOMAINUNLOADED;
8371 if (g_fADUnloadWorkerOK != 1)
8374 return E_UNEXPECTED;
8379 pApp->EnableADUnloadWorker();
8383 pSink = pApp->PrepareForWaitUnloadCompletion();
8385 pApp->EnableADUnloadWorker();
8387 // release the holders - we don't care anymore if the appdomain is gone
8390 #ifdef FEATURE_TESTHOOKS
8391 if (fExceptionsPassThrough)
8393 CONTRACT_VIOLATION(FaultViolation);
8394 return UnloadWaitNoCatch(dwId,pSink);
8398 return UnloadWait(dwId,pSink);
8401 HRESULT AppDomain::UnloadWait(ADID Id, ADUnloadSink * pSink)
8407 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_TRIGGERS);}
8414 // IF you ever try to change this to something not using events, please address the fact that
8415 // AppDomain::StopEEAndUnwindThreads relies on that events are used.
8417 pSink->WaitUnloadCompletion();
8419 EX_CATCH_HRESULT(hr);
8422 hr=pSink->GetUnloadResult();
8426 ResetUnloadRequestThread(Id);
8431 #ifdef FEATURE_TESTHOOKS
8432 HRESULT AppDomain::UnloadWaitNoCatch(ADID Id, ADUnloadSink * pSink)
8434 STATIC_CONTRACT_THROWS;
8435 STATIC_CONTRACT_MODE_ANY;
8437 Holder<ADID, DoNothing<ADID>, AppDomain::ResetUnloadRequestThread> resetUnloadHolder(Id);
8439 // IF you ever try to change this to something not using events, please address the fact that
8440 // AppDomain::StopEEAndUnwindThreads relies on that events are used.
8441 pSink->WaitUnloadCompletion();
8443 HRESULT hr = pSink->GetUnloadResult();
8446 resetUnloadHolder.SuppressRelease();
8452 void AppDomain::Unload(BOOL fForceUnload)
8459 INJECT_FAULT(COMPlusThrowOM(););
8463 #ifdef FEATURE_MULTICOREJIT
8465 // Avoid profiling file is partially written in ASP.net scenarios, call it earlier
8466 GetMulticoreJitManager().StopProfile(true);
8470 Thread *pThread = GetThread();
8473 if (! fForceUnload && !g_pConfig->AppDomainUnload())
8476 EPolicyAction action;
8477 EClrOperation operation;
8478 if (!IsRudeUnload())
8480 operation = OPR_AppDomainUnload;
8484 operation = OPR_AppDomainRudeUnload;
8486 action = GetEEPolicy()->GetDefaultAction(operation,NULL);
8487 GetEEPolicy()->NotifyHostOnDefaultAction(operation,action);
8491 case eUnloadAppDomain:
8493 case eRudeUnloadAppDomain:
8497 case eFastExitProcess:
8498 case eRudeExitProcess:
8499 case eDisableRuntime:
8500 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_ADUNLOAD);
8501 _ASSERTE (!"Should not get here");
8507 #if (defined(_DEBUG) || defined(BREAK_ON_UNLOAD) || defined(AD_LOG_MEMORY) || defined(AD_SNAPSHOT))
8508 static int unloadCount = 0;
8511 #ifdef AD_LOG_MEMORY
8514 static int logMemory = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADLogMemory);
8515 typedef void (__cdecl *LogItFcn) ( int );
8516 static LogItFcn pLogIt = NULL;
8518 if (logMemory && ! pLogIt)
8520 HMODULE hMod = CLRLoadLibrary(W("mpdh.dll"));
8523 pLogIt = (LogItFcn)GetProcAddress(hMod, "logIt");
8532 #endif // AD_LOG_MEMORY
8534 if (IsDefaultDomain() && !IsSingleAppDomain())
8535 COMPlusThrow(kCannotUnloadAppDomainException, IDS_EE_ADUNLOAD_DEFAULT);
8537 _ASSERTE(CanUnload());
8539 if (pThread == FinalizerThread::GetFinalizerThread() || GetUnloadRequestThread() == FinalizerThread::GetFinalizerThread())
8540 COMPlusThrow(kCannotUnloadAppDomainException, IDS_EE_ADUNLOAD_IN_FINALIZER);
8542 _ASSERTE(! SystemDomain::AppDomainBeingUnloaded());
8544 // should not be running in this AD because unload spawned thread in default domain
8545 if (!NingenEnabled())
8547 _ASSERTE(!pThread->IsRunningIn(this, NULL));
8551 #ifdef APPDOMAIN_STATE
8552 _ASSERTE_ALL_BUILDS("clr/src/VM/AppDomain.cpp", pThread->GetDomain()->IsDefaultDomain());
8555 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Unloading domain [%d] %#08x %ls\n", GetId().m_dwId, this, GetFriendlyName()));
8557 STRESS_LOG3 (LF_APPDOMAIN, LL_INFO100, "Unload domain [%d, %d] %p\n", GetId().m_dwId, GetIndex().m_dwIndex, this);
8559 UnloadHolder hold(this);
8561 SystemDomain::System()->SetUnloadRequestingThread(GetUnloadRequestThread());
8562 SystemDomain::System()->SetUnloadingThread(pThread);
8566 static int dumpSB = -1;
8569 dumpSB = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADDumpSB);
8573 LogSpewAlways("Starting unload %3.3d\n", unloadCount);
8574 DumpSyncBlockCache();
8578 BOOL bForceGC=m_bForceGCOnUnload;
8580 #ifdef AD_LOG_MEMORY
8583 #endif // AD_LOG_MEMORY
8586 static int takeSnapShot = -1;
8588 if (takeSnapShot == -1)
8589 takeSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeSnapShot);
8593 #endif // AD_SNAPSHOT
8599 static int cfgForceGC = -1;
8601 if (cfgForceGC == -1)
8602 cfgForceGC =!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_ADULazyMemoryRelease);
8604 bForceGC=bForceGC||cfgForceGC;
8605 AppDomainRefHolder This(this);
8608 // Do the actual unloading
8610 // We do not want other threads to abort the current one.
8611 ThreadPreventAsyncHolder preventAsync;
8612 Exit(TRUE, !bForceGC);
8616 GCHeapUtilities::GetGCHeap()->GarbageCollect();
8617 FinalizerThread::FinalizerThreadWait();
8618 SetStage(STAGE_COLLECTED);
8622 #ifdef AD_LOG_MEMORY
8626 pLogIt(unloadCount);
8628 #endif // AD_LOG_MEMORY
8634 sprintf_s(buffer, _countof(buffer), "vadump -p %d -o > vadump.%d", GetCurrentProcessId(), unloadCount);
8636 sprintf_s(buffer, _countof(buffer), "umdh -p:%d -d -i:1 -f:umdh.%d", GetCurrentProcessId(), unloadCount);
8638 int takeDHSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeDHSnapShot);
8641 sprintf_s(buffer, _countof(buffer), "dh -p %d -s -g -h -b -f dh.%d", GetCurrentProcessId(), unloadCount);
8645 #endif // AD_SNAPSHOT
8650 // do extra finalizer wait to remove any leftover sb entries
8651 FinalizerThread::FinalizerThreadWait();
8652 GCHeapUtilities::GetGCHeap()->GarbageCollect();
8653 FinalizerThread::FinalizerThreadWait();
8654 LogSpewAlways("Done unload %3.3d\n", unloadCount);
8655 DumpSyncBlockCache();
8658 swprintf_s(buffer, NumItems(buffer), W("DumpSB.%d"), unloadCount);
8659 _ASSERTE(WszMoveFileEx(W("COMPLUS.LOG"), buffer, MOVEFILE_REPLACE_EXISTING));
8660 // this will open a new file
8666 void AppDomain::ExceptionUnwind(Frame *pFrame)
8670 DISABLED(GC_TRIGGERS); // EEResourceException
8671 DISABLED(THROWS); // EEResourceException
8676 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind for %8.8x\n", pFrame));
8678 printf("%x AppDomain::ExceptionUnwind for %8.8p\n", GetThread()->GetThreadId(), pFrame);
8680 Thread *pThread = GetThread();
8683 if (! pThread->ShouldChangeAbortToUnload(pFrame))
8685 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind: not first transition or abort\n"));
8689 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind: changing to unload\n"));
8692 OBJECTREF throwable = NULL;
8693 EEResourceException e(kAppDomainUnloadedException, W("Remoting_AppDomainUnloaded_ThreadUnwound"));
8694 throwable = e.GetThrowable();
8696 // reset the exception to an AppDomainUnloadedException
8697 if (throwable != NULL)
8699 GetThread()->SafeSetThrowables(throwable);
8703 BOOL AppDomain::StopEEAndUnwindThreads(unsigned int retryCount, BOOL *pFMarkUnloadRequestThread)
8714 Thread *pThread = NULL;
8715 DWORD nThreadsNeedMoreWork=0;
8716 if (retryCount != (unsigned int)-1 && retryCount < g_pConfig->AppDomainUnloadRetryCount())
8718 Thread *pCurThread = GetThread();
8719 if (pCurThread->CatchAtSafePoint())
8720 pCurThread->PulseGCMode();
8723 // We know which thread is not in the domain now. We just need to
8724 // work on those threads. We do not need to suspend the runtime.
8725 ThreadStoreLockHolder tsl;
8727 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8729 if (pThread == pCurThread)
8734 if (pThread == FinalizerThread::GetFinalizerThread())
8739 if (pThread->GetUnloadBoundaryFrame() == NULL)
8744 // A thread may have UnloadBoundaryFrame set if
8745 // 1. Being unloaded by AD unload helper thread
8746 // 2. Escalation from OOM or SO triggers AD unload
8747 // Here we only need to work on threads that are in the domain. If we work on other threads,
8748 // those threads may be stucked in a finally, and we will not be able to escalate for them,
8749 // therefore AD unload is blocked.
8750 if (pThread->IsBeingAbortedForADUnload() ||
8751 pThread == SystemDomain::System()->GetUnloadRequestingThread())
8753 nThreadsNeedMoreWork++;
8756 if (!(IsRudeUnload() ||
8757 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft())))
8762 if ((pThread == SystemDomain::System()->GetUnloadRequestingThread()) && *pFMarkUnloadRequestThread)
8764 // Mark thread for abortion only once; later on interrupt only
8765 *pFMarkUnloadRequestThread = FALSE;
8766 pThread->SetAbortRequest(m_fRudeUnload? EEPolicy::TA_Rude : EEPolicy::TA_V1Compatible);
8770 if (pThread->m_State & Thread::TS_Interruptible)
8772 pThread->UserInterrupt(Thread::TI_Abort);
8776 if (pThread->PreemptiveGCDisabledOther())
8778 #if defined(FEATURE_HIJACK) && !defined(PLATFORM_UNIX)
8779 Thread::SuspendThreadResult str = pThread->SuspendThread();
8780 if (str == Thread::STR_Success)
8782 if (pThread->PreemptiveGCDisabledOther() &&
8783 (!pThread->IsAbortInitiated() || pThread->IsRudeAbort()))
8785 pThread->HandleJITCaseForAbort();
8787 pThread->ResumeThread();
8792 } // ThreadStoreLockHolder
8794 m_dwThreadsStillInAppDomain=nThreadsNeedMoreWork;
8795 return !nThreadsNeedMoreWork;
8798 // For now piggyback on the GC's suspend EE mechanism
8799 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
8801 // <TODO>@todo: what to do with any threads that didn't stop?</TODO>
8802 _ASSERTE(ThreadStore::s_pThreadStore->DbgBackgroundThreadCount() > 0);
8805 int totalADCount = 0;
8806 int finalizerADCount = 0;
8809 RuntimeExceptionKind reKind = kLastException;
8811 SmallStackSString ssThreadId;
8813 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8815 // we already checked that we're not running in the unload domain
8816 if (pThread == GetThread())
8822 void PrintStackTraceWithADToLog(Thread *pThread);
8823 if (LoggingOn(LF_APPDOMAIN, LL_INFO100)) {
8824 LOG((LF_APPDOMAIN, LL_INFO100, "\nStackTrace for %x\n", pThread->GetThreadId()));
8825 PrintStackTraceWithADToLog(pThread);
8829 Frame *pFrame = pThread->GetFirstTransitionInto(this, &count);
8831 _ASSERTE(count == 0);
8832 if (pThread->IsBeingAbortedForADUnload())
8834 pThread->ResetBeginAbortedForADUnload();
8839 if (pThread != FinalizerThread::GetFinalizerThread())
8841 totalADCount += count;
8842 nThreadsNeedMoreWork++;
8843 pThread->SetUnloadBoundaryFrame(pFrame);
8847 finalizerADCount = count;
8850 // don't setup the exception info for the unloading thread unless it's the last one in
8851 if (retryCount != ((unsigned int) -1) && retryCount > g_pConfig->AppDomainUnloadRetryCount() && reKind == kLastException &&
8852 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft()))
8854 #ifdef AD_BREAK_ON_CANNOT_UNLOAD
8855 static int breakOnCannotUnload = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADBreakOnCannotUnload);
8856 if (breakOnCannotUnload)
8857 _ASSERTE(!"Cannot unload AD");
8858 #endif // AD_BREAK_ON_CANNOT_UNLOAD
8859 reKind = kCannotUnloadAppDomainException;
8860 resId = IDS_EE_ADUNLOAD_CANT_UNWIND_THREAD;
8861 ssThreadId.Printf(W("%x"), pThread->GetThreadId());
8862 STRESS_LOG2(LF_APPDOMAIN, LL_INFO10, "AppDomain::UnwindThreads cannot stop thread %x with %d transitions\n", pThread->GetThreadId(), count);
8863 // don't break out of this early or the assert totalADCount == (int)m_dwThreadEnterCount below will fire
8864 // it's better to chew a little extra time here and make sure our counts are consistent
8866 // only abort the thread requesting the unload if it's the last one in, that way it will get
8867 // notification that the unload failed for some other thread not being aborted. And don't abort
8868 // the finalizer thread - let it finish it's work as it's allowed to be in there. If it won't finish,
8869 // then we will eventually get a CannotUnloadException on it.
8871 if (pThread != FinalizerThread::GetFinalizerThread() &&
8872 // If the domain is rudely unloaded, we will unwind the requesting thread out
8873 // Rude unload is going to succeed, or escalated to disable runtime or higher.
8875 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft())
8880 STRESS_LOG2(LF_APPDOMAIN, LL_INFO100, "AppDomain::UnwindThreads stopping %x with %d transitions\n", pThread->GetThreadId(), count);
8881 LOG((LF_APPDOMAIN, LL_INFO100, "AppDomain::UnwindThreads stopping %x with %d transitions\n", pThread->GetThreadId(), count));
8883 printf("AppDomain::UnwindThreads %x stopping %x with first frame %8.8p\n", GetThread()->GetThreadId(), pThread->GetThreadId(), pFrame);
8885 if (pThread == SystemDomain::System()->GetUnloadRequestingThread())
8887 // Mark thread for abortion only once; later on interrupt only
8888 *pFMarkUnloadRequestThread = FALSE;
8890 pThread->SetAbortRequest(m_fRudeUnload? EEPolicy::TA_Rude : EEPolicy::TA_V1Compatible);
8892 TESTHOOKCALL(UnwindingThreads(GetId().m_dwId)) ;
8894 _ASSERTE(totalADCount + finalizerADCount == (int)m_dwThreadEnterCount);
8896 //@TODO: This is intended to catch a stress bug. Remove when no longer needed.
8897 if (totalADCount + finalizerADCount != (int)m_dwThreadEnterCount)
8898 FreeBuildDebugBreak();
8900 // if our count did get messed up, set it to whatever count we actually found in the domain to avoid looping
8901 // or other problems related to incorrect count. This is very much a bug if this happens - a thread should always
8902 // exit the domain gracefully.
8903 // m_dwThreadEnterCount = totalADCount;
8905 if (reKind != kLastException)
8908 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8910 if (pThread->IsBeingAbortedForADUnload())
8912 pThread->ResetBeginAbortedForADUnload();
8917 // CommonTripThread will handle the abort for any threads that we've marked
8918 ThreadSuspend::RestartEE(FALSE, TRUE);
8919 if (reKind != kLastException)
8920 COMPlusThrow(reKind, resId, ssThreadId.GetUnicode());
8922 _ASSERTE((totalADCount==0 && nThreadsNeedMoreWork==0) ||(totalADCount!=0 && nThreadsNeedMoreWork!=0));
8924 m_dwThreadsStillInAppDomain=nThreadsNeedMoreWork;
8925 return (totalADCount == 0);
8928 void AppDomain::UnwindThreads()
8930 // This function should guarantee appdomain
8931 // consistency even if it fails. Everything that is going
8932 // to make the appdomain impossible to reenter
8933 // should be factored out
8935 // <TODO>@todo: need real synchronization here!!!</TODO>
8944 int retryCount = -1;
8945 m_dwThreadsStillInAppDomain=(ULONG)-1;
8946 ULONGLONG startTime = CLRGetTickCount64();
8948 if (GetEEPolicy()->GetDefaultAction(OPR_AppDomainUnload, NULL) == eRudeUnloadAppDomain &&
8951 GetEEPolicy()->NotifyHostOnDefaultAction(OPR_AppDomainUnload, eRudeUnloadAppDomain);
8955 // Force threads to go through slow path during AD unload.
8956 TSSuspendHolder shTrap;
8958 BOOL fCurrentUnloadMode = IsRudeUnload();
8959 BOOL fMarkUnloadRequestThread = TRUE;
8961 // now wait for all the threads running in our AD to get out
8964 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8965 EPolicyAction action = GetEEPolicy()->GetActionOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, NULL);
8966 if (timeout != INFINITE && action > eUnloadAppDomain) {
8967 // Escalation policy specified.
8968 ULONGLONG curTime = CLRGetTickCount64();
8969 ULONGLONG elapseTime = curTime - startTime;
8970 if (elapseTime > timeout)
8975 case eRudeUnloadAppDomain:
8976 GetEEPolicy()->NotifyHostOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, action);
8978 STRESS_LOG1(LF_APPDOMAIN, LL_INFO100,"Escalating to RADU, adid=%d",GetId().m_dwId);
8981 case eFastExitProcess:
8982 case eRudeExitProcess:
8983 case eDisableRuntime:
8984 GetEEPolicy()->NotifyHostOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, action);
8985 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_TIMEOUT);
8986 _ASSERTE (!"Should not reach here");
8994 if (LoggingOn(LF_APPDOMAIN, LL_INFO100))
8995 DumpADThreadTrack();
8997 BOOL fNextUnloadMode = IsRudeUnload();
8998 if (fCurrentUnloadMode != fNextUnloadMode)
9000 // We have changed from normal unload to rude unload. We need to mark the thread
9001 // with RudeAbort, but we can only do this safely if the runtime is suspended.
9002 fCurrentUnloadMode = fNextUnloadMode;
9005 if (StopEEAndUnwindThreads(retryCount, &fMarkUnloadRequestThread))
9007 if (timeout != INFINITE)
9009 // Turn off the timeout used by AD.
9014 // GCStress takes a long time to unwind, due to expensive creation of
9015 // a threadabort exception.
9016 if (!GCStress<cfg_any>::IsEnabled())
9018 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::UnwindThreads iteration %d waiting on thread count %d\n", retryCount, m_dwThreadEnterCount));
9020 printf("AppDomain::UnwindThreads iteration %d waiting on thread count %d\n", retryCount, m_dwThreadEnterCount);
9024 if (m_dwThreadEnterCount != 0)
9027 GetThread()->UserSleep(20);
9029 GetThread()->UserSleep(10);
9036 void AppDomain::ClearGCHandles()
9046 SetStage(STAGE_HANDLETABLE_NOACCESS);
9048 GCHeapUtilities::GetGCHeap()->WaitUntilConcurrentGCComplete();
9050 // Keep async pin handles alive by moving them to default domain
9051 HandleAsyncPinHandles();
9053 // Remove our handle store as a source of GC roots
9054 m_handleStore->Uproot();
9057 // When an AD is unloaded, we will release all objects in this AD.
9058 // If a future asynchronous operation, like io completion port function,
9059 // we need to keep the memory space fixed so that the gc heap is not corrupted.
9060 void AppDomain::HandleAsyncPinHandles()
9070 IGCHandleStore *pBucket = m_handleStore;
9072 // IO completion port picks IO job using FIFO. Here is how we know which AsyncPinHandle can be freed.
9073 // 1. We mark all non-pending AsyncPinHandle with READYTOCLEAN.
9074 // 2. We queue a dump Overlapped to the IO completion as a marker.
9075 // 3. When the Overlapped is picked up by completion port, we wait until all previous IO jobs are processed.
9076 // 4. Then we can delete all AsyncPinHandle marked with READYTOCLEAN.
9077 IGCHandleStore *pBucketInDefault = SystemDomain::System()->DefaultDomain()->m_handleStore;
9079 pBucket->RelocateAsyncPinnedHandles(pBucketInDefault);
9081 OverlappedDataObject::RequestCleanup();
9084 void AppDomain::ClearGCRoots()
9094 Thread *pThread = NULL;
9095 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
9097 // Tell the JIT managers to delete any entries in their structures. All the cooperative mode threads are stopped at
9098 // this point, so only need to synchronize the preemptive mode threads.
9099 ExecutionManager::Unload(GetLoaderAllocator());
9101 while ((pThread = ThreadStore::GetAllThreadList(pThread, 0, 0)) != NULL)
9103 // Delete the thread local static store
9104 pThread->DeleteThreadStaticData(this);
9106 // <TODO>@TODO: A pre-allocated AppDomainUnloaded exception might be better.</TODO>
9107 if (m_handleStore->ContainsHandle(pThread->m_LastThrownObjectHandle))
9109 // Never delete a handle to a preallocated exception object.
9110 if (!CLRException::IsPreallocatedExceptionHandle(pThread->m_LastThrownObjectHandle))
9112 DestroyHandle(pThread->m_LastThrownObjectHandle);
9115 pThread->m_LastThrownObjectHandle = NULL;
9118 // Clear out the exceptions objects held by a thread.
9119 pThread->GetExceptionState()->ClearThrowablesForUnload(m_handleStore);
9122 //delete them while we still have the runtime suspended
9123 // This must be deleted before the loader heaps are deleted.
9124 if (m_pMarshalingData != NULL)
9126 delete m_pMarshalingData;
9127 m_pMarshalingData = NULL;
9130 if (m_pLargeHeapHandleTable != NULL)
9132 delete m_pLargeHeapHandleTable;
9133 m_pLargeHeapHandleTable = NULL;
9136 ThreadSuspend::RestartEE(FALSE, TRUE);
9141 void AppDomain::TrackADThreadEnter(Thread *pThread, Frame *pFrame)
9148 PRECONDITION(CheckPointer(pThread));
9149 PRECONDITION(pFrame != (Frame*)(size_t) INVALID_POINTER_CD);
9153 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9155 if (m_pThreadTrackInfoList == NULL)
9156 m_pThreadTrackInfoList = new (nothrow) ThreadTrackInfoList;
9157 // If we don't assert here, we will AV in the for loop below
9158 _ASSERTE(m_pThreadTrackInfoList);
9160 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9162 ThreadTrackInfo *pTrack = NULL;
9164 for (i=0; i < pTrackList->Count(); i++) {
9165 if ((*(pTrackList->Get(i)))->pThread == pThread) {
9166 pTrack = *(pTrackList->Get(i));
9171 pTrack = new (nothrow) ThreadTrackInfo;
9172 // If we don't assert here, we will AV in the for loop below.
9174 pTrack->pThread = pThread;
9175 ThreadTrackInfo **pSlot = pTrackList->Append();
9179 InterlockedIncrement((LONG*)&m_dwThreadEnterCount);
9183 pSlot = pTrack->frameStack.Insert(0);
9187 for (i=0; i < pTrackList->Count(); i++)
9188 totThreads += (*(pTrackList->Get(i)))->frameStack.Count();
9189 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9191 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9195 void AppDomain::TrackADThreadExit(Thread *pThread, Frame *pFrame)
9199 if (GetThread()) {MODE_COOPERATIVE;}
9205 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9207 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9208 _ASSERTE(pTrackList);
9209 ThreadTrackInfo *pTrack = NULL;
9211 for (i=0; i < pTrackList->Count(); i++)
9213 if ((*(pTrackList->Get(i)))->pThread == pThread)
9215 pTrack = *(pTrackList->Get(i));
9220 _ASSERTE(*(pTrack->frameStack.Get(0)) == pFrame);
9221 pTrack->frameStack.Delete(0);
9222 InterlockedDecrement((LONG*)&m_dwThreadEnterCount);
9225 for (i=0; i < pTrackList->Count(); i++)
9226 totThreads += (*(pTrackList->Get(i)))->frameStack.Count();
9227 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9229 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9232 void AppDomain::DumpADThreadTrack()
9242 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9244 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9249 LOG((LF_APPDOMAIN, LL_INFO10000, "\nThread dump of %d threads for [%d] %#08x %S\n",
9250 m_dwThreadEnterCount, GetId().m_dwId, this, GetFriendlyNameForLogging()));
9252 for (int i=0; i < pTrackList->Count(); i++)
9254 ThreadTrackInfo *pTrack = *(pTrackList->Get(i));
9255 if (pTrack->frameStack.Count()==0)
9257 LOG((LF_APPDOMAIN, LL_INFO100, " ADEnterCount for %x is %d\n", pTrack->pThread->GetThreadId(), pTrack->frameStack.Count()));
9258 totThreads += pTrack->frameStack.Count();
9259 for (int j=0; j < pTrack->frameStack.Count(); j++)
9260 LOG((LF_APPDOMAIN, LL_INFO100, " frame %8.8x\n", *(pTrack->frameStack.Get(j))));
9262 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9265 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9270 #endif // CROSSGEN_COMPILE
9272 void *SharedDomain::operator new(size_t size, void *pInPlace)
9274 LIMITED_METHOD_CONTRACT;
9278 void SharedDomain::operator delete(void *pMem)
9280 LIMITED_METHOD_CONTRACT;
9281 // Do nothing - new() was in-place
9285 void SharedDomain::Attach()
9292 INJECT_FAULT(COMPlusThrowOM(););
9296 // Create the global SharedDomain and initialize it.
9297 m_pSharedDomain = new (&g_pSharedDomainMemory[0]) SharedDomain();
9298 SystemDomain::GetGlobalLoaderAllocator()->m_pDomain = m_pSharedDomain;
9299 // This cannot fail since g_pSharedDomainMemory is a static array.
9300 CONSISTENCY_CHECK(CheckPointer(m_pSharedDomain));
9302 LOG((LF_CLASSLOADER,
9304 "Created shared domain at %p\n",
9307 // We need to initialize the memory pools etc. for the system domain.
9308 m_pSharedDomain->Init(); // Setup the memory heaps
9310 // allocate a Virtual Call Stub Manager for the shared domain
9311 m_pSharedDomain->InitVSD();
9314 #ifndef CROSSGEN_COMPILE
9315 void SharedDomain::Detach()
9317 if (m_pSharedDomain)
9319 m_pSharedDomain->Terminate();
9320 delete m_pSharedDomain;
9321 m_pSharedDomain = NULL;
9324 #endif // CROSSGEN_COMPILE
9326 #endif // !DACCESS_COMPILE
9328 SharedDomain *SharedDomain::GetDomain()
9330 LIMITED_METHOD_DAC_CONTRACT;
9332 return m_pSharedDomain;
9335 #ifndef DACCESS_COMPILE
9337 #define INITIAL_ASSEMBLY_MAP_SIZE 17
9338 void SharedDomain::Init()
9345 INJECT_FAULT(COMPlusThrowOM(););
9351 #ifdef FEATURE_LOADER_OPTIMIZATION
9352 m_FileCreateLock.Init(CrstSharedAssemblyCreate, CRST_DEFAULT,TRUE);
9354 LockOwner lock = { &m_DomainCrst, IsOwnerOfCrst };
9355 m_assemblyMap.Init(INITIAL_ASSEMBLY_MAP_SIZE, CompareSharedAssembly, TRUE, &lock);
9356 #endif // FEATURE_LOADER_OPTIMIZATION
9358 ETW::LoaderLog::DomainLoad(this);
9361 #ifndef CROSSGEN_COMPILE
9362 void SharedDomain::Terminate()
9364 // make sure we delete the StringLiteralMap before unloading
9365 // the asemblies since the string literal map entries can
9366 // point to metadata string literals.
9367 GetLoaderAllocator()->CleanupStringLiteralMap();
9369 #ifdef FEATURE_LOADER_OPTIMIZATION
9370 PtrHashMap::PtrIterator i = m_assemblyMap.begin();
9374 Assembly *pAssembly = (Assembly*) i.GetValue();
9379 ListLockEntry* pElement;
9380 pElement = m_FileCreateLock.Pop(TRUE);
9383 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
9384 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
9387 pElement = (FileLoadLock*) m_FileCreateLock.Pop(TRUE);
9389 m_FileCreateLock.Destroy();
9390 #endif // FEATURE_LOADER_OPTIMIZATION
9391 BaseDomain::Terminate();
9393 #endif // CROSSGEN_COMPILE
9397 #ifdef FEATURE_LOADER_OPTIMIZATION
9399 BOOL SharedDomain::CompareSharedAssembly(UPTR u1, UPTR u2)
9409 // This is the input to the lookup
9410 SharedAssemblyLocator *pLocator = (SharedAssemblyLocator *) (u1<<1);
9412 // This is the value stored in the table
9413 Assembly *pAssembly = (Assembly *) u2;
9414 if (pLocator->GetType()==SharedAssemblyLocator::DOMAINASSEMBLY)
9416 if (!pAssembly->GetManifestFile()->Equals(pLocator->GetDomainAssembly()->GetFile()))
9419 return pAssembly->CanBeShared(pLocator->GetDomainAssembly());
9422 if (pLocator->GetType()==SharedAssemblyLocator::PEASSEMBLY)
9423 return pAssembly->GetManifestFile()->Equals(pLocator->GetPEAssembly());
9425 if (pLocator->GetType()==SharedAssemblyLocator::PEASSEMBLYEXACT)
9426 return pAssembly->GetManifestFile() == pLocator->GetPEAssembly();
9427 _ASSERTE(!"Unexpected type of assembly locator");
9431 DWORD SharedAssemblyLocator::Hash()
9438 INJECT_FAULT(COMPlusThrowOM(););
9441 if (m_type==DOMAINASSEMBLY)
9442 return GetDomainAssembly()->HashIdentity();
9443 if (m_type==PEASSEMBLY||m_type==PEASSEMBLYEXACT)
9444 return GetPEAssembly()->HashIdentity();
9445 _ASSERTE(!"Unexpected type of assembly locator");
9449 Assembly * SharedDomain::FindShareableAssembly(SharedAssemblyLocator * pLocator)
9456 INJECT_FAULT(COMPlusThrowOM(););
9460 Assembly * match= (Assembly *) m_assemblyMap.LookupValue(pLocator->Hash(), pLocator);
9461 if (match != (Assembly *) INVALIDENTRY)
9467 SIZE_T SharedDomain::GetShareableAssemblyCount()
9469 LIMITED_METHOD_CONTRACT;
9471 return m_assemblyMap.GetCount();
9474 void SharedDomain::AddShareableAssembly(Assembly * pAssembly)
9481 INJECT_FAULT(COMPlusThrowOM(););
9485 // We have a lock on the file. There should be no races to add the same assembly.
9488 LockHolder holder(this);
9492 pAssembly->SetIsTenured();
9493 m_assemblyMap.InsertValue(pAssembly->HashIdentity(), pAssembly);
9497 // There was an error adding the assembly to the assembly hash (probably an OOM),
9498 // so we need to unset the tenured bit so that correct cleanup can happen.
9499 pAssembly->UnsetIsTenured();
9504 LOG((LF_CODESHARING,
9506 "Successfully added shareable assembly \"%s\".\n",
9507 pAssembly->GetManifestFile()->GetSimpleName()));
9510 #endif // FEATURE_LOADER_OPTIMIZATION
9511 #endif // !DACCESS_COMPILE
9513 DWORD DomainLocalModule::GetClassFlags(MethodTable* pMT, DWORD iClassIndex /*=(DWORD)-1*/)
9521 { // SO tolerance exception for debug-only assertion.
9522 CONTRACT_VIOLATION(SOToleranceViolation);
9523 CONSISTENCY_CHECK(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9526 if (pMT->IsDynamicStatics())
9528 _ASSERTE(!pMT->ContainsGenericVariables());
9529 DWORD dynamicClassID = pMT->GetModuleDynamicEntryID();
9530 if(m_aDynamicEntries <= dynamicClassID)
9532 return (m_pDynamicClassTable[dynamicClassID].m_dwFlags);
9536 if (iClassIndex == (DWORD)-1)
9537 iClassIndex = pMT->GetClassIndex();
9538 return GetPrecomputedStaticsClassData()[iClassIndex];
9542 #ifndef DACCESS_COMPILE
9544 void DomainLocalModule::SetClassInitialized(MethodTable* pMT)
9554 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9556 _ASSERTE(!IsClassInitialized(pMT));
9557 _ASSERTE(!IsClassInitError(pMT));
9559 SetClassFlags(pMT, ClassInitFlags::INITIALIZED_FLAG);
9562 void DomainLocalModule::SetClassInitError(MethodTable* pMT)
9564 WRAPPER_NO_CONTRACT;
9566 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9568 SetClassFlags(pMT, ClassInitFlags::ERROR_FLAG);
9571 void DomainLocalModule::SetClassFlags(MethodTable* pMT, DWORD dwFlags)
9576 PRECONDITION(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9577 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9578 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9581 if (pMT->IsDynamicStatics())
9583 _ASSERTE(!pMT->ContainsGenericVariables());
9584 DWORD dwID = pMT->GetModuleDynamicEntryID();
9585 EnsureDynamicClassIndex(dwID);
9586 m_pDynamicClassTable[dwID].m_dwFlags |= dwFlags;
9590 GetPrecomputedStaticsClassData()[pMT->GetClassIndex()] |= dwFlags;
9594 void DomainLocalModule::EnsureDynamicClassIndex(DWORD dwID)
9601 INJECT_FAULT(COMPlusThrowOM(););
9602 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9603 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9607 if (dwID < m_aDynamicEntries)
9609 _ASSERTE(m_pDynamicClassTable.Load() != NULL);
9613 SIZE_T aDynamicEntries = max(16, m_aDynamicEntries.Load());
9614 while (aDynamicEntries <= dwID)
9616 aDynamicEntries *= 2;
9619 DynamicClassInfo* pNewDynamicClassTable;
9620 pNewDynamicClassTable = (DynamicClassInfo*)
9621 (void*)GetDomainFile()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(
9622 S_SIZE_T(sizeof(DynamicClassInfo)) * S_SIZE_T(aDynamicEntries));
9624 memcpy(pNewDynamicClassTable, m_pDynamicClassTable, sizeof(DynamicClassInfo) * m_aDynamicEntries);
9626 // Note: Memory allocated on loader heap is zero filled
9627 // memset(pNewDynamicClassTable + m_aDynamicEntries, 0, (aDynamicEntries - m_aDynamicEntries) * sizeof(DynamicClassInfo));
9629 _ASSERTE(m_aDynamicEntries%2 == 0);
9631 // Commit new dynamic table. The lock-free helpers depend on the order.
9633 m_pDynamicClassTable = pNewDynamicClassTable;
9635 m_aDynamicEntries = aDynamicEntries;
9638 #ifndef CROSSGEN_COMPILE
9639 void DomainLocalModule::AllocateDynamicClass(MethodTable *pMT)
9645 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9646 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9650 _ASSERTE(!pMT->ContainsGenericVariables());
9651 _ASSERTE(!pMT->IsSharedByGenericInstantiations());
9652 _ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9653 _ASSERTE(pMT->IsDynamicStatics());
9655 DWORD dynamicEntryIDIndex = pMT->GetModuleDynamicEntryID();
9657 EnsureDynamicClassIndex(dynamicEntryIDIndex);
9659 _ASSERTE(m_aDynamicEntries > dynamicEntryIDIndex);
9661 EEClass *pClass = pMT->GetClass();
9663 DWORD dwStaticBytes = pClass->GetNonGCRegularStaticFieldBytes();
9664 DWORD dwNumHandleStatics = pClass->GetNumHandleRegularStatics();
9666 _ASSERTE(!IsClassAllocated(pMT));
9667 _ASSERTE(!IsClassInitialized(pMT));
9668 _ASSERTE(!IsClassInitError(pMT));
9670 DynamicEntry *pDynamicStatics = m_pDynamicClassTable[dynamicEntryIDIndex].m_pDynamicEntry;
9672 // We need this check because maybe a class had a cctor but no statics
9673 if (dwStaticBytes > 0 || dwNumHandleStatics > 0)
9675 if (pDynamicStatics == NULL)
9677 LoaderHeap * pLoaderAllocator = GetDomainFile()->GetLoaderAllocator()->GetHighFrequencyHeap();
9679 if (pMT->Collectible())
9681 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocMem(S_SIZE_T(sizeof(CollectibleDynamicEntry)));
9685 SIZE_T dynamicEntrySize = DynamicEntry::GetOffsetOfDataBlob() + dwStaticBytes;
9687 #ifdef FEATURE_64BIT_ALIGNMENT
9688 // Allocate memory with extra alignment only if it is really necessary
9689 if (dwStaticBytes >= MAX_PRIMITIVE_FIELD_SIZE)
9691 static_assert_no_msg(sizeof(NormalDynamicEntry) % MAX_PRIMITIVE_FIELD_SIZE == 0);
9692 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocAlignedMem(dynamicEntrySize, MAX_PRIMITIVE_FIELD_SIZE);
9696 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocMem(S_SIZE_T(dynamicEntrySize));
9699 // Note: Memory allocated on loader heap is zero filled
9701 m_pDynamicClassTable[dynamicEntryIDIndex].m_pDynamicEntry = pDynamicStatics;
9704 if (pMT->Collectible() && (dwStaticBytes != 0))
9707 OBJECTREF nongcStaticsArray = NULL;
9708 GCPROTECT_BEGIN(nongcStaticsArray);
9709 #ifdef FEATURE_64BIT_ALIGNMENT
9710 // Allocate memory with extra alignment only if it is really necessary
9711 if (dwStaticBytes >= MAX_PRIMITIVE_FIELD_SIZE)
9712 nongcStaticsArray = AllocatePrimitiveArray(ELEMENT_TYPE_I8, (dwStaticBytes + (sizeof(CLR_I8)-1)) / (sizeof(CLR_I8)));
9715 nongcStaticsArray = AllocatePrimitiveArray(ELEMENT_TYPE_U1, dwStaticBytes);
9716 ((CollectibleDynamicEntry *)pDynamicStatics)->m_hNonGCStatics = GetDomainFile()->GetModule()->GetLoaderAllocator()->AllocateHandle(nongcStaticsArray);
9719 if (dwNumHandleStatics > 0)
9721 if (!pMT->Collectible())
9723 GetAppDomain()->AllocateStaticFieldObjRefPtrs(dwNumHandleStatics,
9724 &((NormalDynamicEntry *)pDynamicStatics)->m_pGCStatics);
9729 OBJECTREF gcStaticsArray = NULL;
9730 GCPROTECT_BEGIN(gcStaticsArray);
9731 gcStaticsArray = AllocateObjectArray(dwNumHandleStatics, g_pObjectClass);
9732 ((CollectibleDynamicEntry *)pDynamicStatics)->m_hGCStatics = GetDomainFile()->GetModule()->GetLoaderAllocator()->AllocateHandle(gcStaticsArray);
9740 void DomainLocalModule::PopulateClass(MethodTable *pMT)
9749 _ASSERTE(!pMT->ContainsGenericVariables());
9751 // <todo> the only work actually done here for non-dynamics is the freezing related work.
9752 // See if we can eliminate this and make this a dynamic-only path </todo>
9753 DWORD iClassIndex = pMT->GetClassIndex();
9755 if (!IsClassAllocated(pMT, iClassIndex))
9757 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9759 if (!IsClassAllocated(pMT, iClassIndex))
9761 // Allocate dynamic space if necessary
9762 if (pMT->IsDynamicStatics())
9763 AllocateDynamicClass(pMT);
9765 // determine flags to set on the statics block
9766 DWORD dwFlags = ClassInitFlags::ALLOCATECLASS_FLAG;
9768 if (!pMT->HasClassConstructor() && !pMT->HasBoxedRegularStatics())
9770 _ASSERTE(!IsClassInitialized(pMT));
9771 _ASSERTE(!IsClassInitError(pMT));
9772 dwFlags |= ClassInitFlags::INITIALIZED_FLAG;
9775 if (pMT->Collectible())
9777 dwFlags |= ClassInitFlags::COLLECTIBLE_FLAG;
9780 // Set all flags at the same time to avoid races
9781 SetClassFlags(pMT, dwFlags);
9787 #endif // CROSSGEN_COMPILE
9789 void DomainLocalBlock::EnsureModuleIndex(ModuleIndex index)
9796 INJECT_FAULT(COMPlusThrowOM(););
9797 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9798 PRECONDITION(m_pDomain->OwnDomainLocalBlockLock());
9802 if (m_aModuleIndices > index.m_dwIndex)
9804 _ASSERTE(m_pModuleSlots != NULL);
9808 SIZE_T aModuleIndices = max(16, m_aModuleIndices);
9809 while (aModuleIndices <= index.m_dwIndex)
9811 aModuleIndices *= 2;
9814 PTR_DomainLocalModule* pNewModuleSlots = (PTR_DomainLocalModule*) (void*)m_pDomain->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(PTR_DomainLocalModule)) * S_SIZE_T(aModuleIndices));
9816 memcpy(pNewModuleSlots, m_pModuleSlots, sizeof(SIZE_T)*m_aModuleIndices);
9818 // Note: Memory allocated on loader heap is zero filled
9819 // memset(pNewModuleSlots + m_aModuleIndices, 0 , (aModuleIndices - m_aModuleIndices)*sizeof(PTR_DomainLocalModule) );
9821 // Commit new table. The lock-free helpers depend on the order.
9823 m_pModuleSlots = pNewModuleSlots;
9825 m_aModuleIndices = aModuleIndices;
9829 void DomainLocalBlock::SetModuleSlot(ModuleIndex index, PTR_DomainLocalModule pLocalModule)
9831 // Need to synchronize with table growth in this domain
9832 BaseDomain::DomainLocalBlockLockHolder lh(m_pDomain);
9834 EnsureModuleIndex(index);
9836 _ASSERTE(index.m_dwIndex < m_aModuleIndices);
9838 // We would like this assert here, unfortunately, loading a module in this appdomain can fail
9839 // after here and we will keep the module around and reuse the slot when we retry (if
9840 // the failure happened due to a transient error, such as OOM). In that case the slot wont
9842 //_ASSERTE(m_pModuleSlots[index.m_dwIndex] == 0);
9844 m_pModuleSlots[index.m_dwIndex] = pLocalModule;
9847 #ifndef CROSSGEN_COMPILE
9849 DomainAssembly* AppDomain::RaiseTypeResolveEventThrowing(DomainAssembly* pAssembly, LPCSTR szName, ASSEMBLYREF *pResultingAssemblyRef)
9856 INJECT_FAULT(COMPlusThrowOM(););
9860 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
9863 DomainAssembly* pResolvedAssembly = NULL;
9864 _ASSERTE(strcmp(szName, g_AppDomainClassName));
9869 OBJECTREF AppDomainRef;
9870 OBJECTREF AssemblyRef;
9873 ZeroMemory(&gc, sizeof(gc));
9875 GCPROTECT_BEGIN(gc);
9876 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
9878 if (pAssembly != NULL)
9879 gc.AssemblyRef = pAssembly->GetExposedAssemblyObject();
9881 MethodDescCallSite onTypeResolve(METHOD__APP_DOMAIN__ON_TYPE_RESOLVE, &gc.AppDomainRef);
9883 gc.str = StringObject::NewString(szName);
9886 ObjToArgSlot(gc.AppDomainRef),
9887 ObjToArgSlot(gc.AssemblyRef),
9888 ObjToArgSlot(gc.str)
9890 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onTypeResolve.Call_RetOBJECTREF(args);
9892 if (ResultingAssemblyRef != NULL)
9894 pResolvedAssembly = ResultingAssemblyRef->GetDomainAssembly();
9896 if (pResultingAssemblyRef)
9897 *pResultingAssemblyRef = ResultingAssemblyRef;
9900 if (pResolvedAssembly->IsCollectible())
9902 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleBoundNonCollectible"));
9909 return pResolvedAssembly;
9913 Assembly* AppDomain::RaiseResourceResolveEvent(DomainAssembly* pAssembly, LPCSTR szName)
9920 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
9921 INJECT_FAULT(COMPlusThrowOM(););
9925 Assembly* pResolvedAssembly = NULL;
9930 OBJECTREF AppDomainRef;
9931 OBJECTREF AssemblyRef;
9934 ZeroMemory(&gc, sizeof(gc));
9936 GCPROTECT_BEGIN(gc);
9937 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
9939 if (pAssembly != NULL)
9940 gc.AssemblyRef=pAssembly->GetExposedAssemblyObject();
9942 MethodDescCallSite onResourceResolve(METHOD__APP_DOMAIN__ON_RESOURCE_RESOLVE, &gc.AppDomainRef);
9943 gc.str = StringObject::NewString(szName);
9946 ObjToArgSlot(gc.AppDomainRef),
9947 ObjToArgSlot(gc.AssemblyRef),
9948 ObjToArgSlot(gc.str)
9950 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onResourceResolve.Call_RetOBJECTREF(args);
9951 if (ResultingAssemblyRef != NULL)
9953 pResolvedAssembly = ResultingAssemblyRef->GetAssembly();
9954 if (pResolvedAssembly->IsCollectible())
9956 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleAssemblyResolve"));
9962 RETURN pResolvedAssembly;
9967 AppDomain::RaiseAssemblyResolveEvent(
9968 AssemblySpec * pSpec,
9969 BOOL fIntrospection,
9977 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
9978 INJECT_FAULT(COMPlusThrowOM(););
9982 BinderMethodID methodId;
9983 StackSString ssName;
9984 pSpec->GetFileOrDisplayName(0, ssName);
9988 methodId = METHOD__APP_DOMAIN__ON_ASSEMBLY_RESOLVE; // post-bind execution event (the classic V1.0 event)
9996 // Elevate threads allowed loading level. This allows the host to load an assembly even in a restricted
9997 // condition. Note, however, that this exposes us to possible recursion failures, if the host tries to
9998 // load the assemblies currently being loaded. (Such cases would then throw an exception.)
10000 OVERRIDE_LOAD_LEVEL_LIMIT(FILE_ACTIVE);
10001 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
10005 Assembly* pAssembly = NULL;
10008 OBJECTREF AppDomainRef;
10009 OBJECTREF AssemblyRef;
10012 ZeroMemory(&gc, sizeof(gc));
10014 GCPROTECT_BEGIN(gc);
10015 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
10017 if (pSpec->GetParentAssembly() != NULL)
10020 gc.AssemblyRef=pSpec->GetParentAssembly()->GetExposedAssemblyObject();
10023 MethodDescCallSite onAssemblyResolve(methodId, &gc.AppDomainRef);
10025 gc.str = StringObject::NewString(ssName);
10026 ARG_SLOT args[3] = {
10027 ObjToArgSlot(gc.AppDomainRef),
10028 ObjToArgSlot(gc.AssemblyRef),
10029 ObjToArgSlot(gc.str)
10032 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onAssemblyResolve.Call_RetOBJECTREF(args);
10034 if (ResultingAssemblyRef != NULL)
10036 pAssembly = ResultingAssemblyRef->GetAssembly();
10037 if (pAssembly->IsCollectible())
10039 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleAssemblyResolve"));
10045 if (pAssembly != NULL)
10047 if ((!(pAssembly->IsIntrospectionOnly())) != (!fIntrospection))
10049 // Cannot return an introspection assembly from an execution callback or vice-versa
10050 COMPlusThrow(kFileLoadException, pAssembly->IsIntrospectionOnly() ? IDS_CLASSLOAD_ASSEMBLY_RESOLVE_RETURNED_INTROSPECTION : IDS_CLASSLOAD_ASSEMBLY_RESOLVE_RETURNED_EXECUTION);
10053 // Check that the public key token matches the one specified in the spec
10054 // MatchPublicKeys throws as appropriate
10055 pSpec->MatchPublicKeys(pAssembly);
10059 } // AppDomain::RaiseAssemblyResolveEvent
10062 //---------------------------------------------------------------------------------------
10064 // Determine the type of AppDomainManager to use for the default AppDomain
10067 // v2.0 of the CLR used environment variables APPDOMAIN_MANAGER_ASM and APPDOMAIN_MANAGER_TYPE to set the
10068 // domain manager. For compatibility these are still supported, along with appDomainManagerAsm and
10069 // appDomainManagerType config file switches. If the config switches are supplied, the entry point must be
10073 void AppDomain::InitializeDefaultDomainManager()
10080 INJECT_FAULT(COMPlusThrowOM(););
10081 PRECONDITION(GetId().m_dwId == DefaultADID);
10085 OBJECTREF orThis = GetExposedObject();
10086 GCPROTECT_BEGIN(orThis);
10088 MethodDescCallSite initCompatFlags(METHOD__APP_DOMAIN__INITIALIZE_COMPATIBILITY_FLAGS);
10091 ObjToArgSlot(orThis)
10094 initCompatFlags.Call(args);
10099 CLREvent * AppDomain::g_pUnloadStartEvent;
10101 void AppDomain::CreateADUnloadWorker()
10103 STANDARD_VM_CONTRACT;
10105 // Do not create adUnload thread if there is only default domain
10106 if(IsSingleAppDomain())
10110 BOOL fCreator = FALSE;
10111 if (FastInterlockCompareExchange((LONG *)&g_fADUnloadWorkerOK,-2,-1)==-1) //we're first
10113 #ifdef _TARGET_X86_ // use the smallest possible stack on X86
10114 DWORD stackSize = 128 * 1024;
10116 DWORD stackSize = 512 * 1024; // leave X64 unchanged since we have plenty of VM
10118 Thread *pThread = SetupUnstartedThread();
10119 if (pThread->CreateNewThread(stackSize, ADUnloadThreadStart, pThread))
10123 dwRet = pThread->StartThread();
10125 // When running under a user mode native debugger there is a race
10126 // between the moment we've created the thread (in CreateNewThread) and
10127 // the moment we resume it (in StartThread); the debugger may receive
10128 // the "ct" (create thread) notification, and it will attempt to
10129 // suspend/resume all threads in the process. Now imagine the debugger
10130 // resumes this thread first, and only later does it try to resume the
10131 // newly created thread (the ADU worker thread). In these conditions our
10132 // call to ResumeThread may come before the debugger's call to ResumeThread
10133 // actually causing dwRet to equal 2.
10134 // We cannot use IsDebuggerPresent() in the condition below because the
10135 // debugger may have been detached between the time it got the notification
10136 // and the moment we execute the test below.
10137 _ASSERTE(dwRet == 1 || dwRet == 2);
10141 pThread->DecExternalCount(FALSE);
10142 FastInterlockExchange((LONG *)&g_fADUnloadWorkerOK, -1);
10143 ThrowOutOfMemory();
10147 YIELD_WHILE (g_fADUnloadWorkerOK == -2);
10149 if (g_fADUnloadWorkerOK == -1) {
10152 ThrowOutOfMemory();
10161 /*static*/ void AppDomain::ADUnloadWorkerHelper(AppDomain *pDomain)
10163 STATIC_CONTRACT_NOTHROW;
10164 STATIC_CONTRACT_GC_TRIGGERS;
10165 STATIC_CONTRACT_MODE_COOPERATIVE;
10166 ADUnloadSink* pADUnloadSink=pDomain->GetADUnloadSinkForUnload();
10171 pDomain->Unload(FALSE);
10173 EX_CATCH_HRESULT(hr);
10177 SystemDomain::LockHolder lh;
10178 pADUnloadSink->ReportUnloadResult(hr,NULL);
10179 pADUnloadSink->Release();
10183 void AppDomain::DoADUnloadWork()
10190 INJECT_FAULT(COMPlusThrowOM(););
10197 AppDomain *pDomainToUnload = NULL;
10200 // Take the lock so that no domain can be added or removed from the system domain
10201 SystemDomain::LockHolder lh;
10203 DWORD numDomain = SystemDomain::GetCurrentAppDomainMaxIndex();
10204 for (; i <= numDomain; i ++) {
10205 AppDomain * pDomain = SystemDomain::TestGetAppDomainAtIndex(ADIndex(i));
10207 // @todo: We used to also select a domain if pDomain->IsUnload() returned true. But that causes
10208 // problems when we've failed to completely unload the AD in the past. If we've reached the CLEARED
10209 // stage, for instance, then there will be no default context and AppDomain::Exit() will simply crash.
10211 if (pDomain && pDomain->IsUnloadRequested())
10213 pDomainToUnload = pDomain;
10220 if (!pDomainToUnload) {
10224 // We are the only thread that can unload domains so no one else can delete the appdomain
10225 ADUnloadWorkerHelper(pDomainToUnload);
10229 static void DoADUnloadWorkHelper()
10231 STATIC_CONTRACT_NOTHROW;
10232 STATIC_CONTRACT_GC_TRIGGERS;
10233 STATIC_CONTRACT_MODE_COOPERATIVE;
10236 AppDomain::DoADUnloadWork();
10241 EX_END_CATCH(SwallowAllExceptions);
10244 ULONGLONG g_ObjFinalizeStartTime = 0;
10245 Volatile<BOOL> g_FinalizerIsRunning = FALSE;
10246 Volatile<ULONG> g_FinalizerLoopCount = 0;
10248 ULONGLONG GetObjFinalizeStartTime()
10250 LIMITED_METHOD_CONTRACT;
10251 return g_ObjFinalizeStartTime;
10254 void FinalizerThreadAbortOnTimeout()
10256 STATIC_CONTRACT_NOTHROW;
10257 STATIC_CONTRACT_MODE_COOPERATIVE;
10258 STATIC_CONTRACT_GC_TRIGGERS;
10261 // If finalizer thread is blocked because scheduler is running another task,
10262 // or it is waiting for another thread, we first see if we get finalizer thread
10264 Thread::ThreadAbortWatchDog();
10269 Thread *pFinalizerThread = FinalizerThread::GetFinalizerThread();
10270 EPolicyAction action = GetEEPolicy()->GetActionOnTimeout(OPR_FinalizerRun, pFinalizerThread);
10274 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10275 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10278 Thread::UAC_FinalizerTimeout);
10280 case eRudeAbortThread:
10281 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10282 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10285 Thread::UAC_FinalizerTimeout);
10287 case eUnloadAppDomain:
10289 AppDomain *pDomain = pFinalizerThread->GetDomain();
10290 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10293 Thread::UAC_FinalizerTimeout);
10294 if (!pDomain->IsDefaultDomain())
10296 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10297 pDomain->EnableADUnloadWorker(EEPolicy::ADU_Safe);
10301 case eRudeUnloadAppDomain:
10303 AppDomain *pDomain = pFinalizerThread->GetDomain();
10304 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10307 Thread::UAC_FinalizerTimeout);
10308 if (!pDomain->IsDefaultDomain())
10310 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10311 pDomain->EnableADUnloadWorker(EEPolicy::ADU_Rude);
10316 case eFastExitProcess:
10317 case eRudeExitProcess:
10318 case eDisableRuntime:
10319 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10320 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_TIMEOUT);
10321 _ASSERTE (!"Should not get here");
10330 EX_END_CATCH(SwallowAllExceptions);
10335 WT_UnloadDomain = 0x1,
10336 WT_ThreadAbort = 0x2,
10337 WT_FinalizerThread = 0x4,
10338 WT_ClearCollectedDomains=0x8
10341 static Volatile<DWORD> s_WorkType = 0;
10344 DWORD WINAPI AppDomain::ADUnloadThreadStart(void *args)
10349 DISABLED(GC_TRIGGERS);
10351 // This function will always be at the very bottom of the stack. The only
10352 // user code it calls is the AppDomainUnload notifications which we will
10353 // not be hardenning for Whidbey.
10359 BEGIN_ENTRYPOINT_NOTHROW;
10361 ClrFlsSetThreadType (ThreadType_ADUnloadHelper);
10363 Thread *pThread = (Thread*)args;
10364 bool fOK = (pThread->HasStarted() != 0);
10367 GCX_MAYBE_PREEMP(fOK);
10369 _ASSERTE (g_fADUnloadWorkerOK == -2);
10371 FastInterlockExchange((LONG *)&g_fADUnloadWorkerOK,fOK?1:-1);
10375 DestroyThread(pThread);
10379 pThread->SetBackground(TRUE);
10381 pThread->SetThreadStateNC(Thread::TSNC_ADUnloadHelper);
10384 DWORD TAtimeout = INFINITE;
10385 ULONGLONG endTime = Thread::GetNextSelfAbortEndTime();
10386 ULONGLONG curTime = CLRGetTickCount64();
10387 if (endTime <= curTime) {
10392 ULONGLONG diff = endTime - curTime;
10393 if (diff < MAXULONG)
10395 TAtimeout = (DWORD)diff;
10398 ULONGLONG finalizeStartTime = GetObjFinalizeStartTime();
10399 DWORD finalizeTimeout = INFINITE;
10400 DWORD finalizeTimeoutSetting = GetEEPolicy()->GetTimeout(OPR_FinalizerRun);
10401 if (finalizeTimeoutSetting != INFINITE && g_FinalizerIsRunning)
10403 if (finalizeStartTime == 0)
10405 finalizeTimeout = finalizeTimeoutSetting;
10409 endTime = finalizeStartTime + finalizeTimeoutSetting;
10410 if (endTime <= curTime) {
10411 finalizeTimeout = 0;
10415 ULONGLONG diff = endTime - curTime;
10416 if (diff < MAXULONG)
10418 finalizeTimeout = (DWORD)diff;
10424 if (AppDomain::HasWorkForFinalizerThread())
10426 if (finalizeTimeout > finalizeTimeoutSetting)
10428 finalizeTimeout = finalizeTimeoutSetting;
10432 DWORD timeout = INFINITE;
10433 if (finalizeTimeout <= TAtimeout)
10435 timeout = finalizeTimeout;
10439 timeout = TAtimeout;
10444 LOG((LF_APPDOMAIN, LL_INFO10, "Waiting to start unload\n"));
10445 g_pUnloadStartEvent->Wait(timeout,FALSE);
10448 if (finalizeTimeout != INFINITE || (s_WorkType & WT_FinalizerThread) != 0)
10450 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for Finalizer thread\n");
10451 FastInterlockAnd(&s_WorkType, ~WT_FinalizerThread);
10452 // only watch finalizer thread is finalizer method or unloadevent is being processed
10453 if (GetObjFinalizeStartTime() == finalizeStartTime && finalizeStartTime != 0 && g_FinalizerIsRunning)
10455 if (CLRGetTickCount64() >= finalizeStartTime+finalizeTimeoutSetting)
10458 FinalizerThreadAbortOnTimeout();
10461 if (s_fProcessUnloadDomainEvent && g_FinalizerIsRunning)
10464 FinalizerThreadAbortOnTimeout();
10468 if (TAtimeout != INFINITE || (s_WorkType & WT_ThreadAbort) != 0)
10470 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for thread abort\n");
10471 FastInterlockAnd(&s_WorkType, ~WT_ThreadAbort);
10473 Thread::ThreadAbortWatchDog();
10476 if ((s_WorkType & WT_UnloadDomain) != 0 && !AppDomain::HasWorkForFinalizerThread())
10478 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for AD unload\n");
10479 FastInterlockAnd(&s_WorkType, ~WT_UnloadDomain);
10481 DoADUnloadWorkHelper();
10484 if ((s_WorkType & WT_ClearCollectedDomains) != 0)
10486 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for AD cleanup\n");
10487 FastInterlockAnd(&s_WorkType, ~WT_ClearCollectedDomains);
10489 SystemDomain::System()->ClearCollectedDomains();
10496 END_ENTRYPOINT_NOTHROW;
10501 void AppDomain::EnableADUnloadWorker()
10507 SO_TOLERANT; // Called during a SO
10511 EEPolicy::AppDomainUnloadTypes type = EEPolicy::ADU_Safe;
10514 DWORD hostTestADUnload = g_pConfig->GetHostTestADUnload();
10515 if (hostTestADUnload == 2) {
10516 type = EEPolicy::ADU_Rude;
10520 EnableADUnloadWorker(type);
10523 void AppDomain::EnableADUnloadWorker(EEPolicy::AppDomainUnloadTypes type, BOOL fHasStack)
10529 SO_TOLERANT; // Called during a SO
10533 FastInterlockOr (&s_WorkType, WT_UnloadDomain);
10535 LONG stage = m_Stage;
10536 static_assert_no_msg(sizeof(m_Stage) == sizeof(int));
10538 _ASSERTE(!IsDefaultDomain());
10540 // Mark unload requested.
10541 if (type == EEPolicy::ADU_Rude) {
10544 while (stage < STAGE_UNLOAD_REQUESTED) {
10545 stage = FastInterlockCompareExchange((LONG*)&m_Stage,STAGE_UNLOAD_REQUESTED,stage);
10550 // Can not call Set due to limited stack.
10553 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker\n"));
10554 g_pUnloadStartEvent->Set();
10557 void AppDomain::EnableADUnloadWorkerForThreadAbort()
10559 LIMITED_METHOD_CONTRACT;
10560 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "Enabling unload worker for thread abort\n");
10561 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for thread abort\n"));
10562 FastInterlockOr (&s_WorkType, WT_ThreadAbort);
10563 g_pUnloadStartEvent->Set();
10567 void AppDomain::EnableADUnloadWorkerForFinalizer()
10569 LIMITED_METHOD_CONTRACT;
10570 if (GetEEPolicy()->GetTimeout(OPR_FinalizerRun) != INFINITE)
10572 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for Finalizer Thread\n"));
10573 FastInterlockOr (&s_WorkType, WT_FinalizerThread);
10574 g_pUnloadStartEvent->Set();
10578 void AppDomain::EnableADUnloadWorkerForCollectedADCleanup()
10580 LIMITED_METHOD_CONTRACT;
10581 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for collected domains\n"));
10582 FastInterlockOr (&s_WorkType, WT_ClearCollectedDomains);
10583 g_pUnloadStartEvent->Set();
10587 void SystemDomain::ClearCollectedDomains()
10597 AppDomain* pDomainsToClear=NULL;
10599 CrstHolder lh(&m_DelayedUnloadCrst);
10600 for (AppDomain** ppDomain=&m_pDelayedUnloadList;(*ppDomain)!=NULL; )
10602 if ((*ppDomain)->m_Stage==AppDomain::STAGE_COLLECTED)
10604 AppDomain* pAppDomain=*ppDomain;
10605 *ppDomain=(*ppDomain)->m_pNextInDelayedUnloadList;
10606 pAppDomain->m_pNextInDelayedUnloadList=pDomainsToClear;
10607 pDomainsToClear=pAppDomain;
10610 ppDomain=&((*ppDomain)->m_pNextInDelayedUnloadList);
10614 for (AppDomain* pDomain=pDomainsToClear;pDomain!=NULL;)
10616 AppDomain* pNext=pDomain->m_pNextInDelayedUnloadList;
10617 pDomain->Close(); //NOTHROW!
10618 pDomain->Release();
10623 void SystemDomain::ProcessClearingDomains()
10632 CrstHolder lh(&m_DelayedUnloadCrst);
10634 for (AppDomain** ppDomain=&m_pDelayedUnloadList;(*ppDomain)!=NULL; )
10636 if ((*ppDomain)->m_Stage==AppDomain::STAGE_HANDLETABLE_NOACCESS)
10638 AppDomain* pAppDomain=*ppDomain;
10639 pAppDomain->SetStage(AppDomain::STAGE_CLEARED);
10641 ppDomain=&((*ppDomain)->m_pNextInDelayedUnloadList);
10644 if (!m_UnloadIsAsync)
10646 // For synchronous mode, we are now done with the list.
10647 m_pDelayedUnloadList = NULL;
10651 void SystemDomain::ProcessDelayedUnloadDomains()
10661 int iGCRefPoint=GCHeapUtilities::GetGCHeap()->CollectionCount(GCHeapUtilities::GetGCHeap()->GetMaxGeneration());
10662 if (GCHeapUtilities::GetGCHeap()->IsConcurrentGCInProgress())
10665 BOOL bAppDomainToCleanup = FALSE;
10666 LoaderAllocator * pAllocatorsToDelete = NULL;
10669 CrstHolder lh(&m_DelayedUnloadCrst);
10671 for (AppDomain* pDomain=m_pDelayedUnloadList; pDomain!=NULL; pDomain=pDomain->m_pNextInDelayedUnloadList)
10673 if (pDomain->m_Stage==AppDomain::STAGE_CLEARED)
10675 // Compare with 0 to handle overflows gracefully
10676 if (0 < iGCRefPoint - pDomain->GetGCRefPoint())
10678 bAppDomainToCleanup=TRUE;
10679 pDomain->SetStage(AppDomain::STAGE_COLLECTED);
10684 LoaderAllocator ** ppAllocator=&m_pDelayedUnloadListOfLoaderAllocators;
10685 while (*ppAllocator!= NULL)
10687 LoaderAllocator * pAllocator = *ppAllocator;
10688 if (0 < iGCRefPoint - pAllocator->GetGCRefPoint())
10690 *ppAllocator = pAllocator->m_pLoaderAllocatorDestroyNext;
10692 pAllocator->m_pLoaderAllocatorDestroyNext = pAllocatorsToDelete;
10693 pAllocatorsToDelete = pAllocator;
10697 ppAllocator = &pAllocator->m_pLoaderAllocatorDestroyNext;
10702 if (bAppDomainToCleanup)
10703 AppDomain::EnableADUnloadWorkerForCollectedADCleanup();
10705 // Delete collected loader allocators on the finalizer thread. We cannot offload it to appdomain unload thread because of
10706 // there is not guaranteed to be one, and it is not that expensive operation anyway.
10707 while (pAllocatorsToDelete != NULL)
10709 LoaderAllocator * pAllocator = pAllocatorsToDelete;
10710 pAllocatorsToDelete = pAllocator->m_pLoaderAllocatorDestroyNext;
10715 #endif // CROSSGEN_COMPILE
10717 AppDomainFromIDHolder::AppDomainFromIDHolder(ADID adId, BOOL bUnsafePoint, SyncType synctype)
10719 WRAPPER_NO_CONTRACT;
10720 ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
10727 Assign(adId, bUnsafePoint);
10730 AppDomainFromIDHolder::AppDomainFromIDHolder(SyncType synctype)
10732 LIMITED_METHOD_CONTRACT;
10733 ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
10742 #ifndef CROSSGEN_COMPILE
10743 void ADUnloadSink::ReportUnloadResult (HRESULT hr, OBJECTREF* pException)
10749 PRECONDITION(CheckPointer(this));
10750 PRECONDITION(m_UnloadCompleteEvent.IsValid());
10754 //pException is unused;
10756 m_UnloadCompleteEvent.Set();
10759 void ADUnloadSink::WaitUnloadCompletion()
10765 PRECONDITION(CheckPointer(this));
10766 PRECONDITION(m_UnloadCompleteEvent.IsValid());
10770 CONTRACT_VIOLATION(FaultViolation);
10771 m_UnloadCompleteEvent.WaitEx(INFINITE, (WaitMode)(WaitMode_Alertable | WaitMode_ADUnload));
10774 ADUnloadSink* AppDomain::PrepareForWaitUnloadCompletion()
10780 PRECONDITION(SystemDomain::IsUnderDomainLock());
10785 ADUnloadSink* pADSink=GetADUnloadSink();
10786 PREFIX_ASSUME(pADSink!=NULL);
10787 if (m_Stage < AppDomain::STAGE_UNLOAD_REQUESTED) //we're first
10790 SetUnloadRequestThread(GetThread());
10795 ADUnloadSink::ADUnloadSink()
10803 INJECT_FAULT(COMPlusThrowOM(););
10808 m_UnloadCompleteEvent.CreateManualEvent(FALSE);
10809 m_UnloadResult=S_OK;
10812 ADUnloadSink::~ADUnloadSink()
10822 m_UnloadCompleteEvent.CloseEvent();
10827 ULONG ADUnloadSink::AddRef()
10829 LIMITED_METHOD_CONTRACT;
10830 return InterlockedIncrement(&m_cRef);
10833 ULONG ADUnloadSink::Release()
10835 LIMITED_METHOD_CONTRACT;
10836 ULONG ulRef = InterlockedDecrement(&m_cRef);
10844 void ADUnloadSink::Reset()
10846 LIMITED_METHOD_CONTRACT;
10847 m_UnloadResult=S_OK;
10848 m_UnloadCompleteEvent.Reset();
10851 ADUnloadSink* AppDomain::GetADUnloadSink()
10853 LIMITED_METHOD_CONTRACT;
10854 _ASSERTE(SystemDomain::IsUnderDomainLock());
10856 m_ADUnloadSink->AddRef();
10857 return m_ADUnloadSink;
10860 ADUnloadSink* AppDomain::GetADUnloadSinkForUnload()
10862 // unload thread only. Doesn't need to have AD lock
10863 LIMITED_METHOD_CONTRACT;
10865 m_ADUnloadSink->AddRef();
10866 return m_ADUnloadSink;
10868 #endif // CROSSGEN_COMPILE
10870 void AppDomain::EnumStaticGCRefs(promote_func* fn, ScanContext* sc)
10879 _ASSERTE(GCHeapUtilities::IsGCInProgress() &&
10880 GCHeapUtilities::IsServerHeap() &&
10881 IsGCSpecialThread());
10883 AppDomain::AssemblyIterator asmIterator = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution));
10884 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
10885 while (asmIterator.Next(pDomainAssembly.This()))
10887 // @TODO: Review when DomainAssemblies get added.
10888 _ASSERTE(pDomainAssembly != NULL);
10889 pDomainAssembly->EnumStaticGCRefs(fn, sc);
10895 #endif // !DACCESS_COMPILE
10897 //------------------------------------------------------------------------
10898 UINT32 BaseDomain::GetTypeID(PTR_MethodTable pMT) {
10902 PRECONDITION(pMT->GetDomain() == this);
10905 return m_typeIDMap.GetTypeID(pMT);
10908 //------------------------------------------------------------------------
10909 // Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
10910 UINT32 BaseDomain::LookupTypeID(PTR_MethodTable pMT)
10915 WRAPPER(GC_TRIGGERS);
10916 PRECONDITION(pMT->GetDomain() == this);
10919 return m_typeIDMap.LookupTypeID(pMT);
10922 //------------------------------------------------------------------------
10923 PTR_MethodTable BaseDomain::LookupType(UINT32 id) {
10927 WRAPPER(GC_TRIGGERS);
10928 CONSISTENCY_CHECK(id != TYPE_ID_THIS_CLASS);
10931 PTR_MethodTable pMT = m_typeIDMap.LookupType(id);
10932 if (pMT == NULL && !IsSharedDomain()) {
10933 pMT = SharedDomain::GetDomain()->LookupType(id);
10936 CONSISTENCY_CHECK(CheckPointer(pMT));
10937 CONSISTENCY_CHECK(pMT->IsInterface());
10941 #ifndef DACCESS_COMPILE
10944 //------------------------------------------------------------------------
10945 BOOL GetCompatibilityFlag(CompatibilityFlag flag)
10955 #endif // !DACCESS_COMPILE
10957 //---------------------------------------------------------------------------------------
10960 AppDomain::AssemblyIterator::Next(
10961 CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder)
10965 WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
10969 CrstHolder ch(m_pAppDomain->GetAssemblyListLock());
10970 return Next_Unlocked(pDomainAssemblyHolder);
10973 //---------------------------------------------------------------------------------------
10975 // Note: Does not lock the assembly list, but locks collectible assemblies for adding references.
10978 AppDomain::AssemblyIterator::Next_Unlocked(
10979 CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder)
10987 #ifndef DACCESS_COMPILE
10988 _ASSERTE(m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
10991 while (m_Iterator.Next())
10993 // Get element from the list/iterator (without adding reference to the assembly)
10994 DomainAssembly * pDomainAssembly = dac_cast<PTR_DomainAssembly>(m_Iterator.GetElement());
10995 if (pDomainAssembly == NULL)
11000 if (pDomainAssembly->IsError())
11002 if (m_assemblyIterationFlags & kIncludeFailedToLoad)
11004 *pDomainAssemblyHolder = pDomainAssembly;
11007 continue; // reject
11010 // First, reject DomainAssemblies whose load status is not to be included in
11013 if (pDomainAssembly->IsAvailableToProfilers() &&
11014 (m_assemblyIterationFlags & kIncludeAvailableToProfilers))
11016 // The assembly has reached the state at which we would notify profilers,
11017 // and we're supposed to include such assemblies in the enumeration. So
11018 // don't reject it (i.e., noop here, and don't bother with the rest of
11019 // the load status checks). Check for this first, since
11020 // kIncludeAvailableToProfilers contains some loaded AND loading
11023 else if (pDomainAssembly->IsLoaded())
11025 // A loaded assembly
11026 if (!(m_assemblyIterationFlags & kIncludeLoaded))
11028 continue; // reject
11033 // A loading assembly
11034 if (!(m_assemblyIterationFlags & kIncludeLoading))
11036 continue; // reject
11040 // Next, reject DomainAssemblies whose execution / introspection status is
11041 // not to be included in the enumeration
11043 if (pDomainAssembly->IsIntrospectionOnly())
11045 // introspection assembly
11046 if (!(m_assemblyIterationFlags & kIncludeIntrospection))
11048 continue; // reject
11053 // execution assembly
11054 if (!(m_assemblyIterationFlags & kIncludeExecution))
11056 continue; // reject
11060 // Next, reject collectible assemblies
11061 if (pDomainAssembly->IsCollectible())
11063 if (m_assemblyIterationFlags & kExcludeCollectible)
11065 _ASSERTE(!(m_assemblyIterationFlags & kIncludeCollected));
11066 continue; // reject
11069 // Un-tenured collectible assemblies should not be returned. (This can only happen in a brief
11070 // window during collectible assembly creation. No thread should need to have a pointer
11071 // to the just allocated DomainAssembly at this stage.)
11072 if (!pDomainAssembly->GetAssembly()->GetManifestModule()->IsTenured())
11074 continue; // reject
11077 if (pDomainAssembly->GetLoaderAllocator()->AddReferenceIfAlive())
11078 { // The assembly is alive
11080 // Set the holder value (incl. increasing ref-count)
11081 *pDomainAssemblyHolder = pDomainAssembly;
11083 // Now release the reference we took in the if-condition
11084 pDomainAssembly->GetLoaderAllocator()->Release();
11087 // The assembly is not alive anymore (and we didn't increase its ref-count in the
11090 if (!(m_assemblyIterationFlags & kIncludeCollected))
11092 continue; // reject
11094 // Set the holder value to assembly with 0 ref-count without increasing the ref-count (won't
11095 // call Release either)
11096 pDomainAssemblyHolder->Assign(pDomainAssembly, FALSE);
11100 *pDomainAssemblyHolder = pDomainAssembly;
11104 *pDomainAssemblyHolder = NULL;
11106 } // AppDomain::AssemblyIterator::Next_Unlocked
11108 #ifndef DACCESS_COMPILE
11110 //---------------------------------------------------------------------------------------
11112 // Can be called only from AppDomain shutdown code:AppDomain::ShutdownAssemblies.
11113 // Does not add-ref collectible assemblies (as the LoaderAllocator might not be reachable from the
11114 // DomainAssembly anymore).
11117 AppDomain::AssemblyIterator::Next_UnsafeNoAddRef(
11118 DomainAssembly ** ppDomainAssembly)
11126 // Make sure we are iterating all assemblies (see the only caller code:AppDomain::ShutdownAssemblies)
11127 _ASSERTE(m_assemblyIterationFlags ==
11128 (kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
11129 // It also means that we do not exclude anything
11130 _ASSERTE((m_assemblyIterationFlags & kExcludeCollectible) == 0);
11132 // We are on shutdown path, so lock shouldn't be neccessary, but all _Unlocked methods on AssemblyList
11133 // have asserts that the lock is held, so why not to take it ...
11134 CrstHolder ch(m_pAppDomain->GetAssemblyListLock());
11136 while (m_Iterator.Next())
11138 // Get element from the list/iterator (without adding reference to the assembly)
11139 *ppDomainAssembly = dac_cast<PTR_DomainAssembly>(m_Iterator.GetElement());
11140 if (*ppDomainAssembly == NULL)
11148 *ppDomainAssembly = NULL;
11150 } // AppDomain::AssemblyIterator::Next_UnsafeNoAddRef
11153 //---------------------------------------------------------------------------------------
11155 BOOL AppDomain::IsImageFromTrustedPath(PEImage* pPEImage)
11162 PRECONDITION(CheckPointer(pPEImage));
11166 const SString &sImagePath = pPEImage->GetPath();
11168 return !sImagePath.IsEmpty();
11171 #endif //!DACCESS_COMPILE
11173 #if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
11175 // Returns a BOOL indicating if the binding model has been locked for the AppDomain
11176 BOOL AppDomain::IsBindingModelLocked()
11186 return m_fIsBindingModelLocked.Load();
11189 // Marks the binding model locked for AppDomain
11190 BOOL AppDomain::LockBindingModel()
11192 LIMITED_METHOD_CONTRACT;
11194 BOOL fDidWeLockBindingModel = FALSE;
11196 if (InterlockedCompareExchangeT<BOOL>(&m_fIsBindingModelLocked, TRUE, FALSE) == FALSE)
11198 fDidWeLockBindingModel = TRUE;
11201 return fDidWeLockBindingModel;
11204 BOOL AppDomain::IsHostAssemblyResolverInUse()
11206 LIMITED_METHOD_CONTRACT;
11208 return (GetFusionContext() != GetTPABinderContext());
11211 // Helper used by the assembly binder to check if the specified AppDomain can use apppath assembly resolver
11212 BOOL RuntimeCanUseAppPathAssemblyResolver(DWORD adid)
11216 NOTHROW; // Cannot throw since it is invoked by the Binder that expects to get a hresult
11224 // We need to be in COOP mode to get the AppDomain*
11227 AppDomain *pTargetDomain = SystemDomain::GetAppDomainFromId(id, ADV_CURRENTAD);
11228 _ASSERTE(pTargetDomain != NULL);
11230 pTargetDomain->LockBindingModel();
11232 return !pTargetDomain->IsHostAssemblyResolverInUse();
11235 // Returns S_OK if the assembly was successfully loaded
11236 HRESULT RuntimeInvokeHostAssemblyResolver(INT_PTR pManagedAssemblyLoadContextToBindWithin, IAssemblyName *pIAssemblyName, CLRPrivBinderCoreCLR *pTPABinder, BINDER_SPACE::AssemblyName *pAssemblyName, ICLRPrivAssembly **ppLoadedAssembly)
11243 PRECONDITION(ppLoadedAssembly != NULL);
11247 HRESULT hr = E_FAIL;
11249 // DevDiv #933506: Exceptions thrown during AssemblyLoadContext.Load should propagate
11252 // Switch to COOP mode since we are going to work with managed references
11257 ASSEMBLYNAMEREF oRefAssemblyName;
11258 ASSEMBLYREF oRefLoadedAssembly;
11261 ZeroMemory(&_gcRefs, sizeof(_gcRefs));
11263 GCPROTECT_BEGIN(_gcRefs);
11265 ICLRPrivAssembly *pAssemblyBindingContext = NULL;
11267 bool fInvokedForTPABinder = (pTPABinder == NULL)?true:false;
11269 // Prepare to invoke System.Runtime.Loader.AssemblyLoadContext.Resolve method.
11271 // First, initialize an assembly spec for the requested assembly
11274 hr = spec.Init(pIAssemblyName);
11277 bool fResolvedAssembly = false;
11278 bool fResolvedAssemblyViaTPALoadContext = false;
11280 // Allocate an AssemblyName managed object
11281 _gcRefs.oRefAssemblyName = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME));
11283 // Initialize the AssemblyName object from the AssemblySpec
11284 spec.AssemblyNameInit(&_gcRefs.oRefAssemblyName, NULL);
11286 if (!fInvokedForTPABinder)
11288 // Step 2 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName) - Invoke Load method
11289 // This is not invoked for TPA Binder since it always returns NULL.
11291 // Finally, setup arguments for invocation
11292 BinderMethodID idHAR_Resolve = METHOD__ASSEMBLYLOADCONTEXT__RESOLVE;
11293 MethodDescCallSite methLoadAssembly(idHAR_Resolve);
11295 // Setup the arguments for the call
11298 PtrToArgSlot(pManagedAssemblyLoadContextToBindWithin), // IntPtr for managed assembly load context instance
11299 ObjToArgSlot(_gcRefs.oRefAssemblyName), // AssemblyName instance
11303 _gcRefs.oRefLoadedAssembly = (ASSEMBLYREF) methLoadAssembly.Call_RetOBJECTREF(args);
11304 if (_gcRefs.oRefLoadedAssembly != NULL)
11306 fResolvedAssembly = true;
11309 // Step 3 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName)
11310 if (!fResolvedAssembly)
11312 // If we could not resolve the assembly using Load method, then attempt fallback with TPA Binder.
11313 // Since TPA binder cannot fallback to itself, this fallback does not happen for binds within TPA binder.
11315 // Switch to pre-emp mode before calling into the binder
11317 ICLRPrivAssembly *pCoreCLRFoundAssembly = NULL;
11318 hr = pTPABinder->BindAssemblyByName(pIAssemblyName, &pCoreCLRFoundAssembly);
11321 pAssemblyBindingContext = pCoreCLRFoundAssembly;
11322 fResolvedAssembly = true;
11323 fResolvedAssemblyViaTPALoadContext = true;
11328 if (!fResolvedAssembly)
11330 // Step 4 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName)
11332 // If we couldnt resolve the assembly using TPA LoadContext as well, then
11333 // attempt to resolve it using the Resolving event.
11334 // Finally, setup arguments for invocation
11335 BinderMethodID idHAR_ResolveUsingEvent = METHOD__ASSEMBLYLOADCONTEXT__RESOLVEUSINGEVENT;
11336 MethodDescCallSite methLoadAssembly(idHAR_ResolveUsingEvent);
11338 // Setup the arguments for the call
11341 PtrToArgSlot(pManagedAssemblyLoadContextToBindWithin), // IntPtr for managed assembly load context instance
11342 ObjToArgSlot(_gcRefs.oRefAssemblyName), // AssemblyName instance
11346 _gcRefs.oRefLoadedAssembly = (ASSEMBLYREF) methLoadAssembly.Call_RetOBJECTREF(args);
11347 if (_gcRefs.oRefLoadedAssembly != NULL)
11349 // Set the flag indicating we found the assembly
11350 fResolvedAssembly = true;
11354 if (fResolvedAssembly && !fResolvedAssemblyViaTPALoadContext)
11356 // If we are here, assembly was successfully resolved via Load or Resolving events.
11357 _ASSERTE(_gcRefs.oRefLoadedAssembly != NULL);
11359 // We were able to get the assembly loaded. Now, get its name since the host could have
11360 // performed the resolution using an assembly with different name.
11361 DomainAssembly *pDomainAssembly = _gcRefs.oRefLoadedAssembly->GetDomainAssembly();
11362 PEAssembly *pLoadedPEAssembly = NULL;
11363 bool fFailLoad = false;
11364 if (!pDomainAssembly)
11366 // Reflection emitted assemblies will not have a domain assembly.
11371 pLoadedPEAssembly = pDomainAssembly->GetFile();
11372 if (pLoadedPEAssembly->HasHostAssembly() != true)
11374 // Reflection emitted assemblies will not have a domain assembly.
11379 // The loaded assembly's ICLRPrivAssembly* is saved as HostAssembly in PEAssembly
11383 spec.GetFileOrDisplayName(0, name);
11384 COMPlusThrowHR(COR_E_INVALIDOPERATION, IDS_HOST_ASSEMBLY_RESOLVER_DYNAMICALLY_EMITTED_ASSEMBLIES_UNSUPPORTED, name);
11387 // Is the assembly already bound using a binding context that will be incompatible?
11388 // An example is attempting to consume an assembly bound to WinRT binder.
11389 pAssemblyBindingContext = pLoadedPEAssembly->GetHostAssembly();
11392 #ifdef FEATURE_COMINTEROP
11393 if (AreSameBinderInstance(pAssemblyBindingContext, GetAppDomain()->GetWinRtBinder()))
11395 // It is invalid to return an assembly bound to an incompatible binder
11396 *ppLoadedAssembly = NULL;
11398 spec.GetFileOrDisplayName(0, name);
11399 COMPlusThrowHR(COR_E_INVALIDOPERATION, IDS_HOST_ASSEMBLY_RESOLVER_INCOMPATIBLE_BINDING_CONTEXT, name);
11401 #endif // FEATURE_COMINTEROP
11403 // Get the ICLRPrivAssembly reference to return back to.
11404 *ppLoadedAssembly = clr::SafeAddRef(pAssemblyBindingContext);
11410 // EX_CATCH_HRESULT(hr);
11415 #endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
11417 //approximate size of loader data
11418 //maintained for each assembly
11419 #define APPROX_LOADER_DATA_PER_ASSEMBLY 8196
11421 size_t AppDomain::EstimateSize()
11431 size_t retval = sizeof(AppDomain);
11432 retval += GetLoaderAllocator()->EstimateSize();
11433 //very rough estimate
11434 retval += GetAssemblyCount() * APPROX_LOADER_DATA_PER_ASSEMBLY;
11438 #ifdef DACCESS_COMPILE
11441 DomainLocalModule::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
11445 // Enumerate the DomainLocalModule itself. DLMs are allocated to be larger than
11446 // sizeof(DomainLocalModule) to make room for ClassInit flags and non-GC statics.
11447 // "DAC_ENUM_DTHIS()" probably does not account for this, so we might not enumerate
11448 // all of the ClassInit flags and non-GC statics.
11449 // sizeof(DomainLocalModule) == 0x28
11452 if (m_pDomainFile.IsValid())
11454 m_pDomainFile->EnumMemoryRegions(flags);
11457 if (m_pDynamicClassTable.Load().IsValid())
11459 DacEnumMemoryRegion(dac_cast<TADDR>(m_pDynamicClassTable.Load()),
11460 m_aDynamicEntries * sizeof(DynamicClassInfo));
11462 for (SIZE_T i = 0; i < m_aDynamicEntries; i++)
11464 PTR_DynamicEntry entry = dac_cast<PTR_DynamicEntry>(m_pDynamicClassTable[i].m_pDynamicEntry.Load());
11465 if (entry.IsValid())
11467 // sizeof(DomainLocalModule::DynamicEntry) == 8
11475 DomainLocalBlock::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
11478 // Block is contained in AppDomain, don't enum this.
11480 if (m_pModuleSlots.IsValid())
11482 DacEnumMemoryRegion(dac_cast<TADDR>(m_pModuleSlots),
11483 m_aModuleIndices * sizeof(TADDR));
11485 for (SIZE_T i = 0; i < m_aModuleIndices; i++)
11487 PTR_DomainLocalModule domMod = m_pModuleSlots[i];
11488 if (domMod.IsValid())
11490 domMod->EnumMemoryRegions(flags);
11497 BaseDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11503 // This is wrong. Don't do it.
11504 // BaseDomain cannot be instantiated.
11505 // The only thing this code can hope to accomplish is to potentially break
11506 // memory enumeration walking through the derived class if we
11507 // explicitly call the base class enum first.
11508 // DAC_ENUM_VTHIS();
11511 EMEM_OUT(("MEM: %p BaseDomain\n", dac_cast<TADDR>(this)));
11515 AppDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11522 //sizeof(AppDomain) == 0xeb0
11525 BaseDomain::EnumMemoryRegions(flags, false);
11527 // We don't need AppDomain name in triage dumps.
11528 if (flags != CLRDATA_ENUM_MEM_TRIAGE)
11530 m_friendlyName.EnumMemoryRegions(flags);
11533 m_Assemblies.EnumMemoryRegions(flags);
11534 AssemblyIterator assem = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution | kIncludeIntrospection));
11535 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
11537 while (assem.Next(pDomainAssembly.This()))
11539 pDomainAssembly->EnumMemoryRegions(flags);
11542 m_sDomainLocalBlock.EnumMemoryRegions(flags);
11544 m_LoaderAllocator.EnumMemoryRegions(flags);
11548 SystemDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11556 BaseDomain::EnumMemoryRegions(flags, false);
11558 if (m_pSystemFile.IsValid())
11560 m_pSystemFile->EnumMemoryRegions(flags);
11562 if (m_pSystemAssembly.IsValid())
11564 m_pSystemAssembly->EnumMemoryRegions(flags);
11566 if (m_pDefaultDomain.IsValid())
11568 m_pDefaultDomain->EnumMemoryRegions(flags, true);
11571 m_appDomainIndexList.EnumMem();
11572 (&m_appDomainIndexList)->EnumMemoryRegions(flags);
11576 SharedDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11584 BaseDomain::EnumMemoryRegions(flags, false);
11585 #ifdef FEATURE_LOADER_OPTIMIZATION
11586 m_assemblyMap.EnumMemoryRegions(flags);
11587 SharedAssemblyIterator assem;
11588 while (assem.Next())
11590 assem.GetAssembly()->EnumMemoryRegions(flags);
11595 #endif //DACCESS_COMPILE
11598 PTR_LoaderAllocator SystemDomain::GetGlobalLoaderAllocator()
11600 return PTR_LoaderAllocator(PTR_HOST_MEMBER_TADDR(SystemDomain,System(),m_GlobalAllocator));
11603 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
11605 #ifndef CROSSGEN_COMPILE
11606 // Return the total processor time (user and kernel) used by threads executing in this AppDomain so far. The
11607 // result is in 100ns units.
11608 ULONGLONG AppDomain::QueryProcessorUsage()
11618 #ifndef DACCESS_COMPILE
11619 Thread *pThread = NULL;
11621 // Need to update our accumulated processor time count with current values from each thread that is
11622 // currently executing in this domain.
11624 // Take the thread store lock while we enumerate threads.
11625 ThreadStoreLockHolder tsl;
11626 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
11628 // Skip unstarted and dead threads and those that are currently executing in a different AppDomain.
11629 if (pThread->IsUnstarted() || pThread->IsDead() || pThread->GetDomain(INDEBUG(TRUE)) != this)
11632 // Add the amount of time spent by the thread in the AppDomain since the last time we asked (calling
11633 // Thread::QueryThreadProcessorUsage() will reset the thread's counter).
11634 UpdateProcessorUsage(pThread->QueryThreadProcessorUsage());
11636 #endif // !DACCESS_COMPILE
11638 // Return the updated total.
11639 return m_ullTotalProcessorUsage;
11642 // Add to the current count of processor time used by threads within this AppDomain. This API is called by
11643 // threads transitioning between AppDomains.
11644 void AppDomain::UpdateProcessorUsage(ULONGLONG ullAdditionalUsage)
11646 LIMITED_METHOD_CONTRACT;
11648 // Need to be careful to synchronize here, multiple threads could be racing to update this count.
11649 ULONGLONG ullOldValue;
11650 ULONGLONG ullNewValue;
11653 ullOldValue = m_ullTotalProcessorUsage;
11654 ullNewValue = ullOldValue + ullAdditionalUsage;
11655 } while (InterlockedCompareExchange64((LONGLONG*)&m_ullTotalProcessorUsage,
11656 (LONGLONG)ullNewValue,
11657 (LONGLONG)ullOldValue) != (LONGLONG)ullOldValue);
11659 #endif // CROSSGEN_COMPILE
11661 #endif // FEATURE_APPDOMAIN_RESOURCE_MONITORING
11663 #if defined(FEATURE_TYPEEQUIVALENCE)
11665 #ifndef DACCESS_COMPILE
11666 TypeEquivalenceHashTable * AppDomain::GetTypeEquivalenceCache()
11672 INJECT_FAULT(COMPlusThrowOM());
11677 // Take the critical section all of the time in debug builds to ensure that it is safe to take
11678 // the critical section in the unusual times when it may actually be needed in retail builds
11680 CrstHolder ch(&m_TypeEquivalenceCrst);
11683 if (m_pTypeEquivalenceTable.Load() == NULL)
11686 CrstHolder ch(&m_TypeEquivalenceCrst);
11688 if (m_pTypeEquivalenceTable.Load() == NULL)
11690 m_pTypeEquivalenceTable = TypeEquivalenceHashTable::Create(this, 12, &m_TypeEquivalenceCrst);
11693 return m_pTypeEquivalenceTable;
11695 #endif //!DACCESS_COMPILE
11697 #endif //FEATURE_TYPEEQUIVALENCE
11699 #if !defined(DACCESS_COMPILE)
11701 //---------------------------------------------------------------------------------------------------------------------
11702 void AppDomain::PublishHostedAssembly(
11703 DomainAssembly * pDomainAssembly)
11713 if (pDomainAssembly->GetFile()->HasHostAssembly())
11715 // We have to serialize all Add operations
11716 CrstHolder lockAdd(&m_crstHostAssemblyMapAdd);
11717 _ASSERTE(m_hostAssemblyMap.Lookup(pDomainAssembly->GetFile()->GetHostAssembly()) == nullptr);
11719 // Wrapper for m_hostAssemblyMap.Add that avoids call out into host
11720 HostAssemblyMap::AddPhases addCall;
11722 // 1. Preallocate one element
11723 addCall.PreallocateForAdd(&m_hostAssemblyMap);
11725 // 2. Take the reader lock which can be taken during stack walking
11726 // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations)
11727 ForbidSuspendThreadHolder suspend;
11729 CrstHolder lock(&m_crstHostAssemblyMap);
11730 // 3. Add the element to the hash table (no call out into host)
11731 addCall.Add(pDomainAssembly);
11734 // 4. Cleanup the old memory (if any)
11735 addCall.DeleteOldTable();
11742 //---------------------------------------------------------------------------------------------------------------------
11743 void AppDomain::UpdatePublishHostedAssembly(
11744 DomainAssembly * pAssembly,
11756 if (pAssembly->GetFile()->HasHostAssembly())
11758 // We have to serialize all Add operations
11759 CrstHolder lockAdd(&m_crstHostAssemblyMapAdd);
11761 // Wrapper for m_hostAssemblyMap.Add that avoids call out into host
11762 OriginalFileHostAssemblyMap::AddPhases addCall;
11763 bool fAddOrigFile = false;
11765 // For cases where the pefile is being updated
11766 // 1. Preallocate one element
11767 if (pFile != pAssembly->GetFile())
11769 addCall.PreallocateForAdd(&m_hostAssemblyMapForOrigFile);
11770 fAddOrigFile = true;
11774 // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations)
11775 ForbidSuspendThreadHolder suspend;
11777 CrstHolder lock(&m_crstHostAssemblyMap);
11779 // Remove from hash table.
11780 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) != nullptr);
11781 m_hostAssemblyMap.Remove(pAssembly->GetFile()->GetHostAssembly());
11783 // Update PEFile on DomainAssembly. (This may cause the key for the hash to change, which is why we need this function)
11784 pAssembly->UpdatePEFileWorker(pFile);
11786 _ASSERTE(fAddOrigFile == (pAssembly->GetOriginalFile() != pAssembly->GetFile()));
11789 // 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)
11790 addCall.Add(pAssembly);
11793 // Add back to the hashtable (the call to Remove above guarantees that we will not call into host for table reallocation)
11794 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) == nullptr);
11795 m_hostAssemblyMap.Add(pAssembly);
11799 // 4. Cleanup the old memory (if any)
11801 addCall.DeleteOldTable();
11807 pAssembly->UpdatePEFileWorker(pFile);
11811 //---------------------------------------------------------------------------------------------------------------------
11812 void AppDomain::UnPublishHostedAssembly(
11813 DomainAssembly * pAssembly)
11824 if (pAssembly->GetFile()->HasHostAssembly())
11826 ForbidSuspendThreadHolder suspend;
11828 CrstHolder lock(&m_crstHostAssemblyMap);
11829 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) != nullptr);
11830 m_hostAssemblyMap.Remove(pAssembly->GetFile()->GetHostAssembly());
11832 // We also have an entry in m_hostAssemblyMapForOrigFile. Handle that case.
11833 if (pAssembly->GetOriginalFile() != pAssembly->GetFile())
11835 m_hostAssemblyMapForOrigFile.Remove(pAssembly->GetOriginalFile()->GetHostAssembly());
11841 // In AppX processes, all PEAssemblies that are reach this stage should have host binders.
11842 _ASSERTE(!AppX::IsAppXProcess());
11846 #if defined(FEATURE_COMINTEROP)
11847 HRESULT AppDomain::SetWinrtApplicationContext(SString &appLocalWinMD)
11849 STANDARD_VM_CONTRACT;
11851 _ASSERTE(WinRTSupported());
11852 _ASSERTE(m_pWinRtBinder != nullptr);
11854 _ASSERTE(GetTPABinderContext() != NULL);
11855 BINDER_SPACE::ApplicationContext *pApplicationContext = GetTPABinderContext()->GetAppContext();
11856 _ASSERTE(pApplicationContext != NULL);
11858 return m_pWinRtBinder->SetApplicationContext(pApplicationContext, appLocalWinMD);
11861 #endif // FEATURE_COMINTEROP
11863 #endif //!DACCESS_COMPILE
11865 //---------------------------------------------------------------------------------------------------------------------
11866 PTR_DomainAssembly AppDomain::FindAssembly(PTR_ICLRPrivAssembly pHostAssembly)
11877 if (pHostAssembly == nullptr)
11881 ForbidSuspendThreadHolder suspend;
11883 CrstHolder lock(&m_crstHostAssemblyMap);
11884 PTR_DomainAssembly returnValue = m_hostAssemblyMap.Lookup(pHostAssembly);
11885 if (returnValue == NULL)
11887 // If not found in the m_hostAssemblyMap, look in the m_hostAssemblyMapForOrigFile
11888 // This is necessary as it may happen during in a second AppDomain that the PEFile
11889 // first discovered in the AppDomain may not be used by the DomainFile, but the CLRPrivBinderFusion
11890 // will in some cases find the pHostAssembly associated with this no longer used PEFile
11891 // instead of the PEFile that was finally decided upon.
11892 returnValue = m_hostAssemblyMapForOrigFile.Lookup(pHostAssembly);
11895 return returnValue;
11900 #if !defined(DACCESS_COMPILE) && defined(FEATURE_NATIVE_IMAGE_GENERATION)
11902 void ZapperSetBindingPaths(ICorCompilationDomain *pDomain, SString &trustedPlatformAssemblies, SString &platformResourceRoots, SString &appPaths, SString &appNiPaths)
11904 CLRPrivBinderCoreCLR *pBinder = static_cast<CLRPrivBinderCoreCLR*>(((CompilationDomain *)pDomain)->GetFusionContext());
11905 _ASSERTE(pBinder != NULL);
11906 pBinder->SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths);
11907 #ifdef FEATURE_COMINTEROP
11908 SString emptString;
11909 ((CompilationDomain*)pDomain)->SetWinrtApplicationContext(emptString);