Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TypeLoaderEnvironment.Metadata.cs « TypeLoader « Runtime « Internal « src « System.Private.TypeLoader « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 67a0d3da6904bb7705aa9377275d7e26613183db (plain)
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
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.


using System;
using System.Runtime;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

using System.Reflection.Runtime.General;

using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;

using Internal.Metadata.NativeFormat;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.TypeSystem.NativeFormat;
#if ECMA_METADATA_SUPPORT
using Internal.TypeSystem.Ecma;
#endif

namespace Internal.Runtime.TypeLoader
{
    /// <summary>
    /// This structure represents metadata-based information used to construct method invokers.
    /// TypeLoaderEnvironment.TryGetMethodInvokeMetadata fills in this structure based on metadata lookup across
    /// all currently registered binary modules.
    /// </summary>
    public struct MethodInvokeMetadata
    {
        /// <summary>
        /// module containing the relevant metadata, null when not found
        /// </summary>
        public NativeFormatModuleInfo MappingTableModule;

        /// <summary>
        /// Method entrypoint
        /// </summary>
        public IntPtr MethodEntryPoint;

        /// <summary>
        /// Raw method entrypoint
        /// </summary>
        public IntPtr RawMethodEntryPoint;

        /// <summary>
        /// Method dictionary for components
        /// </summary>
        public IntPtr DictionaryComponent;

        /// <summary>
        /// Dynamic invoke cookie
        /// </summary>
        public uint DynamicInvokeCookie;

        /// <summary>
        /// Invoke flags
        /// </summary>
        public InvokeTableFlags InvokeTableFlags;
    }

    public sealed partial class TypeLoaderEnvironment
    {
        /// <summary>
        /// Cross-module RVA has the high bit set which denotes that an additional indirection
        /// through the indirection cell is required to reach the final destination address.
        /// </summary>
        private const uint RVAIsIndirect = 0x80000000u;

        /// <summary>
        /// Convert RVA to runtime type handle with indirection handling.
        /// </summary>
        /// <param name="moduleHandle">Module containing the pointer</param>
        /// <param name="rva">Relative virtual address, high bit denotes additional indirection</param>
        public static unsafe RuntimeTypeHandle RvaToRuntimeTypeHandle(TypeManagerHandle moduleHandle, uint rva)
        {
            if ((rva & RVAIsIndirect) != 0)
            {
                return RuntimeAugments.CreateRuntimeTypeHandle(*(IntPtr*)(moduleHandle.ConvertRVAToPointer(rva & ~RVAIsIndirect)));
            }
            return RuntimeAugments.CreateRuntimeTypeHandle((IntPtr)(moduleHandle.ConvertRVAToPointer(+ rva)));
        }

        /// <summary>
        /// Convert RVA in a given module to function pointer. This may involve an additional indirection
        /// through the indirection cell if the RVA has the DynamicInvokeMapEntry.IsImportMethodFlag set
        /// (when the actual function in question resides in a different binary module).
        /// </summary>
        /// <param name="moduleHandle">Module handle (= load address) containing the function or indirection cell</param>
        /// <param name="rva">
        /// Relative virtual address, the DynamicInvokeMapEntry.IsImportMethodFlag bit denotes additional indirection
        /// </param>
        public static unsafe IntPtr RvaToFunctionPointer(TypeManagerHandle moduleHandle, uint rva)
        {
            if ((rva & DynamicInvokeMapEntry.IsImportMethodFlag) == DynamicInvokeMapEntry.IsImportMethodFlag)
            {
                return *((IntPtr*)((byte*)moduleHandle.ConvertRVAToPointer(rva & DynamicInvokeMapEntry.InstantiationDetailIndexMask)));
            }
            else
            {
                return (IntPtr)((byte*)moduleHandle.ConvertRVAToPointer(rva));
            }
        }

        /// <summary>
        /// Compare two arrays sequentially.
        /// </summary>
        /// <param name="seq1">First array to compare</param>
        /// <param name="seq2">Second array to compare</param>
        /// <returns>
        /// true = arrays have the same values and Equals holds for all pairs of elements
        /// with the same indices
        /// </returns>
        private static bool SequenceEqual<T>(T[] seq1, T[] seq2)
        {
            if (seq1.Length != seq2.Length)
                return false;
            for (int i = 0; i < seq1.Length; i++)
                if (!seq1[i].Equals(seq2[i]))
                    return false;
            return true;
        }

        /// <summary>
        /// Locate blob with given ID and create native reader on it.
        /// </summary>
        /// <param name="module">Address of module to search for the blob</param>
        /// <param name="blob">Blob ID within blob map for the module</param>
        /// <returns>Native reader for the blob (asserts and returns an empty native reader when not found)</returns>
        internal static unsafe NativeReader GetNativeReaderForBlob(NativeFormatModuleInfo module, ReflectionMapBlob blob)
        {
            NativeReader reader;
            if (TryGetNativeReaderForBlob(module, blob, out reader))
            {
                return reader;
            }

            Debug.Assert(false);
            return default(NativeReader);
        }

        /// <summary>
        /// Return the metadata handle for a TypeRef if this type was referenced indirectly by other type that pay-for-play has denoted as browsable
        /// (for example, as part of a method signature.)
        ///
        /// This is only used in "debug" builds to provide better MissingMetadataException diagnostics. 
        ///
        /// Preconditions:
        ///    runtimeTypeHandle is a typedef (not a constructed type such as an array or generic instance.)
        /// </summary>
        /// <param name="runtimeTypeHandle">EEType of the type in question</param>
        /// <param name="metadataReader">Metadata reader for the type</param>
        /// <param name="typeRefHandle">Located TypeRef handle</param>
        public static unsafe bool TryGetTypeReferenceForNamedType(RuntimeTypeHandle runtimeTypeHandle, out MetadataReader metadataReader, out TypeReferenceHandle typeRefHandle)
        {
            int hashCode = runtimeTypeHandle.GetHashCode();

            // Iterate over all modules, starting with the module that defines the EEType
            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(runtimeTypeHandle)))
            {
                NativeReader typeMapReader;
                if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.TypeMap, out typeMapReader))
                {
                    NativeParser typeMapParser = new NativeParser(typeMapReader, 0);
                    NativeHashtable typeHashtable = new NativeHashtable(typeMapParser);

                    ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                    externalReferences.InitializeCommonFixupsTable(module);

                    var lookup = typeHashtable.Lookup(hashCode);
                    NativeParser entryParser;
                    while (!(entryParser = lookup.GetNext()).IsNull)
                    {
                        RuntimeTypeHandle foundType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                        if (foundType.Equals(runtimeTypeHandle))
                        {
                            Handle entryMetadataHandle = entryParser.GetUnsigned().AsHandle();
                            if (entryMetadataHandle.HandleType == HandleType.TypeReference)
                            {
                                metadataReader = module.MetadataReader;
                                typeRefHandle = entryMetadataHandle.ToTypeReferenceHandle(metadataReader);
                                return true;
                            }
                        }
                    }
                }
            }

            metadataReader = null;
            typeRefHandle = default(TypeReferenceHandle);

            return false;
        }

        /// <summary>
        /// Return the RuntimeTypeHandle for the named type referenced by another type that pay-for-play denotes as browsable (for example,
        /// in a member signature.) This will only find the typehandle if it is not defined in the current module, and is primarily used
        /// to find non-browsable types.
        ///
        /// This is used to ensure that we can produce a Type object if requested and that it match up with the analogous
        /// Type obtained via typeof().
        /// 
        ///
        /// Preconditions:
        ///    metadataReader + typeRefHandle  - a valid metadata reader + typeReferenceHandle where "metadataReader" is one
        ///                                      of the metadata readers returned by ExecutionEnvironment.MetadataReaders.
        ///
        /// Note: Although this method has a "bool" return value like the other mapping table accessors, the Project N pay-for-play design 
        /// guarantees that any type that has a metadata TypeReference to it also has a RuntimeTypeHandle underneath.
        /// </summary>
        /// <param name="metadataReader">Metadata reader for module containing the type reference</param>
        /// <param name="typeRefHandle">TypeRef handle to look up</param>
        /// <param name="runtimeTypeHandle">Resolved EEType for the type reference</param>
        public static unsafe bool TryGetNamedTypeForTypeReference(MetadataReader metadataReader, TypeReferenceHandle typeRefHandle, out RuntimeTypeHandle runtimeTypeHandle, bool searchAllModules = false)
        {
            int hashCode = typeRefHandle.ComputeHashCode(metadataReader);
            NativeFormatModuleInfo typeRefModule = ModuleList.Instance.GetModuleInfoForMetadataReader(metadataReader);
            return TryGetNamedTypeForTypeReference_Inner(metadataReader, typeRefModule, typeRefHandle, hashCode, typeRefModule, out runtimeTypeHandle);
        }

        /// <summary>
        /// Return the RuntimeTypeHandle for the named type referenced by another type that pay-for-play denotes as browsable (for example,
        /// in a member signature.) This lookup will attempt to resolve to an EEType in any module to cover situations where the type
        /// does not have a TypeDefinition (non-browsable type) as well as cases where it does.
        ///
        /// Preconditions:
        ///    metadataReader + typeRefHandle  - a valid metadata reader + typeReferenceHandle where "metadataReader" is one
        ///                                      of the metadata readers returned by ExecutionEnvironment.MetadataReaders.
        ///
        /// Note: Although this method has a "bool" return value like the other mapping table accessors, the Project N pay-for-play design 
        /// guarantees that any type that has a metadata TypeReference to it also has a RuntimeTypeHandle underneath.
        /// </summary>
        /// <param name="metadataReader">Metadata reader for module containing the type reference</param>
        /// <param name="typeRefHandle">TypeRef handle to look up</param>
        /// <param name="runtimeTypeHandle">Resolved EEType for the type reference</param>
        public static unsafe bool TryResolveNamedTypeForTypeReference(MetadataReader metadataReader, TypeReferenceHandle typeRefHandle, out RuntimeTypeHandle runtimeTypeHandle)
        {
            int hashCode = typeRefHandle.ComputeHashCode(metadataReader);
            NativeFormatModuleInfo typeRefModule = ModuleList.Instance.GetModuleInfoForMetadataReader(metadataReader);
            runtimeTypeHandle = default(RuntimeTypeHandle);

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(typeRefModule.Handle))
            {
                if (TryGetNamedTypeForTypeReference_Inner(metadataReader, typeRefModule, typeRefHandle, hashCode, module, out runtimeTypeHandle))
                    return true;
            }

            return false;
        }

        private static unsafe bool TryGetNamedTypeForTypeReference_Inner(MetadataReader metadataReader,
            NativeFormatModuleInfo typeRefModule,
            TypeReferenceHandle typeRefHandle,
            int hashCode,
            NativeFormatModuleInfo module,
            out RuntimeTypeHandle runtimeTypeHandle)
        {
            Debug.Assert(typeRefModule == ModuleList.Instance.GetModuleInfoForMetadataReader(metadataReader));

            NativeReader typeMapReader;
            if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.TypeMap, out typeMapReader))
            {
                NativeParser typeMapParser = new NativeParser(typeMapReader, 0);
                NativeHashtable typeHashtable = new NativeHashtable(typeMapParser);

                ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                externalReferences.InitializeCommonFixupsTable(module);

                var lookup = typeHashtable.Lookup(hashCode);
                NativeParser entryParser;
                while (!(entryParser = lookup.GetNext()).IsNull)
                {
                    var foundTypeIndex = entryParser.GetUnsigned();
                    var handle = entryParser.GetUnsigned().AsHandle();

                    if (module == typeRefModule)
                    {
                        if (handle.Equals(typeRefHandle))
                        {
                            runtimeTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(foundTypeIndex);
                            return true;
                        }
                    }
                    else if (handle.HandleType == HandleType.TypeReference)
                    {
                        MetadataReader mrFoundHandle = module.MetadataReader;
                        // We found a type reference handle in another module.. see if it matches
                        if (MetadataReaderHelpers.CompareTypeReferenceAcrossModules(typeRefHandle, metadataReader, handle.ToTypeReferenceHandle(mrFoundHandle), mrFoundHandle))
                        {
                            runtimeTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(foundTypeIndex);
                            return true;
                        }
                    }
                    else if (handle.HandleType == HandleType.TypeDefinition)
                    {
                        // We found a type definition handle in another module. See if it matches
                        MetadataReader mrFoundHandle = module.MetadataReader;
                        // We found a type definition handle in another module.. see if it matches
                        if (MetadataReaderHelpers.CompareTypeReferenceToDefinition(typeRefHandle, metadataReader, handle.ToTypeDefinitionHandle(mrFoundHandle), mrFoundHandle))
                        {
                            runtimeTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(foundTypeIndex);
                            return true;
                        }
                    }
                }
            }

            runtimeTypeHandle = default(RuntimeTypeHandle);
            return false;
        }

        /// <summary>
        /// Given a RuntimeTypeHandle for any non-dynamic type E, return a RuntimeTypeHandle for type E[]
        /// if the pay for play policy denotes E[] as browsable. This is used to implement Array.CreateInstance().
        /// This is not equivalent to calling TryGetMultiDimTypeForElementType() with a rank of 1!
        ///
        /// Preconditions:
        ///     elementTypeHandle is a valid RuntimeTypeHandle.
        /// </summary>
        /// <param name="elementTypeHandle">EEType of the array element type</param>
        /// <param name="arrayTypeHandle">Resolved EEType of the array type</param>
        public static unsafe bool TryGetArrayTypeForNonDynamicElementType(RuntimeTypeHandle elementTypeHandle, out RuntimeTypeHandle arrayTypeHandle)
        {
            arrayTypeHandle = new RuntimeTypeHandle();

            int arrayHashcode = TypeHashingAlgorithms.ComputeArrayTypeHashCode(elementTypeHandle.GetHashCode(), -1);

            // Note: ReflectionMapBlob.ArrayMap may not exist in the module that contains the element type.
            // So we must enumerate all loaded modules in order to find ArrayMap and the array type for
            // the given element.
            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules())
            {
                NativeReader arrayMapReader;
                if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.ArrayMap, out arrayMapReader))
                {
                    NativeParser arrayMapParser = new NativeParser(arrayMapReader, 0);
                    NativeHashtable arrayHashtable = new NativeHashtable(arrayMapParser);

                    ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                    externalReferences.InitializeCommonFixupsTable(module);

                    var lookup = arrayHashtable.Lookup(arrayHashcode);
                    NativeParser entryParser;
                    while (!(entryParser = lookup.GetNext()).IsNull)
                    {
                        RuntimeTypeHandle foundArrayType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                        RuntimeTypeHandle foundArrayElementType = RuntimeAugments.GetRelatedParameterTypeHandle(foundArrayType);
                        if (foundArrayElementType.Equals(elementTypeHandle))
                        {
                            arrayTypeHandle = foundArrayType;
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// The array table only holds some of the precomputed array types, others may be found in the template type.
        /// As our system requires us to find the RuntimeTypeHandle of templates we must not be in a situation where we fail to find
        /// a RuntimeTypeHandle for a type which is actually in the template table. This function fixes that problem for arrays.
        /// </summary>
        /// <param name="arrayType"></param>
        /// <param name="arrayTypeHandle"></param>
        /// <returns></returns>
        public bool TryGetArrayTypeHandleForNonDynamicArrayTypeFromTemplateTable(ArrayType arrayType, out RuntimeTypeHandle arrayTypeHandle)
        {
            arrayTypeHandle = default(RuntimeTypeHandle);

            // Only SzArray types have templates.
            if (!arrayType.IsSzArray)
                return false;

            // If we can't find a RuntimeTypeHandle for the element type, we can't find the array in the template table.
            if (!arrayType.ParameterType.RetrieveRuntimeTypeHandleIfPossible())
                return false;

            unsafe
            {
                // If the elementType is a dynamic type it cannot exist in the template table.
                if (arrayType.ParameterType.RuntimeTypeHandle.ToEETypePtr()->IsDynamicType)
                    return false;
            }

            // Try to find out if the type exists as a template
            var canonForm = arrayType.ConvertToCanonForm(CanonicalFormKind.Specific);
            var hashCode = canonForm.GetHashCode();
            foreach (var module in ModuleList.EnumerateModules())
            {
                ExternalReferencesTable externalFixupsTable;

                NativeHashtable typeTemplatesHashtable = LoadHashtable(module, ReflectionMapBlob.TypeTemplateMap, out externalFixupsTable);

                if (typeTemplatesHashtable.IsNull)
                    continue;

                var enumerator = typeTemplatesHashtable.Lookup(hashCode);

                NativeParser entryParser;
                while (!(entryParser = enumerator.GetNext()).IsNull)
                {
                    RuntimeTypeHandle candidateTemplateTypeHandle = externalFixupsTable.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                    TypeDesc foundType = arrayType.Context.ResolveRuntimeTypeHandle(candidateTemplateTypeHandle);
                    if (foundType == arrayType)
                    {
                        arrayTypeHandle = candidateTemplateTypeHandle;

                        // This lookup in the template table is fairly slow, so if we find the array here, add it to the dynamic array cache, so that
                        // we can find it faster in the future.
                        if (arrayType.IsSzArray)
                            TypeSystemContext.GetArrayTypesCache(false, -1).AddOrGetExisting(arrayTypeHandle);
                        return true;
                    }
                }
            }

            return false;
        }

        // Lazy loadings of hashtables (load on-demand only)
        private unsafe NativeHashtable LoadHashtable(NativeFormatModuleInfo module, ReflectionMapBlob hashtableBlobId, out ExternalReferencesTable externalFixupsTable)
        {
            // Load the common fixups table
            externalFixupsTable = default(ExternalReferencesTable);
            if (!externalFixupsTable.InitializeCommonFixupsTable(module))
                return default(NativeHashtable);

            // Load the hashtable
            byte* pBlob;
            uint cbBlob;
            if (!module.TryFindBlob(hashtableBlobId, out pBlob, out cbBlob))
                return default(NativeHashtable);

            NativeReader reader = new NativeReader(pBlob, cbBlob);
            NativeParser parser = new NativeParser(reader, 0);
            return new NativeHashtable(parser);
        }

        /// <summary>
        /// Locate the static constructor context given the runtime type handle (EEType) for the type in question.
        /// </summary>
        /// <param name="typeHandle">EEType of the type to look up</param>
        public static unsafe IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle typeHandle)
        {
            if (RuntimeAugments.HasCctor(typeHandle))
            {
                if (RuntimeAugments.IsDynamicType(typeHandle))
                {
                    // For dynamic types, its always possible to get the non-gc static data section directly.
                    byte* ptr = (byte*)Instance.TryGetNonGcStaticFieldDataDirect(typeHandle);

                    // what we have now is the base address of the non-gc statics of the type
                    // what we need is the cctor context, which is just before that
                    ptr = ptr - sizeof(System.Runtime.CompilerServices.StaticClassConstructionContext);

                    return (IntPtr)ptr;
                }
                else
                {
                    // Non-dynamic types do not provide a way to directly get at the non-gc static region. 
                    // Use the CctorContextMap instead.

                    var moduleHandle = RuntimeAugments.GetModuleFromTypeHandle(typeHandle);
                    NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(moduleHandle);
                    Debug.Assert(!moduleHandle.IsNull);

                    NativeReader typeMapReader;
                    if (TryGetNativeReaderForBlob(module, ReflectionMapBlob.CCtorContextMap, out typeMapReader))
                    {
                        NativeParser typeMapParser = new NativeParser(typeMapReader, 0);
                        NativeHashtable typeHashtable = new NativeHashtable(typeMapParser);

                        ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                        externalReferences.InitializeCommonFixupsTable(module);

                        var lookup = typeHashtable.Lookup(typeHandle.GetHashCode());
                        NativeParser entryParser;
                        while (!(entryParser = lookup.GetNext()).IsNull)
                        {
                            RuntimeTypeHandle foundType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                            if (foundType.Equals(typeHandle))
                            {
                                byte* pNonGcStaticBase = (byte*)externalReferences.GetIntPtrFromIndex(entryParser.GetUnsigned());

                                // cctor context is located before the non-GC static base
                                return (IntPtr)(pNonGcStaticBase - sizeof(System.Runtime.CompilerServices.StaticClassConstructionContext));
                            }
                        }
                    }
                }

                // If the type has a lazy/deferred Cctor, the compiler must have missed emitting
                // a data structure if we reach this.
                Debug.Assert(false);
            }

            return IntPtr.Zero;
        }

        /// <summary>
        /// Construct the native reader for a given blob in a specified module.
        /// </summary>
        /// <param name="module">Containing binary module for the blob</param>
        /// <param name="blob">Blob ID to fetch from the module</param>
        /// <param name="reader">Native reader created for the module blob</param>
        /// <returns>true when the blob was found in the module, false when not</returns>
        private static unsafe bool TryGetNativeReaderForBlob(NativeFormatModuleInfo module, ReflectionMapBlob blob, out NativeReader reader)
        {
            byte* pBlob;
            uint cbBlob;

            if (module.TryFindBlob(blob, out pBlob, out cbBlob))
            {
                reader = new NativeReader(pBlob, cbBlob);
                return true;
            }

            reader = default(NativeReader);
            return false;
        }

        /// <summary>
        /// Look up the default constructor for a given type. Should not be called by code which has already initialized 
        /// the type system.
        /// </summary>
        /// <param name="type">TypeDesc for the type in question</param>
        /// <returns>Function pointer representing the constructor, IntPtr.Zero when not found</returns>
        internal IntPtr TryGetDefaultConstructorForType(TypeDesc type)
        {
            // Try to find the default constructor in metadata first
            IntPtr result = IntPtr.Zero;

#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
            result = TryGetDefaultConstructorForTypeViaMetadata_Inner(type);
#endif

            DefType defType = type as DefType;
            if ((result == IntPtr.Zero) && (defType != null))
            {
#if GENERICS_FORCE_USG
                // In force USG mode, prefer universal matches over canon specific matches.
                CanonicalFormKind firstCanonFormKind = CanonicalFormKind.Universal;
                CanonicalFormKind secondCanonFormKind = CanonicalFormKind.Specific;
#else
                CanonicalFormKind firstCanonFormKind = CanonicalFormKind.Specific;
                CanonicalFormKind secondCanonFormKind = CanonicalFormKind.Universal;
#endif

                CanonicallyEquivalentEntryLocator canonHelperSpecific = new CanonicallyEquivalentEntryLocator(defType, firstCanonFormKind);

                foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules())
                {
                    result = TryGetDefaultConstructorForType_Inner(module, ref canonHelperSpecific);

                    if (result != IntPtr.Zero)
                        break;
                }

                if (result == IntPtr.Zero)
                {
                    CanonicallyEquivalentEntryLocator canonHelperUniversal = new CanonicallyEquivalentEntryLocator(defType, secondCanonFormKind);

                    foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules())
                    {
                        result = TryGetDefaultConstructorForType_Inner(module, ref canonHelperUniversal);

                        if (result != IntPtr.Zero)
                            break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Look up the default constructor for a given type. Should not be called by code which has already initialized 
        /// the type system.
        /// </summary>
        /// <param name="runtimeTypeHandle">Type handle (EEType) for the type in question</param>
        /// <returns>Function pointer representing the constructor, IntPtr.Zero when not found</returns>
        public IntPtr TryGetDefaultConstructorForType(RuntimeTypeHandle runtimeTypeHandle)
        {
            CanonicallyEquivalentEntryLocator canonHelperSpecific = new CanonicallyEquivalentEntryLocator(runtimeTypeHandle, CanonicalFormKind.Specific);

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(runtimeTypeHandle)))
            {
                IntPtr result = TryGetDefaultConstructorForType_Inner(module, ref canonHelperSpecific);

                if (result != IntPtr.Zero)
                    return result;
            }

            CanonicallyEquivalentEntryLocator canonHelperUniversal = new CanonicallyEquivalentEntryLocator(runtimeTypeHandle, CanonicalFormKind.Universal);

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(runtimeTypeHandle)))
            {
                IntPtr result = TryGetDefaultConstructorForType_Inner(module, ref canonHelperUniversal);

                if (result != IntPtr.Zero)
                    return result;
            }

            // Try to find the default constructor in metadata last (this is costly as it requires spinning up a TypeLoaderContext, and 
            // currently also the _typeLoaderLock) (TODO when the _typeLoaderLock is no longer necessary to correctly use the type system
            // context, remove the use of the lock here.)
            using (LockHolder.Hold(_typeLoaderLock))
            {
                TypeSystemContext context = TypeSystemContextFactory.Create();

                TypeDesc type = context.ResolveRuntimeTypeHandle(runtimeTypeHandle);
                IntPtr result = TryGetDefaultConstructorForTypeViaMetadata_Inner(type);

                TypeSystemContextFactory.Recycle(context);

                if (result != IntPtr.Zero)
                    return result;
            }

            return IntPtr.Zero;
        }

        /// <summary>
        /// Lookup default constructor via the typesystem api surface and such
        /// </summary>
        private IntPtr TryGetDefaultConstructorForTypeViaMetadata_Inner(TypeDesc type)
        {
            IntPtr metadataLookupResult = IntPtr.Zero;

            DefType defType = type as DefType;

            if (defType != null)
            {
                if (!defType.IsValueType && defType is MetadataType)
                {
                    MethodDesc defaultConstructor = ((MetadataType)defType).GetDefaultConstructor();
                    if (defaultConstructor != null)
                    {
                        IntPtr dummyUnboxingStub;
                        TypeLoaderEnvironment.MethodAddressType foundAddressType;
                        TypeLoaderEnvironment.TryGetMethodAddressFromMethodDesc(defaultConstructor, out metadataLookupResult, out dummyUnboxingStub, out foundAddressType);
                    }
                }
            }

            return metadataLookupResult;
        }

        /// <summary>
        /// Attempt to locate the default type constructor in a given module.
        /// </summary>
        /// <param name="module">Module to search for the constructor</param>
        /// <param name="canonHelper">Canonically equivalent entry locator representing the type</param>
        /// <returns>Function pointer representing the constructor, IntPtr.Zero when not found</returns>
        internal unsafe IntPtr TryGetDefaultConstructorForType_Inner(NativeFormatModuleInfo mappingTableModule, ref CanonicallyEquivalentEntryLocator canonHelper)
        {
            NativeReader invokeMapReader;
            if (TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.InvokeMap, out invokeMapReader))
            {
                NativeParser invokeMapParser = new NativeParser(invokeMapReader, 0);
                NativeHashtable invokeHashtable = new NativeHashtable(invokeMapParser);

                ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                externalReferences.InitializeCommonFixupsTable(mappingTableModule);

                var lookup = invokeHashtable.Lookup(canonHelper.LookupHashCode);
                NativeParser entryParser;
                while (!(entryParser = lookup.GetNext()).IsNull)
                {
                    InvokeTableFlags entryFlags = (InvokeTableFlags)entryParser.GetUnsigned();
                    if ((entryFlags & InvokeTableFlags.IsDefaultConstructor) == 0)
                        continue;

                    entryParser.GetUnsigned(); // Skip method handle or the NameAndSig cookie

                    RuntimeTypeHandle entryType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                    if (!canonHelper.IsCanonicallyEquivalent(entryType))
                        continue;

                    return externalReferences.GetFunctionPointerFromIndex(entryParser.GetUnsigned());
                }
            }

            // If not found in the invoke map, try the default constructor map
            NativeReader defaultCtorMapReader;
            if (TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.DefaultConstructorMap, out defaultCtorMapReader))
            {
                NativeParser defaultCtorMapParser = new NativeParser(defaultCtorMapReader, 0);
                NativeHashtable defaultCtorHashtable = new NativeHashtable(defaultCtorMapParser);

                ExternalReferencesTable externalReferencesForDefaultCtorMap = default(ExternalReferencesTable);
                externalReferencesForDefaultCtorMap.InitializeCommonFixupsTable(mappingTableModule);
                var lookup = defaultCtorHashtable.Lookup(canonHelper.LookupHashCode);
                NativeParser defaultCtorParser;
                while (!(defaultCtorParser = lookup.GetNext()).IsNull)
                {
                    RuntimeTypeHandle entryType = externalReferencesForDefaultCtorMap.GetRuntimeTypeHandleFromIndex(defaultCtorParser.GetUnsigned());
                    if (!canonHelper.IsCanonicallyEquivalent(entryType))
                        continue;

                    return externalReferencesForDefaultCtorMap.GetFunctionPointerFromIndex(defaultCtorParser.GetUnsigned());
                }
            }
            return IntPtr.Zero;
        }

        /// <summary>
        /// <summary>
        /// Try to resolve a member reference in all registered binary modules containing metadata.
        /// </summary>
        /// <param name="metadataReader">Metadata reader for the member reference</param>
        /// <param name="memberReferenceHandle">Member reference handle (method, field, property, event) to resolve</param>
        /// <param name="resolvedMetadataReader">Metadata reader for the resolved reference</param>
        /// <param name="resolvedContainingTypeHandle">Resolved runtime handle to the containing type</param>
        /// <param name="resolvedMemberHandle">Resolved handle to the referenced member</param>
        /// <returns>true when the lookup was successful; false when not</return>
        public static bool TryResolveMemberReference(
            MetadataReader metadataReader,
            MemberReferenceHandle memberReferenceHandle,
            out MetadataReader resolvedMetadataReader,
            out RuntimeTypeHandle resolvedContainingTypeHandle,
            out Handle resolvedMemberHandle)
        {
            // TODO
            resolvedMetadataReader = null;
            resolvedContainingTypeHandle = default(RuntimeTypeHandle);
            resolvedMemberHandle = default(Handle);
            return false;
        }

        /// <summary>
        /// Get the information necessary to resolve to metadata given a vtable slot and a type that defines that vtable slot
        /// </summary>
        /// <param name="context">type context to use.</param>
        /// <param name="type">Type that defines the vtable slot. (Derived types are not valid here)</param>
        /// <param name="vtableSlot">vtable slot index</param>
        /// <param name="methodNameAndSig">output name/sig of method</param>
        /// <returns></returns>
        public static unsafe bool TryGetMethodMethodNameAndSigFromVTableSlotForPregeneratedOrTemplateType(TypeSystemContext context, RuntimeTypeHandle type, int vtableSlot, out MethodNameAndSignature methodNameAndSig)
        {
            // 
            // NOTE: The semantics of the vtable slot and method declaring type in the VirtualInvokeMap table have slight differences between ProjectN and CoreRT ABIs.
            // See comment in TryGetVirtualResolveData for more details.
            //

            int logicalSlot = vtableSlot;
            EEType* ptrType = type.ToEETypePtr();
            RuntimeTypeHandle openOrNonGenericTypeDefinition = default(RuntimeTypeHandle);

            // Compute the logical slot by removing space reserved for generic dictionary pointers
            if (ptrType->IsInterface && ptrType->IsGeneric)
            {
                openOrNonGenericTypeDefinition = RuntimeAugments.GetGenericDefinition(type);
                logicalSlot--;
            }
            else
            {
                EEType* searchForSharedGenericTypesInParentHierarchy = ptrType;
                while (searchForSharedGenericTypesInParentHierarchy != null)
                {
                    // See if this type is shared generic. If so, adjust the slot by 1.
                    if (searchForSharedGenericTypesInParentHierarchy->IsGeneric)
                    {
                        RuntimeTypeHandle[] genericTypeArgs;
                        RuntimeTypeHandle genericDefinition = RuntimeAugments.GetGenericInstantiation(searchForSharedGenericTypesInParentHierarchy->ToRuntimeTypeHandle(),
                                                                                                      out genericTypeArgs);

                        if (Instance.ConversionToCanonFormIsAChange(genericTypeArgs, CanonicalFormKind.Specific))
                        {
                            // Shared generic types have a slot dedicated to holding the generic dictionary.
                            logicalSlot--;
                        }
                        if (openOrNonGenericTypeDefinition.IsNull())
                            openOrNonGenericTypeDefinition = genericDefinition;
                    }
                    else if (searchForSharedGenericTypesInParentHierarchy->IsArray)
                    {
                        // Arrays are like shared generics
                        RuntimeTypeHandle arrayElementTypeHandle = searchForSharedGenericTypesInParentHierarchy->RelatedParameterType->ToRuntimeTypeHandle();

                        TypeDesc arrayElementType = context.ResolveRuntimeTypeHandle(arrayElementTypeHandle);
                        TypeDesc canonFormOfArrayElementType = context.ConvertToCanon(arrayElementType, CanonicalFormKind.Specific);

                        if (canonFormOfArrayElementType != arrayElementType)
                        {
                            logicalSlot--;
                        }
                    }

                    // Walk to parent
                    searchForSharedGenericTypesInParentHierarchy = searchForSharedGenericTypesInParentHierarchy->BaseType;
                }
            }

            if (openOrNonGenericTypeDefinition.IsNull())
                openOrNonGenericTypeDefinition = type;

            TypeManagerHandle moduleHandle = RuntimeAugments.GetModuleFromTypeHandle(openOrNonGenericTypeDefinition);
            NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(moduleHandle);

            return TryGetMethodNameAndSigFromVirtualResolveData(module, openOrNonGenericTypeDefinition, logicalSlot, out methodNameAndSig);
        }

        public struct VirtualResolveDataResult
        {
            public RuntimeTypeHandle DeclaringInvokeType;
            public ushort SlotIndex;
            public RuntimeMethodHandle GVMHandle;
            public bool IsGVM;
        }

        public static bool TryGetVirtualResolveData(NativeFormatModuleInfo module,
            RuntimeTypeHandle methodHandleDeclaringType, RuntimeTypeHandle[] genericArgs,
            ref MethodSignatureComparer methodSignatureComparer,
            out VirtualResolveDataResult lookupResult)
        {
            lookupResult = default(VirtualResolveDataResult);
            NativeReader invokeMapReader = GetNativeReaderForBlob(module, ReflectionMapBlob.VirtualInvokeMap);
            NativeParser invokeMapParser = new NativeParser(invokeMapReader, 0);
            NativeHashtable invokeHashtable = new NativeHashtable(invokeMapParser);
            ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
            externalReferences.InitializeCommonFixupsTable(module);

            //
            // When working with the ProjectN ABI, the entries in the map are based on the definition types. All
            // instantiations of these definition types will have the same vtable method entries.
            // On CoreRT, the vtable entries for each instantiated type might not necessarily exist.
            // Example 1: 
            //      If there's a call to Foo<string>.Method1 and a call to Foo<int>.Method2, Foo<string> will
            //      not have Method2 in its vtable and Foo<int> will not have Method1.
            // Example 2:
            //      If there's a call to Foo<string>.Method1 and a call to Foo<object>.Method2, given that both
            //      of these instantiations share the same canonical form, Foo<__Canon> will have both method 
            //      entries, and therefore Foo<string> and Foo<object> will have both entries too.
            // For this reason, the entries that we write to the map in CoreRT will be based on the canonical form
            // of the method's containing type instead of the open type definition.
            //
            // Similarly, given that we use the open type definition for ProjectN, the slot numbers ignore dictionary
            // entries in the vtable, and computing the correct slot number in the presence of dictionary entries is 
            // done at runtime. When working with the CoreRT ABI, the correct slot numbers will be written to the map,
            // and no adjustments will be performed at runtime.
            //

#if PROJECTN
            CanonicallyEquivalentEntryLocator canonHelper = new CanonicallyEquivalentEntryLocator(
                Instance.GetTypeDefinition(methodHandleDeclaringType), 
                CanonicalFormKind.Specific);
#else
            CanonicallyEquivalentEntryLocator canonHelper = new CanonicallyEquivalentEntryLocator(
                methodHandleDeclaringType,
                CanonicalFormKind.Specific);
#endif

            var lookup = invokeHashtable.Lookup(canonHelper.LookupHashCode);

            NativeParser entryParser;
            while (!(entryParser = lookup.GetNext()).IsNull)
            {
                // Grammar of an entry in the hash table:
                // Virtual Method uses a normal slot 
                // TypeKey + NameAndSig metadata offset into the native layout metadata + (NumberOfStepsUpParentHierarchyToType << 1) + slot
                // OR
                // Generic Virtual Method 
                // TypeKey + NameAndSig metadata offset into the native layout metadata + (NumberOfStepsUpParentHierarchyToType << 1 + 1)

                RuntimeTypeHandle entryType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                if (!canonHelper.IsCanonicallyEquivalent(entryType))
                    continue;

                uint nameAndSigPointerToken = externalReferences.GetExternalNativeLayoutOffset(entryParser.GetUnsigned());

                MethodNameAndSignature nameAndSig;
                if (!TypeLoaderEnvironment.Instance.TryGetMethodNameAndSignatureFromNativeLayoutOffset(module.Handle, nameAndSigPointerToken, out nameAndSig))
                {
                    Debug.Assert(false);
                    continue;
                }

                if (!methodSignatureComparer.IsMatchingNativeLayoutMethodNameAndSignature(nameAndSig.Name, nameAndSig.Signature))
                {
                    continue;
                }

                uint parentHierarchyAndFlag = entryParser.GetUnsigned();
                uint parentHierarchy = parentHierarchyAndFlag >> 1;
                RuntimeTypeHandle declaringTypeOfVirtualInvoke = methodHandleDeclaringType;
                for (uint iType = 0; iType < parentHierarchy; iType++)
                {
                    if (!RuntimeAugments.TryGetBaseType(declaringTypeOfVirtualInvoke, out declaringTypeOfVirtualInvoke))
                    {
                        Debug.Assert(false); // This will only fail if the virtual invoke data is malformed as specifies that a type
                        // has a deeper inheritance hierarchy than it actually does.
                        return false;
                    }
                }

                bool isGenericVirtualMethod = ((parentHierarchyAndFlag & VirtualInvokeTableEntry.FlagsMask) == VirtualInvokeTableEntry.GenericVirtualMethod);

                Debug.Assert(isGenericVirtualMethod == ((genericArgs != null) && genericArgs.Length > 0));

                if (isGenericVirtualMethod)
                {
                    RuntimeSignature methodName;
                    RuntimeSignature methodSignature;

                    if (!TypeLoaderEnvironment.Instance.TryGetMethodNameAndSignaturePointersFromNativeLayoutSignature(module.Handle, nameAndSigPointerToken, out methodName, out methodSignature))
                    {
                        Debug.Assert(false);
                        return false;
                    }

                    RuntimeMethodHandle gvmSlot = TypeLoaderEnvironment.Instance.GetRuntimeMethodHandleForComponents(declaringTypeOfVirtualInvoke, methodName.NativeLayoutSignature(), methodSignature, genericArgs);

                    lookupResult = new VirtualResolveDataResult
                    {
                        DeclaringInvokeType = declaringTypeOfVirtualInvoke,
                        SlotIndex = 0,
                        GVMHandle = gvmSlot,
                        IsGVM = true
                    };
                    return true;
                }
                else
                {
                    uint slot = entryParser.GetUnsigned();

#if PROJECTN
                    RuntimeTypeHandle searchForSharedGenericTypesInParentHierarchy = declaringTypeOfVirtualInvoke;
                    while (!searchForSharedGenericTypesInParentHierarchy.IsNull())
                    {
                        // See if this type is shared generic. If so, adjust the slot by 1.
                        if (RuntimeAugments.IsGenericType(searchForSharedGenericTypesInParentHierarchy))
                        {
                            if (RuntimeAugments.IsInterface(searchForSharedGenericTypesInParentHierarchy))
                            {
                                // Generic interfaces always have a dictionary slot in the vtable (see binder code in MdilModule::SaveMethodTable)
                                // Interfaces do not have base types, so we can just break out of the loop here ...
                                slot++;
                                break;
                            }

                            RuntimeTypeHandle[] genericTypeArgs;
                            RuntimeAugments.GetGenericInstantiation(searchForSharedGenericTypesInParentHierarchy,
                                                                    out genericTypeArgs);
                            if (TypeLoaderEnvironment.Instance.ConversionToCanonFormIsAChange(genericTypeArgs, CanonicalFormKind.Specific))
                            {
                                // Shared generic types have a slot dedicated to holding the generic dictionary.
                                slot++;
                            }
                        }

                        // Walk to parent
                        if (!RuntimeAugments.TryGetBaseType(searchForSharedGenericTypesInParentHierarchy, out searchForSharedGenericTypesInParentHierarchy))
                        {
                            break;
                        }
                    }
#endif

                    lookupResult = new VirtualResolveDataResult
                    {
                        DeclaringInvokeType = declaringTypeOfVirtualInvoke,
                        SlotIndex = checked((ushort)slot),
                        GVMHandle = default(RuntimeMethodHandle),
                        IsGVM = false
                    };
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Given a virtual logical slot and its open defining type, get information necessary to acquire the associated metadata from the mapping tables.
        /// </summary>
        /// <param name="moduleHandle">Module to look in</param>
        /// <param name="declaringType">Declaring type that is known to define the slot</param>
        /// <param name="logicalSlot">The logical slot that the method goes in. For this method, the logical 
        /// slot is defined as the nth virtual method defined in order on the type (including base types). 
        /// VTable slots reserved for dictionary pointers are ignored.</param>
        /// <param name="methodNameAndSig">The name and signature of the method</param>
        /// <returns>true if a definition is found, false if not</returns>
        private static unsafe bool TryGetMethodNameAndSigFromVirtualResolveData(NativeFormatModuleInfo module,
            RuntimeTypeHandle declaringType, int logicalSlot, out MethodNameAndSignature methodNameAndSig)
        {
            // 
            // NOTE: The semantics of the vtable slot and method declaring type in the VirtualInvokeMap table have slight differences between ProjectN and CoreRT ABIs.
            // See comment in TryGetVirtualResolveData for more details.
            //

            NativeReader invokeMapReader = GetNativeReaderForBlob(module, ReflectionMapBlob.VirtualInvokeMap);
            NativeParser invokeMapParser = new NativeParser(invokeMapReader, 0);
            NativeHashtable invokeHashtable = new NativeHashtable(invokeMapParser);
            ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
            externalReferences.InitializeCommonFixupsTable(module);

            CanonicallyEquivalentEntryLocator canonHelper = new CanonicallyEquivalentEntryLocator(declaringType, CanonicalFormKind.Specific);

            methodNameAndSig = default(MethodNameAndSignature);

            var lookup = invokeHashtable.Lookup(canonHelper.LookupHashCode);
            NativeParser entryParser;
            while (!(entryParser = lookup.GetNext()).IsNull)
            {
                // Grammar of an entry in the hash table:
                // Virtual Method uses a normal slot 
                // TypeKey + NameAndSig metadata offset into the native layout metadata + (NumberOfStepsUpParentHierarchyToType << 1) + slot
                // OR
                // Generic Virtual Method 
                // TypeKey + NameAndSig metadata offset into the native layout metadata + (NumberOfStepsUpParentHierarchyToType << 1 + 1)

                RuntimeTypeHandle entryType = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                if (!canonHelper.IsCanonicallyEquivalent(entryType))
                    continue;

                uint nameAndSigPointerToken = externalReferences.GetExternalNativeLayoutOffset(entryParser.GetUnsigned());

                uint parentHierarchyAndFlag = entryParser.GetUnsigned();
                bool isGenericVirtualMethod = ((parentHierarchyAndFlag & VirtualInvokeTableEntry.FlagsMask) == VirtualInvokeTableEntry.GenericVirtualMethod);

                // We're looking for a method with a specific slot. By definition, it isn't a GVM as we define GVM as not having slots in the vtable
                if (isGenericVirtualMethod)
                    continue;

                uint mappingTableSlot = entryParser.GetUnsigned();

                // Slot doesn't match
                if (logicalSlot != mappingTableSlot)
                    continue;

                if (!TypeLoaderEnvironment.Instance.TryGetMethodNameAndSignatureFromNativeLayoutOffset(module.Handle, nameAndSigPointerToken, out methodNameAndSig))
                {
                    Debug.Assert(false);
                    continue;
                }

                return true;
            }
            return false;
        }

        /// <summary>
        /// Try to look up method invoke info for given canon.
        /// </summary>
        /// <param name="metadataReader">Metadata reader for the declaring type</param>
        /// <param name="declaringTypeHandle">Declaring type for the method</param>
        /// <param name="methodHandle">Method handle</param>
        /// <param name="genericMethodTypeArgumentHandles">Handles of generic argument types</param>
        /// <param name="methodSignatureComparer">Helper class used to compare method signatures</param>
        /// <param name="canonFormKind">Canonical form to use</param>
        /// <param name="methodInvokeMetadata">Output - metadata information for method invoker construction</param>
        /// <returns>true when found, false otherwise</returns>
        public static bool TryGetMethodInvokeMetadata(
            RuntimeTypeHandle declaringTypeHandle,
            QMethodDefinition methodHandle,
            RuntimeTypeHandle[] genericMethodTypeArgumentHandles,
            ref MethodSignatureComparer methodSignatureComparer,
            CanonicalFormKind canonFormKind,
            out MethodInvokeMetadata methodInvokeMetadata)
        {
            if (methodHandle.IsNativeFormatMetadataBased)
            {
                if (TryGetMethodInvokeMetadataFromInvokeMap(
                    methodHandle.NativeFormatReader,
                    declaringTypeHandle,
                    methodHandle.NativeFormatHandle,
                    genericMethodTypeArgumentHandles,
                    ref methodSignatureComparer,
                    canonFormKind,
                    out methodInvokeMetadata))
                {
                    return true;
                }
            }

            TypeSystemContext context = TypeSystemContextFactory.Create();

            bool success = TryGetMethodInvokeMetadataFromNativeFormatMetadata(
                declaringTypeHandle,
                methodHandle,
                genericMethodTypeArgumentHandles,
                ref methodSignatureComparer,
                context,
                canonFormKind,
                out methodInvokeMetadata);

            TypeSystemContextFactory.Recycle(context);

            return success;
        }

#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
        /// <summary>
        /// Try to look up method invoke info for given canon in InvokeMap blobs for all available modules.
        /// </summary>
        /// <param name="typicalMethodDesc">Metadata MethodDesc to look for</param>
        /// <param name="method">method to search for</param>
        /// <param name="methodSignatureComparer">Helper class used to compare method signatures</param>
        /// <param name="canonFormKind">Canonical form to use</param>
        /// <param name="methodEntryPoint">Output - Output code address</param>
        /// <param name="foundAddressType">Output - The type of method address match found. A canonical address may require extra parameters to call.</param>
        /// <returns>true when found, false otherwise</returns>
        private static bool TryGetMethodInvokeDataFromInvokeMap(
            NativeFormatMethod typicalMethodDesc,
            MethodDesc method,
            ref MethodSignatureComparer methodSignatureComparer,
            CanonicalFormKind canonFormKind,
            out IntPtr methodEntryPoint,
            out MethodAddressType foundAddressType)
        {
            methodEntryPoint = IntPtr.Zero;
            foundAddressType = MethodAddressType.None;

            CanonicallyEquivalentEntryLocator canonHelper = new CanonicallyEquivalentEntryLocator(method.OwningType.GetClosestDefType(), canonFormKind);

            TypeManagerHandle methodHandleModule = typicalMethodDesc.MetadataUnit.RuntimeModule;

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(methodHandleModule))
            {
                NativeReader invokeMapReader;
                if (!TryGetNativeReaderForBlob(module, ReflectionMapBlob.InvokeMap, out invokeMapReader))
                {
                    continue;
                }

                NativeParser invokeMapParser = new NativeParser(invokeMapReader, 0);
                NativeHashtable invokeHashtable = new NativeHashtable(invokeMapParser);

                ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                externalReferences.InitializeCommonFixupsTable(module);

                var lookup = invokeHashtable.Lookup(canonHelper.LookupHashCode);
                var entryData = new InvokeMapEntryDataEnumerator<TypeSystemTypeComparator, bool>(
                    new TypeSystemTypeComparator(method),
                    canonFormKind,
                    module.Handle,
                    typicalMethodDesc.Handle,
                    methodHandleModule);

                NativeParser entryParser;
                while (!(entryParser = lookup.GetNext()).IsNull)
                {
                    entryData.GetNext(ref entryParser, ref externalReferences, ref methodSignatureComparer, canonHelper);

                    if (!entryData.IsMatchingOrCompatibleEntry())
                        continue;

                    IntPtr rawMethodEntryPoint;
                    bool needsDictionaryForCall;

                    if (entryData.GetMethodEntryPoint(
                        out methodEntryPoint,
                        out needsDictionaryForCall,
                        out rawMethodEntryPoint))
                    {
                        // At this time, because we don't have any logic which generates a true fat function pointer
                        // in the TypeSystemTypeComparator, rawMethodEntryPoint should always be the same as methodEntryPoint
                        Debug.Assert(rawMethodEntryPoint == methodEntryPoint);

                        if (canonFormKind == CanonicalFormKind.Universal)
                        {
                            foundAddressType = MethodAddressType.UniversalCanonical;
                        }
                        else
                        {
                            Debug.Assert(canonFormKind == CanonicalFormKind.Specific);

                            if (needsDictionaryForCall)
                            {
                                foundAddressType = MethodAddressType.Canonical;
                            }
                            else
                            {
                                if (method.OwningType.IsValueType && method.OwningType != method.OwningType.ConvertToCanonForm(canonFormKind) && !method.Signature.IsStatic)
                                {
                                    // The entrypoint found is the unboxing stub for a non-generic instance method on a structure
                                    foundAddressType = MethodAddressType.Canonical;
                                }
                                else
                                {
                                    foundAddressType = MethodAddressType.Exact; // We may or may not have found a canonical method here, but if its exactly callable... its close enough
                                }
                            }
                        }
                    }

                    return true;
                }
            }

            return false;
        }
#endif

        /// <summary>
        /// Try to look up method invoke info for given canon in InvokeMap blobs for all available modules.
        /// </summary>
        /// <param name="metadataReader">Metadata reader for the declaring type</param>
        /// <param name="declaringTypeHandle">Declaring type for the method</param>
        /// <param name="methodHandle">Method handle</param>
        /// <param name="genericMethodTypeArgumentHandles">Handles of generic argument types</param>
        /// <param name="methodSignatureComparer">Helper class used to compare method signatures</param>
        /// <param name="canonFormKind">Canonical form to use</param>
        /// <param name="methodInvokeMetadata">Output - metadata information for method invoker construction</param>
        /// <returns>true when found, false otherwise</returns>
        private static bool TryGetMethodInvokeMetadataFromInvokeMap(
            MetadataReader metadataReader,
            RuntimeTypeHandle declaringTypeHandle,
            MethodHandle methodHandle,
            RuntimeTypeHandle[] genericMethodTypeArgumentHandles,
            ref MethodSignatureComparer methodSignatureComparer,
            CanonicalFormKind canonFormKind,
            out MethodInvokeMetadata methodInvokeMetadata)
        {
            CanonicallyEquivalentEntryLocator canonHelper = new CanonicallyEquivalentEntryLocator(declaringTypeHandle, canonFormKind);
            TypeManagerHandle methodHandleModule = ModuleList.Instance.GetModuleForMetadataReader(metadataReader);

            foreach (NativeFormatModuleInfo module in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(declaringTypeHandle)))
            {
                NativeReader invokeMapReader;
                if (!TryGetNativeReaderForBlob(module, ReflectionMapBlob.InvokeMap, out invokeMapReader))
                {
                    continue;
                }

                NativeParser invokeMapParser = new NativeParser(invokeMapReader, 0);
                NativeHashtable invokeHashtable = new NativeHashtable(invokeMapParser);

                ExternalReferencesTable externalReferences = default(ExternalReferencesTable);
                externalReferences.InitializeCommonFixupsTable(module);

                var lookup = invokeHashtable.Lookup(canonHelper.LookupHashCode);
                var entryData = new InvokeMapEntryDataEnumerator<PreloadedTypeComparator, IntPtr>(
                    new PreloadedTypeComparator(declaringTypeHandle, genericMethodTypeArgumentHandles),
                    canonFormKind,
                    module.Handle,
                    methodHandle,
                    methodHandleModule);

                NativeParser entryParser;
                while (!(entryParser = lookup.GetNext()).IsNull)
                {
                    entryData.GetNext(ref entryParser, ref externalReferences, ref methodSignatureComparer, canonHelper);

                    if (!entryData.IsMatchingOrCompatibleEntry())
                        continue;

                    if (entryData.GetMethodEntryPoint(
                        out methodInvokeMetadata.MethodEntryPoint,
                        out methodInvokeMetadata.DictionaryComponent,
                        out methodInvokeMetadata.RawMethodEntryPoint))
                    {
                        methodInvokeMetadata.MappingTableModule = module;
                        methodInvokeMetadata.DynamicInvokeCookie = entryData._dynamicInvokeCookie;
                        methodInvokeMetadata.InvokeTableFlags = entryData._flags;

                        return true;
                    }
                }
            }

            methodInvokeMetadata = default(MethodInvokeMetadata);
            return false;
        }

        /// <summary>
        /// Look up method entry point based on native format metadata information.
        /// </summary>
        /// <param name="metadataReader">Metadata reader for the declaring type</param>
        /// <param name="declaringTypeHandle">Declaring type for the method</param>
        /// <param name="methodHandle">Method handle</param>
        /// <param name="genericMethodTypeArgumentHandles">Handles of generic argument types</param>
        /// <param name="methodSignatureComparer">Helper class used to compare method signatures</param>
        /// <param name="typeSystemContext">Type system context to use</param>
        /// <param name="canonFormKind">Canonical form to use</param>
        /// <param name="methodInvokeMetadata">Output - metadata information for method invoker construction</param>
        /// <returns>true when found, false otherwise</returns>
        private static bool TryGetMethodInvokeMetadataFromNativeFormatMetadata(
            RuntimeTypeHandle declaringTypeHandle,
            QMethodDefinition methodHandle,
            RuntimeTypeHandle[] genericMethodTypeArgumentHandles,
            ref MethodSignatureComparer methodSignatureComparer,
            TypeSystemContext typeSystemContext,
            CanonicalFormKind canonFormKind,
            out MethodInvokeMetadata methodInvokeMetadata)
        {
            methodInvokeMetadata = default(MethodInvokeMetadata);

#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
            TypeDesc declaringType = typeSystemContext.ResolveRuntimeTypeHandle(declaringTypeHandle);
            TypeDesc declaringTypeDefinition = declaringType.GetTypeDefinition();

            if (declaringTypeDefinition == null)
                return false;


            MethodDesc methodOnType = null;
            
            if (declaringTypeDefinition is NativeFormatType)
            {
                NativeFormatType nativeFormatType = ((NativeFormatType)declaringTypeDefinition);
                Debug.Assert(methodHandle.NativeFormatReader == nativeFormatType.MetadataReader);
                methodOnType = nativeFormatType.MetadataUnit.GetMethod(methodHandle.NativeFormatHandle, nativeFormatType);
            }
            else
            {
                EcmaType ecmaType = ((EcmaType)declaringTypeDefinition);
                Debug.Assert(methodHandle.EcmaFormatReader == ecmaType.MetadataReader);
                methodOnType = ecmaType.EcmaModule.GetMethod(methodHandle.EcmaFormatHandle);
            }

            if (methodOnType == null)
            {
                return false;
            }

            if (declaringTypeDefinition != declaringType)
            {
                // If we reach here, then the method is on a generic type, and we just found the uninstantiated form
                // Get the method on the instantiated type and continue
                methodOnType = typeSystemContext.GetMethodForInstantiatedType(methodOnType, (InstantiatedType)declaringType);
            }

            if (genericMethodTypeArgumentHandles.Length > 0)
            {
                // If we reach here, this is a generic method, instantiate and continue
                methodOnType = typeSystemContext.GetInstantiatedMethod(methodOnType, typeSystemContext.ResolveRuntimeTypeHandles(genericMethodTypeArgumentHandles));
            }

            IntPtr entryPoint = IntPtr.Zero;
            IntPtr unboxingStubAddress = IntPtr.Zero;
            MethodAddressType foundAddressType = MethodAddressType.None;
#if SUPPORTS_R2R_LOADING
            TryGetCodeTableEntry(methodOnType, out entryPoint, out unboxingStubAddress, out foundAddressType);
#endif
#if SUPPORT_DYNAMIC_CODE
            if (foundAddressType == MethodAddressType.None)
                MethodEntrypointStubs.TryGetMethodEntrypoint(methodOnType, out entryPoint, out unboxingStubAddress, out foundAddressType);
#endif
            if (foundAddressType == MethodAddressType.None)
                return false;

            // Only find a universal canon implementation if searching for one
            if (foundAddressType == MethodAddressType.UniversalCanonical &&
                !((canonFormKind == CanonicalFormKind.Universal) || (canonFormKind == CanonicalFormKind.Any)))
            {
                return false;
            }

            // TODO: This will probably require additional work to smoothly use unboxing stubs
            // in vtables - for plain reflection invoke everything seems to work
            // without additional changes thanks to the "NeedsParameterInterpretation" flag.
            if (methodHandle.IsNativeFormatMetadataBased)
                methodInvokeMetadata.MappingTableModule = ((NativeFormatType)declaringTypeDefinition).MetadataUnit.RuntimeModuleInfo;
            else
                methodInvokeMetadata.MappingTableModule = null; // MappingTableModule is only used if NeedsParameterInterpretation isn't set
            methodInvokeMetadata.MethodEntryPoint = entryPoint;
            methodInvokeMetadata.RawMethodEntryPoint = entryPoint;
            // TODO: methodInvokeMetadata.DictionaryComponent
            // TODO: methodInvokeMetadata.DefaultValueString
            // TODO: methodInvokeMetadata.DynamicInvokeCookie

            methodInvokeMetadata.InvokeTableFlags =
                InvokeTableFlags.HasMetadataHandle |
                InvokeTableFlags.HasEntrypoint |
                InvokeTableFlags.NeedsParameterInterpretation;
            if (methodOnType.Signature.GenericParameterCount != 0)
            {
                methodInvokeMetadata.InvokeTableFlags |= InvokeTableFlags.IsGenericMethod;
            }
            if (canonFormKind == CanonicalFormKind.Universal)
            {
                methodInvokeMetadata.InvokeTableFlags |= InvokeTableFlags.IsUniversalCanonicalEntry;
            }
            /* TODO
            if (methodOnType.HasDefaultParameters)
            {
                methodInvokeMetadata.InvokeTableFlags |= InvokeTableFlags.HasDefaultParameters;
            }
            */

            return true;
#else
            return false;
#endif
        }

        // Api surface for controlling invoke map enumeration.
        private interface IInvokeMapEntryDataDeclaringTypeAndGenericMethodParameterHandling<TDictionaryComponentType>
        {
            bool GetTypeDictionary(out TDictionaryComponentType dictionary);
            bool GetMethodDictionary(MethodNameAndSignature nameAndSignature, out TDictionaryComponentType dictionary);
            bool IsUninterestingDictionaryComponent(TDictionaryComponentType dictionary);
            bool CompareMethodInstantiation(RuntimeTypeHandle[] methodInstantiation);
            bool CanInstantiationsShareCode(RuntimeTypeHandle[] methodInstantiation, CanonicalFormKind canonFormKind);
            IntPtr ProduceFatFunctionPointerMethodEntryPoint(IntPtr methodEntrypoint, TDictionaryComponentType dictionary);
        }

        // Comparator for invoke map when used to find an invoke map entry and the search data is a set of
        // pre-loaded types, and metadata handles.
        private struct PreloadedTypeComparator : IInvokeMapEntryDataDeclaringTypeAndGenericMethodParameterHandling<IntPtr>
        {
            readonly private RuntimeTypeHandle _declaringTypeHandle;
            readonly private RuntimeTypeHandle[] _genericMethodTypeArgumentHandles;

            public PreloadedTypeComparator(RuntimeTypeHandle declaringTypeHandle, RuntimeTypeHandle[] genericMethodTypeArgumentHandles)
            {
                _declaringTypeHandle = declaringTypeHandle;
                _genericMethodTypeArgumentHandles = genericMethodTypeArgumentHandles;
            }

            public bool GetTypeDictionary(out IntPtr dictionary)
            {
                dictionary = RuntimeAugments.GetPointerFromTypeHandle(_declaringTypeHandle);
                Debug.Assert(dictionary != IntPtr.Zero);
                return true;
            }

            public bool GetMethodDictionary(MethodNameAndSignature nameAndSignature, out IntPtr dictionary)
            {
                return TypeLoaderEnvironment.Instance.TryGetGenericMethodDictionaryForComponents(_declaringTypeHandle,
                    _genericMethodTypeArgumentHandles,
                    nameAndSignature,
                    out dictionary);
            }

            public bool IsUninterestingDictionaryComponent(IntPtr dictionary)
            {
                return dictionary == IntPtr.Zero;
            }

            public IntPtr ProduceFatFunctionPointerMethodEntryPoint(IntPtr methodEntrypoint, IntPtr dictionary)
            {
                return FunctionPointerOps.GetGenericMethodFunctionPointer(methodEntrypoint, dictionary);
            }

            public bool CompareMethodInstantiation(RuntimeTypeHandle[] methodInstantiation)
            {
                return SequenceEqual(_genericMethodTypeArgumentHandles, methodInstantiation);
            }

            public bool CanInstantiationsShareCode(RuntimeTypeHandle[] methodInstantiation, CanonicalFormKind canonFormKind)
            {
                return TypeLoaderEnvironment.Instance.CanInstantiationsShareCode(methodInstantiation, _genericMethodTypeArgumentHandles, canonFormKind);
            }
        }

        // Comparator for invoke map when used to find an invoke map entry and the search data is
        // a type system object with Metadata
        private struct TypeSystemTypeComparator : IInvokeMapEntryDataDeclaringTypeAndGenericMethodParameterHandling<bool>
        {
            readonly private MethodDesc _targetMethod;

            public TypeSystemTypeComparator(MethodDesc targetMethod)
            {
                _targetMethod = targetMethod;
            }

            public bool GetTypeDictionary(out bool dictionary)
            {
                // The true is to indicate a dictionary is necessary
                dictionary = true;
                return true;
            }

            public bool GetMethodDictionary(MethodNameAndSignature nameAndSignature, out bool dictionary)
            {
                // The true is to indicate a dictionary is necessary
                dictionary = true;
                return true;
            }

            public bool IsUninterestingDictionaryComponent(bool dictionary)
            {
                return dictionary == false;
            }

            public IntPtr ProduceFatFunctionPointerMethodEntryPoint(IntPtr methodEntrypoint, bool dictionary)
            {
                // We don't actually want to produce the fat function pointer here. We want to delay until its actually needed
                return methodEntrypoint;
            }

            public bool CompareMethodInstantiation(RuntimeTypeHandle[] methodInstantiation)
            {
                if (!_targetMethod.HasInstantiation)
                    return false;

                if (_targetMethod.Instantiation.Length != methodInstantiation.Length)
                    return false;

                int i = 0;
                foreach (TypeDesc instantiationType in _targetMethod.Instantiation)
                {
                    TypeDesc genericArg2 = _targetMethod.Context.ResolveRuntimeTypeHandle(methodInstantiation[i]);
                    if (instantiationType != genericArg2)
                    {
                        return false;
                    }
                    i++;
                }

                return true;
            }

            public bool CanInstantiationsShareCode(RuntimeTypeHandle[] methodInstantiation, CanonicalFormKind canonFormKind)
            {
                if (!_targetMethod.HasInstantiation)
                    return false;

                if (_targetMethod.Instantiation.Length != methodInstantiation.Length)
                    return false;

                int i = 0;
                foreach (TypeDesc instantiationType in _targetMethod.Instantiation)
                {
                    TypeSystemContext context = _targetMethod.Context;
                    TypeDesc genericArg2 = context.ResolveRuntimeTypeHandle(methodInstantiation[i]);
                    if (context.ConvertToCanon(instantiationType, canonFormKind) != context.ConvertToCanon(genericArg2, canonFormKind))
                    {
                        return false;
                    }
                    i++;
                }

                return true;
            }
        }

        // Enumerator for discovering methods in the InvokeMap. This is generic to allow highly efficient
        // searching of this table with multiple different input data formats.
        private struct InvokeMapEntryDataEnumerator<TLookupMethodInfo, TDictionaryComponentType> where TLookupMethodInfo : IInvokeMapEntryDataDeclaringTypeAndGenericMethodParameterHandling<TDictionaryComponentType>
        {
            // Read-only inputs
            private TLookupMethodInfo _lookupMethodInfo;
            readonly private CanonicalFormKind _canonFormKind;
            readonly private TypeManagerHandle _moduleHandle;
            readonly private TypeManagerHandle _moduleForMethodHandle;
            readonly private MethodHandle _methodHandle;

            // Parsed data from entry in the hashtable
            public InvokeTableFlags _flags;
            public RuntimeTypeHandle _entryType;
            public IntPtr _methodEntrypoint;
            public uint _dynamicInvokeCookie;
            public IntPtr _entryDictionary;
            public RuntimeTypeHandle[] _methodInstantiation;

            // Computed data
            private bool _hasEntryPoint;
            private bool _isMatchingMethodHandleAndDeclaringType;
            private MethodNameAndSignature _nameAndSignature;
            private RuntimeTypeHandle[] _entryMethodInstantiation;

            public InvokeMapEntryDataEnumerator(
                TLookupMethodInfo lookupMethodInfo,
                CanonicalFormKind canonFormKind,
                TypeManagerHandle moduleHandle,
                MethodHandle methodHandle,
                TypeManagerHandle moduleForMethodHandle)
            {
                _lookupMethodInfo = lookupMethodInfo;
                _canonFormKind = canonFormKind;
                _moduleHandle = moduleHandle;
                _methodHandle = methodHandle;
                _moduleForMethodHandle = moduleForMethodHandle;

                _flags = 0;
                _entryType = default(RuntimeTypeHandle);
                _methodEntrypoint = IntPtr.Zero;
                _dynamicInvokeCookie = 0xffffffff;
                _hasEntryPoint = false;
                _isMatchingMethodHandleAndDeclaringType = false;
                _entryDictionary = IntPtr.Zero;
                _methodInstantiation = null;
                _nameAndSignature = null;
                _entryMethodInstantiation = null;
            }

            public void GetNext(
                ref NativeParser entryParser,
                ref ExternalReferencesTable extRefTable,
                ref MethodSignatureComparer methodSignatureComparer,
                CanonicallyEquivalentEntryLocator canonHelper)
            {
                // Read flags and reset members data
                _flags = (InvokeTableFlags)entryParser.GetUnsigned();
                _hasEntryPoint = ((_flags & InvokeTableFlags.HasEntrypoint) != 0);
                _isMatchingMethodHandleAndDeclaringType = false;
                _entryType = default(RuntimeTypeHandle);
                _methodEntrypoint = IntPtr.Zero;
                _dynamicInvokeCookie = 0xffffffff;
                _entryDictionary = IntPtr.Zero;
                _methodInstantiation = null;
                _nameAndSignature = null;
                _entryMethodInstantiation = null;

                // If the current entry is not a canonical entry of the same canonical form kind we are looking for, then this cannot be a match
                if (((_flags & InvokeTableFlags.IsUniversalCanonicalEntry) != 0) != (_canonFormKind == CanonicalFormKind.Universal))
                    return;

                if ((_flags & InvokeTableFlags.HasMetadataHandle) != 0)
                {
                    // Metadata handles are not known cross module, and cannot be compared across modules.
                    if (_moduleHandle != _moduleForMethodHandle)
                        return;

                    Handle entryMethodHandle = (((uint)HandleType.Method << 24) | entryParser.GetUnsigned()).AsHandle();
                    if (!_methodHandle.Equals(entryMethodHandle))
                        return;
                }
                else
                {
                    uint nameAndSigToken = extRefTable.GetExternalNativeLayoutOffset(entryParser.GetUnsigned());
                    MethodNameAndSignature nameAndSig;
                    if (!TypeLoaderEnvironment.Instance.TryGetMethodNameAndSignatureFromNativeLayoutOffset(_moduleHandle, nameAndSigToken, out nameAndSig))
                    {
                        Debug.Assert(false);
                        return;
                    }
                    Debug.Assert(nameAndSig.Signature.IsNativeLayoutSignature);
                    if (!methodSignatureComparer.IsMatchingNativeLayoutMethodNameAndSignature(nameAndSig.Name, nameAndSig.Signature))
                        return;
                }

                _entryType = extRefTable.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
                if (!canonHelper.IsCanonicallyEquivalent(_entryType))
                    return;

                // Method handle and entry type match at this point. Continue reading data from the entry...
                _isMatchingMethodHandleAndDeclaringType = true;

                if (_hasEntryPoint)
                    _methodEntrypoint = extRefTable.GetFunctionPointerFromIndex(entryParser.GetUnsigned());

                if ((_flags & InvokeTableFlags.NeedsParameterInterpretation) == 0)
                    _dynamicInvokeCookie = entryParser.GetUnsigned();

                if ((_flags & InvokeTableFlags.IsGenericMethod) == 0)
                    return;

                if ((_flags & InvokeTableFlags.IsUniversalCanonicalEntry) != 0)
                {
                    Debug.Assert((_hasEntryPoint || ((_flags & InvokeTableFlags.HasVirtualInvoke) != 0)) && ((_flags & InvokeTableFlags.RequiresInstArg) != 0));

                    uint nameAndSigPointerToken = extRefTable.GetExternalNativeLayoutOffset(entryParser.GetUnsigned());
                    if (!TypeLoaderEnvironment.Instance.TryGetMethodNameAndSignatureFromNativeLayoutOffset(_moduleHandle, nameAndSigPointerToken, out _nameAndSignature))
                    {
                        Debug.Assert(false);    //Error
                        _isMatchingMethodHandleAndDeclaringType = false;
                    }
                }
                else if (((_flags & InvokeTableFlags.RequiresInstArg) != 0) && _hasEntryPoint)
                    _entryDictionary = extRefTable.GetGenericDictionaryFromIndex(entryParser.GetUnsigned());
                else
                    _methodInstantiation = GetTypeSequence(ref extRefTable, ref entryParser);
            }

            public bool IsMatchingOrCompatibleEntry()
            {
                // Check if method handle and entry type were matching or compatible
                if (!_isMatchingMethodHandleAndDeclaringType)
                    return false;

                // Nothing special about non-generic methods. 
                if ((_flags & InvokeTableFlags.IsGenericMethod) == 0)
                    return true;

                // A universal canonical method entry can share code with any method instantiation (no need to call CanInstantiationsShareCode())
                if ((_flags & InvokeTableFlags.IsUniversalCanonicalEntry) != 0)
                {
                    Debug.Assert(_canonFormKind == CanonicalFormKind.Universal);
                    return true;
                }

                // Generic non-shareable method or abstract methods: check for the canonical equivalency of the method 
                // instantiation arguments that we read from the entry
                if (((_flags & InvokeTableFlags.RequiresInstArg) == 0) || !_hasEntryPoint)
                    return _lookupMethodInfo.CanInstantiationsShareCode(_methodInstantiation, _canonFormKind);

                // Generic shareable method: check for canonical equivalency of the method instantiation arguments.
                // The method instantiation arguments are extracted from the generic dictionary pointer that we read from the entry.
                Debug.Assert(_entryDictionary != IntPtr.Zero);
                return GetNameAndSignatureAndMethodInstantiation() && _lookupMethodInfo.CanInstantiationsShareCode(_entryMethodInstantiation, _canonFormKind);
            }

            public bool GetMethodEntryPoint(out IntPtr methodEntrypoint, out TDictionaryComponentType dictionaryComponent, out IntPtr rawMethodEntrypoint)
            {
                // Debug-only sanity check before proceeding (IsMatchingOrCompatibleEntry is called from TryGetDynamicMethodInvokeInfo)
                Debug.Assert(IsMatchingOrCompatibleEntry());

                rawMethodEntrypoint = _methodEntrypoint;
                methodEntrypoint = IntPtr.Zero;
                dictionaryComponent = default(TDictionaryComponentType);

                if (!GetDictionaryComponent(out dictionaryComponent) || !GetMethodEntryPointComponent(dictionaryComponent, out methodEntrypoint))
                    return false;

                return true;
            }

            private bool GetDictionaryComponent(out TDictionaryComponentType dictionaryComponent)
            {
                dictionaryComponent = default(TDictionaryComponentType);

                if (((_flags & InvokeTableFlags.RequiresInstArg) == 0) || !_hasEntryPoint)
                    return true;

                // Dictionary for non-generic method is the type handle of the declaring type
                if ((_flags & InvokeTableFlags.IsGenericMethod) == 0)
                {
                    return _lookupMethodInfo.GetTypeDictionary(out dictionaryComponent);
                }

                // Dictionary for generic method (either found statically or constructed dynamically)
                return GetNameAndSignatureAndMethodInstantiation() && _lookupMethodInfo.GetMethodDictionary(_nameAndSignature, out dictionaryComponent);
            }

            private bool GetMethodEntryPointComponent(TDictionaryComponentType dictionaryComponent, out IntPtr methodEntrypoint)
            {
                methodEntrypoint = _methodEntrypoint;

                if (_lookupMethodInfo.IsUninterestingDictionaryComponent(dictionaryComponent))
                    return true;

                // Do not use a fat function-pointer for universal canonical methods because the converter data block already holds the 
                // dictionary pointer so it serves as its own instantiating stub
                if ((_flags & InvokeTableFlags.IsUniversalCanonicalEntry) == 0)
                    methodEntrypoint = _lookupMethodInfo.ProduceFatFunctionPointerMethodEntryPoint(_methodEntrypoint, dictionaryComponent);

                return true;
            }

            private bool GetNameAndSignatureAndMethodInstantiation()
            {
                if (_nameAndSignature != null)
                {
                    Debug.Assert(((_flags & InvokeTableFlags.IsUniversalCanonicalEntry) != 0) || (_entryMethodInstantiation != null && _entryMethodInstantiation.Length > 0));
                    return true;
                }

                if ((_flags & InvokeTableFlags.IsUniversalCanonicalEntry) != 0)
                {
                    // _nameAndSignature should have been read from the InvokeMap entry directly!
                    Debug.Fail("Universal canonical entries do NOT have dictionary entries!");
                    return false;
                }

                RuntimeTypeHandle dummy1;
                bool success = TypeLoaderEnvironment.Instance.TryGetGenericMethodComponents(_entryDictionary, out dummy1, out _nameAndSignature, out _entryMethodInstantiation);
                Debug.Assert(success && dummy1.Equals(_entryType) && _nameAndSignature != null && _entryMethodInstantiation != null && _entryMethodInstantiation.Length > 0);
                return success;
            }
        }

        public static ModuleInfo GetModuleInfoForType(TypeDesc type)
        {
            for (;;)
            {
                type = type.GetTypeDefinition();
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
                NativeFormatType nativeType = type as NativeFormatType;
                if (nativeType != null)
                {
                    MetadataReader metadataReader = nativeType.MetadataReader;
                    ModuleInfo moduleInfo = ModuleList.Instance.GetModuleInfoForMetadataReader(metadataReader);

                    return moduleInfo;
                }
#endif
#if ECMA_METADATA_SUPPORT
                Internal.TypeSystem.Ecma.EcmaType ecmaType = type as Internal.TypeSystem.Ecma.EcmaType;
                if (ecmaType != null)
                {
                    return ecmaType.EcmaModule.RuntimeModuleInfo;
                }
#endif
                ArrayType arrayType = type as ArrayType;
                if (arrayType != null)
                {
                    // Arrays are defined in the core shared library
                    return ModuleList.Instance.SystemModule;
                }
                InstantiatedType instantiatedType = type as InstantiatedType;
                if (instantiatedType != null)
                {
                    type = instantiatedType.GetTypeDefinition();
                }
                ParameterizedType parameterizedType = type as ParameterizedType;
                if (parameterizedType != null)
                {
                    type = parameterizedType.ParameterType;
                    continue;
                }
                // Unable to resolve the native type
                return ModuleList.Instance.SystemModule;
            }
        }

        public bool TryGetMetadataForTypeMethodNameAndSignature(RuntimeTypeHandle declaringTypeHandle, MethodNameAndSignature nameAndSignature, out QMethodDefinition methodHandle)
        {
            if (!nameAndSignature.Signature.IsNativeLayoutSignature)
            {
                ModuleInfo moduleInfo = nameAndSignature.Signature.GetModuleInfo();

#if ECMA_METADATA_SUPPORT
                if (moduleInfo is NativeFormatModuleInfo)
#endif
                {
                    methodHandle = new QMethodDefinition(((NativeFormatModuleInfo)moduleInfo).MetadataReader, nameAndSignature.Signature.Token.AsHandle().ToMethodHandle(null));
                }
#if ECMA_METADATA_SUPPORT
                else
                {
                    methodHandle = new QMethodDefinition(((EcmaModuleInfo)moduleInfo).MetadataReader, (System.Reflection.Metadata.MethodDefinitionHandle)System.Reflection.Metadata.Ecma335.MetadataTokens.Handle(nameAndSignature.Signature.Token));
                }
#endif
                // When working with method signature that draw directly from metadata, just return the metadata token
                return true;
            }

            QTypeDefinition qTypeDefinition;
            RuntimeTypeHandle metadataLookupTypeHandle = GetTypeDefinition(declaringTypeHandle);
            methodHandle = default(QMethodDefinition);

            if (!TryGetMetadataForNamedType(metadataLookupTypeHandle, out qTypeDefinition))
                return false;

            MetadataReader reader = qTypeDefinition.NativeFormatReader;
            TypeDefinitionHandle typeDefinitionHandle = qTypeDefinition.NativeFormatHandle;

            TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);

            Debug.Assert(nameAndSignature.Signature.IsNativeLayoutSignature);

            foreach (MethodHandle mh in typeDefinition.Methods)
            {
                Method method = mh.GetMethod(reader);
                if (method.Name.StringEquals(nameAndSignature.Name, reader))
                {
                    MethodSignatureComparer methodSignatureComparer = new MethodSignatureComparer(reader, mh);
                    if (methodSignatureComparer.IsMatchingNativeLayoutMethodSignature(nameAndSignature.Signature))
                    {
                        methodHandle = new QMethodDefinition(reader, mh);
                        return true;
                    }
                }
            }

            return false;
        }
    }
}