download clsload.hpp
Language: C++
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 907
Project Info
Shared Source Common Language Infrastructure(sscli20)
Server: Shared Source Common Language Infrastructure
Type: filesystem
...sscli20\sscli20\clr\src\vm\
   appdomain.cpp
   appdomain.hpp
   appdomain.inl
   appdomainhelper.cpp
   appdomainhelper.h
   appdomainnative.cpp
   appdomainnative.hpp
   appdomainstack.cpp
   appdomainstack.h
   appdomainstack.inl
   argslot.h
   array.cpp
   array.h
   assembly.cpp
   assembly.hpp
   assemblyname.cpp
   assemblyname.hpp
   assemblynative.cpp
   assemblynative.hpp
   assemblysink.cpp
   assemblysink.h
   assemblyspec.cpp
   assemblyspec.hpp
   binder.cpp
   binder.h
   cachelinealloc.cpp
   cachelinealloc.h
   ceeload.cpp
   ceeload.h
   ceeload.inl
   ceemain.cpp
   ceemain.h
   certificatecache.cpp
   certificatecache.h
   cgensys.h
   class.cpp
   class.h
   class.inl
   classloadlevel.h
   classnames.h
   clrex.cpp
   clrex.h
   clsload.cpp
   clsload.hpp
   clsload.inl
   codeman.cpp
   codeman.h
   codeman.inl
   comarrayhelpers.cpp
   comarrayhelpers.h
   comarrayinfo.cpp
   comarrayinfo.h
   comcallablewrapper.cpp
   comcallablewrapper.h
   comcurrency.cpp
   comcurrency.h
   comdatetime.cpp
   comdatetime.h
   comdecimal.cpp
   comdecimal.h
   comdelegate.cpp
   comdelegate.h
   comdynamic.cpp
   comdynamic.h
   comisolatedstorage.cpp
   comisolatedstorage.h
   commemoryfailpoint.cpp
   commemoryfailpoint.h
   commethodrental.cpp
   commethodrental.h
   commodule.cpp
   commodule.h
   common.cpp
   common.h
   comnumber.cpp
   comnumber.h
   comobject.cpp
   comobject.h
   comreflectioncache.hpp
   comreflectioncommon.cpp
   comreflectioncommon.h
   comstreams.cpp
   comstreams.h
   comstring.cpp
   comstring.h
   comstringbuffer.cpp
   comstringbuffer.h
   comstringcommon.h
   comsynchronizable.cpp
   comsynchronizable.h
   comsystem.cpp
   comsystem.h
   comthreadpool.cpp
   comthreadpool.h
   comutilnative.cpp
   comutilnative.h
   comvarargs.cpp
   comvarargs.h
   comvariant.cpp
   comvariant.h
   comwaithandle.cpp
   comwaithandle.h
   confighelper.cpp
   confighelper.h
   ...inedexecutionregion.cpp
   ...rainedexecutionregion.h
   context.h
   contexts.cpp
   contractimpl.cpp
   contractimpl.h
   corhost.cpp
   crossdomaincalls.cpp
   crossdomaincalls.h
   crst.cpp
   crst.h
   cryptapis.h
   ctxtcall.h
   customattribute.cpp
   customattribute.h
   custommarshalerinfo.cpp
   custommarshalerinfo.h
   dbginterface.h
   debugdebugger.cpp
   debugdebugger.h
   debughelp.cpp
   debuginfostore.cpp
   debuginfostore.h
   decodemd.cpp
   decodemd.h
   delegateinfo.h
   dllimport.cpp
   dllimport.h
   dllimportcallback.cpp
   dllimportcallback.h
   domainfile.cpp
   domainfile.h
   domainfile.inl
   dynamicmethod.cpp
   dynamicmethod.h
   ecall.cpp
   ecall.h
   ecmakey.h
   eecallconv.h
   eeconfig.cpp
   eeconfig.h
   eeconfigfactory.cpp
   eeconfigfactory.h
   eecontract.cpp
   eecontract.h
   eecontract.inl
   eedbginterface.h
   eedbginterfaceimpl.cpp
   eedbginterfaceimpl.h
   eedbginterfaceimpl.inl
   eehash.cpp
   eehash.h
   eemessagebox.cpp
   eemessagebox.h
   eepolicy.cpp
   eepolicy.h
   eeprofinterfaces.h
   eeprofinterfaces.inl
   ...rofinterfacewrapper.inl
   eetwain.cpp
   encee.h
   eventstore.cpp
   eventstore.hpp
   excep.cpp
   excep.h
   exceptmacros.h
   exinfo.cpp
   exinfo.h
   exstate.cpp
   exstate.h
   exstatecommon.h
   fcall.cpp
   fcall.h
   field.cpp
   field.h
   fieldmarshaler.cpp
   fieldmarshaler.h
   fjit_eetwain.cpp
   fjit_eetwain.h
   fptrstubs.cpp
   fptrstubs.h
   frames.cpp
   frames.h
   fusionbind.cpp
   fusioninit.cpp
   fusionsink.cpp
   fusionwrap.cpp
   fusionwrap.h
   gc.h
   gccommon.cpp
   gcdecode.cpp
   gcdesc.h
   gcee.cpp
   gceesvr.cpp
   gceewks.cpp
   gchost.cpp
   gcimpl.h
   gcscan.cpp
   gcscan.h
   gcsmp.cpp
   gcsmppriv.h
   gcsvr.cpp
   gcwks.cpp
   genericdict.cpp
   genericdict.h
   generics.cpp
   generics.h
   genmeth.cpp
   gmheap.cpp
   gmheap.hpp
   gms.h
   h2inc.pl
   handletable.cpp
   handletable.h
   handletable.inl
   handletablecache.cpp
   handletablecore.cpp
   handletablepriv.h
   handletablescan.cpp
   hash.cpp
   hash.h
   hostexecutioncontext.cpp
   hostexecutioncontext.h
   hosting.cpp
   hosting.h
   ibclogger.h
   ildump.h
   ilmarshalers.cpp
   ilmarshalers.h
   ilstubcache.cpp
   ilstubcache.h
   ilstubresolver.cpp
   ilstubresolver.h
   instmethhash.cpp
   instmethhash.h
   interopconverter.cpp
   interopconverter.h
   interoputil.cpp
   interoputil.h
   ...lidoverlappedwrappers.h
   invokeutil.cpp
   invokeutil.h
   jithelpers.cpp
   jitinterface.cpp
   jitinterface.h
   jitinterfacegen.cpp
   list.cpp
   list.h
   listlock.cpp
   listlock.h
   listlock.inl
   makefile.inc
   managedmdimport.cpp
   managedmdimport.hpp
   marshaler.h
   marshalnative.cpp
   marshalnative.h
   mdaassistants.h
   mdaassistantsptr.h
   memberload.cpp
   memberload.h
   message.cpp
   message.h
   metasig.h
   method.cpp
   method.hpp
   method.inl
   methodimpl.cpp
   methodimpl.h
   methoditer.cpp
   methoditer.h
   methodtable.cpp
   methodtable.h
   methodtable.inl
   ml.cpp
   ml.h
   mlcache.cpp
   mlcache.h
   mlgen.cpp
   mlgen.h
   mlinfo.cpp
   mlinfo.h
   mlopdef.h
   mscorlib.h
   mtypes.h
   namespace.h
   nativeoverlapped.cpp
   nativeoverlapped.h
   newcompressedstack.cpp
   newcompressedstack.h
   nsenums.h
   object.cpp
   object.h
   object.inl
   objectclone.cpp
   objectclone.h
   objecthandle.cpp
   objecthandle.h
   objectlist.cpp
   objectlist.h
   olevariant.cpp
   olevariant.h
   pefile.cpp
   pefile.h
   pefile.inl
   peimage.cpp
   peimage.h
   peimage.inl
   peimagelayout.cpp
   peimagelayout.h
   peimagelayout.inl
   pendingload.cpp
   pendingload.h
   precode.cpp
   precode.h
   prestub.cpp
   proftoeeinterfaceimpl.cpp
   proftoeeinterfaceimpl.h
   reflectclasswriter.cpp
   reflectclasswriter.h
   reflectioninvocation.cpp
   reflectioninvocation.h
   remoting.cpp
   remoting.h
   rexcep.h
   runtimeexceptionkind.h
   runtimehandles.cpp
   runtimehandles.h
   rwlock.cpp
   rwlock.h
   safehandle.cpp
   security.h
   security.inl
   securityattributes.cpp
   securityattributes.h
   securityconfig.cpp
   securityconfig.h
   securitydeclarative.cpp
   securitydeclarative.h
   securitydescriptor.cpp
   securitydescriptor.h
   ...descriptorappdomain.cpp
   ...tydescriptorappdomain.h
   ...ydescriptorassembly.cpp
   ...itydescriptorassembly.h
   securityhostprotection.cpp
   securityhostprotection.h
   securityimperative.cpp
   securityimperative.h
   securitymeta.cpp
   securitymeta.h
   securitypolicy.cpp
   securitypolicy.h
   securitystackwalk.cpp
   securitystackwalk.h
   ...transparentassembly.cpp
   ...tytransparentassembly.h
   sigformat.cpp
   sigformat.h
   siginfo.cpp
   siginfo.hpp
   simplerwlock.cpp
   simplerwlock.hpp
   sourceline.cpp
   sourceline.h
   sources.dac
   sources.inc
   specialstatics.h
   spinlock.cpp
   spinlock.h
   stackbuildersink.cpp
   stackbuildersink.h
   stackcompressor.cpp
   stackcompressor.h
   stackingallocator.cpp
   stackingallocator.h
   stackprobe.h
   stackprobe.inl
   stackwalk.cpp
   stackwalk.h
   stackwalktypes.h
   stringliteralmap.cpp
   stringliteralmap.h
   strongname.cpp
   stubgen.h
   stublink.cpp
   stublink.h
   stublink.inl
   stubmgr.cpp
   stubmgr.h
   syncblk.cpp
   syncblk.h
   syncblk.inl
   syncclean.cpp
   syncclean.hpp
   synch.cpp
   synch.h
   ...zationcontextnative.cpp
   ...nizationcontextnative.h
   testhookmgr.cpp
   testhookmgr.h
   thekey.h
   threads.cpp
   threads.h
   threads.inl
   tokeniter.cpp
   tokeniter.hpp
   typectxt.cpp
   typectxt.h
   typedesc.cpp
   typedesc.h
   typedesc.inl
   typehandle.cpp
   typehandle.h
   typehandle.inl
   typehash.cpp
   typehash.h
   typekey.h
   typeparse.cpp
   typeparse.h
   typestring.cpp
   typestring.h
   umthunkhash.cpp
   umthunkhash.h
   util.cpp
   util.hpp
   validator.cpp
   vars.cpp
   vars.hpp
   verifier.cpp
   verifier.hpp
   veropcodes.hpp
   vertable.h
   virtualcallstub.cpp
   virtualcallstub.h
   vmholder.h
   win32threadpool.cpp
   win32threadpool.h
   wrappers.h

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
// ==++==
//
//   
//    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
//
// ==--==
//
// clsload.hpp
//
#ifndef _H_CLSLOAD
#define _H_CLSLOAD

#include "crst.h"
#include "eehash.h"
#include "vars.hpp"
#include "stubmgr.h"
#include "typehandle.h"
#include "object.h" // only needed for def. of PTRARRAYREF
#include "classloadlevel.h"
#include "specstrings.h"
#include "simplerwlock.hpp"

// SystemDomain is a friend of ClassLoader.
class SystemDomain;
class Assembly;
class ClassLoader;
class TypeKey;
struct EnCInfo;
interface IEnCErrorCallback;
class PendingTypeLoadEntry;
class PendingTypeLoadTable;
class PendingTypeLoadEntry_LockHolder;
class EEClass;
class Thread;
class EETypeHashTable;

// Hash table parameter for unresolved class hash
#define UNRESOLVED_CLASS_HASH_BUCKETS 8

// Used by Module Index / CL hash
#define MAX_CLASSES_PER_MODULE (1 << 21)

// This is information required to look up a type in the loader. Besides the
// basic name there is the meta data information for the type, whether the
// the name is case sensitive, and tokens not to load. This last item allows
// the loader to prevent a type from being recursively loaded.
typedef enum NameHandleTable
{
    nhCaseSensitive = 0,
    nhCaseInsensitive = 1
} NameHandleTable;


    // This token can be used on a pThrowable, it is just a token that says
    // don't return the throwable, just throw it instead

#define RETURN_ON_ERROR (NULL)                   // We do this all the time right now.
inline bool  pThrowableAvailable(OBJECTREF* pThrowable) {LEAF_CONTRACT;  return pThrowable != NULL; }

    // used in a catch handler, updates pThrowable GETHROWABLE, if available
#define UpdateThrowable(_pT)        \
    if (_pT != RETURN_ON_ERROR)     \
        (*_pT) = GET_THROWABLE();


class NameHandle
{
    friend class ClassLoader;

    LPCUTF8 m_nameSpace;
    LPCUTF8 m_name;

    PTR_Module m_pTypeScope;
    mdToken m_mdType;
    mdToken m_mdTokenNotToLoad;
    NameHandleTable m_WhichTable;
    PTR_EEClassHashEntry m_pBucket;

public:

    NameHandle()
    {
        LEAF_CONTRACT;
        memset((void*) this, NULL, sizeof(*this));
    }

    NameHandle(LPCUTF8 name) :
        m_nameSpace(NULL),
        m_name(name),
        m_pTypeScope(PTR_NULL),
        m_mdType(mdTokenNil),
        m_mdTokenNotToLoad(tdNoTypes),
        m_WhichTable(nhCaseSensitive),
        m_pBucket(PTR_NULL)
    {
        LEAF_CONTRACT;
    }

    NameHandle(LPCUTF8 nameSpace, LPCUTF8 name) :
        m_nameSpace(nameSpace),
        m_name(name),
        m_pTypeScope(PTR_NULL),
        m_mdType(mdTokenNil),
        m_mdTokenNotToLoad(tdNoTypes),
        m_WhichTable(nhCaseSensitive),
        m_pBucket(PTR_NULL)
    {
        LEAF_CONTRACT;
    }

    NameHandle(Module* pModule, mdToken token) :
        m_nameSpace(NULL),
        m_name(NULL),
        m_pTypeScope(pModule),
        m_mdType(token),
        m_mdTokenNotToLoad(tdNoTypes),
        m_WhichTable(nhCaseSensitive),
        m_pBucket(PTR_NULL)
    {
        LEAF_CONTRACT;
    }

    NameHandle(NameHandle& p)
    {
        LEAF_CONTRACT;
        m_nameSpace = p.m_nameSpace;
        m_name = p.m_name;
        m_pTypeScope = p.m_pTypeScope;
        m_mdType = p.m_mdType;
        m_mdTokenNotToLoad = p.m_mdTokenNotToLoad;
        m_WhichTable = p.m_WhichTable;
        m_pBucket = p.m_pBucket;
    }

    void SetName(LPCUTF8 pName)
    {
        LEAF_CONTRACT;
        m_name = pName;
    }

    void SetName(LPCUTF8 pNameSpace, LPCUTF8 pName)
    {
        LEAF_CONTRACT;
        m_nameSpace = pNameSpace;
        m_name = pName;
    }

    LPCUTF8 GetName() const
    {
        LEAF_CONTRACT;
        return m_name;
    }

    LPCUTF8 GetNameSpace() const
    {
        LEAF_CONTRACT;
        return m_nameSpace;
    }

    void SetTypeToken(Module* pModule, mdToken mdToken)
    {
        LEAF_CONTRACT;
        m_pTypeScope = PTR_Module(PTR_HOST_TO_TADDR(pModule));
        m_mdType = mdToken;
    }

    Module* GetTypeModule() const
    {
        LEAF_CONTRACT;
        return m_pTypeScope;
    }

    mdToken GetTypeToken() const
    {
        LEAF_CONTRACT;
        return m_mdType;
    }

    void SetTokenNotToLoad(mdToken mdtok)
    {
        LEAF_CONTRACT;
        m_mdTokenNotToLoad = mdtok;
    }

    mdToken GetTokenNotToLoad() const
    {
        LEAF_CONTRACT;
        return m_mdTokenNotToLoad;
    }

    void SetCaseInsensitive()
    {
        LEAF_CONTRACT;
        m_WhichTable = nhCaseInsensitive;
    }

    NameHandleTable GetTable() const
    {
        LEAF_CONTRACT;
        return m_WhichTable;
    }

    void SetBucket(EEClassHashEntry_t * pBucket)
    {
        LEAF_CONTRACT;
        m_pBucket = PTR_EEClassHashEntry(PTR_HOST_TO_TADDR(pBucket));
    }


    EEClassHashEntry_t * GetBucket()
    {
        LEAF_CONTRACT;
        return m_pBucket;
    }


#ifdef _DEBUG
    void Validate()
    {
        WRAPPER_CONTRACT;
        if(g_pConfig->fAssertOnBadImageFormat())
        {
            _ASSERTE(GetName());
            _ASSERTE(ns::IsValidName(GetName()));
        }
    }
#endif

    static BOOL OKToLoad(mdToken token, mdToken tokenNotToLoad)
    {
        LEAF_CONTRACT;

        return (token == 0 || token != tokenNotToLoad) && tokenNotToLoad != tdAllTypes;
    }

    BOOL OKToLoad()
    {
        WRAPPER_CONTRACT;
        return OKToLoad(m_mdType, m_mdTokenNotToLoad);
    }

};

class ClassLoader
{
    friend class MethodTableBuilder;
    friend class SystemDomain;
    friend class AppDomain;
    friend class Assembly;
    friend class Module;

    // the following three classes are friends because they will call LoadTypeHandleForTypeKey by token directly
    friend class COMDynamicWrite;
    friend class COMModule;
    friend class TypeLibExporter;
    friend class MemberLoader;
    friend class PendingTypeLoadEntry;

protected:
    static HRESULT RunMain(MethodDesc *pFD,
                           short numSkipArgs,
                           INT32 *piRetVal,
                           PTRARRAYREF *stringArgs = NULL);

private:
    // Classes for which load is in progress
    PendingTypeLoadTable  * m_pUnresolvedClassHash;
    CrstExplicitInit        m_UnresolvedClassLock;

    // Protects addition of elements to module's m_pAvailableClasses.
    // (indeed thus protects addition of elements to any m_pAvailableClasses in any
    // of the modules managed by this loader)
    CrstExplicitInit        m_AvailableClassLock;

    CrstExplicitInit        m_AvailableParamTypesLock;

    // Do we have any modules which need to have their classes added to
    // the available list?
    volatile LONG       m_cUnhashedModules;

    // Back reference to the assembly
    PTR_Assembly        m_pAssembly;

public:

    // Next classloader in global list
    PTR_ClassLoader     m_pNext;

#ifdef _DEBUG
    DWORD               m_dwDebugMethods;
    DWORD               m_dwDebugFieldDescs; // Doesn't include anything we don't allocate a FieldDesc for
    DWORD               m_dwDebugClasses;
    DWORD               m_dwDebugDuplicateInterfaceSlots;
    DWORD               m_dwDebugArrayClassRefs;
    DWORD               m_dwDebugConvertedSigSize;
    DWORD               m_dwGCSize;
    DWORD               m_dwInterfaceMapSize;
    DWORD               m_dwMethodTableSize;
    DWORD               m_dwVtableData;
    DWORD               m_dwStaticFieldData;
    DWORD               m_dwFieldDescData;
    DWORD               m_dwMethodDescData;
    size_t              m_dwEEClassData;
#endif

public:
    ClassLoader(Assembly *pAssembly);
    ~ClassLoader();

private:

    VOID PopulateAvailableClassHashTable(Module *pModule,
                                         AllocMemTracker *pamTracker);

    void LazyPopulateCaseInsensitiveHashTables();

    // Lookup the hash table entry from the hash table
    EEClassHashEntry_t *GetClassValue(NameHandleTable nhTable,
                                      NameHandle *pName,
                                      HashDatum *pData,
                                      EEClassHashTable **ppTable,
                                      Module* pLookInThisModuleOnly);


public:
    // This determines in which module an item gets placed.  For everything
    // except paramaterized types and methods the choice
    // is easy.
    //
    // If NGEN'ing we may choose to place the item into the current module.
    //
    // If running code then the rule for determining the loader
    // module must ensure that a type or method never outlives
    // its loader module with respect to app-domain unloading
    static Module* ComputeLoaderModule(Module *pDefinitionModule,      // the module that declares the generic type or method
                                       mdToken token,
                                       TypeHandle *pClassArgs,         // the type arguments to the type (if any)
                                       DWORD numClassArgs,             // the number of type argumnts to the type
                                       TypeHandle *pMethodArgs, // the type arguments to the method (if any)
                                       DWORD numMethodArgs);       // the number of type arguments to the method

    static Module* ComputeLoaderModule(MethodTable *pMT,
                                       mdToken token,           // the token of the method
                                       TypeHandle *pMethodArgs, // the type arguments to the method (if any)
                                       DWORD numMethodArgs);       // the number of type arguments to the method

    static Module *ComputeLoaderModule(TypeKey *typeKey);

private:
    BOOL FindClassModuleThrowing(NameHandle* pName,
                                 TypeHandle* pType,
                                 mdToken* pmdClassToken,
                                 Module** ppModule,
                                 mdToken *pmdFoundExportedType,
                                 EEClassHashEntry_t** ppEntry,
                                 Module* pLookInThisModuleOnly,
                                 Loader::LoadFlag loadFlag);

public:
    void Init(AllocMemTracker *pamTracker);

    static BOOL InitializeEE();

    Assembly* GetAssembly();
    DomainAssembly* GetDomainAssembly(AppDomain *pDomain = NULL);

    void    FreeModules();

#ifdef DACCESS_COMPILE
    void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
#endif

    //==================================================================================
    // Main entry points to class loader
    // Organized as follows:
    //   by token:
    //       TypeDef
    //       TypeDefOrRef
    //       TypeDefOrRefOrSpec
    //   by constructed type:
    //       ArrayType
    //       PointerOrByrefType
    //       FnPtrType
    //       GenericInstantiation
    //   by name:
    //       ByName
    // Each takes a parameter comes, with the following semantics:
    //       fLoadTypes=DontLoadTypes:  if type isn't already in the loader's table, return NULL
    //       fLoadTypes=LoadTypes: if type isn't already in the loader's table, then create it
    // Each comes in two variants, LoadXThrowing and LoadXNoThrow, the latter being just
    // a exception-handling wrapper around the former.
    //
    // Each also allows types to be loaded only up to a particular level (see classloadlevel.h).
    // The class loader itself makes use of these levels to "break" recursion across
    // generic instantiations. External clients should leave the parameter at its default
    // value (CLASS_LOADED).
    //==================================================================================

public:

    // We use enums for these flags so that we can easily search the codebase to
    // determine where the flags are set to their non-default values.
    //
    // This enum tells us what to do if the load fails.  If ThrowIfNotFound is used
    // with a HRESULT-returning NOTHROW function then it actually indicates that
    // an error-HRESULT will be returned.
    typedef enum { ThrowIfNotFound, ReturnNullIfNotFound } NotFoundAction;

    // This flag indicates whether we should accept an uninstantiatednaked TypeDef or TypeRef
    // for a generic type definition, where "uninstantiated" means "not used as part of
    // a TypeSpec"
    typedef enum { FailIfUninstDefOrRef, PermitUninstDefOrRef } PermitUninstantiatedFlag;

    // This flag indicates whether we want to "load" the type if it isn't already in the
    // loader's tables and has reached the load level desired.
    typedef enum { LoadTypes, DontLoadTypes } LoadTypesFlag;


    // Load types by token (Def, Ref and Spec)
    static TypeHandle LoadTypeDefThrowing(Module *pModule,
                                          mdToken typeDef,
                                          NotFoundAction fNotFound = ThrowIfNotFound,
                                          PermitUninstantiatedFlag fUninstantiated = FailIfUninstDefOrRef,
                                          mdToken tokenNotToLoad = tdNoTypes,
                                          ClassLoadLevel level = CLASS_LOADED);

    static TypeHandle LoadTypeDefOrRefThrowing(Module *pModule,
                                               mdToken typeRefOrDef,
                                               NotFoundAction fNotFound = ThrowIfNotFound,
                                               PermitUninstantiatedFlag fUninstantiated = FailIfUninstDefOrRef,
                                               mdToken tokenNotToLoad = tdNoTypes,
                                               ClassLoadLevel level = CLASS_LOADED);

    static TypeHandle LoadTypeDefOrRefOrSpecThrowing(Module *pModule,
                                                     mdToken typeRefOrDefOrSpec,
                                                     const SigTypeContext *pTypeContext,
                                                     NotFoundAction fNotFound = ThrowIfNotFound,
                                                     PermitUninstantiatedFlag fUninstantiated = FailIfUninstDefOrRef,
                                                     LoadTypesFlag fLoadTypes = LoadTypes,
                                                     ClassLoadLevel level = CLASS_LOADED,
                                                     BOOL dropGenericArgumentLevel = FALSE,
                                                     const Substitution *pSubst = NULL /* substitution to apply if the token is a type spec with generic variables */ );

    static HRESULT LoadTypeDefOrRefNoThrow(Module *pModule,
                                           mdToken typeRefOrDef,
                                           TypeHandle *pthOut,
                                           OBJECTREF *pThrowable,
                                           NotFoundAction fNotFound = ThrowIfNotFound,
                                           PermitUninstantiatedFlag fUninstantiated = FailIfUninstDefOrRef);


    static HRESULT LoadTypeDefOrRefOrSpecNoThrow(Module *pModule,
                                                 mdToken typeRefOrDefOrSpec,
                                                 const SigTypeContext *pTypeContext,
                                                 TypeHandle *pthOut,
                                                 OBJECTREF *pThrowable,
                                                 NotFoundAction fNotFound = ThrowIfNotFound,
                                                 PermitUninstantiatedFlag fUninstantiated = FailIfUninstDefOrRef,
                                                 LoadTypesFlag fLoadTypes = LoadTypes,
                                                 ClassLoadLevel level = CLASS_LOADED);

    // Load constructed types by providing their constituents
    static TypeHandle LoadPointerOrByrefTypeThrowing(CorElementType typ,
                                                     TypeHandle baseType,
                                                     LoadTypesFlag fLoadTypes = LoadTypes,
                                                     ClassLoadLevel level = CLASS_LOADED);

    static TypeHandle LoadArrayTypeThrowing(TypeHandle baseType,
                                            CorElementType typ = ELEMENT_TYPE_SZARRAY,
                                            unsigned rank = 0,
                                            LoadTypesFlag fLoadTypes = LoadTypes,
                                            ClassLoadLevel level = CLASS_LOADED);

    static TypeHandle LoadFnptrTypeThrowing(BYTE callConv,
                                            DWORD numArgs,
                                            TypeHandle* retAndArgTypes,
                                            LoadTypesFlag fLoadTypes = LoadTypes,
                                            ClassLoadLevel level = CLASS_LOADED);

    // Load types by name
    static TypeHandle LoadTypeByNameThrowing(Assembly *pAssembly,
                                             LPCUTF8 nameSpace,
                                             LPCUTF8 name,
                                             NotFoundAction fNotFound = ThrowIfNotFound,
                                             LoadTypesFlag fLoadTypes = LoadTypes,
                                             ClassLoadLevel level = CLASS_LOADED);

    static TypeHandle LoadTypeByNameNoThrow(Assembly *pAssembly,
                                            LPCUTF8 nameSpace,
                                            LPCUTF8 name,
                                            OBJECTREF *pThrowable,
                                            ClassLoadLevel level = CLASS_LOADED);

    // Resolve a TypeRef to a TypeDef
    // (Just a no-op on TypeDefs)
    // Return FALSE if operation failed (e.g. type does not exist)
    static BOOL ResolveTokenToTypeDefThrowing(Module *pTypeRefModule,
                                              mdTypeRef typeRefToken,
                                              Module **ppTypeDefModule,
                                              mdTypeDef *pTypeDefToken,
                                              Loader::LoadFlag loadFlag=Loader::Load);

    static void EnsureLoaded(TypeHandle typeHnd, ClassLoadLevel level = CLASS_LOADED);
    static void TryEnsureLoaded(TypeHandle typeHnd, ClassLoadLevel level = CLASS_LOADED);

public:
    // Look up a class by name
    //
    // Guaranteed to only return NULL if pName->OKToLoad() returns FALSE.
    // Thus when type loads are enabled this will return non-null.
    TypeHandle LoadTypeHandleThrowIfFailed(NameHandle* pName, ClassLoadLevel level = CLASS_LOADED,
                                           Module* pLookInThisModuleOnly=NULL);

public:
    // Looks up class in the local module table, if it is there it succeeds,
    // Otherwise it fails, This is meant only for optimizations etc
    static TypeHandle LookupTypeDefOrRefInModule(Module *pModule, mdToken cl);

private:

    VOID AddAvailableClassDontHaveLock(Module *pModule,
                                       mdTypeDef classdef,
                                       AllocMemTracker *pamTracker);

    VOID AddAvailableClassHaveLock(Module *pModule,
                                   mdTypeDef classdef,
                                   AllocMemTracker *pamTracker);

    VOID AddExportedTypeHaveLock(Module *pManifestModule,
                                 mdExportedType cl,
                                 AllocMemTracker *pamTracker);

public:

    static TypeHandle LoadCanonicalGenericArg(TypeHandle genericArg,
                                              LoadTypesFlag fLoadTypes = LoadTypes,
                                              ClassLoadLevel = CLASS_LOADED);

    // Create a generic instantiation.
    // If typeDef is not a generic type then throw an exception
    // If its arity does not match nGenericClassArgCount then throw an exception
    // The pointer to the instantiation is not persisted e.g. the type parameters can be stack-allocated.
    // If inst=NULL then <__Canon,...,__Canon> is assumed
    // If fLoadTypes=DontLoadTypes then the type handle is not created if it is not
    // already present in the tables.
    static TypeHandle LoadGenericInstantiationThrowing(Module *pModule,
                                                       mdTypeDef typeDef,
                                                       DWORD nGenericClassArgCount,
                                                       TypeHandle* pGenericClassArgs,
                                                       LoadTypesFlag fLoadTypes = LoadTypes,
                                                       ClassLoadLevel level = CLASS_LOADED);
    static TypeHandle LoadGenericInstantiationNoThrow(Module *pModule,
                                                      mdTypeDef typeDef,
                                                      DWORD nGenericClassArgCount,
                                                      TypeHandle* pGenericClassArgs,
                                                      OBJECTREF *pThrowable,
                                                      LoadTypesFlag fLoadTypes = LoadTypes,
                                                      ClassLoadLevel level = CLASS_LOADED);

    // Return TRUE if inst is the typical instantiation for the type or method specified by pModule/token
    static BOOL IsTypicalInstantiation(Module *pModule, mdToken token, DWORD numGenericArgs, TypeHandle *inst);

    // Can the objectref be cast to the type represented by pMT?
    // pMT cannot represent an array class, pRef can be an array
    // pMT can represent an instantiated type
    static BOOL CanCastToClassOrInterface(OBJECTREF pRef, MethodTable *pMT);

    static BOOL CanAccessMethod(MethodDesc *pCurrentMethod, MethodTable *pParentMT, MethodDesc *pMD);
    static BOOL CanAccessField(MethodDesc *pCurrentMethod, MethodTable *pParentMT, FieldDesc *pFD);
    static BOOL CanAccessMethodInstantiation(MethodDesc* pCallerMD, MethodTable *pCurrentClass, Assembly *pCurrentAssembly, MethodDesc *pOptionalTargetMethod);
    static BOOL CanAccessClass(MethodDesc* pCallerMD, MethodTable *pCurrentClass, Assembly *pCurrentAssembly,
                               MethodTable *pTargetClass, Assembly *pTargetAssembly);
    static BOOL CanAccess(MethodDesc* pCurrentMD, MethodTable *pCurrentClass, Assembly *pCurrentAssembly,
                          MethodTable *pTargetClass, Assembly *pTargetAssembly,
                          DWORD dwMemberAttrs, MethodDesc *pOptionalTargetMethod, FieldDesc* pOptionalTargetField = NULL);
    static BOOL CanAccess(MethodDesc* pCurrentMD, MethodTable *pCurrentClass, Assembly *pCurrentAssembly,
                          MethodTable *pTargetClass, Assembly *pTargetAssembly,
                          MethodTable *pInstanceClass, DWORD dwMemberAccess, MethodDesc *pOptionalTargetMethod, FieldDesc* pOptionalTargetField = NULL);
    static BOOL CanAccessMemberForExtraChecks(
                        MethodDesc*  pCurrentMD,
                        MethodTable *pCurrentMT,
                        Assembly    *pCurrentAssembly,
                        MethodTable *pTargetExactMT,
                        MethodDesc  *pOptionalTargetMethod,
                        FieldDesc   *pOptionalTargetField);
    static BOOL CanAccessSigForExtraChecks(
                        MethodDesc*  pCurrentMD,
                        MethodTable *pCurrentMT,
                        Assembly    *pCurrentAssembly,
                        MethodDesc  *pTargetMethodSig,
                        MethodTable *pTargetExactMT);
    static BOOL CanAccessSigForExtraChecks(
                        MethodDesc*  pCurrentMD,
                        PCCOR_SIGNATURE sig);
    static BOOL CanAccessClassForExtraChecks(
                        MethodDesc * pCurrentMD,
                        MethodTable *pCurrentClass,
                        Assembly *   pCurrentAssembly,
                        MethodTable *pTargetClass,
                        Assembly    *pTargetAssembly);
    static BOOL CanAccessFamily(MethodTable *pCurrentClass, MethodTable *pTargetClass,
                                MethodTable *pInstanceClass);
    static BOOL CheckAccess(MethodDesc* pCurrentMD, MethodTable *pCurrentClass, Assembly *pCurrentAssembly,
                            MethodTable *pTargetClass, Assembly *pTargetAssembly,
                            DWORD dwMemberAttrs,
                            MethodDesc *pOptionalTargetMethod, FieldDesc* pOptionalTargetField = NULL);
    static BOOL CheckAccess(MethodDesc* pCurrentMD, MethodTable *pCurrentClass, Assembly *pCurrentAssembly,
                            MethodTable *pTargetClass, Assembly *pTargetAssembly,
                            MethodTable *pInstanceClass, 
                            DWORD dwMemberAttrs,
                            MethodDesc *pOptionalTargetMethod, FieldDesc* pOptionalTargetField = NULL);

    //Creates a key with both the namespace and name converted to lowercase and
    //made into a proper namespace-path.
    VOID CreateCanonicallyCasedKey(LPCUTF8 pszNameSpace, LPCUTF8 pszName,
                                      LPUTF8 *ppszOutNameSpace, LPUTF8 *ppszOutName);

    static HRESULT FindTypeDefByExportedType(IMDInternalImport *pCTImport,
                                             mdExportedType mdCurrent,
                                             IMDInternalImport *pTDImport,
                                             mdTypeDef *mtd);

    class AvailableClasses_LockHolder : public CrstPreempHolder
    {
    public:
        AvailableClasses_LockHolder(ClassLoader *classLoader, BOOL Take = TRUE)
            : CrstPreempHolder(&classLoader->m_AvailableClassLock, Take)
        {
            WRAPPER_CONTRACT;
        }
    };
    friend class AvailableClasses_LockHolder;

private:

    static TypeHandle LoadConstructedTypeThrowing(TypeKey *pKey,
                                                  LoadTypesFlag fLoadTypes = LoadTypes,
                                                  ClassLoadLevel level = CLASS_LOADED);

    static TypeHandle LookupTypeKeyUnderLock(TypeKey *pKey,
                                             EETypeHashTable *pTable,
                                             CrstBase *pLock);

    static TypeHandle LookupTypeKey(TypeKey *pKey,
                                    EETypeHashTable *pTable,
                                    CrstBase *pLock,
                                    BOOL fCheckUnderLock);

    static TypeHandle LookupInLoaderModule(TypeKey* pKey, BOOL fCheckUnderLock);

    // Lookup a handle in the appropriate table 
    // (declaring module for TypeDef or loader-module for constructed types) 
    static TypeHandle LookupTypeHandleForTypeKey(TypeKey *pTypeKey);
    static TypeHandle LookupTypeHandleForTypeKeyInner(TypeKey *pTypeKey, BOOL fCheckUnderLock);

    static void DECLSPEC_NORETURN  ThrowTypeLoadException(TypeKey *pKey, UINT resIDWhy);


    BOOL IsNested(NameHandle* pName, mdToken *mdEncloser);
    static BOOL IsNested(Module *pModude, mdToken typeDefOrRef, mdToken *mdEncloser);

    // Helpers for FindClassModule()
    BOOL CompareNestedEntryWithTypeDef(IMDInternalImport *pImport,
                                       mdTypeDef mdCurrent,
                                       EEClassHashTable *pClassHash,
                                       EEClassHashEntry_t *pEntry);
    BOOL CompareNestedEntryWithTypeRef(IMDInternalImport *pImport,
                                       mdTypeRef mdCurrent,
                                       EEClassHashTable *pClassHash,
                                       EEClassHashEntry_t *pEntry);
    BOOL CompareNestedEntryWithExportedType(IMDInternalImport *pImport,
                                            mdExportedType mdCurrent,
                                            EEClassHashTable *pClassHash,
                                            EEClassHashEntry_t *pEntry);

public:
    //Attempts to find/load/create a type handle but does not throw
    // if used in "find" mode.
    TypeHandle LoadTypeHandleThrowing(NameHandle* pName, ClassLoadLevel level = CLASS_LOADED,
                                      Module* pLookInThisModuleOnly=NULL);

private:

#ifndef DACCESS_COMPILE
    // Perform a single phase of class loading
    // If no type handle has yet been created, typeHnd is null.
    static TypeHandle DoIncrementalLoad(TypeKey *pTypeKey, 
                                        TypeHandle typeHnd, 
                                        ClassLoadLevel workLevel);

    // Phase CLASS_LOAD_CREATE of class loading
    static TypeHandle CreateTypeHandleForTypeKey(TypeKey *pTypeKey,
                                                 AllocMemTracker *pamTracker);

    // Publish the type in the loader's tables
    static void PublishType(TypeKey *pTypeKey, TypeHandle typeHnd);

    // Notify profiler and debugger that a type load has completed
    // Also update perf counters
    static void Notify(TypeHandle typeHnd);

    // Phase CLASS_LOAD_EXACTPARENTS of class loading
    // Load exact parents and interfaces and dependent structures (generics dictionary, vtable fixes)
    static void LoadExactParents(MethodTable *pMT);

    static BOOL LoadExactParentAndInterfacesTransitively(MethodTable *pMT);


    static TypeHandle TryFindDynLinkZapType(TypeKey* pKey);

    // Create a non-canonical instantiation of a generic type based off the canonical instantiation
    // (For example, MethodTable for List<string> is based on the MethodTable for List<__Canon>)
    static TypeHandle CreateTypeHandleForNonCanonicalGenericInstantiation(TypeKey *pTypeKey,
                                                                          AllocMemTracker *pamTracker);

    // Loads a class. This is the inner call from the multi-threaded load. This load must
    // be protected in some manner.
    // If we're attempting to load a fresh instantiated type then genericArgs should be filled in

    static TypeHandle CreateTypeHandleForTypeDefThrowing(Module *pModule,
                                                         mdTypeDef cl,
                                                         TypeHandle* genericArgs,
                                                         AllocMemTracker *pamTracker);

    TypeHandle LoadTypeHandleForTypeKey(TypeKey *pTypeKey,
                                        TypeHandle typeHnd,
                                        ClassLoadLevel level = CLASS_LOADED);

    TypeHandle LoadTypeHandleForTypeKeyNoLock(TypeKey *pTypeKey,
                                              ClassLoadLevel level = CLASS_LOADED);

    // Used for initial loading of parent class and implemented interfaces
    // When tok represents an instantiated type return an *approximate* instantiated
    // type (where reference type arguments are replaced by Object)
    static TypeHandle LoadApproxTypeThrowing(Module *pModule,
                                             mdToken tok,
                                             PCCOR_SIGNATURE *formalInst,
                                             const SigTypeContext *pClassTypeContext);

    // Returns the parent of a token. The token must be a typedef.
    // If the parent is a shared constructed type (e.g. class C : List<string>) then
    // only the canonical instantiation is loaded at this point.
    // This is to avoid cycles in the loader e.g. on class C : D<C> or class C<T> : D<C<T>>
    // We fix up the exact parent later in LoadInstantiatedInfo.
    static MethodTable* LoadApproxParentThrowing(Module *pModule,
                                                 mdToken cl,
                                                 PCCOR_SIGNATURE* pParentInst,
                                                 const SigTypeContext *pClassTypeContext);

    // Locates the enclosing class of a token if any. The token must be a typedef.
    static VOID GetEnclosingClassThrowing(IMDInternalImport *pInternalImport,
                                          Module *pModule,
                                          mdTypeDef cl,
                                          mdTypeDef *tdEnclosing);
    
    // Insert the class in the classes hash table and if needed in the case insensitive one
    EEClassHashEntry_t *InsertValue(EEClassHashTable *pClassHash,
                                    EEClassHashTable *pClassCaseInsHash,
                                    LPCUTF8 pszNamespace,
                                    LPCUTF8 pszClassName,
                                    HashDatum Data,
                                    EEClassHashEntry_t *pEncloser,
                                    AllocMemTracker *pamTracker);

    // don't call this directly.
    TypeHandle LoadTypeHandleForTypeKey_Body(TypeKey *pTypeKey,
                                             TypeHandle typeHnd,
                                             ClassLoadLevel workLevel,
                                             PendingTypeLoadEntry_LockHolder *pLoadingEntryLockHolder,
                                             CrstHolder *pUnresolvedClassLockHolder);

    // don't call this directly.
    TypeHandle LoadTypeHandleForTypeKey_Inner(TypeKey *pTypeKey,
                                              TypeHandle typeHnd,
                                              ClassLoadLevel workLevel,
                                              PendingTypeLoadEntry_LockHolder *pLoadingEntryLockHolder,
                                              CrstHolder *pUnresolvedClassLockHolder,
                                              PendingTypeLoadEntry*& pPendingLoadingEntry);

#endif // #ifndef DACCESS_COMPILE

};

// Class to encapsulate Cor Command line processing
class CorCommandLine
{
public:

//********** TYPES

    // Note: We don't bother with interlocked operations as we manipulate these bits,
    // because we don't anticipate free-threaded access.  (Most of this is used only
    // during startup / shutdown).

//********** DATA

    // Hold the current (possibly parsed) command line here
    static DWORD            m_NumArgs;
    static LPWSTR          *m_ArgvW;

    static LPWSTR          m_pwszAppFullName;
    static DWORD           m_dwManifestPaths;
    static LPWSTR         *m_ppwszManifestPaths;
    static DWORD           m_dwActivationData;
    static LPWSTR         *m_ppwszActivationData;

//********** METHODS

    // parse the command line
    static HRESULT         SetArgvW(LPCWSTR lpCommandLine);

    // Retrieve the parsed command line
    static LPWSTR          *GetArgvW(DWORD *pNumArgs);

private:
    static HRESULT ReadClickOnceEnvVariables();
    static HRESULT ParseCor();
};

// -------------------------------------------------------
// This just wraps the RangeList methods in a read or
// write lock depending on the operation.
// -------------------------------------------------------

class LockedRangeList : public RangeList
{
  public:
    VPTR_VTABLE_CLASS(LockedRangeList, RangeList)
    
    LockedRangeList() : RangeList(), m_RangeListRWLock(COOPERATIVE_OR_PREEMPTIVE, LOCK_TYPE_DEFAULT)
    {
        WRAPPER_CONTRACT;
    }

    ~LockedRangeList()
    {
        LEAF_CONTRACT;
    }

  protected:

    virtual BOOL AddRangeWorker(const BYTE *start, const BYTE *end, void *id)
    {
        WRAPPER_CONTRACT;
        SimpleWriteLockHolder lh(&m_RangeListRWLock);
        return RangeList::AddRangeWorker(start,end,id);
    }

    virtual void RemoveRangesWorker(void *id, const BYTE *start = NULL, const BYTE *end = NULL)
    {
        WRAPPER_CONTRACT;
        SimpleWriteLockHolder lh(&m_RangeListRWLock);
        RangeList::RemoveRangesWorker(id,start,end);
    }

    virtual BOOL IsInRangeWorker(TADDR address, TADDR *pID = NULL)
    {
        WRAPPER_CONTRACT;
        SimpleReadLockHolder lh(&m_RangeListRWLock);
        return RangeList::IsInRangeWorker(address, pID);
    }

    virtual TADDR FindIdWithinRangeWorker(TADDR start, TADDR end)
    {
        WRAPPER_CONTRACT;
        SimpleReadLockHolder lh(&m_RangeListRWLock);
        return RangeList::FindIdWithinRangeWorker(start, end);
    }
  
    SimpleRWLock m_RangeListRWLock;
};

// -------------------------------------------------------
// Stub manager classes for method desc prestubs & normal
// frame-pushing, StubLinker created stubs
// -------------------------------------------------------

typedef VPTR(class MethodDescPrestubManager) PTR_MethodDescPrestubManager;

class MethodDescPrestubManager : public StubManager
{
    VPTR_VTABLE_CLASS(MethodDescPrestubManager, StubManager)

  public:

    SPTR_DECL(MethodDescPrestubManager, g_pManager);

#ifdef _DEBUG
        // Debug helper to help identify stub-managers.
        virtual const char * DbgGetName() { return "MethodDescPrestubManager"; }
#endif


    static void Init();

#ifndef DACCESS_COMPILE
    MethodDescPrestubManager() : StubManager(), m_rangeList() {WRAPPER_CONTRACT;}
    ~MethodDescPrestubManager() {LEAF_CONTRACT;}
#endif

  protected:
    LockedRangeList m_rangeList;
  public:
    // Get dac-ized pointer to rangelist.
    PTR_RangeList GetRangeList() 
    {
        TADDR addr = PTR_HOST_MEMBER_TADDR(MethodDescPrestubManager, this, m_rangeList);
        return PTR_RangeList(addr);
    }


    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);
#ifndef DACCESS_COMPILE
    virtual BOOL TraceManager(Thread *thread,
                              TraceDestination *trace,
                              CONTEXT *pContext,
                              BYTE **pRetAddr);
#endif

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT);

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"MethodDescPrestub"; }
#endif
};

// Note that this stub was written by a debugger guy, and thus when he refers to 'multicast'
// stub, he really means multi or single cast stub.  This was done b/c the same stub
// services both types of stub.
// Note from the debugger guy: the way to understand what this manager does is to
// first grok EmitMulticastInvoke for the platform you're working on (right now, just x86).
// Then return here, and understand that (for x86) the only way we know which method
// we're going to invoke next is by inspecting EDI when we've got the debuggee stopped
// in the stub, and so our trace frame will either (FRAME_PUSH) put a breakpoint
// in the stub, or (if we hit the BP) examine EDI, etc, & figure out where we're going next.

typedef VPTR(class StubLinkStubManager) PTR_StubLinkStubManager;

class StubLinkStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(StubLinkStubManager, StubManager)

  public:

#ifdef _DEBUG
    virtual const char * DbgGetName() { return "StubLinkStubManager"; }
#endif    


    SPTR_DECL(StubLinkStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    StubLinkStubManager() : StubManager(), m_rangeList() {WRAPPER_CONTRACT;}
    ~StubLinkStubManager() {LEAF_CONTRACT;}
#endif
  
  protected:
    LockedRangeList m_rangeList;
  public:
    // Get dac-ized pointer to rangelist.
    PTR_RangeList GetRangeList() 
    {
        TADDR addr = PTR_HOST_MEMBER_TADDR(StubLinkStubManager, this, m_rangeList);
        return PTR_RangeList(addr);
    }


    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

  private:
    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);
#ifndef DACCESS_COMPILE
    virtual BOOL TraceManager(Thread *thread,
                              TraceDestination *trace,
                              CONTEXT *pContext,
                              BYTE **pRetAddr);
#endif

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT)  {LEAF_CONTRACT; return NULL;}

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"StubLinkStub"; }
#endif
} ;

// Stub manager for thunks.

typedef VPTR(class ThunkHeapStubManager) PTR_ThunkHeapStubManager;

class ThunkHeapStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(ThunkHeapStubManager, StubManager)

  public:

    SPTR_DECL(ThunkHeapStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    ThunkHeapStubManager() : StubManager(), m_rangeList() {WRAPPER_CONTRACT;}
    ~ThunkHeapStubManager() {LEAF_CONTRACT;}
#endif

#ifdef _DEBUG
    virtual const char * DbgGetName() { return "ThunkHeapStubManager"; }
#endif

  protected:
    LockedRangeList m_rangeList;
  public:
    // Get dac-ized pointer to rangelist.
    PTR_RangeList GetRangeList() 
    {
        TADDR addr = PTR_HOST_MEMBER_TADDR(ThunkHeapStubManager, this, m_rangeList);
        return PTR_RangeList(addr);
    }
    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

  private:
    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);
    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT)  {LEAF_CONTRACT; return NULL;}

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"ThunkHeapStub"; }
#endif
};

//
// Stub manager for jump stubs created by ExecutionManager::jumpStub()
// These are currently used only on the 64-bit targets IA64 and AMD64
//
typedef VPTR(class JumpStubStubManager) PTR_JumpStubStubManager;

class JumpStubStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(JumpStubStubManager, StubManager)

  public:

    SPTR_DECL(JumpStubStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    JumpStubStubManager() : StubManager(), m_rangeList() {WRAPPER_CONTRACT;}
    ~JumpStubStubManager() {LEAF_CONTRACT;}
#endif
  
  protected:
    LockedRangeList m_rangeList;
  public:
    // Get dac-ized pointer to rangelist.
    PTR_RangeList GetRangeList() 
    {
        TADDR addr = PTR_HOST_MEMBER_TADDR(JumpStubStubManager, this, m_rangeList);
        return PTR_RangeList(addr);
    }


#ifdef _DEBUG
    virtual const char * DbgGetName() { return "JumpStubStubManager"; }
#endif

    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT);

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"JumpStub"; }
#endif
};

//
// Stub manager for method entry points
// These are currently used only by the IA64 target
//
typedef VPTR(class EntryPointStubManager) PTR_EntryPointStubManager;

class EntryPointStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(EntryPointStubManager, StubManager)

  public:

    SPTR_DECL(EntryPointStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    EntryPointStubManager() : StubManager(), m_rangeList() {WRAPPER_CONTRACT;}
    ~EntryPointStubManager() {LEAF_CONTRACT;}
#endif

   protected:
    LockedRangeList m_rangeList;
   public:
    // Get dac-ized pointer to rangelist.
    PTR_RangeList GetRangeList() 
    {
        TADDR addr = PTR_HOST_MEMBER_TADDR(EntryPointStubManager, this, m_rangeList);
        return PTR_RangeList(addr);
    }


#ifdef _DEBUG
    virtual const char * DbgGetName() { return "EntryPointStubManager"; }
#endif

    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

    static BOOL CheckIsStub_Static(const BYTE *stubStartAddress, const BYTE **stubTargetAddress);

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT);

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"EntryPointStub"; }
#endif
};

//
// This is the stub manager for IL stubs, which are only used if
// STUBS_AS_IL is defined.
//
typedef VPTR(class ILStubManager) PTR_ILStubManager;

class ILStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(ILStubManager, StubManager)

  public:

    SPTR_DECL(ILStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    ILStubManager() : StubManager(), m_rangeList() {WRAPPER_CONTRACT;}
    ~ILStubManager() {LEAF_CONTRACT;}
#endif

   protected:
    LockedRangeList m_rangeList;
   public:
    // Get dac-ized pointer to rangelist.
    PTR_RangeList GetRangeList() 
    {
        TADDR addr = PTR_HOST_MEMBER_TADDR(ILStubManager, this, m_rangeList);
        return PTR_RangeList(addr);
    }


#ifdef _DEBUG
    virtual const char * DbgGetName() { return "ILStubManager"; }
#endif

    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

    virtual BOOL AddStub(const BYTE* pILStub, MethodDesc* pMD);

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT) {LEAF_CONTRACT; return NULL;}

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"ILStub"; }
#endif
};

// This is only used to recognize NDirectEntryPointStub() on WIN64.
typedef VPTR(class NDirectDispatchStubManager) PTR_NDirectDispatchStubManager;

class NDirectDispatchStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(NDirectDispatchStubManager, StubManager)

  public:

    SPTR_DECL(NDirectDispatchStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    NDirectDispatchStubManager() : StubManager() {LEAF_CONTRACT;}
    ~NDirectDispatchStubManager() {LEAF_CONTRACT;}
#endif

#ifdef _DEBUG
    virtual const char * DbgGetName() { return "NDirectDispatchStubManager"; }
#endif

    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT)  {LEAF_CONTRACT; return NULL;}

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"NDirectEntryPointStub"; }
#endif
};

// This is only used to recognize NDirectEntryPointStub() on WIN64.
typedef VPTR(class ComPlusDispatchStubManager) PTR_ComPlusDispatchStubManager;

class ComPlusDispatchStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(ComPlusDispatchStubManager, StubManager)

  public:

    SPTR_DECL(ComPlusDispatchStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    ComPlusDispatchStubManager() : StubManager() {LEAF_CONTRACT;}
    ~ComPlusDispatchStubManager() {LEAF_CONTRACT;}
#endif

#ifdef _DEBUG
    virtual const char * DbgGetName() { return "ComPlusDispatchStubManager"; }
#endif

    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT)  {LEAF_CONTRACT; return NULL;}

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"GenericComPlusCallStub"; }
#endif
};

// This is only used to recognize UMThunkStub() on WIN64.
typedef VPTR(class ReverseInteropStubManager) PTR_ReverseInteropStubManager;

class ReverseInteropStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(ReverseInteropStubManager, StubManager)

  public:

    SPTR_DECL(ReverseInteropStubManager, g_pManager);

    static void Init();

#ifndef DACCESS_COMPILE
    ReverseInteropStubManager() : StubManager() {LEAF_CONTRACT;}
    ~ReverseInteropStubManager() {LEAF_CONTRACT;}
#endif

#ifdef _DEBUG
    virtual const char * DbgGetName() { return "ReverseInteropILStub"; }
#endif

    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT)  {LEAF_CONTRACT; return NULL;}

#if !defined(DACCESS_COMPILE)
    virtual BOOL TraceManager(Thread *thread, TraceDestination *trace, CONTEXT *pContext, BYTE **pRetAddr);
    virtual void GetVirtualTraceCallTarget(TADDR* pTargets, DWORD* pdwNumTargets);
#endif // DACCESS_COMPILE

#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"UMThunkStub"; }
#endif
};

//
// Since we don't generate delegate invoke stubs at runtime on WIN64, we
// can't use the StubLinkStubManager for these stubs.  Instead, we create
// an additional DelegateInvokeStubManager instead.
//
typedef VPTR(class DelegateInvokeStubManager) PTR_DelegateInvokeStubManager;

class DelegateInvokeStubManager : public StubManager
{
    VPTR_VTABLE_CLASS(DelegateInvokeStubManager, StubManager)

  public:

    SPTR_DECL(DelegateInvokeStubManager, g_pManager);

    static void Init();

#if !defined(DACCESS_COMPILE)
    DelegateInvokeStubManager() : StubManager(), m_rangeList() {WRAPPER_CONTRACT;}
    ~DelegateInvokeStubManager() {LEAF_CONTRACT;}
#endif // DACCESS_COMPILE

    BOOL AddStub(Stub* pStub);
    void RemoveStub(Stub* pStub);

#ifdef _DEBUG
    virtual const char * DbgGetName() { return "DelegateInvokeStubManager"; }
#endif


    virtual BOOL CheckIsStub_Internal(TADDR stubStartAddress);

#if !defined(DACCESS_COMPILE)
    virtual BOOL TraceManager(Thread *thread, TraceDestination *trace, CONTEXT *pContext, BYTE **pRetAddr);
    static BOOL TraceDelegateObject(BYTE *orDel, TraceDestination *trace);
#endif // DACCESS_COMPILE

  private:

    virtual BOOL DoTraceStub(const BYTE *stubStartAddress, TraceDestination *trace);

    virtual MethodDesc *Entry2MethodDesc(const BYTE *StubStartAddress, MethodTable *pMT)  {LEAF_CONTRACT; return NULL;}

   protected:
    LockedRangeList m_rangeList;
   public:
    // Get dac-ized pointer to rangelist.
    PTR_RangeList GetRangeList() 
    {
        TADDR addr = PTR_HOST_MEMBER_TADDR(DelegateInvokeStubManager, this, m_rangeList);
        return PTR_RangeList(addr);
    }


#ifdef DACCESS_COMPILE
    virtual void DoEnumMemoryRegions(CLRDataEnumMemoryFlags flags);

  protected:
    virtual LPCWSTR GetStubManagerName(TADDR addr)
        { LEAF_CONTRACT; return L"DelegateInvokeStub"; }
#endif
};

#endif /* _H_CLSLOAD */

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us