-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathclsload.cpp
More file actions
4637 lines (4032 loc) · 164 KB
/
clsload.cpp
File metadata and controls
4637 lines (4032 loc) · 164 KB
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: clsload.cpp
//
// ============================================================================
#include "common.h"
#include "winwrap.h"
#include "ceeload.h"
#include "siginfo.hpp"
#include "vars.hpp"
#include "clsload.hpp"
#include "classhash.inl"
#include "class.h"
#include "method.hpp"
#include "ecall.h"
#include "stublink.h"
#include "object.h"
#include "excep.h"
#include "threads.h"
#include "comsynchronizable.h"
#include "threads.h"
#include "dllimport.h"
#include "dbginterface.h"
#include "log.h"
#include "eeconfig.h"
#include "fieldmarshaler.h"
#include "jitinterface.h"
#include "vars.hpp"
#include "assembly.hpp"
#include "eeprofinterfaces.h"
#include "eehash.h"
#include "typehash.h"
#include "comdelegate.h"
#include "array.h"
#include "posterror.h"
#include "wrappers.h"
#include "generics.h"
#include "typestring.h"
#include "typedesc.h"
#include "cgencpu.h"
#include "eventtrace.h"
#include "typekey.h"
#include "pendingload.h"
#include "proftoeeinterfaceimpl.h"
#include "virtualcallstub.h"
#include "stringarraylist.h"
NameHandle::NameHandle(ModuleBase* pModule, mdToken token) :
m_nameSpace(NULL),
m_name(NULL),
m_pTypeScope(pModule),
m_mdType(token),
m_mdTokenNotToLoad(tdNoTypes),
m_WhichTable(nhCaseSensitive),
m_Bucket()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
}
NameHandle::NameHandle(Module* pModule, mdToken token) :
m_nameSpace(NULL),
m_name(NULL),
m_pTypeScope(pModule),
m_mdType(token),
m_mdTokenNotToLoad(tdNoTypes),
m_WhichTable(nhCaseSensitive),
m_Bucket()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
}
// This method determines the "loader module" for an instantiated type
// or method. The rule must ensure that any types involved in the
// instantiated type or method do not outlive the loader module itself
// with respect to module unloading (e.g. MyList<MyType> can't be
// put in the module of MyList if MyList's assembly is
// non-collectible but MyType's assembly is collectible).
// The rule we use is:
//
// * Pick the first type in the class instantiation, followed by
// method instantiation, whose loader allocator is collectible and has the highest creation number.
// * If no type is in collectible assembly, return the module containing the generic type itself.
//
// Some useful effects of this rule (for ngen purposes) are:
//
// * G<object,...,object> lives in the module defining G
// * non-CoreLib instantiations of CoreLib-defined generic types live in the module
// of the instantiation (when only one module is invloved in the instantiation)
//
/* static */
PTR_Module ClassLoader::ComputeLoaderModuleWorker(
Module * pDefinitionModule, // the module that declares the generic type or method
mdToken token, // method or class token for this item
Instantiation classInst, // the type arguments to the type (if any)
Instantiation methodInst) // the type arguments to the method (if any)
{
CONTRACT(Module*)
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
MODE_ANY;
PRECONDITION(CheckPointer(pDefinitionModule, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL));
SUPPORTS_DAC;
}
CONTRACT_END
// No generic instantiation, return the definition module
if (classInst.IsEmpty() && methodInst.IsEmpty())
RETURN PTR_Module(pDefinitionModule);
// Use the definition module as the loader module by default
Module *pLoaderModule = pDefinitionModule;
// If any of generic type arguments are in collectible module,
// we use a generic procedure.
for (DWORD i = 0; i < classInst.GetNumArgs(); i++)
{
TypeHandle classArg = classInst[i];
Module* pModule = classArg.GetLoaderModule();
if (pModule->IsCollectible())
goto ComputeCollectibleLoaderModule;
if (pLoaderModule == NULL)
pLoaderModule = pModule;
}
// If any of generic method arguments are in collectible module,
// we also use a generic procedure.
for (DWORD i = 0; i < methodInst.GetNumArgs(); i++)
{
TypeHandle methodArg = methodInst[i];
Module *pModule = methodArg.GetLoaderModule();
if (pModule->IsCollectible())
goto ComputeCollectibleLoaderModule;
if (pLoaderModule == NULL)
pLoaderModule = pModule;
}
if (pLoaderModule == NULL)
{
CONSISTENCY_CHECK(CoreLibBinder::GetModule() && CoreLibBinder::GetModule()->IsSystem());
pLoaderModule = CoreLibBinder::GetModule();
}
if (FALSE)
{
ComputeCollectibleLoaderModule:
Module *pLatestLoaderModule = NULL;
UINT64 latestFoundNumber = 0;
DWORD classArgsCount = classInst.GetNumArgs();
DWORD totalArgsCount = classArgsCount + methodInst.GetNumArgs();
// If loader allocator of the defining type is collectible, we use it
// and its creation number as the starting age.
if (pDefinitionModule != NULL && pDefinitionModule->IsCollectible())
{
pLatestLoaderModule = pDefinitionModule;
latestFoundNumber = pDefinitionModule->GetLoaderAllocator()->GetCreationNumber();
}
for (DWORD i = 0; i < totalArgsCount; i++) {
TypeHandle arg;
if (i < classArgsCount)
arg = classInst[i];
else
arg = methodInst[i - classArgsCount];
Module *pModuleCheck = arg.GetLoaderModule();
LoaderAllocator *pLoaderAllocatorCheck = pModuleCheck->GetLoaderAllocator();
if (pLoaderAllocatorCheck->IsCollectible() &&
pLoaderAllocatorCheck->GetCreationNumber() > latestFoundNumber)
{
pLatestLoaderModule = pModuleCheck;
latestFoundNumber = pLoaderAllocatorCheck->GetCreationNumber();
}
}
// Use the module of the latest found collectible loader allocator.
// If nothing was found, then by default we use the defining module.
if (pLatestLoaderModule != NULL)
pLoaderModule = pLatestLoaderModule;
}
RETURN PTR_Module(pLoaderModule);
}
/*static*/
Module * ClassLoader::ComputeLoaderModule(MethodTable * pMT,
mdToken token,
Instantiation methodInst)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
return ComputeLoaderModuleWorker(pMT->GetModule(),
token,
pMT->GetInstantiation(),
methodInst);
}
/*static*/
Module *ClassLoader::ComputeLoaderModule(const TypeKey *typeKey)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (typeKey->GetKind() == ELEMENT_TYPE_CLASS)
return ComputeLoaderModuleWorker(typeKey->GetModule(),
typeKey->GetTypeToken(),
typeKey->GetInstantiation(),
Instantiation());
else if (typeKey->GetKind() == ELEMENT_TYPE_FNPTR)
return ComputeLoaderModuleForFunctionPointer(typeKey->GetRetAndArgTypes(), typeKey->GetNumArgs() + 1);
else
return ComputeLoaderModuleForParamType(typeKey->GetElementType());
}
/*static*/
BOOL ClassLoader::IsTypicalInstantiation(Module *pModule, mdToken token, Instantiation inst)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pModule));
PRECONDITION(TypeFromToken(token) == mdtTypeDef || TypeFromToken(token) == mdtMethodDef);
SUPPORTS_DAC;
}
CONTRACTL_END
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle thArg = inst[i];
if (thArg.IsGenericVariable())
{
TypeVarTypeDesc* tyvar = thArg.AsGenericVariable();
_ASSERTE(tyvar!=NULL);
if ((tyvar->GetTypeOrMethodDef() != token) ||
(tyvar->GetModule() != dac_cast<PTR_Module>(pModule)) ||
(tyvar->GetIndex() != i))
return FALSE;
}
else
{
return FALSE;
}
}
return TRUE;
}
/*static*/
TypeHandle ClassLoader::LoadTypeByNameThrowing(Assembly *pAssembly,
LPCUTF8 nameSpace,
LPCUTF8 name,
NotFoundAction fNotFound,
ClassLoader::LoadTypesFlag fLoadTypes,
ClassLoadLevel level)
{
WRAPPER_NO_CONTRACT;
CQuickBytes qbszNamespace;
if (nameSpace == NULL)
{
LPCUTF8 szFullyQualifiedName = name;
nameSpace = "";
if ((name = ns::FindSep(szFullyQualifiedName)) != NULL)
{
SIZE_T d = name - szFullyQualifiedName;
nameSpace = qbszNamespace.SetString(szFullyQualifiedName, d);
name++;
}
else
{
name = szFullyQualifiedName;
}
}
NameHandle nameHandle(nameSpace, name);
return LoadTypeByNameThrowing(pAssembly, &nameHandle, fNotFound, fLoadTypes, level);
}
/*static*/
TypeHandle ClassLoader::LoadTypeByNameThrowing(Assembly *pAssembly,
NameHandle *pNameHandle,
NotFoundAction fNotFound,
ClassLoader::LoadTypesFlag fLoadTypes,
ClassLoadLevel level)
{
CONTRACT(TypeHandle)
{
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;
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
PRECONDITION(CheckPointer(pAssembly));
PRECONDITION(pNameHandle != NULL);
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
POSTCONDITION(CheckPointer(RETVAL,
(fNotFound == ThrowIfNotFound && fLoadTypes == LoadTypes )? NULL_NOT_OK : NULL_OK));
POSTCONDITION(RETVAL.IsNull() || RETVAL.CheckLoadLevel(level));
SUPPORTS_DAC;
#ifdef DACCESS_COMPILE
PRECONDITION((fNotFound == ClassLoader::ReturnNullIfNotFound) && (fLoadTypes == DontLoadTypes));
#endif
}
CONTRACT_END
if (fLoadTypes == ClassLoader::DontLoadTypes)
pNameHandle->SetTokenNotToLoad(tdAllTypes);
ClassLoader* classLoader = pAssembly->GetLoader();
if (fNotFound == ClassLoader::ThrowIfNotFound)
RETURN classLoader->LoadTypeHandleThrowIfFailed(pNameHandle, level);
else
RETURN classLoader->LoadTypeHandleThrowing(pNameHandle, level);
}
#ifndef DACCESS_COMPILE
#define DAC_LOADS_TYPE(level, expression) \
if (FORBIDGC_LOADER_USE_ENABLED() || (expression)) \
{ LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
#else
#define DAC_LOADS_TYPE(level, expression) { LOADS_TYPE(CLASS_LOAD_BEGIN); }
#endif // #ifndef DACCESS_COMPILE
//
// Find a class given name, using the classloader's global list of known classes.
// If the type is found, it will be restored unless pName->GetTokenNotToLoad() prohibits that
// Returns NULL if class not found AND pName->OKToLoad returns false
TypeHandle ClassLoader::LoadTypeHandleThrowIfFailed(NameHandle* pName, ClassLoadLevel level,
Module* pLookInThisModuleOnly/*=NULL*/)
{
CONTRACT(TypeHandle)
{
INSTANCE_CHECK;
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()); }
DAC_LOADS_TYPE(level, !pName->OKToLoad());
MODE_ANY;
PRECONDITION(CheckPointer(pName));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
POSTCONDITION(CheckPointer(RETVAL, pName->OKToLoad() ? NULL_NOT_OK : NULL_OK));
POSTCONDITION(RETVAL.IsNull() || RETVAL.CheckLoadLevel(level));
SUPPORTS_DAC;
}
CONTRACT_END;
// Lookup in the classes that this class loader knows about
TypeHandle typeHnd = LoadTypeHandleThrowing(pName, level, pLookInThisModuleOnly);
if(typeHnd.IsNull()) {
if ( pName->OKToLoad() ) {
#ifdef _DEBUG_IMPL
{
LPCUTF8 szName = pName->GetName();
if (szName == NULL)
szName = "<UNKNOWN>";
StackSString codeBase;
GetAssembly()->GetCodeBase(codeBase);
LOG((LF_CLASSLOADER, LL_INFO10, "Failed to find class \"%s\" in the manifest for assembly \"%s\"\n", szName, codeBase.GetUTF8()));
}
#endif
#ifndef DACCESS_COMPILE
m_pAssembly->ThrowTypeLoadException(pName, IDS_CLASSLOAD_GENERAL);
#else
DacNotImpl();
#endif
}
}
RETURN(typeHnd);
}
#ifndef DACCESS_COMPILE
//<TODO>@TODO: Need to allow exceptions to be thrown when classloader is cleaned up</TODO>
EEClassHashEntry_t* ClassLoader::InsertValue(EEClassHashTable *pClassHash, EEClassHashTable *pClassCaseInsHash, LPCUTF8 pszNamespace, LPCUTF8 pszClassName, HashDatum Data, EEClassHashEntry_t *pEncloser, AllocMemTracker *pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LPUTF8 pszLowerCaseNS = NULL;
LPUTF8 pszLowerCaseName = NULL;
EEClassHashEntry_t *pCaseInsEntry = NULL;
EEClassHashEntry_t *pEntry = pClassHash->AllocNewEntry(pamTracker);
if (pClassCaseInsHash) {
CreateCanonicallyCasedKey(pszNamespace, pszClassName, &pszLowerCaseNS, &pszLowerCaseName);
pCaseInsEntry = pClassCaseInsHash->AllocNewEntry(pamTracker);
}
{
// ! We cannot fail after this point.
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
pClassHash->InsertValueUsingPreallocatedEntry(pEntry, pszNamespace, pszClassName, Data, pEncloser);
//If we're keeping a table for case-insensitive lookup, keep that up to date
if (pClassCaseInsHash)
pClassCaseInsHash->InsertValueUsingPreallocatedEntry(pCaseInsEntry, pszLowerCaseNS, pszLowerCaseName, pEntry, pEncloser);
return pEntry;
}
}
#endif // #ifndef DACCESS_COMPILE
void ClassLoader::GetClassValue(NameHandleTable nhTable,
const NameHandle *pName,
HashDatum *pData,
EEClassHashTable **ppTable,
Module* pLookInThisModuleOnly,
HashedTypeEntry* pFoundEntry,
Loader::LoadFlag loadFlag,
BOOL& needsToBuildHashtable)
{
CONTRACTL
{
INSTANCE_CHECK;
MODE_ANY;
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()); }
PRECONDITION(CheckPointer(pName));
SUPPORTS_DAC;
}
CONTRACTL_END
PTR_EEClassHashEntry pBucket = NULL;
needsToBuildHashtable = FALSE;
#if _DEBUG
if (pName->GetName()) {
if (pName->GetNameSpace() == NULL)
LOG((LF_CLASSLOADER, LL_INFO1000, "Looking up %s by name.\n",
pName->GetName()));
else
LOG((LF_CLASSLOADER, LL_INFO1000, "Looking up %s.%s by name.\n",
pName->GetNameSpace(), pName->GetName()));
}
#endif
PTR_Assembly assembly = GetAssembly();
Module * pCurrentClsModule = assembly->GetModule();
_ASSERTE(pCurrentClsModule != NULL);
if (!pLookInThisModuleOnly || (pCurrentClsModule == pLookInThisModuleOnly))
{
#ifdef FEATURE_READYTORUN
if (nhTable == nhCaseSensitive && pCurrentClsModule->IsReadyToRun() && pCurrentClsModule->GetReadyToRunInfo()->HasHashtableOfTypes() &&
pCurrentClsModule->GetAvailableClassHash() == NULL)
{
// For R2R modules, we only search the hashtable of token types stored in the module's image, and don't fallback
// to searching m_pAvailableClasses or m_pAvailableClassesCaseIns (in fact, we don't even allocate them for R2R modules).
// Also note that type lookups in R2R modules only support case sensitive lookups.
mdToken mdFoundTypeToken;
if (pCurrentClsModule->GetReadyToRunInfo()->TryLookupTypeTokenFromName(pName, &mdFoundTypeToken))
{
if (TypeFromToken(mdFoundTypeToken) == mdtExportedType)
{
mdToken mdUnused;
Module * pTargetModule = GetAssembly()->FindModuleByExportedType(mdFoundTypeToken, loadFlag, mdTypeDefNil, &mdUnused);
pFoundEntry->SetTokenBasedEntryValue(mdFoundTypeToken, pTargetModule);
}
else
{
pFoundEntry->SetTokenBasedEntryValue(mdFoundTypeToken, pCurrentClsModule);
}
return; // Return on the first success
}
}
else
#endif
{
EEClassHashTable* pTable = NULL;
if (nhTable == nhCaseSensitive)
{
*ppTable = pTable = pCurrentClsModule->GetAvailableClassHash();
#ifdef FEATURE_READYTORUN
if (pTable == NULL && pCurrentClsModule->IsReadyToRun() && !pCurrentClsModule->GetReadyToRunInfo()->HasHashtableOfTypes())
{
// Old R2R image generated without the hashtable of types.
// We fallback to the slow path of creating the hashtable dynamically
// at execution time in that scenario. The caller will handle
pFoundEntry->SetClassHashBasedEntryValue(NULL);
needsToBuildHashtable = TRUE;
return;
}
#endif
}
else
{
// currently we expect only these two kinds--for DAC builds, nhTable will be nhCaseSensitive
_ASSERTE(nhTable == nhCaseInsensitive);
*ppTable = pTable = pCurrentClsModule->GetAvailableClassCaseInsHash();
if (pTable == NULL)
{
// We have not built the table yet - the caller will handle
pFoundEntry->SetClassHashBasedEntryValue(NULL);
needsToBuildHashtable = TRUE;
return;
}
}
_ASSERTE(pTable);
pBucket = pTable->FindByNameHandle(pName);
if (pBucket) // Return on the first success
{
*pData = pBucket->GetData();
pFoundEntry->SetClassHashBasedEntryValue(pBucket);
return;
}
}
}
// No results found: default to a NULL EEClassHashEntry_t result
pFoundEntry->SetClassHashBasedEntryValue(NULL);
}
#ifndef DACCESS_COMPILE
VOID ClassLoader::PopulateAvailableClassHashTable(Module* pModule,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
SArray<EEClassHashEntry_t*> entries;
IMDInternalImport * pImport = pModule->GetMDImport();
{
mdTypeDef td;
HENUMInternalHolder hTypeDefEnum(pImport);
hTypeDefEnum.EnumTypeDefInit();
DWORD cEntries = hTypeDefEnum.EnumGetCount() + 1; // Add 1 since this enum doesn't report the <module> class
EEClassHashEntry_t** pBuffer = entries.OpenRawBuffer(cEntries);
memset(pBuffer, 0, sizeof(EEClassHashEntry_t*) * cEntries);
entries.CloseRawBuffer();
// Now loop through all the classdefs adding the CVID and scope to the hash
while(pImport->EnumNext(&hTypeDefEnum, &td))
{
AddAvailableClassHaveLock(pModule,
td,
&entries,
pamTracker);
}
}
{
// Add exported types to the hashtable
HENUMInternalHolder phEnum(pImport);
phEnum.EnumInit(mdtExportedType, mdTokenNil);
DWORD cEntries = phEnum.EnumGetCount();
EEClassHashEntry_t** pBuffer = entries.OpenRawBuffer(cEntries);
memset(pBuffer, 0, sizeof(EEClassHashEntry_t*) * cEntries);
entries.CloseRawBuffer();
mdToken mdExportedType;
while (pImport->EnumNext(&phEnum, &mdExportedType))
{
AddExportedTypeHaveLock(pModule, mdExportedType, &entries, pamTracker);
}
}
}
void ClassLoader::LazyPopulateCaseSensitiveHashTablesDontHaveLock()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
CrstHolder ch(&m_AvailableClassLock);
LazyPopulateCaseSensitiveHashTables();
}
void ClassLoader::LazyPopulateCaseSensitiveHashTables()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
_ASSERT(m_cUnhashedModules > 0);
AllocMemTracker amTracker;
// Create a case-sensitive hashtable for the module, and fill it with the module's typedef entries
Module *pModule = GetAssembly()->GetModule();
if (pModule->GetAvailableClassHash() == NULL)
{
// Lazy construction of the case-sensitive hashtable of types is *only* a scenario for ReadyToRun images
// (either images compiled with an old version of crossgen, or for case-insensitive type lookups in R2R modules)
_ASSERT(pModule->IsReadyToRun());
EEClassHashTable * pNewClassHash = EEClassHashTable::Create(pModule, AVAILABLE_CLASSES_HASH_BUCKETS, NULL, &amTracker);
pModule->SetAvailableClassHash(pNewClassHash);
PopulateAvailableClassHashTable(pModule, &amTracker);
}
amTracker.SuppressRelease();
}
void ClassLoader::LazyPopulateCaseInsensitiveHashTables()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
if (GetAssembly()->GetModule()->GetAvailableClassHash() == NULL)
{
// This is a R2R assembly, and a case insensitive type lookup was triggered.
// Construct the case-sensitive table first, since the case-insensitive table
// create piggy-backs on the first.
LazyPopulateCaseSensitiveHashTables();
}
// Add any unhashed modules into our hash tables, and try again.
AllocMemTracker amTracker;
Module *pModule = GetAssembly()->GetModule();
if (pModule->GetAvailableClassCaseInsHash() == NULL)
{
EEClassHashTable *pNewClassCaseInsHash = pModule->GetAvailableClassHash()->MakeCaseInsensitiveTable(pModule, &amTracker);
LOG((LF_CLASSLOADER, LL_INFO10, "%s's classes being added to case insensitive hash table\n",
pModule->GetSimpleName()));
{
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
amTracker.SuppressRelease();
pModule->SetAvailableClassCaseInsHash(pNewClassCaseInsHash);
InterlockedDecrement((LONG*)&m_cUnhashedModules);
_ASSERT(m_cUnhashedModules >= 0);
}
}
}
/*static*/
void DECLSPEC_NORETURN ClassLoader::ThrowTypeLoadException(const TypeKey *pKey,
UINT resIDWhy)
{
STATIC_CONTRACT_THROWS;
StackSString fullName;
StackSString assemblyName;
TypeString::AppendTypeKey(fullName, pKey);
pKey->GetModule()->GetAssembly()->GetDisplayName(assemblyName);
::ThrowTypeLoadException(fullName, assemblyName, NULL, resIDWhy);
}
#endif
TypeHandle ClassLoader::LoadConstructedTypeThrowing(const TypeKey *pKey,
LoadTypesFlag fLoadTypes /*= LoadTypes*/,
ClassLoadLevel level /*=CLASS_LOADED*/,
const InstantiationContext *pInstContext /*=NULL*/)
{
CONTRACT(TypeHandle)
{
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()); }
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
PRECONDITION(CheckPointer(pKey));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
PRECONDITION(CheckPointer(pInstContext, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL, fLoadTypes==DontLoadTypes ? NULL_OK : NULL_NOT_OK));
POSTCONDITION(RETVAL.IsNull() || RETVAL.GetLoadLevel() >= level);
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACT_END
// Lookup in the classes that this class loader knows about
TypeHandle typeHnd = LookupTypeHandleForTypeKey(pKey);
if (!typeHnd.IsNull())
{
if (typeHnd.GetLoadLevel() >= level)
{
// If something has been published in the tables, and it's at the right level, just return it
RETURN typeHnd;
}
}
#ifndef DACCESS_COMPILE
if (typeHnd.IsNull() && pKey->HasInstantiation())
{
if (!Generics::CheckInstantiation(pKey->GetInstantiation()))
pKey->GetModule()->GetAssembly()->ThrowTypeLoadException(pKey->GetModule()->GetMDImport(), pKey->GetTypeToken(), IDS_CLASSLOAD_INVALIDINSTANTIATION);
}
#endif
// If we're not loading any types at all, then we're not creating
// instantiations either because we're in FORBIDGC_LOADER_USE mode, so
// we should bail out here.
if (fLoadTypes == DontLoadTypes)
RETURN TypeHandle();
#ifndef DACCESS_COMPILE
// If we got here, we now have to allocate a new parameterized type.
// By definition, forbidgc-users aren't allowed to reach this point.
CONSISTENCY_CHECK(!FORBIDGC_LOADER_USE_ENABLED());
Module *pLoaderModule = ComputeLoaderModule(pKey);
RETURN(pLoaderModule->GetClassLoader()->LoadTypeHandleForTypeKey(pKey, typeHnd, level, pInstContext));
#else
DacNotImpl();
RETURN(typeHnd);
#endif
}
/*static*/
void ClassLoader::EnsureLoaded(TypeHandle typeHnd, ClassLoadLevel level)
{
CONTRACTL
{
PRECONDITION(CheckPointer(typeHnd));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
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()); }
if (FORBIDGC_LOADER_USE_ENABLED()) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
SUPPORTS_DAC;
MODE_ANY;
}
CONTRACTL_END
#ifndef DACCESS_COMPILE // Nothing to do for the DAC case
if (typeHnd.GetLoadLevel() < level)
{
if (level >= CLASS_LOAD_APPROXPARENTS)
{
TypeKey typeKey = typeHnd.GetTypeKey();
Module *pLoaderModule = ComputeLoaderModule(&typeKey);
pLoaderModule->GetClassLoader()->LoadTypeHandleForTypeKey(&typeKey, typeHnd, level);
}
}
#endif // DACCESS_COMPILE
}
/* static */
TypeHandle ClassLoader::LookupTypeKey(const TypeKey *pKey, EETypeHashTable *pTable)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pKey));
PRECONDITION(pKey->IsConstructed());
PRECONDITION(CheckPointer(pTable));
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
return pTable->GetValue(pKey);
}
/* static */
TypeHandle ClassLoader::LookupInLoaderModule(const TypeKey *pKey)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pKey));
PRECONDITION(pKey->IsConstructed());
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
Module *pLoaderModule = ComputeLoaderModule(pKey);
_ASSERTE(pLoaderModule!=NULL);
return LookupTypeKey(pKey, pLoaderModule->GetAvailableParamTypes());
}
/* static */
TypeHandle ClassLoader::LookupTypeHandleForTypeKey(const TypeKey *pKey)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pKey));
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END
// Check if it's the typical instantiation. In this case it's not stored in the same
// way as other constructed types.
if (!pKey->IsConstructed() ||
(pKey->GetKind() == ELEMENT_TYPE_CLASS && ClassLoader::IsTypicalInstantiation(pKey->GetModule(),
pKey->GetTypeToken(),
pKey->GetInstantiation())))
{
return TypeHandle(pKey->GetModule()->LookupTypeDef(pKey->GetTypeToken()));
}
// Next look in the loader module. This is where the item is guaranteed to live if
// it is not latched from an NGEN image, i.e. if it is JIT loaded.
// If the thing is not NGEN'd then this may
// be different to pPreferredZapModule. If they are the same then
// we can reuse the results of the lookup above.
TypeHandle thLM = LookupInLoaderModule(pKey);
if (!thLM.IsNull())
{
return thLM;
}
return TypeHandle();
}
// FindClassModuleThrowing discovers which module the type you're looking for is in and loads the Module if necessary.
// Basically, it iterates through all of the assembly's modules until a name match is found in a module's
// AvailableClassHashTable.
//
// The possible outcomes are:
//
// - Function returns TRUE - class exists and we successfully found/created the containing Module. See below
// for how to deconstruct the results.
// - Function returns FALSE - class affirmatively NOT found (that means it doesn't exist as a regular type although
// it could also be a parameterized type)
// - Function throws - OOM or some other reason we couldn't do the job (if it's a case-sensitive search
// and you're looking for already loaded type or you've set the TokenNotToLoad.
// we are guaranteed not to find a reason to throw.)
//
//
// If it succeeds (returns TRUE), one of the following will occur. Check (*pType)->IsNull() to discriminate.
//
// 1. *pType: set to the null TypeHandle()
// *ppModule: set to the owning Module
// *pmdClassToken: set to the typedef
// *pmdFoundExportedType: if this name bound to an ExportedType, this contains the mdtExportedType token (otherwise,
// it's set to mdTokenNil.) You need this because in this case, *pmdClassToken is just
// a best guess and you need to verify it. (The division of labor between this
// and LoadTypeHandle could definitely be better!)
//
// 2. *pType: set to non-null TypeHandle()
// This means someone else had already done this same lookup before you and caused the actual
// TypeHandle to be cached. Since we know that's what you *really* wanted, we'll just forget the
// Module/typedef stuff and give you the actual TypeHandle.
//
//
BOOL ClassLoader::FindClassModuleThrowing(
const NameHandle * pName,
TypeHandle * pType,
mdToken * pmdClassToken,
Module ** ppModule,
mdToken * pmdFoundExportedType,
HashedTypeEntry * pFoundEntry,
Module * pLookInThisModuleOnly,
Loader::LoadFlag loadFlag)
{
CONTRACTL
{
INSTANCE_CHECK;
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()); }
PRECONDITION(CheckPointer(pName));
PRECONDITION(CheckPointer(ppModule));
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END
// Note that the type name is expected to be lower-cased by the caller for case-insensitive lookups
NameHandleTable nhTable = pName->GetTable();
// Remember if there are any unhashed modules. We must do this before
// the actual look to avoid a race condition with other threads doing lookups.
#ifdef LOGGING
BOOL incomplete = (m_cUnhashedModules > 0);
#endif
HashDatum Data;
EEClassHashTable * pTable = NULL;
HashedTypeEntry foundEntry;
BOOL needsToBuildHashtable;
GetClassValue(nhTable, pName, &Data, &pTable, pLookInThisModuleOnly, &foundEntry, loadFlag, needsToBuildHashtable);
// In the case of R2R modules, the search is only performed in the hashtable saved in the
// R2R image, and this is why we return (whether we found a valid typedef token or not).
// Note: case insensitive searches are not used/supported in R2R images.
if (foundEntry.GetEntryType() == HashedTypeEntry::EntryType::IsHashedTokenEntry)
{
*pType = TypeHandle();
HashedTypeEntry::TokenTypeEntry tokenAndModulePair = foundEntry.GetTokenBasedEntryValue();
switch (TypeFromToken(tokenAndModulePair.m_TypeToken))
{
case mdtTypeDef:
*pmdClassToken = tokenAndModulePair.m_TypeToken;
*pmdFoundExportedType = mdTokenNil;
break;
case mdtExportedType:
*pmdClassToken = mdTokenNil;
*pmdFoundExportedType = tokenAndModulePair.m_TypeToken;
break;
default: