-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathceeload.cpp
13844 lines (11594 loc) · 447 KB
/
ceeload.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.
// ===========================================================================
// File: CEELOAD.CPP
//
//
// CEELOAD reads in the PE file format using LoadLibrary
// ===========================================================================
#include "common.h"
#include "array.h"
#include "ceeload.h"
#include "hash.h"
#include "vars.hpp"
#include "reflectclasswriter.h"
#include "method.hpp"
#include "stublink.h"
#include "cgensys.h"
#include "excep.h"
#include "dbginterface.h"
#include "dllimport.h"
#include "eeprofinterfaces.h"
#include "encee.h"
#include "jitinterface.h"
#include "eeconfig.h"
#include "dllimportcallback.h"
#include "contractimpl.h"
#include "typehash.h"
#include "instmethhash.h"
#include "virtualcallstub.h"
#include "typestring.h"
#include "stringliteralmap.h"
#include <formattype.h>
#include "fieldmarshaler.h"
#include "sigbuilder.h"
#include "metadataexports.h"
#include "inlinetracking.h"
#include "threads.h"
#include "nativeimage.h"
#ifdef FEATURE_PREJIT
#include "exceptionhandling.h"
#include "corcompile.h"
#include "compile.h"
#include "nibblestream.h"
#include "zapsig.h"
#endif //FEATURE_PREJIT
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "comcallablewrapper.h"
#endif //FEATURE_COMINTEROP
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4724)
#endif // _MSC_VER
#include "ngenhash.inl"
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
#include "ecall.h"
#include "../md/compiler/custattr.h"
#include "typekey.h"
#include "peimagelayout.inl"
#include "ildbsymlib.h"
#if defined(PROFILING_SUPPORTED)
#include "profilermetadataemitvalidator.h"
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4244)
#endif // _MSC_VER
#ifdef TARGET_64BIT
#define COR_VTABLE_PTRSIZED COR_VTABLE_64BIT
#define COR_VTABLE_NOT_PTRSIZED COR_VTABLE_32BIT
#else // !TARGET_64BIT
#define COR_VTABLE_PTRSIZED COR_VTABLE_32BIT
#define COR_VTABLE_NOT_PTRSIZED COR_VTABLE_64BIT
#endif // !TARGET_64BIT
#define CEE_FILE_GEN_GROWTH_COLLECTIBLE 2048
#define NGEN_STATICS_ALLCLASSES_WERE_LOADED -1
BOOL Module::HasNativeOrReadyToRunInlineTrackingMap()
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef FEATURE_READYTORUN
if (IsReadyToRun() && GetReadyToRunInfo()->GetInlineTrackingMap() != NULL)
{
return TRUE;
}
#endif
return (m_pPersistentInlineTrackingMapNGen != NULL);
}
COUNT_T Module::GetNativeOrReadyToRunInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData)
{
WRAPPER_NO_CONTRACT;
#ifdef FEATURE_READYTORUN
if(IsReadyToRun() && GetReadyToRunInfo()->GetInlineTrackingMap() != NULL)
{
return GetReadyToRunInfo()->GetInlineTrackingMap()->GetInliners(inlineeOwnerMod, inlineeTkn, inlinersSize, inliners, incompleteData);
}
#endif
if(m_pPersistentInlineTrackingMapNGen != NULL)
{
return m_pPersistentInlineTrackingMapNGen->GetInliners(inlineeOwnerMod, inlineeTkn, inlinersSize, inliners, incompleteData);
}
return 0;
}
#if defined(PROFILING_SUPPORTED) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
BOOL Module::HasJitInlineTrackingMap()
{
LIMITED_METHOD_CONTRACT;
return m_pJitInlinerTrackingMap != NULL;
}
void Module::AddInlining(MethodDesc *inliner, MethodDesc *inlinee)
{
STANDARD_VM_CONTRACT;
_ASSERTE(inliner != NULL && inlinee != NULL);
_ASSERTE(inlinee->GetModule() == this);
if (m_pJitInlinerTrackingMap != NULL)
{
m_pJitInlinerTrackingMap->AddInlining(inliner, inlinee);
}
}
#endif // defined(PROFILING_SUPPORTED) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
#ifndef DACCESS_COMPILE
// ===========================================================================
// Module
// ===========================================================================
//---------------------------------------------------------------------------------------------------
// This wrapper just invokes the real initialization inside a try/hook.
// szName is not null only for dynamic modules
//---------------------------------------------------------------------------------------------------
void Module::DoInit(AllocMemTracker *pamTracker, LPCWSTR szName)
{
CONTRACTL
{
INSTANCE_CHECK;
STANDARD_VM_CHECK;
}
CONTRACTL_END;
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads());
GCX_COOP();
g_profControlBlock.pProfInterface->ModuleLoadStarted((ModuleID) this);
END_PIN_PROFILER();
}
// Need TRY/HOOK instead of holder so we can get HR of exception thrown for profiler callback
EX_TRY
#endif
{
Initialize(pamTracker, szName);
}
#ifdef PROFILING_SUPPORTED
EX_HOOK
{
{
BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads());
g_profControlBlock.pProfInterface->ModuleLoadFinished((ModuleID) this, GET_EXCEPTION()->GetHR());
END_PIN_PROFILER();
}
}
EX_END_HOOK;
#endif
}
// Set the given bit on m_dwTransientFlags. Return true if we won the race to set the bit.
BOOL Module::SetTransientFlagInterlocked(DWORD dwFlag)
{
LIMITED_METHOD_CONTRACT;
for (;;)
{
DWORD dwTransientFlags = m_dwTransientFlags;
if ((dwTransientFlags & dwFlag) != 0)
return FALSE;
if ((DWORD)FastInterlockCompareExchange((LONG*)&m_dwTransientFlags, dwTransientFlags | dwFlag, dwTransientFlags) == dwTransientFlags)
return TRUE;
}
}
#if PROFILING_SUPPORTED
void Module::UpdateNewlyAddedTypes()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
DWORD countTypesAfterProfilerUpdate = GetMDImport()->GetCountWithTokenKind(mdtTypeDef);
DWORD countExportedTypesAfterProfilerUpdate = GetMDImport()->GetCountWithTokenKind(mdtExportedType);
DWORD countCustomAttributeCount = GetMDImport()->GetCountWithTokenKind(mdtCustomAttribute);
// R2R pre-computes an export table and tries to avoid populating a class hash at runtime. However the profiler can
// still add new types on the fly by calling here. If that occurs we fallback to the slower path of creating the
// in memory hashtable as usual.
if (!IsResource() && GetAvailableClassHash() == NULL)
{
// This call will populate the hash tables with anything that is in metadata already.
GetClassLoader()->LazyPopulateCaseSensitiveHashTablesDontHaveLock();
}
else
{
// If the hash tables already exist (either R2R and we've previously populated the ) we need to manually add the types.
// typeDefs rids 0 and 1 aren't included in the count, thus X typeDefs before means rid X+1 was valid and our incremental addition should start at X+2
for (DWORD typeDefRid = m_dwTypeCount + 2; typeDefRid < countTypesAfterProfilerUpdate + 2; typeDefRid++)
{
GetAssembly()->AddType(this, TokenFromRid(typeDefRid, mdtTypeDef));
}
// exportedType rid 0 isn't included in the count, thus X exportedTypes before means rid X was valid and our incremental addition should start at X+1
for (DWORD exportedTypeDef = m_dwExportedTypeCount + 1; exportedTypeDef < countExportedTypesAfterProfilerUpdate + 1; exportedTypeDef++)
{
GetAssembly()->AddExportedType(TokenFromRid(exportedTypeDef, mdtExportedType));
}
if ((countCustomAttributeCount != m_dwCustomAttributeCount) && IsReadyToRun())
{
// Set of custom attributes has changed. Disable the cuckoo filter from ready to run, and do normal custom attribute parsing
GetReadyToRunInfo()->DisableCustomAttributeFilter();
}
}
m_dwTypeCount = countTypesAfterProfilerUpdate;
m_dwExportedTypeCount = countExportedTypesAfterProfilerUpdate;
m_dwCustomAttributeCount = countCustomAttributeCount;
}
void Module::NotifyProfilerLoadFinished(HRESULT hr)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
MODE_ANY;
}
CONTRACTL_END;
// Note that in general we wil reuse shared modules. So we need to make sure we only notify
// the profiler once.
if (SetTransientFlagInterlocked(IS_PROFILER_NOTIFIED))
{
// Record how many types are already present
if (!IsResource())
{
m_dwTypeCount = GetMDImport()->GetCountWithTokenKind(mdtTypeDef);
m_dwExportedTypeCount = GetMDImport()->GetCountWithTokenKind(mdtExportedType);
m_dwCustomAttributeCount = GetMDImport()->GetCountWithTokenKind(mdtCustomAttribute);
}
// Notify the profiler, this may cause metadata to be updated
{
BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads());
{
GCX_PREEMP();
g_profControlBlock.pProfInterface->ModuleLoadFinished((ModuleID) this, hr);
if (SUCCEEDED(hr))
{
g_profControlBlock.pProfInterface->ModuleAttachedToAssembly((ModuleID) this,
(AssemblyID)m_pAssembly);
}
}
END_PIN_PROFILER();
}
// If there are more types than before, add these new types to the
// assembly
if (!IsResource())
{
UpdateNewlyAddedTypes();
}
{
BEGIN_PIN_PROFILER(CORProfilerTrackAssemblyLoads());
if (IsManifest())
{
GCX_COOP();
g_profControlBlock.pProfInterface->AssemblyLoadFinished((AssemblyID) m_pAssembly, hr);
}
END_PIN_PROFILER();
}
}
}
#ifndef CROSSGEN_COMPILE
IMetaDataEmit *Module::GetValidatedEmitter()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM());
MODE_ANY;
}
CONTRACTL_END;
if (m_pValidatedEmitter.Load() == NULL)
{
// In the past profilers could call any API they wanted on the the IMetaDataEmit interface and we didn't
// verify anything. To ensure we don't break back-compat the verifications are not enabled by default.
// Right now I have only added verifications for NGEN images, but in the future we might want verifications
// for all modules.
IMetaDataEmit* pEmit = NULL;
if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_ProfAPI_ValidateNGENInstrumentation) && HasNativeImage())
{
ProfilerMetadataEmitValidator* pValidator = new ProfilerMetadataEmitValidator(GetEmitter());
pValidator->QueryInterface(IID_IMetaDataEmit, (void**)&pEmit);
}
else
{
pEmit = GetEmitter();
pEmit->AddRef();
}
// Atomically swap it into the field (release it if we lose the race)
if (FastInterlockCompareExchangePointer(&m_pValidatedEmitter, pEmit, NULL) != NULL)
{
pEmit->Release();
}
}
return m_pValidatedEmitter.Load();
}
#endif // CROSSGEN_COMPILE
#endif // PROFILING_SUPPORTED
void Module::NotifyEtwLoadFinished(HRESULT hr)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
}
CONTRACTL_END
// we report only successful loads
if (SUCCEEDED(hr) &&
ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context,
TRACE_LEVEL_INFORMATION,
KEYWORDZERO))
{
BOOL fSharedModule = !SetTransientFlagInterlocked(IS_ETW_NOTIFIED);
ETW::LoaderLog::ModuleLoad(this, fSharedModule);
}
}
// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The constructor phase initializes just enough so that Destruct() can be safely called.
// It cannot throw or fail.
//
Module::Module(Assembly *pAssembly, mdFile moduleRef, PEFile *file)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
}
CONTRACTL_END
PREFIX_ASSUME(pAssembly != NULL);
m_pAssembly = pAssembly;
m_moduleRef = moduleRef;
m_file = file;
m_dwTransientFlags = CLASSES_FREED;
if (!m_file->HasNativeImage())
{
// Memory allocated on LoaderHeap is zero-filled. Spot-check it here.
_ASSERTE(m_pBinder == NULL);
_ASSERTE(m_symbolFormat == eSymbolFormatNone);
}
file->AddRef();
}
void Module::InitializeForProfiling()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_PREEMPTIVE;
PRECONDITION(HasNativeOrReadyToRunImage());
}
CONTRACTL_END;
COUNT_T cbProfileList = 0;
m_nativeImageProfiling = FALSE;
#ifdef FEATURE_PREJIT
if (HasNativeImage())
{
PEImageLayout * pNativeImage = GetNativeImage();
CORCOMPILE_VERSION_INFO * pNativeVersionInfo = pNativeImage->GetNativeVersionInfoMaybeNull();
if ((pNativeVersionInfo != NULL) && (pNativeVersionInfo->wConfigFlags & CORCOMPILE_CONFIG_INSTRUMENTATION))
{
m_nativeImageProfiling = GetAssembly()->IsInstrumented();
}
// Link the module to the profile data list if available.
m_methodProfileList = pNativeImage->GetNativeProfileDataList(&cbProfileList);
}
else // ReadyToRun image
#endif
{
#ifdef FEATURE_READYTORUN
// We already setup the m_methodProfileList in the ReadyToRunInfo constructor
if (m_methodProfileList != nullptr)
{
ReadyToRunInfo * pInfo = GetReadyToRunInfo();
PEImageLayout * pImage = pInfo->GetImage();
// Enable profiling if the ZapBBInstr value says to
m_nativeImageProfiling = GetAssembly()->IsInstrumented();
}
#endif
}
}
#ifdef FEATURE_PREJIT
void Module::InitializeNativeImage(AllocMemTracker* pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_PREEMPTIVE;
PRECONDITION(HasNativeImage());
}
CONTRACTL_END;
PEImageLayout * pNativeImage = GetNativeImage();
ExecutionManager::AddNativeImageRange(dac_cast<TADDR>(pNativeImage->GetBase()), pNativeImage->GetVirtualSize(), this);
#ifndef CROSSGEN_COMPILE
LoadTokenTables();
LoadHelperTable();
#endif // CROSSGEN_COMPILE
#if defined(HAVE_GCCOVER)
if (GCStress<cfg_instr_ngen>::IsEnabled())
{
// Setting up gc coverage requires the base system classes
// to be initialized. So we must defer this for CoreLib.
if(!IsSystem())
{
SetupGcCoverageForNativeImage(this);
}
}
#endif // defined(HAVE_GCCOVER)
}
#else // FEATURE_PREJIT
BOOL Module::IsPersistedObject(void *address)
{
LIMITED_METHOD_CONTRACT;
return FALSE;
}
#endif // FEATURE_PREJIT
uint32_t Module::GetNativeMetadataAssemblyCount()
{
if (m_pNativeImage != NULL)
{
return m_pNativeImage->GetManifestAssemblyCount();
}
else
{
return GetNativeAssemblyImport()->GetCountWithTokenKind(mdtAssemblyRef);
}
}
void Module::SetNativeMetadataAssemblyRefInCache(DWORD rid, PTR_Assembly pAssembly)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
if (m_NativeMetadataAssemblyRefMap == NULL)
{
uint32_t dwMaxRid = GetNativeMetadataAssemblyCount();
_ASSERTE(dwMaxRid > 0);
S_SIZE_T dwAllocSize = S_SIZE_T(sizeof(PTR_Assembly)) * S_SIZE_T(dwMaxRid);
AllocMemTracker amTracker;
PTR_Assembly* NativeMetadataAssemblyRefMap = (PTR_Assembly*)amTracker.Track(GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(dwAllocSize));
// Note: Memory allocated on loader heap is zero filled
if (InterlockedCompareExchangeT<PTR_Assembly*>(&m_NativeMetadataAssemblyRefMap, NativeMetadataAssemblyRefMap, NULL) == NULL)
amTracker.SuppressRelease();
}
_ASSERTE(m_NativeMetadataAssemblyRefMap != NULL);
_ASSERTE(rid <= GetNativeMetadataAssemblyCount());
m_NativeMetadataAssemblyRefMap[rid - 1] = pAssembly;
}
// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The Initialize() phase completes the initialization after the constructor has run.
// It can throw exceptions but whether it throws or succeeds, it must leave the Module
// in a state where Destruct() can be safely called.
//
// szName is only used by dynamic modules, see ReflectionModule::Initialize
//
//
void Module::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName)
{
CONTRACTL
{
INSTANCE_CHECK;
STANDARD_VM_CHECK;
PRECONDITION(szName == NULL);
}
CONTRACTL_END;
m_pSimpleName = m_file->GetSimpleName();
m_Crst.Init(CrstModule);
m_LookupTableCrst.Init(CrstModuleLookupTable, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD));
m_FixupCrst.Init(CrstModuleFixup, (CrstFlags)(CRST_HOST_BREAKABLE|CRST_REENTRANCY));
m_InstMethodHashTableCrst.Init(CrstInstMethodHashTable, CRST_REENTRANCY);
m_ISymUnmanagedReaderCrst.Init(CrstISymUnmanagedReader, CRST_DEBUGGER_THREAD);
m_DictionaryCrst.Init(CrstDomainLocalBlock);
if (!m_file->HasNativeImage())
{
AllocateMaps();
if (IsSystem() ||
(strcmp(m_pSimpleName, "System") == 0) ||
(strcmp(m_pSimpleName, "System.Core") == 0))
{
FastInterlockOr(&m_dwPersistedFlags, LOW_LEVEL_SYSTEM_ASSEMBLY_BY_NAME);
}
}
m_dwTransientFlags &= ~((DWORD)CLASSES_FREED); // Set flag indicating LookupMaps are now in a consistent and destructable state
#ifdef FEATURE_COLLECTIBLE_TYPES
if (GetAssembly()->IsCollectible())
{
FastInterlockOr(&m_dwPersistedFlags, COLLECTIBLE_MODULE);
}
#endif // FEATURE_COLLECTIBLE_TYPES
#ifdef FEATURE_READYTORUN
m_pNativeImage = NULL;
if (!HasNativeImage() && !IsResource())
{
if ((m_pReadyToRunInfo = ReadyToRunInfo::Initialize(this, pamTracker)) != NULL)
{
m_pNativeImage = m_pReadyToRunInfo->GetNativeImage();
if (m_pNativeImage != NULL)
{
m_NativeMetadataAssemblyRefMap = m_pNativeImage->GetManifestMetadataAssemblyRefMap();
}
else
{
// For composite images, manifest metadata gets loaded as part of the native image
COUNT_T cMeta = 0;
if (GetFile()->GetOpenedILimage()->GetNativeManifestMetadata(&cMeta) != NULL)
{
// Load the native assembly import
GetNativeAssemblyImport(TRUE /* loadAllowed */);
}
}
}
}
#endif
// Initialize the instance fields that we need for all non-Resource Modules
if (!IsResource())
{
if (m_pAvailableClasses == NULL && !IsReadyToRun())
{
m_pAvailableClasses = EEClassHashTable::Create(this,
GetAssembly()->IsCollectible() ? AVAILABLE_CLASSES_HASH_BUCKETS_COLLECTIBLE : AVAILABLE_CLASSES_HASH_BUCKETS,
FALSE /* bCaseInsensitive */, pamTracker);
}
if (m_pAvailableParamTypes == NULL)
{
m_pAvailableParamTypes = EETypeHashTable::Create(GetLoaderAllocator(), this, PARAMTYPES_HASH_BUCKETS, pamTracker);
}
if (m_pInstMethodHashTable == NULL)
{
m_pInstMethodHashTable = InstMethodHashTable::Create(GetLoaderAllocator(), this, PARAMMETHODS_HASH_BUCKETS, pamTracker);
}
if(m_pMemberRefToDescHashTable == NULL)
{
if (IsReflection())
{
m_pMemberRefToDescHashTable = MemberRefToDescHashTable::Create(this, MEMBERREF_MAP_INITIAL_SIZE, pamTracker);
}
else
{
IMDInternalImport * pImport = GetMDImport();
// Get #MemberRefs and create memberrefToDesc hash table
m_pMemberRefToDescHashTable = MemberRefToDescHashTable::Create(this, pImport->GetCountWithTokenKind(mdtMemberRef)+1, pamTracker);
}
}
}
// this will be initialized a bit later.
m_ModuleID = NULL;
m_ModuleIndex.m_dwIndex = (SIZE_T)-1;
// These will be initialized in NotifyProfilerLoadFinished, set them to
// a safe initial value now.
m_dwTypeCount = 0;
m_dwExportedTypeCount = 0;
m_dwCustomAttributeCount = 0;
// Prepare statics that are known at module load time
AllocateStatics(pamTracker);
#ifdef FEATURE_PREJIT
// Set up native image
if (HasNativeImage())
{
InitializeNativeImage(pamTracker);
}
#endif // FEATURE_PREJIT
if (HasNativeOrReadyToRunImage())
{
InitializeForProfiling();
}
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
if (g_CorCompileVerboseLevel)
m_pNgenStats = new NgenStats();
#endif
if (!IsResource() && (m_AssemblyRefByNameTable == NULL))
{
Module::CreateAssemblyRefByNameTable(pamTracker);
}
// If the program has the "ForceEnc" env variable set we ensure every eligible
// module has EnC turned on.
if (g_pConfig->ForceEnc() && IsEditAndContinueCapable())
EnableEditAndContinue();
#if defined(PROFILING_SUPPORTED) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
m_pJitInlinerTrackingMap = NULL;
if (ReJitManager::IsReJITInlineTrackingEnabled())
{
m_pJitInlinerTrackingMap = new JITInlineTrackingMap(GetLoaderAllocator());
}
#endif // defined (PROFILING_SUPPORTED) &&!defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
LOG((LF_CLASSLOADER, LL_INFO10, "Loaded pModule: \"%ws\".\n", GetDebugName()));
}
#endif // DACCESS_COMPILE
#ifdef FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
// static
GuidToMethodTableHashTable* GuidToMethodTableHashTable::Create(Module* pModule, DWORD cInitialBuckets,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED());
}
CONTRACTL_END;
LoaderHeap *pHeap = pModule->GetAssembly()->GetLowFrequencyHeap();
GuidToMethodTableHashTable *pThis = (GuidToMethodTableHashTable*)pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(GuidToMethodTableHashTable)));
// The base class get initialized through chaining of constructors. We allocated the hash instance via the
// loader heap instead of new so use an in-place new to call the constructors now.
new (pThis) GuidToMethodTableHashTable(pModule, pHeap, cInitialBuckets);
return pThis;
}
GuidToMethodTableEntry *GuidToMethodTableHashTable::InsertValue(PTR_GUID pGuid, PTR_MethodTable pMT,
BOOL bReplaceIfFound, AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED());
}
CONTRACTL_END;
GuidToMethodTableEntry *pEntry = NULL;
if (bReplaceIfFound)
{
pEntry = FindItem(pGuid, NULL);
}
if (pEntry != NULL)
{
pEntry->m_pMT = pMT;
}
else
{
pEntry = BaseAllocateEntry(pamTracker);
pEntry->m_Guid = pGuid;
pEntry->m_pMT = pMT;
DWORD hash = Hash(pGuid);
BaseInsertEntry(hash, pEntry);
}
return pEntry;
}
#endif // !DACCESS_COMPILE
PTR_MethodTable GuidToMethodTableHashTable::GetValue(const GUID * pGuid, LookupContext *pContext)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
PRECONDITION(CheckPointer(pGuid));
}
CONTRACTL_END;
GuidToMethodTableEntry * pEntry = FindItem(pGuid, pContext);
if (pEntry != NULL)
{
return pEntry->m_pMT;
}
return NULL;
}
GuidToMethodTableEntry *GuidToMethodTableHashTable::FindItem(const GUID * pGuid, LookupContext *pContext)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
PRECONDITION(CheckPointer(pGuid));
}
CONTRACTL_END;
// It's legal for the caller not to pass us a LookupContext, but we might need to iterate
// internally (since we lookup via hash and hashes may collide). So substitute our own
// private context if one was not provided.
LookupContext sAltContext;
if (pContext == NULL)
pContext = &sAltContext;
// The base class provides the ability to enumerate all entries with the same hash code.
// We further check which of these entries actually match the full key.
PTR_GuidToMethodTableEntry pSearch = BaseFindFirstEntryByHash(Hash(pGuid), pContext);
while (pSearch)
{
if (CompareKeys(pSearch, pGuid))
{
return pSearch;
}
pSearch = BaseFindNextEntryByHash(pContext);
}
return NULL;
}
BOOL GuidToMethodTableHashTable::CompareKeys(PTR_GuidToMethodTableEntry pEntry, const GUID * pGuid)
{
LIMITED_METHOD_DAC_CONTRACT;
return *pGuid == *(pEntry->m_Guid);
}
DWORD GuidToMethodTableHashTable::Hash(const GUID * pGuid)
{
LIMITED_METHOD_DAC_CONTRACT;
static_assert_no_msg(sizeof(GUID) % sizeof(DWORD) == 0);
static_assert_no_msg(sizeof(GUID) / sizeof(DWORD) == 4);
DWORD * pSlice = (DWORD*) pGuid;
return pSlice[0] ^ pSlice[1] ^ pSlice[2] ^ pSlice[3];
}
BOOL GuidToMethodTableHashTable::FindNext(Iterator *it, GuidToMethodTableEntry **ppEntry)
{
LIMITED_METHOD_DAC_CONTRACT;
if (!it->m_fIterating)
{
BaseInitIterator(&it->m_sIterator);
it->m_fIterating = true;
}
*ppEntry = it->m_sIterator.Next();
return *ppEntry ? TRUE : FALSE;
}
DWORD GuidToMethodTableHashTable::GetCount()
{
LIMITED_METHOD_DAC_CONTRACT;
return BaseGetElementCount();
}
#if defined(FEATURE_NATIVE_IMAGE_GENERATION) && !defined(DACCESS_COMPILE)
void GuidToMethodTableHashTable::Save(DataImage *pImage, CorProfileData *pProfileData)
{
WRAPPER_NO_CONTRACT;
Base_t::BaseSave(pImage, pProfileData);
}
void GuidToMethodTableHashTable::Fixup(DataImage *pImage)
{
WRAPPER_NO_CONTRACT;
Base_t::BaseFixup(pImage);
}
bool GuidToMethodTableHashTable::SaveEntry(DataImage *pImage, CorProfileData *pProfileData,
GuidToMethodTableEntry *pOldEntry, GuidToMethodTableEntry *pNewEntry,
EntryMappingTable *pMap)
{
LIMITED_METHOD_CONTRACT;
return false;
}
void GuidToMethodTableHashTable::FixupEntry(DataImage *pImage, GuidToMethodTableEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset)
{
WRAPPER_NO_CONTRACT;
pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(GuidToMethodTableEntry, m_pMT), pEntry->m_pMT);
pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(GuidToMethodTableEntry, m_Guid), pEntry->m_Guid);
}
#endif // FEATURE_NATIVE_IMAGE_GENERATION && !DACCESS_COMPILE
#endif // FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
MemberRefToDescHashTable* MemberRefToDescHashTable::Create(Module *pModule, DWORD cInitialBuckets, AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED());
}
CONTRACTL_END;
LoaderHeap *pHeap = pModule->GetAssembly()->GetLowFrequencyHeap();
MemberRefToDescHashTable *pThis = (MemberRefToDescHashTable*)pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(MemberRefToDescHashTable)));
// The base class get initialized through chaining of constructors. We allocated the hash instance via the
// loader heap instead of new so use an in-place new to call the constructors now.
new (pThis) MemberRefToDescHashTable(pModule, pHeap, cInitialBuckets);
return pThis;
}
//Inserts FieldRef
MemberRefToDescHashEntry* MemberRefToDescHashTable::Insert(mdMemberRef token , FieldDesc *value)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED());
}
CONTRACTL_END;
LookupContext sAltContext;
_ASSERTE((dac_cast<TADDR>(value) & IS_FIELD_MEMBER_REF) == 0);
MemberRefToDescHashEntry *pEntry = (PTR_MemberRefToDescHashEntry) BaseFindFirstEntryByHash(RidFromToken(token), &sAltContext);
if (pEntry != NULL)
{
// If memberRef is hot token in that case entry for memberref is already persisted in ngen image. So entry for it will already be present in hash table.
// However its value will be null. We need to set its actual value.
if(pEntry->m_value == dac_cast<TADDR>(NULL))
{
pEntry->m_value = dac_cast<TADDR>(value)|IS_FIELD_MEMBER_REF;
}
_ASSERTE(pEntry->m_value == (dac_cast<TADDR>(value)|IS_FIELD_MEMBER_REF));
return pEntry;
}
// For non hot tokens insert new entry in hashtable
pEntry = BaseAllocateEntry(NULL);
pEntry->m_value = dac_cast<TADDR>(value)|IS_FIELD_MEMBER_REF;
BaseInsertEntry(RidFromToken(token), pEntry);
return pEntry;
}
// Insert MethodRef
MemberRefToDescHashEntry* MemberRefToDescHashTable::Insert(mdMemberRef token , MethodDesc *value)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED());
}
CONTRACTL_END;
LookupContext sAltContext;
MemberRefToDescHashEntry *pEntry = (PTR_MemberRefToDescHashEntry) BaseFindFirstEntryByHash(RidFromToken(token), &sAltContext);
if (pEntry != NULL)
{
// If memberRef is hot token in that case entry for memberref is already persisted in ngen image. So entry for it will already be present in hash table.
// However its value will be null. We need to set its actual value.
if(pEntry->m_value == dac_cast<TADDR>(NULL))
{
pEntry->m_value = dac_cast<TADDR>(value);
}
_ASSERTE(pEntry->m_value == dac_cast<TADDR>(value));
return pEntry;
}
// For non hot tokens insert new entry in hashtable
pEntry = BaseAllocateEntry(NULL);
pEntry->m_value = dac_cast<TADDR>(value);
BaseInsertEntry(RidFromToken(token), pEntry);
return pEntry;
}
#if defined(FEATURE_NATIVE_IMAGE_GENERATION)
void MemberRefToDescHashTable::Save(DataImage *pImage, CorProfileData *pProfileData)