-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathassembly.cpp
2451 lines (1989 loc) · 72.6 KB
/
assembly.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** Header: Assembly.cpp
**
**
** Purpose: Implements assembly (loader domain) architecture
**
**
===========================================================*/
#include "common.h"
#include <stdlib.h>
#include "assembly.hpp"
#include "appdomain.hpp"
#include "assemblyname.hpp"
#include "eeprofinterfaces.h"
#include "reflectclasswriter.h"
#include "comdynamic.h"
#include <wincrypt.h>
#include "urlmon.h"
#include "sha1.h"
#include "eeconfig.h"
#include "ceefilegenwriter.h"
#include "assemblynative.hpp"
#include "threadsuspend.h"
#ifdef FEATURE_PREJIT
#include "corcompile.h"
#endif
#include "appdomainnative.hpp"
#include "customattribute.h"
#include "winnls.h"
#include "caparser.h"
#include "../md/compiler/custattr.h"
#include "peimagelayout.inl"
// Define these macro's to do strict validation for jit lock and class init entry leaks.
// This defines determine if the asserts that verify for these leaks are defined or not.
// These asserts can sometimes go off even if no entries have been leaked so this defines
// should be used with caution.
//
// If we are inside a .cctor when the application shut's down then the class init lock's
// head will be set and this will cause the assert to go off.,
//
// If we are jitting a method when the application shut's down then the jit lock's head
// will be set causing the assert to go off.
//#define STRICT_JITLOCK_ENTRY_LEAK_DETECTION
//#define STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
#ifndef DACCESS_COMPILE
// This value is to make it easier to diagnose Assembly Loader "grant set" crashes.
// See Dev11 bug 358184 for more details.
// This value is not thread safe and is not intended to be. It is just a best
// effort to collect more data on the problem. Is is possible, though unlikely,
// that thread A would record a reason for an upcoming crash,
// thread B would then record a different reason, and we would then
// crash on thread A, thus ending up with the recorded reason not matching
// the thread we crash in. Be aware of this when using this value
// to help your debugging.
DWORD g_dwLoaderReasonForNotSharing = 0; // See code:DomainFile::m_dwReasonForRejectingNativeImage for a similar variable.
volatile uint32_t g_cAssemblies = 0;
// These will sometimes result in a crash with error code 0x80131401 SECURITY_E_INCOMPATIBLE_SHARE
// "Loading this assembly would produce a different grant set from other instances."
enum ReasonForNotSharing
{
ReasonForNotSharing_NoInfoRecorded = 0x1,
ReasonForNotSharing_NullDomainassembly = 0x2,
ReasonForNotSharing_DebuggerFlagMismatch = 0x3,
ReasonForNotSharing_NullPeassembly = 0x4,
ReasonForNotSharing_MissingAssemblyClosure1 = 0x5,
ReasonForNotSharing_MissingAssemblyClosure2 = 0x6,
ReasonForNotSharing_MissingDependenciesResolved = 0x7,
ReasonForNotSharing_ClosureComparisonFailed = 0x8,
};
#define NO_FRIEND_ASSEMBLIES_MARKER ((FriendAssemblyDescriptor *)S_FALSE)
//----------------------------------------------------------------------------------------------
// The ctor's job is to initialize the Assembly enough so that the dtor can safely run.
// It cannot do any allocations or operations that might fail. Those operations should be done
// in Assembly::Init()
//----------------------------------------------------------------------------------------------
Assembly::Assembly(BaseDomain *pDomain, PEAssembly* pFile, DebuggerAssemblyControlFlags debuggerFlags, BOOL fIsCollectible) :
m_pDomain(pDomain),
m_pClassLoader(NULL),
m_pEntryPoint(NULL),
m_pManifest(NULL),
m_pManifestFile(clr::SafeAddRef(pFile)),
m_pFriendAssemblyDescriptor(NULL),
m_isDynamic(false),
#ifdef FEATURE_COLLECTIBLE_TYPES
m_isCollectible(fIsCollectible),
#endif
m_nextAvailableModuleIndex(1),
m_pLoaderAllocator(NULL),
m_isDisabledPrivateReflection(0),
#ifdef FEATURE_COMINTEROP
m_pITypeLib(NULL),
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_COMINTEROP
m_InteropAttributeStatus(INTEROP_ATTRIBUTE_UNSET),
#endif
m_debuggerFlags(debuggerFlags),
m_fTerminated(FALSE),
#if defined(FEATURE_PREJIT) || defined(FEATURE_READYTORUN)
m_isInstrumentedStatus(IS_INSTRUMENTED_UNSET)
#endif
{
STANDARD_VM_CONTRACT;
}
// This name needs to stay in sync with AssemblyBuilder.ManifestModuleName
// which is used in AssemblyBuilder.InitManifestModule
#define REFEMIT_MANIFEST_MODULE_NAME W("RefEmit_InMemoryManifestModule")
//----------------------------------------------------------------------------------------------
// Does most Assembly initialization tasks. It can assume the ctor has already run
// and the assembly is safely destructable. Whether this function throws or succeeds,
// it must leave the Assembly in a safely destructable state.
//----------------------------------------------------------------------------------------------
void Assembly::Init(AllocMemTracker *pamTracker, LoaderAllocator *pLoaderAllocator)
{
STANDARD_VM_CONTRACT;
if (IsSystem())
{
_ASSERTE(pLoaderAllocator == NULL); // pLoaderAllocator may only be non-null for collectible types
m_pLoaderAllocator = SystemDomain::GetGlobalLoaderAllocator();
}
else
{
if (!IsCollectible())
{
// pLoaderAllocator will only be non-null for reflection emit assemblies
_ASSERTE((pLoaderAllocator == NULL) || (pLoaderAllocator == GetDomain()->AsAppDomain()->GetLoaderAllocator()));
m_pLoaderAllocator = GetDomain()->AsAppDomain()->GetLoaderAllocator();
}
else
{
_ASSERTE(pLoaderAllocator != NULL); // ppLoaderAllocator must be non-null for collectible assemblies
m_pLoaderAllocator = pLoaderAllocator;
}
}
_ASSERTE(m_pLoaderAllocator != NULL);
m_pClassLoader = new ClassLoader(this);
m_pClassLoader->Init(pamTracker);
#ifndef CROSSGEN_COMPILE
if (GetManifestFile()->IsDynamic())
// manifest modules of dynamic assemblies are always transient
m_pManifest = ReflectionModule::Create(this, GetManifestFile(), pamTracker, REFEMIT_MANIFEST_MODULE_NAME, TRUE);
else
#endif
m_pManifest = Module::Create(this, mdFileNil, GetManifestFile(), pamTracker);
FastInterlockIncrement((LONG*)&g_cAssemblies);
PrepareModuleForAssembly(m_pManifest, pamTracker);
CacheManifestFiles();
if (!m_pManifest->IsReadyToRun())
CacheManifestExportedTypes(pamTracker);
// We'll load the friend assembly information lazily. For the ngen case we should avoid
// loading it entirely.
//CacheFriendAssemblyInfo();
#ifndef CROSSGEN_COMPILE
if (IsCollectible())
{
COUNT_T size;
BYTE *start = (BYTE*)m_pManifest->GetFile()->GetLoadedImageContents(&size);
if (start != NULL)
{
GCX_COOP();
LoaderAllocator::AssociateMemoryWithLoaderAllocator(start, start + size, m_pLoaderAllocator);
}
}
#endif
{
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
//Cannot fail after this point.
PublishModuleIntoAssembly(m_pManifest);
return; // Explicit return to let you know you are NOT welcome to add code after the CANNOTTHROW/FAULT_FORBID expires
}
}
BOOL Assembly::IsDisabledPrivateReflection()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
enum { UNINITIALIZED, ENABLED, DISABLED};
if (m_isDisabledPrivateReflection == UNINITIALIZED)
{
HRESULT hr = GetManifestModule()->GetCustomAttribute(GetManifestToken(), WellKnownAttribute::DisablePrivateReflectionType, NULL, 0);
IfFailThrow(hr);
if (hr == S_OK)
{
m_isDisabledPrivateReflection = DISABLED;
}
else
{
m_isDisabledPrivateReflection = ENABLED;
}
}
return m_isDisabledPrivateReflection == DISABLED;
}
#ifndef CROSSGEN_COMPILE
Assembly::~Assembly()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
DISABLED(FORBID_FAULT); //Must clean up some profiler stuff
}
CONTRACTL_END
Terminate();
if (m_pFriendAssemblyDescriptor != NULL && m_pFriendAssemblyDescriptor != NO_FRIEND_ASSEMBLIES_MARKER)
delete m_pFriendAssemblyDescriptor;
if (m_pManifestFile)
{
m_pManifestFile->Release();
}
#ifdef FEATURE_COMINTEROP
if (m_pITypeLib != nullptr && m_pITypeLib != Assembly::InvalidTypeLib)
{
m_pITypeLib->Release();
}
#endif // FEATURE_COMINTEROP
}
#ifdef FEATURE_PREJIT
void Assembly::DeleteNativeCodeRanges()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
FORBID_FAULT;
}
CONTRACTL_END
ModuleIterator i = IterateModules();
while (i.Next())
i.GetModule()->DeleteNativeCodeRanges();
}
#endif
#ifdef PROFILING_SUPPORTED
void ProfilerCallAssemblyUnloadStarted(Assembly* assemblyUnloaded)
{
WRAPPER_NO_CONTRACT;
{
BEGIN_PIN_PROFILER(CORProfilerPresent());
GCX_PREEMP();
g_profControlBlock.pProfInterface->AssemblyUnloadStarted((AssemblyID)assemblyUnloaded);
END_PIN_PROFILER();
}
}
void ProfilerCallAssemblyUnloadFinished(Assembly* assemblyUnloaded)
{
WRAPPER_NO_CONTRACT;
{
BEGIN_PIN_PROFILER(CORProfilerPresent());
GCX_PREEMP();
g_profControlBlock.pProfInterface->AssemblyUnloadFinished((AssemblyID) assemblyUnloaded, S_OK);
END_PIN_PROFILER();
}
}
#endif
void Assembly::StartUnload()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FORBID_FAULT;
#ifdef PROFILING_SUPPORTED
if (CORProfilerTrackAssemblyLoads())
{
ProfilerCallAssemblyUnloadStarted(this);
}
#endif
}
void Assembly::Terminate( BOOL signalProfiler )
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STRESS_LOG1(LF_LOADER, LL_INFO100, "Assembly::Terminate (this = 0x%p)\n", reinterpret_cast<void *>(this));
if (this->m_fTerminated)
return;
if (m_pClassLoader != NULL)
{
GCX_PREEMP();
delete m_pClassLoader;
m_pClassLoader = NULL;
}
FastInterlockDecrement((LONG*)&g_cAssemblies);
#ifdef PROFILING_SUPPORTED
if (CORProfilerTrackAssemblyLoads())
{
ProfilerCallAssemblyUnloadFinished(this);
}
#endif // PROFILING_SUPPORTED
this->m_fTerminated = TRUE;
}
#endif // CROSSGEN_COMPILE
Assembly * Assembly::Create(
BaseDomain * pDomain,
PEAssembly * pFile,
DebuggerAssemblyControlFlags debuggerFlags,
BOOL fIsCollectible,
AllocMemTracker * pamTracker,
LoaderAllocator * pLoaderAllocator)
{
STANDARD_VM_CONTRACT;
NewHolder<Assembly> pAssembly (new Assembly(pDomain, pFile, debuggerFlags, fIsCollectible));
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackAssemblyLoads());
GCX_COOP();
g_profControlBlock.pProfInterface->AssemblyLoadStarted((AssemblyID)(Assembly *) pAssembly);
END_PIN_PROFILER();
}
// Need TRY/HOOK instead of holder so we can get HR of exception thrown for profiler callback
EX_TRY
#endif
{
pAssembly->Init(pamTracker, pLoaderAllocator);
}
#ifdef PROFILING_SUPPORTED
EX_HOOK
{
{
BEGIN_PIN_PROFILER(CORProfilerTrackAssemblyLoads());
GCX_COOP();
g_profControlBlock.pProfInterface->AssemblyLoadFinished((AssemblyID)(Assembly *) pAssembly,
GET_EXCEPTION()->GetHR());
END_PIN_PROFILER();
}
}
EX_END_HOOK;
#endif
pAssembly.SuppressRelease();
return pAssembly;
} // Assembly::Create
#ifndef CROSSGEN_COMPILE
Assembly *Assembly::CreateDynamic(AppDomain *pDomain, CreateDynamicAssemblyArgs *args)
{
// WARNING: not backout clean
CONTRACT(Assembly *)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(args));
}
CONTRACT_END;
// This must be before creation of the AllocMemTracker so that the destructor for the AllocMemTracker happens before the destructor for pLoaderAllocator.
// That is necessary as the allocation of Assembly objects and other related details is done on top of heaps located in
// the loader allocator objects.
NewHolder<LoaderAllocator> pLoaderAllocator;
AllocMemTracker amTracker;
AllocMemTracker *pamTracker = &amTracker;
Assembly *pRetVal = NULL;
MethodDesc *pmdEmitter = SystemDomain::GetCallersMethod(args->stackMark);
// Called either from interop or async delegate invocation. Rejecting because we don't
// know how to set the correct permission on the new dynamic assembly.
if (!pmdEmitter)
COMPlusThrow(kInvalidOperationException);
Assembly *pCallerAssembly = pmdEmitter->GetAssembly();
// First, we set up a pseudo-manifest file for the assembly.
// Set up the assembly name
STRINGREF strRefName = (STRINGREF) args->assemblyName->GetSimpleName();
if (strRefName == NULL)
COMPlusThrow(kArgumentException, W("ArgumentNull_AssemblyNameName"));
StackSString name;
strRefName->GetSString(name);
if (name.GetCount() == 0)
COMPlusThrow(kArgumentException, W("ArgumentNull_AssemblyNameName"));
SString::Iterator i = name.Begin();
if (COMCharacter::nativeIsWhiteSpace(*i)
|| name.Find(i, '\\')
|| name.Find(i, ':')
|| name.Find(i, '/'))
{
COMPlusThrow(kArgumentException, W("Argument_InvalidAssemblyName"));
}
// Set up the assembly manifest metadata
// When we create dynamic assembly, we always use a working copy of IMetaDataAssemblyEmit
// to store temporary runtime assembly information. This is to preserve the invariant that
// an assembly must have a PEFile with proper metadata.
// This working copy of IMetaDataAssemblyEmit will store every AssemblyRef as a simple name
// reference as we must have an instance of Assembly(can be dynamic assembly) before we can
// add such a reference. Also because the referenced assembly if dynamic strong name, it may
// not be ready to be hashed!
SafeComHolder<IMetaDataAssemblyEmit> pAssemblyEmit;
PEFile::DefineEmitScope(
IID_IMetaDataAssemblyEmit,
&pAssemblyEmit);
// remember the hash algorithm
ULONG ulHashAlgId = args->assemblyName->GetAssemblyHashAlgorithm();
if (ulHashAlgId == 0)
ulHashAlgId = CALG_SHA1;
ASSEMBLYMETADATA assemData;
memset(&assemData, 0, sizeof(assemData));
// get the version info (default to 0.0.0.0 if none)
VERSIONREF versionRef = (VERSIONREF) args->assemblyName->GetVersion();
if (versionRef != NULL)
{
assemData.usMajorVersion = (USHORT)versionRef->GetMajor();
assemData.usMinorVersion = (USHORT)versionRef->GetMinor();
assemData.usBuildNumber = (USHORT)versionRef->GetBuild();
assemData.usRevisionNumber = (USHORT)versionRef->GetRevision();
}
struct _gc
{
OBJECTREF cultureinfo;
STRINGREF pString;
OBJECTREF orArrayOrContainer;
OBJECTREF throwable;
OBJECTREF strongNameKeyPair;
} gc;
ZeroMemory(&gc, sizeof(gc));
GCPROTECT_BEGIN(gc);
StackSString culture;
gc.cultureinfo = args->assemblyName->GetCultureInfo();
if (gc.cultureinfo != NULL)
{
MethodDescCallSite getName(METHOD__CULTURE_INFO__GET_NAME, &gc.cultureinfo);
ARG_SLOT args2[] =
{
ObjToArgSlot(gc.cultureinfo)
};
// convert culture info into a managed string form
gc.pString = getName.Call_RetSTRINGREF(args2);
gc.pString->GetSString(culture);
assemData.szLocale = (LPWSTR) (LPCWSTR) culture;
}
SBuffer publicKey;
if (args->assemblyName->GetPublicKey() != NULL)
{
publicKey.Set(args->assemblyName->GetPublicKey()->GetDataPtr(),
args->assemblyName->GetPublicKey()->GetNumComponents());
}
// get flags
DWORD dwFlags = args->assemblyName->GetFlags();
// Now create a dynamic PE file out of the name & metadata
PEAssemblyHolder pFile;
{
GCX_PREEMP();
mdAssembly ma;
IfFailThrow(pAssemblyEmit->DefineAssembly(publicKey, publicKey.GetSize(), ulHashAlgId,
name, &assemData, dwFlags,
&ma));
pFile = PEAssembly::Create(pCallerAssembly->GetManifestFile(), pAssemblyEmit);
// Dynamically created modules (aka RefEmit assemblies) do not have a LoadContext associated with them since they are not bound
// using an actual binder. As a result, we will assume the same binding/loadcontext information for the dynamic assembly as its
// caller/creator to ensure that any assembly loads triggered by the dynamic assembly are resolved using the intended load context.
//
// If the creator assembly has a HostAssembly associated with it, then use it for binding. Otherwise, the creator is dynamic
// and will have a fallback load context binder associated with it.
ICLRPrivBinder *pFallbackLoadContextBinder = nullptr;
// There is always a manifest file - wehther working with static or dynamic assemblies.
PEFile *pCallerAssemblyManifestFile = pCallerAssembly->GetManifestFile();
_ASSERTE(pCallerAssemblyManifestFile != NULL);
if (!pCallerAssemblyManifestFile->IsDynamic())
{
// Static assemblies with do not have fallback load context
_ASSERTE(pCallerAssemblyManifestFile->GetFallbackLoadContextBinder() == nullptr);
if (pCallerAssemblyManifestFile->IsSystem())
{
// CoreLibrary is always bound to TPA binder
pFallbackLoadContextBinder = pDomain->GetTPABinderContext();
}
else
{
// Fetch the binder from the host assembly
PTR_ICLRPrivAssembly pCallerAssemblyHostAssembly = pCallerAssemblyManifestFile->GetHostAssembly();
_ASSERTE(pCallerAssemblyHostAssembly != nullptr);
UINT_PTR assemblyBinderID = 0;
IfFailThrow(pCallerAssemblyHostAssembly->GetBinderID(&assemblyBinderID));
pFallbackLoadContextBinder = reinterpret_cast<ICLRPrivBinder *>(assemblyBinderID);
}
}
else
{
// Creator assembly is dynamic too, so use its fallback load context for the one
// we are creating.
pFallbackLoadContextBinder = pCallerAssemblyManifestFile->GetFallbackLoadContextBinder();
}
// At this point, we should have a fallback load context binder to work with
_ASSERTE(pFallbackLoadContextBinder != nullptr);
// Set it as the fallback load context binder for the dynamic assembly being created
pFile->SetFallbackLoadContextBinder(pFallbackLoadContextBinder);
}
NewHolder<DomainAssembly> pDomainAssembly;
{
GCX_PREEMP();
// Create a new LoaderAllocator if appropriate
if ((args->access & ASSEMBLY_ACCESS_COLLECT) != 0)
{
AssemblyLoaderAllocator *pAssemblyLoaderAllocator = new AssemblyLoaderAllocator();
pAssemblyLoaderAllocator->SetCollectible();
pLoaderAllocator = pAssemblyLoaderAllocator;
// Some of the initialization functions are not virtual. Call through the derived class
// to prevent calling the base class version.
pAssemblyLoaderAllocator->Init(pDomain);
// Setup the managed proxy now, but do not actually transfer ownership to it.
// Once everything is setup and nothing can fail anymore, the ownership will be
// atomically transfered by call to LoaderAllocator::ActivateManagedTracking().
pAssemblyLoaderAllocator->SetupManagedTracking(&args->loaderAllocator);
}
else
{
pLoaderAllocator = pDomain->GetLoaderAllocator();
pLoaderAllocator.SuppressRelease();
}
// Create a domain assembly
pDomainAssembly = new DomainAssembly(pDomain, pFile, pLoaderAllocator);
if (pDomainAssembly->IsCollectible())
{
// We add the assembly to the LoaderAllocator only when we are sure that it can be added
// and won't be deleted in case of a concurrent load from the same ALC
((AssemblyLoaderAllocator *)(LoaderAllocator *)pLoaderAllocator)->AddDomainAssembly(pDomainAssembly);
}
}
// Start loading process
{
// Create a concrete assembly
// (!Do not remove scoping brace: order is important here: the Assembly holder must destruct before the AllocMemTracker!)
NewHolder<Assembly> pAssem;
{
GCX_PREEMP();
// Assembly::Create will call SuppressRelease on the NewHolder that holds the LoaderAllocator when it transfers ownership
pAssem = Assembly::Create(pDomain, pFile, pDomainAssembly->GetDebuggerInfoBits(), args->access & ASSEMBLY_ACCESS_COLLECT ? TRUE : FALSE, pamTracker, pLoaderAllocator);
ReflectionModule* pModule = (ReflectionModule*) pAssem->GetManifestModule();
pModule->SetCreatingAssembly( pCallerAssembly );
if ((args->access & ASSEMBLY_ACCESS_COLLECT) != 0)
{
// Initializing the virtual call stub manager is delayed to remove the need for the LoaderAllocator destructor to properly handle
// uninitializing the VSD system. (There is a need to suspend the runtime, and that's tricky)
pLoaderAllocator->InitVirtualCallStubManager(pDomain);
}
}
pAssem->m_isDynamic = true;
//we need to suppress release for pAssem to avoid double release
pAssem.SuppressRelease ();
{
GCX_PREEMP();
// Finish loading process
// <TODO> would be REALLY nice to unify this with main loading loop </TODO>
pDomainAssembly->Begin();
pDomainAssembly->SetAssembly(pAssem);
pDomainAssembly->m_level = FILE_LOAD_ALLOCATE;
pDomainAssembly->DeliverSyncEvents();
pDomainAssembly->DeliverAsyncEvents();
pDomainAssembly->FinishLoad();
pDomainAssembly->ClearLoading();
pDomainAssembly->m_level = FILE_ACTIVE;
}
{
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
//Cannot fail after this point
pDomainAssembly.SuppressRelease(); // This also effectively suppresses the release of the pAssem
pamTracker->SuppressRelease();
// Once we reach this point, the loader allocator lifetime is controlled by the Assembly object.
if ((args->access & ASSEMBLY_ACCESS_COLLECT) != 0)
{
// Atomically transfer ownership to the managed heap
pLoaderAllocator->ActivateManagedTracking();
pLoaderAllocator.SuppressRelease();
}
pAssem->SetIsTenured();
pRetVal = pAssem;
}
}
GCPROTECT_END();
RETURN pRetVal;
} // Assembly::CreateDynamic
#endif // CROSSGEN_COMPILE
void Assembly::SetDomainAssembly(DomainAssembly *pDomainAssembly)
{
CONTRACTL
{
PRECONDITION(CheckPointer(pDomainAssembly));
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
GetManifestModule()->SetDomainFile(pDomainAssembly);
} // Assembly::SetDomainAssembly
#endif // #ifndef DACCESS_COMPILE
DomainAssembly *Assembly::GetDomainAssembly()
{
LIMITED_METHOD_DAC_CONTRACT;
return GetManifestModule()->GetDomainAssembly();
}
PTR_LoaderHeap Assembly::GetLowFrequencyHeap()
{
WRAPPER_NO_CONTRACT;
return GetLoaderAllocator()->GetLowFrequencyHeap();
}
PTR_LoaderHeap Assembly::GetHighFrequencyHeap()
{
WRAPPER_NO_CONTRACT;
return GetLoaderAllocator()->GetHighFrequencyHeap();
}
PTR_LoaderHeap Assembly::GetStubHeap()
{
WRAPPER_NO_CONTRACT;
return GetLoaderAllocator()->GetStubHeap();
}
PTR_BaseDomain Assembly::GetDomain()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(m_pDomain);
return (m_pDomain);
}
#ifndef DACCESS_COMPILE
void Assembly::SetParent(BaseDomain* pParent)
{
LIMITED_METHOD_CONTRACT;
m_pDomain = pParent;
}
#endif // !DACCCESS_COMPILE
mdFile Assembly::GetManifestFileToken(LPCSTR name)
{
return mdFileNil;
}
mdFile Assembly::GetManifestFileToken(IMDInternalImport *pImport, mdFile kFile)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
LPCSTR name;
if ((TypeFromToken(kFile) != mdtFile) ||
!pImport->IsValidToken(kFile))
{
BAD_FORMAT_NOTHROW_ASSERT(!"Invalid File token");
return mdTokenNil;
}
if (FAILED(pImport->GetFileProps(kFile, &name, NULL, NULL, NULL)))
{
BAD_FORMAT_NOTHROW_ASSERT(!"Invalid File token");
return mdTokenNil;
}
return GetManifestFileToken(name);
}
Module *Assembly::FindModuleByExportedType(mdExportedType mdType,
Loader::LoadFlag loadFlag,
mdTypeDef mdNested,
mdTypeDef* pCL)
{
CONTRACT(Module *)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
POSTCONDITION(CheckPointer(RETVAL, loadFlag==Loader::Load ? NULL_NOT_OK : NULL_OK));
SUPPORTS_DAC;
}
CONTRACT_END
mdToken mdLinkRef;
mdToken mdBinding;
IMDInternalImport *pManifestImport = GetManifestImport();
IfFailThrow(pManifestImport->GetExportedTypeProps(
mdType,
NULL,
NULL,
&mdLinkRef, // Impl
&mdBinding, // Hint
NULL)); // dwflags
// Don't trust the returned tokens.
if (!pManifestImport->IsValidToken(mdLinkRef))
{
if (loadFlag != Loader::Load)
{
RETURN NULL;
}
else
{
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN);
}
}
switch(TypeFromToken(mdLinkRef)) {
case mdtAssemblyRef:
{
*pCL = mdTypeDefNil; // We don't trust the mdBinding token
Assembly *pAssembly = NULL;
switch(loadFlag)
{
case Loader::Load:
{
#ifndef DACCESS_COMPILE
// LoadAssembly never returns NULL
DomainAssembly * pDomainAssembly =
GetManifestModule()->LoadAssembly(mdLinkRef);
PREFIX_ASSUME(pDomainAssembly != NULL);
RETURN pDomainAssembly->GetCurrentModule();
#else
_ASSERTE(!"DAC shouldn't attempt to trigger loading");
return NULL;
#endif // !DACCESS_COMPILE
};
case Loader::DontLoad:
pAssembly = GetManifestModule()->GetAssemblyIfLoaded(mdLinkRef);
break;
case Loader::SafeLookup:
pAssembly = GetManifestModule()->LookupAssemblyRef(mdLinkRef);
break;
default:
_ASSERTE(FALSE);
}
if (pAssembly)
RETURN pAssembly->GetManifestModule();
else
RETURN NULL;
}
case mdtFile:
{
// We may not want to trust this TypeDef token, since it
// was saved in a scope other than the one it was defined in
if (mdNested == mdTypeDefNil)
*pCL = mdBinding;
else
*pCL = mdNested;
// Note that we don't want to attempt a LoadModule if a GetModuleIfLoaded will
// succeed, because it has a stronger contract.
Module *pModule = GetManifestModule()->GetModuleIfLoaded(mdLinkRef, TRUE, FALSE);
#ifdef DACCESS_COMPILE
return pModule;
#else
if (pModule != NULL)
RETURN pModule;
if(loadFlag==Loader::SafeLookup)
return NULL;
// We should never get here in the GC case - the above should have succeeded.
CONSISTENCY_CHECK(!FORBIDGC_LOADER_USE_ENABLED());
DomainFile * pDomainModule = GetManifestModule()->LoadModule(::GetAppDomain(), mdLinkRef, FALSE, loadFlag!=Loader::Load);
if (pDomainModule == NULL)
RETURN NULL;
else
{
pModule = pDomainModule->GetCurrentModule();
if (pModule == NULL)
{
_ASSERTE(loadFlag!=Loader::Load);
}
RETURN pModule;
}
#endif // DACCESS_COMPILE
}
case mdtExportedType:
// Only override the nested type token if it hasn't been set yet.
if (mdNested != mdTypeDefNil)
mdBinding = mdNested;
RETURN FindModuleByExportedType(mdLinkRef, loadFlag, mdBinding, pCL);
default:
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN_TYPE);
}
} // Assembly::FindModuleByExportedType
// The returned Module is non-NULL unless you prevented the load by setting loadFlag=Loader::DontLoad.
/* static */
Module * Assembly::FindModuleByTypeRef(
Module * pModule,
mdTypeRef tkType,
Loader::LoadFlag loadFlag,
BOOL * pfNoResolutionScope)
{
CONTRACT(Module *)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM();); }
MODE_ANY;
PRECONDITION(CheckPointer(pModule));
PRECONDITION(TypeFromToken(tkType) == mdtTypeRef);
PRECONDITION(CheckPointer(pfNoResolutionScope));
POSTCONDITION( CheckPointer(RETVAL, loadFlag==Loader::Load ? NULL_NOT_OK : NULL_OK) );
SUPPORTS_DAC;
}
CONTRACT_END
// WARNING! Correctness of the type forwarder detection algorithm in code:ClassLoader::ResolveTokenToTypeDefThrowing
// relies on this function not performing any form of type forwarding itself.
IMDInternalImport * pImport;
mdTypeRef tkTopLevelEncloserTypeRef;
pImport = pModule->GetMDImport();
if (TypeFromToken(tkType) != mdtTypeRef)
{
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN_TYPE);
}
{
// Find the top level encloser
GCX_NOTRIGGER();
// If nested, get top level encloser's impl
int iter = 0;
int maxIter = 1000;
do
{
_ASSERTE(TypeFromToken(tkType) == mdtTypeRef);
tkTopLevelEncloserTypeRef = tkType;
if (!pImport->IsValidToken(tkType) || iter >= maxIter)
{
break;
}
IfFailThrow(pImport->GetResolutionScopeOfTypeRef(tkType, &tkType));
// nil-scope TR okay if there's an ExportedType
// Return manifest file
if (IsNilToken(tkType))
{
*pfNoResolutionScope = TRUE;
RETURN(pModule);
}
iter++;
}
while (TypeFromToken(tkType) == mdtTypeRef);
}
*pfNoResolutionScope = FALSE;