1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
8 #include "appdomain.hpp"
9 #include "peimagelayout.inl"
11 #include "strongnameinternal.h"
14 #include "gcheaputilities.h"
15 #include "eventtrace.h"
16 #include "perfcounters.h"
17 #include "assemblyname.hpp"
18 #include "eeprofinterfaces.h"
19 #include "dbginterface.h"
20 #ifndef DACCESS_COMPILE
21 #include "eedbginterfaceimpl.h"
23 #include "comdynamic.h"
25 #include "posterror.h"
26 #include "assemblynative.hpp"
28 #include "stringliteralmap.h"
30 #include "comcallablewrapper.h"
31 #include "apithreadstress.h"
32 #include "eventtrace.h"
33 #include "comdelegate.h"
34 #include "siginfo.hpp"
39 #include "finalizerthread.h"
40 #include "threadsuspend.h"
43 #include "corcompile.h"
45 #endif // FEATURE_PREJIT
47 #ifdef FEATURE_COMINTEROP
48 #include "comtoclrcall.h"
49 #include "runtimecallablewrapper.h"
50 #include "mngstdinterfaces.h"
51 #include "olevariant.h"
52 #include "rcwrefcache.h"
53 #include "olecontexthelpers.h"
54 #endif // FEATURE_COMINTEROP
55 #ifdef FEATURE_TYPEEQUIVALENCE
56 #include "typeequivalencehash.hpp"
59 #include "appdomain.inl"
60 #include "typeparse.h"
61 #include "mdaassistants.h"
62 #include "threadpoolrequest.h"
64 #include "nativeoverlapped.h"
68 #endif // !FEATURE_PAL
70 #include "stringarraylist.h"
72 #include "../binder/inc/clrprivbindercoreclr.h"
75 #include "clrprivtypecachewinrt.h"
79 #pragma warning(disable:4324)
83 // this file handles string conversion errors for itself
84 #undef MAKE_TRANSLATIONFAILED
86 // Define these macro's to do strict validation for jit lock and class
87 // init entry leaks. This defines determine if the asserts that
88 // verify for these leaks are defined or not. These asserts can
89 // sometimes go off even if no entries have been leaked so this
90 // defines should be used with caution.
92 // If we are inside a .cctor when the application shut's down then the
93 // class init lock's head will be set and this will cause the assert
96 // If we are jitting a method when the application shut's down then
97 // the jit lock's head will be set causing the assert to go off.
99 //#define STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
101 static const WCHAR DEFAULT_DOMAIN_FRIENDLY_NAME[] = W("DefaultDomain");
102 static const WCHAR OTHER_DOMAIN_FRIENDLY_NAME_PREFIX[] = W("Domain");
104 #define STATIC_OBJECT_TABLE_BUCKET_SIZE 1020
106 #define MAX_URL_LENGTH 2084 // same as INTERNET_MAX_URL_LENGTH
108 //#define _DEBUG_ADUNLOAD 1
110 HRESULT RunDllMain(MethodDesc *pMD, HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved); // clsload.cpp
118 SPTR_IMPL(SystemDomain, SystemDomain, m_pSystemDomain);
119 SVAL_IMPL(ArrayListStatic, SystemDomain, m_appDomainIndexList);
120 SPTR_IMPL(SharedDomain, SharedDomain, m_pSharedDomain);
121 SVAL_IMPL(BOOL, SystemDomain, s_fForceDebug);
122 SVAL_IMPL(BOOL, SystemDomain, s_fForceProfiling);
123 SVAL_IMPL(BOOL, SystemDomain, s_fForceInstrument);
125 #ifndef DACCESS_COMPILE
127 // Base Domain Statics
128 CrstStatic BaseDomain::m_SpecialStaticsCrst;
130 int BaseDomain::m_iNumberOfProcessors = 0;
132 // Shared Domain Statics
134 static BYTE g_pSharedDomainMemory[sizeof(SharedDomain)];
136 // System Domain Statics
137 GlobalStringLiteralMap* SystemDomain::m_pGlobalStringLiteralMap = NULL;
140 static BYTE g_pSystemDomainMemory[sizeof(SystemDomain)];
142 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
143 size_t SystemDomain::m_totalSurvivedBytes = 0;
144 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
146 CrstStatic SystemDomain::m_SystemDomainCrst;
147 CrstStatic SystemDomain::m_DelayedUnloadCrst;
149 ULONG SystemDomain::s_dNumAppDomains = 0;
151 AppDomain * SystemDomain::m_pAppDomainBeingUnloaded = NULL;
152 ADIndex SystemDomain::m_dwIndexOfAppDomainBeingUnloaded;
153 Thread *SystemDomain::m_pAppDomainUnloadRequestingThread = 0;
154 Thread *SystemDomain::m_pAppDomainUnloadingThread = 0;
156 ArrayListStatic SystemDomain::m_appDomainIdList;
158 DWORD SystemDomain::m_dwLowestFreeIndex = 0;
162 // comparison function to be used for matching clsids in our clsid hash table
163 BOOL CompareCLSID(UPTR u1, UPTR u2)
171 INJECT_FAULT(COMPlusThrowOM(););
175 GUID *pguid = (GUID *)(u1 << 1);
176 _ASSERTE(pguid != NULL);
178 MethodTable *pMT= (MethodTable *)u2;
179 _ASSERTE(pMT!= NULL);
182 pMT->GetGuid(&guid, TRUE);
183 if (!IsEqualIID(guid, *pguid))
189 #ifndef CROSSGEN_COMPILE
190 // Constructor for the LargeHeapHandleBucket class.
191 LargeHeapHandleBucket::LargeHeapHandleBucket(LargeHeapHandleBucket *pNext, DWORD Size, BaseDomain *pDomain, BOOL bCrossAD)
195 , m_CurrentEmbeddedFreePos(0) // hint for where to start a search for an embedded free item
202 PRECONDITION(CheckPointer(pDomain));
203 INJECT_FAULT(COMPlusThrowOM(););
207 PTRARRAYREF HandleArrayObj;
209 // Allocate the array in the large object heap.
212 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
213 HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, TRUE);
217 // During AD creation we don't want to assign the handle array to the currently running AD but
218 // to the AD being created. Ensure that AllocateArrayEx doesn't set the AD and then set it here.
219 AppDomain *pAD = pDomain->AsAppDomain();
221 _ASSERTE(pAD->IsBeingCreated());
225 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
226 array = AllocateArrayEx(
227 ClassLoader::LoadArrayTypeThrowing(g_pObjectClass),
234 array->SetAppDomain(pAD);
236 HandleArrayObj = (PTRARRAYREF)array;
239 // Retrieve the pointer to the data inside the array. This is legal since the array
240 // is located in the large object heap and is guaranteed not to move.
241 m_pArrayDataPtr = (OBJECTREF *)HandleArrayObj->GetDataPtr();
243 // Store the array in a strong handle to keep it alive.
244 m_hndHandleArray = pDomain->CreatePinningHandle((OBJECTREF)HandleArrayObj);
248 // Destructor for the LargeHeapHandleBucket class.
249 LargeHeapHandleBucket::~LargeHeapHandleBucket()
258 if (m_hndHandleArray)
260 DestroyPinningHandle(m_hndHandleArray);
261 m_hndHandleArray = NULL;
266 // Allocate handles from the bucket.
267 OBJECTREF *LargeHeapHandleBucket::AllocateHandles(DWORD nRequested)
277 _ASSERTE(nRequested > 0 && nRequested <= GetNumRemainingHandles());
278 _ASSERTE(m_pArrayDataPtr == (OBJECTREF*)((PTRARRAYREF)ObjectFromHandle(m_hndHandleArray))->GetDataPtr());
280 // Store the handles in the buffer that was passed in
281 OBJECTREF* ret = &m_pArrayDataPtr[m_CurrentPos];
282 m_CurrentPos += nRequested;
287 // look for a free item embedded in the table
288 OBJECTREF *LargeHeapHandleBucket::TryAllocateEmbeddedFreeHandle()
298 OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
299 _ASSERTE(pPreallocatedSentinalObject != NULL);
301 for (int i = m_CurrentEmbeddedFreePos; i < m_CurrentPos; i++)
303 if (m_pArrayDataPtr[i] == pPreallocatedSentinalObject)
305 m_CurrentEmbeddedFreePos = i;
306 m_pArrayDataPtr[i] = NULL;
307 return &m_pArrayDataPtr[i];
311 // didn't find it (we don't bother wrapping around for a full search, it's not worth it to try that hard, we'll get it next time)
313 m_CurrentEmbeddedFreePos = 0;
318 // Maximum bucket size will be 64K on 32-bit and 128K on 64-bit.
319 // We subtract out a small amount to leave room for the object
320 // header and length of the array.
322 #define MAX_BUCKETSIZE (16384 - 4)
324 // Constructor for the LargeHeapHandleTable class.
325 LargeHeapHandleTable::LargeHeapHandleTable(BaseDomain *pDomain, DWORD InitialBucketSize)
328 , m_NextBucketSize(InitialBucketSize)
329 , m_pFreeSearchHint(NULL)
337 PRECONDITION(CheckPointer(pDomain));
338 INJECT_FAULT(COMPlusThrowOM(););
348 // Destructor for the LargeHeapHandleTable class.
349 LargeHeapHandleTable::~LargeHeapHandleTable()
358 // Delete the buckets.
361 LargeHeapHandleBucket *pOld = m_pHead;
362 m_pHead = pOld->GetNext();
367 //*****************************************************************************
369 // LOCKING RULES FOR AllocateHandles() and ReleaseHandles() 12/08/2004
372 // These functions are not protected by any locking in this location but rather the callers are
373 // assumed to be doing suitable locking for the handle table. The handle table itself is
374 // behaving rather like a thread-agnostic collection class -- it doesn't want to know
375 // much about the outside world and so it is just doing its job with no awareness of
378 // The instance in question is
379 // There are two locations you can find a LargeHeapHandleTable
380 // 1) there is one in every BaseDomain, it is used to keep track of the static members
382 // 2) there is one in the System Domain that is used for the GlobalStringLiteralMap
384 // the one in (2) is not the same as the one that is in the BaseDomain object that corresponds
385 // to the SystemDomain -- that one is basically stilborn because the string literals don't go
386 // there and of course the System Domain has no code loaded into it -- only regular
387 // AppDomains (like Domain 0) actually execute code. As a result handle tables are in
388 // practice used either for string literals or for static members but never for both.
389 // At least not at this writing.
391 // Now it's useful to consider what the locking discipline is for these classes.
395 // First case: (easiest) is the statics members
397 // Each BaseDomain has its own critical section
399 // BaseDomain::AllocateObjRefPtrsInLargeTable takes a lock with
400 // CrstHolder ch(&m_LargeHeapHandleTableCrst);
402 // it does this before it calls AllocateHandles which suffices. It does not call ReleaseHandles
403 // at any time (although ReleaseHandles may be called via AllocateHandles if the request
404 // doesn't fit in the current block, the remaining handles at the end of the block are released
405 // automatically as part of allocation/recycling)
407 // note: Recycled handles are only used during String Literal allocation because we only try
408 // to recycle handles if the allocation request is for exactly one handle.
410 // The handles in the BaseDomain handle table are released when the Domain is unloaded
411 // as the GC objects become rootless at that time.
413 // This dispenses with all of the Handle tables except the one that is used for string literals
417 // Second case: Allocation for use in a string literal
419 // AppDomainStringLiteralMap::GetStringLiteral
421 // LargeHeapHandleBlockHolder constructor
423 // m_Data = pOwner->AllocateHandles(nCount);
425 // before doing this AppDomainStringLiteralMap::GetStringLiteral takes this lock
427 // CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
429 // which is the lock for the hash table that it owns
431 // STRINGREF *AppDomainStringLiteralMap::GetInternedString
433 // has a similar call path and uses the same approach and the same lock
434 // this covers all the paths which allocate
438 // Third case: Releases for use in a string literal entry
440 // CrstHolder gch(&(SystemDomain::GetGlobalStringLiteralMap()->m_HashTableCrstGlobal));
441 // taken in the AppDomainStringLiteralMap functions below protects the 4 ways that this can happen
445 // in an appdomain unload case
447 // AppDomainStringLiteralMap::~AppDomainStringLiteralMap() takes the lock then
449 // StringLiteralEntry::Release
451 // SystemDomain::GetGlobalStringLiteralMapNoCreate()->RemoveStringLiteralEntry(this)
453 // m_LargeHeapHandleTable.ReleaseHandles((OBJECTREF*)pObjRef, 1);
457 // AppDomainStringLiteralMap::GetStringLiteral() can call StringLiteralEntry::Release in some
458 // error cases, leading to the same stack as above
462 // AppDomainStringLiteralMap::GetInternedString() can call StringLiteralEntry::Release in some
463 // error cases, leading to the same stack as above
467 // The same code paths in 3b and 3c and also end up releasing if an exception is thrown
468 // during their processing. Both these paths use a StringLiteralEntryHolder to assist in cleanup,
469 // the StaticRelease method of the StringLiteralEntry gets called, which in turn calls the
473 // Allocate handles from the large heap handle table.
474 OBJECTREF* LargeHeapHandleTable::AllocateHandles(DWORD nRequested, BOOL bCrossAD)
481 PRECONDITION(nRequested > 0);
482 INJECT_FAULT(COMPlusThrowOM(););
486 // SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
488 // the lock must be registered and already held by the caller per contract
490 _ASSERTE(m_pCrstDebug != NULL);
491 _ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
494 if (nRequested == 1 && m_cEmbeddedFree != 0)
496 // special casing singleton requests to look for slots that can be re-used
498 // we need to do this because string literals are allocated one at a time and then sometimes
499 // released. we do not wish for the number of handles consumed by string literals to
500 // increase forever as assemblies are loaded and unloaded
502 if (m_pFreeSearchHint == NULL)
503 m_pFreeSearchHint = m_pHead;
505 while (m_pFreeSearchHint)
507 OBJECTREF* pObjRef = m_pFreeSearchHint->TryAllocateEmbeddedFreeHandle();
510 // the slot is to have been prepared with a null ready to go
511 _ASSERTE(*pObjRef == NULL);
515 m_pFreeSearchHint = m_pFreeSearchHint->GetNext();
518 // the search doesn't wrap around so it's possible that we might have embedded free items
519 // and not find them but that's ok, we'll get them on the next alloc... all we're trying to do
520 // is to not have big leaks over time.
524 // Retrieve the remaining number of handles in the bucket.
525 DWORD NumRemainingHandlesInBucket = (m_pHead != NULL) ? m_pHead->GetNumRemainingHandles() : 0;
527 // create a new block if this request doesn't fit in the current block
528 if (nRequested > NumRemainingHandlesInBucket)
532 // mark the handles in that remaining region as available for re-use
533 ReleaseHandles(m_pHead->CurrentPos(), NumRemainingHandlesInBucket);
535 // mark what's left as having been used
536 m_pHead->ConsumeRemaining();
539 // create a new bucket for this allocation
541 // We need a block big enough to hold the requested handles
542 DWORD NewBucketSize = max(m_NextBucketSize, nRequested);
544 m_pHead = new LargeHeapHandleBucket(m_pHead, NewBucketSize, m_pDomain, bCrossAD);
546 m_NextBucketSize = min(m_NextBucketSize * 2, MAX_BUCKETSIZE);
549 return m_pHead->AllocateHandles(nRequested);
552 //*****************************************************************************
553 // Release object handles allocated using AllocateHandles().
554 void LargeHeapHandleTable::ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased)
561 PRECONDITION(CheckPointer(pObjRef));
565 // SEE "LOCKING RULES FOR AllocateHandles() and ReleaseHandles()" above
567 // the lock must be registered and already held by the caller per contract
569 _ASSERTE(m_pCrstDebug != NULL);
570 _ASSERTE(m_pCrstDebug->OwnedByCurrentThread());
573 OBJECTREF pPreallocatedSentinalObject = ObjectFromHandle(g_pPreallocatedSentinelObject);
574 _ASSERTE(pPreallocatedSentinalObject != NULL);
577 // Add the released handles to the list of available handles.
578 for (DWORD i = 0; i < nReleased; i++)
580 SetObjectReference(&pObjRef[i], pPreallocatedSentinalObject, NULL);
583 m_cEmbeddedFree += nReleased;
589 // Constructor for the ThreadStaticHandleBucket class.
590 ThreadStaticHandleBucket::ThreadStaticHandleBucket(ThreadStaticHandleBucket *pNext, DWORD Size, BaseDomain *pDomain)
599 PRECONDITION(CheckPointer(pDomain));
600 INJECT_FAULT(COMPlusThrowOM(););
604 PTRARRAYREF HandleArrayObj;
606 // Allocate the array on the GC heap.
607 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
608 HandleArrayObj = (PTRARRAYREF)AllocateObjectArray(Size, g_pObjectClass, FALSE);
610 // Store the array in a strong handle to keep it alive.
611 m_hndHandleArray = pDomain->CreateStrongHandle((OBJECTREF)HandleArrayObj);
614 // Destructor for the ThreadStaticHandleBucket class.
615 ThreadStaticHandleBucket::~ThreadStaticHandleBucket()
625 if (m_hndHandleArray)
627 DestroyStrongHandle(m_hndHandleArray);
628 m_hndHandleArray = NULL;
632 // Allocate handles from the bucket.
633 OBJECTHANDLE ThreadStaticHandleBucket::GetHandles()
643 return m_hndHandleArray;
646 // Constructor for the ThreadStaticHandleTable class.
647 ThreadStaticHandleTable::ThreadStaticHandleTable(BaseDomain *pDomain)
656 PRECONDITION(CheckPointer(pDomain));
661 // Destructor for the ThreadStaticHandleTable class.
662 ThreadStaticHandleTable::~ThreadStaticHandleTable()
671 // Delete the buckets.
674 ThreadStaticHandleBucket *pOld = m_pHead;
675 m_pHead = pOld->GetNext();
680 // Allocate handles from the large heap handle table.
681 OBJECTHANDLE ThreadStaticHandleTable::AllocateHandles(DWORD nRequested)
688 PRECONDITION(nRequested > 0);
689 INJECT_FAULT(COMPlusThrowOM(););
693 // create a new bucket for this allocation
694 m_pHead = new ThreadStaticHandleBucket(m_pHead, nRequested, m_pDomain);
696 return m_pHead->GetHandles();
699 #endif // CROSSGEN_COMPILE
702 //*****************************************************************************
704 //*****************************************************************************
705 void BaseDomain::Attach()
707 m_SpecialStaticsCrst.Init(CrstSpecialStatics);
710 BaseDomain::BaseDomain()
712 // initialize fields so the domain can be safely destructed
713 // shouldn't call anything that can fail here - use ::Init instead
723 m_fDisableInterfaceCache = FALSE;
725 m_pFusionContext = NULL;
726 m_pTPABinderContext = NULL;
728 // Make sure the container is set to NULL so that it gets loaded when it is used.
729 m_pLargeHeapHandleTable = NULL;
731 #ifndef CROSSGEN_COMPILE
732 // Note that m_handleStore is overridden by app domains
733 m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
735 m_handleStore = NULL;
738 m_pMarshalingData = NULL;
740 m_dwContextStatics = 0;
741 #ifdef FEATURE_COMINTEROP
742 m_pMngStdInterfacesInfo = NULL;
743 m_pWinRtBinder = NULL;
745 m_FileLoadLock.PreInit();
747 m_ClassInitLock.PreInit();
748 m_ILStubGenLock.PreInit();
750 #ifdef FEATURE_CODE_VERSIONING
751 m_codeVersionManager.PreInit(this == (BaseDomain *)g_pSharedDomainMemory);
754 } //BaseDomain::BaseDomain
756 //*****************************************************************************
757 void BaseDomain::Init()
764 INJECT_FAULT(COMPlusThrowOM(););
769 // Initialize the domain locks
772 if (this == reinterpret_cast<BaseDomain*>(&g_pSharedDomainMemory[0]))
773 m_DomainCrst.Init(CrstSharedBaseDomain);
774 else if (this == reinterpret_cast<BaseDomain*>(&g_pSystemDomainMemory[0]))
775 m_DomainCrst.Init(CrstSystemBaseDomain);
777 m_DomainCrst.Init(CrstBaseDomain);
779 m_DomainCacheCrst.Init(CrstAppDomainCache);
780 m_DomainLocalBlockCrst.Init(CrstDomainLocalBlock);
782 m_InteropDataCrst.Init(CrstInteropData, CRST_REENTRANCY);
784 m_WinRTFactoryCacheCrst.Init(CrstWinRTFactoryCache, CRST_UNSAFE_COOPGC);
786 // NOTE: CRST_UNSAFE_COOPGC prevents a GC mode switch to preemptive when entering this crst.
787 // If you remove this flag, we will switch to preemptive mode when entering
788 // m_FileLoadLock, which means all functions that enter it will become
789 // GC_TRIGGERS. (This includes all uses of PEFileListLockHolder, LoadLockHolder, etc.) So be sure
790 // to update the contracts if you remove this flag.
791 m_FileLoadLock.Init(CrstAssemblyLoader,
792 CrstFlags(CRST_HOST_BREAKABLE), TRUE);
795 // The JIT lock and the CCtor locks are at the same level (and marked as
796 // UNSAFE_SAME_LEVEL) because they are all part of the same deadlock detection mechanism. We
797 // see through cycles of JITting and .cctor execution and then explicitly allow the cycle to
798 // be broken by giving access to uninitialized classes. If there is no cycle or if the cycle
799 // involves other locks that arent part of this special deadlock-breaking semantics, then
800 // we continue to block.
802 m_JITLock.Init(CrstJit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
803 m_ClassInitLock.Init(CrstClassInit, CrstFlags(CRST_REENTRANCY | CRST_UNSAFE_SAMELEVEL), TRUE);
805 m_ILStubGenLock.Init(CrstILStubGen, CrstFlags(CRST_REENTRANCY), TRUE);
807 // Large heap handle table CRST.
808 m_LargeHeapHandleTableCrst.Init(CrstAppDomainHandleTable);
810 m_crstLoaderAllocatorReferences.Init(CrstLoaderAllocatorReferences);
811 // Has to switch thread to GC_NOTRIGGER while being held (see code:BaseDomain#AssemblyListLock)
812 m_crstAssemblyList.Init(CrstAssemblyList, CrstFlags(
813 CRST_GC_NOTRIGGER_WHEN_TAKEN | CRST_DEBUGGER_THREAD | CRST_TAKEN_DURING_SHUTDOWN));
815 // Initialize the EE marshaling data to NULL.
816 m_pMarshalingData = NULL;
818 #ifdef FEATURE_COMINTEROP
819 // Allocate the managed standard interfaces information.
820 m_pMngStdInterfacesInfo = new MngStdInterfacesInfo();
823 CLRPrivBinderWinRT::NamespaceResolutionKind fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_WindowsAPI;
824 if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_DesignerNamespaceResolutionEnabled) != FALSE)
826 fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_DesignerResolveEvent;
828 CLRPrivTypeCacheWinRT * pWinRtTypeCache = CLRPrivTypeCacheWinRT::GetOrCreateTypeCache();
829 m_pWinRtBinder = CLRPrivBinderWinRT::GetOrCreateBinder(pWinRtTypeCache, fNamespaceResolutionKind);
831 #endif // FEATURE_COMINTEROP
833 // Init the COM Interop data hash
835 LockOwner lock = {&m_InteropDataCrst, IsOwnerOfCrst};
836 m_interopDataHash.Init(0, NULL, false, &lock);
839 m_dwSizedRefHandles = 0;
840 if (!m_iNumberOfProcessors)
842 m_iNumberOfProcessors = GetCurrentProcessCpuCount();
846 #undef LOADERHEAP_PROFILE_COUNTER
848 #ifndef CROSSGEN_COMPILE
849 //*****************************************************************************
850 void BaseDomain::Terminate()
860 m_crstLoaderAllocatorReferences.Destroy();
861 m_DomainCrst.Destroy();
862 m_DomainCacheCrst.Destroy();
863 m_DomainLocalBlockCrst.Destroy();
864 m_InteropDataCrst.Destroy();
866 JitListLockEntry* pJitElement;
867 ListLockEntry* pElement;
869 // All the threads that are in this domain had better be stopped by this
872 // We might be jitting or running a .cctor so we need to empty that queue.
873 pJitElement = m_JITLock.Pop(TRUE);
876 #ifdef STRICT_JITLOCK_ENTRY_LEAK_DETECTION
877 _ASSERTE ((m_JITLock.m_pHead->m_dwRefCount == 1
878 && m_JITLock.m_pHead->m_hrResultCode == E_FAIL) ||
879 dbg_fDrasticShutdown || g_fInControlC);
880 #endif // STRICT_JITLOCK_ENTRY_LEAK_DETECTION
882 pJitElement = m_JITLock.Pop(TRUE);
887 pElement = m_ClassInitLock.Pop(TRUE);
890 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
891 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
894 pElement = m_ClassInitLock.Pop(TRUE);
896 m_ClassInitLock.Destroy();
898 FileLoadLock* pFileElement;
899 pFileElement = (FileLoadLock*) m_FileLoadLock.Pop(TRUE);
902 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
903 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
905 pFileElement->Release();
906 pFileElement = (FileLoadLock*) m_FileLoadLock.Pop(TRUE);
908 m_FileLoadLock.Destroy();
910 pElement = m_ILStubGenLock.Pop(TRUE);
913 #ifdef STRICT_JITLOCK_ENTRY_LEAK_DETECTION
914 _ASSERTE ((m_ILStubGenLock.m_pHead->m_dwRefCount == 1
915 && m_ILStubGenLock.m_pHead->m_hrResultCode == E_FAIL) ||
916 dbg_fDrasticShutdown || g_fInControlC);
917 #endif // STRICT_JITLOCK_ENTRY_LEAK_DETECTION
919 pElement = m_ILStubGenLock.Pop(TRUE);
921 m_ILStubGenLock.Destroy();
923 m_LargeHeapHandleTableCrst.Destroy();
925 if (m_pLargeHeapHandleTable != NULL)
927 delete m_pLargeHeapHandleTable;
928 m_pLargeHeapHandleTable = NULL;
933 // Kind of a workaround - during unloading, we need to have an EE halt
934 // around deleting this stuff. So it gets deleted in AppDomain::Terminate()
935 // for those things (because there is a convenient place there.)
936 GetLoaderAllocator()->CleanupStringLiteralMap();
939 #ifdef FEATURE_COMINTEROP
940 if (m_pMngStdInterfacesInfo)
942 delete m_pMngStdInterfacesInfo;
943 m_pMngStdInterfacesInfo = NULL;
946 if (m_pWinRtBinder != NULL)
948 m_pWinRtBinder->Release();
950 #endif // FEATURE_COMINTEROP
952 ClearFusionContext();
954 m_dwSizedRefHandles = 0;
956 #endif // CROSSGEN_COMPILE
958 void BaseDomain::InitVSD()
960 STANDARD_VM_CONTRACT;
962 // This is a workaround for gcc, since it fails to successfully resolve
963 // "TypeIDMap::STARTING_SHARED_DOMAIN_ID" when used within the ?: operator.
965 if (IsSharedDomain())
967 startingId = TypeIDMap::STARTING_SHARED_DOMAIN_ID;
971 startingId = TypeIDMap::STARTING_UNSHARED_DOMAIN_ID;
974 // By passing false as the last parameter, interfaces loaded in the
975 // shared domain will not be given fat type ids if RequiresFatDispatchTokens
976 // is set. This is correct, as the fat dispatch tokens are only needed to solve
977 // uniqueness problems involving domain specific types.
978 m_typeIDMap.Init(startingId, 2, !IsSharedDomain());
980 #ifndef CROSSGEN_COMPILE
981 GetLoaderAllocator()->InitVirtualCallStubManager(this);
985 #ifndef CROSSGEN_COMPILE
987 DWORD BaseDomain::AllocateContextStaticsOffset(DWORD* pOffsetSlot)
996 CrstHolder ch(&m_SpecialStaticsCrst);
998 DWORD dwOffset = *pOffsetSlot;
1000 if (dwOffset == (DWORD)-1)
1002 // Allocate the slot
1003 dwOffset = m_dwContextStatics++;
1004 *pOffsetSlot = dwOffset;
1010 void BaseDomain::ClearFusionContext()
1020 if(m_pFusionContext) {
1021 m_pFusionContext->Release();
1022 m_pFusionContext = NULL;
1024 if (m_pTPABinderContext) {
1025 m_pTPABinderContext->Release();
1026 m_pTPABinderContext = NULL;
1030 #ifdef FEATURE_PREJIT
1031 void AppDomain::DeleteNativeCodeRanges()
1042 // Fast path to skip using the assembly iterator when the appdomain has not yet completely been initialized
1043 // and yet we are destroying it. (This is the case if we OOM during AppDomain creation.)
1044 if (m_Assemblies.IsEmpty())
1047 // Shutdown assemblies
1048 AssemblyIterator i = IterateAssembliesEx( (AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad) );
1049 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1051 while (i.Next(pDomainAssembly.This()))
1053 Assembly * assembly = pDomainAssembly->m_pAssembly;
1054 if ((assembly != NULL) && !assembly->IsDomainNeutral())
1055 assembly->DeleteNativeCodeRanges();
1060 void AppDomain::ShutdownAssemblies()
1070 // Fast path to skip using the assembly iterator when the appdomain has not yet completely been initialized
1071 // and yet we are destroying it. (This is the case if we OOM during AppDomain creation.)
1072 if (m_Assemblies.IsEmpty())
1075 // Shutdown assemblies
1076 // has two stages because Terminate needs info from the Assembly's dependencies
1078 // Stage 1: call code:Assembly::Terminate
1079 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
1080 kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
1081 DomainAssembly * pDomainAssembly = NULL;
1083 while (i.Next_UnsafeNoAddRef(&pDomainAssembly))
1085 // Note: cannot use DomainAssembly::GetAssembly() here as it asserts that the assembly has been
1086 // loaded to at least the FILE_LOAD_ALLOCATE level. Since domain shutdown can take place
1087 // asynchronously this property cannot be guaranteed. Access the m_pAssembly field directly instead.
1088 Assembly * assembly = pDomainAssembly->m_pAssembly;
1089 if (assembly && !assembly->IsDomainNeutral())
1090 assembly->Terminate();
1093 // Stage 2: Clear the list of assemblies
1094 i = IterateAssembliesEx((AssemblyIterationFlags)(
1095 kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
1096 while (i.Next_UnsafeNoAddRef(&pDomainAssembly))
1098 // We are in shutdown path, no one else can get to the list anymore
1099 delete pDomainAssembly;
1101 m_Assemblies.Clear(this);
1103 // Stage 2: Clear the loader allocators registered for deletion from code:Assembly:Terminate calls in
1105 // Note: It is not clear to me why we cannot delete the loader allocator from within
1106 // code:DomainAssembly::~DomainAssembly
1107 ShutdownFreeLoaderAllocators(FALSE);
1108 } // AppDomain::ShutdownAssemblies
1110 void AppDomain::ShutdownFreeLoaderAllocators(BOOL bFromManagedCode)
1112 // If we're called from managed code (i.e. the finalizer thread) we take a lock in
1113 // LoaderAllocator::CleanupFailedTypeInit, which may throw. Otherwise we're called
1114 // from the app-domain shutdown path in which we can avoid taking the lock.
1118 if (bFromManagedCode) THROWS; else NOTHROW;
1124 CrstHolder ch(GetLoaderAllocatorReferencesLock());
1126 // Shutdown the LoaderAllocators associated with collectible assemblies
1127 while (m_pDelayedLoaderAllocatorUnloadList != NULL)
1129 LoaderAllocator * pCurrentLoaderAllocator = m_pDelayedLoaderAllocatorUnloadList;
1130 // Remove next loader allocator from the list
1131 m_pDelayedLoaderAllocatorUnloadList = m_pDelayedLoaderAllocatorUnloadList->m_pLoaderAllocatorDestroyNext;
1133 if (bFromManagedCode)
1135 // For loader allocator finalization, we need to be careful about cleaning up per-appdomain allocations
1136 // and synchronizing with GC using delay unload list. We need to wait for next Gen2 GC to finish to ensure
1137 // that GC heap does not have any references to the MethodTables being unloaded.
1139 pCurrentLoaderAllocator->CleanupFailedTypeInit();
1141 pCurrentLoaderAllocator->CleanupHandles();
1144 SystemDomain::System()->AddToDelayedUnloadList(pCurrentLoaderAllocator);
1148 // For appdomain unload, delete the loader allocator right away
1149 delete pCurrentLoaderAllocator;
1152 } // AppDomain::ShutdownFreeLoaderAllocators
1154 //---------------------------------------------------------------------------------------
1156 // Register the loader allocator for deletion in code:AppDomain::ShutdownFreeLoaderAllocators.
1158 void AppDomain::RegisterLoaderAllocatorForDeletion(LoaderAllocator * pLoaderAllocator)
1169 CrstHolder ch(GetLoaderAllocatorReferencesLock());
1171 pLoaderAllocator->m_pLoaderAllocatorDestroyNext = m_pDelayedLoaderAllocatorUnloadList;
1172 m_pDelayedLoaderAllocatorUnloadList = pLoaderAllocator;
1175 void AppDomain::ShutdownNativeDllSearchDirectories()
1177 LIMITED_METHOD_CONTRACT;
1178 // Shutdown assemblies
1179 PathIterator i = IterateNativeDllSearchDirectories();
1186 m_NativeDllSearchDirectories.Clear();
1189 void AppDomain::ReleaseDomainBoundInfo()
1198 // Shutdown assemblies
1199 m_AssemblyCache.OnAppDomainUnload();
1201 AssemblyIterator i = IterateAssembliesEx( (AssemblyIterationFlags)(kIncludeFailedToLoad) );
1202 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1204 while (i.Next(pDomainAssembly.This()))
1206 pDomainAssembly->ReleaseManagedData();
1210 void AppDomain::ReleaseFiles()
1212 STANDARD_VM_CONTRACT;
1214 // Shutdown assemblies
1215 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
1216 kIncludeLoaded | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeLoading));
1217 CollectibleAssemblyHolder<DomainAssembly *> pAsm;
1219 while (i.Next(pAsm.This()))
1221 if (pAsm->GetCurrentAssembly() == NULL)
1223 // Might be domain neutral or not, but should have no live objects as it has not been
1224 // really loaded yet. Just reset it.
1225 _ASSERTE(FitsIn<DWORD>(i.GetIndex()));
1226 m_Assemblies.Set(this, static_cast<DWORD>(i.GetIndex()), NULL);
1227 delete pAsm.Extract();
1231 if (!pAsm->GetCurrentAssembly()->IsDomainNeutral())
1232 pAsm->ReleaseFiles();
1235 } // AppDomain::ReleaseFiles
1238 OBJECTREF* BaseDomain::AllocateObjRefPtrsInLargeTable(int nRequested, OBJECTREF** ppLazyAllocate, BOOL bCrossAD)
1245 PRECONDITION((nRequested > 0));
1246 INJECT_FAULT(COMPlusThrowOM(););
1250 if (ppLazyAllocate && *ppLazyAllocate)
1252 // Allocation already happened
1253 return *ppLazyAllocate;
1256 // Enter preemptive state, take the lock and go back to cooperative mode.
1258 CrstHolder ch(&m_LargeHeapHandleTableCrst);
1261 if (ppLazyAllocate && *ppLazyAllocate)
1263 // Allocation already happened
1264 return *ppLazyAllocate;
1267 // Make sure the large heap handle table is initialized.
1268 if (!m_pLargeHeapHandleTable)
1269 InitLargeHeapHandleTable();
1271 // Allocate the handles.
1272 OBJECTREF* result = m_pLargeHeapHandleTable->AllocateHandles(nRequested, bCrossAD);
1276 *ppLazyAllocate = result;
1282 #endif // CROSSGEN_COMPILE
1284 #endif // !DACCESS_COMPILE
1287 PTR_BaseDomain BaseDomain::ComputeBaseDomain(
1288 BaseDomain * pGenericDefinitionDomain, // the domain that owns the generic type or method
1289 Instantiation classInst, // the type arguments to the type (if any)
1290 Instantiation methodInst) // the type arguments to the method (if any)
1292 CONTRACT(PTR_BaseDomain)
1298 POSTCONDITION(CheckPointer(RETVAL));
1304 if (pGenericDefinitionDomain && pGenericDefinitionDomain->IsAppDomain())
1305 RETURN PTR_BaseDomain(pGenericDefinitionDomain);
1307 for (DWORD i = 0; i < classInst.GetNumArgs(); i++)
1309 PTR_BaseDomain pArgDomain = classInst[i].GetDomain();
1310 if (pArgDomain->IsAppDomain())
1314 for (DWORD i = 0; i < methodInst.GetNumArgs(); i++)
1316 PTR_BaseDomain pArgDomain = methodInst[i].GetDomain();
1317 if (pArgDomain->IsAppDomain())
1320 RETURN (pGenericDefinitionDomain ?
1321 PTR_BaseDomain(pGenericDefinitionDomain) :
1322 PTR_BaseDomain(SystemDomain::System()));
1325 PTR_BaseDomain BaseDomain::ComputeBaseDomain(TypeKey * pKey)
1337 if (pKey->GetKind() == ELEMENT_TYPE_CLASS)
1338 return BaseDomain::ComputeBaseDomain(pKey->GetModule()->GetDomain(),
1339 pKey->GetInstantiation());
1340 else if (pKey->GetKind() != ELEMENT_TYPE_FNPTR)
1341 return pKey->GetElementType().GetDomain();
1343 return BaseDomain::ComputeBaseDomain(NULL,Instantiation(pKey->GetRetAndArgTypes(), pKey->GetNumArgs()+1));
1350 #ifndef DACCESS_COMPILE
1352 // Insert class in the hash table
1353 void AppDomain::InsertClassForCLSID(MethodTable* pMT, BOOL fForceInsert /*=FALSE*/)
1360 INJECT_FAULT(COMPlusThrowOM(););
1366 // Ensure that registered classes are activated for allocation
1367 pMT->EnsureInstanceActive();
1369 // Note that it is possible for multiple classes to claim the same CLSID, and in such a
1370 // case it is arbitrary which one we will return for a future query for a given app domain.
1372 pMT->GetGuid(&cvid, fForceInsert);
1374 if (!IsEqualIID(cvid, GUID_NULL))
1376 //<TODO>@todo get a better key</TODO>
1377 LPVOID val = (LPVOID)pMT;
1379 LockHolder lh(this);
1381 if (LookupClass(cvid) != pMT)
1383 m_clsidHash.InsertValue(GetKeyFromGUID(&cvid), val);
1389 void AppDomain::InsertClassForCLSID(MethodTable* pMT, GUID *pGuid)
1394 PRECONDITION(CheckPointer(pMT));
1395 PRECONDITION(CheckPointer(pGuid));
1399 LPVOID val = (LPVOID)pMT;
1401 LockHolder lh(this);
1404 if (LookupClass(*cvid) != pMT)
1406 m_clsidHash.InsertValue(GetKeyFromGUID(pGuid), val);
1412 #endif // DACCESS_COMPILE
1414 #ifdef FEATURE_COMINTEROP
1416 #ifndef DACCESS_COMPILE
1417 void AppDomain::CacheTypeByName(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/)
1419 WRAPPER_NO_CONTRACT;
1420 LockHolder lh(this);
1421 CacheTypeByNameWorker(ssClassName, vCacheVersion, typeHandle, bFlags, bReplaceExisting);
1424 void AppDomain::CacheTypeByNameWorker(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/)
1430 PRECONDITION(!typeHandle.IsNull());
1434 NewArrayHolder<WCHAR> wzClassName(DuplicateStringThrowing(ssClassName.GetUnicode()));
1436 if (m_vNameToTypeMapVersion != vCacheVersion)
1439 if (m_pNameToTypeMap == nullptr)
1441 m_pNameToTypeMap = new NameToTypeMapTable();
1444 NameToTypeMapEntry e;
1445 e.m_key.m_wzName = wzClassName;
1446 e.m_key.m_cchName = ssClassName.GetCount();
1447 e.m_typeHandle = typeHandle;
1448 e.m_nEpoch = this->m_nEpoch;
1449 e.m_bFlags = bFlags;
1450 if (!bReplaceExisting)
1451 m_pNameToTypeMap->Add(e);
1453 m_pNameToTypeMap->AddOrReplace(e);
1455 wzClassName.SuppressRelease();
1457 #endif // DACCESS_COMPILE
1459 TypeHandle AppDomain::LookupTypeByName(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags)
1461 WRAPPER_NO_CONTRACT;
1462 LockHolder lh(this);
1463 return LookupTypeByNameWorker(ssClassName, pvCacheVersion, pbFlags);
1466 TypeHandle AppDomain::LookupTypeByNameWorker(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags)
1473 PRECONDITION(CheckPointer(pbFlags, NULL_OK));
1477 *pvCacheVersion = m_vNameToTypeMapVersion;
1479 if (m_pNameToTypeMap == nullptr)
1480 return TypeHandle(); // a null TypeHandle
1482 NameToTypeMapEntry::Key key;
1483 key.m_cchName = ssClassName.GetCount();
1484 key.m_wzName = ssClassName.GetUnicode();
1486 const NameToTypeMapEntry * pEntry = m_pNameToTypeMap->LookupPtr(key);
1488 return TypeHandle(); // a null TypeHandle
1490 if (pbFlags != NULL)
1491 *pbFlags = pEntry->m_bFlags;
1493 return pEntry->m_typeHandle;
1496 PTR_MethodTable AppDomain::LookupTypeByGuid(const GUID & guid)
1510 GuidToLPWSTR(guid, wszGuid, _countof(wszGuid));
1511 sGuid.Append(wszGuid);
1514 TypeHandle th = LookupTypeByName(sGuid, &ver, NULL);
1518 _ASSERTE(!th.IsTypeDesc());
1519 return th.AsMethodTable();
1522 #ifdef FEATURE_PREJIT
1525 // Next look in each ngen'ed image in turn
1526 AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)(
1527 kIncludeLoaded | kIncludeExecution));
1528 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1529 while (assemblyIterator.Next(pDomainAssembly.This()))
1531 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
1533 DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded);
1536 Module * pModule = i.GetLoadedModule();
1537 if (!pModule->HasNativeImage())
1539 _ASSERTE(!pModule->IsCollectible());
1540 PTR_MethodTable pMT = pModule->LookupTypeByGuid(guid);
1548 #endif // FEATURE_PREJIT
1552 #ifndef DACCESS_COMPILE
1553 void AppDomain::CacheWinRTTypeByGuid(TypeHandle typeHandle)
1560 PRECONDITION(!typeHandle.IsTypeDesc());
1561 PRECONDITION(CanCacheWinRTTypeByGuid(typeHandle));
1565 PTR_MethodTable pMT = typeHandle.AsMethodTable();
1568 if (pMT->GetGuidForWinRT(&guid))
1574 GuidToLPWSTR(guid, wszGuid, _countof(wszGuid));
1575 sGuid.Append(wszGuid);
1582 LockHolder lh(this);
1583 th = LookupTypeByNameWorker(sGuid, &vCacheVersion, &bFlags);
1587 // no other entry with the same GUID exists in the cache
1588 CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags);
1590 else if (typeHandle.AsMethodTable() != th.AsMethodTable() && th.IsProjectedFromWinRT())
1592 // If we found a native WinRT type cached with the same GUID, replace it.
1593 // Otherwise simply add the new mapping to the cache.
1594 CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags, TRUE);
1599 #endif // DACCESS_COMPILE
1601 void AppDomain::GetCachedWinRTTypes(
1602 SArray<PTR_MethodTable> * pTypes,
1603 SArray<GUID> * pGuids,
1616 LockHolder lh(this);
1618 for (auto it = m_pNameToTypeMap->Begin(), end = m_pNameToTypeMap->End();
1622 NameToTypeMapEntry entry = (NameToTypeMapEntry)(*it);
1623 TypeHandle th = entry.m_typeHandle;
1624 if (th.AsMethodTable() != NULL &&
1625 entry.m_key.m_wzName[0] == W('{') &&
1626 entry.m_nEpoch >= minEpoch)
1628 _ASSERTE(!th.IsTypeDesc());
1629 PTR_MethodTable pMT = th.AsMethodTable();
1630 // we're parsing the GUID value from the cache, because projected types do not cache the
1631 // COM GUID in their GetGuid() but rather the legacy GUID
1633 if (LPWSTRToGuid(&iid, entry.m_key.m_wzName, 38) && iid != GUID_NULL)
1635 pTypes->Append(pMT);
1636 pGuids->Append(iid);
1641 #ifdef FEATURE_PREJIT
1642 // Next look in each ngen'ed image in turn
1643 AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)(
1644 kIncludeLoaded | kIncludeExecution));
1645 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
1646 while (assemblyIterator.Next(pDomainAssembly.This()))
1648 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
1650 DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded);
1653 Module * pModule = i.GetLoadedModule();
1654 if (!pModule->HasNativeImage())
1656 _ASSERTE(!pModule->IsCollectible());
1658 pModule->GetCachedWinRTTypes(pTypes, pGuids);
1661 #endif // FEATURE_PREJIT
1663 if (pCurEpoch != NULL)
1664 *pCurEpoch = m_nEpoch;
1668 #ifndef CROSSGEN_COMPILE
1669 #ifndef DACCESS_COMPILE
1671 void WinRTFactoryCacheTraits::OnDestructPerEntryCleanupAction(const WinRTFactoryCacheEntry& e)
1673 WRAPPER_NO_CONTRACT;
1674 if (e.m_pCtxEntry != NULL)
1676 e.m_pCtxEntry->Release();
1678 // the AD is going away, no need to destroy the OBJECTHANDLE
1681 void AppDomain::CacheWinRTFactoryObject(MethodTable *pClassMT, OBJECTREF *refFactory, LPVOID lpCtxCookie)
1688 PRECONDITION(CheckPointer(pClassMT));
1692 CtxEntryHolder pNewCtxEntry;
1693 if (lpCtxCookie != NULL)
1695 // We don't want to insert the context cookie in the cache because it's just an address
1696 // of an internal COM data structure which will be freed when the apartment is torn down.
1697 // What's worse, if another apartment is later created, its context cookie may have exactly
1698 // the same value leading to incorrect cache hits. We'll use our CtxEntry instead which
1699 // is ref-counted and keeps the COM data structure alive even after the apartment ceases
1701 pNewCtxEntry = CtxEntryCache::GetCtxEntryCache()->FindCtxEntry(lpCtxCookie, GetThread());
1704 WinRTFactoryCacheLockHolder lh(this);
1706 if (m_pWinRTFactoryCache == nullptr)
1708 m_pWinRTFactoryCache = new WinRTFactoryCache();
1711 WinRTFactoryCacheEntry *pEntry = const_cast<WinRTFactoryCacheEntry*>(m_pWinRTFactoryCache->LookupPtr(pClassMT));
1715 // No existing entry for this cache
1718 WinRTFactoryCacheEntry e;
1720 OBJECTHANDLEHolder ohNewHandle(CreateHandle(*refFactory));
1723 e.m_pCtxEntry = pNewCtxEntry;
1724 e.m_ohFactoryObject = ohNewHandle;
1726 m_pWinRTFactoryCache->Add(e);
1728 // suppress release of the CtxEntry and handle after we successfully inserted the new entry
1729 pNewCtxEntry.SuppressRelease();
1730 ohNewHandle.SuppressRelease();
1737 // release the old CtxEntry and update the entry
1738 CtxEntry *pTemp = pNewCtxEntry.Extract();
1739 pNewCtxEntry = pEntry->m_pCtxEntry;
1740 pEntry->m_pCtxEntry = pTemp;
1742 IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
1743 mgr->StoreObjectInHandle(pEntry->m_ohFactoryObject, OBJECTREFToObject(*refFactory));
1747 OBJECTREF AppDomain::LookupWinRTFactoryObject(MethodTable *pClassMT, LPVOID lpCtxCookie)
1754 PRECONDITION(CheckPointer(pClassMT));
1755 PRECONDITION(CheckPointer(m_pWinRTFactoryCache, NULL_OK));
1760 if (m_pWinRTFactoryCache == nullptr)
1764 // Retrieve cached factory
1766 WinRTFactoryCacheLockHolder lh(this);
1768 const WinRTFactoryCacheEntry *pEntry = m_pWinRTFactoryCache->LookupPtr(pClassMT);
1773 // Ignore factories from a different context, unless lpCtxCookie == NULL,
1774 // which means the factory is free-threaded
1775 // Note that we cannot touch the RCW to retrieve cookie at this point
1776 // because the RCW might belong to a STA thread and that STA thread might die
1777 // and take the RCW with it. Therefore we have to save cookie in this cache
1779 if (pEntry->m_pCtxEntry == NULL || pEntry->m_pCtxEntry->GetCtxCookie() == lpCtxCookie)
1780 return ObjectFromHandle(pEntry->m_ohFactoryObject);
1785 void AppDomain::RemoveWinRTFactoryObjects(LPVOID pCtxCookie)
1795 if (m_pWinRTFactoryCache == nullptr)
1798 // helper class for delayed CtxEntry cleanup
1799 class CtxEntryListReleaseHolder
1802 CQuickArrayList<CtxEntry *> m_list;
1804 ~CtxEntryListReleaseHolder()
1814 for (SIZE_T i = 0; i < m_list.Size(); i++)
1816 m_list[i]->Release();
1819 } ctxEntryListReleaseHolder;
1823 WinRTFactoryCacheLockHolder lh(this);
1825 // Go through the hash table and remove items in the given context
1826 for (WinRTFactoryCache::Iterator it = m_pWinRTFactoryCache->Begin(); it != m_pWinRTFactoryCache->End(); it++)
1828 if (it->m_pCtxEntry != NULL && it->m_pCtxEntry->GetCtxCookie() == pCtxCookie)
1830 // Releasing the CtxEntry may trigger GC which we can't do under the lock so we push
1831 // it on our local list and release them all after we're done iterating the hashtable.
1832 ctxEntryListReleaseHolder.m_list.Push(it->m_pCtxEntry);
1834 DestroyHandle(it->m_ohFactoryObject);
1835 m_pWinRTFactoryCache->Remove(it);
1841 OBJECTREF AppDomain::GetMissingObject()
1854 FieldDesc *pValueFD = MscorlibBinder::GetField(FIELD__MISSING__VALUE);
1856 pValueFD->CheckRunClassInitThrowing();
1858 // Retrieve the value static field and store it.
1859 OBJECTHANDLE hndMissing = CreateHandle(pValueFD->GetStaticOBJECTREF());
1861 if (FastInterlockCompareExchangePointer(&m_hndMissing, hndMissing, NULL) != NULL)
1863 // Exchanged failed. The m_hndMissing did not equal NULL and was returned.
1864 DestroyHandle(hndMissing);
1868 return ObjectFromHandle(m_hndMissing);
1871 #endif // DACCESS_COMPILE
1872 #endif //CROSSGEN_COMPILE
1873 #endif // FEATURE_COMINTEROP
1875 #ifndef DACCESS_COMPILE
1877 EEMarshalingData *BaseDomain::GetMarshalingData()
1879 CONTRACT (EEMarshalingData*)
1884 INJECT_FAULT(COMPlusThrowOM());
1885 POSTCONDITION(CheckPointer(m_pMarshalingData));
1889 if (!m_pMarshalingData)
1892 CrstHolder holder(&m_InteropDataCrst);
1894 if (!m_pMarshalingData)
1896 LoaderHeap* pHeap = GetLoaderAllocator()->GetLowFrequencyHeap();
1897 m_pMarshalingData = new (pHeap) EEMarshalingData(this, pHeap, &m_DomainCrst);
1901 RETURN m_pMarshalingData;
1904 void BaseDomain::DeleteMarshalingData()
1914 // We are in shutdown - no need to take any lock
1915 if (m_pMarshalingData)
1917 delete m_pMarshalingData;
1918 m_pMarshalingData = NULL;
1922 #ifndef CROSSGEN_COMPILE
1924 STRINGREF *BaseDomain::IsStringInterned(STRINGREF *pString)
1931 PRECONDITION(CheckPointer(pString));
1932 INJECT_FAULT(COMPlusThrowOM(););
1936 return GetLoaderAllocator()->IsStringInterned(pString);
1939 STRINGREF *BaseDomain::GetOrInternString(STRINGREF *pString)
1946 PRECONDITION(CheckPointer(pString));
1947 INJECT_FAULT(COMPlusThrowOM(););
1951 return GetLoaderAllocator()->GetOrInternString(pString);
1954 void BaseDomain::InitLargeHeapHandleTable()
1961 PRECONDITION(m_pLargeHeapHandleTable==NULL);
1962 INJECT_FAULT(COMPlusThrowOM(););
1966 m_pLargeHeapHandleTable = new LargeHeapHandleTable(this, STATIC_OBJECT_TABLE_BUCKET_SIZE);
1969 m_pLargeHeapHandleTable->RegisterCrstDebug(&m_LargeHeapHandleTableCrst);
1973 #ifdef FEATURE_COMINTEROP
1974 MethodTable* AppDomain::GetLicenseInteropHelperMethodTable()
1983 if(m_pLicenseInteropHelperMT == NULL)
1985 // Do this work outside of the lock so we don't have an unbreakable lock condition
1987 TypeHandle licenseMgrTypeHnd;
1988 MethodDescCallSite loadLM(METHOD__MARSHAL__LOAD_LICENSE_MANAGER);
1990 licenseMgrTypeHnd = (MethodTable*) loadLM.Call_RetLPVOID((ARG_SLOT*)NULL);
1993 // Look up this method by name, because the type is actually declared in System.dll. <TODO>@todo: why?</TODO>
1996 MethodDesc *pGetLIHMD = MemberLoader::FindMethod(licenseMgrTypeHnd.AsMethodTable(),
1997 "GetLicenseInteropHelperType", &gsig_SM_Void_RetIntPtr);
1998 _ASSERTE(pGetLIHMD);
2000 TypeHandle lihTypeHnd;
2002 MethodDescCallSite getLIH(pGetLIHMD);
2003 lihTypeHnd = (MethodTable*) getLIH.Call_RetLPVOID((ARG_SLOT*)NULL);
2005 BaseDomain::LockHolder lh(this);
2007 if(m_pLicenseInteropHelperMT == NULL)
2008 m_pLicenseInteropHelperMT = lihTypeHnd.AsMethodTable();
2010 return m_pLicenseInteropHelperMT;
2013 COMorRemotingFlag AppDomain::GetComOrRemotingFlag()
2023 // 0. check if the value is already been set
2024 if (m_COMorRemotingFlag != COMorRemoting_NotInitialized)
2025 return m_COMorRemotingFlag;
2027 // 1. check whether the process is AppX
2028 if (AppX::IsAppXProcess())
2030 // do not use Remoting in AppX
2031 m_COMorRemotingFlag = COMorRemoting_COM;
2032 return m_COMorRemotingFlag;
2035 // 2. check the xml file
2036 m_COMorRemotingFlag = GetPreferComInsteadOfManagedRemotingFromConfigFile();
2037 if (m_COMorRemotingFlag != COMorRemoting_NotInitialized)
2039 return m_COMorRemotingFlag;
2042 // 3. check the global setting
2043 if (NULL != g_pConfig && g_pConfig->ComInsteadOfManagedRemoting())
2045 m_COMorRemotingFlag = COMorRemoting_COM;
2049 m_COMorRemotingFlag = COMorRemoting_Remoting;
2052 return m_COMorRemotingFlag;
2055 BOOL AppDomain::GetPreferComInsteadOfManagedRemoting()
2057 WRAPPER_NO_CONTRACT;
2059 return (GetComOrRemotingFlag() == COMorRemoting_COM);
2062 COMorRemotingFlag AppDomain::GetPreferComInsteadOfManagedRemotingFromConfigFile()
2072 return COMorRemoting_COM;
2074 #endif // FEATURE_COMINTEROP
2076 #endif // CROSSGEN_COMPILE
2078 //*****************************************************************************
2079 //*****************************************************************************
2080 //*****************************************************************************
2082 void *SystemDomain::operator new(size_t size, void *pInPlace)
2084 LIMITED_METHOD_CONTRACT;
2089 void SystemDomain::operator delete(void *pMem)
2091 LIMITED_METHOD_CONTRACT;
2092 // Do nothing - new() was in-place
2096 void SystemDomain::SetCompilationOverrides(BOOL fForceDebug,
2097 BOOL fForceProfiling,
2098 BOOL fForceInstrument)
2100 LIMITED_METHOD_CONTRACT;
2101 s_fForceDebug = fForceDebug;
2102 s_fForceProfiling = fForceProfiling;
2103 s_fForceInstrument = fForceInstrument;
2106 #endif //!DACCESS_COMPILE
2108 void SystemDomain::GetCompilationOverrides(BOOL * fForceDebug,
2109 BOOL * fForceProfiling,
2110 BOOL * fForceInstrument)
2112 LIMITED_METHOD_DAC_CONTRACT;
2113 *fForceDebug = s_fForceDebug;
2114 *fForceProfiling = s_fForceProfiling;
2115 *fForceInstrument = s_fForceInstrument;
2118 #ifndef DACCESS_COMPILE
2120 void SystemDomain::Attach()
2127 PRECONDITION(m_pSystemDomain == NULL);
2128 INJECT_FAULT(COMPlusThrowOM(););
2132 #ifndef CROSSGEN_COMPILE
2133 // Initialize stub managers
2134 PrecodeStubManager::Init();
2135 DelegateInvokeStubManager::Init();
2136 JumpStubStubManager::Init();
2137 RangeSectionStubManager::Init();
2138 ILStubManager::Init();
2139 InteropDispatchStubManager::Init();
2140 StubLinkStubManager::Init();
2142 ThunkHeapStubManager::Init();
2144 TailCallStubManager::Init();
2146 PerAppDomainTPCountList::InitAppDomainIndexList();
2147 #endif // CROSSGEN_COMPILE
2149 m_appDomainIndexList.Init();
2150 m_appDomainIdList.Init();
2152 m_SystemDomainCrst.Init(CrstSystemDomain, (CrstFlags)(CRST_REENTRANCY | CRST_TAKEN_DURING_SHUTDOWN));
2153 m_DelayedUnloadCrst.Init(CrstSystemDomainDelayedUnloadList, CRST_UNSAFE_COOPGC);
2155 // Initialize the ID dispenser that is used for domain neutral module IDs
2156 g_pModuleIndexDispenser = new IdDispenser();
2158 // Create the global SystemDomain and initialize it.
2159 m_pSystemDomain = new (&g_pSystemDomainMemory[0]) SystemDomain();
2160 // No way it can fail since g_pSystemDomainMemory is a static array.
2161 CONSISTENCY_CHECK(CheckPointer(m_pSystemDomain));
2163 LOG((LF_CLASSLOADER,
2165 "Created system domain at %p\n",
2168 // We need to initialize the memory pools etc. for the system domain.
2169 m_pSystemDomain->BaseDomain::Init(); // Setup the memory heaps
2171 // Create the default domain
2172 m_pSystemDomain->CreateDefaultDomain();
2173 SharedDomain::Attach();
2175 // Each domain gets its own ReJitManager, and ReJitManager has its own static
2176 // initialization to run
2177 ReJitManager::InitStatic();
2180 #ifndef CROSSGEN_COMPILE
2182 void SystemDomain::DetachBegin()
2184 WRAPPER_NO_CONTRACT;
2185 // Shut down the domain and its children (but don't deallocate anything just
2188 // TODO: we should really not running managed DLLMain during process detach.
2189 if (GetThread() == NULL)
2195 m_pSystemDomain->Stop();
2198 void SystemDomain::DetachEnd()
2207 // Shut down the domain and its children (but don't deallocate anything just
2212 m_pSystemDomain->ClearFusionContext();
2213 if (m_pSystemDomain->m_pDefaultDomain)
2214 m_pSystemDomain->m_pDefaultDomain->ClearFusionContext();
2218 void SystemDomain::Stop()
2220 WRAPPER_NO_CONTRACT;
2221 AppDomainIterator i(TRUE);
2224 if (i.GetDomain()->m_Stage < AppDomain::STAGE_CLEARED)
2225 i.GetDomain()->Stop();
2229 void SystemDomain::Terminate() // bNotifyProfiler is ignored
2239 // This ignores the refences and terminates the appdomains
2240 AppDomainIterator i(FALSE);
2244 delete i.GetDomain();
2245 // Keep the iterator from Releasing the current domain
2246 i.m_pCurrent = NULL;
2249 if (m_pSystemFile != NULL) {
2250 m_pSystemFile->Release();
2251 m_pSystemFile = NULL;
2254 m_pSystemAssembly = NULL;
2257 delete[] m_pwDevpath;
2263 if (m_pGlobalStringLiteralMap) {
2264 delete m_pGlobalStringLiteralMap;
2265 m_pGlobalStringLiteralMap = NULL;
2269 SharedDomain::Detach();
2271 BaseDomain::Terminate();
2273 #ifdef FEATURE_COMINTEROP
2274 if (g_pRCWCleanupList != NULL)
2275 delete g_pRCWCleanupList;
2276 #endif // FEATURE_COMINTEROP
2277 m_GlobalAllocator.Terminate();
2281 void SystemDomain::PreallocateSpecialObjects()
2288 INJECT_FAULT(COMPlusThrowOM(););
2292 _ASSERTE(g_pPreallocatedSentinelObject == NULL);
2294 OBJECTREF pPreallocatedSentinalObject = AllocateObject(g_pObjectClass);
2295 #if CHECK_APP_DOMAIN_LEAKS
2296 pPreallocatedSentinalObject->SetSyncBlockAppDomainAgile();
2298 g_pPreallocatedSentinelObject = CreatePinningHandle( pPreallocatedSentinalObject );
2300 #ifdef FEATURE_PREJIT
2301 if (SystemModule()->HasNativeImage())
2303 CORCOMPILE_EE_INFO_TABLE *pEEInfo = SystemModule()->GetNativeImage()->GetNativeEEInfoTable();
2304 pEEInfo->emptyString = (CORINFO_Object **)StringObject::GetEmptyStringRefPtr();
2309 void SystemDomain::CreatePreallocatedExceptions()
2316 INJECT_FAULT(COMPlusThrowOM(););
2320 EXCEPTIONREF pBaseException = (EXCEPTIONREF)AllocateObject(g_pExceptionClass);
2321 pBaseException->SetHResult(COR_E_EXCEPTION);
2322 pBaseException->SetXCode(EXCEPTION_COMPLUS);
2323 _ASSERTE(g_pPreallocatedBaseException == NULL);
2324 g_pPreallocatedBaseException = CreateHandle(pBaseException);
2327 EXCEPTIONREF pOutOfMemory = (EXCEPTIONREF)AllocateObject(g_pOutOfMemoryExceptionClass);
2328 pOutOfMemory->SetHResult(COR_E_OUTOFMEMORY);
2329 pOutOfMemory->SetXCode(EXCEPTION_COMPLUS);
2330 _ASSERTE(g_pPreallocatedOutOfMemoryException == NULL);
2331 g_pPreallocatedOutOfMemoryException = CreateHandle(pOutOfMemory);
2334 EXCEPTIONREF pStackOverflow = (EXCEPTIONREF)AllocateObject(g_pStackOverflowExceptionClass);
2335 pStackOverflow->SetHResult(COR_E_STACKOVERFLOW);
2336 pStackOverflow->SetXCode(EXCEPTION_COMPLUS);
2337 _ASSERTE(g_pPreallocatedStackOverflowException == NULL);
2338 g_pPreallocatedStackOverflowException = CreateHandle(pStackOverflow);
2341 EXCEPTIONREF pExecutionEngine = (EXCEPTIONREF)AllocateObject(g_pExecutionEngineExceptionClass);
2342 pExecutionEngine->SetHResult(COR_E_EXECUTIONENGINE);
2343 pExecutionEngine->SetXCode(EXCEPTION_COMPLUS);
2344 _ASSERTE(g_pPreallocatedExecutionEngineException == NULL);
2345 g_pPreallocatedExecutionEngineException = CreateHandle(pExecutionEngine);
2348 EXCEPTIONREF pRudeAbortException = (EXCEPTIONREF)AllocateObject(g_pThreadAbortExceptionClass);
2349 #if CHECK_APP_DOMAIN_LEAKS
2350 pRudeAbortException->SetSyncBlockAppDomainAgile();
2352 pRudeAbortException->SetHResult(COR_E_THREADABORTED);
2353 pRudeAbortException->SetXCode(EXCEPTION_COMPLUS);
2354 _ASSERTE(g_pPreallocatedRudeThreadAbortException == NULL);
2355 g_pPreallocatedRudeThreadAbortException = CreateHandle(pRudeAbortException);
2358 EXCEPTIONREF pAbortException = (EXCEPTIONREF)AllocateObject(g_pThreadAbortExceptionClass);
2359 #if CHECK_APP_DOMAIN_LEAKS
2360 pAbortException->SetSyncBlockAppDomainAgile();
2362 pAbortException->SetHResult(COR_E_THREADABORTED);
2363 pAbortException->SetXCode(EXCEPTION_COMPLUS);
2364 _ASSERTE(g_pPreallocatedThreadAbortException == NULL);
2365 g_pPreallocatedThreadAbortException = CreateHandle( pAbortException );
2367 #endif // CROSSGEN_COMPILE
2369 void SystemDomain::Init()
2371 STANDARD_VM_CONTRACT;
2379 "sizeof(EEClass) = %d\n"
2380 "sizeof(MethodTable) = %d\n"
2381 "sizeof(MethodDesc)= %d\n"
2382 "sizeof(FieldDesc) = %d\n"
2383 "sizeof(Module) = %d\n",
2385 sizeof(MethodTable),
2392 // The base domain is initialized in SystemDomain::Attach()
2393 // to allow stub caches to use the memory pool. Do not
2394 // initialze it here!
2396 #ifndef CROSSGEN_COMPILE
2398 Context *curCtx = GetCurrentContext();
2401 _ASSERTE(curCtx->GetDomain() != NULL);
2404 #ifdef FEATURE_PREJIT
2405 if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_ZapDisable) != 0)
2406 g_fAllowNativeImages = false;
2409 m_pSystemFile = NULL;
2410 m_pSystemAssembly = NULL;
2415 // Get the install directory so we can find mscorlib
2416 hr = GetInternalSystemDirectory(NULL, &size);
2417 if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
2420 // GetInternalSystemDirectory returns a size, including the null!
2421 WCHAR *buffer = m_SystemDirectory.OpenUnicodeBuffer(size-1);
2422 IfFailThrow(GetInternalSystemDirectory(buffer, &size));
2423 m_SystemDirectory.CloseBuffer();
2424 m_SystemDirectory.Normalize();
2426 // At this point m_SystemDirectory should already be canonicalized
2429 m_BaseLibrary.Append(m_SystemDirectory);
2430 if (!m_BaseLibrary.EndsWith(DIRECTORY_SEPARATOR_CHAR_W))
2432 m_BaseLibrary.Append(DIRECTORY_SEPARATOR_CHAR_W);
2434 m_BaseLibrary.Append(g_pwBaseLibrary);
2435 m_BaseLibrary.Normalize();
2437 LoadBaseSystemClasses();
2440 // We are about to start allocating objects, so we must be in cooperative mode.
2441 // However, many of the entrypoints to the system (DllGetClassObject and all
2442 // N/Direct exports) get called multiple times. Sometimes they initialize the EE,
2443 // but generally they remain in preemptive mode. So we really want to push/pop
2447 #ifndef CROSSGEN_COMPILE
2448 if (!NingenEnabled())
2450 CreatePreallocatedExceptions();
2452 PreallocateSpecialObjects();
2456 // Finish loading mscorlib now.
2457 m_pSystemAssembly->GetDomainAssembly()->EnsureActive();
2461 BOOL fPause = EEConfig::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_PauseOnLoad, FALSE);
2465 ClrSleepEx(20, TRUE);
2470 #ifndef CROSSGEN_COMPILE
2471 void SystemDomain::LazyInitGlobalStringLiteralMap()
2478 INJECT_FAULT(COMPlusThrowOM(););
2482 // Allocate the global string literal map.
2483 NewHolder<GlobalStringLiteralMap> pGlobalStringLiteralMap(new GlobalStringLiteralMap());
2485 // Initialize the global string literal map.
2486 pGlobalStringLiteralMap->Init();
2488 if (InterlockedCompareExchangeT<GlobalStringLiteralMap *>(&m_pGlobalStringLiteralMap, pGlobalStringLiteralMap, NULL) == NULL)
2490 pGlobalStringLiteralMap.SuppressRelease();
2494 void AppDomain::CreateADUnloadStartEvent()
2505 g_pUnloadStartEvent = new CLREvent();
2506 g_pUnloadStartEvent->CreateAutoEvent(FALSE);
2509 /*static*/ void SystemDomain::EnumAllStaticGCRefs(promote_func* fn, ScanContext* sc)
2519 // We don't do a normal AppDomainIterator because we can't take the SystemDomain lock from
2521 // We're only supposed to call this from a Server GC. We're walking here m_appDomainIdList
2522 // m_appDomainIdList will have an AppDomain* or will be NULL. So the only danger is if we
2523 // Fetch an AppDomain and then in some other thread the AppDomain is deleted.
2525 // If the thread deleting the AppDomain (AppDomain::~AppDomain)was in Preemptive mode
2526 // while doing SystemDomain::EnumAllStaticGCRefs we will issue a GCX_COOP(), which will wait
2527 // for the GC to finish, so we are safe
2529 // If the thread is in cooperative mode, it must have been suspended for the GC so a delete
2532 _ASSERTE(GCHeapUtilities::IsGCInProgress() &&
2533 GCHeapUtilities::IsServerHeap() &&
2534 IsGCSpecialThread());
2536 SystemDomain* sysDomain = SystemDomain::System();
2540 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2541 for (i = 0 ; i < count ; i++)
2543 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2544 if (pAppDomain && pAppDomain->IsActive() && !pAppDomain->IsUnloading())
2546 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
2549 sc->pCurrentDomain = pAppDomain;
2551 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
2552 pAppDomain->EnumStaticGCRefs(fn, sc);
2560 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
2561 void SystemDomain::ResetADSurvivedBytes()
2571 _ASSERTE(GCHeapUtilities::IsGCInProgress());
2573 SystemDomain* sysDomain = SystemDomain::System();
2577 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2578 for (i = 0 ; i < count ; i++)
2580 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2581 if (pAppDomain && pAppDomain->IsUserActive())
2583 pAppDomain->ResetSurvivedBytes();
2591 ULONGLONG SystemDomain::GetADSurvivedBytes()
2601 SystemDomain* sysDomain = SystemDomain::System();
2602 ULONGLONG ullTotalADSurvived = 0;
2606 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2607 for (i = 0 ; i < count ; i++)
2609 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2610 if (pAppDomain && pAppDomain->IsUserActive())
2612 ULONGLONG ullSurvived = pAppDomain->GetSurvivedBytes();
2613 ullTotalADSurvived += ullSurvived;
2618 return ullTotalADSurvived;
2621 void SystemDomain::RecordTotalSurvivedBytes(size_t totalSurvivedBytes)
2631 m_totalSurvivedBytes = totalSurvivedBytes;
2633 SystemDomain* sysDomain = SystemDomain::System();
2637 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2638 for (i = 0 ; i < count ; i++)
2640 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2641 if (pAppDomain && pAppDomain->IsUserActive())
2643 FireEtwAppDomainMemSurvived((ULONGLONG)pAppDomain, pAppDomain->GetSurvivedBytes(), totalSurvivedBytes, GetClrInstanceId());
2650 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
2652 // Only called when EE is suspended.
2653 DWORD SystemDomain::GetTotalNumSizedRefHandles()
2663 SystemDomain* sysDomain = SystemDomain::System();
2664 DWORD dwTotalNumSizedRefHandles = 0;
2668 DWORD count = (DWORD) m_appDomainIdList.GetCount();
2669 for (i = 0 ; i < count ; i++)
2671 AppDomain* pAppDomain = (AppDomain *)m_appDomainIdList.Get(i);
2672 if (pAppDomain && pAppDomain->IsActive() && !pAppDomain->IsUnloading())
2674 dwTotalNumSizedRefHandles += pAppDomain->GetNumSizedRefHandles();
2679 return dwTotalNumSizedRefHandles;
2681 #endif // CROSSGEN_COMPILE
2683 void SystemDomain::LoadBaseSystemClasses()
2685 STANDARD_VM_CONTRACT;
2687 ETWOnStartup(LdSysBases_V1, LdSysBasesEnd_V1);
2690 m_pSystemFile = PEAssembly::OpenSystem(NULL);
2692 // Only partially load the system assembly. Other parts of the code will want to access
2693 // the globals in this function before finishing the load.
2694 m_pSystemAssembly = DefaultDomain()->LoadDomainAssembly(NULL, m_pSystemFile, FILE_LOAD_POST_LOADLIBRARY)->GetCurrentAssembly();
2696 // Set up binder for mscorlib
2697 MscorlibBinder::AttachModule(m_pSystemAssembly->GetManifestModule());
2700 g_pObjectClass = MscorlibBinder::GetClass(CLASS__OBJECT);
2702 // Now that ObjectClass is loaded, we can set up
2703 // the system for finalizers. There is no point in deferring this, since we need
2704 // to know this before we allocate our first object.
2705 g_pObjectFinalizerMD = MscorlibBinder::GetMethod(METHOD__OBJECT__FINALIZE);
2708 g_pCanonMethodTableClass = MscorlibBinder::GetClass(CLASS____CANON);
2710 // NOTE: !!!IMPORTANT!!! ValueType and Enum MUST be loaded one immediately after
2711 // the other, because we have coded MethodTable::IsChildValueType
2712 // in such a way that it depends on this behaviour.
2713 // Load the ValueType class
2714 g_pValueTypeClass = MscorlibBinder::GetClass(CLASS__VALUE_TYPE);
2716 // Load the enum class
2717 g_pEnumClass = MscorlibBinder::GetClass(CLASS__ENUM);
2718 _ASSERTE(!g_pEnumClass->IsValueType());
2720 // Load System.RuntimeType
2721 g_pRuntimeTypeClass = MscorlibBinder::GetClass(CLASS__CLASS);
2722 _ASSERTE(g_pRuntimeTypeClass->IsFullyLoaded());
2725 g_pArrayClass = MscorlibBinder::GetClass(CLASS__ARRAY);
2727 // Calling a method on IList<T> for an array requires redirection to a method on
2728 // the SZArrayHelper class. Retrieving such methods means calling
2729 // GetActualImplementationForArrayGenericIListMethod, which calls FetchMethod for
2730 // the corresponding method on SZArrayHelper. This basically results in a class
2731 // load due to a method call, which the debugger cannot handle, so we pre-load
2732 // the SZArrayHelper class here.
2733 g_pSZArrayHelperClass = MscorlibBinder::GetClass(CLASS__SZARRAYHELPER);
2735 // Load ByReference class
2737 // NOTE: ByReference<T> must be the first by-ref-like system type to be loaded,
2738 // because MethodTable::ClassifyEightBytesWithManagedLayout depends on it.
2739 g_pByReferenceClass = MscorlibBinder::GetClass(CLASS__BYREFERENCE);
2741 // Load Nullable class
2742 g_pNullableClass = MscorlibBinder::GetClass(CLASS__NULLABLE);
2744 // Load the Object array class.
2745 g_pPredefinedArrayTypes[ELEMENT_TYPE_OBJECT] = ClassLoader::LoadArrayTypeThrowing(TypeHandle(g_pObjectClass)).AsArray();
2747 // We have delayed allocation of mscorlib's static handles until we load the object class
2748 MscorlibBinder::GetModule()->AllocateRegularStaticHandles(DefaultDomain());
2750 g_TypedReferenceMT = MscorlibBinder::GetClass(CLASS__TYPED_REFERENCE);
2752 // Make sure all primitive types are loaded
2753 for (int et = ELEMENT_TYPE_VOID; et <= ELEMENT_TYPE_R8; et++)
2754 MscorlibBinder::LoadPrimitiveType((CorElementType)et);
2756 MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_I);
2757 MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_U);
2759 // unfortunately, the following cannot be delay loaded since the jit
2760 // uses it to compute method attributes within a function that cannot
2761 // handle Complus exception and the following call goes through a path
2762 // where a complus exception can be thrown. It is unfortunate, because
2763 // we know that the delegate class and multidelegate class are always
2764 // guaranteed to be found.
2765 g_pDelegateClass = MscorlibBinder::GetClass(CLASS__DELEGATE);
2766 g_pMulticastDelegateClass = MscorlibBinder::GetClass(CLASS__MULTICAST_DELEGATE);
2768 // used by IsImplicitInterfaceOfSZArray
2769 MscorlibBinder::GetClass(CLASS__IENUMERABLEGENERIC);
2770 MscorlibBinder::GetClass(CLASS__ICOLLECTIONGENERIC);
2771 MscorlibBinder::GetClass(CLASS__ILISTGENERIC);
2772 MscorlibBinder::GetClass(CLASS__IREADONLYCOLLECTIONGENERIC);
2773 MscorlibBinder::GetClass(CLASS__IREADONLYLISTGENERIC);
2776 g_pStringClass = MscorlibBinder::LoadPrimitiveType(ELEMENT_TYPE_STRING);
2777 _ASSERTE(g_pStringClass->GetBaseSize() == ObjSizeOf(StringObject)+sizeof(WCHAR));
2778 _ASSERTE(g_pStringClass->GetComponentSize() == 2);
2780 // Used by Buffer::BlockCopy
2781 g_pByteArrayMT = ClassLoader::LoadArrayTypeThrowing(
2782 TypeHandle(MscorlibBinder::GetElementType(ELEMENT_TYPE_U1))).AsArray()->GetMethodTable();
2784 #ifndef CROSSGEN_COMPILE
2785 ECall::PopulateManagedStringConstructors();
2786 #endif // CROSSGEN_COMPILE
2788 g_pExceptionClass = MscorlibBinder::GetClass(CLASS__EXCEPTION);
2789 g_pOutOfMemoryExceptionClass = MscorlibBinder::GetException(kOutOfMemoryException);
2790 g_pStackOverflowExceptionClass = MscorlibBinder::GetException(kStackOverflowException);
2791 g_pExecutionEngineExceptionClass = MscorlibBinder::GetException(kExecutionEngineException);
2792 g_pThreadAbortExceptionClass = MscorlibBinder::GetException(kThreadAbortException);
2795 // used by gc to handle predefined agility checking
2796 g_pThreadClass = MscorlibBinder::GetClass(CLASS__THREAD);
2798 #ifdef FEATURE_COMINTEROP
2799 g_pBaseCOMObject = MscorlibBinder::GetClass(CLASS__COM_OBJECT);
2800 g_pBaseRuntimeClass = MscorlibBinder::GetClass(CLASS__RUNTIME_CLASS);
2802 MscorlibBinder::GetClass(CLASS__IDICTIONARYGENERIC);
2803 MscorlibBinder::GetClass(CLASS__IREADONLYDICTIONARYGENERIC);
2804 MscorlibBinder::GetClass(CLASS__ATTRIBUTE);
2805 MscorlibBinder::GetClass(CLASS__EVENT_HANDLERGENERIC);
2807 MscorlibBinder::GetClass(CLASS__IENUMERABLE);
2808 MscorlibBinder::GetClass(CLASS__ICOLLECTION);
2809 MscorlibBinder::GetClass(CLASS__ILIST);
2810 MscorlibBinder::GetClass(CLASS__IDISPOSABLE);
2813 WinRTInterfaceRedirector::VerifyRedirectedInterfaceStubs();
2817 #ifdef FEATURE_ICASTABLE
2818 g_pICastableInterface = MscorlibBinder::GetClass(CLASS__ICASTABLE);
2819 #endif // FEATURE_ICASTABLE
2821 // Load a special marker method used to detect Constrained Execution Regions
2823 g_pExecuteBackoutCodeHelperMethod = MscorlibBinder::GetMethod(METHOD__RUNTIME_HELPERS__EXECUTE_BACKOUT_CODE_HELPER);
2825 // Make sure that FCall mapping for Monitor.Enter is initialized. We need it in case Monitor.Enter is used only as JIT helper.
2826 // For more details, see comment in code:JITutil_MonEnterWorker around "__me = GetEEFuncEntryPointMacro(JIT_MonEnter)".
2827 ECall::GetFCallImpl(MscorlibBinder::GetMethod(METHOD__MONITOR__ENTER));
2829 #ifdef PROFILING_SUPPORTED
2830 // Note that g_profControlBlock.fBaseSystemClassesLoaded must be set to TRUE only after
2831 // all base system classes are loaded. Profilers are not allowed to call any type-loading
2832 // APIs until g_profControlBlock.fBaseSystemClassesLoaded is TRUE. It is important that
2833 // all base system classes need to be loaded before profilers can trigger the type loading.
2834 g_profControlBlock.fBaseSystemClassesLoaded = TRUE;
2835 #endif // PROFILING_SUPPORTED
2837 #if defined(_DEBUG) && !defined(CROSSGEN_COMPILE)
2838 if (!NingenEnabled())
2844 #if defined(HAVE_GCCOVER) && defined(FEATURE_PREJIT)
2845 if (GCStress<cfg_instr_ngen>::IsEnabled())
2847 // Setting up gc coverage requires the base system classes
2848 // to be initialized. So we have deferred it until now for mscorlib.
2849 Module *pModule = MscorlibBinder::GetModule();
2850 _ASSERTE(pModule->IsSystem());
2851 if(pModule->HasNativeImage())
2853 SetupGcCoverageForNativeImage(pModule);
2856 #endif // defined(HAVE_GCCOVER) && !defined(FEATURE_PREJIT)
2860 void SystemDomain::LoadDomain(AppDomain *pDomain)
2867 PRECONDITION(CheckPointer(System()));
2868 INJECT_FAULT(COMPlusThrowOM(););
2872 pDomain->SetCanUnload(); // by default can unload any domain
2873 SystemDomain::System()->AddDomain(pDomain);
2876 ADIndex SystemDomain::GetNewAppDomainIndex(AppDomain *pAppDomain)
2878 STANDARD_VM_CONTRACT;
2880 DWORD count = m_appDomainIndexList.GetCount();
2886 // So that we can keep AD index inside object header.
2887 // We do not want to create syncblock unless needed.
2894 // Look for an unused index. Note that in a checked build,
2895 // we never reuse indexes - this makes it easier to tell
2896 // when we are looking at a stale app domain.
2899 i = m_appDomainIndexList.FindElement(m_dwLowestFreeIndex, NULL);
2900 if (i == (DWORD) ArrayList::NOT_FOUND)
2902 m_dwLowestFreeIndex = i+1;
2904 if (m_dwLowestFreeIndex >= 2000)
2906 m_dwLowestFreeIndex = 0;
2912 IfFailThrow(m_appDomainIndexList.Append(pAppDomain));
2914 m_appDomainIndexList.Set(i, pAppDomain);
2916 _ASSERTE(i < m_appDomainIndexList.GetCount());
2918 // Note that index 0 means domain agile.
2919 return ADIndex(i+1);
2922 void SystemDomain::ReleaseAppDomainIndex(ADIndex index)
2924 WRAPPER_NO_CONTRACT;
2925 SystemDomain::LockHolder lh;
2926 // Note that index 0 means domain agile.
2929 _ASSERTE(m_appDomainIndexList.Get(index.m_dwIndex) != NULL);
2931 m_appDomainIndexList.Set(index.m_dwIndex, NULL);
2934 if (index.m_dwIndex < m_dwLowestFreeIndex)
2935 m_dwLowestFreeIndex = index.m_dwIndex;
2939 #endif // !DACCESS_COMPILE
2941 PTR_AppDomain SystemDomain::GetAppDomainAtIndex(ADIndex index)
2943 LIMITED_METHOD_CONTRACT;
2945 _ASSERTE(index.m_dwIndex != 0);
2947 PTR_AppDomain pAppDomain = TestGetAppDomainAtIndex(index);
2949 _ASSERTE(pAppDomain || !"Attempt to access unloaded app domain");
2954 PTR_AppDomain SystemDomain::TestGetAppDomainAtIndex(ADIndex index)
2956 LIMITED_METHOD_CONTRACT;
2958 _ASSERTE(index.m_dwIndex != 0);
2961 #ifndef DACCESS_COMPILE
2962 _ASSERTE(index.m_dwIndex < (DWORD)m_appDomainIndexList.GetCount());
2963 AppDomain *pAppDomain = (AppDomain*) m_appDomainIndexList.Get(index.m_dwIndex);
2964 #else // DACCESS_COMPILE
2965 PTR_ArrayListStatic pList = &m_appDomainIndexList;
2966 AppDomain *pAppDomain = dac_cast<PTR_AppDomain>(pList->Get(index.m_dwIndex));
2967 #endif // DACCESS_COMPILE
2968 return PTR_AppDomain(pAppDomain);
2971 #ifndef DACCESS_COMPILE
2973 // See also code:SystemDomain::ReleaseAppDomainId
2974 ADID SystemDomain::GetNewAppDomainId(AppDomain *pAppDomain)
2981 INJECT_FAULT(COMPlusThrowOM(););
2985 DWORD i = m_appDomainIdList.GetCount();
2987 IfFailThrow(m_appDomainIdList.Append(pAppDomain));
2989 _ASSERTE(i < m_appDomainIdList.GetCount());
2994 AppDomain *SystemDomain::GetAppDomainAtId(ADID index)
2999 if (!SystemDomain::IsUnderDomainLock() && !IsGCThread()) { MODE_COOPERATIVE;} else { DISABLED(MODE_ANY);}
3007 if(index.m_dwId == 0)
3009 DWORD requestedID = index.m_dwId - 1;
3011 if(requestedID >= (DWORD)m_appDomainIdList.GetCount())
3014 AppDomain * result = (AppDomain *)m_appDomainIdList.Get(requestedID);
3016 #ifndef CROSSGEN_COMPILE
3017 if(result==NULL && GetThread() == FinalizerThread::GetFinalizerThread() &&
3018 SystemDomain::System()->AppDomainBeingUnloaded()!=NULL &&
3019 SystemDomain::System()->AppDomainBeingUnloaded()->GetId()==index)
3020 result=SystemDomain::System()->AppDomainBeingUnloaded();
3021 // If the current thread can't enter the AppDomain, then don't return it.
3022 if (!result || !result->CanThreadEnter(GetThread()))
3024 #endif // CROSSGEN_COMPILE
3029 // Releases an appdomain index. Note that today we have code that depends on these
3030 // indexes not being recycled, so we don't actually shrink m_appDomainIdList, but
3031 // simply zero out an entry. THus we 'leak' the memory associated the slot in
3032 // m_appDomainIdList.
3034 // TODO make this a sparse structure so that we avoid that leak.
3036 void SystemDomain::ReleaseAppDomainId(ADID index)
3038 LIMITED_METHOD_CONTRACT;
3041 _ASSERTE(index.m_dwId < (DWORD)m_appDomainIdList.GetCount());
3043 m_appDomainIdList.Set(index.m_dwId, NULL);
3046 #if defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
3049 int g_fMainThreadApartmentStateSet = 0;
3052 Thread::ApartmentState SystemDomain::GetEntryPointThreadAptState(IMDInternalImport* pScope, mdMethodDef mdMethod)
3054 STANDARD_VM_CONTRACT;
3057 IfFailThrow(hr = pScope->GetCustomAttributeByName(mdMethod,
3058 DEFAULTDOMAIN_MTA_TYPE,
3061 BOOL fIsMTA = FALSE;
3065 IfFailThrow(hr = pScope->GetCustomAttributeByName(mdMethod,
3066 DEFAULTDOMAIN_STA_TYPE,
3069 BOOL fIsSTA = FALSE;
3073 if (fIsSTA && fIsMTA)
3074 COMPlusThrowHR(COR_E_CUSTOMATTRIBUTEFORMAT);
3077 return Thread::AS_InSTA;
3079 return Thread::AS_InMTA;
3081 return Thread::AS_Unknown;
3084 void SystemDomain::SetThreadAptState (IMDInternalImport* pScope, Thread::ApartmentState state)
3086 STANDARD_VM_CONTRACT;
3088 BOOL fIsLegacy = FALSE;
3090 // Check for legacy behavior regarding COM Apartment state of the main thread.
3092 #define METAMODEL_MAJOR_VER_WITH_NEW_BEHAVIOR 2
3093 #define METAMODEL_MINOR_VER_WITH_NEW_BEHAVIOR 0
3096 IfFailThrow(pScope->GetVersionString(&pVer));
3098 // Does this look like a version?
3101 // Is it 'vN.' where N is a digit?
3102 if ((pVer[0] == 'v' || pVer[0] == 'V') &&
3103 IS_DIGIT(pVer[1]) &&
3106 // Looks like a version. Is it lesser than v2.0 major version where we start using new behavior?
3107 fIsLegacy = DIGIT_TO_INT(pVer[1]) < METAMODEL_MAJOR_VER_WITH_NEW_BEHAVIOR;
3111 if (!fIsLegacy && g_pConfig != NULL)
3113 fIsLegacy = g_pConfig->LegacyApartmentInitPolicy();
3117 Thread* pThread = GetThread();
3120 if(state == Thread::AS_InSTA)
3122 Thread::ApartmentState pState = pThread->SetApartment(Thread::AS_InSTA, TRUE);
3123 _ASSERTE(pState == Thread::AS_InSTA);
3125 else if ((state == Thread::AS_InMTA) || (!fIsLegacy))
3127 // If either MTAThreadAttribute is specified or (if no attribute is specified and we are not
3128 // running in legacy mode), then
3129 // we will set the apartment state to MTA. The reason for this is to ensure the apartment
3130 // state is consistent and reliably set. Without this, the apartment state for the main
3131 // thread would be undefined and would actually be dependent on if the assembly was
3132 // ngen'd, which other type were loaded, etc.
3133 Thread::ApartmentState pState = pThread->SetApartment(Thread::AS_InMTA, TRUE);
3134 _ASSERTE(pState == Thread::AS_InMTA);
3138 g_fMainThreadApartmentStateSet++;
3141 #endif // defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
3143 // Looks in all the modules for the DefaultDomain attribute
3144 // The order is assembly and then the modules. It is first
3145 // come, first serve.
3146 BOOL SystemDomain::SetGlobalSharePolicyUsingAttribute(IMDInternalImport* pScope, mdMethodDef mdMethod)
3148 STANDARD_VM_CONTRACT;
3154 void SystemDomain::SetupDefaultDomain()
3161 INJECT_FAULT(COMPlusThrowOM(););
3166 Thread *pThread = GetThread();
3170 pDomain = pThread->GetDomain();
3175 ENTER_DOMAIN_PTR(SystemDomain::System()->DefaultDomain(),ADV_DEFAULTAD)
3177 // Push this frame around loading the main assembly to ensure the
3178 // debugger can properly recgonize any managed code that gets run
3179 // as "class initializaion" code.
3180 FrameWithCookie<DebuggerClassInitMarkFrame> __dcimf;
3184 InitializeDefaultDomain(TRUE);
3189 END_DOMAIN_TRANSITION;
3194 HRESULT SystemDomain::SetupDefaultDomainNoThrow()
3207 SystemDomain::SetupDefaultDomain();
3209 EX_CATCH_HRESULT(hr);
3215 int g_fInitializingInitialAD = 0;
3218 // This routine completes the initialization of the default domaine.
3219 // After this call mananged code can be executed.
3220 void SystemDomain::InitializeDefaultDomain(
3221 BOOL allowRedirects,
3222 ICLRPrivBinder * pBinder)
3224 STANDARD_VM_CONTRACT;
3226 WCHAR* pwsConfig = NULL;
3227 WCHAR* pwsPath = NULL;
3229 ETWOnStartup (InitDefaultDomain_V1, InitDefaultDomainEnd_V1);
3232 // Setup the default AppDomain.
3235 g_fInitializingInitialAD++;
3238 AppDomain* pDefaultDomain = SystemDomain::System()->DefaultDomain();
3240 if (pBinder != nullptr)
3242 pDefaultDomain->SetLoadContextHostBinder(pBinder);
3248 pDefaultDomain->InitializeDomainContext(allowRedirects, pwsPath, pwsConfig);
3250 #ifndef CROSSGEN_COMPILE
3251 if (!NingenEnabled())
3254 if (!IsSingleAppDomain())
3256 pDefaultDomain->InitializeDefaultDomainManager();
3259 #endif // CROSSGEN_COMPILE
3262 // DefaultDomain Load event
3263 ETW::LoaderLog::DomainLoad(pDefaultDomain);
3266 g_fInitializingInitialAD--;
3269 TESTHOOKCALL(RuntimeStarted(RTS_DEFAULTADREADY));
3274 #ifndef CROSSGEN_COMPILE
3277 Volatile<LONG> g_fInExecuteMainMethod = 0;
3283 #endif // CROSSGEN_COMPILE
3287 // Helper function to load an assembly. This is called from LoadCOMClass.
3290 Assembly *AppDomain::LoadAssemblyHelper(LPCWSTR wszAssembly,
3291 LPCWSTR wszCodeBase)
3293 CONTRACT(Assembly *)
3296 POSTCONDITION(CheckPointer(RETVAL));
3297 PRECONDITION(wszAssembly || wszCodeBase);
3298 INJECT_FAULT(COMPlusThrowOM(););
3304 #define MAKE_TRANSLATIONFAILED { ThrowOutOfMemory(); }
3305 MAKE_UTF8PTR_FROMWIDE(szAssembly,wszAssembly);
3306 #undef MAKE_TRANSLATIONFAILED
3308 IfFailThrow(spec.Init(szAssembly));
3312 spec.SetCodeBase(wszCodeBase);
3314 RETURN spec.LoadAssembly(FILE_LOADED);
3317 #if defined(FEATURE_CLASSIC_COMINTEROP) && !defined(CROSSGEN_COMPILE)
3319 MethodTable *AppDomain::LoadCOMClass(GUID clsid,
3320 BOOL bLoadRecord/*=FALSE*/,
3321 BOOL* pfAssemblyInReg/*=NULL*/)
3323 // @CORESYSTODO: what to do here?
3327 #endif // FEATURE_CLASSIC_COMINTEROP && !CROSSGEN_COMPILE
3331 bool SystemDomain::IsReflectionInvocationMethod(MethodDesc* pMeth)
3341 MethodTable* pCaller = pMeth->GetMethodTable();
3343 // All Reflection Invocation methods are defined in mscorlib.dll
3344 if (!pCaller->GetModule()->IsSystem())
3347 /* List of types that should be skipped to identify true caller */
3348 static const BinderClassID reflectionInvocationTypes[] = {
3353 CLASS__CONSTRUCTOR_INFO,
3356 CLASS__METHOD_HANDLE,
3357 CLASS__FIELD_HANDLE,
3360 CLASS__RT_FIELD_INFO,
3365 CLASS__PROPERTY_INFO,
3368 CLASS__ASSEMBLYBASE,
3370 CLASS__TYPE_DELEGATOR,
3371 CLASS__RUNTIME_HELPERS,
3372 CLASS__LAZY_INITIALIZER,
3373 CLASS__DYNAMICMETHOD,
3375 CLASS__MULTICAST_DELEGATE,
3379 static const BinderClassID genericReflectionInvocationTypes[] = {
3383 static mdTypeDef genericReflectionInvocationTypeDefs[NumItems(genericReflectionInvocationTypes)];
3385 static bool fInited = false;
3387 if (!VolatileLoad(&fInited))
3389 // Make sure all types are loaded so that we can use faster GetExistingClass()
3390 for (unsigned i = 0; i < NumItems(reflectionInvocationTypes); i++)
3392 MscorlibBinder::GetClass(reflectionInvocationTypes[i]);
3395 // Make sure all types are loaded so that we can use faster GetExistingClass()
3396 for (unsigned i = 0; i < NumItems(genericReflectionInvocationTypes); i++)
3398 genericReflectionInvocationTypeDefs[i] = MscorlibBinder::GetClass(genericReflectionInvocationTypes[i])->GetCl();
3401 MscorlibBinder::GetClass(CLASS__APP_DOMAIN);
3403 VolatileStore(&fInited, true);
3406 if (pCaller->HasInstantiation())
3408 // For generic types, pCaller will be an instantiated type and never equal to the type definition.
3409 // So we compare their TypeDef tokens instead.
3410 for (unsigned i = 0; i < NumItems(genericReflectionInvocationTypeDefs); i++)
3412 if (pCaller->GetCl() == genericReflectionInvocationTypeDefs[i])
3418 for (unsigned i = 0; i < NumItems(reflectionInvocationTypes); i++)
3420 if (MscorlibBinder::GetExistingClass(reflectionInvocationTypes[i]) == pCaller)
3428 #ifndef CROSSGEN_COMPILE
3429 struct CallersDataWithStackMark
3431 StackCrawlMark* stackMark;
3433 MethodDesc* pFoundMethod;
3434 MethodDesc* pPrevMethod;
3435 AppDomain* pAppDomain;
3439 MethodDesc* SystemDomain::GetCallersMethod(StackCrawlMark* stackMark,
3440 AppDomain **ppAppDomain/*=NULL*/)
3448 INJECT_FAULT(COMPlusThrowOM(););
3454 CallersDataWithStackMark cdata;
3455 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3456 cdata.stackMark = stackMark;
3458 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3460 if(cdata.pFoundMethod) {
3462 *ppAppDomain = cdata.pAppDomain;
3463 return cdata.pFoundMethod;
3469 MethodTable* SystemDomain::GetCallersType(StackCrawlMark* stackMark,
3470 AppDomain **ppAppDomain/*=NULL*/)
3478 INJECT_FAULT(COMPlusThrowOM(););
3482 CallersDataWithStackMark cdata;
3483 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3484 cdata.stackMark = stackMark;
3486 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3488 if(cdata.pFoundMethod) {
3490 *ppAppDomain = cdata.pAppDomain;
3491 return cdata.pFoundMethod->GetMethodTable();
3497 Module* SystemDomain::GetCallersModule(StackCrawlMark* stackMark,
3498 AppDomain **ppAppDomain/*=NULL*/)
3506 INJECT_FAULT(COMPlusThrowOM(););
3512 CallersDataWithStackMark cdata;
3513 ZeroMemory(&cdata, sizeof(CallersDataWithStackMark));
3514 cdata.stackMark = stackMark;
3516 GetThread()->StackWalkFrames(CallersMethodCallbackWithStackMark, &cdata, FUNCTIONSONLY | LIGHTUNWIND);
3518 if(cdata.pFoundMethod) {
3520 *ppAppDomain = cdata.pAppDomain;
3521 return cdata.pFoundMethod->GetModule();
3529 MethodDesc* pMethod;
3533 Assembly* SystemDomain::GetCallersAssembly(StackCrawlMark *stackMark,
3534 AppDomain **ppAppDomain/*=NULL*/)
3536 WRAPPER_NO_CONTRACT;
3537 Module* mod = GetCallersModule(stackMark, ppAppDomain);
3539 return mod->GetAssembly();
3544 Module* SystemDomain::GetCallersModule(int skip)
3551 INJECT_FAULT(COMPlusThrowOM(););
3558 ZeroMemory(&cdata, sizeof(CallersData));
3561 StackWalkFunctions(GetThread(), CallersMethodCallback, &cdata);
3564 return cdata.pMethod->GetModule();
3570 StackWalkAction SystemDomain::CallersMethodCallbackWithStackMark(CrawlFrame* pCf, VOID* data)
3578 INJECT_FAULT(COMPlusThrowOM(););
3583 MethodDesc *pFunc = pCf->GetFunction();
3585 /* We asked to be called back only for functions */
3588 CallersDataWithStackMark* pCaller = (CallersDataWithStackMark*) data;
3589 if (pCaller->stackMark)
3591 if (!pCf->IsInCalleesFrames(pCaller->stackMark))
3593 // save the current in case it is the one we want
3594 pCaller->pPrevMethod = pFunc;
3595 pCaller->pAppDomain = pCf->GetAppDomain();
3596 return SWA_CONTINUE;
3599 // LookForMe stack crawl marks needn't worry about reflection or
3600 // remoting frames on the stack. Each frame above (newer than) the
3601 // target will be captured by the logic above. Once we transition to
3602 // finding the stack mark below the AofRA, we know that we hit the
3603 // target last time round and immediately exit with the cached result.
3605 if (*(pCaller->stackMark) == LookForMe)
3607 pCaller->pFoundMethod = pCaller->pPrevMethod;
3612 // Skip reflection and remoting frames that could lie between a stack marked
3613 // method and its true caller (or that caller and its own caller). These
3614 // frames are infrastructure and logically transparent to the stack crawling
3617 // Skipping remoting frames. We always skip entire client to server spans
3618 // (though we see them in the order server then client during a stack crawl
3621 // We spot the server dispatcher end because all calls are dispatched
3622 // through a single method: StackBuilderSink._PrivateProcessMessage.
3624 Frame* frame = pCf->GetFrame();
3625 _ASSERTE(pCf->IsFrameless() || frame);
3629 // Skipping reflection frames. We don't need to be quite as exhaustive here
3630 // as the security or reflection stack walking code since we know this logic
3631 // is only invoked for selected methods in mscorlib itself. So we're
3632 // reasonably sure we won't have any sensitive methods late bound invoked on
3633 // constructors, properties or events. This leaves being invoked via
3634 // MethodInfo, Type or Delegate (and depending on which invoke overload is
3635 // being used, several different reflection classes may be involved).
3637 g_IBCLogger.LogMethodDescAccess(pFunc);
3639 if (SystemDomain::IsReflectionInvocationMethod(pFunc))
3640 return SWA_CONTINUE;
3642 if (frame && frame->GetFrameType() == Frame::TYPE_MULTICAST)
3644 // This must be either a secure delegate frame or a true multicast delegate invocation.
3646 _ASSERTE(pFunc->GetMethodTable()->IsDelegate());
3648 DELEGATEREF del = (DELEGATEREF)((SecureDelegateFrame*)frame)->GetThis(); // This can throw.
3650 if (COMDelegate::IsSecureDelegate(del))
3652 if (del->IsWrapperDelegate())
3654 // On ARM, we use secure delegate infrastructure to preserve R4 register.
3655 return SWA_CONTINUE;
3657 // For a secure delegate frame, we should return the delegate creator instead
3658 // of the delegate method itself.
3659 pFunc = (MethodDesc*) del->GetMethodPtrAux();
3663 _ASSERTE(COMDelegate::IsTrueMulticastDelegate(del));
3664 return SWA_CONTINUE;
3668 // Return the first non-reflection/remoting frame if no stack mark was
3670 if (!pCaller->stackMark)
3672 pCaller->pFoundMethod = pFunc;
3673 pCaller->pAppDomain = pCf->GetAppDomain();
3677 // If we got here, we must already be in the frame containing the stack mark and we are not looking for "me".
3678 _ASSERTE(pCaller->stackMark &&
3679 pCf->IsInCalleesFrames(pCaller->stackMark) &&
3680 *(pCaller->stackMark) != LookForMe);
3682 // When looking for caller's caller, we delay returning results for another
3683 // round (the way this is structured, we will still be able to skip
3684 // reflection and remoting frames between the caller and the caller's
3687 if ((*(pCaller->stackMark) == LookForMyCallersCaller) &&
3688 (pCaller->pFoundMethod == NULL))
3690 pCaller->pFoundMethod = pFunc;
3691 return SWA_CONTINUE;
3694 // If remoting is not available, we only set the caller if the crawlframe is from the same domain.
3695 // Why? Because if the callerdomain is different from current domain,
3696 // there have to be interop/native frames in between.
3697 // For example, in the CORECLR, if we find the caller to be in a different domain, then the
3698 // call into reflection is due to an unmanaged call into mscorlib. For that
3699 // case, the caller really is an INTEROP method.
3700 // In general, if the caller is INTEROP, we set the caller/callerdomain to be NULL
3701 // (To be precise: they are already NULL and we don't change them).
3702 if (pCf->GetAppDomain() == GetAppDomain())
3703 // We must either be looking for the caller, or the caller's caller when
3704 // we've already found the caller (we used a non-null value in pFoundMethod
3705 // simply as a flag, the correct method to return in both case is the
3708 pCaller->pFoundMethod = pFunc;
3709 pCaller->pAppDomain = pCf->GetAppDomain();
3716 StackWalkAction SystemDomain::CallersMethodCallback(CrawlFrame* pCf, VOID* data)
3718 LIMITED_METHOD_CONTRACT;
3719 STATIC_CONTRACT_SO_TOLERANT;
3720 MethodDesc *pFunc = pCf->GetFunction();
3722 /* We asked to be called back only for functions */
3725 CallersData* pCaller = (CallersData*) data;
3726 if(pCaller->skip == 0) {
3727 pCaller->pMethod = pFunc;
3732 return SWA_CONTINUE;
3736 #endif // CROSSGEN_COMPILE
3738 #ifdef CROSSGEN_COMPILE
3739 // defined in compile.cpp
3740 extern CompilationDomain * theDomain;
3743 void SystemDomain::CreateDefaultDomain()
3745 STANDARD_VM_CONTRACT;
3747 #ifdef CROSSGEN_COMPILE
3748 AppDomainRefHolder pDomain(theDomain);
3750 AppDomainRefHolder pDomain(new AppDomain());
3753 SystemDomain::LockHolder lh;
3756 // need to make this assignment here since we'll be releasing
3757 // the lock before calling AddDomain. So any other thread
3758 // grabbing this lock after we release it will find that
3759 // the COM Domain has already been created
3760 m_pDefaultDomain = pDomain;
3761 _ASSERTE (pDomain->GetId().m_dwId == DefaultADID);
3763 // allocate a Virtual Call Stub Manager for the default domain
3764 m_pDefaultDomain->InitVSD();
3766 pDomain->SetStage(AppDomain::STAGE_OPEN);
3767 pDomain.SuppressRelease();
3769 LOG((LF_CLASSLOADER | LF_CORDB,
3771 "Created default domain at %p\n", m_pDefaultDomain));
3774 #ifdef DEBUGGING_SUPPORTED
3776 void SystemDomain::PublishAppDomainAndInformDebugger (AppDomain *pDomain)
3780 if(!g_fEEInit) {THROWS;} else {DISABLED(NOTHROW);};
3781 if(!g_fEEInit) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);};
3786 LOG((LF_CORDB, LL_INFO100, "SD::PADAID: Adding 0x%x\n", pDomain));
3788 // Call the publisher API to add this appdomain entry to the list
3789 // The publisher will handle failures, so we don't care if this succeeds or fails.
3790 if (g_pDebugInterface != NULL)
3792 g_pDebugInterface->AddAppDomainToIPC(pDomain);
3796 #endif // DEBUGGING_SUPPORTED
3798 void SystemDomain::AddDomain(AppDomain* pDomain)
3805 PRECONDITION(CheckPointer((pDomain)));
3812 _ASSERTE (pDomain->m_Stage != AppDomain::STAGE_CREATING);
3813 if (pDomain->m_Stage == AppDomain::STAGE_READYFORMANAGEDCODE ||
3814 pDomain->m_Stage == AppDomain::STAGE_ACTIVE)
3816 pDomain->SetStage(AppDomain::STAGE_OPEN);
3817 IncrementNumAppDomains(); // Maintain a count of app domains added to the list.
3821 // Note that if you add another path that can reach here without calling
3822 // PublishAppDomainAndInformDebugger, then you should go back & make sure
3823 // that PADAID gets called. Right after this call, if not sooner.
3824 LOG((LF_CORDB, LL_INFO1000, "SD::AD:Would have added domain here! 0x%x\n",
3828 BOOL SystemDomain::RemoveDomain(AppDomain* pDomain)
3835 PRECONDITION(CheckPointer(pDomain));
3836 PRECONDITION(!pDomain->IsDefaultDomain());
3840 // You can not remove the default domain.
3843 if (!pDomain->IsActive())
3852 #ifdef PROFILING_SUPPORTED
3853 void SystemDomain::NotifyProfilerStartup()
3864 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3866 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) System());
3871 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3873 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) System(), S_OK);
3878 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3879 _ASSERTE(System()->DefaultDomain());
3880 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) System()->DefaultDomain());
3885 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3886 _ASSERTE(System()->DefaultDomain());
3887 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) System()->DefaultDomain(), S_OK);
3892 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3893 _ASSERTE(SharedDomain::GetDomain());
3894 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) SharedDomain::GetDomain());
3899 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3900 _ASSERTE(SharedDomain::GetDomain());
3901 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID) SharedDomain::GetDomain(), S_OK);
3906 HRESULT SystemDomain::NotifyProfilerShutdown()
3917 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3919 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) System());
3924 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3926 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) System(), S_OK);
3931 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3932 _ASSERTE(System()->DefaultDomain());
3933 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) System()->DefaultDomain());
3938 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
3939 _ASSERTE(System()->DefaultDomain());
3940 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) System()->DefaultDomain(), S_OK);
3945 #endif // PROFILING_SUPPORTED
3949 struct AppDomain::ThreadTrackInfo {
3951 CDynArray<Frame *> frameStack;
3955 AppDomain::AppDomain()
3957 // initialize fields so the appdomain can be safely destructed
3958 // shouldn't call anything that can fail here - use ::Init instead
3969 m_pNextInDelayedUnloadList = NULL;
3970 m_fRudeUnload = FALSE;
3971 m_pUnloadRequestThread = NULL;
3972 m_ADUnloadSink=NULL;
3975 // Initialize Shared state. Assemblies are loaded
3976 // into each domain by default.
3977 #ifdef FEATURE_LOADER_OPTIMIZATION
3978 m_SharePolicy = SHARE_POLICY_UNSPECIFIED;
3981 m_pRootAssembly = NULL;
3983 m_pwDynamicDir = NULL;
3986 m_pDefaultContext = NULL;
3987 #ifdef FEATURE_COMINTEROP
3988 m_pComCallWrapperCache = NULL;
3990 m_pRCWRefCache = NULL;
3991 m_pLicenseInteropHelperMT = NULL;
3992 m_COMorRemotingFlag = COMorRemoting_NotInitialized;
3993 memset(m_rpCLRTypes, 0, sizeof(m_rpCLRTypes));
3994 #endif // FEATURE_COMINTEROP
3996 m_pUMEntryThunkCache = NULL;
3998 m_pAsyncPool = NULL;
3999 m_handleStore = NULL;
4001 m_ExposedObject = NULL;
4002 m_pComIPForExposedObject = NULL;
4005 m_pThreadTrackInfoList = NULL;
4006 m_TrackSpinLock = 0;
4007 m_Assemblies.Debug_SetAppDomain(this);
4010 m_dwThreadEnterCount = 0;
4011 m_dwThreadsStillInAppDomain = (ULONG)-1;
4013 #ifdef FEATURE_COMINTEROP
4014 m_pRefDispIDCache = NULL;
4015 m_hndMissing = NULL;
4018 m_pRefClassFactHash = NULL;
4019 m_anonymouslyHostedDynamicMethodsAssembly = NULL;
4021 m_ReversePInvokeCanEnter=TRUE;
4022 m_ForceTrivialWaitOperations = false;
4023 m_Stage=STAGE_CREATING;
4025 m_bForceGCOnUnload=FALSE;
4026 m_bUnloadingFromUnloadEvent=FALSE;
4030 m_dwCreationHolders=0;
4033 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4034 m_ullTotalProcessorUsage = 0;
4035 m_pullAllocBytes = NULL;
4036 m_pullSurvivedBytes = NULL;
4037 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4039 #ifdef FEATURE_TYPEEQUIVALENCE
4040 m_pTypeEquivalenceTable = NULL;
4041 #endif // FEATURE_TYPEEQUIVALENCE
4043 #ifdef FEATURE_COMINTEROP
4044 m_pNameToTypeMap = NULL;
4045 m_vNameToTypeMapVersion = 0;
4047 m_pWinRTFactoryCache = NULL;
4048 #endif // FEATURE_COMINTEROP
4050 #ifdef FEATURE_PREJIT
4051 m_pDomainFileWithNativeImageList = NULL;
4054 m_fIsBindingModelLocked.Store(FALSE);
4056 } // AppDomain::AppDomain
4058 AppDomain::~AppDomain()
4068 #ifndef CROSSGEN_COMPILE
4070 _ASSERTE(m_dwCreationHolders == 0);
4072 // release the TPIndex. note that since TPIndex values are recycled the TPIndex
4073 // can only be released once all threads in the AppDomain have exited.
4074 if (GetTPIndex().m_dwIndex != 0)
4075 PerAppDomainTPCountList::ResetAppDomainIndex(GetTPIndex());
4077 if (m_dwId.m_dwId!=0)
4078 SystemDomain::ReleaseAppDomainId(m_dwId);
4080 m_AssemblyCache.Clear();
4083 m_ADUnloadSink->Release();
4091 #ifdef FEATURE_COMINTEROP
4092 if (m_pNameToTypeMap != nullptr)
4094 delete m_pNameToTypeMap;
4095 m_pNameToTypeMap = nullptr;
4097 if (m_pWinRTFactoryCache != nullptr)
4099 delete m_pWinRTFactoryCache;
4100 m_pWinRTFactoryCache = nullptr;
4102 #endif //FEATURE_COMINTEROP
4105 // If we were tracking thread AD transitions, cleanup the list on shutdown
4106 if (m_pThreadTrackInfoList)
4108 while (m_pThreadTrackInfoList->Count() > 0)
4110 // Get the very last element
4111 ThreadTrackInfo *pElem = *(m_pThreadTrackInfoList->Get(m_pThreadTrackInfoList->Count() - 1));
4117 // Remove pointer entry from the list
4118 m_pThreadTrackInfoList->Delete(m_pThreadTrackInfoList->Count() - 1);
4121 // Now delete the list itself
4122 delete m_pThreadTrackInfoList;
4123 m_pThreadTrackInfoList = NULL;
4127 #endif // CROSSGEN_COMPILE
4130 //*****************************************************************************
4131 //*****************************************************************************
4132 //*****************************************************************************
4133 void AppDomain::Init()
4138 PRECONDITION(SystemDomain::IsUnderDomainLock());
4142 m_pDelayedLoaderAllocatorUnloadList = NULL;
4144 SetStage( STAGE_CREATING);
4147 // The lock is taken also during stack walking (GC or profiler)
4148 // - To prevent deadlock with GC thread, we cannot trigger GC while holding the lock
4149 // - To prevent deadlock with profiler thread, we cannot allow thread suspension
4150 m_crstHostAssemblyMap.Init(
4151 CrstHostAssemblyMap,
4152 (CrstFlags)(CRST_GC_NOTRIGGER_WHEN_TAKEN
4153 | CRST_DEBUGGER_THREAD
4154 INDEBUG(| CRST_DEBUG_ONLY_CHECK_FORBID_SUSPEND_THREAD)));
4155 m_crstHostAssemblyMapAdd.Init(CrstHostAssemblyMapAdd);
4157 m_dwId = SystemDomain::GetNewAppDomainId(this);
4159 m_LoaderAllocator.Init(this);
4161 #ifndef CROSSGEN_COMPILE
4162 //Allocate the threadpool entry before the appdomin id list. Otherwise,
4163 //the thread pool list will be out of sync if insertion of id in
4164 //the appdomain fails.
4165 m_tpIndex = PerAppDomainTPCountList::AddNewTPIndex();
4166 #endif // CROSSGEN_COMPILE
4168 m_dwIndex = SystemDomain::GetNewAppDomainIndex(this);
4170 #ifndef CROSSGEN_COMPILE
4171 PerAppDomainTPCountList::SetAppDomainId(m_tpIndex, m_dwId);
4173 m_ADUnloadSink=new ADUnloadSink();
4178 // Set up the IL stub cache
4179 m_ILStubCache.Init(GetLoaderAllocator()->GetHighFrequencyHeap());
4181 // Set up the binding caches
4182 m_AssemblyCache.Init(&m_DomainCacheCrst, GetHighFrequencyHeap());
4183 m_UnmanagedCache.InitializeTable(this, &m_DomainCacheCrst);
4185 m_MemoryPressure = 0;
4187 m_sDomainLocalBlock.Init(this);
4189 #ifndef CROSSGEN_COMPILE
4191 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4192 // NOTE: it's important that we initialize ARM data structures before calling
4193 // Ref_CreateHandleTableBucket, this is because AD::Init() can race with GC
4194 // and once we add ourselves to the handle table map the GC can start walking
4195 // our handles and calling AD::RecordSurvivedBytes() which touches ARM data.
4196 if (GCHeapUtilities::IsServerHeap())
4197 m_dwNumHeaps = CPUGroupInfo::CanEnableGCCPUGroups() ?
4198 CPUGroupInfo::GetNumActiveProcessors() :
4199 GetCurrentProcessCpuCount();
4202 m_pullAllocBytes = new ULONGLONG [m_dwNumHeaps * ARM_CACHE_LINE_SIZE_ULL];
4203 m_pullSurvivedBytes = new ULONGLONG [m_dwNumHeaps * ARM_CACHE_LINE_SIZE_ULL];
4204 for (DWORD i = 0; i < m_dwNumHeaps; i++)
4206 m_pullAllocBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
4207 m_pullSurvivedBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
4209 m_ullLastEtwAllocBytes = 0;
4210 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4212 // Default domain reuses the handletablemap that was created during EEStartup since
4213 // default domain cannot be unloaded.
4214 if (GetId().m_dwId == DefaultADID)
4216 m_handleStore = GCHandleUtilities::GetGCHandleManager()->GetGlobalHandleStore();
4220 m_handleStore = GCHandleUtilities::GetGCHandleManager()->CreateHandleStore((void*)(uintptr_t)m_dwIndex.m_dwIndex);
4228 #endif // CROSSGEN_COMPILE
4230 #ifdef FEATURE_TYPEEQUIVALENCE
4231 m_TypeEquivalenceCrst.Init(CrstTypeEquivalenceMap);
4234 m_ReflectionCrst.Init(CrstReflection, CRST_UNSAFE_ANYMODE);
4235 m_RefClassFactCrst.Init(CrstClassFactInfoHash);
4238 LockOwner lock = {&m_DomainCrst, IsOwnerOfCrst};
4239 m_clsidHash.Init(0,&CompareCLSID,true, &lock); // init hash table
4242 SetStage(STAGE_READYFORMANAGEDCODE);
4244 #ifndef CROSSGEN_COMPILE
4245 m_pDefaultContext = new Context(this);
4247 m_ExposedObject = CreateHandle(NULL);
4249 // Create the Application Security Descriptor
4251 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomains++);
4253 #ifdef FEATURE_COMINTEROP
4254 if (!AppX::IsAppXProcess())
4257 #endif //FEATURE_COMINTEROP
4259 #ifdef FEATURE_TIERED_COMPILATION
4260 m_tieredCompilationManager.Init(GetId());
4262 #endif // CROSSGEN_COMPILE
4263 } // AppDomain::Init
4266 /*********************************************************************/
4268 BOOL AppDomain::IsCompilationDomain()
4270 LIMITED_METHOD_CONTRACT;
4272 BOOL isCompilationDomain = (m_dwFlags & COMPILATION_DOMAIN) != 0;
4273 #ifdef FEATURE_PREJIT
4274 _ASSERTE(!isCompilationDomain ||
4275 (IsCompilationProcess() && IsPassiveDomain()));
4276 #endif // FEATURE_PREJIT
4277 return isCompilationDomain;
4280 #ifndef CROSSGEN_COMPILE
4282 extern int g_fADUnloadWorkerOK;
4285 // This helper will send the AppDomain creation notifications for profiler / debugger.
4286 // If it throws, its backout code will also send a notification.
4287 // If it succeeds, then we still need to send a AppDomainCreateFinished notification.
4288 void AppDomain::CreateUnmanagedObject(AppDomainCreationHolder<AppDomain>& pDomain)
4295 INJECT_FAULT(COMPlusThrowOM(););
4301 pDomain.Assign(new AppDomain());
4302 if (g_fADUnloadWorkerOK<0)
4304 AppDomain::CreateADUnloadWorker();
4308 // We addref Appdomain object here and notify a profiler that appdomain
4309 // creation has started, then return to managed code which will call
4310 // the function that releases the appdomain and notifies a profiler that we finished
4311 // creating the appdomain. If an exception is raised while we're in that managed code
4312 // we will leak memory and the profiler will not be notified about the failure
4314 #ifdef PROFILING_SUPPORTED
4315 // Signal profile if present.
4317 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
4318 g_profControlBlock.pProfInterface->AppDomainCreationStarted((AppDomainID) (AppDomain*) pDomain);
4322 #endif // PROFILING_SUPPORTED
4325 SystemDomain::LockHolder lh;
4327 // allocate a Virtual Call Stub Manager for this domain
4331 pDomain->SetCanUnload(); // by default can unload any domain
4333 #ifdef DEBUGGING_SUPPORTED
4334 // Notify the debugger here, before the thread transitions into the
4335 // AD to finish the setup, and before any assemblies are loaded into it.
4336 SystemDomain::PublishAppDomainAndInformDebugger(pDomain);
4337 #endif // DEBUGGING_SUPPORTED
4339 STRESS_LOG2 (LF_APPDOMAIN, LL_INFO100, "Create domain [%d] %p\n", pDomain->GetId().m_dwId, (AppDomain*)pDomain);
4340 pDomain->LoadSystemAssemblies();
4341 pDomain->SetupSharedStatics();
4343 pDomain->SetStage(AppDomain::STAGE_ACTIVE);
4345 #ifdef PROFILING_SUPPORTED
4348 // Need the first assembly loaded in to get any data on an app domain.
4350 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
4351 g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID)(AppDomain*) pDomain, GET_EXCEPTION()->GetHR());
4357 // On success, caller must still send the AppDomainCreationFinished notification.
4358 #endif // PROFILING_SUPPORTED
4361 void AppDomain::Stop()
4371 #ifdef FEATURE_MULTICOREJIT
4372 GetMulticoreJitManager().StopProfile(true);
4375 // Set the unloaded flag before notifying the debugger
4376 GetLoaderAllocator()->SetIsUnloaded();
4378 #ifdef DEBUGGING_SUPPORTED
4379 if (IsDebuggerAttached())
4380 NotifyDebuggerUnload();
4381 #endif // DEBUGGING_SUPPORTED
4383 m_pRootAssembly = NULL; // This assembly is in the assembly list;
4385 #ifdef DEBUGGING_SUPPORTED
4386 if (NULL != g_pDebugInterface)
4388 // Call the publisher API to delete this appdomain entry from the list
4389 CONTRACT_VIOLATION(ThrowsViolation);
4390 g_pDebugInterface->RemoveAppDomainFromIPC (this);
4392 #endif // DEBUGGING_SUPPORTED
4395 void AppDomain::Terminate()
4408 _ASSERTE(m_dwThreadEnterCount == 0 || IsDefaultDomain());
4410 if (m_pComIPForExposedObject)
4412 m_pComIPForExposedObject->Release();
4413 m_pComIPForExposedObject = NULL;
4416 delete m_pDefaultContext;
4417 m_pDefaultContext = NULL;
4419 if (m_pUMEntryThunkCache)
4421 delete m_pUMEntryThunkCache;
4422 m_pUMEntryThunkCache = NULL;
4425 #ifdef FEATURE_COMINTEROP
4434 delete m_pRCWRefCache;
4435 m_pRCWRefCache = NULL;
4438 if (m_pComCallWrapperCache)
4440 m_pComCallWrapperCache->Neuter();
4441 m_pComCallWrapperCache->Release();
4444 // if the above released the wrapper cache, then it will call back and reset our
4445 // m_pComCallWrapperCache to null. If not null, then need to set it's domain pointer to
4447 if (! m_pComCallWrapperCache)
4449 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::Terminate ComCallWrapperCache released\n"));
4454 m_pComCallWrapperCache = NULL;
4455 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::Terminate ComCallWrapperCache not released\n"));
4459 #endif // FEATURE_COMINTEROP
4462 if (!IsAtProcessExit())
4464 // if we're not shutting down everything then clean up the string literals associated
4465 // with this appdomain -- note that is no longer needs to happen while suspended
4466 // because the appropriate locks are taken in the GlobalStringLiteralMap
4467 // this is important as this locks have a higher lock number than does the
4468 // thread-store lock which is taken when we suspend.
4469 GetLoaderAllocator()->CleanupStringLiteralMap();
4471 // Suspend the EE to do some clean up that can only occur
4472 // while no threads are running.
4473 GCX_COOP (); // SuspendEE may require current thread to be in Coop mode
4474 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
4477 // Note that this must be performed before restarting the EE. It will clean
4478 // the cache and prevent others from using stale cache entries.
4479 //@TODO: Would be nice to get this back to BaseDomain, but need larger fix for that.
4480 // NOTE: Must have the runtime suspended to unlink managers
4481 // NOTE: May be NULL due to OOM during initialization. Can skip in that case.
4482 GetLoaderAllocator()->UninitVirtualCallStubManager();
4483 MethodTable::ClearMethodDataCache();
4484 ClearJitGenericHandleCache(this);
4486 // @TODO s_TPMethodTableCrst prevents us from from keeping the whole
4487 // assembly shutdown logic here. See if we can do better in the next milestone
4488 #ifdef FEATURE_PREJIT
4489 DeleteNativeCodeRanges();
4492 if (!IsAtProcessExit())
4495 ThreadSuspend::RestartEE(FALSE, TRUE);
4498 ShutdownAssemblies();
4499 ShutdownNativeDllSearchDirectories();
4501 if (m_pRefClassFactHash)
4503 m_pRefClassFactHash->Destroy();
4504 // storage for m_pRefClassFactHash itself is allocated on the loader heap
4507 #ifdef FEATURE_TYPEEQUIVALENCE
4508 m_TypeEquivalenceCrst.Destroy();
4511 m_ReflectionCrst.Destroy();
4512 m_RefClassFactCrst.Destroy();
4514 m_LoaderAllocator.Terminate();
4516 BaseDomain::Terminate();
4520 GCHandleUtilities::GetGCHandleManager()->DestroyHandleStore(m_handleStore);
4521 m_handleStore = NULL;
4524 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
4525 if (m_pullAllocBytes)
4527 delete [] m_pullAllocBytes;
4529 if (m_pullSurvivedBytes)
4531 delete [] m_pullSurvivedBytes;
4533 #endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
4535 if(m_dwIndex.m_dwIndex != 0)
4536 SystemDomain::ReleaseAppDomainIndex(m_dwIndex);
4537 } // AppDomain::Terminate
4539 void AppDomain::CloseDomain()
4550 BOOL bADRemoved=FALSE;;
4552 AddRef(); // Hold a reference
4553 AppDomainRefHolder AdHolder(this);
4555 SystemDomain::LockHolder lh;
4557 SystemDomain::System()->DecrementNumAppDomains(); // Maintain a count of app domains added to the list.
4558 bADRemoved = SystemDomain::System()->RemoveDomain(this);
4565 /*********************************************************************/
4567 struct GetExposedObject_Args
4573 static void GetExposedObject_Wrapper(LPVOID ptr)
4582 GetExposedObject_Args *args = (GetExposedObject_Args *) ptr;
4583 *(args->ref) = args->pDomain->GetExposedObject();
4587 OBJECTREF AppDomain::GetExposedObject()
4594 INJECT_FAULT(COMPlusThrowOM(););
4598 OBJECTREF ref = GetRawExposedObject();
4601 APPDOMAINREF obj = NULL;
4603 Thread *pThread = GetThread();
4604 if (pThread->GetDomain() != this)
4606 GCPROTECT_BEGIN(ref);
4607 GetExposedObject_Args args = {this, &ref};
4608 // call through DoCallBack with a domain transition
4609 pThread->DoADCallBack(this,GetExposedObject_Wrapper, &args,ADV_CREATING|ADV_RUNNINGIN);
4613 MethodTable *pMT = MscorlibBinder::GetClass(CLASS__APP_DOMAIN);
4615 // Create the module object
4616 obj = (APPDOMAINREF) AllocateObject(pMT);
4617 obj->SetDomain(this);
4619 if (!StoreFirstObjectInHandle(m_ExposedObject, (OBJECTREF) obj))
4621 obj = (APPDOMAINREF) GetRawExposedObject();
4625 return (OBJECTREF) obj;
4633 OBJECTREF AppDomain::DoSetup(OBJECTREF* setupInfo)
4640 INJECT_FAULT(COMPlusThrowOM(););
4644 ADID adid=GetAppDomain()->GetId();
4646 OBJECTREF retval=NULL;
4647 GCPROTECT_BEGIN(retval);
4649 ENTER_DOMAIN_PTR(this,ADV_CREATING);
4651 MethodDescCallSite setup(METHOD__APP_DOMAIN__SETUP);
4655 args[0]=ObjToArgSlot(*setupInfo);
4657 OBJECTREF activator;
4658 activator=setup.Call_RetOBJECTREF(args);
4659 _ASSERTE(activator==NULL);
4661 #if defined(FEATURE_MULTICOREJIT)
4662 // Disable AutoStartProfile in default domain from this code path.
4663 // It's called from SystemDomain::ExecuteMainMethod for normal program, not needed for SL and Asp.Net
4664 if (! IsDefaultDomain())
4668 GetMulticoreJitManager().AutoStartProfile(this);
4672 END_DOMAIN_TRANSITION;
4677 #endif // !CROSSGEN_COMPILE
4679 #ifdef FEATURE_COMINTEROP
4680 #ifndef CROSSGEN_COMPILE
4681 HRESULT AppDomain::GetComIPForExposedObject(IUnknown **pComIP)
4683 // Assumption: This function is called for AppDomain's that the current
4684 // thread is in or has entered, or the AppDomain is kept alive.
4686 // Assumption: This function can now throw. The caller is responsible for any
4687 // BEGIN_EXTERNAL_ENTRYPOINT, EX_TRY, or other
4688 // techniques to convert to a COM HRESULT protocol.
4698 Thread *pThread = GetThread();
4699 if (m_pComIPForExposedObject)
4701 GCX_PREEMP_THREAD_EXISTS(pThread);
4702 m_pComIPForExposedObject->AddRef();
4703 *pComIP = m_pComIPForExposedObject;
4707 IUnknown* punk = NULL;
4709 OBJECTREF ref = NULL;
4710 GCPROTECT_BEGIN(ref);
4714 ENTER_DOMAIN_PTR(this,ADV_DEFAULTAD)
4716 ref = GetExposedObject();
4717 punk = GetComIPFromObjectRef(&ref);
4718 if (FastInterlockCompareExchangePointer(&m_pComIPForExposedObject, punk, NULL) == NULL)
4720 GCX_PREEMP_THREAD_EXISTS(pThread);
4721 m_pComIPForExposedObject->AddRef();
4724 END_DOMAIN_TRANSITION;
4730 *pComIP = m_pComIPForExposedObject;
4735 #endif //#ifndef CROSSGEN_COMPILE
4737 MethodTable *AppDomain::GetRedirectedType(WinMDAdapter::RedirectedTypeIndex index)
4747 // If we have the type loaded already, use that
4748 if (m_rpCLRTypes[index] != nullptr)
4750 return m_rpCLRTypes[index];
4753 WinMDAdapter::FrameworkAssemblyIndex frameworkAssemblyIndex;
4754 WinMDAdapter::GetRedirectedTypeInfo(index, nullptr, nullptr, nullptr, &frameworkAssemblyIndex, nullptr, nullptr);
4755 MethodTable * pMT = LoadRedirectedType(index, frameworkAssemblyIndex);
4756 m_rpCLRTypes[index] = pMT;
4760 MethodTable* AppDomain::LoadRedirectedType(WinMDAdapter::RedirectedTypeIndex index, WinMDAdapter::FrameworkAssemblyIndex assembly)
4767 PRECONDITION(index < WinMDAdapter::RedirectedTypeIndex_Count);
4771 LPCSTR szClrNamespace;
4773 LPCSTR szFullWinRTName;
4774 WinMDAdapter::FrameworkAssemblyIndex nFrameworkAssemblyIndex;
4776 WinMDAdapter::GetRedirectedTypeInfo(index, &szClrNamespace, &szClrName, &szFullWinRTName, &nFrameworkAssemblyIndex, nullptr, nullptr);
4778 _ASSERTE(nFrameworkAssemblyIndex >= WinMDAdapter::FrameworkAssembly_Mscorlib &&
4779 nFrameworkAssemblyIndex < WinMDAdapter::FrameworkAssembly_Count);
4781 if (assembly != nFrameworkAssemblyIndex)
4783 // The framework type does not live in the assembly we were requested to load redirected types from
4786 else if (nFrameworkAssemblyIndex == WinMDAdapter::FrameworkAssembly_Mscorlib)
4788 return ClassLoader::LoadTypeByNameThrowing(MscorlibBinder::GetModule()->GetAssembly(),
4791 ClassLoader::ThrowIfNotFound,
4792 ClassLoader::LoadTypes,
4793 CLASS_LOAD_EXACTPARENTS).GetMethodTable();
4798 AssemblyMetaDataInternal context;
4799 const BYTE * pbKeyToken;
4800 DWORD cbKeyTokenLength;
4803 WinMDAdapter::GetExtraAssemblyRefProps(nFrameworkAssemblyIndex,
4810 Assembly* pAssembly = AssemblySpec::LoadAssembly(pSimpleName,
4816 return ClassLoader::LoadTypeByNameThrowing(
4820 ClassLoader::ThrowIfNotFound,
4821 ClassLoader::LoadTypes,
4822 CLASS_LOAD_EXACTPARENTS).GetMethodTable();
4825 #endif //FEATURE_COMINTEROP
4827 #endif //!DACCESS_COMPILE
4829 #ifndef DACCESS_COMPILE
4831 bool IsPlatformAssembly(LPCSTR szName, DomainAssembly *pDomainAssembly)
4838 PRECONDITION(CheckPointer(szName));
4839 PRECONDITION(CheckPointer(pDomainAssembly));
4843 PEAssembly *pPEAssembly = pDomainAssembly->GetFile();
4845 if (strcmp(szName, pPEAssembly->GetSimpleName()) != 0)
4851 const BYTE *pbPublicKey = static_cast<const BYTE *>(pPEAssembly->GetPublicKey(&cbPublicKey));
4852 if (pbPublicKey == nullptr)
4857 return StrongNameIsSilverlightPlatformKey(pbPublicKey, cbPublicKey);
4860 void AppDomain::AddAssembly(DomainAssembly * assem)
4867 INJECT_FAULT(COMPlusThrowOM(););
4872 CrstHolder ch(GetAssemblyListLock());
4874 // Attempt to find empty space in assemblies list
4875 DWORD asmCount = m_Assemblies.GetCount_Unlocked();
4876 for (DWORD i = 0; i < asmCount; ++i)
4878 if (m_Assemblies.Get_UnlockedNoReference(i) == NULL)
4880 m_Assemblies.Set_Unlocked(i, assem);
4885 // If empty space not found, simply add to end of list
4886 IfFailThrow(m_Assemblies.Append_Unlocked(assem));
4890 void AppDomain::RemoveAssembly_Unlocked(DomainAssembly * pAsm)
4899 _ASSERTE(GetAssemblyListLock()->OwnedByCurrentThread());
4901 DWORD asmCount = m_Assemblies.GetCount_Unlocked();
4902 for (DWORD i = 0; i < asmCount; ++i)
4904 if (m_Assemblies.Get_UnlockedNoReference(i) == pAsm)
4906 m_Assemblies.Set_Unlocked(i, NULL);
4911 _ASSERTE(!"Unreachable");
4914 BOOL AppDomain::ContainsAssembly(Assembly * assem)
4916 WRAPPER_NO_CONTRACT;
4917 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
4919 (assem->IsIntrospectionOnly() ? kIncludeIntrospection : kIncludeExecution)));
4920 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
4922 while (i.Next(pDomainAssembly.This()))
4924 CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
4925 if (pAssembly == assem)
4932 EEClassFactoryInfoHashTable* AppDomain::SetupClassFactHash()
4939 INJECT_FAULT(COMPlusThrowOM(););
4943 CrstHolder ch(&m_ReflectionCrst);
4945 if (m_pRefClassFactHash == NULL)
4947 AllocMemHolder<void> pCache(GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof (EEClassFactoryInfoHashTable))));
4948 EEClassFactoryInfoHashTable *tmp = new (pCache) EEClassFactoryInfoHashTable;
4949 LockOwner lock = {&m_RefClassFactCrst,IsOwnerOfCrst};
4950 if (!tmp->Init(20, &lock))
4952 pCache.SuppressRelease();
4953 m_pRefClassFactHash = tmp;
4956 return m_pRefClassFactHash;
4959 #ifdef FEATURE_COMINTEROP
4960 DispIDCache* AppDomain::SetupRefDispIDCache()
4967 INJECT_FAULT(COMPlusThrowOM(););
4971 CrstHolder ch(&m_ReflectionCrst);
4973 if (m_pRefDispIDCache == NULL)
4975 AllocMemHolder<void> pCache = GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof (DispIDCache)));
4977 DispIDCache *tmp = new (pCache) DispIDCache;
4980 pCache.SuppressRelease();
4981 m_pRefDispIDCache = tmp;
4984 return m_pRefDispIDCache;
4987 #endif // FEATURE_COMINTEROP
4989 FileLoadLock *FileLoadLock::Create(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile)
4996 PRECONDITION(pLock->HasLock());
4997 PRECONDITION(pLock->FindFileLock(pFile) == NULL);
4998 INJECT_FAULT(COMPlusThrowOM(););
5002 NewHolder<FileLoadLock> result(new FileLoadLock(pLock, pFile, pDomainFile));
5004 pLock->AddElement(result);
5005 result->AddRef(); // Add one ref on behalf of the ListLock's reference. The corresponding Release() happens in FileLoadLock::CompleteLoadLevel.
5006 return result.Extract();
5009 FileLoadLock::~FileLoadLock()
5019 ((PEFile *) m_data)->Release();
5022 DomainFile *FileLoadLock::GetDomainFile()
5024 LIMITED_METHOD_CONTRACT;
5025 return m_pDomainFile;
5028 FileLoadLevel FileLoadLock::GetLoadLevel()
5030 LIMITED_METHOD_CONTRACT;
5034 ADID FileLoadLock::GetAppDomainId()
5036 LIMITED_METHOD_CONTRACT;
5037 return m_AppDomainId;
5040 // Acquire will return FALSE and not take the lock if the file
5041 // has already been loaded to the target level. Otherwise,
5042 // it will return TRUE and take the lock.
5044 // Note that the taker must release the lock via IncrementLoadLevel.
5046 BOOL FileLoadLock::Acquire(FileLoadLevel targetLevel)
5048 WRAPPER_NO_CONTRACT;
5050 // If we are already loaded to the desired level, the lock is "free".
5051 if (m_level >= targetLevel)
5054 if (!DeadlockAwareEnter())
5056 // We failed to get the lock due to a deadlock.
5060 if (m_level >= targetLevel)
5069 BOOL FileLoadLock::CanAcquire(FileLoadLevel targetLevel)
5071 // If we are already loaded to the desired level, the lock is "free".
5072 if (m_level >= targetLevel)
5075 return CanDeadlockAwareEnter();
5078 #if !defined(DACCESS_COMPILE) && (defined(LOGGING) || defined(STRESS_LOG))
5079 static const char *fileLoadLevelName[] =
5081 "CREATE", // FILE_LOAD_CREATE
5082 "BEGIN", // FILE_LOAD_BEGIN
5083 "FIND_NATIVE_IMAGE", // FILE_LOAD_FIND_NATIVE_IMAGE
5084 "VERIFY_NATIVE_IMAGE_DEPENDENCIES", // FILE_LOAD_VERIFY_NATIVE_IMAGE_DEPENDENCIES
5085 "ALLOCATE", // FILE_LOAD_ALLOCATE
5086 "ADD_DEPENDENCIES", // FILE_LOAD_ADD_DEPENDENCIES
5087 "PRE_LOADLIBRARY", // FILE_LOAD_PRE_LOADLIBRARY
5088 "LOADLIBRARY", // FILE_LOAD_LOADLIBRARY
5089 "POST_LOADLIBRARY", // FILE_LOAD_POST_LOADLIBRARY
5090 "EAGER_FIXUPS", // FILE_LOAD_EAGER_FIXUPS
5091 "VTABLE FIXUPS", // FILE_LOAD_VTABLE_FIXUPS
5092 "DELIVER_EVENTS", // FILE_LOAD_DELIVER_EVENTS
5093 "LOADED", // FILE_LOADED
5094 "VERIFY_EXECUTION", // FILE_LOAD_VERIFY_EXECUTION
5095 "ACTIVE", // FILE_ACTIVE
5097 #endif // !DACCESS_COMPILE && (LOGGING || STRESS_LOG)
5099 BOOL FileLoadLock::CompleteLoadLevel(FileLoadLevel level, BOOL success)
5106 PRECONDITION(HasLock());
5110 // Increment may happen more than once if reentrancy occurs (e.g. LoadLibrary)
5111 if (level > m_level)
5113 // Must complete each level in turn, unless we have an error
5114 CONSISTENCY_CHECK(m_pDomainFile->IsError() || (level == (m_level+1)));
5115 // Remove the lock from the list if the load is completed
5116 if (level >= FILE_ACTIVE)
5120 PEFileListLockHolder lock((PEFileListLock*)m_pList);
5123 BOOL fDbgOnly_SuccessfulUnlink =
5125 m_pList->Unlink(this);
5126 _ASSERTE(fDbgOnly_SuccessfulUnlink);
5128 m_pDomainFile->ClearLoading();
5130 CONSISTENCY_CHECK(m_dwRefCount >= 2); // Caller (LoadDomainFile) should have 1 refcount and m_pList should have another which was acquired in FileLoadLock::Create.
5132 m_level = (FileLoadLevel)level;
5135 // In AppDomain::IsLoading, if the lock is taken on m_pList and then FindFileLock returns NULL,
5136 // we depend on the DomainFile's load level being up to date. Hence we must update the load
5137 // level while the m_pList lock is held.
5139 m_pDomainFile->SetLoadLevel(level);
5143 Release(); // Release m_pList's refcount on this lock, which was acquired in FileLoadLock::Create
5148 m_level = (FileLoadLevel)level;
5151 m_pDomainFile->SetLoadLevel(level);
5154 #ifndef DACCESS_COMPILE
5157 case FILE_LOAD_ALLOCATE:
5158 case FILE_LOAD_ADD_DEPENDENCIES:
5159 case FILE_LOAD_DELIVER_EVENTS:
5161 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.
5162 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);
5175 void FileLoadLock::SetError(Exception *ex)
5182 PRECONDITION(CheckPointer(ex));
5183 PRECONDITION(HasLock());
5184 INJECT_FAULT(COMPlusThrowOM(););
5188 m_cachedHR = ex->GetHR();
5190 LOG((LF_LOADER, LL_WARNING, "LOADER: %x:***%s*\t!!!Non-transient error 0x%x\n",
5191 m_pDomainFile->GetAppDomain(), m_pDomainFile->GetSimpleName(), m_cachedHR));
5193 m_pDomainFile->SetError(ex);
5195 CompleteLoadLevel(FILE_ACTIVE, FALSE);
5198 void FileLoadLock::AddRef()
5200 LIMITED_METHOD_CONTRACT;
5201 FastInterlockIncrement((LONG *) &m_dwRefCount);
5204 UINT32 FileLoadLock::Release()
5214 LONG count = FastInterlockDecrement((LONG *) &m_dwRefCount);
5221 FileLoadLock::FileLoadLock(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile)
5222 : ListLockEntry(pLock, pFile, "File load lock"),
5223 m_level((FileLoadLevel) (FILE_LOAD_CREATE)),
5224 m_pDomainFile(pDomainFile),
5226 m_AppDomainId(pDomainFile->GetAppDomain()->GetId())
5228 WRAPPER_NO_CONTRACT;
5232 void FileLoadLock::HolderLeave(FileLoadLock *pThis)
5234 LIMITED_METHOD_CONTRACT;
5244 // Assembly loading:
5246 // Assembly loading is carefully layered to avoid deadlocks in the
5247 // presence of circular loading dependencies.
5248 // A LoadLevel is associated with each assembly as it is being loaded. During the
5249 // act of loading (abstractly, increasing its load level), its lock is
5250 // held, and the current load level is stored on the thread. Any
5251 // recursive loads during that period are automatically restricted to
5252 // only partially load the dependent assembly to the same level as the
5253 // caller (or to one short of that level in the presence of a deadlock
5256 // Each loading stage must be carfully constructed so that
5257 // this constraint is expected and can be dealt with.
5259 // Note that there is one case where this still doesn't handle recursion, and that is the
5260 // security subsytem. The security system runs managed code, and thus must typically fully
5261 // initialize assemblies of permission sets it is trying to use. (And of course, these may be used
5262 // while those assemblies are initializing.) This is dealt with in the historical manner - namely
5263 // the security system passes in a special flag which says that it will deal with null return values
5264 // in the case where a load cannot be safely completed due to such issues.
5267 void AppDomain::LoadSystemAssemblies()
5269 STANDARD_VM_CONTRACT;
5271 // The only reason to make an assembly a "system assembly" is if the EE is caching
5272 // pointers to stuff in the assembly. Because this is going on, we need to preserve
5273 // the invariant that the assembly is loaded into every app domain.
5275 // Right now we have only one system assembly. We shouldn't need to add any more.
5277 LoadAssembly(NULL, SystemDomain::System()->SystemFile(), FILE_ACTIVE);
5280 FileLoadLevel AppDomain::GetDomainFileLoadLevel(DomainFile *pFile)
5290 LoadLockHolder lock(this);
5292 FileLoadLock* pLockEntry = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5294 if (pLockEntry == NULL)
5295 return pFile->GetLoadLevel();
5297 return pLockEntry->GetLoadLevel();
5300 // This checks if the thread has initiated (or completed) loading at the given level. A false guarantees that
5301 // (a) The current thread (or a thread blocking on the current thread) has not started loading the file
5302 // at the given level, and
5303 // (b) No other thread had started loading the file at this level at the start of this function call.
5305 // Note that another thread may start loading the file at that level in a race with the completion of
5306 // this function. However, the caller still has the guarantee that such a load started after this
5307 // function was called (and e.g. any state in place before the function call will be seen by the other thread.)
5309 // Conversely, a true guarantees that either the current thread has started the load step, or another
5310 // thread has completed the load step.
5313 BOOL AppDomain::IsLoading(DomainFile *pFile, FileLoadLevel level)
5316 if (pFile->GetLoadLevel() < level)
5318 FileLoadLock *pLock = NULL;
5320 LoadLockHolder lock(this);
5322 pLock = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5326 // No thread involved with loading
5327 return pFile->GetLoadLevel() >= level;
5333 FileLoadLockRefHolder lockRef(pLock);
5335 if (pLock->Acquire(level))
5337 // We got the lock - therefore no other thread has started this loading step yet.
5342 // We didn't get the lock - either this thread is already doing the load,
5343 // or else the load has already finished.
5348 // CheckLoading is a weaker form of IsLoading, which will not block on
5349 // other threads waiting for their status. This is appropriate for asserts.
5350 CHECK AppDomain::CheckLoading(DomainFile *pFile, FileLoadLevel level)
5353 if (pFile->GetLoadLevel() < level)
5355 FileLoadLock *pLock = NULL;
5357 LoadLockHolder lock(this);
5359 pLock = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5362 && pLock->CanAcquire(level))
5364 // We can get the lock - therefore no other thread has started this loading step yet.
5365 CHECK_FAILF(("Loading step %d has not been initiated yet", level));
5368 // We didn't get the lock - either this thread is already doing the load,
5369 // or else the load has already finished.
5375 CHECK AppDomain::CheckCanLoadTypes(Assembly *pAssembly)
5384 CHECK_MSG(CheckValidModule(pAssembly->GetManifestModule()),
5385 "Type loading can occur only when executing in the assembly's app domain");
5389 CHECK AppDomain::CheckCanExecuteManagedCode(MethodDesc* pMD)
5399 Module* pModule=pMD->GetModule();
5401 CHECK_MSG(CheckValidModule(pModule),
5402 "Managed code can only run when executing in the module's app domain");
5404 if (!pMD->IsInterface() || pMD->IsStatic()) //interfaces require no activation for instance methods
5406 //cctor could have been interupted by ADU
5407 CHECK_MSG(HasUnloadStarted() || pModule->CheckActivated(),
5408 "Managed code can only run when its module has been activated in the current app domain");
5411 CHECK_MSG(!IsPassiveDomain() || pModule->CanExecuteCode(),
5412 "Executing managed code from an unsafe assembly in a Passive AppDomain");
5417 #endif // !DACCESS_COMPILE
5419 void AppDomain::LoadDomainFile(DomainFile *pFile,
5420 FileLoadLevel targetLevel)
5424 if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
5425 if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
5426 if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM();); }
5427 INJECT_FAULT(COMPlusThrowOM(););
5431 // Quick exit if finished
5432 if (pFile->GetLoadLevel() >= targetLevel)
5435 // Handle the error case
5436 pFile->ThrowIfError(targetLevel);
5439 #ifndef DACCESS_COMPILE
5441 if (pFile->IsLoading())
5445 // Load some more if appropriate
5446 LoadLockHolder lock(this);
5448 FileLoadLock* pLockEntry = (FileLoadLock *) lock->FindFileLock(pFile->GetFile());
5449 if (pLockEntry == NULL)
5451 _ASSERTE (!pFile->IsLoading());
5455 pLockEntry->AddRef();
5459 LoadDomainFile(pLockEntry, targetLevel);
5462 #else // DACCESS_COMPILE
5464 #endif // DACCESS_COMPILE
5467 #ifndef DACCESS_COMPILE
5469 FileLoadLevel AppDomain::GetThreadFileLoadLevel()
5471 WRAPPER_NO_CONTRACT;
5472 if (GetThread()->GetLoadLevelLimiter() == NULL)
5475 return (FileLoadLevel)(GetThread()->GetLoadLevelLimiter()->GetLoadLevel()-1);
5479 Assembly *AppDomain::LoadAssembly(AssemblySpec* pIdentity,
5481 FileLoadLevel targetLevel)
5483 CONTRACT(Assembly *)
5488 PRECONDITION(CheckPointer(pFile));
5489 POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); // May be NULL in recursive load case
5490 INJECT_FAULT(COMPlusThrowOM(););
5494 DomainAssembly *pAssembly = LoadDomainAssembly(pIdentity, pFile, targetLevel);
5495 PREFIX_ASSUME(pAssembly != NULL);
5497 RETURN pAssembly->GetAssembly();
5500 #ifndef CROSSGEN_COMPILE
5502 class LoadDomainAssemblyStress : APIThreadStress
5506 AssemblySpec* pSpec;
5508 FileLoadLevel targetLevel;
5510 LoadDomainAssemblyStress(AppDomain *pThis, AssemblySpec* pSpec, PEAssembly *pFile, FileLoadLevel targetLevel)
5511 : pThis(pThis), pSpec(pSpec), pFile(pFile), targetLevel(targetLevel) {LIMITED_METHOD_CONTRACT;}
5515 WRAPPER_NO_CONTRACT;
5516 STATIC_CONTRACT_SO_INTOLERANT;
5518 pThis->LoadDomainAssembly(pSpec, pFile, targetLevel);
5521 #endif // CROSSGEN_COMPILE
5523 extern BOOL AreSameBinderInstance(ICLRPrivBinder *pBinderA, ICLRPrivBinder *pBinderB);
5525 DomainAssembly* AppDomain::LoadDomainAssembly( AssemblySpec* pSpec,
5527 FileLoadLevel targetLevel)
5529 STATIC_CONTRACT_THROWS;
5531 if (pSpec == nullptr)
5533 // skip caching, since we don't have anything to base it on
5534 return LoadDomainAssemblyInternal(pSpec, pFile, targetLevel);
5537 DomainAssembly* pRetVal = NULL;
5540 pRetVal = LoadDomainAssemblyInternal(pSpec, pFile, targetLevel);
5544 Exception* pEx=GET_EXCEPTION();
5545 if (!pEx->IsTransient())
5547 // Setup the binder reference in AssemblySpec from the PEAssembly if one is not already set.
5548 ICLRPrivBinder* pCurrentBindingContext = pSpec->GetBindingContext();
5549 ICLRPrivBinder* pBindingContextFromPEAssembly = pFile->GetBindingContext();
5551 if (pCurrentBindingContext == NULL)
5553 // Set the binding context we got from the PEAssembly if AssemblySpec does not
5554 // have that information
5555 _ASSERTE(pBindingContextFromPEAssembly != NULL);
5556 pSpec->SetBindingContext(pBindingContextFromPEAssembly);
5561 // Binding context in the spec should be the same as the binding context in the PEAssembly
5562 _ASSERTE(AreSameBinderInstance(pCurrentBindingContext, pBindingContextFromPEAssembly));
5566 if (!EEFileLoadException::CheckType(pEx))
5569 pSpec->GetFileOrDisplayName(0, name);
5570 pEx=new EEFileLoadException(name, pEx->GetHR(), NULL, pEx);
5571 AddExceptionToCache(pSpec, pEx);
5572 PAL_CPP_THROW(Exception *, pEx);
5575 AddExceptionToCache(pSpec, pEx);
5584 DomainAssembly *AppDomain::LoadDomainAssemblyInternal(AssemblySpec* pIdentity,
5586 FileLoadLevel targetLevel)
5588 CONTRACT(DomainAssembly *)
5593 PRECONDITION(CheckPointer(pFile));
5594 PRECONDITION(pFile->IsSystem() || ::GetAppDomain()==this);
5595 POSTCONDITION(CheckPointer(RETVAL));
5596 POSTCONDITION(RETVAL->GetLoadLevel() >= GetThreadFileLoadLevel()
5597 || RETVAL->GetLoadLevel() >= targetLevel);
5598 POSTCONDITION(RETVAL->CheckNoError(targetLevel));
5599 INJECT_FAULT(COMPlusThrowOM(););
5604 DomainAssembly * result;
5606 #ifndef CROSSGEN_COMPILE
5607 LoadDomainAssemblyStress ts (this, pIdentity, pFile, targetLevel);
5610 // Go into preemptive mode since this may take a while.
5613 // Check for existing fully loaded assembly, or for an assembly which has failed during the loading process.
5614 result = FindAssembly(pFile, FindAssemblyOptions_IncludeFailedToLoad);
5618 // Allocate the DomainAssembly a bit early to avoid GC mode problems. We could potentially avoid
5619 // a rare redundant allocation by moving this closer to FileLoadLock::Create, but it's not worth it.
5621 NewHolder<DomainAssembly> pDomainAssembly;
5622 pDomainAssembly = new DomainAssembly(this, pFile, this->GetLoaderAllocator());
5624 LoadLockHolder lock(this);
5626 // Find the list lock entry
5627 FileLoadLock * fileLock = (FileLoadLock *)lock->FindFileLock(pFile);
5628 if (fileLock == NULL)
5630 // Check again in case we were racing
5631 result = FindAssembly(pFile, FindAssemblyOptions_IncludeFailedToLoad);
5634 // We are the first one in - create the DomainAssembly
5635 fileLock = FileLoadLock::Create(lock, pFile, pDomainAssembly);
5636 pDomainAssembly.SuppressRelease();
5648 // We pass our ref on fileLock to LoadDomainFile to release.
5650 // Note that if we throw here, we will poison fileLock with an error condition,
5651 // so it will not be removed until app domain unload. So there is no need
5652 // to release our ref count.
5653 result = (DomainAssembly *)LoadDomainFile(fileLock, targetLevel);
5657 result->EnsureLoadLevel(targetLevel);
5661 result->EnsureLoadLevel(targetLevel);
5663 // Malformed metadata may contain a Module reference to what is actually
5664 // an Assembly. In this case we need to throw an exception, since returning
5665 // a DomainModule as a DomainAssembly is a type safety violation.
5666 if (!result->IsAssembly())
5668 ThrowHR(COR_E_ASSEMBLYEXPECTED);
5671 // Cache result in all cases, since found pFile could be from a different AssemblyRef than pIdentity
5672 // Do not cache WindowsRuntime assemblies, they are cached in code:CLRPrivTypeCacheWinRT
5673 if ((pIdentity != NULL) && (pIdentity->CanUseWithBindingCache()) && (result->CanUseWithBindingCache()))
5674 GetAppDomain()->AddAssemblyToCache(pIdentity, result);
5677 } // AppDomain::LoadDomainAssembly
5682 FileLoadLock *pLock;
5683 FileLoadLevel targetLevel;
5687 #ifndef CROSSGEN_COMPILE
5688 static void LoadDomainFile_Wrapper(void *ptr)
5690 WRAPPER_NO_CONTRACT;
5691 STATIC_CONTRACT_SO_INTOLERANT;
5693 LoadFileArgs *args = (LoadFileArgs *) ptr;
5694 args->result = GetAppDomain()->LoadDomainFile(args->pLock, args->targetLevel);
5696 #endif // !CROSSGEN_COMPILE
5698 DomainFile *AppDomain::LoadDomainFile(FileLoadLock *pLock, FileLoadLevel targetLevel)
5700 CONTRACT(DomainFile *)
5703 PRECONDITION(CheckPointer(pLock));
5704 PRECONDITION(pLock->GetDomainFile()->GetAppDomain() == this);
5705 POSTCONDITION(RETVAL->GetLoadLevel() >= GetThreadFileLoadLevel()
5706 || RETVAL->GetLoadLevel() >= targetLevel);
5707 POSTCONDITION(RETVAL->CheckNoError(targetLevel));
5713 COMPlusThrow(kAppDomainUnloadedException);
5716 APIThreadStress::SyncThreadStress();
5718 DomainFile *pFile = pLock->GetDomainFile();
5720 // Make sure we release the lock on exit
5721 FileLoadLockRefHolder lockRef(pLock);
5723 // We need to perform the early steps of loading mscorlib without a domain transition. This is
5724 // important for bootstrapping purposes - we need to get mscorlib at least partially loaded
5725 // into a domain before we can run serialization code to do the transition.
5727 // Note that we cannot do this in general for all assemblies, because some of the security computations
5728 // require the managed exposed object, which must be created in the correct app domain.
5730 if (this != GetAppDomain()
5731 && pFile->GetFile()->IsSystem()
5732 && targetLevel > FILE_LOAD_ALLOCATE)
5734 // Re-call the routine with a limited load level. This will cause the first part of the load to
5735 // get performed in the current app domain.
5738 LoadDomainFile(pLock, targetLevel > FILE_LOAD_ALLOCATE ? FILE_LOAD_ALLOCATE : targetLevel);
5740 // Now continue on to complete the rest of the load, if any.
5743 // Do a quick out check for the already loaded case.
5744 if (pLock->GetLoadLevel() >= targetLevel)
5746 pFile->ThrowIfError(targetLevel);
5751 #ifndef CROSSGEN_COMPILE
5752 // Make sure we are in the right domain. Many of the load operations require the target domain
5753 // to be the current app domain, most notably anything involving managed code or managed object
5755 if (this != GetAppDomain()
5756 && (!pFile->GetFile()->IsSystem() || targetLevel > FILE_LOAD_ALLOCATE))
5758 // Transition to the correct app domain and perform the load there.
5761 // we will release the lock in the other app domain
5762 lockRef.SuppressRelease();
5764 if(!CanLoadCode() || GetDefaultContext() ==NULL)
5765 COMPlusThrow(kAppDomainUnloadedException);
5766 LoadFileArgs args = {pLock, targetLevel, NULL};
5767 GetThread()->DoADCallBack(this, LoadDomainFile_Wrapper, (void *) &args, ADV_CREATING);
5771 #endif // CROSSGEN_COMPILE
5773 // Initialize a loading queue. This will hold any loads which are triggered recursively but
5774 // which cannot be immediately satisfied due to anti-deadlock constraints.
5776 // PendingLoadQueues are allocated on the stack during a load, and
5777 // shared with all nested loads on the same thread. (Note that we won't use
5778 // "candidate" if we are in a recursive load; that's OK since they are cheap to
5780 FileLoadLevel immediateTargetLevel = targetLevel;
5782 LoadLevelLimiter limit;
5785 // We cannot set a target level higher than that allowed by the limiter currently.
5786 // This is because of anti-deadlock constraints.
5787 if (immediateTargetLevel > limit.GetLoadLevel())
5788 immediateTargetLevel = limit.GetLoadLevel();
5790 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t>>>Load initiated, %s/%s\n",
5791 pFile->GetAppDomain(), pFile->GetSimpleName(),
5792 fileLoadLevelName[immediateTargetLevel], fileLoadLevelName[targetLevel]));
5794 // Now loop and do the load incrementally to the target level.
5795 if (pLock->GetLoadLevel() < immediateTargetLevel)
5798 APIThreadStress::SyncThreadStress();
5800 while (pLock->Acquire(immediateTargetLevel))
5802 FileLoadLevel workLevel;
5804 FileLoadLockHolder fileLock(pLock);
5806 // Work level is next step to do
5807 workLevel = (FileLoadLevel)(fileLock->GetLoadLevel()+1);
5809 // Set up the anti-deadlock constraint: we cannot safely recursively load any assemblies
5810 // on this thread to a higher level than this assembly is being loaded now.
5811 // Note that we do allow work at a parallel level; any deadlocks caused here will
5812 // be resolved by the deadlock detection in the FileLoadLocks.
5813 limit.SetLoadLevel(workLevel);
5816 (workLevel == FILE_LOAD_BEGIN
5817 || workLevel == FILE_LOADED
5818 || workLevel == FILE_ACTIVE)
5819 ? LL_INFO10 : LL_INFO1000,
5820 "LOADER: %p:***%s*\t loading at level %s\n",
5821 this, pFile->GetSimpleName(), fileLoadLevelName[workLevel]));
5823 TryIncrementalLoad(pFile, workLevel, fileLock);
5825 TESTHOOKCALL(CompletedFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5828 if (pLock->GetLoadLevel() == immediateTargetLevel-1)
5830 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t<<<Load limited due to detected deadlock, %s\n",
5831 pFile->GetAppDomain(), pFile->GetSimpleName(),
5832 fileLoadLevelName[immediateTargetLevel-1]));
5836 LOG((LF_LOADER, LL_INFO100, "LOADER: %x:***%s*\t<<<Load completed, %s\n",
5837 pFile->GetAppDomain(), pFile->GetSimpleName(),
5838 fileLoadLevelName[pLock->GetLoadLevel()]));
5842 // There may have been an error stored on the domain file by another thread, or from a previous load
5843 pFile->ThrowIfError(targetLevel);
5845 // There are two normal results from the above loop.
5847 // 1. We succeeded in loading the file to the current thread's load level.
5848 // 2. We succeeded in loading the file to the current thread's load level - 1, due
5849 // to deadlock condition with another thread loading the same assembly.
5851 // Either of these are considered satisfactory results, as code inside a load must expect
5852 // a parial load result.
5854 // However, if load level elevation has occurred, then it is possible for a deadlock to
5855 // prevent us from loading an assembly which was loading before the elevation at a radically
5856 // lower level. In such a case, we throw an exception which transiently fails the current
5857 // load, since it is likely we have not satisfied the caller.
5858 // (An alternate, and possibly preferable, strategy here would be for all callers to explicitly
5859 // identify the minimum load level acceptable via CheckLoadDomainFile and throw from there.)
5861 pFile->RequireLoadLevel((FileLoadLevel)(immediateTargetLevel-1));
5867 void AppDomain::TryIncrementalLoad(DomainFile *pFile, FileLoadLevel workLevel, FileLoadLockHolder &lockHolder)
5869 STANDARD_VM_CONTRACT;
5871 // This is factored out so we don't call EX_TRY in a loop (EX_TRY can _alloca)
5873 BOOL released = FALSE;
5874 FileLoadLock* pLoadLock = lockHolder.GetValue();
5879 // Special case: for LoadLibrary, we cannot hold the lock during the
5880 // actual LoadLibrary call, because we might get a callback from _CorDllMain on any
5881 // other thread. (Note that this requires DomainFile's LoadLibrary to be independently threadsafe.)
5883 if (workLevel == FILE_LOAD_LOADLIBRARY)
5885 lockHolder.Release();
5890 TESTHOOKCALL(NextFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5891 BOOL success = pFile->DoIncrementalLoad(workLevel);
5892 TESTHOOKCALL(CompletingFileLoadLevel(GetId().m_dwId,pFile,workLevel));
5895 // Reobtain lock to increment level. (Note that another thread may
5896 // have already done it which is OK.
5897 if (pLoadLock->Acquire(workLevel))
5899 // note lockHolder.Acquire isn't wired up to actually take the lock
5900 lockHolder = pLoadLock;
5907 // Complete the level.
5908 if (pLoadLock->CompleteLoadLevel(workLevel, success) &&
5909 pLoadLock->GetLoadLevel()==FILE_LOAD_DELIVER_EVENTS)
5911 lockHolder.Release();
5913 pFile->DeliverAsyncEvents();
5919 Exception *pEx = GET_EXCEPTION();
5922 //We will cache this error and wire this load to forever fail,
5923 // unless the exception is transient or the file is loaded OK but just cannot execute
5924 if (!pEx->IsTransient() && !pFile->IsLoaded())
5929 // Reobtain lock to increment level. (Note that another thread may
5930 // have already done it which is OK.
5931 if (pLoadLock->Acquire(workLevel)) // note pLockHolder->Acquire isn't wired up to actually take the lock
5933 // note lockHolder.Acquire isn't wired up to actually take the lock
5934 lockHolder = pLoadLock;
5941 // Report the error in the lock
5942 pLoadLock->SetError(pEx);
5945 if (!EEFileLoadException::CheckType(pEx))
5946 EEFileLoadException::Throw(pFile->GetFile(), pEx->GetHR(), pEx);
5949 // Otherwise, we simply abort this load, and can retry later on.
5950 // @todo cleanup: make sure that each level is restartable after an exception, and
5951 // leaves no bad side effects
5956 // Checks whether the module is valid to be in the given app domain (need not be yet loaded)
5957 CHECK AppDomain::CheckValidModule(Module * pModule)
5967 if (pModule->FindDomainFile(this) != NULL)
5972 Assembly * pAssembly = pModule->GetAssembly();
5974 CCHECK(pAssembly->IsDomainNeutral());
5975 #ifdef FEATURE_LOADER_OPTIMIZATION
5976 Assembly * pSharedAssembly = NULL;
5977 _ASSERTE(this == ::GetAppDomain());
5979 SharedAssemblyLocator locator(pAssembly->GetManifestFile());
5980 pSharedAssembly = SharedDomain::GetDomain()->FindShareableAssembly(&locator);
5983 CCHECK(pAssembly == pSharedAssembly);
5991 #ifdef FEATURE_LOADER_OPTIMIZATION
5992 // Loads an existing Module into an AppDomain
5993 // WARNING: this can only be done in a very limited scenario - the Module must be an unloaded domain neutral
5994 // dependency in the app domain in question. Normal code should not call this!
5995 DomainFile *AppDomain::LoadDomainNeutralModuleDependency(Module *pModule, FileLoadLevel targetLevel)
5997 CONTRACT(DomainFile *)
6002 PRECONDITION(::GetAppDomain()==this);
6003 PRECONDITION(CheckPointer(pModule));
6004 POSTCONDITION(CheckValidModule(pModule));
6005 POSTCONDITION(CheckPointer(RETVAL));
6006 POSTCONDITION(RETVAL->GetModule() == pModule);
6010 DomainFile *pDomainFile = pModule->FindDomainFile(this);
6012 STRESS_LOG3(LF_CLASSLOADER, LL_INFO100,"LDNMD: DomainFile %p for module %p in AppDomain %i\n",pDomainFile,pModule,GetId().m_dwId);
6014 if (pDomainFile == NULL)
6018 Assembly *pAssembly = pModule->GetAssembly();
6020 DomainAssembly *pDomainAssembly = pAssembly->FindDomainAssembly(this);
6021 if (pDomainAssembly == NULL)
6023 AssemblySpec spec(this);
6024 spec.InitializeSpec(pAssembly->GetManifestFile());
6026 pDomainAssembly = spec.LoadDomainAssembly(targetLevel);
6030 //if the domain assembly already exists, we need to load it to the target level
6031 pDomainAssembly->EnsureLoadLevel (targetLevel);
6034 if(pAssembly != pDomainAssembly->GetAssembly())
6036 ThrowHR(SECURITY_E_INCOMPATIBLE_SHARE);
6039 _ASSERTE (pModule == pAssembly->GetManifestModule());
6040 pDomainFile = pDomainAssembly;
6044 // If the DomainFile already exists, we need to load it to the target level.
6045 pDomainFile->EnsureLoadLevel (targetLevel);
6051 AppDomain::SharePolicy AppDomain::GetSharePolicy()
6053 LIMITED_METHOD_CONTRACT;
6055 return SHARE_POLICY_NEVER;
6057 #endif // FEATURE_LOADER_OPTIMIZATION
6060 void AppDomain::CheckForMismatchedNativeImages(AssemblySpec * pSpec, const GUID * pGuid)
6062 STANDARD_VM_CONTRACT;
6065 // The native images are ever used only for trusted images in CoreCLR.
6066 // We don't wish to open the IL file at runtime so we just forgo any
6067 // eager consistency checking. But we still want to prevent mistmatched
6068 // NGen images from being used. We record all mappings between assembly
6069 // names and MVID, and fail once we detect mismatch.
6072 if (pSpec->IsStrongNamed() && pSpec->HasPublicKey())
6074 pSpec->ConvertPublicKeyToToken();
6078 // CoreCLR binder unifies assembly versions. Ignore assembly version here to
6079 // detect more types of potential mismatches.
6081 AssemblyMetaDataInternal * pContext = pSpec->GetContext();
6082 pContext->usMajorVersion = (USHORT)-1;
6083 pContext->usMinorVersion = (USHORT)-1;
6084 pContext->usBuildNumber = (USHORT)-1;
6085 pContext->usRevisionNumber = (USHORT)-1;
6087 // Ignore the WinRT type while considering if two assemblies have the same identity.
6088 pSpec->SetWindowsRuntimeType(NULL, NULL);
6090 CrstHolder ch(&m_DomainCrst);
6092 const NativeImageDependenciesEntry * pEntry = m_NativeImageDependencies.Lookup(pSpec);
6096 if (*pGuid != pEntry->m_guidMVID)
6099 msg.Printf("ERROR: Native images generated against multiple versions of assembly %s. ", pSpec->GetName());
6100 WszOutputDebugString(msg.GetUnicode());
6101 COMPlusThrowNonLocalized(kFileLoadException, msg.GetUnicode());
6107 // No entry yet - create one
6109 AllocMemTracker amTracker;
6110 AllocMemTracker *pamTracker = &amTracker;
6112 NativeImageDependenciesEntry * pNewEntry =
6113 new (pamTracker->Track(GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(NativeImageDependenciesEntry)))))
6114 NativeImageDependenciesEntry();
6116 pNewEntry->m_AssemblySpec.CopyFrom(pSpec);
6117 pNewEntry->m_AssemblySpec.CloneFieldsToLoaderHeap(AssemblySpec::ALL_OWNED, GetLowFrequencyHeap(), pamTracker);
6119 pNewEntry->m_guidMVID = *pGuid;
6121 m_NativeImageDependencies.Add(pNewEntry);
6122 amTracker.SuppressRelease();
6127 void AppDomain::SetupSharedStatics()
6134 INJECT_FAULT(COMPlusThrowOM(););
6138 #ifndef CROSSGEN_COMPILE
6139 if (NingenEnabled())
6142 LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: SetupSharedStatics()"));
6144 // don't do any work in init stage. If not init only do work in non-shared case if are default domain
6145 _ASSERTE(!g_fEEInit);
6147 // Because we are allocating/referencing objects, need to be in cooperative mode
6150 static OBJECTHANDLE hSharedStaticsHandle = NULL;
6152 if (hSharedStaticsHandle == NULL) {
6153 // Note that there is no race here since the default domain is always set up first
6154 _ASSERTE(IsDefaultDomain());
6156 MethodTable *pMT = MscorlibBinder::GetClass(CLASS__SHARED_STATICS);
6157 _ASSERTE(pMT->IsClassPreInited());
6159 hSharedStaticsHandle = CreateGlobalHandle(AllocateObject(pMT));
6162 DomainLocalModule *pLocalModule;
6164 if (IsSingleAppDomain())
6166 pLocalModule = MscorlibBinder::GetModule()->GetDomainLocalModule();
6170 pLocalModule = GetDomainLocalBlock()->GetModuleSlot(
6171 MscorlibBinder::GetModule()->GetModuleIndex());
6174 FieldDesc *pFD = MscorlibBinder::GetField(FIELD__SHARED_STATICS__SHARED_STATICS);
6176 OBJECTREF* pHandle = (OBJECTREF*)
6177 ((TADDR)pLocalModule->GetPrecomputedGCStaticsBasePointer()+pFD->GetOffset());
6178 SetObjectReference( pHandle, ObjectFromHandle(hSharedStaticsHandle), this );
6180 // This is a convenient place to initialize String.Empty.
6181 // It is treated as intrinsic by the JIT as so the static constructor would never run.
6182 // Leaving it uninitialized would confuse debuggers.
6184 // String should not have any static constructors.
6185 _ASSERTE(g_pStringClass->IsClassPreInited());
6187 FieldDesc * pEmptyStringFD = MscorlibBinder::GetField(FIELD__STRING__EMPTY);
6188 OBJECTREF* pEmptyStringHandle = (OBJECTREF*)
6189 ((TADDR)pLocalModule->GetPrecomputedGCStaticsBasePointer()+pEmptyStringFD->GetOffset());
6190 SetObjectReference( pEmptyStringHandle, StringObject::GetEmptyString(), this );
6191 #endif // CROSSGEN_COMPILE
6194 DomainAssembly * AppDomain::FindAssembly(PEAssembly * pFile, FindAssemblyOptions options/* = FindAssemblyOptions_None*/)
6201 INJECT_FAULT(COMPlusThrowOM(););
6205 const bool includeFailedToLoad = (options & FindAssemblyOptions_IncludeFailedToLoad) != 0;
6207 if (pFile->HasHostAssembly())
6209 DomainAssembly * pDA = FindAssembly(pFile->GetHostAssembly());
6210 if (pDA != nullptr && (pDA->IsLoaded() || (includeFailedToLoad && pDA->IsError())))
6217 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(
6219 (includeFailedToLoad ? kIncludeFailedToLoad : 0) |
6220 (pFile->IsIntrospectionOnly() ? kIncludeIntrospection : kIncludeExecution)));
6221 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
6223 while (i.Next(pDomainAssembly.This()))
6225 PEFile * pManifestFile = pDomainAssembly->GetFile();
6226 if (pManifestFile &&
6227 !pManifestFile->IsResource() &&
6228 pManifestFile->Equals(pFile))
6230 // Caller already has PEAssembly, so we can give DomainAssembly away freely without AddRef
6231 return pDomainAssembly.Extract();
6237 static const AssemblyIterationFlags STANDARD_IJW_ITERATOR_FLAGS =
6238 (AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution | kExcludeCollectible);
6241 void AppDomain::SetFriendlyName(LPCWSTR pwzFriendlyName, BOOL fDebuggerCares/*=TRUE*/)
6246 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6248 INJECT_FAULT(COMPlusThrowOM(););
6252 // Do all computations into a temporary until we're ensured of success
6253 SString tmpFriendlyName;
6256 if (pwzFriendlyName)
6257 tmpFriendlyName.Set(pwzFriendlyName);
6260 // If there is an assembly, try to get the name from it.
6261 // If no assembly, but if it's the DefaultDomain, then give it a name
6263 if (m_pRootAssembly)
6265 tmpFriendlyName.SetUTF8(m_pRootAssembly->GetSimpleName());
6267 SString::Iterator i = tmpFriendlyName.End();
6268 if (tmpFriendlyName.FindBack(i, '.'))
6269 tmpFriendlyName.Truncate(i);
6273 if (IsDefaultDomain())
6274 tmpFriendlyName.Set(DEFAULT_DOMAIN_FRIENDLY_NAME);
6276 // This is for the profiler - if they call GetFriendlyName on an AppdomainCreateStarted
6277 // event, then we want to give them a temporary name they can use.
6278 else if (GetId().m_dwId != 0)
6280 tmpFriendlyName.Clear();
6281 tmpFriendlyName.Printf(W("%s %d"), OTHER_DOMAIN_FRIENDLY_NAME_PREFIX, GetId().m_dwId);
6287 tmpFriendlyName.Normalize();
6290 m_friendlyName = tmpFriendlyName;
6291 m_friendlyName.Normalize();
6293 if(g_pDebugInterface)
6295 // update the name in the IPC publishing block
6296 if (SUCCEEDED(g_pDebugInterface->UpdateAppDomainEntryInIPC(this)))
6298 // inform the attached debugger that the name of this appdomain has changed.
6299 if (IsDebuggerAttached() && fDebuggerCares)
6300 g_pDebugInterface->NameChangeEvent(this, NULL);
6305 void AppDomain::ResetFriendlyName(BOOL fDebuggerCares/*=TRUE*/)
6307 WRAPPER_NO_CONTRACT;
6308 SetFriendlyName(NULL, fDebuggerCares);
6311 LPCWSTR AppDomain::GetFriendlyName(BOOL fDebuggerCares/*=TRUE*/)
6316 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6318 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
6319 INJECT_FAULT(COMPlusThrowOM(););
6324 // Handle NULL this pointer - this happens sometimes when printing log messages
6325 // but in general shouldn't occur in real code
6330 if (m_friendlyName.IsEmpty())
6331 SetFriendlyName(NULL, fDebuggerCares);
6333 RETURN m_friendlyName;
6336 LPCWSTR AppDomain::GetFriendlyNameForLogging()
6343 POSTCONDITION(CheckPointer(RETVAL,NULL_OK));
6347 // Handle NULL this pointer - this happens sometimes when printing log messages
6348 // but in general shouldn't occur in real code
6352 RETURN (m_friendlyName.IsEmpty() ?W(""):(LPCWSTR)m_friendlyName);
6355 LPCWSTR AppDomain::GetFriendlyNameForDebugger()
6360 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
6362 POSTCONDITION(CheckPointer(RETVAL));
6367 if (m_friendlyName.IsEmpty())
6369 BOOL fSuccess = FALSE;
6373 SetFriendlyName(NULL);
6379 // Gobble all exceptions.
6381 EX_END_CATCH(SwallowAllExceptions);
6389 RETURN m_friendlyName;
6393 #endif // !DACCESS_COMPILE
6395 #ifdef DACCESS_COMPILE
6397 PVOID AppDomain::GetFriendlyNameNoSet(bool* isUtf8)
6401 if (!m_friendlyName.IsEmpty())
6404 return m_friendlyName.DacGetRawContent();
6406 else if (m_pRootAssembly)
6409 return (PVOID)m_pRootAssembly->GetSimpleName();
6411 else if (dac_cast<TADDR>(this) ==
6412 dac_cast<TADDR>(SystemDomain::System()->DefaultDomain()))
6415 return (PVOID)DEFAULT_DOMAIN_FRIENDLY_NAME;
6423 #endif // DACCESS_COMPILE
6425 void AppDomain::CacheStringsForDAC()
6436 // If the application base, private bin paths, and configuration file are
6437 // available, cache them so DAC can read them out of memory
6441 #ifndef DACCESS_COMPILE
6443 BOOL AppDomain::AddFileToCache(AssemblySpec* pSpec, PEAssembly *pFile, BOOL fAllowFailure)
6450 PRECONDITION(CheckPointer(pSpec));
6451 // Hosted fusion binder makes an exception here, so we cannot assert.
6452 //PRECONDITION(pSpec->CanUseWithBindingCache());
6453 //PRECONDITION(pFile->CanUseWithBindingCache());
6454 INJECT_FAULT(COMPlusThrowOM(););
6458 CrstHolder holder(&m_DomainCacheCrst);
6459 // !!! suppress exceptions
6460 if(!m_AssemblyCache.StoreFile(pSpec, pFile) && !fAllowFailure)
6462 // TODO: Disabling the below assertion as currently we experience
6463 // inconsistency on resolving the Microsoft.Office.Interop.MSProject.dll
6464 // This causes below assertion to fire and crashes the VS. This issue
6465 // is being tracked with Dev10 Bug 658555. Brought back it when this bug
6469 EEFileLoadException::Throw(pSpec, FUSION_E_CACHEFILE_FAILED, NULL);
6475 BOOL AppDomain::AddAssemblyToCache(AssemblySpec* pSpec, DomainAssembly *pAssembly)
6482 PRECONDITION(CheckPointer(pSpec));
6483 PRECONDITION(CheckPointer(pAssembly));
6484 PRECONDITION(pSpec->CanUseWithBindingCache());
6485 PRECONDITION(pAssembly->CanUseWithBindingCache());
6486 INJECT_FAULT(COMPlusThrowOM(););
6490 CrstHolder holder(&m_DomainCacheCrst);
6491 // !!! suppress exceptions
6492 BOOL bRetVal = m_AssemblyCache.StoreAssembly(pSpec, pAssembly);
6496 BOOL AppDomain::AddExceptionToCache(AssemblySpec* pSpec, Exception *ex)
6503 PRECONDITION(CheckPointer(pSpec));
6504 PRECONDITION(pSpec->CanUseWithBindingCache());
6505 INJECT_FAULT(COMPlusThrowOM(););
6509 if (ex->IsTransient())
6512 CrstHolder holder(&m_DomainCacheCrst);
6513 // !!! suppress exceptions
6514 return m_AssemblyCache.StoreException(pSpec, ex);
6517 void AppDomain::AddUnmanagedImageToCache(LPCWSTR libraryName, HMODULE hMod)
6524 PRECONDITION(CheckPointer(libraryName));
6525 INJECT_FAULT(COMPlusThrowOM(););
6531 spec.SetCodeBase(libraryName);
6532 m_UnmanagedCache.InsertEntry(&spec, hMod);
6538 HMODULE AppDomain::FindUnmanagedImageInCache(LPCWSTR libraryName)
6545 PRECONDITION(CheckPointer(libraryName,NULL_OK));
6546 POSTCONDITION(CheckPointer(RETVAL,NULL_OK));
6547 INJECT_FAULT(COMPlusThrowOM(););
6550 if(libraryName == NULL) RETURN NULL;
6553 spec.SetCodeBase(libraryName);
6554 RETURN (HMODULE) m_UnmanagedCache.LookupEntry(&spec, 0);
6558 BOOL AppDomain::IsCached(AssemblySpec *pSpec)
6560 WRAPPER_NO_CONTRACT;
6562 // Check to see if this fits our rather loose idea of a reference to mscorlib.
6563 // If so, don't use fusion to bind it - do it ourselves.
6564 if (pSpec->IsMscorlib())
6567 return m_AssemblyCache.Contains(pSpec);
6570 void AppDomain::GetCacheAssemblyList(SetSHash<PTR_DomainAssembly>& assemblyList)
6572 CrstHolder holder(&m_DomainCacheCrst);
6573 m_AssemblyCache.GetAllAssemblies(assemblyList);
6576 PEAssembly* AppDomain::FindCachedFile(AssemblySpec* pSpec, BOOL fThrow /*=TRUE*/)
6592 // Check to see if this fits our rather loose idea of a reference to mscorlib.
6593 // If so, don't use fusion to bind it - do it ourselves.
6594 if (fThrow && pSpec->IsMscorlib())
6596 CONSISTENCY_CHECK(SystemDomain::System()->SystemAssembly() != NULL);
6597 PEAssembly *pFile = SystemDomain::System()->SystemFile();
6602 return m_AssemblyCache.LookupFile(pSpec, fThrow);
6606 BOOL AppDomain::PostBindResolveAssembly(AssemblySpec *pPrePolicySpec,
6607 AssemblySpec *pPostPolicySpec,
6608 HRESULT hrBindResult,
6609 AssemblySpec **ppFailedSpec)
6611 STATIC_CONTRACT_THROWS;
6612 STATIC_CONTRACT_GC_TRIGGERS;
6613 PRECONDITION(CheckPointer(pPrePolicySpec));
6614 PRECONDITION(CheckPointer(pPostPolicySpec));
6615 PRECONDITION(CheckPointer(ppFailedSpec));
6617 BOOL fFailure = TRUE;
6618 *ppFailedSpec = pPrePolicySpec;
6621 PEAssemblyHolder result;
6623 if ((EEFileLoadException::GetFileLoadKind(hrBindResult) == kFileNotFoundException) ||
6624 (hrBindResult == FUSION_E_REF_DEF_MISMATCH) ||
6625 (hrBindResult == FUSION_E_INVALID_NAME))
6627 result = TryResolveAssembly(*ppFailedSpec, FALSE /* fPreBind */);
6629 if (result != NULL && pPrePolicySpec->CanUseWithBindingCache() && result->CanUseWithBindingCache())
6633 // Given the post-policy resolve event construction of the CLR binder,
6634 // chained managed resolve events can race with each other, therefore we do allow
6635 // the adding of the result to fail. Checking for already chached specs
6636 // is not an option as it would introduce another race window.
6637 // The binder does a re-fetch of the
6638 // orignal binding spec and therefore will not cause inconsistency here.
6639 // For the purposes of the resolve event, failure to add to the cache still is a success.
6640 AddFileToCache(pPrePolicySpec, result, TRUE /* fAllowFailure */);
6641 if (*ppFailedSpec != pPrePolicySpec && pPostPolicySpec->CanUseWithBindingCache())
6643 AddFileToCache(pPostPolicySpec, result, TRUE /* fAllowFailure */ );
6651 //----------------------------------------------------------------------------------------
6652 // Helper class for hosted binder
6654 class PEAssemblyAsPrivAssemblyInfo : public IUnknownCommon<ICLRPrivAssemblyInfo>
6657 //------------------------------------------------------------------------------------
6660 PEAssemblyAsPrivAssemblyInfo(PEAssembly *pPEAssembly)
6662 LIMITED_METHOD_CONTRACT;
6663 STATIC_CONTRACT_THROWS;
6665 if (pPEAssembly == nullptr)
6666 ThrowHR(E_UNEXPECTED);
6668 pPEAssembly->AddRef();
6669 m_pPEAssembly = pPEAssembly;
6672 //------------------------------------------------------------------------------------
6673 // ICLRPrivAssemblyInfo methods
6675 //------------------------------------------------------------------------------------
6676 STDMETHOD(GetAssemblyName)(
6677 __in DWORD cchBuffer,
6678 __out_opt LPDWORD pcchBuffer,
6679 __out_ecount_part_opt(cchBuffer, *pcchBuffer) LPWSTR wzBuffer)
6691 if ((cchBuffer == 0) != (wzBuffer == nullptr))
6693 return E_INVALIDARG;
6696 LPCUTF8 szName = m_pPEAssembly->GetSimpleName();
6700 IfFailRet(FString::Utf8_Unicode_Length(szName, &bIsAscii, &cchName));
6702 if (cchBuffer < cchName + 1)
6704 if (pcchBuffer != nullptr)
6706 *pcchBuffer = cchName + 1;
6708 return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
6712 IfFailRet(FString::Utf8_Unicode(szName, bIsAscii, wzBuffer, cchName));
6713 if (pcchBuffer != nullptr)
6715 *pcchBuffer = cchName;
6721 //------------------------------------------------------------------------------------
6722 STDMETHOD(GetAssemblyVersion)(
6728 WRAPPER_NO_CONTRACT;
6729 return m_pPEAssembly->GetVersion(pMajor, pMinor, pBuild, pRevision);
6732 //------------------------------------------------------------------------------------
6733 STDMETHOD(GetAssemblyPublicKey)(
6738 STATIC_CONTRACT_LIMITED_METHOD;
6739 STATIC_CONTRACT_CAN_TAKE_LOCK;
6741 VALIDATE_PTR_RET(pcbBuffer);
6742 VALIDATE_CONDITION((pbBuffer == nullptr) == (cbBuffer == 0), return E_INVALIDARG);
6748 // Note: PEAssembly::GetPublicKey will return bogus data pointer when *pcbBuffer == 0
6749 LPCVOID pbKey = m_pPEAssembly->GetPublicKey(pcbBuffer);
6751 if (*pcbBuffer != 0)
6753 if (pbBuffer != nullptr && cbBuffer >= *pcbBuffer)
6755 memcpy(pbBuffer, pbKey, *pcbBuffer);
6760 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
6765 hr = S_FALSE; // ==> No public key
6768 EX_CATCH_HRESULT(hr);
6774 ReleaseHolder<PEAssembly> m_pPEAssembly;
6777 //-----------------------------------------------------------------------------------------------------------------
6778 static HRESULT VerifyBindHelper(
6779 ICLRPrivAssembly *pPrivAssembly,
6780 IAssemblyName *pAssemblyName,
6781 PEAssembly *pPEAssembly)
6783 STATIC_CONTRACT_THROWS;
6784 STATIC_CONTRACT_GC_TRIGGERS;
6787 // Create an ICLRPrivAssemblyInfo to call to ICLRPrivAssembly::VerifyBind
6788 NewHolder<PEAssemblyAsPrivAssemblyInfo> pPrivAssemblyInfoImpl = new PEAssemblyAsPrivAssemblyInfo(pPEAssembly);
6789 ReleaseHolder<ICLRPrivAssemblyInfo> pPrivAssemblyInfo;
6790 IfFailRet(pPrivAssemblyInfoImpl->QueryInterface(__uuidof(ICLRPrivAssemblyInfo), (LPVOID *)&pPrivAssemblyInfo));
6791 pPrivAssemblyInfoImpl.SuppressRelease();
6793 // Call VerifyBind to give the host a chance to reject the bind based on assembly image contents.
6794 IfFailRet(pPrivAssembly->VerifyBind(pAssemblyName, pPrivAssembly, pPrivAssemblyInfo));
6799 //-----------------------------------------------------------------------------------------------------------------
6800 HRESULT AppDomain::BindAssemblySpecForHostedBinder(
6801 AssemblySpec * pSpec,
6802 IAssemblyName * pAssemblyName,
6803 ICLRPrivBinder * pBinder,
6804 PEAssembly ** ppAssembly)
6806 STANDARD_VM_CONTRACT;
6808 PRECONDITION(CheckPointer(pSpec));
6809 PRECONDITION(pSpec->GetAppDomain() == this);
6810 PRECONDITION(CheckPointer(ppAssembly));
6811 PRECONDITION(pSpec->GetCodeBase() == nullptr);
6816 // The Fusion binder can throw (to preserve compat, since it will actually perform an assembly
6817 // load as part of it's bind), so we need to be careful here to catch any FileNotFoundException
6818 // objects if fThrowIfNotFound is false.
6819 ReleaseHolder<ICLRPrivAssembly> pPrivAssembly;
6821 // We return HRESULTs here on failure instead of throwing as failures here are not necessarily indicative
6822 // of an actual application problem. Returning an error code is substantially faster than throwing, and
6823 // should be used when possible.
6824 IfFailRet(pBinder->BindAssemblyByName(pAssemblyName, &pPrivAssembly));
6826 IfFailRet(BindHostedPrivAssembly(nullptr, pPrivAssembly, pAssemblyName, ppAssembly));
6832 //-----------------------------------------------------------------------------------------------------------------
6834 AppDomain::BindHostedPrivAssembly(
6835 PEAssembly * pParentAssembly,
6836 ICLRPrivAssembly * pPrivAssembly,
6837 IAssemblyName * pAssemblyName,
6838 PEAssembly ** ppAssembly,
6839 BOOL fIsIntrospectionOnly) // = FALSE
6841 STANDARD_VM_CONTRACT;
6843 PRECONDITION(CheckPointer(pPrivAssembly));
6844 PRECONDITION(CheckPointer(ppAssembly));
6848 *ppAssembly = nullptr;
6850 // See if result has been previously loaded.
6852 DomainAssembly* pDomainAssembly = FindAssembly(pPrivAssembly);
6853 if (pDomainAssembly != nullptr)
6855 *ppAssembly = clr::SafeAddRef(pDomainAssembly->GetFile());
6859 if (*ppAssembly != nullptr)
6860 { // Already exists: ask the binder to verify and return the assembly.
6861 return VerifyBindHelper(pPrivAssembly, pAssemblyName, *ppAssembly);
6864 // Get the IL PEFile.
6865 PEImageHolder pPEImageIL;
6867 // Does not already exist, so get the resource for the assembly and load it.
6869 ReleaseHolder<ICLRPrivResource> pIResourceIL;
6871 IfFailRet(pPrivAssembly->GetImageResource(ASSEMBLY_IMAGE_TYPE_IL, &dwImageType, &pIResourceIL));
6872 _ASSERTE(dwImageType == ASSEMBLY_IMAGE_TYPE_IL);
6874 pPEImageIL = PEImage::OpenImage(pIResourceIL, MDInternalImport_Default);
6877 // See if an NI is available.
6878 DWORD dwAvailableImages;
6879 IfFailRet(pPrivAssembly->GetAvailableImageTypes(&dwAvailableImages));
6880 _ASSERTE(dwAvailableImages & ASSEMBLY_IMAGE_TYPE_IL); // Just double checking that IL bit is always set.
6882 // Get the NI PEFile if available.
6883 PEImageHolder pPEImageNI;
6884 if (dwAvailableImages & ASSEMBLY_IMAGE_TYPE_NATIVE)
6887 ReleaseHolder<ICLRPrivResource> pIResourceNI;
6889 IfFailRet(pPrivAssembly->GetImageResource(ASSEMBLY_IMAGE_TYPE_NATIVE, &dwImageType, &pIResourceNI));
6890 _ASSERTE(dwImageType == ASSEMBLY_IMAGE_TYPE_NATIVE || FAILED(hr));
6892 pPEImageNI = PEImage::OpenImage(pIResourceNI, MDInternalImport_TrustedNativeImage);
6894 _ASSERTE(pPEImageIL != nullptr);
6896 // Create a PEAssembly using the IL and NI images.
6897 PEAssemblyHolder pPEAssembly = PEAssembly::Open(pParentAssembly, pPEImageIL, pPEImageNI, pPrivAssembly, fIsIntrospectionOnly);
6900 // Ask the binder to verify.
6901 IfFailRet(VerifyBindHelper(pPrivAssembly, pAssemblyName, pPEAssembly));
6904 *ppAssembly = pPEAssembly.Extract();
6907 } // AppDomain::BindHostedPrivAssembly
6909 //---------------------------------------------------------------------------------------------------------------------
6910 PEAssembly * AppDomain::BindAssemblySpec(
6911 AssemblySpec * pSpec,
6912 BOOL fThrowOnFileNotFound,
6913 BOOL fRaisePrebindEvents,
6914 StackCrawlMark * pCallerStackMark,
6915 BOOL fUseHostBinderIfAvailable)
6917 STATIC_CONTRACT_THROWS;
6918 STATIC_CONTRACT_GC_TRIGGERS;
6919 PRECONDITION(CheckPointer(pSpec));
6920 PRECONDITION(pSpec->GetAppDomain() == this);
6921 PRECONDITION(this==::GetAppDomain());
6925 BOOL fForceReThrow = FALSE;
6927 #if defined(FEATURE_COMINTEROP)
6928 // Handle WinRT assemblies in the classic/hybrid scenario. If this is an AppX process,
6929 // then this case will be handled by the previous block as part of the full set of
6930 // available binding hosts.
6931 if (pSpec->IsContentType_WindowsRuntime())
6935 // Get the assembly display name.
6936 ReleaseHolder<IAssemblyName> pAssemblyName;
6938 IfFailThrow(pSpec->CreateFusionName(&pAssemblyName, TRUE, TRUE));
6941 PEAssemblyHolder pAssembly;
6945 hr = BindAssemblySpecForHostedBinder(pSpec, pAssemblyName, m_pWinRtBinder, &pAssembly);
6947 goto EndTry2; // Goto end of try block.
6950 // The combination of this conditional catch/ the following if statement which will throw reduces the count of exceptions
6951 // thrown in scenarios where the exception does not escape the method. We cannot get rid of the try/catch block, as
6952 // there are cases within some of the clrpriv binder's which throw.
6953 // Note: In theory, FileNotFound should always come here as HRESULT, never as exception.
6954 EX_CATCH_HRESULT_IF(hr,
6955 !fThrowOnFileNotFound && Assembly::FileNotFound(hr))
6957 if (FAILED(hr) && (fThrowOnFileNotFound || !Assembly::FileNotFound(hr)))
6959 if (Assembly::FileNotFound(hr))
6961 _ASSERTE(fThrowOnFileNotFound);
6962 // Uses defaultScope
6963 EEFileLoadException::Throw(pSpec, hr);
6966 // WinRT type bind failures
6967 _ASSERTE(pSpec->IsContentType_WindowsRuntime());
6968 if (hr == HRESULT_FROM_WIN32(APPMODEL_ERROR_NO_PACKAGE)) // Returned by RoResolveNamespace when using 3rd party WinRT types in classic process
6970 if (fThrowOnFileNotFound)
6971 { // Throw NotSupportedException (with custom message) wrapped by TypeLoadException to give user type name for diagnostics
6972 // Note: TypeLoadException is equivalent of FileNotFound in WinRT world
6973 EEMessageException ex(kNotSupportedException, IDS_EE_WINRT_THIRDPARTY_NOTSUPPORTED);
6974 EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex);
6977 else if ((hr == CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT) || // Returned e.g. for WinRT type name without namespace
6978 (hr == COR_E_PLATFORMNOTSUPPORTED)) // Using WinRT on pre-Win8 OS
6980 if (fThrowOnFileNotFound)
6981 { // Throw ArgumentException/PlatformNotSupportedException wrapped by TypeLoadException to give user type name for diagnostics
6982 // Note: TypeLoadException is equivalent of FileNotFound in WinRT world
6983 EEMessageException ex(hr);
6984 EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex);
6992 _ASSERTE((FAILED(hr) && !fThrowOnFileNotFound) || pAssembly != nullptr);
6994 return pAssembly.Extract();
6997 #endif // FEATURE_COMINTEROP
6998 if (pSpec->HasUniqueIdentity())
7000 HRESULT hrBindResult = S_OK;
7001 PEAssemblyHolder result;
7006 if (!IsCached(pSpec))
7010 bool fAddFileToCache = false;
7012 BOOL fIsWellKnown = FALSE;
7014 // Use CoreClr's fusion alternative
7015 CoreBindResult bindResult;
7017 pSpec->Bind(this, fThrowOnFileNotFound, &bindResult, FALSE /* fNgenExplicitBind */, FALSE /* fExplicitBindToNativeImage */, pCallerStackMark);
7018 hrBindResult = bindResult.GetHRBindResult();
7020 if (bindResult.Found())
7022 if (SystemDomain::SystemFile() && bindResult.IsMscorlib())
7024 // Avoid rebinding to another copy of mscorlib
7025 result = SystemDomain::SystemFile();
7026 result.SuppressRelease(); // Didn't get a refcount
7030 // IsSystem on the PEFile should be false, even for mscorlib satellites
7031 result = PEAssembly::Open(&bindResult,
7032 FALSE, pSpec->IsIntrospectionOnly());
7034 fAddFileToCache = true;
7036 // Setup the reference to the binder, which performed the bind, into the AssemblySpec
7037 ICLRPrivBinder* pBinder = result->GetBindingContext();
7038 _ASSERTE(pBinder != NULL);
7039 pSpec->SetBindingContext(pBinder);
7043 if (fAddFileToCache)
7047 if (pSpec->CanUseWithBindingCache() && result->CanUseWithBindingCache())
7049 // Failure to add simply means someone else beat us to it. In that case
7050 // the FindCachedFile call below (after catch block) will update result
7051 // to the cached value.
7052 AddFileToCache(pSpec, result, TRUE /*fAllowFailure*/);
7055 else if (!fIsWellKnown)
7057 _ASSERTE(fThrowOnFileNotFound == FALSE);
7059 // Don't trigger the resolve event for the CoreLib satellite assembly. A misbehaving resolve event may
7060 // return an assembly that does not match, and this can cause recursive resource lookups during error
7061 // reporting. The CoreLib satellite assembly is loaded from relative locations based on the culture, see
7062 // AssemblySpec::Bind().
7063 if (!pSpec->IsMscorlibSatellite())
7065 // Trigger the resolve event also for non-throw situation.
7066 // However, this code path will behave as if the resolve handler has thrown,
7067 // that is, not trigger an MDA.
7069 AssemblySpec NewSpec(this);
7070 AssemblySpec *pFailedSpec = NULL;
7072 fForceReThrow = TRUE; // Managed resolve event handler can throw
7074 // Purposly ignore return value
7075 PostBindResolveAssembly(pSpec, &NewSpec, hrBindResult, &pFailedSpec);
7083 Exception *ex = GET_EXCEPTION();
7085 AssemblySpec NewSpec(this);
7086 AssemblySpec *pFailedSpec = NULL;
7088 // Let transient exceptions or managed resolve event handler exceptions propagate
7089 if (ex->IsTransient() || fForceReThrow)
7095 // This is not executed for SO exceptions so we need to disable the backout
7096 // stack validation to prevent false violations from being reported.
7097 DISABLE_BACKOUT_STACK_VALIDATION;
7099 BOOL fFailure = PostBindResolveAssembly(pSpec, &NewSpec, ex->GetHR(), &pFailedSpec);
7102 BOOL bFileNotFoundException =
7103 (EEFileLoadException::GetFileLoadKind(ex->GetHR()) == kFileNotFoundException);
7105 if (!bFileNotFoundException)
7107 fFailure = AddExceptionToCache(pFailedSpec, ex);
7108 } // else, fFailure stays TRUE
7109 // Effectively, fFailure == bFileNotFoundException || AddExceptionToCache(pFailedSpec, ex)
7111 // Only throw this exception if we are the first in the cache
7115 // If the BindingFailure MDA is enabled, trigger one for this failure
7116 // Note: TryResolveAssembly() can also throw if an AssemblyResolve event subscriber throws
7117 // and the MDA isn't sent in this case (or for transient failure cases)
7119 #ifdef MDA_SUPPORTED
7120 MdaBindingFailure* pProbe = MDA_GET_ASSISTANT(BindingFailure);
7123 // Transition to cooperative GC mode before using any OBJECTREFs.
7126 OBJECTREF exceptionObj = GET_THROWABLE();
7127 GCPROTECT_BEGIN(exceptionObj)
7129 pProbe->BindFailed(pFailedSpec, &exceptionObj);
7135 // In the same cases as for the MDA, store the failure information for DAC to read
7136 if (IsDebuggerAttached()) {
7137 FailedAssembly *pFailed = new FailedAssembly();
7138 pFailed->Initialize(pFailedSpec, ex);
7139 IfFailThrow(m_failedAssemblies.Append(pFailed));
7142 if (!bFileNotFoundException || fThrowOnFileNotFound)
7145 // V1.1 App-compatibility workaround. See VSW530166 if you want to whine about it.
7147 // In Everett, if we failed to download an assembly because of a broken network cable,
7148 // we returned a FileNotFoundException with a COR_E_FILENOTFOUND hr embedded inside
7149 // (which would be exposed when marshaled to native.)
7151 // In Whidbey, we now set the more appropriate INET_E_RESOURCE_NOT_FOUND hr. But
7152 // the online/offline switch code in VSTO for Everett hardcoded a check for
7153 // COR_E_FILENOTFOUND.
7155 // So now, to keep that code from breaking, we have to remap INET_E_RESOURCE_NOT_FOUND
7156 // back to COR_E_FILENOTFOUND. We're doing it here rather down in Fusion so as to affect
7157 // the least number of callers.
7159 if (ex->GetHR() == INET_E_RESOURCE_NOT_FOUND)
7161 EEFileLoadException::Throw(pFailedSpec, COR_E_FILENOTFOUND, ex);
7164 if (EEFileLoadException::CheckType(ex))
7166 if (pFailedSpec == pSpec)
7168 EX_RETHROW; //preserve the information
7172 StackSString exceptionDisplayName, failedSpecDisplayName;
7174 ((EEFileLoadException*)ex)->GetName(exceptionDisplayName);
7175 pFailedSpec->GetFileOrDisplayName(0, failedSpecDisplayName);
7177 if (exceptionDisplayName.CompareCaseInsensitive(failedSpecDisplayName) == 0)
7179 EX_RETHROW; // Throw the original exception. Otherwise, we'd throw an exception that contains the same message twice.
7184 EEFileLoadException::Throw(pFailedSpec, ex->GetHR(), ex);
7191 EX_END_CATCH(RethrowTerminalExceptions);
7193 // 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
7194 // thread to store our result. Note that we may throw from here, if there is a cached exception.
7195 // This will release the refcount of the current result holder (if any), and will replace
7196 // it with a non-addref'ed result
7197 if (pSpec->CanUseWithBindingCache() && (result== NULL || result->CanUseWithBindingCache()))
7199 result = FindCachedFile(pSpec);
7205 return result.Extract();
7209 // Unsupported content type
7210 if (fThrowOnFileNotFound)
7212 ThrowHR(COR_E_BADIMAGEFORMAT);
7216 } // AppDomain::BindAssemblySpec
7220 PEAssembly *AppDomain::TryResolveAssembly(AssemblySpec *pSpec, BOOL fPreBind)
7222 STATIC_CONTRACT_THROWS;
7223 STATIC_CONTRACT_GC_TRIGGERS;
7224 STATIC_CONTRACT_MODE_ANY;
7226 PEAssembly *result = NULL;
7230 result = pSpec->ResolveAssemblyFile(this, fPreBind);
7234 Exception *pEx = GET_EXCEPTION();
7236 if (!pEx->IsTransient())
7238 AddExceptionToCache(pSpec, pEx);
7239 if (!EEFileLoadException::CheckType(pEx))
7240 EEFileLoadException::Throw(pSpec, pEx->GetHR(), pEx);
7249 ULONG AppDomain::AddRef()
7251 LIMITED_METHOD_CONTRACT;
7252 return InterlockedIncrement(&m_cRef);
7255 ULONG AppDomain::Release()
7262 PRECONDITION(m_cRef > 0);
7266 ULONG cRef = InterlockedDecrement(&m_cRef);
7269 _ASSERTE (m_Stage == STAGE_CREATING || m_Stage == STAGE_CLOSED);
7272 TESTHOOKCALL(AppDomainDestroyed(adid.m_dwId));
7278 AppDomain* AppDomain::s_pAppDomainToRaiseUnloadEvent;
7279 BOOL AppDomain::s_fProcessUnloadDomainEvent = FALSE;
7281 #ifndef CROSSGEN_COMPILE
7283 void AppDomain::RaiseUnloadDomainEvent_Wrapper(LPVOID ptr)
7290 INJECT_FAULT(COMPlusThrowOM(););
7295 AppDomain* pDomain = (AppDomain *) ptr;
7296 pDomain->RaiseUnloadDomainEvent();
7299 void AppDomain::ProcessUnloadDomainEventOnFinalizeThread()
7308 Thread *pThread = GetThread();
7309 _ASSERTE (pThread && IsFinalizerThread());
7311 // if we are not unloading domain now, do not process the event
7312 if (SystemDomain::AppDomainBeingUnloaded() == NULL)
7314 s_pAppDomainToRaiseUnloadEvent->SetStage(STAGE_UNLOAD_REQUESTED);
7315 s_pAppDomainToRaiseUnloadEvent->EnableADUnloadWorker(
7316 s_pAppDomainToRaiseUnloadEvent->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7317 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, NULL);
7320 FastInterlockExchange((LONG*)&s_fProcessUnloadDomainEvent, TRUE);
7321 AppDomain::EnableADUnloadWorkerForFinalizer();
7322 pThread->SetThreadStateNC(Thread::TSNC_RaiseUnloadEvent);
7323 s_pAppDomainToRaiseUnloadEvent->RaiseUnloadDomainEvent();
7324 pThread->ResetThreadStateNC(Thread::TSNC_RaiseUnloadEvent);
7325 s_pAppDomainToRaiseUnloadEvent->EnableADUnloadWorker(
7326 s_pAppDomainToRaiseUnloadEvent->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7327 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, NULL);
7328 FastInterlockExchange((LONG*)&s_fProcessUnloadDomainEvent, FALSE);
7330 if (pThread->IsAbortRequested())
7332 pThread->UnmarkThreadForAbort(Thread::TAR_Thread);
7336 void AppDomain::RaiseUnloadDomainEvent()
7347 Thread *pThread = GetThread();
7348 if (this != pThread->GetDomain())
7350 pThread->DoADCallBack(this, AppDomain::RaiseUnloadDomainEvent_Wrapper, this,ADV_FINALIZER|ADV_COMPILATION);
7356 APPDOMAINREF Domain;
7359 ZeroMemory(&gc, sizeof(gc));
7361 GCPROTECT_BEGIN(gc);
7362 gc.Domain = (APPDOMAINREF) GetRawExposedObject();
7363 if (gc.Domain != NULL)
7365 gc.Delegate = gc.Domain->m_pDomainUnloadEventHandler;
7366 if (gc.Delegate != NULL)
7367 DistributeEvent(&gc.Delegate, (OBJECTREF *) &gc.Domain);
7373 void AppDomain::RaiseLoadingAssemblyEvent(DomainAssembly *pAssembly)
7379 PRECONDITION(this == GetAppDomain());
7386 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
7391 APPDOMAINREF AppDomainRef;
7394 ZeroMemory(&gc, sizeof(gc));
7396 if ((gc.AppDomainRef = (APPDOMAINREF) GetRawExposedObject()) != NULL) {
7397 if (gc.AppDomainRef->m_pAssemblyEventHandler != NULL)
7400 GCPROTECT_BEGIN(gc);
7402 gc.orThis = pAssembly->GetExposedAssemblyObject();
7404 MethodDescCallSite onAssemblyLoad(METHOD__APP_DOMAIN__ON_ASSEMBLY_LOAD, &gc.orThis);
7406 // GetExposedAssemblyObject may cause a gc, so call this before filling args[0]
7407 args[1] = ObjToArgSlot(gc.orThis);
7408 args[0] = ObjToArgSlot(gc.AppDomainRef);
7410 onAssemblyLoad.Call(args);
7419 EX_END_CATCH(SwallowAllExceptions);
7423 BOOL AppDomain::OnUnhandledException(OBJECTREF *pThrowable, BOOL isTerminating/*=TRUE*/)
7425 STATIC_CONTRACT_NOTHROW;
7426 STATIC_CONTRACT_GC_TRIGGERS;
7427 STATIC_CONTRACT_MODE_ANY;
7433 // The Everett behavior was to send the unhandled exception event only to the Default
7434 // AppDomain (since that's the only place that exceptions actually went unhandled).
7436 // During Whidbey development, we broadcast the event to all AppDomains in the process.
7438 // But the official shipping Whidbey behavior is that the unhandled exception event is
7439 // sent to the Default AppDomain and to whatever AppDomain the exception went unhandled
7440 // in. To achieve this, we declare the exception to be unhandled *BEFORE* we marshal
7441 // it back to the Default AppDomain at the base of the Finalizer, threadpool and managed
7444 // The rationale for sending the event to the Default AppDomain as well as the one the
7445 // exception went unhandled in is:
7447 // 1) This is compatible with the pre-Whidbey behavior, where only the Default AppDomain
7448 // received the notification.
7450 // 2) This is convenient for hosts, which don't want to bother injecting listeners into
7451 // every single AppDomain.
7453 AppDomain *pAppDomain = GetAppDomain();
7454 OBJECTREF orSender = 0;
7456 GCPROTECT_BEGIN(orSender);
7458 orSender = pAppDomain->GetRawExposedObject();
7460 retVal = pAppDomain->RaiseUnhandledExceptionEventNoThrow(&orSender, pThrowable, isTerminating);
7468 // Move outside of the AppDomain iteration, to avoid issues with the GC Frames being outside
7469 // the domain transition. This is a chronic issue that causes us to report roots for an AppDomain
7470 // after we have left it. This causes problems with AppDomain unloading that we only find
7471 // with stress coverage..
7472 void AppDomain::RaiseOneExitProcessEvent()
7484 APPDOMAINREF Domain;
7487 ZeroMemory(&gc, sizeof(gc));
7489 GCPROTECT_BEGIN(gc);
7490 gc.Domain = (APPDOMAINREF) SystemDomain::GetCurrentDomain()->GetRawExposedObject();
7491 if (gc.Domain != NULL)
7493 gc.Delegate = gc.Domain->m_pProcessExitEventHandler;
7494 if (gc.Delegate != NULL)
7495 DistributeEvent(&gc.Delegate, (OBJECTREF *) &gc.Domain);
7500 // Local wrapper used in AppDomain::RaiseExitProcessEvent,
7501 // introduced solely to avoid stack overflow because of _alloca in the loop.
7502 // It's just factored out body of the loop, but it has to be a member method of AppDomain,
7503 // because it calls private RaiseOneExitProcessEvent
7504 /*static*/ void AppDomain::RaiseOneExitProcessEvent_Wrapper(AppDomainIterator* pi)
7506 STATIC_CONTRACT_MODE_COOPERATIVE;
7507 STATIC_CONTRACT_THROWS;
7508 STATIC_CONTRACT_GC_TRIGGERS;
7510 ENTER_DOMAIN_PTR(pi->GetDomain(), ADV_ITERATOR)
7511 AppDomain::RaiseOneExitProcessEvent();
7512 END_DOMAIN_TRANSITION;
7515 static LONG s_ProcessedExitProcessEventCount = 0;
7517 LONG GetProcessedExitProcessEventCount()
7519 LIMITED_METHOD_CONTRACT;
7520 return s_ProcessedExitProcessEventCount;
7523 void AppDomain::RaiseExitProcessEvent()
7528 STATIC_CONTRACT_MODE_COOPERATIVE;
7529 STATIC_CONTRACT_THROWS;
7530 STATIC_CONTRACT_GC_TRIGGERS;
7532 // Only finalizer thread during shutdown can call this function.
7533 _ASSERTE ((g_fEEShutDown&ShutDown_Finalize1) && GetThread() == FinalizerThread::GetFinalizerThread());
7535 _ASSERTE (GetThread()->PreemptiveGCDisabled());
7537 _ASSERTE (GetThread()->GetDomain()->IsDefaultDomain());
7539 AppDomainIterator i(TRUE);
7542 RaiseOneExitProcessEvent_Wrapper(&i);
7543 FastInterlockIncrement(&s_ProcessedExitProcessEventCount);
7549 AppDomain::RaiseUnhandledExceptionEventNoThrow(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating)
7562 bRetVal = RaiseUnhandledExceptionEvent(pSender, pThrowable, isTerminating);
7567 EX_END_CATCH(SwallowAllExceptions) // Swallow any errors.
7573 AppDomain::HasUnhandledExceptionEventHandler()
7578 GC_NOTRIGGER; //essential
7582 if (!CanThreadEnter(GetThread()))
7584 if (GetRawExposedObject()==NULL)
7586 return (((APPDOMAINREF)GetRawExposedObject())->m_pUnhandledExceptionEventHandler!=NULL);
7590 AppDomain::RaiseUnhandledExceptionEvent(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating)
7597 INJECT_FAULT(COMPlusThrowOM(););
7601 if (!HasUnhandledExceptionEventHandler())
7604 BOOL result = FALSE;
7606 _ASSERTE(pThrowable != NULL && IsProtectedByGCFrame(pThrowable));
7607 _ASSERTE(pSender != NULL && IsProtectedByGCFrame(pSender));
7609 _ASSERTE(this == GetThread()->GetDomain());
7612 OBJECTREF orDelegate = NULL;
7614 GCPROTECT_BEGIN(orDelegate);
7616 APPDOMAINREF orAD = (APPDOMAINREF) GetAppDomain()->GetRawExposedObject();
7620 orDelegate = orAD->m_pUnhandledExceptionEventHandler;
7621 if (orDelegate != NULL)
7624 DistributeUnhandledExceptionReliably(&orDelegate, pSender, pThrowable, isTerminating);
7633 #endif // CROSSGEN_COMPILE
7635 // You must be in the correct context before calling this
7636 // routine. Therefore, it is only good for initializing the
7638 void AppDomain::InitializeDomainContext(BOOL allowRedirects,
7647 INJECT_FAULT(COMPlusThrowOM(););
7651 if (NingenEnabled())
7654 CreateFusionContext();
7659 #ifndef CROSSGEN_COMPILE
7661 STRINGREF pFilePath;
7664 PTRARRAYREF propertyNames;
7665 PTRARRAYREF propertyValues;
7667 ZeroMemory(&gc, sizeof(gc));
7669 GCPROTECT_BEGIN(gc);
7672 gc.pFilePath = StringObject::NewString(pwszPath);
7677 gc.pConfig = StringObject::NewString(pwszConfig);
7681 if ((gc.ref = GetExposedObject()) != NULL)
7683 MethodDescCallSite setupDomain(METHOD__APP_DOMAIN__SETUP_DOMAIN);
7687 ObjToArgSlot(gc.ref),
7688 BoolToArgSlot(allowRedirects),
7689 ObjToArgSlot(gc.pFilePath),
7690 ObjToArgSlot(gc.pConfig),
7691 ObjToArgSlot(gc.propertyNames),
7692 ObjToArgSlot(gc.propertyValues)
7694 setupDomain.Call(args);
7698 CacheStringsForDAC();
7699 #endif // CROSSGEN_COMPILE
7703 IUnknown *AppDomain::CreateFusionContext()
7705 CONTRACT(IUnknown *)
7710 POSTCONDITION(CheckPointer(RETVAL));
7711 INJECT_FAULT(COMPlusThrowOM(););
7715 if (!m_pFusionContext)
7717 ETWOnStartup (FusionAppCtx_V1, FusionAppCtxEnd_V1);
7718 CLRPrivBinderCoreCLR *pTPABinder = NULL;
7722 // Initialize the assembly binder for the default context loads for CoreCLR.
7723 IfFailThrow(CCoreCLRBinderHelper::DefaultBinderSetupContext(GetId().m_dwId, &pTPABinder));
7724 m_pFusionContext = reinterpret_cast<IUnknown *>(pTPABinder);
7726 // By default, initial binding context setup for CoreCLR is also the TPABinding context
7727 (m_pTPABinderContext = pTPABinder)->AddRef();
7731 RETURN m_pFusionContext;
7736 //---------------------------------------------------------------------------------------
7738 // AppDomain::IsDebuggerAttached - is a debugger attached to this process
7744 // TRUE if a debugger is attached to this process, FALSE otherwise.
7747 // This is identical to CORDebuggerAttached. This exists idependantly for legacy reasons - we used to
7748 // support attaching to individual AppDomains. This should probably go away eventually.
7751 BOOL AppDomain::IsDebuggerAttached()
7753 LIMITED_METHOD_CONTRACT;
7755 if (CORDebuggerAttached())
7765 #ifdef DEBUGGING_SUPPORTED
7767 // This is called from the debugger to request notification events from
7768 // Assemblies, Modules, Types in this appdomain.
7769 BOOL AppDomain::NotifyDebuggerLoad(int flags, BOOL attaching)
7771 WRAPPER_NO_CONTRACT;
7772 BOOL result = FALSE;
7774 if (!attaching && !IsDebuggerAttached())
7779 // Attach to our assemblies
7780 LOG((LF_CORDB, LL_INFO100, "AD::NDA: Iterating assemblies\n"));
7781 i = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution));
7782 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
7783 while (i.Next(pDomainAssembly.This()))
7785 result = (pDomainAssembly->NotifyDebuggerLoad(flags, attaching) ||
7792 void AppDomain::NotifyDebuggerUnload()
7794 WRAPPER_NO_CONTRACT;
7795 if (!IsDebuggerAttached())
7798 LOG((LF_CORDB, LL_INFO10, "AD::NDD domain [%d] %#08x %ls\n",
7799 GetId().m_dwId, this, GetFriendlyNameForLogging()));
7801 LOG((LF_CORDB, LL_INFO100, "AD::NDD: Interating domain bound assemblies\n"));
7802 AssemblyIterator i = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeLoading | kIncludeExecution));
7803 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
7805 // Detach from our assemblies
7806 while (i.Next(pDomainAssembly.This()))
7808 LOG((LF_CORDB, LL_INFO100, "AD::NDD: Iterating assemblies\n"));
7809 pDomainAssembly->NotifyDebuggerUnload();
7812 #endif // DEBUGGING_SUPPORTED
7814 void AppDomain::SetSystemAssemblyLoadEventSent(BOOL fFlag)
7816 LIMITED_METHOD_CONTRACT;
7818 m_dwFlags |= LOAD_SYSTEM_ASSEMBLY_EVENT_SENT;
7820 m_dwFlags &= ~LOAD_SYSTEM_ASSEMBLY_EVENT_SENT;
7823 BOOL AppDomain::WasSystemAssemblyLoadEventSent(void)
7825 LIMITED_METHOD_CONTRACT;
7826 return ((m_dwFlags & LOAD_SYSTEM_ASSEMBLY_EVENT_SENT) == 0) ? FALSE : TRUE;
7829 #ifndef CROSSGEN_COMPILE
7830 // U->M thunks created in this domain and not associated with a delegate.
7831 UMEntryThunkCache *AppDomain::GetUMEntryThunkCache()
7838 INJECT_FAULT(COMPlusThrowOM(););
7842 if (!m_pUMEntryThunkCache)
7844 UMEntryThunkCache *pUMEntryThunkCache = new UMEntryThunkCache(this);
7846 if (FastInterlockCompareExchangePointer(&m_pUMEntryThunkCache, pUMEntryThunkCache, NULL) != NULL)
7848 // some thread swooped in and set the field
7849 delete pUMEntryThunkCache;
7852 _ASSERTE(m_pUMEntryThunkCache);
7853 return m_pUMEntryThunkCache;
7856 #ifdef FEATURE_COMINTEROP
7858 ComCallWrapperCache *AppDomain::GetComCallWrapperCache()
7865 INJECT_FAULT(COMPlusThrowOM(););
7869 if (! m_pComCallWrapperCache)
7871 BaseDomain::LockHolder lh(this);
7873 if (! m_pComCallWrapperCache)
7874 m_pComCallWrapperCache = ComCallWrapperCache::Create(this);
7876 _ASSERTE(m_pComCallWrapperCache);
7877 return m_pComCallWrapperCache;
7880 RCWRefCache *AppDomain::GetRCWRefCache()
7882 CONTRACT(RCWRefCache*)
7887 POSTCONDITION(CheckPointer(RETVAL));
7891 if (!m_pRCWRefCache) {
7892 NewHolder<RCWRefCache> pRCWRefCache = new RCWRefCache(this);
7893 if (FastInterlockCompareExchangePointer(&m_pRCWRefCache, (RCWRefCache *)pRCWRefCache, NULL) == NULL)
7895 pRCWRefCache.SuppressRelease();
7898 RETURN m_pRCWRefCache;
7901 RCWCache *AppDomain::CreateRCWCache()
7908 INJECT_FAULT(COMPlusThrowOM(););
7909 POSTCONDITION(CheckPointer(RETVAL));
7913 // Initialize the global RCW cleanup list here as well. This is so that it
7914 // it guaranteed to exist if any RCW's are created, but it is not created
7916 if (!g_pRCWCleanupList)
7918 SystemDomain::LockHolder lh;
7920 if (!g_pRCWCleanupList)
7921 g_pRCWCleanupList = new RCWCleanupList();
7923 _ASSERTE(g_pRCWCleanupList);
7926 BaseDomain::LockHolder lh(this);
7929 m_pRCWCache = new RCWCache(this);
7935 void AppDomain::ReleaseRCWs(LPVOID pCtxCookie)
7937 WRAPPER_NO_CONTRACT;
7939 m_pRCWCache->ReleaseWrappersWorker(pCtxCookie);
7941 RemoveWinRTFactoryObjects(pCtxCookie);
7944 void AppDomain::DetachRCWs()
7946 WRAPPER_NO_CONTRACT;
7948 m_pRCWCache->DetachWrappersWorker();
7951 #endif // FEATURE_COMINTEROP
7953 BOOL AppDomain::CanThreadEnter(Thread *pThread)
7955 WRAPPER_NO_CONTRACT;
7957 if (m_Stage < STAGE_EXITED)
7960 if (pThread == SystemDomain::System()->GetUnloadingThread())
7961 return m_Stage < STAGE_FINALIZING;
7962 if (pThread == FinalizerThread::GetFinalizerThread())
7963 return m_Stage < STAGE_FINALIZED;
7968 void AppDomain::AllowThreadEntrance(AppDomain * pApp)
7976 PRECONDITION(CheckPointer(pApp));
7980 if (pApp->GetUnloadRequestThread() == NULL)
7982 // This is asynchonous unload, either by a host, or by AppDomain.Unload from AD unload event.
7983 if (!pApp->IsUnloadingFromUnloadEvent())
7985 pApp->SetStage(STAGE_UNLOAD_REQUESTED);
7986 pApp->EnableADUnloadWorker(
7987 pApp->IsRudeUnload()?EEPolicy::ADU_Rude:EEPolicy::ADU_Safe);
7992 SystemDomain::LockHolder lh; // we don't want to reopen appdomain if other thread can be preparing to unload it
7994 #ifdef FEATURE_COMINTEROP
7995 if (pApp->m_pComCallWrapperCache)
7996 pApp->m_pComCallWrapperCache->ResetDomainIsUnloading();
7997 #endif // FEATURE_COMINTEROP
7999 pApp->SetStage(STAGE_OPEN);
8002 void AppDomain::RestrictThreadEntrance(AppDomain * pApp)
8007 DISABLED(GC_TRIGGERS);
8009 DISABLED(FORBID_FAULT);
8010 PRECONDITION(CheckPointer(pApp));
8014 #ifdef FEATURE_COMINTEROP
8015 // Set the flag on our CCW cache so stubs won't enter
8016 if (pApp->m_pComCallWrapperCache)
8017 pApp->m_pComCallWrapperCache->SetDomainIsUnloading();
8018 #endif // FEATURE_COMINTEROP
8020 SystemDomain::LockHolder lh; // we don't want to reopen appdomain if other thread can be preparing to unload it
8021 // Release our ID so remoting and thread pool won't enter
8022 pApp->SetStage(STAGE_EXITED);
8025 void AppDomain::Exit(BOOL fRunFinalizers, BOOL fAsyncExit)
8035 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Exiting domain [%d] %#08x %ls\n",
8036 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8038 RestrictEnterHolder RestrictEnter(this);
8041 SystemDomain::LockHolder lh; // we don't want to close appdomain if other thread can be preparing to unload it
8042 SetStage(STAGE_EXITING); // Note that we're trying to exit
8045 // Raise the event indicating the domain is being unloaded.
8046 if (GetDefaultContext())
8048 FastInterlockExchangePointer(&s_pAppDomainToRaiseUnloadEvent, this);
8050 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8051 //if (timeout == INFINITE)
8053 // timeout = 20000; // 20 seconds
8055 DWORD timeoutForFinalizer = GetEEPolicy()->GetTimeout(OPR_FinalizerRun);
8056 ULONGLONG curTime = CLRGetTickCount64();
8057 ULONGLONG endTime = 0;
8058 if (timeout != INFINITE)
8060 endTime = curTime + timeout;
8061 // We will try to kill AD unload event if it takes too long, and then we move on to the next registered caller.
8065 while (s_pAppDomainToRaiseUnloadEvent != NULL)
8067 FinalizerThread::FinalizerThreadWait(s_fProcessUnloadDomainEvent?timeout:timeoutForFinalizer);
8068 if (endTime != 0 && s_pAppDomainToRaiseUnloadEvent != NULL)
8070 if (CLRGetTickCount64() >= endTime)
8073 sThreadId.Printf(W("%x"), FinalizerThread::GetFinalizerThread()->GetThreadId());
8074 COMPlusThrow(kCannotUnloadAppDomainException,
8075 IDS_EE_ADUNLOAD_CANT_UNWIND_THREAD,
8082 // Tell the tiered compilation manager to stop initiating any new work for background
8083 // jit optimization. Its possible the standard thread unwind mechanisms would pre-emptively
8084 // evacuate the jit threadpool worker threads from the domain on their own, but I see no reason
8085 // to take the risk of relying on them when we can easily augment with a cooperative
8086 // shutdown check. This notification only initiates the process of evacuating the threads
8087 // and then the UnwindThreads() call below is where blocking will occur to ensure the threads
8088 // have exited the domain.
8090 #ifdef FEATURE_TIERED_COMPILATION
8091 m_tieredCompilationManager.Shutdown(FALSE);
8095 // Set up blocks so no threads can enter except for the finalizer and the thread
8096 // doing the unload.
8099 RestrictThreadEntrance(this);
8101 // Cause existing threads to abort out of this domain. This should ensure all
8102 // normal threads are outside the domain, and we've already ensured that no new threads
8105 PerAppDomainTPCountList::AppDomainUnloadingHolder tpAdUnloadHolder(GetTPIndex());
8108 if (!NingenEnabled())
8113 TESTHOOKCALL(UnwoundThreads(GetId().m_dwId)) ;
8114 ProcessEventForHost(Event_DomainUnload, (PVOID)(UINT_PTR)GetId().m_dwId);
8116 RestrictEnter.SuppressRelease(); //after this point we don't guarantee appdomain consistency
8117 #ifdef PROFILING_SUPPORTED
8118 // Signal profile if present.
8120 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
8122 g_profControlBlock.pProfInterface->AppDomainShutdownStarted((AppDomainID) this);
8125 #endif // PROFILING_SUPPORTED
8126 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomains--);
8127 COUNTER_ONLY(GetPerfCounters().m_Loading.cAppDomainsUnloaded++);
8129 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is exited.\n",
8130 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8132 // Send ETW events for this domain's unload and potentially iterate through this
8133 // domain's modules & assemblies to send events for their unloads as well. This
8134 // needs to occur before STAGE_FINALIZED (to ensure everything is there), so we do
8135 // this before any finalization occurs at all.
8136 ETW::LoaderLog::DomainUnload(this);
8138 CodeVersionManager::OnAppDomainExit(this);
8141 // Spin running finalizers until we flush them all. We need to make multiple passes
8142 // in case the finalizers create more finalizable objects. This is important to clear
8143 // the finalizable objects as roots, as well as to actually execute the finalizers. This
8144 // will only finalize instances instances of types that aren't potentially agile becuase we can't
8145 // risk finalizing agile objects. So we will be left with instances of potentially agile types
8146 // in handles or statics.
8148 // <TODO>@todo: Need to ensure this will terminate in a reasonable amount of time. Eventually
8149 // we should probably start passing FALSE for fRunFinalizers. Also I'm not sure we
8150 // guarantee that FinalizerThreadWait will ever terminate in general.</TODO>
8153 SetStage(STAGE_FINALIZING);
8155 // Flush finalizers now.
8156 FinalizerThread::UnloadAppDomain(this, fRunFinalizers);
8158 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8159 ULONGLONG startTime = CLRGetTickCount64();
8160 ULONGLONG elapsedTime = 0;
8161 DWORD finalizerWait = 0;
8163 while (FinalizerThread::GetUnloadingAppDomain() != NULL)
8166 if (timeout != INFINITE)
8168 elapsedTime = CLRGetTickCount64() - startTime;
8170 if (timeout > elapsedTime)
8172 finalizerWait = timeout - static_cast<DWORD>(elapsedTime);
8174 FinalizerThread::FinalizerThreadWait(finalizerWait); //will set stage to finalized
8175 if (timeout != INFINITE && FinalizerThread::GetUnloadingAppDomain() != NULL)
8177 elapsedTime = CLRGetTickCount64() - startTime;
8178 if (timeout <= elapsedTime)
8181 // TODO: Consider escalation from RudeAppDomain
8187 tpAdUnloadHolder.SuppressRelease();
8188 PerAppDomainTPCountList::ResetAppDomainTPCounts(GetTPIndex());
8190 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is finalized.\n",
8191 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8194 AppDomainRefHolder This(this);
8195 AddRef(); // Hold a reference so CloseDomain won't delete us yet
8196 CloseDomain(); // Remove ourself from the list of app domains
8198 // This needs to be done prior to destroying the handle tables below.
8199 ReleaseDomainBoundInfo();
8202 // It should be impossible to run non-mscorlib code in this domain now.
8203 // Cleanup all of our roots except the handles. We do this to allow as many
8204 // finalizers as possible to run correctly. If we delete the handles, they
8207 if (!NingenEnabled())
8214 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is cleared.\n",
8215 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8217 if (fAsyncExit && fRunFinalizers)
8220 m_AssemblyCache.Clear();
8221 ClearFusionContext();
8223 if (!NingenEnabled())
8225 AddMemoryPressure();
8228 SystemDomain::System()->AddToDelayedUnloadList(this, fAsyncExit);
8229 SystemDomain::SetUnloadDomainCleared();
8230 if (m_dwId.m_dwId!=0)
8231 SystemDomain::ReleaseAppDomainId(m_dwId);
8232 #ifdef PROFILING_SUPPORTED
8233 // Always signal profile if present, even when failed.
8235 BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
8237 g_profControlBlock.pProfInterface->AppDomainShutdownFinished((AppDomainID) this, S_OK);
8240 #endif // PROFILING_SUPPORTED
8244 void AppDomain::Close()
8253 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Domain [%d] %#08x %ls is collected.\n",
8254 GetId().m_dwId, this, GetFriendlyNameForLogging()));
8257 #if CHECK_APP_DOMAIN_LEAKS
8258 if (g_pConfig->AppDomainLeaks())
8259 // at this point shouldn't have any non-agile objects in the heap because we finalized all the non-agile ones.
8260 SyncBlockCache::GetSyncBlockCache()->CheckForUnloadedInstances(GetIndex());
8261 #endif // CHECK_APP_DOMAIN_LEAKS
8264 RemoveMemoryPressure();
8266 _ASSERTE(m_cRef>0); //should be alive at this point otherwise iterator can revive us and crash
8268 SystemDomain::LockHolder lh; // Avoid races with AppDomainIterator
8269 SetStage(STAGE_CLOSED);
8272 // CONSIDER: move releasing remoting cache from managed code to here.
8276 void AppDomain::ResetUnloadRequestThread(ADID Id)
8282 PRECONDITION(!IsADUnloadHelperThread());
8287 AppDomainFromIDHolder ad(Id, TRUE);
8288 if(!ad.IsUnloaded() && ad->m_Stage < STAGE_UNLOAD_REQUESTED)
8290 Thread *pThread = ad->GetUnloadRequestThread();
8291 if(pThread==GetThread())
8293 ad->m_dwThreadsStillInAppDomain=(ULONG)-1;
8297 if (pThread->GetUnloadBoundaryFrame() && pThread->IsBeingAbortedForADUnload())
8299 pThread->UnmarkThreadForAbort(Thread::TAR_ADUnload);
8301 ad->GetUnloadRequestThread()->ResetUnloadBoundaryFrame();
8302 pThread->ResetBeginAbortedForADUnload();
8305 ad->SetUnloadRequestThread(NULL);
8311 int g_fADUnloadWorkerOK = -1;
8313 HRESULT AppDomain::UnloadById(ADID dwId, BOOL fSync,BOOL fExceptionsPassThrough)
8317 if(fExceptionsPassThrough) {THROWS;} else {NOTHROW;}
8319 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_TRIGGERS);}
8324 if (dwId==(ADID)DefaultADID)
8325 return COR_E_CANNOTUNLOADAPPDOMAIN;
8327 Thread *pThread = GetThread();
8329 // Finalizer thread can not wait until AD unload is done,
8330 // because AD unload is going to wait for Finalizer Thread.
8331 if (fSync && pThread == FinalizerThread::GetFinalizerThread() &&
8332 !pThread->HasThreadStateNC(Thread::TSNC_RaiseUnloadEvent))
8333 return COR_E_CANNOTUNLOADAPPDOMAIN;
8336 // AD unload helper thread should have been created.
8337 _ASSERTE (g_fADUnloadWorkerOK == 1);
8339 _ASSERTE (!IsADUnloadHelperThread());
8341 BOOL fIsRaisingUnloadEvent = (pThread != NULL && pThread->HasThreadStateNC(Thread::TSNC_RaiseUnloadEvent));
8343 if (fIsRaisingUnloadEvent)
8345 AppDomainFromIDHolder pApp(dwId, TRUE, AppDomainFromIDHolder::SyncType_GC);
8347 if (pApp.IsUnloaded() || ! pApp->CanLoadCode() || pApp->GetId().m_dwId == 0)
8348 return COR_E_APPDOMAINUNLOADED;
8350 pApp->EnableADUnloadWorker();
8356 ADUnloadSinkHolder pSink;
8359 SystemDomain::LockHolder ulh;
8361 AppDomainFromIDHolder pApp(dwId, TRUE, AppDomainFromIDHolder::SyncType_ADLock);
8363 if (pApp.IsUnloaded() || ! pApp->CanLoadCode() || pApp->GetId().m_dwId == 0)
8364 return COR_E_APPDOMAINUNLOADED;
8366 if (g_fADUnloadWorkerOK != 1)
8369 return E_UNEXPECTED;
8374 pApp->EnableADUnloadWorker();
8378 pSink = pApp->PrepareForWaitUnloadCompletion();
8380 pApp->EnableADUnloadWorker();
8382 // release the holders - we don't care anymore if the appdomain is gone
8385 #ifdef FEATURE_TESTHOOKS
8386 if (fExceptionsPassThrough)
8388 CONTRACT_VIOLATION(FaultViolation);
8389 return UnloadWaitNoCatch(dwId,pSink);
8393 return UnloadWait(dwId,pSink);
8396 HRESULT AppDomain::UnloadWait(ADID Id, ADUnloadSink * pSink)
8402 if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_TRIGGERS);}
8409 // IF you ever try to change this to something not using events, please address the fact that
8410 // AppDomain::StopEEAndUnwindThreads relies on that events are used.
8412 pSink->WaitUnloadCompletion();
8414 EX_CATCH_HRESULT(hr);
8417 hr=pSink->GetUnloadResult();
8421 ResetUnloadRequestThread(Id);
8426 #ifdef FEATURE_TESTHOOKS
8427 HRESULT AppDomain::UnloadWaitNoCatch(ADID Id, ADUnloadSink * pSink)
8429 STATIC_CONTRACT_THROWS;
8430 STATIC_CONTRACT_MODE_ANY;
8432 Holder<ADID, DoNothing<ADID>, AppDomain::ResetUnloadRequestThread> resetUnloadHolder(Id);
8434 // IF you ever try to change this to something not using events, please address the fact that
8435 // AppDomain::StopEEAndUnwindThreads relies on that events are used.
8436 pSink->WaitUnloadCompletion();
8438 HRESULT hr = pSink->GetUnloadResult();
8441 resetUnloadHolder.SuppressRelease();
8447 void AppDomain::Unload(BOOL fForceUnload)
8454 INJECT_FAULT(COMPlusThrowOM(););
8458 #ifdef FEATURE_MULTICOREJIT
8460 // Avoid profiling file is partially written in ASP.net scenarios, call it earlier
8461 GetMulticoreJitManager().StopProfile(true);
8465 Thread *pThread = GetThread();
8468 if (! fForceUnload && !g_pConfig->AppDomainUnload())
8471 EPolicyAction action;
8472 EClrOperation operation;
8473 if (!IsRudeUnload())
8475 operation = OPR_AppDomainUnload;
8479 operation = OPR_AppDomainRudeUnload;
8481 action = GetEEPolicy()->GetDefaultAction(operation,NULL);
8482 GetEEPolicy()->NotifyHostOnDefaultAction(operation,action);
8486 case eUnloadAppDomain:
8488 case eRudeUnloadAppDomain:
8492 case eFastExitProcess:
8493 case eRudeExitProcess:
8494 case eDisableRuntime:
8495 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_ADUNLOAD);
8496 _ASSERTE (!"Should not get here");
8502 #if (defined(_DEBUG) || defined(BREAK_ON_UNLOAD) || defined(AD_LOG_MEMORY) || defined(AD_SNAPSHOT))
8503 static int unloadCount = 0;
8506 #ifdef AD_LOG_MEMORY
8509 static int logMemory = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADLogMemory);
8510 typedef void (__cdecl *LogItFcn) ( int );
8511 static LogItFcn pLogIt = NULL;
8513 if (logMemory && ! pLogIt)
8515 HMODULE hMod = CLRLoadLibrary(W("mpdh.dll"));
8518 pLogIt = (LogItFcn)GetProcAddress(hMod, "logIt");
8527 #endif // AD_LOG_MEMORY
8529 if (IsDefaultDomain() && !IsSingleAppDomain())
8530 COMPlusThrow(kCannotUnloadAppDomainException, IDS_EE_ADUNLOAD_DEFAULT);
8532 _ASSERTE(CanUnload());
8534 if (pThread == FinalizerThread::GetFinalizerThread() || GetUnloadRequestThread() == FinalizerThread::GetFinalizerThread())
8535 COMPlusThrow(kCannotUnloadAppDomainException, IDS_EE_ADUNLOAD_IN_FINALIZER);
8537 _ASSERTE(! SystemDomain::AppDomainBeingUnloaded());
8539 // should not be running in this AD because unload spawned thread in default domain
8540 if (!NingenEnabled())
8542 _ASSERTE(!pThread->IsRunningIn(this, NULL));
8546 #ifdef APPDOMAIN_STATE
8547 _ASSERTE_ALL_BUILDS("clr/src/VM/AppDomain.cpp", pThread->GetDomain()->IsDefaultDomain());
8550 LOG((LF_APPDOMAIN | LF_CORDB, LL_INFO10, "AppDomain::Unloading domain [%d] %#08x %ls\n", GetId().m_dwId, this, GetFriendlyName()));
8552 STRESS_LOG3 (LF_APPDOMAIN, LL_INFO100, "Unload domain [%d, %d] %p\n", GetId().m_dwId, GetIndex().m_dwIndex, this);
8554 UnloadHolder hold(this);
8556 SystemDomain::System()->SetUnloadRequestingThread(GetUnloadRequestThread());
8557 SystemDomain::System()->SetUnloadingThread(pThread);
8561 static int dumpSB = -1;
8564 dumpSB = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADDumpSB);
8568 LogSpewAlways("Starting unload %3.3d\n", unloadCount);
8569 DumpSyncBlockCache();
8573 BOOL bForceGC=m_bForceGCOnUnload;
8575 #ifdef AD_LOG_MEMORY
8578 #endif // AD_LOG_MEMORY
8581 static int takeSnapShot = -1;
8583 if (takeSnapShot == -1)
8584 takeSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeSnapShot);
8588 #endif // AD_SNAPSHOT
8594 static int cfgForceGC = -1;
8596 if (cfgForceGC == -1)
8597 cfgForceGC =!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_ADULazyMemoryRelease);
8599 bForceGC=bForceGC||cfgForceGC;
8600 AppDomainRefHolder This(this);
8603 // Do the actual unloading
8605 // We do not want other threads to abort the current one.
8606 ThreadPreventAsyncHolder preventAsync;
8607 Exit(TRUE, !bForceGC);
8611 GCHeapUtilities::GetGCHeap()->GarbageCollect();
8612 FinalizerThread::FinalizerThreadWait();
8613 SetStage(STAGE_COLLECTED);
8617 #ifdef AD_LOG_MEMORY
8621 pLogIt(unloadCount);
8623 #endif // AD_LOG_MEMORY
8629 sprintf_s(buffer, _countof(buffer), "vadump -p %d -o > vadump.%d", GetCurrentProcessId(), unloadCount);
8631 sprintf_s(buffer, _countof(buffer), "umdh -p:%d -d -i:1 -f:umdh.%d", GetCurrentProcessId(), unloadCount);
8633 int takeDHSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeDHSnapShot);
8636 sprintf_s(buffer, _countof(buffer), "dh -p %d -s -g -h -b -f dh.%d", GetCurrentProcessId(), unloadCount);
8640 #endif // AD_SNAPSHOT
8645 // do extra finalizer wait to remove any leftover sb entries
8646 FinalizerThread::FinalizerThreadWait();
8647 GCHeapUtilities::GetGCHeap()->GarbageCollect();
8648 FinalizerThread::FinalizerThreadWait();
8649 LogSpewAlways("Done unload %3.3d\n", unloadCount);
8650 DumpSyncBlockCache();
8653 swprintf_s(buffer, NumItems(buffer), W("DumpSB.%d"), unloadCount);
8654 _ASSERTE(WszMoveFileEx(W("COMPLUS.LOG"), buffer, MOVEFILE_REPLACE_EXISTING));
8655 // this will open a new file
8661 void AppDomain::ExceptionUnwind(Frame *pFrame)
8665 DISABLED(GC_TRIGGERS); // EEResourceException
8666 DISABLED(THROWS); // EEResourceException
8671 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind for %8.8x\n", pFrame));
8673 printf("%x AppDomain::ExceptionUnwind for %8.8p\n", GetThread()->GetThreadId(), pFrame);
8675 Thread *pThread = GetThread();
8678 if (! pThread->ShouldChangeAbortToUnload(pFrame))
8680 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind: not first transition or abort\n"));
8684 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::ExceptionUnwind: changing to unload\n"));
8687 OBJECTREF throwable = NULL;
8688 EEResourceException e(kAppDomainUnloadedException, W("Remoting_AppDomainUnloaded_ThreadUnwound"));
8689 throwable = e.GetThrowable();
8691 // reset the exception to an AppDomainUnloadedException
8692 if (throwable != NULL)
8694 GetThread()->SafeSetThrowables(throwable);
8698 BOOL AppDomain::StopEEAndUnwindThreads(unsigned int retryCount, BOOL *pFMarkUnloadRequestThread)
8709 Thread *pThread = NULL;
8710 DWORD nThreadsNeedMoreWork=0;
8711 if (retryCount != (unsigned int)-1 && retryCount < g_pConfig->AppDomainUnloadRetryCount())
8713 Thread *pCurThread = GetThread();
8714 if (pCurThread->CatchAtSafePoint())
8715 pCurThread->PulseGCMode();
8718 // We know which thread is not in the domain now. We just need to
8719 // work on those threads. We do not need to suspend the runtime.
8720 ThreadStoreLockHolder tsl;
8722 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8724 if (pThread == pCurThread)
8729 if (pThread == FinalizerThread::GetFinalizerThread())
8734 if (pThread->GetUnloadBoundaryFrame() == NULL)
8739 // A thread may have UnloadBoundaryFrame set if
8740 // 1. Being unloaded by AD unload helper thread
8741 // 2. Escalation from OOM or SO triggers AD unload
8742 // Here we only need to work on threads that are in the domain. If we work on other threads,
8743 // those threads may be stucked in a finally, and we will not be able to escalate for them,
8744 // therefore AD unload is blocked.
8745 if (pThread->IsBeingAbortedForADUnload() ||
8746 pThread == SystemDomain::System()->GetUnloadRequestingThread())
8748 nThreadsNeedMoreWork++;
8751 if (!(IsRudeUnload() ||
8752 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft())))
8757 if ((pThread == SystemDomain::System()->GetUnloadRequestingThread()) && *pFMarkUnloadRequestThread)
8759 // Mark thread for abortion only once; later on interrupt only
8760 *pFMarkUnloadRequestThread = FALSE;
8761 pThread->SetAbortRequest(m_fRudeUnload? EEPolicy::TA_Rude : EEPolicy::TA_V1Compatible);
8765 if (pThread->m_State & Thread::TS_Interruptible)
8767 pThread->UserInterrupt(Thread::TI_Abort);
8771 if (pThread->PreemptiveGCDisabledOther())
8773 #if defined(FEATURE_HIJACK) && !defined(PLATFORM_UNIX)
8774 Thread::SuspendThreadResult str = pThread->SuspendThread();
8775 if (str == Thread::STR_Success)
8777 if (pThread->PreemptiveGCDisabledOther() &&
8778 (!pThread->IsAbortInitiated() || pThread->IsRudeAbort()))
8780 pThread->HandleJITCaseForAbort();
8782 pThread->ResumeThread();
8787 } // ThreadStoreLockHolder
8789 m_dwThreadsStillInAppDomain=nThreadsNeedMoreWork;
8790 return !nThreadsNeedMoreWork;
8793 // For now piggyback on the GC's suspend EE mechanism
8794 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
8796 // <TODO>@todo: what to do with any threads that didn't stop?</TODO>
8797 _ASSERTE(ThreadStore::s_pThreadStore->DbgBackgroundThreadCount() > 0);
8800 int totalADCount = 0;
8801 int finalizerADCount = 0;
8804 RuntimeExceptionKind reKind = kLastException;
8806 SmallStackSString ssThreadId;
8808 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8810 // we already checked that we're not running in the unload domain
8811 if (pThread == GetThread())
8817 void PrintStackTraceWithADToLog(Thread *pThread);
8818 if (LoggingOn(LF_APPDOMAIN, LL_INFO100)) {
8819 LOG((LF_APPDOMAIN, LL_INFO100, "\nStackTrace for %x\n", pThread->GetThreadId()));
8820 PrintStackTraceWithADToLog(pThread);
8824 Frame *pFrame = pThread->GetFirstTransitionInto(this, &count);
8826 _ASSERTE(count == 0);
8827 if (pThread->IsBeingAbortedForADUnload())
8829 pThread->ResetBeginAbortedForADUnload();
8834 if (pThread != FinalizerThread::GetFinalizerThread())
8836 totalADCount += count;
8837 nThreadsNeedMoreWork++;
8838 pThread->SetUnloadBoundaryFrame(pFrame);
8842 finalizerADCount = count;
8845 // don't setup the exception info for the unloading thread unless it's the last one in
8846 if (retryCount != ((unsigned int) -1) && retryCount > g_pConfig->AppDomainUnloadRetryCount() && reKind == kLastException &&
8847 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft()))
8849 #ifdef AD_BREAK_ON_CANNOT_UNLOAD
8850 static int breakOnCannotUnload = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADBreakOnCannotUnload);
8851 if (breakOnCannotUnload)
8852 _ASSERTE(!"Cannot unload AD");
8853 #endif // AD_BREAK_ON_CANNOT_UNLOAD
8854 reKind = kCannotUnloadAppDomainException;
8855 resId = IDS_EE_ADUNLOAD_CANT_UNWIND_THREAD;
8856 ssThreadId.Printf(W("%x"), pThread->GetThreadId());
8857 STRESS_LOG2(LF_APPDOMAIN, LL_INFO10, "AppDomain::UnwindThreads cannot stop thread %x with %d transitions\n", pThread->GetThreadId(), count);
8858 // don't break out of this early or the assert totalADCount == (int)m_dwThreadEnterCount below will fire
8859 // it's better to chew a little extra time here and make sure our counts are consistent
8861 // only abort the thread requesting the unload if it's the last one in, that way it will get
8862 // notification that the unload failed for some other thread not being aborted. And don't abort
8863 // the finalizer thread - let it finish it's work as it's allowed to be in there. If it won't finish,
8864 // then we will eventually get a CannotUnloadException on it.
8866 if (pThread != FinalizerThread::GetFinalizerThread() &&
8867 // If the domain is rudely unloaded, we will unwind the requesting thread out
8868 // Rude unload is going to succeed, or escalated to disable runtime or higher.
8870 (pThread != SystemDomain::System()->GetUnloadRequestingThread() || OnlyOneThreadLeft())
8875 STRESS_LOG2(LF_APPDOMAIN, LL_INFO100, "AppDomain::UnwindThreads stopping %x with %d transitions\n", pThread->GetThreadId(), count);
8876 LOG((LF_APPDOMAIN, LL_INFO100, "AppDomain::UnwindThreads stopping %x with %d transitions\n", pThread->GetThreadId(), count));
8878 printf("AppDomain::UnwindThreads %x stopping %x with first frame %8.8p\n", GetThread()->GetThreadId(), pThread->GetThreadId(), pFrame);
8880 if (pThread == SystemDomain::System()->GetUnloadRequestingThread())
8882 // Mark thread for abortion only once; later on interrupt only
8883 *pFMarkUnloadRequestThread = FALSE;
8885 pThread->SetAbortRequest(m_fRudeUnload? EEPolicy::TA_Rude : EEPolicy::TA_V1Compatible);
8887 TESTHOOKCALL(UnwindingThreads(GetId().m_dwId)) ;
8889 _ASSERTE(totalADCount + finalizerADCount == (int)m_dwThreadEnterCount);
8891 //@TODO: This is intended to catch a stress bug. Remove when no longer needed.
8892 if (totalADCount + finalizerADCount != (int)m_dwThreadEnterCount)
8893 FreeBuildDebugBreak();
8895 // if our count did get messed up, set it to whatever count we actually found in the domain to avoid looping
8896 // or other problems related to incorrect count. This is very much a bug if this happens - a thread should always
8897 // exit the domain gracefully.
8898 // m_dwThreadEnterCount = totalADCount;
8900 if (reKind != kLastException)
8903 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
8905 if (pThread->IsBeingAbortedForADUnload())
8907 pThread->ResetBeginAbortedForADUnload();
8912 // CommonTripThread will handle the abort for any threads that we've marked
8913 ThreadSuspend::RestartEE(FALSE, TRUE);
8914 if (reKind != kLastException)
8915 COMPlusThrow(reKind, resId, ssThreadId.GetUnicode());
8917 _ASSERTE((totalADCount==0 && nThreadsNeedMoreWork==0) ||(totalADCount!=0 && nThreadsNeedMoreWork!=0));
8919 m_dwThreadsStillInAppDomain=nThreadsNeedMoreWork;
8920 return (totalADCount == 0);
8923 void AppDomain::UnwindThreads()
8925 // This function should guarantee appdomain
8926 // consistency even if it fails. Everything that is going
8927 // to make the appdomain impossible to reenter
8928 // should be factored out
8930 // <TODO>@todo: need real synchronization here!!!</TODO>
8939 int retryCount = -1;
8940 m_dwThreadsStillInAppDomain=(ULONG)-1;
8941 ULONGLONG startTime = CLRGetTickCount64();
8943 if (GetEEPolicy()->GetDefaultAction(OPR_AppDomainUnload, NULL) == eRudeUnloadAppDomain &&
8946 GetEEPolicy()->NotifyHostOnDefaultAction(OPR_AppDomainUnload, eRudeUnloadAppDomain);
8950 // Force threads to go through slow path during AD unload.
8951 TSSuspendHolder shTrap;
8953 BOOL fCurrentUnloadMode = IsRudeUnload();
8954 BOOL fMarkUnloadRequestThread = TRUE;
8956 // now wait for all the threads running in our AD to get out
8959 DWORD timeout = GetEEPolicy()->GetTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload);
8960 EPolicyAction action = GetEEPolicy()->GetActionOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, NULL);
8961 if (timeout != INFINITE && action > eUnloadAppDomain) {
8962 // Escalation policy specified.
8963 ULONGLONG curTime = CLRGetTickCount64();
8964 ULONGLONG elapseTime = curTime - startTime;
8965 if (elapseTime > timeout)
8970 case eRudeUnloadAppDomain:
8971 GetEEPolicy()->NotifyHostOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, action);
8973 STRESS_LOG1(LF_APPDOMAIN, LL_INFO100,"Escalating to RADU, adid=%d",GetId().m_dwId);
8976 case eFastExitProcess:
8977 case eRudeExitProcess:
8978 case eDisableRuntime:
8979 GetEEPolicy()->NotifyHostOnTimeout(m_fRudeUnload?OPR_AppDomainRudeUnload : OPR_AppDomainUnload, action);
8980 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_TIMEOUT);
8981 _ASSERTE (!"Should not reach here");
8989 if (LoggingOn(LF_APPDOMAIN, LL_INFO100))
8990 DumpADThreadTrack();
8992 BOOL fNextUnloadMode = IsRudeUnload();
8993 if (fCurrentUnloadMode != fNextUnloadMode)
8995 // We have changed from normal unload to rude unload. We need to mark the thread
8996 // with RudeAbort, but we can only do this safely if the runtime is suspended.
8997 fCurrentUnloadMode = fNextUnloadMode;
9000 if (StopEEAndUnwindThreads(retryCount, &fMarkUnloadRequestThread))
9002 if (timeout != INFINITE)
9004 // Turn off the timeout used by AD.
9009 // GCStress takes a long time to unwind, due to expensive creation of
9010 // a threadabort exception.
9011 if (!GCStress<cfg_any>::IsEnabled())
9013 LOG((LF_APPDOMAIN, LL_INFO10, "AppDomain::UnwindThreads iteration %d waiting on thread count %d\n", retryCount, m_dwThreadEnterCount));
9015 printf("AppDomain::UnwindThreads iteration %d waiting on thread count %d\n", retryCount, m_dwThreadEnterCount);
9019 if (m_dwThreadEnterCount != 0)
9022 GetThread()->UserSleep(20);
9024 GetThread()->UserSleep(10);
9031 void AppDomain::ClearGCHandles()
9041 SetStage(STAGE_HANDLETABLE_NOACCESS);
9043 GCHeapUtilities::GetGCHeap()->WaitUntilConcurrentGCComplete();
9045 // Keep async pin handles alive by moving them to default domain
9046 HandleAsyncPinHandles();
9048 // Remove our handle store as a source of GC roots
9049 m_handleStore->Uproot();
9052 // When an AD is unloaded, we will release all objects in this AD.
9053 // If a future asynchronous operation, like io completion port function,
9054 // we need to keep the memory space fixed so that the gc heap is not corrupted.
9055 void AppDomain::HandleAsyncPinHandles()
9065 IGCHandleStore *pBucket = m_handleStore;
9067 // IO completion port picks IO job using FIFO. Here is how we know which AsyncPinHandle can be freed.
9068 // 1. We mark all non-pending AsyncPinHandle with READYTOCLEAN.
9069 // 2. We queue a dump Overlapped to the IO completion as a marker.
9070 // 3. When the Overlapped is picked up by completion port, we wait until all previous IO jobs are processed.
9071 // 4. Then we can delete all AsyncPinHandle marked with READYTOCLEAN.
9072 IGCHandleStore *pBucketInDefault = SystemDomain::System()->DefaultDomain()->m_handleStore;
9074 pBucket->RelocateAsyncPinnedHandles(pBucketInDefault);
9076 OverlappedDataObject::RequestCleanup();
9079 void AppDomain::ClearGCRoots()
9089 Thread *pThread = NULL;
9090 ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
9092 // Tell the JIT managers to delete any entries in their structures. All the cooperative mode threads are stopped at
9093 // this point, so only need to synchronize the preemptive mode threads.
9094 ExecutionManager::Unload(GetLoaderAllocator());
9096 while ((pThread = ThreadStore::GetAllThreadList(pThread, 0, 0)) != NULL)
9098 // Delete the thread local static store
9099 pThread->DeleteThreadStaticData(this);
9101 // <TODO>@TODO: A pre-allocated AppDomainUnloaded exception might be better.</TODO>
9102 if (m_handleStore->ContainsHandle(pThread->m_LastThrownObjectHandle))
9104 // Never delete a handle to a preallocated exception object.
9105 if (!CLRException::IsPreallocatedExceptionHandle(pThread->m_LastThrownObjectHandle))
9107 DestroyHandle(pThread->m_LastThrownObjectHandle);
9110 pThread->m_LastThrownObjectHandle = NULL;
9113 // Clear out the exceptions objects held by a thread.
9114 pThread->GetExceptionState()->ClearThrowablesForUnload(m_handleStore);
9117 //delete them while we still have the runtime suspended
9118 // This must be deleted before the loader heaps are deleted.
9119 if (m_pMarshalingData != NULL)
9121 delete m_pMarshalingData;
9122 m_pMarshalingData = NULL;
9125 if (m_pLargeHeapHandleTable != NULL)
9127 delete m_pLargeHeapHandleTable;
9128 m_pLargeHeapHandleTable = NULL;
9131 ThreadSuspend::RestartEE(FALSE, TRUE);
9136 void AppDomain::TrackADThreadEnter(Thread *pThread, Frame *pFrame)
9143 PRECONDITION(CheckPointer(pThread));
9144 PRECONDITION(pFrame != (Frame*)(size_t) INVALID_POINTER_CD);
9148 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9150 if (m_pThreadTrackInfoList == NULL)
9151 m_pThreadTrackInfoList = new (nothrow) ThreadTrackInfoList;
9152 // If we don't assert here, we will AV in the for loop below
9153 _ASSERTE(m_pThreadTrackInfoList);
9155 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9157 ThreadTrackInfo *pTrack = NULL;
9159 for (i=0; i < pTrackList->Count(); i++) {
9160 if ((*(pTrackList->Get(i)))->pThread == pThread) {
9161 pTrack = *(pTrackList->Get(i));
9166 pTrack = new (nothrow) ThreadTrackInfo;
9167 // If we don't assert here, we will AV in the for loop below.
9169 pTrack->pThread = pThread;
9170 ThreadTrackInfo **pSlot = pTrackList->Append();
9174 InterlockedIncrement((LONG*)&m_dwThreadEnterCount);
9178 pSlot = pTrack->frameStack.Insert(0);
9182 for (i=0; i < pTrackList->Count(); i++)
9183 totThreads += (*(pTrackList->Get(i)))->frameStack.Count();
9184 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9186 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9190 void AppDomain::TrackADThreadExit(Thread *pThread, Frame *pFrame)
9194 if (GetThread()) {MODE_COOPERATIVE;}
9200 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9202 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9203 _ASSERTE(pTrackList);
9204 ThreadTrackInfo *pTrack = NULL;
9206 for (i=0; i < pTrackList->Count(); i++)
9208 if ((*(pTrackList->Get(i)))->pThread == pThread)
9210 pTrack = *(pTrackList->Get(i));
9215 _ASSERTE(*(pTrack->frameStack.Get(0)) == pFrame);
9216 pTrack->frameStack.Delete(0);
9217 InterlockedDecrement((LONG*)&m_dwThreadEnterCount);
9220 for (i=0; i < pTrackList->Count(); i++)
9221 totThreads += (*(pTrackList->Get(i)))->frameStack.Count();
9222 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9224 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9227 void AppDomain::DumpADThreadTrack()
9237 while (FastInterlockCompareExchange((LONG*)&m_TrackSpinLock, 1, 0) != 0)
9239 ThreadTrackInfoList *pTrackList= m_pThreadTrackInfoList;
9244 LOG((LF_APPDOMAIN, LL_INFO10000, "\nThread dump of %d threads for [%d] %#08x %S\n",
9245 m_dwThreadEnterCount, GetId().m_dwId, this, GetFriendlyNameForLogging()));
9247 for (int i=0; i < pTrackList->Count(); i++)
9249 ThreadTrackInfo *pTrack = *(pTrackList->Get(i));
9250 if (pTrack->frameStack.Count()==0)
9252 LOG((LF_APPDOMAIN, LL_INFO100, " ADEnterCount for %x is %d\n", pTrack->pThread->GetThreadId(), pTrack->frameStack.Count()));
9253 totThreads += pTrack->frameStack.Count();
9254 for (int j=0; j < pTrack->frameStack.Count(); j++)
9255 LOG((LF_APPDOMAIN, LL_INFO100, " frame %8.8x\n", *(pTrack->frameStack.Get(j))));
9257 _ASSERTE(totThreads == (int)m_dwThreadEnterCount);
9260 InterlockedExchange((LONG*)&m_TrackSpinLock, 0);
9265 #endif // CROSSGEN_COMPILE
9267 void *SharedDomain::operator new(size_t size, void *pInPlace)
9269 LIMITED_METHOD_CONTRACT;
9273 void SharedDomain::operator delete(void *pMem)
9275 LIMITED_METHOD_CONTRACT;
9276 // Do nothing - new() was in-place
9280 void SharedDomain::Attach()
9287 INJECT_FAULT(COMPlusThrowOM(););
9291 // Create the global SharedDomain and initialize it.
9292 m_pSharedDomain = new (&g_pSharedDomainMemory[0]) SharedDomain();
9293 SystemDomain::GetGlobalLoaderAllocator()->m_pDomain = m_pSharedDomain;
9294 // This cannot fail since g_pSharedDomainMemory is a static array.
9295 CONSISTENCY_CHECK(CheckPointer(m_pSharedDomain));
9297 LOG((LF_CLASSLOADER,
9299 "Created shared domain at %p\n",
9302 // We need to initialize the memory pools etc. for the system domain.
9303 m_pSharedDomain->Init(); // Setup the memory heaps
9305 // allocate a Virtual Call Stub Manager for the shared domain
9306 m_pSharedDomain->InitVSD();
9309 #ifndef CROSSGEN_COMPILE
9310 void SharedDomain::Detach()
9312 if (m_pSharedDomain)
9314 m_pSharedDomain->Terminate();
9315 delete m_pSharedDomain;
9316 m_pSharedDomain = NULL;
9319 #endif // CROSSGEN_COMPILE
9321 #endif // !DACCESS_COMPILE
9323 SharedDomain *SharedDomain::GetDomain()
9325 LIMITED_METHOD_DAC_CONTRACT;
9327 return m_pSharedDomain;
9330 #ifndef DACCESS_COMPILE
9332 #define INITIAL_ASSEMBLY_MAP_SIZE 17
9333 void SharedDomain::Init()
9340 INJECT_FAULT(COMPlusThrowOM(););
9346 #ifdef FEATURE_LOADER_OPTIMIZATION
9347 m_FileCreateLock.Init(CrstSharedAssemblyCreate, CRST_DEFAULT,TRUE);
9349 LockOwner lock = { &m_DomainCrst, IsOwnerOfCrst };
9350 m_assemblyMap.Init(INITIAL_ASSEMBLY_MAP_SIZE, CompareSharedAssembly, TRUE, &lock);
9351 #endif // FEATURE_LOADER_OPTIMIZATION
9353 ETW::LoaderLog::DomainLoad(this);
9356 #ifndef CROSSGEN_COMPILE
9357 void SharedDomain::Terminate()
9359 // make sure we delete the StringLiteralMap before unloading
9360 // the asemblies since the string literal map entries can
9361 // point to metadata string literals.
9362 GetLoaderAllocator()->CleanupStringLiteralMap();
9364 #ifdef FEATURE_LOADER_OPTIMIZATION
9365 PtrHashMap::PtrIterator i = m_assemblyMap.begin();
9369 Assembly *pAssembly = (Assembly*) i.GetValue();
9374 ListLockEntry* pElement;
9375 pElement = m_FileCreateLock.Pop(TRUE);
9378 #ifdef STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
9379 _ASSERTE (dbg_fDrasticShutdown || g_fInControlC);
9382 pElement = (FileLoadLock*) m_FileCreateLock.Pop(TRUE);
9384 m_FileCreateLock.Destroy();
9385 #endif // FEATURE_LOADER_OPTIMIZATION
9386 BaseDomain::Terminate();
9388 #endif // CROSSGEN_COMPILE
9392 #ifdef FEATURE_LOADER_OPTIMIZATION
9394 BOOL SharedDomain::CompareSharedAssembly(UPTR u1, UPTR u2)
9404 // This is the input to the lookup
9405 SharedAssemblyLocator *pLocator = (SharedAssemblyLocator *) (u1<<1);
9407 // This is the value stored in the table
9408 Assembly *pAssembly = (Assembly *) u2;
9409 if (pLocator->GetType()==SharedAssemblyLocator::DOMAINASSEMBLY)
9411 if (!pAssembly->GetManifestFile()->Equals(pLocator->GetDomainAssembly()->GetFile()))
9414 return pAssembly->CanBeShared(pLocator->GetDomainAssembly());
9417 if (pLocator->GetType()==SharedAssemblyLocator::PEASSEMBLY)
9418 return pAssembly->GetManifestFile()->Equals(pLocator->GetPEAssembly());
9420 if (pLocator->GetType()==SharedAssemblyLocator::PEASSEMBLYEXACT)
9421 return pAssembly->GetManifestFile() == pLocator->GetPEAssembly();
9422 _ASSERTE(!"Unexpected type of assembly locator");
9426 DWORD SharedAssemblyLocator::Hash()
9433 INJECT_FAULT(COMPlusThrowOM(););
9436 if (m_type==DOMAINASSEMBLY)
9437 return GetDomainAssembly()->HashIdentity();
9438 if (m_type==PEASSEMBLY||m_type==PEASSEMBLYEXACT)
9439 return GetPEAssembly()->HashIdentity();
9440 _ASSERTE(!"Unexpected type of assembly locator");
9444 Assembly * SharedDomain::FindShareableAssembly(SharedAssemblyLocator * pLocator)
9451 INJECT_FAULT(COMPlusThrowOM(););
9455 Assembly * match= (Assembly *) m_assemblyMap.LookupValue(pLocator->Hash(), pLocator);
9456 if (match != (Assembly *) INVALIDENTRY)
9462 SIZE_T SharedDomain::GetShareableAssemblyCount()
9464 LIMITED_METHOD_CONTRACT;
9466 return m_assemblyMap.GetCount();
9469 void SharedDomain::AddShareableAssembly(Assembly * pAssembly)
9476 INJECT_FAULT(COMPlusThrowOM(););
9480 // We have a lock on the file. There should be no races to add the same assembly.
9483 LockHolder holder(this);
9487 pAssembly->SetIsTenured();
9488 m_assemblyMap.InsertValue(pAssembly->HashIdentity(), pAssembly);
9492 // There was an error adding the assembly to the assembly hash (probably an OOM),
9493 // so we need to unset the tenured bit so that correct cleanup can happen.
9494 pAssembly->UnsetIsTenured();
9499 LOG((LF_CODESHARING,
9501 "Successfully added shareable assembly \"%s\".\n",
9502 pAssembly->GetManifestFile()->GetSimpleName()));
9505 #endif // FEATURE_LOADER_OPTIMIZATION
9506 #endif // !DACCESS_COMPILE
9508 DWORD DomainLocalModule::GetClassFlags(MethodTable* pMT, DWORD iClassIndex /*=(DWORD)-1*/)
9516 { // SO tolerance exception for debug-only assertion.
9517 CONTRACT_VIOLATION(SOToleranceViolation);
9518 CONSISTENCY_CHECK(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9521 if (pMT->IsDynamicStatics())
9523 _ASSERTE(!pMT->ContainsGenericVariables());
9524 DWORD dynamicClassID = pMT->GetModuleDynamicEntryID();
9525 if(m_aDynamicEntries <= dynamicClassID)
9527 return (m_pDynamicClassTable[dynamicClassID].m_dwFlags);
9531 if (iClassIndex == (DWORD)-1)
9532 iClassIndex = pMT->GetClassIndex();
9533 return GetPrecomputedStaticsClassData()[iClassIndex];
9537 #ifndef DACCESS_COMPILE
9539 void DomainLocalModule::SetClassInitialized(MethodTable* pMT)
9549 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9551 _ASSERTE(!IsClassInitialized(pMT));
9552 _ASSERTE(!IsClassInitError(pMT));
9554 SetClassFlags(pMT, ClassInitFlags::INITIALIZED_FLAG);
9557 void DomainLocalModule::SetClassInitError(MethodTable* pMT)
9559 WRAPPER_NO_CONTRACT;
9561 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9563 SetClassFlags(pMT, ClassInitFlags::ERROR_FLAG);
9566 void DomainLocalModule::SetClassFlags(MethodTable* pMT, DWORD dwFlags)
9571 PRECONDITION(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9572 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9573 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9576 if (pMT->IsDynamicStatics())
9578 _ASSERTE(!pMT->ContainsGenericVariables());
9579 DWORD dwID = pMT->GetModuleDynamicEntryID();
9580 EnsureDynamicClassIndex(dwID);
9581 m_pDynamicClassTable[dwID].m_dwFlags |= dwFlags;
9585 GetPrecomputedStaticsClassData()[pMT->GetClassIndex()] |= dwFlags;
9589 void DomainLocalModule::EnsureDynamicClassIndex(DWORD dwID)
9596 INJECT_FAULT(COMPlusThrowOM(););
9597 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9598 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9602 if (dwID < m_aDynamicEntries)
9604 _ASSERTE(m_pDynamicClassTable.Load() != NULL);
9608 SIZE_T aDynamicEntries = max(16, m_aDynamicEntries.Load());
9609 while (aDynamicEntries <= dwID)
9611 aDynamicEntries *= 2;
9614 DynamicClassInfo* pNewDynamicClassTable;
9615 pNewDynamicClassTable = (DynamicClassInfo*)
9616 (void*)GetDomainFile()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(
9617 S_SIZE_T(sizeof(DynamicClassInfo)) * S_SIZE_T(aDynamicEntries));
9619 memcpy(pNewDynamicClassTable, m_pDynamicClassTable, sizeof(DynamicClassInfo) * m_aDynamicEntries);
9621 // Note: Memory allocated on loader heap is zero filled
9622 // memset(pNewDynamicClassTable + m_aDynamicEntries, 0, (aDynamicEntries - m_aDynamicEntries) * sizeof(DynamicClassInfo));
9624 _ASSERTE(m_aDynamicEntries%2 == 0);
9626 // Commit new dynamic table. The lock-free helpers depend on the order.
9628 m_pDynamicClassTable = pNewDynamicClassTable;
9630 m_aDynamicEntries = aDynamicEntries;
9633 #ifndef CROSSGEN_COMPILE
9634 void DomainLocalModule::AllocateDynamicClass(MethodTable *pMT)
9640 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9641 PRECONDITION(GetDomainFile()->GetAppDomain()->OwnDomainLocalBlockLock());
9645 _ASSERTE(!pMT->ContainsGenericVariables());
9646 _ASSERTE(!pMT->IsSharedByGenericInstantiations());
9647 _ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
9648 _ASSERTE(pMT->IsDynamicStatics());
9650 DWORD dynamicEntryIDIndex = pMT->GetModuleDynamicEntryID();
9652 EnsureDynamicClassIndex(dynamicEntryIDIndex);
9654 _ASSERTE(m_aDynamicEntries > dynamicEntryIDIndex);
9656 EEClass *pClass = pMT->GetClass();
9658 DWORD dwStaticBytes = pClass->GetNonGCRegularStaticFieldBytes();
9659 DWORD dwNumHandleStatics = pClass->GetNumHandleRegularStatics();
9661 _ASSERTE(!IsClassAllocated(pMT));
9662 _ASSERTE(!IsClassInitialized(pMT));
9663 _ASSERTE(!IsClassInitError(pMT));
9665 DynamicEntry *pDynamicStatics = m_pDynamicClassTable[dynamicEntryIDIndex].m_pDynamicEntry;
9667 // We need this check because maybe a class had a cctor but no statics
9668 if (dwStaticBytes > 0 || dwNumHandleStatics > 0)
9670 if (pDynamicStatics == NULL)
9672 LoaderHeap * pLoaderAllocator = GetDomainFile()->GetLoaderAllocator()->GetHighFrequencyHeap();
9674 if (pMT->Collectible())
9676 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocMem(S_SIZE_T(sizeof(CollectibleDynamicEntry)));
9680 SIZE_T dynamicEntrySize = DynamicEntry::GetOffsetOfDataBlob() + dwStaticBytes;
9682 #ifdef FEATURE_64BIT_ALIGNMENT
9683 // Allocate memory with extra alignment only if it is really necessary
9684 if (dwStaticBytes >= MAX_PRIMITIVE_FIELD_SIZE)
9686 static_assert_no_msg(sizeof(NormalDynamicEntry) % MAX_PRIMITIVE_FIELD_SIZE == 0);
9687 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocAlignedMem(dynamicEntrySize, MAX_PRIMITIVE_FIELD_SIZE);
9691 pDynamicStatics = (DynamicEntry*)(void*)pLoaderAllocator->AllocMem(S_SIZE_T(dynamicEntrySize));
9694 // Note: Memory allocated on loader heap is zero filled
9696 m_pDynamicClassTable[dynamicEntryIDIndex].m_pDynamicEntry = pDynamicStatics;
9699 if (pMT->Collectible() && (dwStaticBytes != 0))
9702 OBJECTREF nongcStaticsArray = NULL;
9703 GCPROTECT_BEGIN(nongcStaticsArray);
9704 #ifdef FEATURE_64BIT_ALIGNMENT
9705 // Allocate memory with extra alignment only if it is really necessary
9706 if (dwStaticBytes >= MAX_PRIMITIVE_FIELD_SIZE)
9707 nongcStaticsArray = AllocatePrimitiveArray(ELEMENT_TYPE_I8, (dwStaticBytes + (sizeof(CLR_I8)-1)) / (sizeof(CLR_I8)));
9710 nongcStaticsArray = AllocatePrimitiveArray(ELEMENT_TYPE_U1, dwStaticBytes);
9711 ((CollectibleDynamicEntry *)pDynamicStatics)->m_hNonGCStatics = GetDomainFile()->GetModule()->GetLoaderAllocator()->AllocateHandle(nongcStaticsArray);
9714 if (dwNumHandleStatics > 0)
9716 if (!pMT->Collectible())
9718 GetAppDomain()->AllocateStaticFieldObjRefPtrs(dwNumHandleStatics,
9719 &((NormalDynamicEntry *)pDynamicStatics)->m_pGCStatics);
9724 OBJECTREF gcStaticsArray = NULL;
9725 GCPROTECT_BEGIN(gcStaticsArray);
9726 gcStaticsArray = AllocateObjectArray(dwNumHandleStatics, g_pObjectClass);
9727 ((CollectibleDynamicEntry *)pDynamicStatics)->m_hGCStatics = GetDomainFile()->GetModule()->GetLoaderAllocator()->AllocateHandle(gcStaticsArray);
9735 void DomainLocalModule::PopulateClass(MethodTable *pMT)
9744 _ASSERTE(!pMT->ContainsGenericVariables());
9746 // <todo> the only work actually done here for non-dynamics is the freezing related work.
9747 // See if we can eliminate this and make this a dynamic-only path </todo>
9748 DWORD iClassIndex = pMT->GetClassIndex();
9750 if (!IsClassAllocated(pMT, iClassIndex))
9752 BaseDomain::DomainLocalBlockLockHolder lh(GetDomainFile()->GetAppDomain());
9754 if (!IsClassAllocated(pMT, iClassIndex))
9756 // Allocate dynamic space if necessary
9757 if (pMT->IsDynamicStatics())
9758 AllocateDynamicClass(pMT);
9760 // determine flags to set on the statics block
9761 DWORD dwFlags = ClassInitFlags::ALLOCATECLASS_FLAG;
9763 if (!pMT->HasClassConstructor() && !pMT->HasBoxedRegularStatics())
9765 _ASSERTE(!IsClassInitialized(pMT));
9766 _ASSERTE(!IsClassInitError(pMT));
9767 dwFlags |= ClassInitFlags::INITIALIZED_FLAG;
9770 if (pMT->Collectible())
9772 dwFlags |= ClassInitFlags::COLLECTIBLE_FLAG;
9775 // Set all flags at the same time to avoid races
9776 SetClassFlags(pMT, dwFlags);
9782 #endif // CROSSGEN_COMPILE
9784 void DomainLocalBlock::EnsureModuleIndex(ModuleIndex index)
9791 INJECT_FAULT(COMPlusThrowOM(););
9792 // Assumes BaseDomain::DomainLocalBlockLockHolder is taken
9793 PRECONDITION(m_pDomain->OwnDomainLocalBlockLock());
9797 if (m_aModuleIndices > index.m_dwIndex)
9799 _ASSERTE(m_pModuleSlots != NULL);
9803 SIZE_T aModuleIndices = max(16, m_aModuleIndices);
9804 while (aModuleIndices <= index.m_dwIndex)
9806 aModuleIndices *= 2;
9809 PTR_DomainLocalModule* pNewModuleSlots = (PTR_DomainLocalModule*) (void*)m_pDomain->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(PTR_DomainLocalModule)) * S_SIZE_T(aModuleIndices));
9811 memcpy(pNewModuleSlots, m_pModuleSlots, sizeof(SIZE_T)*m_aModuleIndices);
9813 // Note: Memory allocated on loader heap is zero filled
9814 // memset(pNewModuleSlots + m_aModuleIndices, 0 , (aModuleIndices - m_aModuleIndices)*sizeof(PTR_DomainLocalModule) );
9816 // Commit new table. The lock-free helpers depend on the order.
9818 m_pModuleSlots = pNewModuleSlots;
9820 m_aModuleIndices = aModuleIndices;
9824 void DomainLocalBlock::SetModuleSlot(ModuleIndex index, PTR_DomainLocalModule pLocalModule)
9826 // Need to synchronize with table growth in this domain
9827 BaseDomain::DomainLocalBlockLockHolder lh(m_pDomain);
9829 EnsureModuleIndex(index);
9831 _ASSERTE(index.m_dwIndex < m_aModuleIndices);
9833 // We would like this assert here, unfortunately, loading a module in this appdomain can fail
9834 // after here and we will keep the module around and reuse the slot when we retry (if
9835 // the failure happened due to a transient error, such as OOM). In that case the slot wont
9837 //_ASSERTE(m_pModuleSlots[index.m_dwIndex] == 0);
9839 m_pModuleSlots[index.m_dwIndex] = pLocalModule;
9842 #ifndef CROSSGEN_COMPILE
9844 DomainAssembly* AppDomain::RaiseTypeResolveEventThrowing(DomainAssembly* pAssembly, LPCSTR szName, ASSEMBLYREF *pResultingAssemblyRef)
9851 INJECT_FAULT(COMPlusThrowOM(););
9855 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
9858 DomainAssembly* pResolvedAssembly = NULL;
9859 _ASSERTE(strcmp(szName, g_AppDomainClassName));
9864 OBJECTREF AppDomainRef;
9865 OBJECTREF AssemblyRef;
9868 ZeroMemory(&gc, sizeof(gc));
9870 GCPROTECT_BEGIN(gc);
9871 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
9873 if (pAssembly != NULL)
9874 gc.AssemblyRef = pAssembly->GetExposedAssemblyObject();
9876 MethodDescCallSite onTypeResolve(METHOD__APP_DOMAIN__ON_TYPE_RESOLVE, &gc.AppDomainRef);
9878 gc.str = StringObject::NewString(szName);
9881 ObjToArgSlot(gc.AppDomainRef),
9882 ObjToArgSlot(gc.AssemblyRef),
9883 ObjToArgSlot(gc.str)
9885 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onTypeResolve.Call_RetOBJECTREF(args);
9887 if (ResultingAssemblyRef != NULL)
9889 pResolvedAssembly = ResultingAssemblyRef->GetDomainAssembly();
9891 if (pResultingAssemblyRef)
9892 *pResultingAssemblyRef = ResultingAssemblyRef;
9895 if (pResolvedAssembly->IsCollectible())
9897 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleBoundNonCollectible"));
9904 return pResolvedAssembly;
9908 Assembly* AppDomain::RaiseResourceResolveEvent(DomainAssembly* pAssembly, LPCSTR szName)
9915 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
9916 INJECT_FAULT(COMPlusThrowOM(););
9920 Assembly* pResolvedAssembly = NULL;
9925 OBJECTREF AppDomainRef;
9926 OBJECTREF AssemblyRef;
9929 ZeroMemory(&gc, sizeof(gc));
9931 GCPROTECT_BEGIN(gc);
9932 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
9934 if (pAssembly != NULL)
9935 gc.AssemblyRef=pAssembly->GetExposedAssemblyObject();
9937 MethodDescCallSite onResourceResolve(METHOD__APP_DOMAIN__ON_RESOURCE_RESOLVE, &gc.AppDomainRef);
9938 gc.str = StringObject::NewString(szName);
9941 ObjToArgSlot(gc.AppDomainRef),
9942 ObjToArgSlot(gc.AssemblyRef),
9943 ObjToArgSlot(gc.str)
9945 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onResourceResolve.Call_RetOBJECTREF(args);
9946 if (ResultingAssemblyRef != NULL)
9948 pResolvedAssembly = ResultingAssemblyRef->GetAssembly();
9949 if (pResolvedAssembly->IsCollectible())
9951 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleAssemblyResolve"));
9957 RETURN pResolvedAssembly;
9962 AppDomain::RaiseAssemblyResolveEvent(
9963 AssemblySpec * pSpec,
9964 BOOL fIntrospection,
9972 POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
9973 INJECT_FAULT(COMPlusThrowOM(););
9977 BinderMethodID methodId;
9978 StackSString ssName;
9979 pSpec->GetFileOrDisplayName(0, ssName);
9983 methodId = METHOD__APP_DOMAIN__ON_ASSEMBLY_RESOLVE; // post-bind execution event (the classic V1.0 event)
9991 // Elevate threads allowed loading level. This allows the host to load an assembly even in a restricted
9992 // condition. Note, however, that this exposes us to possible recursion failures, if the host tries to
9993 // load the assemblies currently being loaded. (Such cases would then throw an exception.)
9995 OVERRIDE_LOAD_LEVEL_LIMIT(FILE_ACTIVE);
9996 OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
10000 Assembly* pAssembly = NULL;
10003 OBJECTREF AppDomainRef;
10004 OBJECTREF AssemblyRef;
10007 ZeroMemory(&gc, sizeof(gc));
10009 GCPROTECT_BEGIN(gc);
10010 if ((gc.AppDomainRef = GetRawExposedObject()) != NULL)
10012 if (pSpec->GetParentAssembly() != NULL)
10015 gc.AssemblyRef=pSpec->GetParentAssembly()->GetExposedAssemblyObject();
10018 MethodDescCallSite onAssemblyResolve(methodId, &gc.AppDomainRef);
10020 gc.str = StringObject::NewString(ssName);
10021 ARG_SLOT args[3] = {
10022 ObjToArgSlot(gc.AppDomainRef),
10023 ObjToArgSlot(gc.AssemblyRef),
10024 ObjToArgSlot(gc.str)
10027 ASSEMBLYREF ResultingAssemblyRef = (ASSEMBLYREF) onAssemblyResolve.Call_RetOBJECTREF(args);
10029 if (ResultingAssemblyRef != NULL)
10031 pAssembly = ResultingAssemblyRef->GetAssembly();
10032 if (pAssembly->IsCollectible())
10034 COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleAssemblyResolve"));
10040 if (pAssembly != NULL)
10042 if ((!(pAssembly->IsIntrospectionOnly())) != (!fIntrospection))
10044 // Cannot return an introspection assembly from an execution callback or vice-versa
10045 COMPlusThrow(kFileLoadException, pAssembly->IsIntrospectionOnly() ? IDS_CLASSLOAD_ASSEMBLY_RESOLVE_RETURNED_INTROSPECTION : IDS_CLASSLOAD_ASSEMBLY_RESOLVE_RETURNED_EXECUTION);
10048 // Check that the public key token matches the one specified in the spec
10049 // MatchPublicKeys throws as appropriate
10050 pSpec->MatchPublicKeys(pAssembly);
10054 } // AppDomain::RaiseAssemblyResolveEvent
10057 //---------------------------------------------------------------------------------------
10059 // Determine the type of AppDomainManager to use for the default AppDomain
10062 // v2.0 of the CLR used environment variables APPDOMAIN_MANAGER_ASM and APPDOMAIN_MANAGER_TYPE to set the
10063 // domain manager. For compatibility these are still supported, along with appDomainManagerAsm and
10064 // appDomainManagerType config file switches. If the config switches are supplied, the entry point must be
10068 void AppDomain::InitializeDefaultDomainManager()
10075 INJECT_FAULT(COMPlusThrowOM(););
10076 PRECONDITION(GetId().m_dwId == DefaultADID);
10080 OBJECTREF orThis = GetExposedObject();
10081 GCPROTECT_BEGIN(orThis);
10083 MethodDescCallSite initCompatFlags(METHOD__APP_DOMAIN__INITIALIZE_COMPATIBILITY_FLAGS);
10086 ObjToArgSlot(orThis)
10089 initCompatFlags.Call(args);
10094 CLREvent * AppDomain::g_pUnloadStartEvent;
10096 void AppDomain::CreateADUnloadWorker()
10098 STANDARD_VM_CONTRACT;
10100 // Do not create adUnload thread if there is only default domain
10101 if(IsSingleAppDomain())
10105 BOOL fCreator = FALSE;
10106 if (FastInterlockCompareExchange((LONG *)&g_fADUnloadWorkerOK,-2,-1)==-1) //we're first
10108 #ifdef _TARGET_X86_ // use the smallest possible stack on X86
10109 DWORD stackSize = 128 * 1024;
10111 DWORD stackSize = 512 * 1024; // leave X64 unchanged since we have plenty of VM
10113 Thread *pThread = SetupUnstartedThread();
10114 if (pThread->CreateNewThread(stackSize, ADUnloadThreadStart, pThread))
10118 dwRet = pThread->StartThread();
10120 // When running under a user mode native debugger there is a race
10121 // between the moment we've created the thread (in CreateNewThread) and
10122 // the moment we resume it (in StartThread); the debugger may receive
10123 // the "ct" (create thread) notification, and it will attempt to
10124 // suspend/resume all threads in the process. Now imagine the debugger
10125 // resumes this thread first, and only later does it try to resume the
10126 // newly created thread (the ADU worker thread). In these conditions our
10127 // call to ResumeThread may come before the debugger's call to ResumeThread
10128 // actually causing dwRet to equal 2.
10129 // We cannot use IsDebuggerPresent() in the condition below because the
10130 // debugger may have been detached between the time it got the notification
10131 // and the moment we execute the test below.
10132 _ASSERTE(dwRet == 1 || dwRet == 2);
10136 pThread->DecExternalCount(FALSE);
10137 FastInterlockExchange((LONG *)&g_fADUnloadWorkerOK, -1);
10138 ThrowOutOfMemory();
10142 YIELD_WHILE (g_fADUnloadWorkerOK == -2);
10144 if (g_fADUnloadWorkerOK == -1) {
10147 ThrowOutOfMemory();
10156 /*static*/ void AppDomain::ADUnloadWorkerHelper(AppDomain *pDomain)
10158 STATIC_CONTRACT_NOTHROW;
10159 STATIC_CONTRACT_GC_TRIGGERS;
10160 STATIC_CONTRACT_MODE_COOPERATIVE;
10161 ADUnloadSink* pADUnloadSink=pDomain->GetADUnloadSinkForUnload();
10166 pDomain->Unload(FALSE);
10168 EX_CATCH_HRESULT(hr);
10172 SystemDomain::LockHolder lh;
10173 pADUnloadSink->ReportUnloadResult(hr,NULL);
10174 pADUnloadSink->Release();
10178 void AppDomain::DoADUnloadWork()
10185 INJECT_FAULT(COMPlusThrowOM(););
10192 AppDomain *pDomainToUnload = NULL;
10195 // Take the lock so that no domain can be added or removed from the system domain
10196 SystemDomain::LockHolder lh;
10198 DWORD numDomain = SystemDomain::GetCurrentAppDomainMaxIndex();
10199 for (; i <= numDomain; i ++) {
10200 AppDomain * pDomain = SystemDomain::TestGetAppDomainAtIndex(ADIndex(i));
10202 // @todo: We used to also select a domain if pDomain->IsUnload() returned true. But that causes
10203 // problems when we've failed to completely unload the AD in the past. If we've reached the CLEARED
10204 // stage, for instance, then there will be no default context and AppDomain::Exit() will simply crash.
10206 if (pDomain && pDomain->IsUnloadRequested())
10208 pDomainToUnload = pDomain;
10215 if (!pDomainToUnload) {
10219 // We are the only thread that can unload domains so no one else can delete the appdomain
10220 ADUnloadWorkerHelper(pDomainToUnload);
10224 static void DoADUnloadWorkHelper()
10226 STATIC_CONTRACT_NOTHROW;
10227 STATIC_CONTRACT_GC_TRIGGERS;
10228 STATIC_CONTRACT_MODE_COOPERATIVE;
10231 AppDomain::DoADUnloadWork();
10236 EX_END_CATCH(SwallowAllExceptions);
10239 ULONGLONG g_ObjFinalizeStartTime = 0;
10240 Volatile<BOOL> g_FinalizerIsRunning = FALSE;
10241 Volatile<ULONG> g_FinalizerLoopCount = 0;
10243 ULONGLONG GetObjFinalizeStartTime()
10245 LIMITED_METHOD_CONTRACT;
10246 return g_ObjFinalizeStartTime;
10249 void FinalizerThreadAbortOnTimeout()
10251 STATIC_CONTRACT_NOTHROW;
10252 STATIC_CONTRACT_MODE_COOPERATIVE;
10253 STATIC_CONTRACT_GC_TRIGGERS;
10256 // If finalizer thread is blocked because scheduler is running another task,
10257 // or it is waiting for another thread, we first see if we get finalizer thread
10259 Thread::ThreadAbortWatchDog();
10264 Thread *pFinalizerThread = FinalizerThread::GetFinalizerThread();
10265 EPolicyAction action = GetEEPolicy()->GetActionOnTimeout(OPR_FinalizerRun, pFinalizerThread);
10269 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10270 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10273 Thread::UAC_FinalizerTimeout);
10275 case eRudeAbortThread:
10276 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10277 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10280 Thread::UAC_FinalizerTimeout);
10282 case eUnloadAppDomain:
10284 AppDomain *pDomain = pFinalizerThread->GetDomain();
10285 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10288 Thread::UAC_FinalizerTimeout);
10289 if (!pDomain->IsDefaultDomain())
10291 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10292 pDomain->EnableADUnloadWorker(EEPolicy::ADU_Safe);
10296 case eRudeUnloadAppDomain:
10298 AppDomain *pDomain = pFinalizerThread->GetDomain();
10299 pFinalizerThread->UserAbort(Thread::TAR_Thread,
10302 Thread::UAC_FinalizerTimeout);
10303 if (!pDomain->IsDefaultDomain())
10305 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10306 pDomain->EnableADUnloadWorker(EEPolicy::ADU_Rude);
10311 case eFastExitProcess:
10312 case eRudeExitProcess:
10313 case eDisableRuntime:
10314 GetEEPolicy()->NotifyHostOnTimeout(OPR_FinalizerRun, action);
10315 EEPolicy::HandleExitProcessFromEscalation(action, HOST_E_EXITPROCESS_TIMEOUT);
10316 _ASSERTE (!"Should not get here");
10325 EX_END_CATCH(SwallowAllExceptions);
10330 WT_UnloadDomain = 0x1,
10331 WT_ThreadAbort = 0x2,
10332 WT_FinalizerThread = 0x4,
10333 WT_ClearCollectedDomains=0x8
10336 static Volatile<DWORD> s_WorkType = 0;
10339 DWORD WINAPI AppDomain::ADUnloadThreadStart(void *args)
10344 DISABLED(GC_TRIGGERS);
10346 // This function will always be at the very bottom of the stack. The only
10347 // user code it calls is the AppDomainUnload notifications which we will
10348 // not be hardenning for Whidbey.
10354 BEGIN_ENTRYPOINT_NOTHROW;
10356 ClrFlsSetThreadType (ThreadType_ADUnloadHelper);
10358 Thread *pThread = (Thread*)args;
10359 bool fOK = (pThread->HasStarted() != 0);
10362 GCX_MAYBE_PREEMP(fOK);
10364 _ASSERTE (g_fADUnloadWorkerOK == -2);
10366 FastInterlockExchange((LONG *)&g_fADUnloadWorkerOK,fOK?1:-1);
10370 DestroyThread(pThread);
10374 pThread->SetBackground(TRUE);
10376 pThread->SetThreadStateNC(Thread::TSNC_ADUnloadHelper);
10379 DWORD TAtimeout = INFINITE;
10380 ULONGLONG endTime = Thread::GetNextSelfAbortEndTime();
10381 ULONGLONG curTime = CLRGetTickCount64();
10382 if (endTime <= curTime) {
10387 ULONGLONG diff = endTime - curTime;
10388 if (diff < MAXULONG)
10390 TAtimeout = (DWORD)diff;
10393 ULONGLONG finalizeStartTime = GetObjFinalizeStartTime();
10394 DWORD finalizeTimeout = INFINITE;
10395 DWORD finalizeTimeoutSetting = GetEEPolicy()->GetTimeout(OPR_FinalizerRun);
10396 if (finalizeTimeoutSetting != INFINITE && g_FinalizerIsRunning)
10398 if (finalizeStartTime == 0)
10400 finalizeTimeout = finalizeTimeoutSetting;
10404 endTime = finalizeStartTime + finalizeTimeoutSetting;
10405 if (endTime <= curTime) {
10406 finalizeTimeout = 0;
10410 ULONGLONG diff = endTime - curTime;
10411 if (diff < MAXULONG)
10413 finalizeTimeout = (DWORD)diff;
10419 if (AppDomain::HasWorkForFinalizerThread())
10421 if (finalizeTimeout > finalizeTimeoutSetting)
10423 finalizeTimeout = finalizeTimeoutSetting;
10427 DWORD timeout = INFINITE;
10428 if (finalizeTimeout <= TAtimeout)
10430 timeout = finalizeTimeout;
10434 timeout = TAtimeout;
10439 LOG((LF_APPDOMAIN, LL_INFO10, "Waiting to start unload\n"));
10440 g_pUnloadStartEvent->Wait(timeout,FALSE);
10443 if (finalizeTimeout != INFINITE || (s_WorkType & WT_FinalizerThread) != 0)
10445 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for Finalizer thread\n");
10446 FastInterlockAnd(&s_WorkType, ~WT_FinalizerThread);
10447 // only watch finalizer thread is finalizer method or unloadevent is being processed
10448 if (GetObjFinalizeStartTime() == finalizeStartTime && finalizeStartTime != 0 && g_FinalizerIsRunning)
10450 if (CLRGetTickCount64() >= finalizeStartTime+finalizeTimeoutSetting)
10453 FinalizerThreadAbortOnTimeout();
10456 if (s_fProcessUnloadDomainEvent && g_FinalizerIsRunning)
10459 FinalizerThreadAbortOnTimeout();
10463 if (TAtimeout != INFINITE || (s_WorkType & WT_ThreadAbort) != 0)
10465 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for thread abort\n");
10466 FastInterlockAnd(&s_WorkType, ~WT_ThreadAbort);
10468 Thread::ThreadAbortWatchDog();
10471 if ((s_WorkType & WT_UnloadDomain) != 0 && !AppDomain::HasWorkForFinalizerThread())
10473 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for AD unload\n");
10474 FastInterlockAnd(&s_WorkType, ~WT_UnloadDomain);
10476 DoADUnloadWorkHelper();
10479 if ((s_WorkType & WT_ClearCollectedDomains) != 0)
10481 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "ADUnloadThreadStart work for AD cleanup\n");
10482 FastInterlockAnd(&s_WorkType, ~WT_ClearCollectedDomains);
10484 SystemDomain::System()->ClearCollectedDomains();
10491 END_ENTRYPOINT_NOTHROW;
10496 void AppDomain::EnableADUnloadWorker()
10502 SO_TOLERANT; // Called during a SO
10506 EEPolicy::AppDomainUnloadTypes type = EEPolicy::ADU_Safe;
10509 DWORD hostTestADUnload = g_pConfig->GetHostTestADUnload();
10510 if (hostTestADUnload == 2) {
10511 type = EEPolicy::ADU_Rude;
10515 EnableADUnloadWorker(type);
10518 void AppDomain::EnableADUnloadWorker(EEPolicy::AppDomainUnloadTypes type, BOOL fHasStack)
10524 SO_TOLERANT; // Called during a SO
10528 FastInterlockOr (&s_WorkType, WT_UnloadDomain);
10530 LONG stage = m_Stage;
10531 static_assert_no_msg(sizeof(m_Stage) == sizeof(int));
10533 _ASSERTE(!IsDefaultDomain());
10535 // Mark unload requested.
10536 if (type == EEPolicy::ADU_Rude) {
10539 while (stage < STAGE_UNLOAD_REQUESTED) {
10540 stage = FastInterlockCompareExchange((LONG*)&m_Stage,STAGE_UNLOAD_REQUESTED,stage);
10545 // Can not call Set due to limited stack.
10548 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker\n"));
10549 g_pUnloadStartEvent->Set();
10552 void AppDomain::EnableADUnloadWorkerForThreadAbort()
10554 LIMITED_METHOD_CONTRACT;
10555 STRESS_LOG0(LF_ALWAYS, LL_ALWAYS, "Enabling unload worker for thread abort\n");
10556 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for thread abort\n"));
10557 FastInterlockOr (&s_WorkType, WT_ThreadAbort);
10558 g_pUnloadStartEvent->Set();
10562 void AppDomain::EnableADUnloadWorkerForFinalizer()
10564 LIMITED_METHOD_CONTRACT;
10565 if (GetEEPolicy()->GetTimeout(OPR_FinalizerRun) != INFINITE)
10567 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for Finalizer Thread\n"));
10568 FastInterlockOr (&s_WorkType, WT_FinalizerThread);
10569 g_pUnloadStartEvent->Set();
10573 void AppDomain::EnableADUnloadWorkerForCollectedADCleanup()
10575 LIMITED_METHOD_CONTRACT;
10576 LOG((LF_APPDOMAIN, LL_INFO10, "Enabling unload worker for collected domains\n"));
10577 FastInterlockOr (&s_WorkType, WT_ClearCollectedDomains);
10578 g_pUnloadStartEvent->Set();
10582 void SystemDomain::ClearCollectedDomains()
10592 AppDomain* pDomainsToClear=NULL;
10594 CrstHolder lh(&m_DelayedUnloadCrst);
10595 for (AppDomain** ppDomain=&m_pDelayedUnloadList;(*ppDomain)!=NULL; )
10597 if ((*ppDomain)->m_Stage==AppDomain::STAGE_COLLECTED)
10599 AppDomain* pAppDomain=*ppDomain;
10600 *ppDomain=(*ppDomain)->m_pNextInDelayedUnloadList;
10601 pAppDomain->m_pNextInDelayedUnloadList=pDomainsToClear;
10602 pDomainsToClear=pAppDomain;
10605 ppDomain=&((*ppDomain)->m_pNextInDelayedUnloadList);
10609 for (AppDomain* pDomain=pDomainsToClear;pDomain!=NULL;)
10611 AppDomain* pNext=pDomain->m_pNextInDelayedUnloadList;
10612 pDomain->Close(); //NOTHROW!
10613 pDomain->Release();
10618 void SystemDomain::ProcessClearingDomains()
10627 CrstHolder lh(&m_DelayedUnloadCrst);
10629 for (AppDomain** ppDomain=&m_pDelayedUnloadList;(*ppDomain)!=NULL; )
10631 if ((*ppDomain)->m_Stage==AppDomain::STAGE_HANDLETABLE_NOACCESS)
10633 AppDomain* pAppDomain=*ppDomain;
10634 pAppDomain->SetStage(AppDomain::STAGE_CLEARED);
10636 ppDomain=&((*ppDomain)->m_pNextInDelayedUnloadList);
10639 if (!m_UnloadIsAsync)
10641 // For synchronous mode, we are now done with the list.
10642 m_pDelayedUnloadList = NULL;
10646 void SystemDomain::ProcessDelayedUnloadDomains()
10656 int iGCRefPoint=GCHeapUtilities::GetGCHeap()->CollectionCount(GCHeapUtilities::GetGCHeap()->GetMaxGeneration());
10657 if (GCHeapUtilities::GetGCHeap()->IsConcurrentGCInProgress())
10660 BOOL bAppDomainToCleanup = FALSE;
10661 LoaderAllocator * pAllocatorsToDelete = NULL;
10664 CrstHolder lh(&m_DelayedUnloadCrst);
10666 for (AppDomain* pDomain=m_pDelayedUnloadList; pDomain!=NULL; pDomain=pDomain->m_pNextInDelayedUnloadList)
10668 if (pDomain->m_Stage==AppDomain::STAGE_CLEARED)
10670 // Compare with 0 to handle overflows gracefully
10671 if (0 < iGCRefPoint - pDomain->GetGCRefPoint())
10673 bAppDomainToCleanup=TRUE;
10674 pDomain->SetStage(AppDomain::STAGE_COLLECTED);
10679 LoaderAllocator ** ppAllocator=&m_pDelayedUnloadListOfLoaderAllocators;
10680 while (*ppAllocator!= NULL)
10682 LoaderAllocator * pAllocator = *ppAllocator;
10683 if (0 < iGCRefPoint - pAllocator->GetGCRefPoint())
10685 *ppAllocator = pAllocator->m_pLoaderAllocatorDestroyNext;
10687 pAllocator->m_pLoaderAllocatorDestroyNext = pAllocatorsToDelete;
10688 pAllocatorsToDelete = pAllocator;
10692 ppAllocator = &pAllocator->m_pLoaderAllocatorDestroyNext;
10697 if (bAppDomainToCleanup)
10698 AppDomain::EnableADUnloadWorkerForCollectedADCleanup();
10700 // Delete collected loader allocators on the finalizer thread. We cannot offload it to appdomain unload thread because of
10701 // there is not guaranteed to be one, and it is not that expensive operation anyway.
10702 while (pAllocatorsToDelete != NULL)
10704 LoaderAllocator * pAllocator = pAllocatorsToDelete;
10705 pAllocatorsToDelete = pAllocator->m_pLoaderAllocatorDestroyNext;
10710 #endif // CROSSGEN_COMPILE
10712 AppDomainFromIDHolder::AppDomainFromIDHolder(ADID adId, BOOL bUnsafePoint, SyncType synctype)
10714 WRAPPER_NO_CONTRACT;
10715 ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
10722 Assign(adId, bUnsafePoint);
10725 AppDomainFromIDHolder::AppDomainFromIDHolder(SyncType synctype)
10727 LIMITED_METHOD_CONTRACT;
10728 ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
10737 #ifndef CROSSGEN_COMPILE
10738 void ADUnloadSink::ReportUnloadResult (HRESULT hr, OBJECTREF* pException)
10744 PRECONDITION(CheckPointer(this));
10745 PRECONDITION(m_UnloadCompleteEvent.IsValid());
10749 //pException is unused;
10751 m_UnloadCompleteEvent.Set();
10754 void ADUnloadSink::WaitUnloadCompletion()
10760 PRECONDITION(CheckPointer(this));
10761 PRECONDITION(m_UnloadCompleteEvent.IsValid());
10765 CONTRACT_VIOLATION(FaultViolation);
10766 m_UnloadCompleteEvent.WaitEx(INFINITE, (WaitMode)(WaitMode_Alertable | WaitMode_ADUnload));
10769 ADUnloadSink* AppDomain::PrepareForWaitUnloadCompletion()
10775 PRECONDITION(SystemDomain::IsUnderDomainLock());
10780 ADUnloadSink* pADSink=GetADUnloadSink();
10781 PREFIX_ASSUME(pADSink!=NULL);
10782 if (m_Stage < AppDomain::STAGE_UNLOAD_REQUESTED) //we're first
10785 SetUnloadRequestThread(GetThread());
10790 ADUnloadSink::ADUnloadSink()
10798 INJECT_FAULT(COMPlusThrowOM(););
10803 m_UnloadCompleteEvent.CreateManualEvent(FALSE);
10804 m_UnloadResult=S_OK;
10807 ADUnloadSink::~ADUnloadSink()
10817 m_UnloadCompleteEvent.CloseEvent();
10822 ULONG ADUnloadSink::AddRef()
10824 LIMITED_METHOD_CONTRACT;
10825 return InterlockedIncrement(&m_cRef);
10828 ULONG ADUnloadSink::Release()
10830 LIMITED_METHOD_CONTRACT;
10831 ULONG ulRef = InterlockedDecrement(&m_cRef);
10839 void ADUnloadSink::Reset()
10841 LIMITED_METHOD_CONTRACT;
10842 m_UnloadResult=S_OK;
10843 m_UnloadCompleteEvent.Reset();
10846 ADUnloadSink* AppDomain::GetADUnloadSink()
10848 LIMITED_METHOD_CONTRACT;
10849 _ASSERTE(SystemDomain::IsUnderDomainLock());
10851 m_ADUnloadSink->AddRef();
10852 return m_ADUnloadSink;
10855 ADUnloadSink* AppDomain::GetADUnloadSinkForUnload()
10857 // unload thread only. Doesn't need to have AD lock
10858 LIMITED_METHOD_CONTRACT;
10860 m_ADUnloadSink->AddRef();
10861 return m_ADUnloadSink;
10863 #endif // CROSSGEN_COMPILE
10865 void AppDomain::EnumStaticGCRefs(promote_func* fn, ScanContext* sc)
10874 _ASSERTE(GCHeapUtilities::IsGCInProgress() &&
10875 GCHeapUtilities::IsServerHeap() &&
10876 IsGCSpecialThread());
10878 AppDomain::AssemblyIterator asmIterator = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution));
10879 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
10880 while (asmIterator.Next(pDomainAssembly.This()))
10882 // @TODO: Review when DomainAssemblies get added.
10883 _ASSERTE(pDomainAssembly != NULL);
10884 pDomainAssembly->EnumStaticGCRefs(fn, sc);
10890 #endif // !DACCESS_COMPILE
10892 //------------------------------------------------------------------------
10893 UINT32 BaseDomain::GetTypeID(PTR_MethodTable pMT) {
10897 PRECONDITION(pMT->GetDomain() == this);
10900 return m_typeIDMap.GetTypeID(pMT);
10903 //------------------------------------------------------------------------
10904 // Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
10905 UINT32 BaseDomain::LookupTypeID(PTR_MethodTable pMT)
10910 WRAPPER(GC_TRIGGERS);
10911 PRECONDITION(pMT->GetDomain() == this);
10914 return m_typeIDMap.LookupTypeID(pMT);
10917 //------------------------------------------------------------------------
10918 PTR_MethodTable BaseDomain::LookupType(UINT32 id) {
10922 WRAPPER(GC_TRIGGERS);
10923 CONSISTENCY_CHECK(id != TYPE_ID_THIS_CLASS);
10926 PTR_MethodTable pMT = m_typeIDMap.LookupType(id);
10927 if (pMT == NULL && !IsSharedDomain()) {
10928 pMT = SharedDomain::GetDomain()->LookupType(id);
10931 CONSISTENCY_CHECK(CheckPointer(pMT));
10932 CONSISTENCY_CHECK(pMT->IsInterface());
10936 //---------------------------------------------------------------------------------------
10939 AppDomain::AssemblyIterator::Next(
10940 CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder)
10944 WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
10948 CrstHolder ch(m_pAppDomain->GetAssemblyListLock());
10949 return Next_Unlocked(pDomainAssemblyHolder);
10952 //---------------------------------------------------------------------------------------
10954 // Note: Does not lock the assembly list, but locks collectible assemblies for adding references.
10957 AppDomain::AssemblyIterator::Next_Unlocked(
10958 CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder)
10966 #ifndef DACCESS_COMPILE
10967 _ASSERTE(m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
10970 while (m_Iterator.Next())
10972 // Get element from the list/iterator (without adding reference to the assembly)
10973 DomainAssembly * pDomainAssembly = dac_cast<PTR_DomainAssembly>(m_Iterator.GetElement());
10974 if (pDomainAssembly == NULL)
10979 if (pDomainAssembly->IsError())
10981 if (m_assemblyIterationFlags & kIncludeFailedToLoad)
10983 *pDomainAssemblyHolder = pDomainAssembly;
10986 continue; // reject
10989 // First, reject DomainAssemblies whose load status is not to be included in
10992 if (pDomainAssembly->IsAvailableToProfilers() &&
10993 (m_assemblyIterationFlags & kIncludeAvailableToProfilers))
10995 // The assembly has reached the state at which we would notify profilers,
10996 // and we're supposed to include such assemblies in the enumeration. So
10997 // don't reject it (i.e., noop here, and don't bother with the rest of
10998 // the load status checks). Check for this first, since
10999 // kIncludeAvailableToProfilers contains some loaded AND loading
11002 else if (pDomainAssembly->IsLoaded())
11004 // A loaded assembly
11005 if (!(m_assemblyIterationFlags & kIncludeLoaded))
11007 continue; // reject
11012 // A loading assembly
11013 if (!(m_assemblyIterationFlags & kIncludeLoading))
11015 continue; // reject
11019 // Next, reject DomainAssemblies whose execution / introspection status is
11020 // not to be included in the enumeration
11022 if (pDomainAssembly->IsIntrospectionOnly())
11024 // introspection assembly
11025 if (!(m_assemblyIterationFlags & kIncludeIntrospection))
11027 continue; // reject
11032 // execution assembly
11033 if (!(m_assemblyIterationFlags & kIncludeExecution))
11035 continue; // reject
11039 // Next, reject collectible assemblies
11040 if (pDomainAssembly->IsCollectible())
11042 if (m_assemblyIterationFlags & kExcludeCollectible)
11044 _ASSERTE(!(m_assemblyIterationFlags & kIncludeCollected));
11045 continue; // reject
11048 // Un-tenured collectible assemblies should not be returned. (This can only happen in a brief
11049 // window during collectible assembly creation. No thread should need to have a pointer
11050 // to the just allocated DomainAssembly at this stage.)
11051 if (!pDomainAssembly->GetAssembly()->GetManifestModule()->IsTenured())
11053 continue; // reject
11056 if (pDomainAssembly->GetLoaderAllocator()->AddReferenceIfAlive())
11057 { // The assembly is alive
11059 // Set the holder value (incl. increasing ref-count)
11060 *pDomainAssemblyHolder = pDomainAssembly;
11062 // Now release the reference we took in the if-condition
11063 pDomainAssembly->GetLoaderAllocator()->Release();
11066 // The assembly is not alive anymore (and we didn't increase its ref-count in the
11069 if (!(m_assemblyIterationFlags & kIncludeCollected))
11071 continue; // reject
11073 // Set the holder value to assembly with 0 ref-count without increasing the ref-count (won't
11074 // call Release either)
11075 pDomainAssemblyHolder->Assign(pDomainAssembly, FALSE);
11079 *pDomainAssemblyHolder = pDomainAssembly;
11083 *pDomainAssemblyHolder = NULL;
11085 } // AppDomain::AssemblyIterator::Next_Unlocked
11087 #ifndef DACCESS_COMPILE
11089 //---------------------------------------------------------------------------------------
11091 // Can be called only from AppDomain shutdown code:AppDomain::ShutdownAssemblies.
11092 // Does not add-ref collectible assemblies (as the LoaderAllocator might not be reachable from the
11093 // DomainAssembly anymore).
11096 AppDomain::AssemblyIterator::Next_UnsafeNoAddRef(
11097 DomainAssembly ** ppDomainAssembly)
11105 // Make sure we are iterating all assemblies (see the only caller code:AppDomain::ShutdownAssemblies)
11106 _ASSERTE(m_assemblyIterationFlags ==
11107 (kIncludeLoaded | kIncludeLoading | kIncludeExecution | kIncludeIntrospection | kIncludeFailedToLoad | kIncludeCollected));
11108 // It also means that we do not exclude anything
11109 _ASSERTE((m_assemblyIterationFlags & kExcludeCollectible) == 0);
11111 // We are on shutdown path, so lock shouldn't be neccessary, but all _Unlocked methods on AssemblyList
11112 // have asserts that the lock is held, so why not to take it ...
11113 CrstHolder ch(m_pAppDomain->GetAssemblyListLock());
11115 while (m_Iterator.Next())
11117 // Get element from the list/iterator (without adding reference to the assembly)
11118 *ppDomainAssembly = dac_cast<PTR_DomainAssembly>(m_Iterator.GetElement());
11119 if (*ppDomainAssembly == NULL)
11127 *ppDomainAssembly = NULL;
11129 } // AppDomain::AssemblyIterator::Next_UnsafeNoAddRef
11132 //---------------------------------------------------------------------------------------
11134 BOOL AppDomain::IsImageFromTrustedPath(PEImage* pPEImage)
11141 PRECONDITION(CheckPointer(pPEImage));
11145 const SString &sImagePath = pPEImage->GetPath();
11147 return !sImagePath.IsEmpty();
11150 #endif //!DACCESS_COMPILE
11152 #if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
11154 // Returns a BOOL indicating if the binding model has been locked for the AppDomain
11155 BOOL AppDomain::IsBindingModelLocked()
11165 return m_fIsBindingModelLocked.Load();
11168 // Marks the binding model locked for AppDomain
11169 BOOL AppDomain::LockBindingModel()
11171 LIMITED_METHOD_CONTRACT;
11173 BOOL fDidWeLockBindingModel = FALSE;
11175 if (InterlockedCompareExchangeT<BOOL>(&m_fIsBindingModelLocked, TRUE, FALSE) == FALSE)
11177 fDidWeLockBindingModel = TRUE;
11180 return fDidWeLockBindingModel;
11183 BOOL AppDomain::IsHostAssemblyResolverInUse()
11185 LIMITED_METHOD_CONTRACT;
11187 return (GetFusionContext() != GetTPABinderContext());
11190 // Helper used by the assembly binder to check if the specified AppDomain can use apppath assembly resolver
11191 BOOL RuntimeCanUseAppPathAssemblyResolver(DWORD adid)
11195 NOTHROW; // Cannot throw since it is invoked by the Binder that expects to get a hresult
11203 // We need to be in COOP mode to get the AppDomain*
11206 AppDomain *pTargetDomain = SystemDomain::GetAppDomainFromId(id, ADV_CURRENTAD);
11207 _ASSERTE(pTargetDomain != NULL);
11209 pTargetDomain->LockBindingModel();
11211 return !pTargetDomain->IsHostAssemblyResolverInUse();
11214 // Returns S_OK if the assembly was successfully loaded
11215 HRESULT RuntimeInvokeHostAssemblyResolver(INT_PTR pManagedAssemblyLoadContextToBindWithin, IAssemblyName *pIAssemblyName, CLRPrivBinderCoreCLR *pTPABinder, BINDER_SPACE::AssemblyName *pAssemblyName, ICLRPrivAssembly **ppLoadedAssembly)
11222 PRECONDITION(ppLoadedAssembly != NULL);
11226 HRESULT hr = E_FAIL;
11228 // DevDiv #933506: Exceptions thrown during AssemblyLoadContext.Load should propagate
11231 // Switch to COOP mode since we are going to work with managed references
11236 ASSEMBLYNAMEREF oRefAssemblyName;
11237 ASSEMBLYREF oRefLoadedAssembly;
11240 ZeroMemory(&_gcRefs, sizeof(_gcRefs));
11242 GCPROTECT_BEGIN(_gcRefs);
11244 ICLRPrivAssembly *pAssemblyBindingContext = NULL;
11246 bool fInvokedForTPABinder = (pTPABinder == NULL)?true:false;
11248 // Prepare to invoke System.Runtime.Loader.AssemblyLoadContext.Resolve method.
11250 // First, initialize an assembly spec for the requested assembly
11253 hr = spec.Init(pIAssemblyName);
11256 bool fResolvedAssembly = false;
11257 bool fResolvedAssemblyViaTPALoadContext = false;
11259 // Allocate an AssemblyName managed object
11260 _gcRefs.oRefAssemblyName = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME));
11262 // Initialize the AssemblyName object from the AssemblySpec
11263 spec.AssemblyNameInit(&_gcRefs.oRefAssemblyName, NULL);
11265 if (!fInvokedForTPABinder)
11267 // Step 2 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName) - Invoke Load method
11268 // This is not invoked for TPA Binder since it always returns NULL.
11270 // Finally, setup arguments for invocation
11271 BinderMethodID idHAR_Resolve = METHOD__ASSEMBLYLOADCONTEXT__RESOLVE;
11272 MethodDescCallSite methLoadAssembly(idHAR_Resolve);
11274 // Setup the arguments for the call
11277 PtrToArgSlot(pManagedAssemblyLoadContextToBindWithin), // IntPtr for managed assembly load context instance
11278 ObjToArgSlot(_gcRefs.oRefAssemblyName), // AssemblyName instance
11282 _gcRefs.oRefLoadedAssembly = (ASSEMBLYREF) methLoadAssembly.Call_RetOBJECTREF(args);
11283 if (_gcRefs.oRefLoadedAssembly != NULL)
11285 fResolvedAssembly = true;
11288 // Step 3 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName)
11289 if (!fResolvedAssembly)
11291 // If we could not resolve the assembly using Load method, then attempt fallback with TPA Binder.
11292 // Since TPA binder cannot fallback to itself, this fallback does not happen for binds within TPA binder.
11294 // Switch to pre-emp mode before calling into the binder
11296 ICLRPrivAssembly *pCoreCLRFoundAssembly = NULL;
11297 hr = pTPABinder->BindAssemblyByName(pIAssemblyName, &pCoreCLRFoundAssembly);
11300 pAssemblyBindingContext = pCoreCLRFoundAssembly;
11301 fResolvedAssembly = true;
11302 fResolvedAssemblyViaTPALoadContext = true;
11307 if (!fResolvedAssembly)
11309 // Step 4 (of CLRPrivBinderAssemblyLoadContext::BindUsingAssemblyName)
11311 // If we couldnt resolve the assembly using TPA LoadContext as well, then
11312 // attempt to resolve it using the Resolving event.
11313 // Finally, setup arguments for invocation
11314 BinderMethodID idHAR_ResolveUsingEvent = METHOD__ASSEMBLYLOADCONTEXT__RESOLVEUSINGEVENT;
11315 MethodDescCallSite methLoadAssembly(idHAR_ResolveUsingEvent);
11317 // Setup the arguments for the call
11320 PtrToArgSlot(pManagedAssemblyLoadContextToBindWithin), // IntPtr for managed assembly load context instance
11321 ObjToArgSlot(_gcRefs.oRefAssemblyName), // AssemblyName instance
11325 _gcRefs.oRefLoadedAssembly = (ASSEMBLYREF) methLoadAssembly.Call_RetOBJECTREF(args);
11326 if (_gcRefs.oRefLoadedAssembly != NULL)
11328 // Set the flag indicating we found the assembly
11329 fResolvedAssembly = true;
11333 if (fResolvedAssembly && !fResolvedAssemblyViaTPALoadContext)
11335 // If we are here, assembly was successfully resolved via Load or Resolving events.
11336 _ASSERTE(_gcRefs.oRefLoadedAssembly != NULL);
11338 // We were able to get the assembly loaded. Now, get its name since the host could have
11339 // performed the resolution using an assembly with different name.
11340 DomainAssembly *pDomainAssembly = _gcRefs.oRefLoadedAssembly->GetDomainAssembly();
11341 PEAssembly *pLoadedPEAssembly = NULL;
11342 bool fFailLoad = false;
11343 if (!pDomainAssembly)
11345 // Reflection emitted assemblies will not have a domain assembly.
11350 pLoadedPEAssembly = pDomainAssembly->GetFile();
11351 if (pLoadedPEAssembly->HasHostAssembly() != true)
11353 // Reflection emitted assemblies will not have a domain assembly.
11358 // The loaded assembly's ICLRPrivAssembly* is saved as HostAssembly in PEAssembly
11362 spec.GetFileOrDisplayName(0, name);
11363 COMPlusThrowHR(COR_E_INVALIDOPERATION, IDS_HOST_ASSEMBLY_RESOLVER_DYNAMICALLY_EMITTED_ASSEMBLIES_UNSUPPORTED, name);
11366 // Is the assembly already bound using a binding context that will be incompatible?
11367 // An example is attempting to consume an assembly bound to WinRT binder.
11368 pAssemblyBindingContext = pLoadedPEAssembly->GetHostAssembly();
11371 #ifdef FEATURE_COMINTEROP
11372 if (AreSameBinderInstance(pAssemblyBindingContext, GetAppDomain()->GetWinRtBinder()))
11374 // It is invalid to return an assembly bound to an incompatible binder
11375 *ppLoadedAssembly = NULL;
11377 spec.GetFileOrDisplayName(0, name);
11378 COMPlusThrowHR(COR_E_INVALIDOPERATION, IDS_HOST_ASSEMBLY_RESOLVER_INCOMPATIBLE_BINDING_CONTEXT, name);
11380 #endif // FEATURE_COMINTEROP
11382 // Get the ICLRPrivAssembly reference to return back to.
11383 *ppLoadedAssembly = clr::SafeAddRef(pAssemblyBindingContext);
11389 // EX_CATCH_HRESULT(hr);
11394 #endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
11396 //approximate size of loader data
11397 //maintained for each assembly
11398 #define APPROX_LOADER_DATA_PER_ASSEMBLY 8196
11400 size_t AppDomain::EstimateSize()
11410 size_t retval = sizeof(AppDomain);
11411 retval += GetLoaderAllocator()->EstimateSize();
11412 //very rough estimate
11413 retval += GetAssemblyCount() * APPROX_LOADER_DATA_PER_ASSEMBLY;
11417 #ifdef DACCESS_COMPILE
11420 DomainLocalModule::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
11424 // Enumerate the DomainLocalModule itself. DLMs are allocated to be larger than
11425 // sizeof(DomainLocalModule) to make room for ClassInit flags and non-GC statics.
11426 // "DAC_ENUM_DTHIS()" probably does not account for this, so we might not enumerate
11427 // all of the ClassInit flags and non-GC statics.
11428 // sizeof(DomainLocalModule) == 0x28
11431 if (m_pDomainFile.IsValid())
11433 m_pDomainFile->EnumMemoryRegions(flags);
11436 if (m_pDynamicClassTable.Load().IsValid())
11438 DacEnumMemoryRegion(dac_cast<TADDR>(m_pDynamicClassTable.Load()),
11439 m_aDynamicEntries * sizeof(DynamicClassInfo));
11441 for (SIZE_T i = 0; i < m_aDynamicEntries; i++)
11443 PTR_DynamicEntry entry = dac_cast<PTR_DynamicEntry>(m_pDynamicClassTable[i].m_pDynamicEntry.Load());
11444 if (entry.IsValid())
11446 // sizeof(DomainLocalModule::DynamicEntry) == 8
11454 DomainLocalBlock::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
11457 // Block is contained in AppDomain, don't enum this.
11459 if (m_pModuleSlots.IsValid())
11461 DacEnumMemoryRegion(dac_cast<TADDR>(m_pModuleSlots),
11462 m_aModuleIndices * sizeof(TADDR));
11464 for (SIZE_T i = 0; i < m_aModuleIndices; i++)
11466 PTR_DomainLocalModule domMod = m_pModuleSlots[i];
11467 if (domMod.IsValid())
11469 domMod->EnumMemoryRegions(flags);
11476 BaseDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11482 // This is wrong. Don't do it.
11483 // BaseDomain cannot be instantiated.
11484 // The only thing this code can hope to accomplish is to potentially break
11485 // memory enumeration walking through the derived class if we
11486 // explicitly call the base class enum first.
11487 // DAC_ENUM_VTHIS();
11490 EMEM_OUT(("MEM: %p BaseDomain\n", dac_cast<TADDR>(this)));
11494 AppDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11501 //sizeof(AppDomain) == 0xeb0
11504 BaseDomain::EnumMemoryRegions(flags, false);
11506 // We don't need AppDomain name in triage dumps.
11507 if (flags != CLRDATA_ENUM_MEM_TRIAGE)
11509 m_friendlyName.EnumMemoryRegions(flags);
11512 m_Assemblies.EnumMemoryRegions(flags);
11513 AssemblyIterator assem = IterateAssembliesEx((AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution | kIncludeIntrospection));
11514 CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
11516 while (assem.Next(pDomainAssembly.This()))
11518 pDomainAssembly->EnumMemoryRegions(flags);
11521 m_sDomainLocalBlock.EnumMemoryRegions(flags);
11523 m_LoaderAllocator.EnumMemoryRegions(flags);
11527 SystemDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11535 BaseDomain::EnumMemoryRegions(flags, false);
11537 if (m_pSystemFile.IsValid())
11539 m_pSystemFile->EnumMemoryRegions(flags);
11541 if (m_pSystemAssembly.IsValid())
11543 m_pSystemAssembly->EnumMemoryRegions(flags);
11545 if (m_pDefaultDomain.IsValid())
11547 m_pDefaultDomain->EnumMemoryRegions(flags, true);
11550 m_appDomainIndexList.EnumMem();
11551 (&m_appDomainIndexList)->EnumMemoryRegions(flags);
11555 SharedDomain::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
11563 BaseDomain::EnumMemoryRegions(flags, false);
11564 #ifdef FEATURE_LOADER_OPTIMIZATION
11565 m_assemblyMap.EnumMemoryRegions(flags);
11566 SharedAssemblyIterator assem;
11567 while (assem.Next())
11569 assem.GetAssembly()->EnumMemoryRegions(flags);
11574 #endif //DACCESS_COMPILE
11577 PTR_LoaderAllocator SystemDomain::GetGlobalLoaderAllocator()
11579 return PTR_LoaderAllocator(PTR_HOST_MEMBER_TADDR(SystemDomain,System(),m_GlobalAllocator));
11582 #ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
11584 #ifndef CROSSGEN_COMPILE
11585 // Return the total processor time (user and kernel) used by threads executing in this AppDomain so far. The
11586 // result is in 100ns units.
11587 ULONGLONG AppDomain::QueryProcessorUsage()
11597 #ifndef DACCESS_COMPILE
11598 Thread *pThread = NULL;
11600 // Need to update our accumulated processor time count with current values from each thread that is
11601 // currently executing in this domain.
11603 // Take the thread store lock while we enumerate threads.
11604 ThreadStoreLockHolder tsl;
11605 while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
11607 // Skip unstarted and dead threads and those that are currently executing in a different AppDomain.
11608 if (pThread->IsUnstarted() || pThread->IsDead() || pThread->GetDomain(INDEBUG(TRUE)) != this)
11611 // Add the amount of time spent by the thread in the AppDomain since the last time we asked (calling
11612 // Thread::QueryThreadProcessorUsage() will reset the thread's counter).
11613 UpdateProcessorUsage(pThread->QueryThreadProcessorUsage());
11615 #endif // !DACCESS_COMPILE
11617 // Return the updated total.
11618 return m_ullTotalProcessorUsage;
11621 // Add to the current count of processor time used by threads within this AppDomain. This API is called by
11622 // threads transitioning between AppDomains.
11623 void AppDomain::UpdateProcessorUsage(ULONGLONG ullAdditionalUsage)
11625 LIMITED_METHOD_CONTRACT;
11627 // Need to be careful to synchronize here, multiple threads could be racing to update this count.
11628 ULONGLONG ullOldValue;
11629 ULONGLONG ullNewValue;
11632 ullOldValue = m_ullTotalProcessorUsage;
11633 ullNewValue = ullOldValue + ullAdditionalUsage;
11634 } while (InterlockedCompareExchange64((LONGLONG*)&m_ullTotalProcessorUsage,
11635 (LONGLONG)ullNewValue,
11636 (LONGLONG)ullOldValue) != (LONGLONG)ullOldValue);
11638 #endif // CROSSGEN_COMPILE
11640 #endif // FEATURE_APPDOMAIN_RESOURCE_MONITORING
11642 #if defined(FEATURE_TYPEEQUIVALENCE)
11644 #ifndef DACCESS_COMPILE
11645 TypeEquivalenceHashTable * AppDomain::GetTypeEquivalenceCache()
11651 INJECT_FAULT(COMPlusThrowOM());
11656 // Take the critical section all of the time in debug builds to ensure that it is safe to take
11657 // the critical section in the unusual times when it may actually be needed in retail builds
11659 CrstHolder ch(&m_TypeEquivalenceCrst);
11662 if (m_pTypeEquivalenceTable.Load() == NULL)
11665 CrstHolder ch(&m_TypeEquivalenceCrst);
11667 if (m_pTypeEquivalenceTable.Load() == NULL)
11669 m_pTypeEquivalenceTable = TypeEquivalenceHashTable::Create(this, 12, &m_TypeEquivalenceCrst);
11672 return m_pTypeEquivalenceTable;
11674 #endif //!DACCESS_COMPILE
11676 #endif //FEATURE_TYPEEQUIVALENCE
11678 #if !defined(DACCESS_COMPILE)
11680 //---------------------------------------------------------------------------------------------------------------------
11681 void AppDomain::PublishHostedAssembly(
11682 DomainAssembly * pDomainAssembly)
11692 if (pDomainAssembly->GetFile()->HasHostAssembly())
11694 // We have to serialize all Add operations
11695 CrstHolder lockAdd(&m_crstHostAssemblyMapAdd);
11696 _ASSERTE(m_hostAssemblyMap.Lookup(pDomainAssembly->GetFile()->GetHostAssembly()) == nullptr);
11698 // Wrapper for m_hostAssemblyMap.Add that avoids call out into host
11699 HostAssemblyMap::AddPhases addCall;
11701 // 1. Preallocate one element
11702 addCall.PreallocateForAdd(&m_hostAssemblyMap);
11704 // 2. Take the reader lock which can be taken during stack walking
11705 // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations)
11706 ForbidSuspendThreadHolder suspend;
11708 CrstHolder lock(&m_crstHostAssemblyMap);
11709 // 3. Add the element to the hash table (no call out into host)
11710 addCall.Add(pDomainAssembly);
11713 // 4. Cleanup the old memory (if any)
11714 addCall.DeleteOldTable();
11721 //---------------------------------------------------------------------------------------------------------------------
11722 void AppDomain::UpdatePublishHostedAssembly(
11723 DomainAssembly * pAssembly,
11735 if (pAssembly->GetFile()->HasHostAssembly())
11737 // We have to serialize all Add operations
11738 CrstHolder lockAdd(&m_crstHostAssemblyMapAdd);
11740 // Wrapper for m_hostAssemblyMap.Add that avoids call out into host
11741 OriginalFileHostAssemblyMap::AddPhases addCall;
11742 bool fAddOrigFile = false;
11744 // For cases where the pefile is being updated
11745 // 1. Preallocate one element
11746 if (pFile != pAssembly->GetFile())
11748 addCall.PreallocateForAdd(&m_hostAssemblyMapForOrigFile);
11749 fAddOrigFile = true;
11753 // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations)
11754 ForbidSuspendThreadHolder suspend;
11756 CrstHolder lock(&m_crstHostAssemblyMap);
11758 // Remove from hash table.
11759 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) != nullptr);
11760 m_hostAssemblyMap.Remove(pAssembly->GetFile()->GetHostAssembly());
11762 // Update PEFile on DomainAssembly. (This may cause the key for the hash to change, which is why we need this function)
11763 pAssembly->UpdatePEFileWorker(pFile);
11765 _ASSERTE(fAddOrigFile == (pAssembly->GetOriginalFile() != pAssembly->GetFile()));
11768 // 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)
11769 addCall.Add(pAssembly);
11772 // Add back to the hashtable (the call to Remove above guarantees that we will not call into host for table reallocation)
11773 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) == nullptr);
11774 m_hostAssemblyMap.Add(pAssembly);
11778 // 4. Cleanup the old memory (if any)
11780 addCall.DeleteOldTable();
11786 pAssembly->UpdatePEFileWorker(pFile);
11790 //---------------------------------------------------------------------------------------------------------------------
11791 void AppDomain::UnPublishHostedAssembly(
11792 DomainAssembly * pAssembly)
11803 if (pAssembly->GetFile()->HasHostAssembly())
11805 ForbidSuspendThreadHolder suspend;
11807 CrstHolder lock(&m_crstHostAssemblyMap);
11808 _ASSERTE(m_hostAssemblyMap.Lookup(pAssembly->GetFile()->GetHostAssembly()) != nullptr);
11809 m_hostAssemblyMap.Remove(pAssembly->GetFile()->GetHostAssembly());
11811 // We also have an entry in m_hostAssemblyMapForOrigFile. Handle that case.
11812 if (pAssembly->GetOriginalFile() != pAssembly->GetFile())
11814 m_hostAssemblyMapForOrigFile.Remove(pAssembly->GetOriginalFile()->GetHostAssembly());
11820 // In AppX processes, all PEAssemblies that are reach this stage should have host binders.
11821 _ASSERTE(!AppX::IsAppXProcess());
11825 #if defined(FEATURE_COMINTEROP)
11826 HRESULT AppDomain::SetWinrtApplicationContext(SString &appLocalWinMD)
11828 STANDARD_VM_CONTRACT;
11830 _ASSERTE(WinRTSupported());
11831 _ASSERTE(m_pWinRtBinder != nullptr);
11833 _ASSERTE(GetTPABinderContext() != NULL);
11834 BINDER_SPACE::ApplicationContext *pApplicationContext = GetTPABinderContext()->GetAppContext();
11835 _ASSERTE(pApplicationContext != NULL);
11837 return m_pWinRtBinder->SetApplicationContext(pApplicationContext, appLocalWinMD);
11840 #endif // FEATURE_COMINTEROP
11842 #endif //!DACCESS_COMPILE
11844 //---------------------------------------------------------------------------------------------------------------------
11845 PTR_DomainAssembly AppDomain::FindAssembly(PTR_ICLRPrivAssembly pHostAssembly)
11856 if (pHostAssembly == nullptr)
11860 ForbidSuspendThreadHolder suspend;
11862 CrstHolder lock(&m_crstHostAssemblyMap);
11863 PTR_DomainAssembly returnValue = m_hostAssemblyMap.Lookup(pHostAssembly);
11864 if (returnValue == NULL)
11866 // If not found in the m_hostAssemblyMap, look in the m_hostAssemblyMapForOrigFile
11867 // This is necessary as it may happen during in a second AppDomain that the PEFile
11868 // first discovered in the AppDomain may not be used by the DomainFile, but the CLRPrivBinderFusion
11869 // will in some cases find the pHostAssembly associated with this no longer used PEFile
11870 // instead of the PEFile that was finally decided upon.
11871 returnValue = m_hostAssemblyMapForOrigFile.Lookup(pHostAssembly);
11874 return returnValue;
11879 #if !defined(DACCESS_COMPILE) && defined(FEATURE_NATIVE_IMAGE_GENERATION)
11881 void ZapperSetBindingPaths(ICorCompilationDomain *pDomain, SString &trustedPlatformAssemblies, SString &platformResourceRoots, SString &appPaths, SString &appNiPaths)
11883 CLRPrivBinderCoreCLR *pBinder = static_cast<CLRPrivBinderCoreCLR*>(((CompilationDomain *)pDomain)->GetFusionContext());
11884 _ASSERTE(pBinder != NULL);
11885 pBinder->SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths);
11886 #ifdef FEATURE_COMINTEROP
11887 SString emptString;
11888 ((CompilationDomain*)pDomain)->SetWinrtApplicationContext(emptString);