-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
ceeload.cpp
4881 lines (4062 loc) · 146 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_COMINTEROP
#include "runtimecallablewrapper.h"
#include "comcallablewrapper.h"
#endif //FEATURE_COMINTEROP
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4724)
#endif // _MSC_VER
#include "dacenumerablehash.inl"
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
#include "ecall.h"
#include "../md/compiler/custattr.h"
#include "typekey.h"
#include "peimagelayout.inl"
#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::HasReadyToRunInlineTrackingMap()
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef FEATURE_READYTORUN
if (IsReadyToRun() && GetReadyToRunInfo()->HasReadyToRunInlineTrackingMap())
{
return TRUE;
}
#endif
return FALSE;
}
COUNT_T Module::GetReadyToRunInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData)
{
WRAPPER_NO_CONTRACT;
#ifdef FEATURE_READYTORUN
if(HasReadyToRunInlineTrackingMap())
{
return GetReadyToRunInfo()->GetInliners(inlineeOwnerMod, inlineeTkn, inlinersSize, inliners, incompleteData);
}
#endif
return 0;
}
#if defined(PROFILING_SUPPORTED) && !defined(DACCESS_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)
#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_PROFILER_CALLBACK(CORProfilerTrackModuleLoads());
GCX_COOP();
(&g_profControlBlock)->ModuleLoadStarted((ModuleID) this);
END_PROFILER_CALLBACK();
}
// 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_PROFILER_CALLBACK(CORProfilerTrackModuleLoads());
(&g_profControlBlock)->ModuleLoadFinished((ModuleID) this, GET_EXCEPTION()->GetHR());
END_PROFILER_CALLBACK();
}
}
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)InterlockedCompareExchange((LONG*)&m_dwTransientFlags, dwTransientFlags | dwFlag, dwTransientFlags) == dwTransientFlags)
return TRUE;
}
}
#if defined(PROFILING_SUPPORTED) || defined(FEATURE_METADATA_UPDATER)
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);
if (m_dwTypeCount == countTypesAfterProfilerUpdate
&& m_dwExportedTypeCount == countExportedTypesAfterProfilerUpdate
&& m_dwCustomAttributeCount == countCustomAttributeCount)
{
// The profiler added no new types, do not create the in memory hashes
return;
}
// 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 (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;
}
#endif // PROFILING_SUPPORTED || FEATURE_METADATA_UPDATER
#if PROFILING_SUPPORTED
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
m_dwTypeCount = GetMDImport()->GetCountWithTokenKind(mdtTypeDef);
m_dwExportedTypeCount = GetMDImport()->GetCountWithTokenKind(mdtExportedType);
m_dwCustomAttributeCount = GetMDImport()->GetCountWithTokenKind(mdtCustomAttribute);
BOOL profilerCallbackHappened = FALSE;
// Notify the profiler, this may cause metadata to be updated
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackModuleLoads());
{
GCX_PREEMP();
(&g_profControlBlock)->ModuleLoadFinished((ModuleID) this, hr);
if (SUCCEEDED(hr))
{
(&g_profControlBlock)->ModuleAttachedToAssembly((ModuleID) this,
(AssemblyID)m_pAssembly);
}
profilerCallbackHappened = TRUE;
}
END_PROFILER_CALLBACK();
}
// If there are more types than before, add these new types to the
// assembly
if (profilerCallbackHappened)
{
UpdateNewlyAddedTypes();
}
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackAssemblyLoads());
{
GCX_COOP();
(&g_profControlBlock)->AssemblyLoadFinished((AssemblyID) m_pAssembly, hr);
}
END_PROFILER_CALLBACK();
}
}
}
#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, PEAssembly *pPEAssembly)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
}
CONTRACTL_END
PREFIX_ASSUME(pAssembly != NULL);
m_loaderAllocator = NULL;
m_pAssembly = pAssembly;
m_pPEAssembly = pPEAssembly;
m_dwTransientFlags = CLASSES_FREED;
m_pDynamicMetadata = (TADDR)NULL;
pPEAssembly->AddRef();
}
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());
VolatileStore(&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);
PRECONDITION(m_pPEAssembly->IsLoaded());
}
CONTRACTL_END;
m_loaderAllocator = GetAssembly()->GetLoaderAllocator();
m_pSimpleName = m_pPEAssembly->GetSimpleName();
m_baseAddress = m_pPEAssembly->HasLoadedPEImage() ? m_pPEAssembly->GetLoadedLayout()->GetBase() : NULL;
if (m_pPEAssembly->IsReflectionEmit())
m_dwTransientFlags |= IS_REFLECTION_EMIT;
m_Crst.Init(CrstModule);
m_LookupTableCrst.Init(CrstModuleLookupTable, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD));
m_InstMethodHashTableCrst.Init(CrstInstMethodHashTable, CRST_REENTRANCY);
m_ISymUnmanagedReaderCrst.Init(CrstISymUnmanagedReader, CRST_DEBUGGER_THREAD);
AllocateMaps();
m_dwTransientFlags &= ~((DWORD)CLASSES_FREED); // Set flag indicating LookupMaps are now in a consistent and destructable state
#ifdef FEATURE_READYTORUN
m_pNativeImage = NULL;
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 (GetPEAssembly()->GetPEImage()->GetNativeManifestMetadata(&cMeta) != NULL)
{
// Load the native assembly import
GetNativeAssemblyImport(TRUE /* loadAllowed */);
}
}
}
#endif
// Initialize the instance fields that we need for all Modules
if (m_pAvailableClasses == NULL && !IsReadyToRun())
{
m_pAvailableClasses = EEClassHashTable::Create(this,
GetAssembly()->IsCollectible() ? AVAILABLE_CLASSES_HASH_BUCKETS_COLLECTIBLE : AVAILABLE_CLASSES_HASH_BUCKETS,
NULL, 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);
}
// These will be initialized in NotifyProfilerLoadFinished, set them to
// a safe initial value now.
m_dwTypeCount = 0;
m_dwExportedTypeCount = 0;
m_dwCustomAttributeCount = 0;
if (m_AssemblyRefByNameTable == NULL)
{
Module::CreateAssemblyRefByNameTable(pamTracker);
}
#if defined(PROFILING_SUPPORTED) && !defined(DACCESS_COMPILE)
m_pJitInlinerTrackingMap = NULL;
if (ReJitManager::IsReJITInlineTrackingEnabled())
{
m_pJitInlinerTrackingMap = new JITInlineTrackingMap(GetLoaderAllocator());
}
#endif // defined (PROFILING_SUPPORTED) &&!defined(DACCESS_COMPILE)
LOG((LF_CLASSLOADER, LL_INFO10, "Loaded pModule: \"%s\".\n", GetDebugName()));
}
#endif // DACCESS_COMPILE
void Module::SetDebuggerInfoBits(DebuggerAssemblyControlFlags newBits)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(((newBits << DEBUGGER_INFO_SHIFT_PRIV) &
~DEBUGGER_INFO_MASK_PRIV) == 0);
m_dwTransientFlags &= ~DEBUGGER_INFO_MASK_PRIV;
m_dwTransientFlags |= (newBits << DEBUGGER_INFO_SHIFT_PRIV);
#ifdef DEBUGGING_SUPPORTED
if (IsEditAndContinueCapable())
{
BOOL setEnC = (newBits & DACF_ENC_ENABLED) != 0 || g_pConfig->ForceEnc() || (g_pConfig->DebugAssembliesModifiable() && CORDisableJITOptimizations(GetDebuggerInfoBits()));
if (setEnC)
{
EnableEditAndContinue();
}
}
#endif // DEBUGGING_SUPPORTED
#if defined(DACCESS_COMPILE)
// Now that we've changed m_dwTransientFlags, update that in the target too.
// This will fail for read-only target.
// If this fails, it will throw an exception.
// @dbgtodo dac write: finalize on plans for how DAC writes to the target.
HRESULT hrDac;
hrDac = DacWriteHostInstance(this, true);
_ASSERTE(SUCCEEDED(hrDac)); // would throw if there was an error.
#endif // DACCESS_COMPILE
}
#ifndef DACCESS_COMPILE
static BOOL IsEditAndContinueCapable(Assembly *pAssembly, PEAssembly *pPEAssembly)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
_ASSERTE(pAssembly != NULL && pPEAssembly != NULL);
// Some modules are never EnC-capable
return ! (pAssembly->GetDebuggerInfoBits() & DACF_ALLOW_JIT_OPTS ||
pPEAssembly->IsSystem() ||
pPEAssembly->IsReflectionEmit());
}
/* static */
Module *Module::Create(Assembly *pAssembly, PEAssembly *pPEAssembly, AllocMemTracker *pamTracker)
{
CONTRACT(Module *)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pAssembly));
PRECONDITION(CheckPointer(pPEAssembly));
POSTCONDITION(CheckPointer(RETVAL));
POSTCONDITION(RETVAL->GetAssembly() == pAssembly);
POSTCONDITION(RETVAL->GetPEAssembly() == pPEAssembly);
}
CONTRACT_END;
// Hoist CONTRACT into separate routine because of EX incompatibility
Module *pModule = NULL;
// Create the module
#ifdef FEATURE_METADATA_UPDATER
if (::IsEditAndContinueCapable(pAssembly, pPEAssembly))
{
// if file is EnCCapable, always create an EnC-module, but EnC won't necessarily be enabled.
// Debugger enables this by calling SetJITCompilerFlags on LoadModule callback.
void* pMemory = pamTracker->Track(pAssembly->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(EditAndContinueModule))));
pModule = new (pMemory) EditAndContinueModule(pAssembly, pPEAssembly);
}
else
#endif // FEATURE_METADATA_UPDATER
{
void* pMemory = pamTracker->Track(pAssembly->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(Module))));
pModule = new (pMemory) Module(pAssembly, pPEAssembly);
}
PREFIX_ASSUME(pModule != NULL);
ModuleHolder pModuleSafe(pModule);
pModuleSafe->DoInit(pamTracker, NULL);
RETURN pModuleSafe.Extract();
}
void Module::ApplyMetaData()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_CLASSLOADER, LL_INFO100, "Module::ApplyNewMetaData this:%p\n", this));
HRESULT hr = S_OK;
ULONG ulCount;
#if defined(PROFILING_SUPPORTED) || defined(FEATURE_METADATA_UPDATER)
UpdateNewlyAddedTypes();
#endif // PROFILING_SUPPORTED || FEATURE_METADATA_UPDATER
// Ensure for TypeRef
ulCount = GetMDImport()->GetCountWithTokenKind(mdtTypeRef) + 1;
EnsureTypeRefCanBeStored(TokenFromRid(ulCount, mdtTypeRef));
// Ensure for AssemblyRef
ulCount = GetMDImport()->GetCountWithTokenKind(mdtAssemblyRef) + 1;
EnsureAssemblyRefCanBeStored(TokenFromRid(ulCount, mdtAssemblyRef));
// Ensure for MethodDef
ulCount = GetMDImport()->GetCountWithTokenKind(mdtMethodDef) + 1;
EnsureMethodDefCanBeStored(TokenFromRid(ulCount, mdtMethodDef));
}
//
// Destructor for Module
//
void Module::Destruct()
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_TRIGGERS;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
LOG((LF_EEMEM, INFO3, "Deleting module %x\n", this));
#ifdef PROFILING_SUPPORTED
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackModuleLoads());
if (!IsBeingUnloaded())
{
// Profiler is causing some peripheral class loads. Probably this just needs
// to be turned into a Fault_not_fatal and moved to a specific place inside the profiler.
EX_TRY
{
GCX_PREEMP();
(&g_profControlBlock)->ModuleUnloadStarted((ModuleID) this);
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
}
END_PROFILER_CALLBACK();
}
#endif // PROFILING_SUPPORTED
DACNotify::DoModuleUnloadNotification(this);
// Free classes in the class table
FreeClassTables();
#ifdef DEBUGGING_SUPPORTED
if (g_pDebugInterface)
{
GCX_PREEMP();
g_pDebugInterface->DestructModule(this);
}
#endif // DEBUGGING_SUPPORTED
ReleaseISymUnmanagedReader();
// Clean up sig cookies
VASigCookieBlock *pVASigCookieBlock = m_pVASigCookieBlock;
while (pVASigCookieBlock)
{
VASigCookieBlock *pNext = pVASigCookieBlock->m_Next;
delete pVASigCookieBlock;
pVASigCookieBlock = pNext;
}
// Clean up the IL stub cache
if (m_pILStubCache != NULL)
{
delete m_pILStubCache;
}
#ifdef PROFILING_SUPPORTED
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackModuleLoads());
// Profiler is causing some peripheral class loads. Probably this just needs
// to be turned into a Fault_not_fatal and moved to a specific place inside the profiler.
EX_TRY
{
GCX_PREEMP();
(&g_profControlBlock)->ModuleUnloadFinished((ModuleID) this, S_OK);
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
END_PROFILER_CALLBACK();
}
#endif // PROFILING_SUPPORTED
//
// Warning - deleting the zap file will cause the module to be unmapped
//
ClearInMemorySymbolStream();
m_Crst.Destroy();
m_LookupTableCrst.Destroy();
m_InstMethodHashTableCrst.Destroy();
m_ISymUnmanagedReaderCrst.Destroy();
if (m_debuggerSpecificData.m_pDynamicILCrst)
{
delete m_debuggerSpecificData.m_pDynamicILCrst;
}
if (m_debuggerSpecificData.m_pDynamicILBlobTable)
{
delete m_debuggerSpecificData.m_pDynamicILBlobTable;
}
if (m_debuggerSpecificData.m_pILOffsetMappingTable)
{
for (ILOffsetMappingTable::Iterator pCurElem = m_debuggerSpecificData.m_pILOffsetMappingTable->Begin(),
pEndElem = m_debuggerSpecificData.m_pILOffsetMappingTable->End();
pCurElem != pEndElem;
pCurElem++)
{
ILOffsetMappingEntry entry = *pCurElem;
entry.m_mapping.Clear();
}
delete m_debuggerSpecificData.m_pILOffsetMappingTable;
}
m_pPEAssembly->Release();
#if defined(PROFILING_SUPPORTED)
delete m_pJitInlinerTrackingMap;
#endif
}
bool Module::NeedsGlobalMethodTable()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
IMDInternalImport * pImport = GetMDImport();
if (pImport->IsValidToken(COR_GLOBAL_PARENT_TOKEN))
{
{
HENUMInternalHolder funcEnum(pImport);
funcEnum.EnumGlobalFunctionsInit();
if (pImport->EnumGetCount(&funcEnum) != 0)
return true;
}
{
HENUMInternalHolder fieldEnum(pImport);
fieldEnum.EnumGlobalFieldsInit();
if (pImport->EnumGetCount(&fieldEnum) != 0)
return true;
}
}
// resource module or no global statics nor global functions
return false;
}
MethodTable *Module::GetGlobalMethodTable()
{
CONTRACT (MethodTable *)
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(CONTRACT_RETURN NULL;);
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
if ((m_dwPersistedFlags & COMPUTED_GLOBAL_CLASS) == 0)
{
MethodTable *pMT = NULL;
if (NeedsGlobalMethodTable())
{
pMT = ClassLoader::LoadTypeDefThrowing(this, COR_GLOBAL_PARENT_TOKEN,
ClassLoader::ThrowIfNotFound,
ClassLoader::FailIfUninstDefOrRef).AsMethodTable();
}
InterlockedOr((LONG*)&m_dwPersistedFlags, COMPUTED_GLOBAL_CLASS);
RETURN pMT;
}
else
{
RETURN LookupTypeDef(COR_GLOBAL_PARENT_TOKEN).AsMethodTable();
}
}
#endif // !DACCESS_COMPILE
BOOL Module::IsCollectible()
{
LIMITED_METHOD_DAC_CONTRACT;
return GetAssembly()->IsCollectible();
}
DomainAssembly* Module::GetDomainAssembly()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pDomainAssembly;
}
#ifndef DACCESS_COMPILE
#include "staticallocationhelpers.inl"
// initialize Crst controlling the Dynamic IL hashtable
void Module::InitializeDynamicILCrst()
{
Crst * pCrst = new Crst(CrstDynamicIL, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD));
if (InterlockedCompareExchangeT(
&m_debuggerSpecificData.m_pDynamicILCrst, pCrst, NULL) != NULL)
{
delete pCrst;
}
}
// Add a (token, address) pair to the table of IL blobs for reflection/dynamics
// Arguments:
// Input:
// token method token
// blobAddress address of the start of the IL blob address, including the header
// Output: not explicit, but if the pair was not already in the table it will be added.
// Does not add duplicate tokens to the table.
void Module::SetDynamicIL(mdToken token, TADDR blobAddress)
{
DynamicILBlobEntry entry = {mdToken(token), TADDR(blobAddress)};
// Lazily allocate a Crst to serialize update access to the info structure.
// Carefully synchronize to ensure we don't leak a Crst in race conditions.
if (m_debuggerSpecificData.m_pDynamicILCrst == NULL)
{
InitializeDynamicILCrst();
}
CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst);
// Lazily allocate the hash table.
if (m_debuggerSpecificData.m_pDynamicILBlobTable == NULL)
{
m_debuggerSpecificData.m_pDynamicILBlobTable = PTR_DynamicILBlobTable(new DynamicILBlobTable);
}
m_debuggerSpecificData.m_pDynamicILBlobTable->AddOrReplace(entry);
}
#endif // !DACCESS_COMPILE
// Get the stored address of the IL blob for reflection/dynamics
// Arguments:
// Input:
// token method token
// fAllowTemporary also check the temporary overrides
// Return Value: starting (target) address of the IL blob corresponding to the input token
TADDR Module::GetDynamicIL(mdToken token)
{
SUPPORTS_DAC;
#ifndef DACCESS_COMPILE
// The Crst to serialize update access to the info structure is lazily allocated.
// If it hasn't been allocated yet, then we don't have any IL blobs (temporary or otherwise)
if (m_debuggerSpecificData.m_pDynamicILCrst == NULL)
{
return TADDR(NULL);
}
CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst);
#endif
// The hash table is lazily allocated, so if it is NULL
// then we have no IL blobs
if (m_debuggerSpecificData.m_pDynamicILBlobTable == NULL)
{
return TADDR(NULL);
}
DynamicILBlobEntry entry = m_debuggerSpecificData.m_pDynamicILBlobTable->Lookup(token);
// If the lookup fails, it returns the 'NULL' entry
// The 'NULL' entry has m_il set to NULL, so either way we're safe
return entry.m_il;
}
#if !defined(DACCESS_COMPILE)
//---------------------------------------------------------------------------------------
//
// Add instrumented IL offset mapping for the specified method.
//
// Arguments:
// token - the MethodDef token of the method in question
// mapping - the mapping information between original IL offsets and instrumented IL offsets
//
// Notes:
// * Once added, the mapping stays valid until the Module containing the method is destructed.
// * The profiler may potentially update the mapping more than once.
//
void Module::SetInstrumentedILOffsetMapping(mdMethodDef token, InstrumentedILOffsetMapping mapping)
{
ILOffsetMappingEntry entry(token, mapping);
// Lazily allocate a Crst to serialize update access to the hash table.
// Carefully synchronize to ensure we don't leak a Crst in race conditions.
if (m_debuggerSpecificData.m_pDynamicILCrst == NULL)
{
InitializeDynamicILCrst();
}
CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst);
// Lazily allocate the hash table.
if (m_debuggerSpecificData.m_pILOffsetMappingTable == NULL)
{
m_debuggerSpecificData.m_pILOffsetMappingTable = PTR_ILOffsetMappingTable(new ILOffsetMappingTable);
}
ILOffsetMappingEntry currentEntry = m_debuggerSpecificData.m_pILOffsetMappingTable->Lookup(ILOffsetMappingTraits::GetKey(entry));
if (!ILOffsetMappingTraits::IsNull(currentEntry))
currentEntry.m_mapping.Clear();
m_debuggerSpecificData.m_pILOffsetMappingTable->AddOrReplace(entry);
}
#endif // DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
// Retrieve the instrumented IL offset mapping for the specified method.
//
// Arguments:
// token - the MethodDef token of the method in question
//
// Return Value:
// Return the mapping information between original IL offsets and instrumented IL offsets.
// Check InstrumentedILOffsetMapping::IsNull() to see if any mapping is available.
//
// Notes:
// * Once added, the mapping stays valid until the Module containing the method is destructed.
// * The profiler may potentially update the mapping more than once.
//
InstrumentedILOffsetMapping Module::GetInstrumentedILOffsetMapping(mdMethodDef token)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
// Lazily allocate a Crst to serialize update access to the hash table.
// If the Crst is NULL, then we couldn't possibly have added any mapping yet, so just return NULL.
if (m_debuggerSpecificData.m_pDynamicILCrst == NULL)
{
InstrumentedILOffsetMapping emptyMapping;
return emptyMapping;
}
CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst);
// If the hash table hasn't been created, then we couldn't possibly have added any mapping yet,
// so just return NULL.
if (m_debuggerSpecificData.m_pILOffsetMappingTable == NULL)
{