A
download binder.cpp
Language: C++
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 1150
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
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
// ==++==
// 
//   
//    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.
//   
// 
// ==--== 
#include "common.h"

#include "binder.h"
#include "ecall.h"

#include "field.h"
#include "excep.h"

#include "message.h"
#include "comnumber.h"
#include "eeconfig.h"
#include "rwlock.h"
#include "runtimehandles.h"
#include "customattribute.h"
#include "debugdebugger.h"

#ifndef DACCESS_COMPILE

void Binder::Init(Module *pModule,
                  const ClassDescription *pClassDescriptions,
                  DWORD cClassDescriptions,
                  const MethodDescription *pMethodDescriptions,
                  DWORD cMethodDescriptions,
                  const FieldDescription *pFieldDescriptions,
                  DWORD cFieldDescriptions,
                  const TypeDescription *pTypeDescriptions,
                  DWORD cTypeDescriptions)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    m_pModule = pModule;
    pModule->m_pBinder = this;

    m_classDescriptions = pClassDescriptions;
    m_methodDescriptions = pMethodDescriptions;
    m_fieldDescriptions = pFieldDescriptions;
    m_typeDescriptions = pTypeDescriptions;

    //
    // Initialize Class RID array
    //

    _ASSERTE(cClassDescriptions < USHRT_MAX);
    m_cClassRIDs = (USHORT) cClassDescriptions;
    m_pClassRIDs = new USHORT [m_cClassRIDs];
    ZeroMemory(m_pClassRIDs, m_cClassRIDs * sizeof(*m_pClassRIDs));

    //
    // Initialize Method RID array
    //

    _ASSERTE(cMethodDescriptions < USHRT_MAX);
    m_cMethodMDs = (USHORT) cMethodDescriptions;
    m_pMethodMDs = new MethodDesc * [m_cMethodMDs];
    ZeroMemory(m_pMethodMDs, m_cMethodMDs * sizeof(*m_pMethodMDs));

    
    //
    // Initialize Field RID array
    //

    _ASSERTE(cFieldDescriptions < USHRT_MAX);
    m_cFieldRIDs = (USHORT) cFieldDescriptions;
    m_pFieldRIDs = new USHORT [m_cFieldRIDs];
    ZeroMemory(m_pFieldRIDs, m_cFieldRIDs * sizeof(*m_pFieldRIDs));

    //
    // Initialize TypeHandle array
    //

    _ASSERTE(cTypeDescriptions < USHRT_MAX);
    m_cTypeHandles = (USHORT) cTypeDescriptions;
    m_pTypeHandles = new TypeHandle [m_cTypeHandles];
    ZeroMemory(m_pTypeHandles, m_cTypeHandles * sizeof(*m_pTypeHandles));
}

void Binder::Destroy()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END;
    
    if (m_pClassRIDs != NULL
        && !m_pModule->IsPersistedObject(m_pClassRIDs))
        delete [] m_pClassRIDs;

    if (m_pMethodMDs != NULL
        && !m_pModule->IsPersistedObject(m_pMethodMDs))
        delete [] m_pMethodMDs;

    if (m_pFieldRIDs != NULL
        && !m_pModule->IsPersistedObject(m_pFieldRIDs))
        delete [] m_pFieldRIDs;

    if (m_pTypeHandles != NULL)
        delete [] m_pTypeHandles;
}


#endif // #ifndef DACCESS_COMPILE

mdTypeDef Binder::GetTypeDef(BinderClassID id) 
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());

        PRECONDITION(id != CLASS__NIL);
        PRECONDITION(id <= m_cClassRIDs);
    }
    CONTRACTL_END;

    if (m_pClassRIDs[id-1] == 0)
        LookupClass(id);
    return TokenFromRid(m_pClassRIDs[id-1], mdtTypeDef);
}

mdMethodDef Binder::GetMethodDef(BinderMethodID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());

        PRECONDITION(id != METHOD__NIL);
        PRECONDITION(id <= m_cMethodMDs);
    }
    CONTRACTL_END;

    if (m_pMethodMDs[id-1] == NULL)
        LookupMethod(id);
    return m_pMethodMDs[id-1]->GetMemberDef();
}

mdFieldDef Binder::GetFieldDef(BinderFieldID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());

        PRECONDITION(id != FIELD__NIL);
        PRECONDITION(id <= m_cFieldRIDs);
    }
    CONTRACTL_END;
    
    if (m_pFieldRIDs[id-1] == 0)
        LookupField(id);
    return TokenFromRid(m_pFieldRIDs[id-1], mdtFieldDef);
}

//
// Raw retrieve structures from ID.  Use these when 
// you don't care about class Restore or .cctors.
//

MethodTable *Binder::RawGetClass(BinderClassID id, ClassLoadLevel level)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        SO_TOLERANT;

        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != CLASS__NIL);
        PRECONDITION(id <= m_cClassRIDs);        
    }
    CONTRACTL_END;

    TypeHandle th = m_pModule->LookupTypeDef(TokenFromRid(m_pClassRIDs[id-1], mdtTypeDef), level);
    _ASSERTE(!th.IsNull());
    _ASSERTE(th.IsUnsharedMT());
    return th.AsMethodTable();
}

MethodDesc *Binder::RawGetMethod(BinderMethodID id)
{
    CONTRACT(MethodDesc*)
    {
        NOTHROW;            
        GC_NOTRIGGER;
        FORBID_FAULT;
        SO_TOLERANT;

        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != METHOD__NIL);
        PRECONDITION(id <= m_cMethodMDs);

        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END;
    
    MethodDesc *pMD = m_pMethodMDs[id - 1];

    RETURN pMD;
}

FieldDesc *Binder::RawGetField(BinderFieldID id)
{
    CONTRACT(FieldDesc*)
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        SO_TOLERANT;
        
        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != FIELD__NIL);
        PRECONDITION(id <= m_cFieldRIDs);    

        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END;
    
        
    const FieldDescription *f = m_fieldDescriptions + (id - 1);
    PREFIX_ASSUME(f != NULL);
    MethodTable *pMT = RawGetClass(f->classID, CLASS_LOAD_UNRESTOREDTYPEKEY);
    PREFIX_ASSUME(pMT != NULL);

    // Can't do this because the class may not be restored yet.
    // _ASSERTE(m_pFieldRIDs[id-1]-1 < (pMT->GetClass()->GetNumStaticFields() 
    //                                  + pMT->GetNumIntroducedInstanceFields()));

    g_IBCLogger.LogFieldDescsAccess(pMT->GetClass());


    FieldDesc *pFD = pMT->GetClass()->GetFieldDescListPtr() +
        (m_pFieldRIDs[id-1] - 1);
    
    RETURN pFD;
}

TypeHandle Binder::RawGetType(BinderTypeID id)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        SO_TOLERANT;

        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != TYPE__NIL);
        PRECONDITION(id <= m_cTypeHandles);
    }
    CONTRACTL_END;
    
    TypeHandle th = m_pTypeHandles[id-1];
    _ASSERTE(!th.IsNull());
    return th;
}

//
// Inline function to check a class for init & restore
//

inline void Binder::CheckInit(MethodTable *pMT)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    if (!pMT->IsClassInited())
    {
#ifndef DACCESS_COMPILE
        InitClass(pMT);
#else
        DacNotImpl();
#endif
    }
}

//
// Fetch retrieve structures from ID - doesn't
// trigger class init
//

MethodTable *Binder::FetchClass(BinderClassID id, BOOL fLoad/* = TRUE*/, ClassLoadLevel level/* = CLASS_LOADED*/)
{
    CONTRACTL
    {
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) GC_NOTRIGGER; else GC_TRIGGERS;
        MODE_ANY;
        if (fLoad) SO_INTOLERANT; else SO_TOLERANT;
    }
    CONTRACTL_END;

    _ASSERTE(id != CLASS__NIL);
    _ASSERTE(id <= m_cClassRIDs);

    MethodTable *pMT;

    if (m_pClassRIDs[id-1] == 0)
    {
        pMT = LookupClass(id, fLoad, level);

        // If we're looking up the class because it wasn't in the class RID cache, then
        // it is possible that we won't load the type. While by definition we will always
        // have String and CriticalFinalizerObject loaded (we load them in
        // AppDomain::LoadBaseSystemClasses), new cases could be introduced so this is
        // just the safe thing to do.
        if (pMT == NULL)
        {
            return NULL;
        }

        // handle special classes
        switch (id) {
        case CLASS__STRING:
            // Strings are not "normal" objects, so we need to mess with their method table a bit
            // so that the GC can figure out how big each string is...
            pMT->SetBaseSize(ObjSizeOf(StringObject));
            pMT->SetComponentSize(2);
            break;

        case CLASS__CRITICAL_FINALIZER_OBJECT:
            // To introduce a class with a critical finalizer,
            // we'll explicitly load CriticalFinalizerObject and set the bit
            // here.
            pMT->SetHasCriticalFinalizer();
            break;

        default:
            break;
        }
    }
    else
    {
        pMT = RawGetClass(id, CLASS_LOAD_UNRESTOREDTYPEKEY);
        PREFIX_ASSUME(pMT != NULL);
        if (fLoad)
            ClassLoader::EnsureLoaded(pMT, level);
        g_IBCLogger.LogMethodTableAccess(pMT);
    }

    return pMT;
}

MethodDesc *Binder::FetchMethod(BinderMethodID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());
    }
    CONTRACTL_END;

    _ASSERTE(id != METHOD__NIL);
    _ASSERTE(id <= m_cMethodMDs);

    MethodDesc *pMD;

    if (m_pMethodMDs[id-1] == 0)
        pMD = LookupMethod(id);
    else
    {
        pMD = RawGetMethod(id);
        pMD->CheckRestore();

        g_IBCLogger.LogMethodDescAccess(pMD);
    }

    if (m_methodDescriptions[id-1].sig != NULL)
    {
        // Initialize the sig here where it's safe.  (Otherwise it would typically happen
        // during a MethodDesc::Call.)
        PCCOR_SIGNATURE pSig;
        DWORD cbSigSize;
        m_methodDescriptions[id-1].sig->GetBinarySig(&pSig, &cbSigSize);
    }

    return pMD;
}

FieldDesc *Binder::FetchField(BinderFieldID id)
{
    CONTRACTL
    {
        if (FORBIDGC_LOADER_USE_ENABLED() ) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED() ) GC_NOTRIGGER; else GC_TRIGGERS;
        MODE_ANY;
        if (FORBIDGC_LOADER_USE_ENABLED() ) FORBID_FAULT; else INJECT_FAULT(ThrowOutOfMemory());
        SO_TOLERANT;
    }
    CONTRACTL_END;

    _ASSERTE(id != FIELD__NIL);
    _ASSERTE(id <= m_cFieldRIDs);

    FieldDesc *pFD;

    if (m_pFieldRIDs[id-1] == 0)
        pFD = LookupField(id);
    else
    {
        pFD = RawGetField(id);
        pFD->GetEnclosingMethodTable()->CheckRestore();
    }

    return pFD;
}

TypeHandle Binder::FetchType(BinderTypeID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());

        PRECONDITION(id != TYPE__NIL);
        PRECONDITION(id <= m_cTypeHandles);
    }
    CONTRACTL_END;
        
    TypeHandle th = m_pTypeHandles[id-1];
    if (th.IsNull())
        th = LookupType(id);

    return th;
}

//
// Normal retrieve structures from ID
//

MethodTable *Binder::GetClass(BinderClassID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());
    }
    CONTRACTL_END;

#ifndef DACCESS_COMPILE
    _ASSERTE (GetThread ());
    TRIGGERSGC ();
#ifdef STRESS_HEAP
    // Force a GC here because GetClass could trigger GC nondeterminsticly
    if (g_pConfig->GetGCStressLevel() != 0)
    {
        Thread * pThread = GetThread ();
        BOOL bInCoopMode = pThread->PreemptiveGCDisabled ();
        GCX_COOP ();
        if (bInCoopMode)
        {
            pThread->PulseGCMode ();
        }
    }
#endif //STRESS_HEAP
#endif //DACCESS_COMPILE
    MethodTable *pMT = FetchClass(id);

    CheckInit(pMT);

    return pMT;
}

MethodDesc *Binder::GetMethod(BinderMethodID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());
    }
    CONTRACTL_END;

#ifndef DACCESS_COMPILE
    _ASSERTE (GetThread ());
    TRIGGERSGC ();
#ifdef STRESS_HEAP
    // Force a GC here because GetMethod could trigger GC nondeterminsticly
    if (g_pConfig->GetGCStressLevel() != 0)
    {
        Thread * pThread = GetThread ();
        BOOL bInCoopMode = pThread->PreemptiveGCDisabled ();
        GCX_COOP ();
        if (bInCoopMode)
        {
            pThread->PulseGCMode ();
        }
    }
#endif //STRESS_HEAP
#endif //DACCESS_COMPILE

    MethodDesc *pMD = FetchMethod(id);

    CheckInit(pMD->GetMethodTable());

    // Record this method desc if required
    g_IBCLogger.LogMethodDescAccess(pMD);

    return pMD;
}

FieldDesc *Binder::GetField(BinderFieldID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());
    }
    CONTRACTL_END;

#ifndef DACCESS_COMPILE
    _ASSERTE (GetThread ());
    TRIGGERSGC ();
#ifdef STRESS_HEAP
    // Force a GC here because GetField could trigger GC nondeterminsticly
    if (g_pConfig->GetGCStressLevel() != 0)
    {
        Thread * pThread = GetThread ();
        BOOL bInCoopMode = pThread->PreemptiveGCDisabled ();
        GCX_COOP ();
        if (bInCoopMode)
        {
            pThread->PulseGCMode ();
        }
    }
#endif //STRESS_HEAP
#endif //DACCESS_COMPILE

    FieldDesc *pFD = FetchField(id);

    CheckInit(pFD->GetEnclosingMethodTable());

    return pFD;
}

TypeHandle Binder::GetType(BinderTypeID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());
    }
    CONTRACTL_END;

#ifndef DACCESS_COMPILE
    _ASSERTE (GetThread ());
    TRIGGERSGC ();
#ifdef STRESS_HEAP
    // Force a GC here because GetType could trigger GC nondeterminsticly
    if (g_pConfig->GetGCStressLevel() != 0)
    {
        Thread * pThread = GetThread ();
        BOOL bInCoopMode = pThread->PreemptiveGCDisabled ();
        GCX_COOP ();
        if (bInCoopMode)
        {
            pThread->PulseGCMode ();
        }
    }
#endif //STRESS_HEAP
#endif //DACCESS_COMPILE

    TypeHandle th = FetchType(id);

    return th;
}

//
// Method address - these could conceivably be implemented
// more efficiently than accessing the Desc info.
// 

const BYTE *Binder::GetMethodAddress(BinderMethodID id)
{ 
    WRAPPER_CONTRACT;
    
    return GetMethod(id)->GetAddrofCode(); 
}

//
// Offsets - these could conceivably be implemented
// more efficiently than accessing the Desc info.
// 

DWORD Binder::GetFieldOffset(BinderFieldID id)
{ 
    WRAPPER_CONTRACT;

    return FetchField(id)->GetOffset(); 
}

BOOL Binder::IsClass(MethodTable *pMT, BinderClassID id)
{
    CONTRACTL
    {
        GC_NOTRIGGER; 
        NOTHROW;
        FORBID_FAULT;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (m_pClassRIDs[id-1] == 0)
        return PTR_HOST_TO_TADDR(LookupClass(id, FALSE, CLASS_LOAD_UNRESTOREDTYPEKEY)) ==
            PTR_HOST_TO_TADDR(pMT);
    else
        return PTR_HOST_TO_TADDR(RawGetClass(id, CLASS_LOAD_UNRESTOREDTYPEKEY)) ==
            PTR_HOST_TO_TADDR(pMT);
}

BOOL Binder::IsType(TypeHandle th, BinderTypeID id)
{
    CONTRACTL
    {
        GC_NOTRIGGER; 
        NOTHROW;
        FORBID_FAULT;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (RawGetType(id) == th)
        return TRUE;
    if (!m_pTypeHandles[id-1].IsNull())
        return FALSE;
    else
        return LookupType(id, FALSE) == th;
}

#ifndef DACCESS_COMPILE

void Binder::InitClass(MethodTable *pMT)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pMT));
    }
    CONTRACTL_END;

    // Switch to cooperative GC mode before we manipulate any OBJECTREF's.
    GCX_COOP();
    pMT->CheckRunClassInitThrowing();
}

#endif // #ifndef DACCESS_COMPILE

MethodTable *Binder::LookupClass(BinderClassID id, BOOL fLoad, ClassLoadLevel level/* = CLASS_LOADED*/)
{
    CONTRACTL
    {
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        MODE_ANY;

        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != CLASS__NIL);
        PRECONDITION(id <= m_cClassRIDs);
    }
    CONTRACTL_END;


    MethodTable *pMT;

    const ClassDescription *d = m_classDescriptions + (id - 1);
    PREFIX_ASSUME(d != NULL);
    if (!fLoad)
    {
        ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();

        pMT = ClassLoader::LoadTypeByNameThrowing(m_pModule->GetAssembly(), d->namesp, d->name, 
                                                  ClassLoader::ReturnNullIfNotFound, 
                                                  // == FailIfNotLoadedOrNotRestored
                                                  ClassLoader::DontLoadTypes,
                                                  level).AsMethodTable();
        if (pMT == NULL)
            return NULL;
    }
    else
    {
        pMT = ClassLoader::LoadTypeByNameThrowing(m_pModule->GetAssembly(), d->namesp, d->name,
                                                  ClassLoader::ThrowIfNotFound, 
                                                  ClassLoader::LoadTypes,
                                                  level).AsMethodTable();
    }

    if (pMT == NULL)
        return NULL; // Not needed, but makes prefast happy


    _ASSERTE(pMT->GetModule() == m_pModule);

    mdTypeDef td = pMT->GetCl();

    _ASSERTE(!IsNilToken(td));

    _ASSERTE(RidFromToken(td) <= USHRT_MAX);
    m_pClassRIDs[id-1] = (USHORT) RidFromToken(td);

    return pMT;
}

MethodDesc *Binder::LookupMethod(BinderMethodID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(ThrowOutOfMemory());

        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != METHOD__NIL);
        PRECONDITION(id <= m_cMethodMDs);
    }
    CONTRACTL_END;
    

    const MethodDescription *d = m_methodDescriptions + (id - 1);

    MethodTable *pMT = FetchClass(d->classID);

    MethodDesc *pMD = (d->sig != NULL) ? 
        pMT->GetClass()->FindMethod(d->name, d->sig) :
        pMT->GetClass()->FindMethodByName(d->name);

    PREFIX_ASSUME_MSGF(pMD != NULL, ("EE expects method to exist: %s:%s\n", pMT->GetDebugClassName(), d->name));

    _ASSERTE(pMD->GetSlot()+1 <= USHRT_MAX);
#ifndef DACCESS_COMPILE
    m_pMethodMDs[id-1] = pMD;
#endif

    return pMD;
}

FieldDesc *Binder::LookupField(BinderFieldID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        SO_TOLERANT;
        INJECT_FAULT(ThrowOutOfMemory());
        
        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != FIELD__NIL);
        PRECONDITION(id <= m_cFieldRIDs);
    }
    CONTRACTL_END;

    const FieldDescription *d = m_fieldDescriptions + (id - 1);
    PREFIX_ASSUME(d != NULL);
    MethodTable *pMT = FetchClass(d->classID);

    FieldDesc *pFD;

    pFD = pMT->GetClass()->FindField(d->name, NULL, 0, NULL);

#ifndef DACCESS_COMPILE
    PREFIX_ASSUME_MSGF(pFD != NULL, ("EE expects field to exist: %s:%s\n", pMT->GetDebugClassName(), d->name));

    _ASSERTE(pFD - pMT->GetApproxFieldDescListRaw() >= 0);
    _ASSERTE(pFD - pMT->GetApproxFieldDescListRaw() < (pMT->GetNumStaticFields() 
                                                             + pMT->GetNumIntroducedInstanceFields()));
    _ASSERTE(pFD - pMT->GetApproxFieldDescListRaw() + 1 < USHRT_MAX);

    USHORT index = (USHORT)(pFD - pMT->GetApproxFieldDescListRaw());

    m_pFieldRIDs[id-1] = index+1;
#endif

    return pFD;
}

TypeHandle Binder::LookupType(BinderTypeID id, BOOL fLoad)
{
    CONTRACTL
    {
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        if (! fLoad) SO_TOLERANT; else SO_INTOLERANT;
        MODE_ANY;

        PRECONDITION(CheckPointer(m_pModule));
        PRECONDITION(id != TYPE__NIL);
        PRECONDITION(id <= m_cTypeHandles);
    }
    CONTRACTL_END;
    
    const TypeDescription *d = m_typeDescriptions + (id - 1);

    TypeHandle th = m_pTypeHandles[id-1];

    if (!th.IsNull())
        return th;

    if (!fLoad)
    {

        MethodTable *mt = LookupClass(d->classID, FALSE);

        if (mt == NULL)
            return TypeHandle();

        {
            ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();
            th = ClassLoader::LoadArrayTypeThrowing(TypeHandle(mt), d->type, d->rank, ClassLoader::LoadTypes);
        }

    }
    else 
    {
        th = ClassLoader::LoadArrayTypeThrowing(TypeHandle(GetClass(d->classID)), d->type, d->rank);
    }
    if (th.IsNull())
        return TypeHandle();

#ifndef DACCESS_COMPILE
    m_pTypeHandles[id-1] = th;
#endif

    return th;

}

BOOL Binder::IsException(MethodTable *pMT, RuntimeExceptionKind kind)
{
    WRAPPER_CONTRACT;
    return IsClass(pMT, (BinderClassID) (kind + CLASS__MSCORLIB_COUNT));
}

MethodTable *Binder::GetException(RuntimeExceptionKind kind)
{
    WRAPPER_CONTRACT;
    
    return GetClass((BinderClassID) (kind + CLASS__MSCORLIB_COUNT));
}

MethodTable *Binder::FetchException(RuntimeExceptionKind kind)
{
    WRAPPER_CONTRACT;
    return FetchClass((BinderClassID) (kind + CLASS__MSCORLIB_COUNT));
}

LPCUTF8 Binder::GetExceptionName(RuntimeExceptionKind kind)
{ 
    WRAPPER_CONTRACT;
    return GetClassName((BinderClassID) (kind + CLASS__MSCORLIB_COUNT));
}


BOOL Binder::IsElementType(MethodTable *pMT, CorElementType type)
{
    WRAPPER_CONTRACT;
    BinderClassID id = (BinderClassID) (type + CLASS__MSCORLIB_COUNT + kLastException);

    _ASSERTE(GetClassName(id) != NULL);

    return IsClass(pMT, id);
}

MethodTable *Binder::GetElementType(CorElementType type)
{
    WRAPPER_CONTRACT;
    
    BinderClassID id = (BinderClassID) (type + CLASS__MSCORLIB_COUNT + kLastException);

    _ASSERTE(GetClassName(id) != NULL);

    return GetClass(id);
}

MethodTable *Binder::FetchElementType(CorElementType type, BOOL fLoad/* = TRUE*/, ClassLoadLevel level/* = CLASS_LOADED*/)
{
    CONTRACTL
    {
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED() || !fLoad) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        MODE_ANY;
    }
    CONTRACTL_END;
    
    BinderClassID id = (BinderClassID) (type + CLASS__MSCORLIB_COUNT + kLastException);

    _ASSERTE(GetClassName(id) != NULL);

    return FetchClass(id, fLoad, level);
}

MethodTable *Binder::LookupElementType(CorElementType type, ClassLoadLevel level /* = CLASS_LOADED */)
{
    WRAPPER_CONTRACT;

    BinderClassID id = (BinderClassID) (type + CLASS__MSCORLIB_COUNT + kLastException);

    return LookupClass(id, FALSE, level);
}


LPCUTF8 Binder::GetElementTypeName(CorElementType type)
{ 
    WRAPPER_CONTRACT;

    return GetClassName((BinderClassID) (type + CLASS__MSCORLIB_COUNT + kLastException));
}

///////////////////////////////////////////////////////////////////////////////
// Mscorlib:
///////////////////////////////////////////////////////////////////////////////

// For the dac compile we only need the array size

#define CountOfMscorlibClassDescriptions                                        \
    ((CLASS__MSCORLIB_COUNT - 1) + kLastException + ELEMENT_TYPE_MAX)

#define CountOfMscorlibMethodDescriptions   (METHOD__MSCORLIB_COUNT - 1)
#define CountOfMscorlibFieldDescriptions    (FIELD__MSCORLIB_COUNT - 1)
#define CountOfMscorlibTypeDescriptions     (TYPE__MSCORLIB_COUNT - 1)

#ifndef DACCESS_COMPILE

#include "nativeoverlapped.h"

const Binder::ClassDescription Binder::MscorlibClassDescriptions[] =
{
#define DEFINE_CLASS(i,n,s)        { PTR_CSTR((TADDR) g_ ## n ## NS ),  PTR_CSTR((TADDR) # s ) },
#include "mscorlib.h"

    // Include all exception types here
#define EXCEPTION_BEGIN_DEFINE(ns, reKind, bHRformessage, hr) { PTR_CSTR((TADDR)ns) , PTR_CSTR((TADDR) # reKind ) },
#define EXCEPTION_ADD_HR(hr)
#define EXCEPTION_END_DEFINE()
#include "rexcep.h"
#undef EXCEPTION_BEGIN_DEFINE
#undef EXCEPTION_ADD_HR
#undef EXCEPTION_END_DEFINE

    // Now include all signature types

#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im)   { PTR_CSTR((TADDR)ns) , PTR_CSTR((TADDR)c) },
#include "cortypeinfo.h"
#undef TYPEINFO
};

#define gsig_NoSig (*(char*)NULL)

const Binder::MethodDescription Binder::MscorlibMethodDescriptions[] =
{
#define DEFINE_METHOD(c,i,s,g)          { CLASS__ ## c , PTR_CUTF8((TADDR) # s ), PTR_HARDCODEDMETASIG((TADDR) & gsig_ ## g ) },
#include "mscorlib.h"
} ;


const Binder::FieldDescription Binder::MscorlibFieldDescriptions[] =
{
#define DEFINE_FIELD(c,i,s)           { CLASS__ ## c , PTR_CUTF8((TADDR) # s ) },
#ifdef _DEBUG
#define DEFINE_FIELD_U(c,i,s,uc,uf)   { CLASS__ ## c , PTR_CUTF8((TADDR) # s ) },
#endif // _DEBUG
#include "mscorlib.h"
};

const Binder::TypeDescription Binder::MscorlibTypeDescriptions[] = 
{
    { CLASS__BYTE,          ELEMENT_TYPE_SZARRAY,       1 },
    { CLASS__OBJECT,        ELEMENT_TYPE_SZARRAY,       1 },
    { CLASS__VARIANT,       ELEMENT_TYPE_SZARRAY,       1 },
    { CLASS__VOID,          ELEMENT_TYPE_PTR,           0 },
};

#endif // DACCESS_COMPILE

#ifndef DACCESS_COMPILE
#ifdef _DEBUG

const Binder::FieldOffsetCheck Binder::MscorlibFieldOffsets[] =
{
#define DEFINE_FIELD_U(c,i,s,uc,uf)  { FIELD__ ## c ## __ ## i, offsetof(uc, uf), sizeof(((uc*)1)->uf) },
#include "mscorlib.h"
    { (BinderFieldID) 0 }
};

const Binder::ClassSizeCheck Binder::MscorlibClassSizes[] =
{
#define DEFINE_CLASS_U(i,n,s,uc)  { CLASS__ ## i, sizeof(uc) },
#include "mscorlib.h"
    { (BinderClassID) 0 }
};

//
// check the basic consistency between mscorlib and mscorwks
//
void Binder::CheckMscorlib()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(ThrowOutOfMemory());
    }
    CONTRACTL_END;

    const FieldOffsetCheck     *pOffsets = MscorlibFieldOffsets;

    while (pOffsets->fieldID != FIELD__NIL)
    {
        FieldDesc *pFD = g_Mscorlib.FetchField(pOffsets->fieldID);
        DWORD offset = pFD->GetOffset();

        if (!pFD->IsFieldOfValueType())
        {
            offset += Object::GetOffsetOfFirstField();
        }

        CONSISTENCY_CHECK_MSGF(offset == pOffsets->expectedOffset, 
            ("Managed class field offset does not match unmanaged class field offset\n"
             "man: 0x%x, unman: 0x%x, Name: %s\n", offset, pOffsets->expectedOffset, pFD->GetName()));

        DWORD size = pFD->LoadSize();

        CONSISTENCY_CHECK_MSGF(size == pOffsets->expectedSize, 
            ("Managed class field size does not match unmanaged class field size\n"
             "man: 0x%x, unman: 0x%x, Name: %s\n", size, pOffsets->expectedSize, pFD->GetName()));

        pOffsets++;
    }

    const ClassSizeCheck     *pSizes = MscorlibClassSizes;

    while (pSizes->classID != CLASS__NIL)
    {
        MethodTable *pMT = g_Mscorlib.FetchClass(pSizes->classID);

        // hidden size of the type that participates in the allignment calculation
        DWORD hiddenSize = pMT->IsValueType() ? sizeof(MethodTable*) : 0;

        DWORD size = pMT->GetBaseSize() - (sizeof(ObjHeader)+hiddenSize);

        DWORD expectedsize = (DWORD)ALIGN_UP(pSizes->expectedSize + (sizeof(ObjHeader) + hiddenSize),
            DATA_ALIGNMENT) - (sizeof(ObjHeader) + hiddenSize);

        CONSISTENCY_CHECK_MSGF(size == expectedsize,
            ("Managed object size does not match unmanaged object size\n"
            "man: 0x%x, unman: 0x%x, Name: %s\n", size, expectedsize, pMT->GetDebugClassName()));
        pSizes++;
    }
}

//
// check consistency of the unmanaged and managed fcall signatures
//
/* static */ FCSigCheck* FCSigCheck::g_pFCSigCheck;

static void FCallCheckSignature(MethodDesc* pMD, LPVOID pImpl, BOOL* pfDuplicateImplementations)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    char* pUnmanagedSig = NULL;

    FCSigCheck* pSigCheck = FCSigCheck::g_pFCSigCheck;
    while (pSigCheck != NULL)
    {
        if (pImpl == pSigCheck->func) {
            if (pUnmanagedSig != NULL)
            {
                // There are multiple fcalls with identical entrypoints. Skip signature check now
                // to give a better assert later.
                *pfDuplicateImplementations = TRUE;
                return;
            }
            pUnmanagedSig = pSigCheck->signature;
        }
        pSigCheck = pSigCheck->next;
    }

    MetaSig msig(pMD);   
    int argIndex = -2; // start with return value
    char* pUnmanagedArg = pUnmanagedSig;
    for (;;)
    {
        CorElementType argType = ELEMENT_TYPE_END;
        TypeHandle argTypeHandle;

        if (argIndex == -2)
        {
            // return value
            argType = msig.GetReturnType();
            if (argType == ELEMENT_TYPE_VALUETYPE)
                argTypeHandle = msig.GetRetTypeHandleThrowing();
        }

        if (argIndex == -1)
        {
            // this ptr
            if (msig.HasThis())
                argType = ELEMENT_TYPE_CLASS;
            else
                argIndex++; // move on to the first argument
        }

        if (argIndex >= 0)
        {
            argType = msig.NextArg();
            if (argType == ELEMENT_TYPE_END)
                break;
            if (argType == ELEMENT_TYPE_VALUETYPE)
                argTypeHandle = msig.GetLastTypeHandleThrowing();
        }

        const char* expectedType = NULL;

        switch (argType)
        {
        case ELEMENT_TYPE_VOID:
            expectedType = pMD->IsCtor() ? NULL : "void";
            break;
        case ELEMENT_TYPE_BOOLEAN:
            expectedType = (argIndex == -2) ? "FC_BOOL_RET" : "CLR_BOOL";
            break;
        case ELEMENT_TYPE_CHAR:
            expectedType = (argIndex == -2) ? "FC_CHAR_RET" : "CLR_CHAR";
            break;
        case ELEMENT_TYPE_I1:
            expectedType = (argIndex == -2) ? "FC_INT8_RET" : "INT8";
            break;
        case ELEMENT_TYPE_U1:
            expectedType = (argIndex == -2) ? "FC_UINT8_RET" : "UINT8";
            break;
        case ELEMENT_TYPE_I2:
            expectedType = (argIndex == -2) ? "FC_INT16_RET" : "INT16";
            break;
        case ELEMENT_TYPE_U2:
            expectedType = (argIndex == -2) ? "FC_UINT16_RET" : "UINT16";
            break;
        // case ELEMENT_TYPE_I4:
        //     expectedType = "INT32";
        //     break;
        // case ELEMENT_TYPE_U4:
        //     expectedType = "UINT32";
        //     break;
        case ELEMENT_TYPE_I8:
            expectedType = (argIndex == -2) ? "INT64" : "VINT64";
            break;
        case ELEMENT_TYPE_U8:
            expectedType = (argIndex == -2) ? "UINT64" : "VUINT64";
            break;
        case ELEMENT_TYPE_R4:
            expectedType = (argIndex == -2) ? "float" : "Vfloat";
            break;
        case ELEMENT_TYPE_R8:
            expectedType = (argIndex == -2) ? "double" : "Vdouble";
            break;
        case ELEMENT_TYPE_VALUETYPE:
            {
                _ASSERTE(!argTypeHandle.IsNull());
                
                StackSString ssArgTypeName;
                argTypeHandle.GetName(ssArgTypeName);

                // These types are special cased as ELEMENT_TYPE_I in class.cpp
                if ((ssArgTypeName.Equals(SL(L"System.RuntimeTypeHandle"))) ||
                    (ssArgTypeName.Equals(SL(L"System.RuntimeArgumentHandle"))) ||
                    (ssArgTypeName.Equals(SL(L"System.RuntimeMethodHandle"))) ||
                    (ssArgTypeName.Equals(SL(L"System.RuntimeFieldHandle"))))
                    break;

                // If the verifier type for a small valuetype is not a valuetype, it means that on
                // all !VALUETYPES_BY_REFERENCE platforms this argument gets passed directly
                // but on this platform it is always BYREF, so there's likely to be a mismatch.
                CONSISTENCY_CHECK_MSGF(
                        (argTypeHandle.GetSize() >= sizeof(ARG_SLOT))
                        || (argTypeHandle.GetVerifierCorElementType() != ELEMENT_TYPE_VALUETYPE),
                    ("The fcall signature contains small value type that is likely to be source of portability problems\n"
                    "Method: %s:%s. Argument: %d\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName, argIndex));
            }
            break;

        default:
            // no checks for other types
            break;
        }

        if (pUnmanagedSig != NULL)
        {
            CONSISTENCY_CHECK_MSGF(pUnmanagedArg != NULL,
                ("Unexpected end of managed fcall signature\n"
                "Method: %s:%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));

            char* pUnmanagedArgEnd = strchr(pUnmanagedArg, ',');

            char* pUnmanagedTypeEnd = (pUnmanagedArgEnd != NULL) ? 
                pUnmanagedArgEnd : (pUnmanagedArg + strlen(pUnmanagedArg));

            if (argIndex != -2)
            {
                // skip argument name
                while(pUnmanagedTypeEnd > pUnmanagedArg) 
                {
                    char c = *(pUnmanagedTypeEnd-1);
                    if ((c != '_') 
                        && ((c < '0') || ('9' < c)) 
                        && ((c < 'a') || ('z' < c)) 
                        && ((c < 'A') || ('Z' < c)))
                        break;
                    pUnmanagedTypeEnd--;
                }
            }

            // skip whitespaces
            while(pUnmanagedTypeEnd > pUnmanagedArg) 
            {
                char c = *(pUnmanagedTypeEnd-1);
                if ((c != 0x20) && (c != '\t') && (c != '\n') && (c != '\r'))
                    break;
                pUnmanagedTypeEnd--;
            }

            if (expectedType != NULL)
            {
                size_t len = pUnmanagedTypeEnd - pUnmanagedArg;
                CONSISTENCY_CHECK_MSGF(strlen(expectedType) == len && SString::_strnicmp(expectedType, pUnmanagedArg, (COUNT_T)len) == 0,
                    ("The managed and unmanaged fcall signatures do not match\n"
                    "Method: %s:%s. Argument: %d Expecting: %s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName, argIndex, expectedType));
            }
            pUnmanagedArg = (pUnmanagedArgEnd != NULL) ? (pUnmanagedArgEnd+1) : NULL;
        }

        argIndex++;
    }

    if (pUnmanagedSig != NULL)
    {
        if (msig.IsVarArg())
        {
            CONSISTENCY_CHECK_MSGF((pUnmanagedArg != NULL) && strcmp(pUnmanagedArg, "...") == 0, 
                ("Expecting varargs in unmanaged fcall signature\n"
                "Method: %s:%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
        }
        else
        {
            CONSISTENCY_CHECK_MSGF(pUnmanagedArg == NULL,
                ("Unexpected end of unmanaged fcall signature\n"
                "Method: %s:%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
        }
    }
}

struct FCImplEntry
{
    LPVOID        m_pImplementation;
    MethodDesc *  m_pMD;
};

static int __cdecl fcImplEntryCmp(const void* a_, const void* b_)
{
    LEAF_CONTRACT;

    FCImplEntry *a = (FCImplEntry *)a_;
    FCImplEntry *b = (FCImplEntry *)b_;
    return(int)((size_t)a->m_pImplementation - (size_t)b->m_pImplementation);
}

//
// extended check of consistency between mscorlib and mscorwks:
//  - verifies that all references from mscorlib to mscorwks are present
//  - verifies that all references from mscorwks to mscorlib are present
//  - limited detection of mismatches between managed and unmanaged fcall signatures
//
void Binder::CheckMscorlibExtended()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(ThrowOutOfMemory());
    }
    CONTRACTL_END;

    // check the consistency of BCL and VM
    // note: it is not enabled by default because of it is time consuming and 
    // changes the bootstrap sequence of the EE
    if (!g_pConfig->GetConfigDWORD(L"ConsistencyCheck", 0))
        return;

    //
    // VM referencing BCL (mscorlib.h)
    //
    for (BinderClassID cID = (BinderClassID) 1; cID <= g_Mscorlib.m_cClassRIDs; cID = (BinderClassID) (cID + 1)) {
        if (g_Mscorlib.GetClassName(cID) != NULL) // Allow for CorSigElement entries with no classes
            g_Mscorlib.FetchClass(cID);
    }

    for (BinderMethodID mID = (BinderMethodID) 1; mID <= g_Mscorlib.m_cMethodMDs; mID = (BinderMethodID) (mID + 1))
        g_Mscorlib.FetchMethod(mID);

    for (BinderFieldID fID = (BinderFieldID) 1; fID <= g_Mscorlib.m_cFieldRIDs; fID = (BinderFieldID) (fID + 1))
        g_Mscorlib.FetchField(fID);

    //
    // BCL referencing VM (ecall.cpp)
    //
    HRESULT hr = S_OK;
    Module *pModule = g_Mscorlib.m_pModule;
    IMDInternalImport *pInternalImport = pModule->GetMDImport();

    HENUMInternal hEnum;
    LPVOID pImplementation = NULL;    
    const DWORD dwMaxNumEntries = 2000;
    DWORD dwNumEntries = 0; 
    NewArrayHolder<FCImplEntry> pSortedEntries(NULL); 
    BOOL fDuplicateImplementations = FALSE;
    
    // for all methods...
    IfFailGo(pInternalImport->EnumAllInit(mdtMethodDef, &hEnum));

    // Allocate a temporary array to store the static FCall entry points.
    pSortedEntries = new FCImplEntry[dwMaxNumEntries];

    for (;;) {
        mdTypeDef td;
        mdTypeDef tdClass;
        DWORD dwImplFlags;

        if (!pInternalImport->EnumNext(&hEnum, &td))
            break;

        pInternalImport->GetMethodImplProps(td, NULL, &dwImplFlags);

        // ... that are internal calls ...
        if (!IsMiInternalCall(dwImplFlags))
            continue;

        IfFailGo(pInternalImport->GetParentToken(td, &tdClass));

        TypeHandle type;

        HRESULT hr = ClassLoader::LoadTypeDefOrRefNoThrow(pModule, tdClass, &type, NULL, 
                                                          ClassLoader::ThrowIfNotFound, 
                                                          ClassLoader::FailIfUninstDefOrRef);
        if (FAILED(hr) || type.IsNull()) {
            LPCUTF8 pszClassName;
            LPCUTF8 pszNameSpace;
            pInternalImport->GetNameOfTypeDef(tdClass, &pszClassName, &pszNameSpace);
            CONSISTENCY_CHECK_MSGF(false, ("Unable to load class from mscorlib: %s.%s\n", pszNameSpace, pszClassName));
        }      

        MethodDesc *pMD = type.AsMethodTable()->GetClass()->FindMethod(td);
        _ASSERTE(pMD);

        // Get the implementation entrypoint and store it in the array
        pImplementation = ECall::GetStaticFCallImpl(pMD);
        if (pImplementation) {
            if (dwNumEntries >= dwMaxNumEntries) {
                _ASSERTE(!"dwMaxNumEntries too small");
                ThrowHR(E_FAIL);
            }
            pSortedEntries[dwNumEntries].m_pImplementation = pImplementation;
            pSortedEntries[dwNumEntries].m_pMD = pMD;
            ++dwNumEntries;
        }
        
        DWORD id = ECall::GetIDForMethod(pMD);

        // ... check that the method is in the fcall table.
        if (id == 0) {
            LPCUTF8 pszClassName;
            LPCUTF8 pszNameSpace;
            pInternalImport->GetNameOfTypeDef(tdClass, &pszClassName, &pszNameSpace);
            LPCUTF8 pszName = pInternalImport->GetNameOfMethodDef(td);
            CONSISTENCY_CHECK_MSGF(false, ("Unable to find internalcall implementation: %s.%s::%s\n", pszNameSpace, pszClassName, pszName));
        }
        else {
            FCallCheckSignature(pMD, ECall::GetFCallImpl(pMD), &fDuplicateImplementations);
        }
    }

    pInternalImport->EnumClose(&hEnum);

    //
    // Sort the static FCall entrypoints, and check for duplication.
    //
    _ASSERTE(dwNumEntries>=2);    // We should at least find 2 static FCall entries.
    qsort (pSortedEntries,                // start of array
           dwNumEntries,                  // array size in elements
           sizeof(FCImplEntry),           // element size in bytes
           fcImplEntryCmp);               // comparere function
      
    for (DWORD i=1; i<dwNumEntries; i++)
    {
        if (pSortedEntries[i].m_pImplementation == pSortedEntries[i-1].m_pImplementation)
        {
            // The fcall entrypoints has to be at unique addresses. If you get failure here, use the following steps
            // to fix it:
            // 1. Consider merging the offending fcalls into one fcall. Do they really do different things?
            // 2. If it does not make sense to merge the offending fcalls into one,
            // add FCUnique(<a random unique number here>); to one of the offending fcalls.
  
            // Attach debugger to see the names of the offending methods in debug output.
            _ASSERTE(!"Duplicate pImplementation entries found in reverse fcall table");

            MethodDesc* pMD1 = pSortedEntries[i-1].m_pMD;
            LPCUTF8 pszMethodName1 = pMD1->GetName();
            LPCUTF8 pszNamespace1 = 0;
            LPCUTF8 pszName1 = pMD1->GetClass()->GetFullyQualifiedNameInfo(&pszNamespace1);
  
            MethodDesc* pMD2 = pSortedEntries[i].m_pMD;
            LPCUTF8 pszMethodName2 = pMD2->GetName();
            LPCUTF8 pszNamespace2 = 0;
            LPCUTF8 pszName2 = pMD2->GetClass()->GetFullyQualifiedNameInfo(&pszNamespace2);
  
            CONSISTENCY_CHECK_MSGF(false, ("Duplicate implementation found: %s.%s::%s and %s.%s::%s\n", 
                pszNamespace1, pszName1, pszMethodName1, pszNamespace2, pszName2, pszMethodName2));

            fDuplicateImplementations = TRUE;
        }
    }

    // Make sure that nothing slipped through the cracks from FCallCheckSignature
    if (fDuplicateImplementations)
    {
        _ASSERTE(!"Duplicate FCALL implementations");
        ThrowHR(E_FAIL);
    }

    // Verify that there are no unused entries in the ecall table
    if (!ECall::CheckUnusedFCalls())
    {
        ThrowHR(E_FAIL);
    }

    //
    // Stub constants
    //
#define ASMCONSTANTS_C_ASSERT(cond)
#define ASMCONSTANTS_RUNTIME_ASSERT(cond) _ASSERTE(cond)
#include "asmconstants.h"



ErrExit:
    _ASSERTE(SUCCEEDED(hr));
}

#endif // _DEBUG

#endif // #ifndef DACCESS_COMPILE

GVAL_IMPL(Binder, g_Mscorlib);

#ifndef DACCESS_COMPILE

void Binder::StartupMscorlib(Module *pModule)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    C_ASSERT(CLASS__MSCORLIB_COUNT < USHRT_MAX);
    C_ASSERT(METHOD__MSCORLIB_COUNT < USHRT_MAX);
    C_ASSERT(FIELD__MSCORLIB_COUNT < USHRT_MAX);
    C_ASSERT(TYPE__MSCORLIB_COUNT < USHRT_MAX);

    C_ASSERT(CountOfMscorlibClassDescriptions == NumItems(MscorlibClassDescriptions));
    C_ASSERT(CountOfMscorlibMethodDescriptions == NumItems(MscorlibMethodDescriptions));
    C_ASSERT(CountOfMscorlibFieldDescriptions == NumItems(MscorlibFieldDescriptions));
    C_ASSERT(CountOfMscorlibTypeDescriptions == NumItems(MscorlibTypeDescriptions));

    {
        g_Mscorlib.Init(pModule,
                        MscorlibClassDescriptions,
                        NumItems(MscorlibClassDescriptions),
                        MscorlibMethodDescriptions,
                        NumItems(MscorlibMethodDescriptions),
                        MscorlibFieldDescriptions,
                        NumItems(MscorlibFieldDescriptions),
                        MscorlibTypeDescriptions,
                        NumItems(MscorlibTypeDescriptions));
    }
}

#endif // #ifndef DACCESS_COMPILE

#ifdef DACCESS_COMPILE

void
Binder::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    DAC_ENUM_DTHIS();

    DacEnumMemoryRegion(PTR_TO_TADDR(m_classDescriptions),
                        CountOfMscorlibClassDescriptions * sizeof(ClassDescription));
    DacEnumMemoryRegion(PTR_TO_TADDR(m_methodDescriptions),
                        CountOfMscorlibMethodDescriptions * sizeof(MethodDescription));
    DacEnumMemoryRegion(PTR_TO_TADDR(m_fieldDescriptions),
                        CountOfMscorlibFieldDescriptions * sizeof(FieldDescription));
    DacEnumMemoryRegion(PTR_TO_TADDR(m_typeDescriptions),
                        CountOfMscorlibTypeDescriptions * sizeof(TypeDescription));

    if (m_pModule.IsValid())
    {
        m_pModule->EnumMemoryRegions(flags, true);
    }

    DacEnumMemoryRegion(PTR_TO_TADDR(m_pClassRIDs),
                        m_cClassRIDs * sizeof(USHORT));
    DacEnumMemoryRegion(PTR_TO_TADDR(m_pFieldRIDs),
                        m_cFieldRIDs * sizeof(USHORT));
    DacEnumMemoryRegion(PTR_TO_TADDR(m_pMethodMDs),
                        m_cMethodMDs * sizeof(PTR_MethodDesc));
    DacEnumMemoryRegion(PTR_TO_TADDR(m_pTypeHandles),
                        m_cTypeHandles * sizeof(TypeHandle));
}

#endif // #ifdef DACCESS_COMPILE

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