summaryrefslogtreecommitdiff
path: root/src/md/compiler/importhelper.cpp
blob: 75764fec4029ae7c5cb61fe1f753b66d1ae986a2 (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
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//*****************************************************************************
// ImportHelper.cpp
// 

//
// contains utility code to MD directory
//
//*****************************************************************************
#include "stdafx.h"
#include "importhelper.h"
#include "mdutil.h"
#include "rwutil.h"
#include "mdlog.h"
#include "strongname.h"
#include "sstring.h"

#define COM_RUNTIME_LIBRARY "ComRuntimeLibrary"


//*******************************************************************************
// Find the MethodSpec by Method and Instantiation
//*******************************************************************************
//@GENERICS: todo: look in hashtable (cf. MetaModelRW.cpp) if necessary
HRESULT ImportHelper::FindMethodSpecByMethodAndInstantiation(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    /*mdMethodDefOrRef*/ mdToken tkMethod,  // [IN] MethodSpec method field
    PCCOR_SIGNATURE pInstantiation,         // [IN] MethodSpec instantiation (a signature)
    ULONG       cbInstantiation,            // [IN] Size of instantiation.
    mdMethodSpec *pMethodSpec,              // [OUT] Put the MethodSpec token here.
    RID         rid /* = 0*/)               // [IN] Optional rid to be ignored.
{
    HRESULT hr;
    MethodSpecRec *pRecord;
    /*mdMethodDefOrRef*/ mdToken tkMethodTmp;
    PCCOR_SIGNATURE pInstantiationTmp;
    ULONG       cbInstantiationTmp;
    ULONG       cMethodSpecs;
    ULONG       i;

    _ASSERTE(pMethodSpec);

    cMethodSpecs = pMiniMd->getCountMethodSpecs();

    // linear scan through the MethodSpec table
    for (i=1; i <= cMethodSpecs; ++i)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetMethodSpecRecord(i, &pRecord));
        
        tkMethodTmp = pMiniMd->getMethodOfMethodSpec(pRecord);
        if ((tkMethodTmp != tkMethod))
            continue;

        //@GENERICS: not sure what is meant by duplicate here: identical sig pointers or sig pointer contents?
        IfFailRet(pMiniMd->getInstantiationOfMethodSpec(pRecord, &pInstantiationTmp, &cbInstantiationTmp));
        if (cbInstantiationTmp != cbInstantiation || memcmp(pInstantiation, pInstantiationTmp, cbInstantiation))
            continue;

        //  Matching record found.
        *pMethodSpec = TokenFromRid(i, mdtMethodSpec);
        return S_OK;
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindMethodSpecByMethodAndInstantiation()


//*******************************************************************************
// Find the GenericParam by owner and constraint
//*******************************************************************************
//@GENERICS: todo: look in hashtable (cf. MetaModelRW.cpp) if necessary
HRESULT ImportHelper::FindGenericParamConstraintByOwnerAndConstraint(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    mdGenericParam tkOwner,                 // [IN] GenericParamConstraint Owner
    mdToken tkConstraint,                   // [IN] GenericParamConstraint Constraint
    mdGenericParamConstraint *pGenericParamConstraint,// [OUT] Put the GenericParam token here.
    RID         rid /* = 0*/)               // [IN] Optional rid to be ignored.
{
    HRESULT hr;
    GenericParamConstraintRec *pRecord;
    mdGenericParam     tkOwnerTmp;
    mdToken     tkConstraintTmp;
    ULONG       cGenericParamConstraints;

    ULONG       i;

    _ASSERTE(pGenericParamConstraint);

    cGenericParamConstraints = pMiniMd->getCountGenericParamConstraints();

    // linear scan through the GenericParam table
    for (i=1; i <= cGenericParamConstraints; ++i)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetGenericParamConstraintRecord(i, &pRecord));
        
        tkOwnerTmp = pMiniMd->getOwnerOfGenericParamConstraint(pRecord);
        tkConstraintTmp = pMiniMd->getConstraintOfGenericParamConstraint(pRecord);

        if ((tkOwnerTmp != tkOwner) || (tkConstraintTmp != tkConstraint))
            continue;
        
        //  Matching record found.
        *pGenericParamConstraint = TokenFromRid(i, mdtGenericParamConstraint);
        return S_OK;
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindGenericParamConstraintByOwnerAndConstraint()

//*******************************************************************************
// Find the GenericParam by owner and name or number
//*******************************************************************************
//<REVISIT_TODO> @GENERICS: todo: look in hashtable (cf. MetaModelRW.cpp) if necessary </REVISIT_TODO>
HRESULT ImportHelper::FindGenericParamByOwner(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    mdToken     tkOwner,                    // [IN] GenericParam Owner
    LPCUTF8     szUTF8Name,                 // [IN] GeneriParam Name, may be NULL if not used for search
    ULONG       *pNumber,                   // [IN] GeneriParam Number, may be NULL if not used for search
    mdGenericParam *pGenericParam,          // [OUT] Put the GenericParam token here.
    RID         rid /* = 0*/)               // [IN] Optional rid to be ignored.
{
    HRESULT          hr;
    GenericParamRec *pRecord;
    mdToken     tkOwnerTmp;
    ULONG       cGenericParams;
    LPCUTF8     szCurName;
    ULONG       curNumber;
    ULONG       i;

    _ASSERTE(pGenericParam);

    cGenericParams = pMiniMd->getCountGenericParams();

    // linear scan through the GenericParam table
    for (i=1; i <= cGenericParams; ++i)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetGenericParamRecord(i, &pRecord));
        
        tkOwnerTmp = pMiniMd->getOwnerOfGenericParam(pRecord);
        if ( tkOwnerTmp != tkOwner)
            continue;

        // if the name is significant, try to match it
        if (szUTF8Name)
        {
            IfFailRet(pMiniMd->getNameOfGenericParam(pRecord, &szCurName));
            if (strcmp(szCurName, szUTF8Name))
                continue;
        }

        // if the number is significant, try to match it
        if (pNumber)
        {  curNumber = pMiniMd->getNumberOfGenericParam(pRecord);
           if (*pNumber != curNumber)
               continue;
        }

        //  Matching record found.
        *pGenericParam = TokenFromRid(i, mdtGenericParam);
        return S_OK;
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindGenericParamByOwner()

//*******************************************************************************
// Find a Method given a parent, name and signature.
//*******************************************************************************
HRESULT ImportHelper::FindMethod(
    CMiniMdRW *     pMiniMd,                        // [IN] the minimd to lookup
    mdTypeDef       td,                             // [IN] parent.
    LPCUTF8         szName,                         // [IN] MethodDef name.
    PCCOR_SIGNATURE pSig,                           // [IN] Signature.
    ULONG           cbSig,                          // [IN] Size of signature.
    mdMethodDef *   pmb,                            // [OUT] Put the MethodDef token here.
    RID             rid,                // = 0      // [IN] Optional rid to be ignored.
    PSIGCOMPARE     pSignatureCompare,  // = NULL   // [IN] Optional Routine to compare signatures
    void *          pCompareContext)    // = NULL   // [IN] Optional context for the compare function
{
    HRESULT     hr = S_OK;
    ULONG       ridStart;               // Start of td's methods.
    ULONG       ridEnd;                 // End of td's methods.
    ULONG       index;                  // Loop control.
    TypeDefRec  *pRec;                  // A TypeDef Record.
    MethodRec   *pMethod;               // A MethodDef Record.
    LPCUTF8     szNameUtf8Tmp;          // A found MethodDef's name.
    PCCOR_SIGNATURE pSigTmp;            // A found MethodDef's signature.
    ULONG       cbSigTmp;               // Size of a found MethodDef's signature.
    PCCOR_SIGNATURE pvSigTemp = pSig;   // For use in parsing a signature.
    CQuickBytes qbSig;                  // Struct to build a non-varargs signature.
    CMiniMdRW::HashSearchResult rtn;

    if (cbSig)
    {   // check to see if this is a vararg signature
        if (isCallConv(CorSigUncompressCallingConv(pvSigTemp), IMAGE_CEE_CS_CALLCONV_VARARG))
        {   // Get the fix part of VARARG signature
            IfFailGo(_GetFixedSigOfVarArg(pSig, cbSig, &qbSig, &cbSig));
            pSig = (PCCOR_SIGNATURE) qbSig.Ptr();
        }
    }

    *pmb = TokenFromRid(rid, mdtMethodDef); // to know what to ignore
    rtn = pMiniMd->FindMemberDefFromHash(td, szName, pSig, cbSig, pmb);
    if (rtn == CMiniMdRW::Found)
    {
        goto ErrExit;
    }
    else if (rtn == CMiniMdRW::NotFound)
    {
        IfFailGo(CLDB_E_RECORD_NOTFOUND);
    }
    _ASSERTE(rtn == CMiniMdRW::NoTable);
    
    *pmb = mdMethodDefNil;

    // get the range of method rids given a typedef
    IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(td), &pRec));
    ridStart = pMiniMd->getMethodListOfTypeDef(pRec);
    IfFailGo(pMiniMd->getEndMethodListOfTypeDef(RidFromToken(td), &ridEnd));
    // Iterate over the methods.
    for (index = ridStart; index < ridEnd; index ++ )
    {
        RID methodRID;
        IfFailGo(pMiniMd->GetMethodRid(index, &methodRID));
        // For the call from Validator ignore the rid passed in.
        if (methodRID != rid)
        {
            // Get the method and its name.
            IfFailGo(pMiniMd->GetMethodRecord(methodRID, &pMethod));
            IfFailGo(pMiniMd->getNameOfMethod(pMethod, &szNameUtf8Tmp));

            // If name matches what was requested...
            if ( strcmp(szNameUtf8Tmp, szName) == 0 )
            {
                if (cbSig && pSig)
                {
                    IfFailGo(pMiniMd->getSignatureOfMethod(pMethod, &pSigTmp, &cbSigTmp));
                    
                    // If the caller did not provide a custom compare routine
                    // then we use memcmp to match the signatures
                    // 
                    if (pSignatureCompare == NULL)
                    {
                        if (cbSigTmp != cbSig || memcmp(pSig, pSigTmp, cbSig))
                            continue;
                    }
                    else
                    {
                        // Call the custom compare routine
                        // 
                        if (!pSignatureCompare(pSigTmp, cbSigTmp, pSig, cbSig, pCompareContext))
                            continue;
                    }
                }
                // Ignore PrivateScope methods.
                if (IsMdPrivateScope(pMiniMd->getFlagsOfMethod(pMethod)))
                    continue;

                // Found method.
                *pmb = TokenFromRid(methodRID, mdtMethodDef);
                goto ErrExit;
            }
        }
    }

    // record not found
    *pmb = mdMethodDefNil;
    hr = CLDB_E_RECORD_NOTFOUND;

ErrExit:
    return hr;
} // ImportHelper::FindMethod

//*******************************************************************************
// Find a Field given a parent, name and signature.
//*******************************************************************************
HRESULT ImportHelper::FindField(
    CMiniMdRW *     pMiniMd,        // [IN] the minimd to lookup
    mdTypeDef       td,             // [IN] parent.
    LPCUTF8         szName,         // [IN] FieldDef name.
    PCCOR_SIGNATURE pSig,           // [IN] Signature.
    ULONG           cbSig,          // [IN] Size of signature.
    mdFieldDef *    pfd,            // [OUT] Put the FieldDef token here.
    RID             rid)    // = 0  // [IN] Optional rid to be ignored.
{
    HRESULT     hr = S_OK;              // A result.
    ULONG       ridStart;               // Start of td's methods.
    ULONG       ridEnd;                 // End of td's methods.
    ULONG       index;                  // Loop control.
    TypeDefRec  *pRec;                  // A TypeDef Record.
    FieldRec    *pField;                // A FieldDef Record.
    LPCUTF8     szNameUtf8Tmp;          // A found FieldDef's name.
    PCCOR_SIGNATURE pSigTmp;            // A found FieldDef's signature.
    ULONG       cbSigTmp;               // Size of a found FieldDef's signature.
    CMiniMdRW::HashSearchResult rtn;

    *pfd = TokenFromRid(rid,mdtFieldDef); // to know what to ignore
    rtn = pMiniMd->FindMemberDefFromHash(td, szName, pSig, cbSig, pfd);
    if (rtn == CMiniMdRW::Found)
    {
        goto ErrExit;
    }
    else if (rtn == CMiniMdRW::NotFound)
    {
        IfFailGo(CLDB_E_RECORD_NOTFOUND);
    }
    _ASSERTE(rtn == CMiniMdRW::NoTable);
    
    *pfd = mdFieldDefNil;

    // get the range of method rids given a typedef
    IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(td), &pRec));
    ridStart = pMiniMd->getFieldListOfTypeDef(pRec);
    IfFailGo(pMiniMd->getEndFieldListOfTypeDef(RidFromToken(td), &ridEnd));

    // Iterate over the methods.
    for (index = ridStart; index < ridEnd; index ++ )
    {
        RID fieldRID;
        IfFailGo(pMiniMd->GetFieldRid(index, &fieldRID));
        // For the call from Validator ignore the rid passed in.
        if (fieldRID != rid)
        {
            // Get the field and its name.
            IfFailGo(pMiniMd->GetFieldRecord(fieldRID, &pField));
            IfFailGo(pMiniMd->getNameOfField(pField, &szNameUtf8Tmp));
            
            // If name matches what was requested...
            if ( strcmp(szNameUtf8Tmp, szName) == 0 )
            {
                // Check signature if specified.
                if (cbSig && pSig)
                {
                    IfFailGo(pMiniMd->getSignatureOfField(pField, &pSigTmp, &cbSigTmp));
                    if (cbSigTmp != cbSig || memcmp(pSig, pSigTmp, cbSig))
                        continue;
                }
                // Ignore PrivateScope fields.
                if (IsFdPrivateScope(pMiniMd->getFlagsOfField(pField)))
                    continue;
                // Field found.
                *pfd = TokenFromRid(fieldRID, mdtFieldDef);
                goto ErrExit;
            }
        }
    }

    // record not found
    *pfd = mdFieldDefNil;
    hr = CLDB_E_RECORD_NOTFOUND;

ErrExit:
    return hr;
} // ImportHelper::FindField

//*******************************************************************************
// Find a Member given a parent, name and signature.
//*******************************************************************************
HRESULT ImportHelper::FindMember(
    CMiniMdRW *     pMiniMd,    // [IN] the minimd to lookup
    mdTypeDef       td,         // [IN] parent.
    LPCUTF8         szName,     // [IN] Member name.
    PCCOR_SIGNATURE pSig,       // [IN] Signature.
    ULONG           cbSig,      // [IN] Size of signature.
    mdToken *       ptk)        // [OUT] Put the token here.
{
    HRESULT  hr;
    
    if (cbSig == 0)
    {
        Debug_ReportError("Invalid signature size 0.");
        return CLDB_E_INDEX_NOTFOUND;
    }
    
    // determine if it is ref to MethodDef or FieldDef
    if ((pSig[0] & IMAGE_CEE_CS_CALLCONV_MASK) != IMAGE_CEE_CS_CALLCONV_FIELD)
    {
        hr = FindMethod(pMiniMd, td, szName, pSig, cbSig, ptk);
    }
    else
    {
        hr = FindField(pMiniMd, td, szName, pSig, cbSig, ptk);
    }
    
    if (hr == CLDB_E_RECORD_NOTFOUND)
        *ptk = mdTokenNil;
    
    return hr;
} // ImportHelper::FindMember


//*******************************************************************************
// Find the memberref given name, sig, and parent
//*******************************************************************************
HRESULT ImportHelper::FindMemberRef(
    CMiniMdRW *           pMiniMd,              // [IN] the minimd to lookup
    mdToken               tkParent,             // [IN] the parent token
    LPCUTF8               szName,               // [IN] memberref name
    const COR_SIGNATURE * pbSig,                // [IN] Signature.
    ULONG                 cbSig,                // [IN] Size of signature.
    mdMemberRef *         pmr,                  // [OUT] Put the MemberRef token found
    RID                   rid,          // = 0  // [IN] Optional rid to be ignored.
    HashSearchOption      fCreateHash)  // = DoNotCreateHash // [IN] Should we create hash first? (Optimize for multiple calls vs. single isolated call)
{
    ULONG          cMemberRefRecs;
    MemberRefRec * pMemberRefRec;
    LPCUTF8        szNameTmp = 0;
    const COR_SIGNATURE * pbSigTmp; // Signature.
    ULONG          cbSigTmp;        // Size of signature.
    mdToken        tkParentTmp;     // the parent token
    HRESULT        hr = NOERROR;
    CMiniMdRW::HashSearchResult rtn;
    
    if ((szName == NULL) || (pmr == NULL))
    {
        IfFailGo(CLDB_E_RECORD_NOTFOUND);
    }
    
    if (fCreateHash == CreateHash)
    {   // Caller asked for creating hash to optimize for multiple calls
        IfFailGo(pMiniMd->CreateMemberRefHash());
    }
    
    *pmr = TokenFromRid(rid, mdtMemberRef); // to know what to ignore
    rtn = pMiniMd->FindMemberRefFromHash(tkParent, szName, pbSig, cbSig, pmr);
    if (rtn == CMiniMdRW::Found)
    {
        goto ErrExit;
    }
    else if (rtn == CMiniMdRW::NotFound)
    {
        IfFailGo(CLDB_E_RECORD_NOTFOUND);
    }
    _ASSERTE(rtn == CMiniMdRW::NoTable);

    *pmr = mdMemberRefNil;

    cMemberRefRecs = pMiniMd->getCountMemberRefs();

    // Search for the MemberRef
    for (ULONG i = 1; i <= cMemberRefRecs; i++)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailGo(pMiniMd->GetMemberRefRecord(i, &pMemberRefRec));
        if (!IsNilToken(tkParent))
        {
            // given a valid parent
            tkParentTmp = pMiniMd->getClassOfMemberRef(pMemberRefRec);
            if (tkParentTmp != tkParent)
            {
                // if parent is specified and not equal to the current row,
                // try the next row.
                continue;
            }
        }
        if ((szName != NULL) && (*szName != 0))
        {
            // name is specified
            IfFailGo(pMiniMd->getNameOfMemberRef(pMemberRefRec, &szNameTmp));
            if (strcmp(szName, szNameTmp) != 0)
            {
                // Name is not equal. Try next row.
                continue;
            }
        }
        if ((cbSig != 0) && (pbSig != NULL))
        {
            // signature is specifed
            IfFailGo(pMiniMd->getSignatureOfMemberRef(pMemberRefRec, &pbSigTmp, &cbSigTmp));
            if (cbSigTmp != cbSig)
                continue;
            if (memcmp( pbSig, pbSigTmp, cbSig ) != 0)
                continue;
        }

        // we found a match
        *pmr = TokenFromRid(i, mdtMemberRef);
        return S_OK;
    }
    hr = CLDB_E_RECORD_NOTFOUND;
ErrExit:
    return hr;
} // ImportHelper::FindMemberRef



//*******************************************************************************
// Find duplicate StandAloneSig
//*******************************************************************************
HRESULT ImportHelper::FindStandAloneSig(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    const COR_SIGNATURE *pbSig,             // [IN] Signature.
    ULONG       cbSig,                      // [IN] Size of signature.
    mdSignature *psa)                       // [OUT] Put the StandAloneSig token found
{
    HRESULT     hr;
    ULONG       cRecs;
    StandAloneSigRec    *pRec;
    const COR_SIGNATURE *pbSigTmp;          // Signature.
    ULONG       cbSigTmp;                   // Size of signature.


    _ASSERTE(cbSig &&  psa);
    *psa = mdSignatureNil;

    cRecs = pMiniMd->getCountStandAloneSigs();

    // Search for the StandAloneSignature
    for (ULONG i = 1; i <= cRecs; i++)
    {
        IfFailRet(pMiniMd->GetStandAloneSigRecord(i, &pRec));
        IfFailRet(pMiniMd->getSignatureOfStandAloneSig(pRec, &pbSigTmp, &cbSigTmp));
        if (cbSigTmp != cbSig)
            continue;
        if (memcmp( pbSig, pbSigTmp, cbSig ) != 0)
            continue;

        // we found a match
        *psa = TokenFromRid(i, mdtSignature);
        return S_OK;
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindStandAloneSig()

//*******************************************************************************
// Find duplicate TypeSpec
//*******************************************************************************
HRESULT 
ImportHelper::FindTypeSpec(
    CMiniMdRW *           pMiniMd,      // [IN] the minimd to lookup
    const COR_SIGNATURE * pbSig,        // [IN] Signature.
    ULONG                 cbSig,        // [IN] Size of signature.
    mdTypeSpec *          pTypeSpec)    // [OUT] Put the TypeSpec token found
{
    HRESULT       hr;
    ULONG         cRecs;
    TypeSpecRec * pRec;
    const COR_SIGNATURE * pbSigTmp; // Signature.
    ULONG                 cbSigTmp; // Size of signature.
    
    // cbSig can be 0
    _ASSERTE(pTypeSpec != NULL);
    *pTypeSpec = mdSignatureNil;

    cRecs = pMiniMd->getCountTypeSpecs();

    // Search for the TypeSpec
    for (ULONG i = 1; i <= cRecs; i++)
    {
        IfFailRet(pMiniMd->GetTypeSpecRecord(i, &pRec));
        IfFailRet(pMiniMd->getSignatureOfTypeSpec(pRec, &pbSigTmp, &cbSigTmp));
        if (cbSigTmp != cbSig)
            continue;
        if (memcmp(pbSig, pbSigTmp, cbSig) != 0)
            continue;

        // we found a match
        *pTypeSpec = TokenFromRid(i, mdtTypeSpec);
        return S_OK;
    }
    return CLDB_E_RECORD_NOTFOUND;
} // ImportHelper::FindTypeSpec


//*******************************************************************************
// Find the MethodImpl
//*******************************************************************************
HRESULT ImportHelper::FindMethodImpl(
    CMiniMdRW   *pMiniMd,                   // [IN] The MiniMd to lookup.
    mdTypeDef   tkClass,                    // [IN] The parent TypeDef token.
    mdMethodDef tkBody,                     // [IN] Method body token.
    mdMethodDef tkDecl,                     // [IN] Method declaration token.
    RID         *pRid)                      // [OUT] Put the MethodImpl rid here
{
    HRESULT hr;
    MethodImplRec *pMethodImplRec;          // MethodImpl record.
    ULONG       cMethodImplRecs;            // Count of MethodImpl records.
    mdTypeDef   tkClassTmp;                 // Parent TypeDef token.
    mdToken     tkBodyTmp;                  // Method body token.
    mdToken     tkDeclTmp;                  // Method declaration token.

    _ASSERTE(TypeFromToken(tkClass) == mdtTypeDef);
    _ASSERTE(TypeFromToken(tkBody) == mdtMemberRef || TypeFromToken(tkBody) == mdtMethodDef);
    _ASSERTE(TypeFromToken(tkDecl) == mdtMemberRef || TypeFromToken(tkDecl) == mdtMethodDef);
    _ASSERTE(!IsNilToken(tkClass) && !IsNilToken(tkBody) && !IsNilToken(tkDecl));
    
    if (pRid)
        *pRid = 0;

    cMethodImplRecs = pMiniMd->getCountMethodImpls();

    // Search for the MethodImpl.
    for (ULONG i = 1; i <= cMethodImplRecs; i++)
    {
        IfFailRet(pMiniMd->GetMethodImplRecord(i, &pMethodImplRec));

        // match the parent column
        tkClassTmp = pMiniMd->getClassOfMethodImpl(pMethodImplRec);
        if (tkClassTmp != tkClass)
            continue;

        // match the method body column
        tkBodyTmp = pMiniMd->getMethodBodyOfMethodImpl(pMethodImplRec);
        if (tkBodyTmp != tkBody)
            continue;

        // match the method declaration column
        tkDeclTmp = pMiniMd->getMethodDeclarationOfMethodImpl(pMethodImplRec);
        if (tkDeclTmp != tkDecl)
            continue;

        // we found a match
        if (pRid)
            *pRid = i;
        return S_OK;
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindMethodImpl()

//*******************************************************************************
// Find the TypeRef given the fully qualified name and the assembly name
//*******************************************************************************
HRESULT ImportHelper::FindCustomAttributeCtorByName(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup
    LPCUTF8     szAssemblyName,         // [IN] Assembly Name.
    LPCUTF8     szNamespace,            // [IN] TypeRef Namespace.
    LPCUTF8     szName,                 // [IN] TypeRef Name.
    mdTypeDef   *ptk,                   // [OUT] Put the TypeRef token here.
    RID         rid /* = 0*/)           // [IN] Optional rid to be ignored.
{
    HRESULT     hr;
    ULONG       cRecs;                  // Count of records.
    AssemblyRefRec *pRec;               // Current record being looked at.
    LPCUTF8     szTmp;                  // Temp string.
    mdTypeRef   tkCAType;

    cRecs = pMiniMd->getCountAssemblyRefs();
    // Search for the AssemblyRef record.
    for (ULONG i = 1; i <= cRecs; i++)
    {
        IfFailRet(pMiniMd->GetAssemblyRefRecord(i, &pRec));

        IfFailRet(pMiniMd->getNameOfAssemblyRef(pRec, &szTmp));
        if (!strcmp(szTmp, szAssemblyName) &&
            (SUCCEEDED(FindTypeRefByName(pMiniMd, TokenFromRid(i, mdtAssemblyRef), szNamespace, szName, &tkCAType, rid))) && 
            (SUCCEEDED(FindMemberRef(pMiniMd, tkCAType, COR_CTOR_METHOD_NAME, NULL, 0 ,ptk))))
        {
            return S_OK;
        }
    }

    return CLDB_E_RECORD_NOTFOUND;
}

//*******************************************************************************
// Find the TypeRef given the fully qualified name.
//*******************************************************************************
HRESULT ImportHelper::FindTypeRefByName(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup
    mdToken     tkResolutionScope,      // [IN] Resolution scope for the TypeRef.
    LPCUTF8     szNamespace,            // [IN] TypeRef Namespace.
    LPCUTF8     szName,                 // [IN] TypeRef Name.
    mdTypeRef   *ptk,                   // [OUT] Put the TypeRef token here.
    RID         rid /* = 0*/)           // [IN] Optional rid to be ignored.
{
    HRESULT     hr=S_OK;                // A result.
    ULONG       cTypeRefRecs;           // Count of TypeRefs to scan.
    TypeRefRec  *pTypeRefRec;           // A TypeRef record.
    LPCUTF8     szNameTmp;              // A TypeRef's Name.
    LPCUTF8     szNamespaceTmp;         // A TypeRef's Namespace.
    mdToken     tkResTmp;               // TypeRef's resolution scope.
    ULONG       i;                      // Loop control.

    _ASSERTE(szName &&  ptk);
    *ptk = mdTypeRefNil;

    // Treat no namespace as empty string.
    if (!szNamespace)
        szNamespace = "";

    if (pMiniMd->m_pNamedItemHash)
    {
        // If hash is build, go through the hash table
        TOKENHASHENTRY *p;              // Hash entry from chain.
        ULONG       iHash;              // Item's hash value.
        int         pos;                // Position in hash chain.

        // Hash the data.
        iHash = pMiniMd->HashNamedItem(0, szName);

        // Go through every entry in the hash chain looking for ours.
        for (p = pMiniMd->m_pNamedItemHash->FindFirst(iHash, pos);
             p;
             p = pMiniMd->m_pNamedItemHash->FindNext(pos))
        {

            // name hash can hold more than one kind of token
            if (TypeFromToken(p->tok) != (ULONG)mdtTypeRef)
            {
                continue;
            }

            // skip this one if asked
            if (RidFromToken(p->tok) == rid)
                continue;

            IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(p->tok), &pTypeRefRec));
            IfFailGo(pMiniMd->getNamespaceOfTypeRef(pTypeRefRec, &szNamespaceTmp));
            IfFailGo(pMiniMd->getNameOfTypeRef(pTypeRefRec, &szNameTmp));
            if (strcmp(szName, szNameTmp) || strcmp(szNamespace, szNamespaceTmp))
            {
                // if the name space is not equal, then check the next one.
                continue;
            }
            tkResTmp = pMiniMd->getResolutionScopeOfTypeRef(pTypeRefRec);

            if (tkResTmp == tkResolutionScope ||
                (IsNilToken(tkResTmp) && IsNilToken(tkResolutionScope)))
            {
                // we found a match
                *ptk = p->tok;
                return S_OK;
            }
        }
        hr = CLDB_E_RECORD_NOTFOUND;
    } 
    else
    {
        cTypeRefRecs = pMiniMd->getCountTypeRefs();

        // Search for the TypeRef.
        for (i = 1; i <= cTypeRefRecs; i++)
        {
            // For the call from Validator ignore the rid passed in.
            if (i == rid)
                continue;

            IfFailGo(pMiniMd->GetTypeRefRecord(i, &pTypeRefRec));

            // See if the Resolution scopes match.
            tkResTmp = pMiniMd->getResolutionScopeOfTypeRef(pTypeRefRec);
            if (IsNilToken(tkResTmp))
            {
                if (!IsNilToken(tkResolutionScope))
                    continue;
            }
            else if (tkResTmp != tkResolutionScope)
                continue;

            IfFailGo(pMiniMd->getNamespaceOfTypeRef(pTypeRefRec, &szNamespaceTmp));
            if (strcmp(szNamespace, szNamespaceTmp))
                continue;

            IfFailGo(pMiniMd->getNameOfTypeRef(pTypeRefRec, &szNameTmp));
            if (! strcmp(szName, szNameTmp))
            {
                *ptk = TokenFromRid(i, mdtTypeRef);
                return S_OK;
            }
        }
        hr = CLDB_E_RECORD_NOTFOUND;
    }
ErrExit:
    return hr;
} // HRESULT ImportHelper::FindTypeRefByName()


//*******************************************************************************
// Find the ModuleRef given the name, guid and mvid.
//*******************************************************************************
HRESULT ImportHelper::FindModuleRef(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    LPCUTF8     szUTF8Name,                 // [IN] ModuleRef name.
    mdModuleRef *pmur,                      // [OUT] Put the ModuleRef token here.
    RID         rid /* = 0*/)               // [IN] Optional rid to be ignored.
{
    HRESULT     hr;
    ModuleRefRec *pModuleRef;
    ULONG       cModuleRefs;
    LPCUTF8     szCurName;
    ULONG       i;

    _ASSERTE(pmur);
    _ASSERTE(szUTF8Name);

    cModuleRefs = pMiniMd->getCountModuleRefs();

    // linear scan through the ModuleRef table
    for (i=1; i <= cModuleRefs; ++i)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetModuleRefRecord(i, &pModuleRef));

        if (szUTF8Name != NULL)
        {
            IfFailRet(pMiniMd->getNameOfModuleRef(pModuleRef, &szCurName));
            if (strcmp(szCurName, szUTF8Name))
                continue;
        }
        //  Matching record found.
        *pmur = TokenFromRid(i, mdtModuleRef);
        return S_OK;
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindModuleRef()



//*******************************************************************************
// Find the TypeDef given the type and namespace name
//*******************************************************************************
HRESULT 
ImportHelper::FindTypeDefByName(
    CMiniMdRW * pMiniMd,            // [IN] the minimd to lookup
    LPCUTF8     szTypeDefNamespace, // [IN] Full qualified TypeRef name.
    LPCUTF8     szTypeDefName,      // [IN] Full qualified TypeRef name.
    mdToken     tkEnclosingClass,   // [IN] TypeDef/TypeRef/Module for Enclosing class.
    mdTypeDef * ptkTypeDef,         // [OUT] Put the TypeRef token here.
    RID         ridIgnore) // =0    // [IN] Optional rid to be ignored.
{
    ULONG        cTypeDefRecs;
    TypeDefRec * pTypeDefRec;
    LPCUTF8      szName;
    LPCUTF8      szNamespace;
    DWORD        dwFlags;
    HRESULT      hr = S_OK;
    
    _ASSERTE((szTypeDefName != NULL) &&  (ptkTypeDef != NULL));
    _ASSERTE((TypeFromToken(tkEnclosingClass) == mdtTypeDef) || 
             (TypeFromToken(tkEnclosingClass) == mdtTypeRef) || 
             (tkEnclosingClass == TokenFromRid(1, mdtModule)) || 
             IsNilToken(tkEnclosingClass));
    
    *ptkTypeDef = mdTypeDefNil;
    
    cTypeDefRecs = pMiniMd->getCountTypeDefs();
    
    // Treat no namespace as empty string.
    if (szTypeDefNamespace == NULL)
        szTypeDefNamespace = "";
    
    if (tkEnclosingClass == TokenFromRid(1, mdtModule))
    {   // Module scope is the same as no scope (used in .winmd files as TypeRef scope for self-references)
        tkEnclosingClass = mdTokenNil;
    }
    
    // Get TypeDef of the tkEnclosingClass passed in
    if (TypeFromToken(tkEnclosingClass) == mdtTypeRef)
    {
        // Resolve the TypeRef to a TypeDef
        TypeRefRec * pTypeRefRec;
        mdToken      tkResolutionScope;
        LPCUTF8      szTypeRefName;
        LPCUTF8      szTypeRefNamespace;
        
        IfFailRet(pMiniMd->GetTypeRefRecord(RidFromToken(tkEnclosingClass), &pTypeRefRec));
        tkResolutionScope = pMiniMd->getResolutionScopeOfTypeRef(pTypeRefRec);
        IfFailRet(pMiniMd->getNameOfTypeRef(pTypeRefRec, &szTypeRefName));
        IfFailRet(pMiniMd->getNamespaceOfTypeRef(pTypeRefRec, &szTypeRefNamespace));
        
        if (tkEnclosingClass == tkResolutionScope && !strcmp(szTypeDefName, szTypeRefName) &&
            ((szTypeDefNamespace == nullptr && szTypeRefNamespace == nullptr) ||
            (szTypeDefNamespace != nullptr && szTypeRefNamespace != nullptr && !strcmp(szTypeDefNamespace, szTypeRefNamespace))))
        {
            //
            // This defensive workaround works around a feature of DotFuscator that adds a bad type-ref
            // which causes tools like ILDASM to crash.  The type-ref's parent is set to itself
            // which causes this function to recurse infinitely. A side-effect is that during Ngen we
            // parse all the type-refs in an assembly and Ngen also hangs infinitely.
            // This workaround is necessary because several popular gaming libraries experience hangs
            // and we need binary compatibility in Apollo.
            //
            return CLDB_E_FILE_CORRUPT;
        }
        
        // Update tkEnclosingClass to TypeDef
        IfFailRet(FindTypeDefByName(
                    pMiniMd, 
                    szTypeRefNamespace, 
                    szTypeRefName, 
                    (TypeFromToken(tkResolutionScope) == mdtTypeRef) ? tkResolutionScope : mdTokenNil, 
                    &tkEnclosingClass));
        _ASSERTE(TypeFromToken(tkEnclosingClass) == mdtTypeDef);
    }
    
    // Search for the TypeDef
    for (ULONG i = 1; i <= cTypeDefRecs; i++)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == ridIgnore)
            continue;
        
        IfFailRet(pMiniMd->GetTypeDefRecord(i, &pTypeDefRec));
        
        dwFlags = pMiniMd->getFlagsOfTypeDef(pTypeDefRec);
        
        if (!IsTdNested(dwFlags) && !IsNilToken(tkEnclosingClass))
        {
            // If the class is not Nested and EnclosingClass passed in is not nil
            continue;
        }
        else if (IsTdNested(dwFlags) && IsNilToken(tkEnclosingClass))
        {
            // If the class is nested and EnclosingClass passed is nil
            continue;
        }
        else if (!IsNilToken(tkEnclosingClass))
        {
            _ASSERTE(TypeFromToken(tkEnclosingClass) == mdtTypeDef);
            
            RID              iNestedClassRec;
            NestedClassRec * pNestedClassRec;
            mdTypeDef        tkEnclosingClassTmp;
            
            IfFailRet(pMiniMd->FindNestedClassHelper(TokenFromRid(i, mdtTypeDef), &iNestedClassRec));
            if (InvalidRid(iNestedClassRec))
                continue;
            IfFailRet(pMiniMd->GetNestedClassRecord(iNestedClassRec, &pNestedClassRec));
            tkEnclosingClassTmp = pMiniMd->getEnclosingClassOfNestedClass(pNestedClassRec);
            if (tkEnclosingClass != tkEnclosingClassTmp)
                continue;
        }
        
        IfFailRet(pMiniMd->getNameOfTypeDef(pTypeDefRec, &szName));
        if (strcmp(szTypeDefName, szName) == 0)
        {
            IfFailRet(pMiniMd->getNamespaceOfTypeDef(pTypeDefRec, &szNamespace));
            if (strcmp(szTypeDefNamespace, szNamespace) == 0)
            {
                *ptkTypeDef = TokenFromRid(i, mdtTypeDef);
                return S_OK;
            }
        }
    }
    return CLDB_E_RECORD_NOTFOUND;
} // ImportHelper::FindTypeDefByName

//*******************************************************************************
// Find the InterfaceImpl given the typedef and implemented interface
//*******************************************************************************
HRESULT ImportHelper::FindInterfaceImpl(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup
    mdToken     tkClass,                // [IN] TypeDef of the type
    mdToken     tkInterface,            // [IN] could be typedef/typeref
    mdInterfaceImpl *ptk,               // [OUT] Put the interface token here.
    RID         rid /* = 0*/)           // [IN] Optional rid to be ignored.
{
    HRESULT hr;
    ULONG       ridStart, ridEnd;
    ULONG       i;
    InterfaceImplRec    *pInterfaceImplRec;

    _ASSERTE(ptk);
    *ptk = mdInterfaceImplNil;
    if ( pMiniMd->IsSorted(TBL_InterfaceImpl) )
    {
        IfFailRet(pMiniMd->getInterfaceImplsForTypeDef(RidFromToken(tkClass), &ridEnd, &ridStart));
    }
    else
    {
        ridStart = 1;
        ridEnd = pMiniMd->getCountInterfaceImpls() + 1;
    }

    // Search for the interfaceimpl
    for (i = ridStart; i < ridEnd; i++)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetInterfaceImplRecord(i, &pInterfaceImplRec));
        if ( tkClass != pMiniMd->getClassOfInterfaceImpl(pInterfaceImplRec) )
            continue;
        if ( tkInterface == pMiniMd->getInterfaceOfInterfaceImpl(pInterfaceImplRec) )
        {
            *ptk = TokenFromRid(i, mdtInterfaceImpl);
            return S_OK;
        }
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindInterfaceImpl()



//*******************************************************************************
// Find the Permission by parent and action
//*******************************************************************************
HRESULT ImportHelper::FindPermission(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup
    mdToken     tkParent,               // [IN] Token with the Permission
    USHORT      usAction,               // [IN] The action of the permission
    mdPermission *ppm)                  // [OUT] Put permission token here
{
    HRESULT hr;
    DeclSecurityRec *pRec;
    ULONG       ridStart, ridEnd;
    ULONG       i;
    mdToken     tkParentTmp;

    _ASSERTE(ppm);

    if ( pMiniMd->IsSorted(TBL_DeclSecurity) )
    {

        IfFailRet(pMiniMd->getDeclSecurityForToken(tkParent, &ridEnd, &ridStart));
    }
    else
    {
        ridStart = 1;
        ridEnd = pMiniMd->getCountDeclSecuritys() + 1;
    }
    // loop through all permission
    for (i = ridStart; i < ridEnd; i++)
    {
        IfFailRet(pMiniMd->GetDeclSecurityRecord(i, &pRec));
        tkParentTmp = pMiniMd->getParentOfDeclSecurity(pRec);
        if ( tkParentTmp != tkParent )
            continue;
        if (pRec->GetAction() == usAction)
        {
            *ppm = TokenFromRid(i, mdtPermission);
            return S_OK;
        }
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindPermission()


//*****************************************************************************
// find a property record
//*****************************************************************************
HRESULT ImportHelper::FindProperty(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    mdToken     tkTypeDef,                  // [IN] typedef token
    LPCUTF8     szName,                     // [IN] name of the property
    const COR_SIGNATURE *pbSig,             // [IN] Signature.
    ULONG       cbSig,                      // [IN] Size of signature.
    mdProperty  *ppr)                       // [OUT] Property token
{
    HRESULT     hr;
    RID         ridPropertyMap;
    PropertyMapRec *pPropertyMapRec;
    PropertyRec *pRec;
    ULONG       ridStart;
    ULONG       ridEnd;
    ULONG       i;
    LPCUTF8     szNameTmp;
    PCCOR_SIGNATURE pbSigTmp;
    ULONG       cbSigTmp;
    ULONG       pr;

    IfFailRet(pMiniMd->FindPropertyMapFor(RidFromToken(tkTypeDef), &ridPropertyMap));
    if ( !InvalidRid(ridPropertyMap) )
    {
        IfFailRet(pMiniMd->GetPropertyMapRecord(ridPropertyMap, &pPropertyMapRec));
        ridStart = pMiniMd->getPropertyListOfPropertyMap(pPropertyMapRec);
        IfFailRet(pMiniMd->getEndPropertyListOfPropertyMap(ridPropertyMap, &ridEnd));

        for (i = ridStart; i < ridEnd; i++)
        {
            // get the property rid
            IfFailRet(pMiniMd->GetPropertyRid(i, &pr));
            IfFailRet(pMiniMd->GetPropertyRecord(pr, &pRec));
            IfFailRet(pMiniMd->getNameOfProperty(pRec, &szNameTmp));
            IfFailRet(pMiniMd->getTypeOfProperty(pRec, &pbSigTmp, &cbSigTmp));
            if ( strcmp (szName, szNameTmp) != 0 )
                continue;
            if ( cbSig != 0 && (cbSigTmp != cbSig || memcmp(pbSig, pbSigTmp, cbSig) != 0 ) )
                continue;
            *ppr = TokenFromRid( i, mdtProperty );
            return S_OK;
        }
        return CLDB_E_RECORD_NOTFOUND;
    }
    else
    {
        return CLDB_E_RECORD_NOTFOUND;
    }
} // HRESULT ImportHelper::FindProperty()




//*****************************************************************************
// find an Event record
//*****************************************************************************
HRESULT ImportHelper::FindEvent(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    mdToken     tkTypeDef,                  // [IN] typedef token
    LPCUTF8     szName,                     // [IN] name of the event
    mdProperty  *pev)                       // [OUT] Event token
{
    HRESULT     hr;
    RID         ridEventMap;
    EventMapRec *pEventMapRec;
    EventRec    *pRec;
    ULONG       ridStart;
    ULONG       ridEnd;
    ULONG       i;
    LPCUTF8     szNameTmp;
    ULONG       ev;

    IfFailRet(pMiniMd->FindEventMapFor(RidFromToken(tkTypeDef), &ridEventMap));
    if ( !InvalidRid(ridEventMap) )
    {
        IfFailRet(pMiniMd->GetEventMapRecord(ridEventMap, &pEventMapRec));
        ridStart = pMiniMd->getEventListOfEventMap(pEventMapRec);
        IfFailRet(pMiniMd->getEndEventListOfEventMap(ridEventMap, &ridEnd));

        for (i = ridStart; i < ridEnd; i++)
        {
            // get the Event rid
            IfFailRet(pMiniMd->GetEventRid(i, &ev));

            // get the event row
            IfFailRet(pMiniMd->GetEventRecord(ev, &pRec));
            IfFailRet(pMiniMd->getNameOfEvent(pRec, &szNameTmp));
            if ( strcmp (szName, szNameTmp) == 0)
            {
                *pev = TokenFromRid( ev, mdtEvent );
                return S_OK;
            }
        }
        return CLDB_E_RECORD_NOTFOUND;
    }
    else
    {
        return CLDB_E_RECORD_NOTFOUND;
    }
} // HRESULT ImportHelper::FindEvent()



//*****************************************************************************
// find an custom value record given by parent and type token. This will always return
// the first one that is found regardless duplicated.
//*****************************************************************************
HRESULT ImportHelper::FindCustomAttributeByToken(
    CMiniMdRW   *pMiniMd,                   // [IN] the minimd to lookup
    mdToken     tkParent,                   // [IN] the parent that custom value is associated with
    mdToken     tkType,                     // [IN] type of the CustomAttribute
    const void  *pCustBlob,                 // [IN] custom attribute blob
    ULONG       cbCustBlob,                 // [IN] size of the blob.
    mdCustomAttribute *pcv)                 // [OUT] CustomAttribute token
{
    HRESULT     hr;
    CustomAttributeRec  *pRec;
    ULONG       ridStart, ridEnd;
    ULONG       i;
    mdToken     tkParentTmp;
    mdToken     tkTypeTmp;
    const void  *pCustBlobTmp;
    ULONG       cbCustBlobTmp;

    _ASSERTE(pcv);
    *pcv = mdCustomAttributeNil;
    if ( pMiniMd->IsSorted(TBL_CustomAttribute) )
    {
        IfFailRet(pMiniMd->FindCustomAttributeFor(
            RidFromToken(tkParent), 
            TypeFromToken(tkParent), 
            tkType, 
            (RID *)pcv));
        if (InvalidRid(*pcv))
        {
            return S_FALSE;
        }
        else if (pCustBlob)
        {
            IfFailRet(pMiniMd->GetCustomAttributeRecord(RidFromToken(*pcv), &pRec));
            IfFailRet(pMiniMd->getValueOfCustomAttribute(pRec, (const BYTE **)&pCustBlobTmp, &cbCustBlobTmp));
            if (cbCustBlob == cbCustBlobTmp &&
                !memcmp(pCustBlob, pCustBlobTmp, cbCustBlob))
                {
                    return S_OK;
                }
        }
        else
        {
            return S_OK;
        }
    }
    else
    {
        CLookUpHash *pHashTable = pMiniMd->m_pLookUpHashs[TBL_CustomAttribute];

        if (pHashTable)
        {
            // table is not sorted but hash is built
            // We want to create dynmaic array to hold the dynamic enumerator.
            TOKENHASHENTRY *p;
            ULONG       iHash;
            int         pos;

            // Hash the data.
            iHash = pMiniMd->HashCustomAttribute(tkParent);

            // Go through every entry in the hash chain looking for ours.
            for (p = pHashTable->FindFirst(iHash, pos);
                 p;
                 p = pHashTable->FindNext(pos))
            {
                IfFailRet(pMiniMd->GetCustomAttributeRecord(RidFromToken(p->tok), &pRec));

                tkParentTmp = pMiniMd->getParentOfCustomAttribute(pRec);
                if (tkParentTmp != tkParent)
                    continue;

                tkTypeTmp = pMiniMd->getTypeOfCustomAttribute(pRec);
                if (tkType != tkTypeTmp)
                    continue;
                if (pCustBlob != NULL)
                {
                    IfFailRet(pMiniMd->getValueOfCustomAttribute(pRec, (const BYTE **)&pCustBlobTmp, &cbCustBlobTmp));
                    if (cbCustBlob == cbCustBlobTmp &&
                        !memcmp(pCustBlob, pCustBlobTmp, cbCustBlob))
                    {
                        *pcv = TokenFromRid(p->tok, mdtCustomAttribute);
                        return S_OK;
                    }
                }
                else
                    return S_OK;
            }
        }
        else
        {
            // linear scan
            ridStart = 1;
            ridEnd = pMiniMd->getCountCustomAttributes() + 1;

            // loop through all custom values
            for (i = ridStart; i < ridEnd; i++)
            {
                IfFailRet(pMiniMd->GetCustomAttributeRecord(i, &pRec));

                tkParentTmp = pMiniMd->getParentOfCustomAttribute(pRec);
                if ( tkParentTmp != tkParent )
                    continue;

                tkTypeTmp = pMiniMd->getTypeOfCustomAttribute(pRec);
                if (tkType != tkTypeTmp)
                    continue;

                if (pCustBlob != NULL)
                {
                    IfFailRet(pMiniMd->getValueOfCustomAttribute(pRec, (const BYTE **)&pCustBlobTmp, &cbCustBlobTmp));
                    if (cbCustBlob == cbCustBlobTmp &&
                        !memcmp(pCustBlob, pCustBlobTmp, cbCustBlob))
                    {
                        *pcv = TokenFromRid(i, mdtCustomAttribute);
                        return S_OK;
                    }
                }
                else
                    return S_OK;
            }
        }
        // fall through
    }
    return S_FALSE;
} // ImportHelper::FindCustomAttributeByToken

//*****************************************************************************
// Helper function to lookup and retrieve a CustomAttribute.
//*****************************************************************************
HRESULT ImportHelper::GetCustomAttributeByName( // S_OK or error.
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup
    mdToken     tkObj,                  // [IN] Object with Custom Attribute.
    LPCUTF8     szName,                 // [IN] Name of desired Custom Attribute.
    const void  **ppData,               // [OUT] Put pointer to data here.
    ULONG       *pcbData)               // [OUT] Put size of data here.
{
    return pMiniMd->CommonGetCustomAttributeByName(tkObj, szName, ppData, pcbData);
}   // ImportHelper::GetCustomAttributeByName

#ifdef FEATURE_METADATA_EMIT

//*******************************************************************************
// Find an AssemblyRef record given the name.
//*******************************************************************************
HRESULT ImportHelper::FindAssemblyRef(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup.
    LPCUTF8     szName,                 // [IN] Name.
    LPCUTF8     szLocale,               // [IN] Locale.
    const void  *pbPublicKeyOrToken,    // [IN] Public key or token (based on flags).
    ULONG       cbPublicKeyOrToken,     // [IN] Byte count of public key or token.
    USHORT      usMajorVersion,         // [IN] Major version.
    USHORT      usMinorVersion,         // [IN] Minor version.
    USHORT      usBuildNumber,          // [IN] Build number.
    USHORT      usRevisionNumber,       // [IN] Revision number.
    DWORD       dwFlags,                // [IN] Flags.
    mdAssemblyRef *pmar)                // [OUT] returned AssemblyRef token.
{
    HRESULT     hr;
    ULONG       cRecs;                  // Count of records.
    AssemblyRefRec *pRec;               // Current record being looked at.
    LPCUTF8     szTmp;                  // Temp string.
    const void  *pbTmp;                 // Temp blob.
    ULONG       cbTmp;                  // Temp byte count.
    DWORD       dwTmp;                  // Temp flags.
    const void  *pbToken = NULL;        // Token version of public key.
    ULONG       cbToken = 0;            // Count of bytes in token.
#if !defined(FEATURE_METADATA_EMIT_IN_DEBUGGER) || defined(DACCESS_COMPILE)
    const void  *pbTmpToken;            // Token version of public key.
    ULONG       cbTmpToken;             // Count of bytes in token.
    bool        fMatch;                 // Did public key or tokens match?
#endif // !FEATURE_METADATA_EMIT_IN_DEBUGGER || DACCESS_COMPILE

    // Handle special cases upfront.
    if (!szLocale)
        szLocale = "";
    if (!pbPublicKeyOrToken)
        cbPublicKeyOrToken = 0;

    if (!IsAfPublicKey(dwFlags))
    {
        pbToken = pbPublicKeyOrToken;
        cbToken = cbPublicKeyOrToken;
    }

    _ASSERTE(pMiniMd && szName && pmar);
    *pmar = 0;

    cRecs = pMiniMd->getCountAssemblyRefs();

    // Search for the AssemblyRef record.
    for (ULONG i = 1; i <= cRecs; i++)
    {
        IfFailRet(pMiniMd->GetAssemblyRefRecord(i, &pRec));

        IfFailRet(pMiniMd->getNameOfAssemblyRef(pRec, &szTmp));
        if (strcmp(szTmp, szName))
            continue;

        IfFailRet(pMiniMd->getLocaleOfAssemblyRef(pRec, &szTmp));
        if (strcmp(szTmp, szLocale))
            continue;

        if (pRec->GetMajorVersion() != usMajorVersion)
            continue;
        if (pRec->GetMinorVersion() != usMinorVersion)
            continue;

        // We'll "unify" all versions of mscorlib and Microsoft.VisualC... so if this
        // is one of those, we won't do the version check beyond the major/minor

        LPCUTF8 szAssemblyRefName;
        IfFailRet(pMiniMd->getNameOfAssemblyRef(pRec, &szAssemblyRefName));
        if (SString::_stricmp(szAssemblyRefName, "mscorlib") && 
            SString::_stricmp(szAssemblyRefName, "microsoft.visualc"))
        {
            if (pRec->GetBuildNumber() != usBuildNumber)
                continue;
            if (pRec->GetRevisionNumber() != usRevisionNumber)
                continue;
        }

        IfFailRet(pMiniMd->getPublicKeyOrTokenOfAssemblyRef(pRec, (const BYTE **)&pbTmp, &cbTmp));

        if ((cbPublicKeyOrToken && !cbTmp) ||
            (!cbPublicKeyOrToken && cbTmp))
            continue;

        if (cbTmp)
        {
            // Either ref may be using either a full public key or a token
            // (determined by the ref flags). Must cope with all variations.
            dwTmp = pMiniMd->getFlagsOfAssemblyRef(pRec);
            if (IsAfPublicKey(dwTmp) == IsAfPublicKey(dwFlags))
            {
                // Easy case, they're both in the same form.
                if (cbTmp != cbPublicKeyOrToken || memcmp(pbTmp, pbPublicKeyOrToken, cbTmp))
                    continue;
            }
            else if (IsAfPublicKey(dwTmp))
            {
#if defined(FEATURE_METADATA_EMIT_IN_DEBUGGER) && !defined(DACCESS_COMPILE)
                return E_FAIL;
#else //!FEATURE_METADATA_EMIT_IN_DEBUGGER || DACCESS_COMPILE
                // Need to compress target public key to see if it matches.
                if (!StrongNameTokenFromPublicKey((BYTE*)pbTmp,
                                                  cbTmp,
                                                  (BYTE**)&pbTmpToken,
                                                  &cbTmpToken))
                {
                    return StrongNameErrorInfo();
                }
                fMatch = cbTmpToken == cbPublicKeyOrToken && !memcmp(pbTmpToken, pbPublicKeyOrToken, cbTmpToken);
                StrongNameFreeBuffer((BYTE*)pbTmpToken);
                if (!fMatch)
                    continue;
#endif //!FEATURE_METADATA_EMIT_IN_DEBUGGER || DACCESS_COMPILE
            }
            else
            {
                // Need to compress out public key to see if it matches. We
                // cache the result of this for further iterations.
                if (!pbToken)
                {
#if defined(FEATURE_METADATA_EMIT_IN_DEBUGGER) && !defined(DACCESS_COMPILE)
                    return E_FAIL;
#else //!FEATURE_METADATA_EMIT_IN_DEBUGGER || DACCESS_COMPILE
                    if (!StrongNameTokenFromPublicKey((BYTE*)pbPublicKeyOrToken,
                                                      cbPublicKeyOrToken,
                                                      (BYTE**)&pbToken,
                                                      &cbToken))
                    {
                        return StrongNameErrorInfo();
                    }
#endif //!FEATURE_METADATA_EMIT_IN_DEBUGGER || DACCESS_COMPILE
                }
                if (cbTmp != cbToken || memcmp(pbTmp, pbToken, cbToken))
                    continue;
            }
        }

        if (pbToken && IsAfPublicKey(dwFlags))
        {
#if !defined(FEATURE_METADATA_EMIT_IN_DEBUGGER) || defined(DACCESS_COMPILE)
            StrongNameFreeBuffer((BYTE*)pbToken);
#endif
        }
        *pmar = TokenFromRid(i, mdtAssemblyRef);
        return S_OK;
    }
    if (pbToken && IsAfPublicKey(dwFlags))
    {
#if !defined(FEATURE_METADATA_EMIT_IN_DEBUGGER) || defined(DACCESS_COMPILE)
        StrongNameFreeBuffer((BYTE*)pbToken);
#endif
    }
    return CLDB_E_RECORD_NOTFOUND;
} // ImportHelper::FindAssemblyRef

//*******************************************************************************
// Find a File record given the name.
//*******************************************************************************
HRESULT ImportHelper::FindFile(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup.
    LPCUTF8     szName,                 // [IN] name for the File.
    mdFile      *pmf,                   // [OUT] returned File token.
    RID         rid /* = 0 */)          // [IN] Optional rid to be ignored.
{
    HRESULT     hr;
    ULONG       cRecs;                  // Count of records.
    FileRec     *pRec;                  // Current record being looked at.

    LPCUTF8     szNameTmp;

    _ASSERTE(pMiniMd && szName && pmf);
    *pmf = 0;

    cRecs = pMiniMd->getCountFiles();

    // Search for the File record.
    for (ULONG i = 1; i <= cRecs; i++)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetFileRecord(i, &pRec));

        IfFailRet(pMiniMd->getNameOfFile(pRec, &szNameTmp));
        if (!strcmp(szNameTmp, szName))
        {
            *pmf = TokenFromRid(i, mdtFile);
            return S_OK;
        }
    }
    return CLDB_E_RECORD_NOTFOUND;
} // ImportHelper::FindFile

#endif //FEATURE_METADATA_EMIT

//*******************************************************************************
// Find a ExportedType record given the name.
//*******************************************************************************
HRESULT ImportHelper::FindExportedType(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup.
    LPCUTF8     szNamespace,            // [IN] namespace for the ExportedType.
    LPCUTF8     szName,                 // [IN] name for the ExportedType.
    mdExportedType   tkEnclosingType,        // [IN] token for the enclosing type.
    mdExportedType   *pmct,                  // [OUT] returned ExportedType token.
    RID         rid /* = 0 */)          // [IN] Optional rid to be ignored.
{
    HRESULT     hr;
    ULONG       cRecs;                  // Count of records.
    ExportedTypeRec  *pRec;                  // Current record being looked at.
    mdToken     tkImpl;
    LPCUTF8     szNamespaceTmp;
    LPCUTF8     szNameTmp;

    _ASSERTE(pMiniMd && szName && pmct);
    *pmct = 0;

    // Treat no namespace as empty string.
    if (!szNamespace)
        szNamespace = "";

    cRecs = pMiniMd->getCountExportedTypes();

    // Search for the ExportedType record.
    for (ULONG i = 1; i <= cRecs; i++)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetExportedTypeRecord(i, &pRec));

        // Handle the case of nested vs. non-nested classes.
        tkImpl = pMiniMd->getImplementationOfExportedType(pRec);
        if (TypeFromToken(tkImpl) == mdtExportedType && !IsNilToken(tkImpl))
        {
            // Current ExportedType being looked at is a nested type, so
            // comparing the implementation token.
            if (tkImpl != tkEnclosingType)
                continue;
        }
        else if (TypeFromToken(tkEnclosingType) == mdtExportedType &&
                 !IsNilToken(tkEnclosingType))
        {
            // ExportedType passed in is nested but the current ExportedType is not.
            continue;
        }

        IfFailRet(pMiniMd->getTypeNamespaceOfExportedType(pRec, &szNamespaceTmp));
        if (strcmp(szNamespaceTmp, szNamespace))
            continue;

        IfFailRet(pMiniMd->getTypeNameOfExportedType(pRec, &szNameTmp));
        if (!strcmp(szNameTmp, szName))
        {
            *pmct = TokenFromRid(i, mdtExportedType);
            return S_OK;
        }
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindExportedType()

//*******************************************************************************
// Find a ManifestResource record given the name.
//*******************************************************************************
HRESULT ImportHelper::FindManifestResource(
    CMiniMdRW   *pMiniMd,               // [IN] the minimd to lookup.
    LPCUTF8     szName,                 // [IN] name for the ManifestResource.
    mdManifestResource *pmmr,           // [OUT] returned ManifestResource token.
    RID         rid /* = 0 */)          // [IN] Optional rid to be ignored.
{
    HRESULT     hr;
    ULONG       cRecs;                  // Count of records.
    ManifestResourceRec *pRec;          // Current record being looked at.

    LPCUTF8     szNameTmp;

    _ASSERTE(pMiniMd && szName && pmmr);
    *pmmr = 0;

    cRecs = pMiniMd->getCountManifestResources();

    // Search for the ManifestResource record.
    for (ULONG i = 1; i <= cRecs; i++)
    {
        // For the call from Validator ignore the rid passed in.
        if (i == rid)
            continue;

        IfFailRet(pMiniMd->GetManifestResourceRecord(i, &pRec));

        IfFailRet(pMiniMd->getNameOfManifestResource(pRec, &szNameTmp));
        if (!strcmp(szNameTmp, szName))
        {
            *pmmr = TokenFromRid(i, mdtManifestResource);
            return S_OK;
        }
    }
    return CLDB_E_RECORD_NOTFOUND;
} // HRESULT ImportHelper::FindManifestResource()

#ifdef FEATURE_METADATA_EMIT

//****************************************************************************
// Convert tokens contained in an element type
//****************************************************************************
HRESULT 
ImportHelper::MergeUpdateTokenInFieldSig(
    CMiniMdRW   *pMiniMdAssemEmit,      // [IN] The assembly emit scope.
    CMiniMdRW   *pMiniMdEmit,           // [IN] The emit scope.
    IMetaModelCommon *pCommonAssemImport,// [IN] Assembly scope where the signature is from.
    const void  *pbHashValue,           // [IN] Hash value for the import assembly.
    ULONG       cbHashValue,            // [IN] Size in bytes for the hash value.
    IMetaModelCommon *pCommonImport,    // [IN] The scope to merge into the emit scope.
    PCCOR_SIGNATURE pbSigImp,           // signature from the imported scope
    MDTOKENMAP      *ptkMap,            // Internal OID mapping structure.
    CQuickBytes     *pqkSigEmit,        // [OUT] buffer for translated signature
    ULONG           cbStartEmit,        // [IN] start point of buffer to write to
    ULONG           *pcbImp,            // [OUT] total number of bytes consumed from pbSigImp
    ULONG           *pcbEmit)           // [OUT] total number of bytes write to pqkSigEmit
{

    HRESULT     hr;                     // A result.
    ULONG       cb;                     // count of bytes
    ULONG       cb1;                    // count of bytes
    ULONG       cb2;                    // count of bytes
    ULONG       cbSubTotal;
    ULONG       cbImp;
    ULONG       cbEmit;
    ULONG       cbSrcTotal = 0;         // count of bytes consumed in the imported signature
    ULONG       cbDestTotal = 0;        // count of bytes for the new signature
    ULONG       ulElementType = 0;      // place holder for expanded data
    ULONG       ulData;
    ULONG       ulTemp;
    mdToken     tkRidFrom;              // Original rid
    mdToken     tkRidTo;                // new rid
    int         iData;
    CQuickArray<mdToken> cqaNesters;    // Array of Nester tokens.
    CQuickArray<LPCUTF8> cqaNesterNamespaces;   // Array of Nester Namespaces.
    CQuickArray<LPCUTF8> cqaNesterNames;    // Array of Nester names.

    _ASSERTE(pcbEmit);

    cb = CorSigUncompressData(&pbSigImp[cbSrcTotal], &ulElementType);
    cbSrcTotal += cb;

    // count numbers of modifiers
    while (CorIsModifierElementType((CorElementType) ulElementType))
    {
        cb = CorSigUncompressData(&pbSigImp[cbSrcTotal], &ulElementType);
        cbSrcTotal += cb;
    }

    // copy ELEMENT_TYPE_* over
    cbDestTotal = cbSrcTotal;
    IfFailGo(pqkSigEmit->ReSizeNoThrow(cbStartEmit + cbDestTotal));
    memcpy(((BYTE *)pqkSigEmit->Ptr()) + cbStartEmit, pbSigImp, cbDestTotal);
    switch (ulElementType)
    {
        case ELEMENT_TYPE_SZARRAY:
            // syntax : SZARRAY <BaseType>

            // conver the base type for the SZARRAY or GENERICARRAY
            IfFailGo(MergeUpdateTokenInFieldSig(
                pMiniMdAssemEmit,           // The assembly emit scope.
                pMiniMdEmit,                // The emit scope.
                pCommonAssemImport,         // The assembly scope where the signature is from.
                pbHashValue,                // Hash value for the import assembly.
                cbHashValue,                // Size in bytes for the hash value.
                pCommonImport,              // scope to merge into the emit scope.
                &pbSigImp[cbSrcTotal],      // from the imported scope
                ptkMap,                     // OID mapping structure.
                pqkSigEmit,                 // [OUT] buffer for translated signature
                cbStartEmit + cbDestTotal,  // [IN] start point of buffer to write to
                &cbImp,                     // [OUT] total number of bytes consumed from pbSigImp
                &cbEmit));                  // [OUT] total number of bytes write to pqkSigEmit
            cbSrcTotal += cbImp;
            cbDestTotal += cbEmit;
            break;

        case ELEMENT_TYPE_GENERICINST:
          {
            // syntax : WITH (ELEMENT_TYPE_CLASS | ELEMENT_TYPE_VALUECLASS)  <BaseType>

            IfFailGo(MergeUpdateTokenInFieldSig(
                pMiniMdAssemEmit,           // The assembly emit scope.
                pMiniMdEmit,                // The emit scope.
                pCommonAssemImport,         // The assembly scope where the signature is from.
                pbHashValue,                // Hash value for the import assembly.
                cbHashValue,                // Size in bytes for the hash value.
                pCommonImport,              // scope to merge into the emit scope.
                &pbSigImp[cbSrcTotal],      // from the imported scope
                ptkMap,                     // OID mapping structure.
                pqkSigEmit,                 // [OUT] buffer for translated signature
                cbStartEmit + cbDestTotal,  // [IN] start point of buffer to write to
                &cbImp,                     // [OUT] total number of bytes consumed from pbSigImp
                &cbEmit));                  // [OUT] total number of bytes write to pqkSigEmit
            cbSrcTotal += cbImp;
            cbDestTotal += cbEmit;

            // copy over the number of arguments
            ULONG nargs;
            cb = CorSigUncompressData(&pbSigImp[cbSrcTotal], &nargs);

            IfFailGo(pqkSigEmit->ReSizeNoThrow(cbStartEmit + cbDestTotal + cb));
            cb1 = CorSigCompressData(nargs, ((BYTE *)pqkSigEmit->Ptr()) + cbStartEmit + cbDestTotal);
            _ASSERTE(cb == cb1);

            cbSrcTotal += cb;
            cbDestTotal += cb1;

            for (ULONG narg = 0; narg < nargs; narg++) {
                IfFailGo(MergeUpdateTokenInFieldSig(
                    pMiniMdAssemEmit,           // The assembly emit scope.
                    pMiniMdEmit,                // The emit scope.
                    pCommonAssemImport,         // The assembly scope where the signature is from.
                    pbHashValue,                // Hash value for the import assembly.
                    cbHashValue,                // Size in bytes for the hash value.
                    pCommonImport,              // The scope to merge into the emit scope.
                    &pbSigImp[cbSrcTotal],      // signature from the imported scope
                    ptkMap,                     // Internal OID mapping structure.
                    pqkSigEmit,                 // [OUT] buffer for translated signature
                    cbStartEmit + cbDestTotal,  // [IN] start point of buffer to write to
                    &cbImp,                     // [OUT] total number of bytes consumed from pbSigImp
                    &cbEmit));                  // [OUT] total number of bytes write to pqkSigEmit
                cbSrcTotal += cbImp;
                cbDestTotal += cbEmit;
            }
         }

         break;

        case ELEMENT_TYPE_MVAR:
        case ELEMENT_TYPE_VAR:
            // syntax : VAR <n>
            // syntax : MVAR <n>

            // after the VAR or MVAR there is an integer indicating which type variable
            //
            cb = CorSigUncompressData(&pbSigImp[cbSrcTotal], &ulData);

            IfFailGo(pqkSigEmit->ReSizeNoThrow(cbStartEmit + cbDestTotal + cb));
            cb1 = CorSigCompressData(ulData, ((BYTE *)pqkSigEmit->Ptr()) + cbStartEmit + cbDestTotal);
            _ASSERTE(cb == cb1);

            cbSrcTotal += cb;
            cbDestTotal += cb1;

            break;

        case ELEMENT_TYPE_ARRAY:
            // syntax : ARRAY BaseType <rank> [i size_1... size_i] [j lowerbound_1 ... lowerbound_j]

            // conver the base type for the MDARRAY
            IfFailGo(MergeUpdateTokenInFieldSig(
                pMiniMdAssemEmit,           // The assembly emit scope.
                pMiniMdEmit,                // The emit scope.
                pCommonAssemImport,         // The assembly scope where the signature is from.
                pbHashValue,                // Hash value for the import assembly.
                cbHashValue,                // Size in bytes for the hash value.
                pCommonImport,              // The scope to merge into the emit scope.
                &pbSigImp[cbSrcTotal],      // signature from the imported scope
                ptkMap,                     // Internal OID mapping structure.
                pqkSigEmit,                 // [OUT] buffer for translated signature
                cbStartEmit + cbSrcTotal,   // [IN] start point of buffer to write to
                &cbImp,                     // [OUT] total number of bytes consumed from pbSigImp
                &cbEmit));                  // [OUT] total number of bytes write to pqkSigEmit
            cbSrcTotal += cbImp;
            cbDestTotal += cbEmit;

            // Parse for the rank
            cbSubTotal = CorSigUncompressData(&pbSigImp[cbSrcTotal], &ulData);

            // if rank == 0, we are done
            if (ulData != 0)
            {
                // any size of dimension specified?
                cb = CorSigUncompressData(&pbSigImp[cbSrcTotal + cbSubTotal], &ulData);
                cbSubTotal += cb;

                while (ulData--)
                {
                    cb = CorSigUncompressData(&pbSigImp[cbSrcTotal + cbSubTotal], &ulTemp);
                    cbSubTotal += cb;
                }

                // any lower bound specified?
                cb = CorSigUncompressData(&pbSigImp[cbSrcTotal + cbSubTotal], &ulData);
                cbSubTotal += cb;

                while (ulData--)
                {
                    cb = CorSigUncompressSignedInt(&pbSigImp[cbSrcTotal + cbSubTotal], &iData);
                    cbSubTotal += cb;
                }
            }

            // cbSubTotal is now the number of bytes still left to move over
            // cbSrcTotal is where bytes start on the pbSigImp to be copied over
            // cbStartEmit + cbDestTotal is where the destination of copy

            IfFailGo(pqkSigEmit->ReSizeNoThrow(cbStartEmit + cbDestTotal + cbSubTotal));
            memcpy(((BYTE *)pqkSigEmit->Ptr())+cbStartEmit + cbDestTotal, &pbSigImp[cbSrcTotal], cbSubTotal);

            cbSrcTotal = cbSrcTotal + cbSubTotal;
            cbDestTotal = cbDestTotal + cbSubTotal;

            break;
        case ELEMENT_TYPE_FNPTR:
            // function pointer is followed by another complete signature
            IfFailGo(MergeUpdateTokenInSig(
                pMiniMdAssemEmit,           // The assembly emit scope.
                pMiniMdEmit,                // The emit scope.
                pCommonAssemImport,         // The assembly scope where the signature is from.
                pbHashValue,                // Hash value for the import assembly.
                cbHashValue,                // Size in bytes for the hash value.
                pCommonImport,              // The scope to merge into the emit scope.
                &pbSigImp[cbSrcTotal],      // signature from the imported scope
                ptkMap,                     // Internal OID mapping structure.
                pqkSigEmit,                 // [OUT] buffer for translated signature
                cbStartEmit + cbDestTotal,  // [IN] start point of buffer to write to
                &cbImp,                     // [OUT] total number of bytes consumed from pbSigImp
                &cbEmit));                  // [OUT] total number of bytes write to pqkSigEmit
            cbSrcTotal += cbImp;
            cbDestTotal += cbEmit;
            break;
        case ELEMENT_TYPE_VALUETYPE:
        case ELEMENT_TYPE_CLASS:
        case ELEMENT_TYPE_CMOD_REQD:
        case ELEMENT_TYPE_CMOD_OPT:

            // syntax for CLASS = ELEMENT_TYPE_CLASS <rid>
            // syntax for VALUE_CLASS = ELEMENT_TYPE_VALUECLASS <rid>

            // now get the embedded typeref token
            cb = CorSigUncompressToken(&pbSigImp[cbSrcTotal], &tkRidFrom);

            // Map the ulRidFrom to ulRidTo
            if (ptkMap)
            {
                // mdtBaseType does not record in the map. It is unique across modules
                if ( TypeFromToken(tkRidFrom) == mdtBaseType )
                {
                    tkRidTo = tkRidFrom;
                }
                else
                {
                    IfFailGo( ptkMap->Remap(tkRidFrom, &tkRidTo) );
                }
            }
            else
            {
                // If the token is a TypeDef or a TypeRef, get/create the
                // ResolutionScope for the outermost TypeRef.
                if (TypeFromToken(tkRidFrom) == mdtTypeDef)
                {
                    IfFailGo(ImportTypeDef(pMiniMdAssemEmit,
                                           pMiniMdEmit,
                                           pCommonAssemImport,
                                           pbHashValue,
                                           cbHashValue,
                                           pCommonImport,
                                           tkRidFrom,
                                           true,    // Optimize to TypeDef if emit and import scopes are identical.
                                           &tkRidTo));
                }
                else if (TypeFromToken(tkRidFrom) == mdtTypeRef)
                {
                    IfFailGo(ImportTypeRef(pMiniMdAssemEmit,
                                           pMiniMdEmit,
                                           pCommonAssemImport,
                                           pbHashValue,
                                           cbHashValue,
                                           pCommonImport,
                                           tkRidFrom,
                                           &tkRidTo));
                }
                else if ( TypeFromToken(tkRidFrom) == mdtTypeSpec )
                {
                    // copy over the TypeSpec
                    PCCOR_SIGNATURE pvTypeSpecSig;
                    ULONG           cbTypeSpecSig;
                    CQuickBytes qkTypeSpecSigEmit;
                    ULONG           cbTypeSpecEmit;

                    IfFailGo(pCommonImport->CommonGetTypeSpecProps(
                        tkRidFrom, 
                        &pvTypeSpecSig, 
                        &cbTypeSpecSig));
                    
                                        // Translate the typespec signature before look up
                    IfFailGo(MergeUpdateTokenInFieldSig(
                        pMiniMdAssemEmit,           // The assembly emit scope.
                        pMiniMdEmit,                // The emit scope.
                        pCommonAssemImport,         // The assembly scope where the signature is from.
                        pbHashValue,                // Hash value for the import assembly.
                        cbHashValue,                // Size in bytes for the hash value.
                        pCommonImport,              // The scope to merge into the emit scope.
                        pvTypeSpecSig,              // signature from the imported scope
                        ptkMap,                     // Internal OID mapping structure.
                        &qkTypeSpecSigEmit,         // [OUT] buffer for translated signature
                        0,                          // start from first byte of TypeSpec signature
                        0,                          // don't care how many bytes are consumed
                        &cbTypeSpecEmit) );         // [OUT] total number of bytes write to pqkSigEmit

                    hr = FindTypeSpec(pMiniMdEmit,
                                      (PCCOR_SIGNATURE) (qkTypeSpecSigEmit.Ptr()),
                                      cbTypeSpecEmit,
                                      &tkRidTo);

                    if ( hr == CLDB_E_RECORD_NOTFOUND )
                    {
                        // Create TypeSpec record.
                        TypeSpecRec     *pRecEmit;

                        IfFailGo(pMiniMdEmit->AddTypeSpecRecord(&pRecEmit, (RID *)&tkRidTo));
                        
                        IfFailGo(pMiniMdEmit->PutBlob(
                            TBL_TypeSpec,
                            TypeSpecRec::COL_Signature,
                            pRecEmit,
                            (PCCOR_SIGNATURE) (qkTypeSpecSigEmit.Ptr()),
                            cbTypeSpecEmit));
                        tkRidTo = TokenFromRid( tkRidTo, mdtTypeSpec );
                        IfFailGo(pMiniMdEmit->UpdateENCLog(tkRidTo));
                    }
                    IfFailGo( hr );
                }
                else
                {
                    _ASSERTE( TypeFromToken(tkRidFrom) == mdtBaseType );

                    // base type is unique across module
                    tkRidTo = tkRidFrom;
                }
            }

            // How many bytes the new rid will consume?
            cb1 = CorSigCompressToken(tkRidTo, &ulData);

            // ensure buffer is big enough
            IfFailGo(pqkSigEmit->ReSizeNoThrow(cbStartEmit + cbDestTotal + cb1));

            // store the new token
            cb2 = CorSigCompressToken(
                    tkRidTo,
                    (ULONG *)( ((BYTE *)pqkSigEmit->Ptr()) + cbStartEmit + cbDestTotal) );

            // inconsistency on CorSigCompressToken and CorSigUncompressToken
            _ASSERTE(cb1 == cb2);

            cbSrcTotal = cbSrcTotal + cb;
            cbDestTotal = cbDestTotal + cb1;

            if ( ulElementType == ELEMENT_TYPE_CMOD_REQD ||
                 ulElementType == ELEMENT_TYPE_CMOD_OPT)
            {
                // need to skip over the base type
                IfFailGo(MergeUpdateTokenInFieldSig(
                    pMiniMdAssemEmit,           // The assembly emit scope.
                    pMiniMdEmit,                // The emit scope.
                    pCommonAssemImport,         // The assembly scope where the signature is from.
                    pbHashValue,                // Hash value for the import assembly.
                    cbHashValue,                // Size in bytes for the hash value.
                    pCommonImport,              // The scope to merge into the emit scope.
                    &pbSigImp[cbSrcTotal],      // signature from the imported scope
                    ptkMap,                     // Internal OID mapping structure.
                    pqkSigEmit,                 // [OUT] buffer for translated signature
                    cbStartEmit + cbDestTotal,  // [IN] start point of buffer to write to
                    &cbImp,                     // [OUT] total number of bytes consumed from pbSigImp
                    &cbEmit));                  // [OUT] total number of bytes write to pqkSigEmit
                cbSrcTotal += cbImp;
                cbDestTotal += cbEmit;
            }

            break;
        default:
            _ASSERTE(cbSrcTotal == cbDestTotal);

            if ((ulElementType >= ELEMENT_TYPE_MAX) || 
                (ulElementType == ELEMENT_TYPE_PTR) || 
                (ulElementType == ELEMENT_TYPE_BYREF) || 
                (ulElementType == ELEMENT_TYPE_VALUEARRAY_UNSUPPORTED))
            {
                IfFailGo(META_E_BAD_SIGNATURE);
            }
            break;
    }
    if (pcbImp)
        *pcbImp = cbSrcTotal;
    *pcbEmit = cbDestTotal;

ErrExit:
    return hr;
} // ImportHelper::MergeUpdateTokenInFieldSig

#endif //FEATURE_METADATA_EMIT

//****************************************************************************
// convert tokens contained in a COM+ signature
//****************************************************************************
HRESULT ImportHelper::MergeUpdateTokenInSig(// S_OK or error.
    CMiniMdRW   *pMiniMdAssemEmit,      // [IN] The assembly emit scope.
    CMiniMdRW   *pMiniMdEmit,           // [IN] The emit scope.
    IMetaModelCommon *pCommonAssemImport,// [IN] Assembly scope where the signature is from.
    const void  *pbHashValue,           // [IN] Hash value for the import assembly.
    ULONG       cbHashValue,            // [IN] Size in bytes for the hash value.
    IMetaModelCommon *pCommonImport,    // [IN] The scope to merge into the emit scope.
    PCCOR_SIGNATURE pbSigImp,           // signature from the imported scope
    MDTOKENMAP      *ptkMap,            // Internal OID mapping structure.
    CQuickBytes     *pqkSigEmit,        // [OUT] translated signature
    ULONG           cbStartEmit,        // [IN] start point of buffer to write to
    ULONG           *pcbImp,            // [OUT] total number of bytes consumed from pbSigImp
    ULONG           *pcbEmit)           // [OUT] total number of bytes write to pqkSigEmit
{
#ifdef FEATURE_METADATA_EMIT
    HRESULT     hr = NOERROR;           // A result.
    ULONG       cb;                     // count of bytes
    ULONG       cb1;
    ULONG       cbSrcTotal = 0;         // count of bytes consumed in the imported signature
    ULONG       cbDestTotal = 0;        // count of bytes for the new signature
    ULONG       cbEmit;                 // count of bytes consumed in the imported signature
    ULONG       cbImp;                  // count of bytes for the new signature
    ULONG       cArg = 0;               // count of arguments in the signature
    ULONG       cTyArg = 0;
    ULONG       callingconv = 0;        // calling convention from signature

    _ASSERTE(pcbEmit && pqkSigEmit && pbSigImp);

    // calling convention
    cb = CorSigUncompressData(&pbSigImp[cbSrcTotal], &callingconv);
    _ASSERTE((callingconv & IMAGE_CEE_CS_CALLCONV_MASK) < IMAGE_CEE_CS_CALLCONV_MAX);

    // skip over calling convention
    cbSrcTotal += cb;

    if (isCallConv(callingconv, IMAGE_CEE_CS_CALLCONV_FIELD))
    {
        // It is a FieldRef
        cb1 = CorSigCompressData(callingconv, ((BYTE *)pqkSigEmit->Ptr()) + cbStartEmit);

        // compression and uncompression better match
        _ASSERTE(cb == cb1);

        cbDestTotal = cbSrcTotal = cb;
        IfFailGo(MergeUpdateTokenInFieldSig(
            pMiniMdAssemEmit,
            pMiniMdEmit,
            pCommonAssemImport,
            pbHashValue,
            cbHashValue,
            pCommonImport,
            &pbSigImp[cbSrcTotal],
            ptkMap,
            pqkSigEmit,                     // output buffer to hold the new sig for the field
            cbStartEmit + cbDestTotal,      // number of bytes already in pqkSigDest
            &cbImp,                         // number of bytes consumed from imported signature
            &cbEmit));                      // number of bytes write to the new signature
        *pcbEmit = cbDestTotal + cbEmit;
    }
    else
    {

        // It is a MethodRef
        // count of type arguments
        if (callingconv & IMAGE_CEE_CS_CALLCONV_GENERIC)
        {
            cb = CorSigUncompressData(&pbSigImp[cbSrcTotal], &cTyArg);
            cbSrcTotal += cb;
        }

        // count of argument
        cb = CorSigUncompressData(&pbSigImp[cbSrcTotal], &cArg);
        cbSrcTotal += cb;

        // move over the calling convention and the count of arguments
        IfFailGo(pqkSigEmit->ReSizeNoThrow(cbStartEmit + cbSrcTotal));
        memcpy(((BYTE *)pqkSigEmit->Ptr()) + cbStartEmit, pbSigImp, cbSrcTotal);
        cbDestTotal = cbSrcTotal;

        if ( !( isCallConv(callingconv, IMAGE_CEE_CS_CALLCONV_LOCAL_SIG) || isCallConv(callingconv, IMAGE_CEE_CS_CALLCONV_GENERICINST)) )
        {
                // LocalVar sig does not have return type
                // process the return type
                IfFailGo(MergeUpdateTokenInFieldSig(
                    pMiniMdAssemEmit,
                    pMiniMdEmit,
                    pCommonAssemImport,
                    pbHashValue,
                    cbHashValue,
                    pCommonImport,
                    &pbSigImp[cbSrcTotal],
                    ptkMap,
                    pqkSigEmit,                     // output buffer to hold the new sig for the field
                    cbStartEmit + cbDestTotal,      // number of bytes already in pqkSigDest
                    &cbImp,                         // number of bytes consumed from imported signature
                    &cbEmit));                      // number of bytes write to the new signature

            // advance the count
            cbSrcTotal += cbImp;
            cbDestTotal += cbEmit;
        }


        while (cArg)
        {
            // process every argument
            IfFailGo(MergeUpdateTokenInFieldSig(
                pMiniMdAssemEmit,
                pMiniMdEmit,
                pCommonAssemImport,
                pbHashValue,
                cbHashValue,
                pCommonImport,
                &pbSigImp[cbSrcTotal],
                ptkMap,
                pqkSigEmit,                 // output buffer to hold the new sig for the field
                cbStartEmit + cbDestTotal,
                &cbImp,                     // number of bytes consumed from imported signature
                &cbEmit));                  // number of bytes write to the new signature
            cbSrcTotal += cbImp;
            cbDestTotal += cbEmit;
            cArg--;
        }

        // total of number of bytes consumed from imported signature
        if (pcbImp)
            *pcbImp = cbSrcTotal;

        // total number of bytes emitted by this function call to the emitting signature
        *pcbEmit = cbDestTotal;
    }

ErrExit:
    return hr;
#else //!FEATURE_METADATA_EMIT
    // This code should be called only with public emit APIs
    _ASSERTE_MSG(FALSE, "This method should not be reachable");
    return E_NOTIMPL;
#endif //!FEATURE_METADATA_EMIT
} // ImportHelper::MergeUpdateTokenInSig

//****************************************************************************
// Given a TypeDef or a TypeRef, return the Nesting hierarchy.  The first
// element in the returned array always refers to the class token passed and
// the nesting hierarchy expands outwards from there.
//****************************************************************************
HRESULT ImportHelper::GetNesterHierarchy(
    IMetaModelCommon *pCommon,          // Scope in which to find the hierarchy.
    mdToken     tk,                     // TypeDef/TypeRef whose hierarchy is needed.
    CQuickArray<mdToken> &cqaNesters,   // Array of Nesters.
    CQuickArray<LPCUTF8> &cqaNamespaces,    // Names of the nesters.
    CQuickArray<LPCUTF8> &cqaNames)     // Namespaces of the nesters.
{
    _ASSERTE(pCommon &&
             (TypeFromToken(tk) == mdtTypeDef ||
              TypeFromToken(tk) == mdtTypeRef) &&
             !IsNilToken(tk));

    if (TypeFromToken(tk) == mdtTypeDef)
    {
        return GetTDNesterHierarchy(pCommon,
                                    tk,
                                    cqaNesters,
                                    cqaNamespaces,
                                    cqaNames);
    }
    else
    {
        return GetTRNesterHierarchy(pCommon,
                                    tk,
                                    cqaNesters,
                                    cqaNamespaces,
                                    cqaNames);
    }
}   // HRESULT ImportHelper::GetNesterHierarchy()

//****************************************************************************
// Get Nesting hierarchy given a TypeDef.
//****************************************************************************
HRESULT ImportHelper::GetTDNesterHierarchy(
    IMetaModelCommon *pCommon,          // Scope in which to find the hierarchy.
    mdTypeDef       td,                 // TypeDef whose hierarchy is needed.
    CQuickArray<mdTypeDef> &cqaTdNesters,// Array of Nesters.
    CQuickArray<LPCUTF8> &cqaNamespaces,    // Namespaces of the nesters.
    CQuickArray<LPCUTF8> &cqaNames)     // Names of the nesters.
{
    LPCUTF8     szName, szNamespace;
    DWORD       dwFlags;
    mdTypeDef   tdNester;
    ULONG       ulNesters;
    HRESULT     hr = NOERROR;

    _ASSERTE(pCommon &&
             TypeFromToken(td) == mdtTypeDef &&
             !IsNilToken(td));

    // Set current Nester index to 0.
    ulNesters = 0;
    // The first element in the hierarchy is the TypeDef itself.
    tdNester = td;
    // Bogus initialization to kick off the while loop.
    dwFlags = tdNestedPublic;
    // Loop as long as the TypeDef is a Nested TypeDef.
    while (IsTdNested(dwFlags))
    {
        if (InvalidRid(tdNester))
            IfFailGo(CLDB_E_RECORD_NOTFOUND);
        // Get the name and namespace for the TypeDef.
        IfFailGo(pCommon->CommonGetTypeDefProps(
            tdNester,
            &szNamespace, 
            &szName, 
            &dwFlags,
            NULL,
            NULL));
        
        // Update the dynamic arrays.
        ulNesters++;

        IfFailGo(cqaTdNesters.ReSizeNoThrow(ulNesters));
        cqaTdNesters[ulNesters-1] = tdNester;

        IfFailGo(cqaNamespaces.ReSizeNoThrow(ulNesters));
        cqaNamespaces[ulNesters-1] = szNamespace;

        IfFailGo(cqaNames.ReSizeNoThrow(ulNesters));
        cqaNames[ulNesters-1] = szName;

        IfFailGo(pCommon->CommonGetEnclosingClassOfTypeDef(tdNester, &tdNester));
    }
    // Outermost class must have enclosing of Nil.
    _ASSERTE(IsNilToken(tdNester));
ErrExit:
    return hr;
}   // HRESULT ImportHelper::GetTDNesterHierarchy()


//****************************************************************************
// Get Nesting hierarchy given a TypeRef.
//****************************************************************************
HRESULT ImportHelper::GetTRNesterHierarchy(
    IMetaModelCommon *pCommon,          // [IN] Scope in which to find the hierarchy.
    mdTypeRef   tr,                     // [IN] TypeRef whose hierarchy is needed.
    CQuickArray<mdTypeRef> &cqaTrNesters,// [OUT] Array of Nesters.
    CQuickArray<LPCUTF8> &cqaNamespaces,    // [OUT] Namespaces of the nesters.
    CQuickArray<LPCUTF8> &cqaNames)    // [OUT] Names of the nesters.
{
    LPCUTF8     szNamespace;
    LPCUTF8     szName;
    mdTypeRef   trNester;
    mdToken     tkResolutionScope;
    ULONG       ulNesters;
    HRESULT     hr = S_OK;

    _ASSERTE(pCommon &&
             TypeFromToken(tr) == mdtTypeRef &&
             !IsNilToken(tr));

    // Set current Nester index to 0.
    ulNesters = 0;
    // The first element in the hierarchy is the TypeRef itself.
    trNester = tr;
    // Loop as long as the TypeRef is a Nested TypeRef.
    while (TypeFromToken(trNester) == mdtTypeRef && !IsNilToken(trNester))
    {
        // Get the name and namespace for the TypeDef.
        IfFailGo(pCommon->CommonGetTypeRefProps(
            trNester,
            &szNamespace,
            &szName,
            &tkResolutionScope));
        
        // Update the dynamic arrays.
        ulNesters++;

        IfFailGo(cqaTrNesters.ReSizeNoThrow(ulNesters));
        cqaTrNesters[ulNesters-1] = trNester;

        IfFailGo(cqaNamespaces.ReSizeNoThrow(ulNesters));
        cqaNamespaces[ulNesters-1] = szNamespace;

        IfFailGo(cqaNames.ReSizeNoThrow(ulNesters));
        cqaNames[ulNesters-1] = szName;

        trNester = tkResolutionScope;
    }
ErrExit:
    return hr;
}   // HRESULT ImportHelper::GetTRNesterHierarchy()

//****************************************************************************
// Create the Nesting hierarchy given the array of TypeRef names.  The first
// TypeRef in the array is the innermost TypeRef.
//****************************************************************************
HRESULT ImportHelper::CreateNesterHierarchy(
    CMiniMdRW   *pMiniMdEmit,           // [IN] Emit scope to create the Nesters in.
    CQuickArray<LPCUTF8> &cqaNesterNamespaces,   // [IN] Array of Nester namespaces.
    CQuickArray<LPCUTF8> &cqaNesterNames,  // [IN] Array of Nester names.
    mdToken     tkResolutionScope,      // [IN] ResolutionScope for the innermost TypeRef.
    mdTypeRef   *ptr)                   // [OUT] Token for the innermost TypeRef.
{
    TypeRefRec  *pRecEmit;
    ULONG       iRecord;
    LPCUTF8     szName;
    LPCUTF8     szNamespace;
    mdTypeRef   trNester;
    mdTypeRef   trCur;
    ULONG       ulNesters;
    HRESULT     hr = S_OK;

    _ASSERTE(cqaNesterNames.Size() == cqaNesterNamespaces.Size() &&
             cqaNesterNames.Size());

    // Initialize the output parameter.
    *ptr = mdTypeRefNil;

    // Get count of Nesters in the hierarchy.
    ulNesters = (ULONG)cqaNesterNames.Size();

    // For each nester try to find the corresponding TypeRef in the emit scope.
    // For the outermost TypeRef, ResolutionScope is what's passed in.
    if (tkResolutionScope == mdTokenNil)
        trNester = mdTypeRefNil;
    else
        trNester = tkResolutionScope;
    ULONG ulCurNester;
    for (ulCurNester = ulNesters-1; ulCurNester != (ULONG) -1; ulCurNester--)
    {
        hr = FindTypeRefByName(pMiniMdEmit,
                               trNester,
                               cqaNesterNamespaces[ulCurNester],
                               cqaNesterNames[ulCurNester],
                               &trCur);
        if (hr == CLDB_E_RECORD_NOTFOUND)
            break;
        else
            IfFailGo(hr);
        trNester = trCur;
    }
    if (SUCCEEDED(hr))
        *ptr = trNester;
    else if ( hr == CLDB_E_RECORD_NOTFOUND )
    {
        // Create TypeRef records for the part of the hierarchy for which
        // TypeRefs are not already present.
        for (;ulCurNester != (ULONG) -1; ulCurNester--)
        {
            szName = cqaNesterNames[ulCurNester];
            szNamespace = cqaNesterNamespaces[ulCurNester];

            IfFailGo(pMiniMdEmit->AddTypeRefRecord(&pRecEmit, &iRecord));
            if (szNamespace && szNamespace[0] != '\0')
            {
                // only put the namespace if it is not an empty string and not NULL
                IfFailGo(pMiniMdEmit->PutString(TBL_TypeRef, TypeRefRec::COL_Namespace,
                                                pRecEmit, szNamespace));
            }
            IfFailGo(pMiniMdEmit->PutString(TBL_TypeRef, TypeRefRec::COL_Name,
                                            pRecEmit, szName));
            IfFailGo(pMiniMdEmit->PutToken(TBL_TypeRef,
                        TypeRefRec::COL_ResolutionScope, pRecEmit, trNester));
            
            trNester = TokenFromRid(iRecord, mdtTypeRef);
            IfFailGo(pMiniMdEmit->UpdateENCLog(trNester));
            
            // Hash the name.
            IfFailGo(pMiniMdEmit->AddNamedItemToHash(TBL_TypeRef, trNester, szName, 0));
        }
        *ptr = trNester;
    }
    else
        IfFailGo(hr);
ErrExit:
    return hr;
}   // ImportHelper::CreateNesterHierarchy

//****************************************************************************
// Given the arrays of names and namespaces for the Nested Type hierarchy,
// find the innermost TypeRef token.  The arrays start with the innermost
// TypeRefs and go outwards.
//****************************************************************************
HRESULT ImportHelper::FindNestedTypeRef(
    CMiniMdRW   *pMiniMd,               // [IN] Scope in which to find the TypeRef.
    CQuickArray<LPCUTF8> &cqaNesterNamespaces,  // [IN] Array of Names.
    CQuickArray<LPCUTF8> &cqaNesterNames,   // [IN] Array of Namespaces.
    mdToken     tkResolutionScope,      // [IN] Resolution scope for the outermost TypeRef.
    mdTypeRef   *ptr)                   // [OUT] Inner most TypeRef token.
{
    ULONG       ulNesters;
    ULONG       ulCurNester;
    HRESULT     hr = S_OK;

    _ASSERTE(cqaNesterNames.Size() == cqaNesterNamespaces.Size() &&
             cqaNesterNames.Size());

    // Set the output parameter to Nil token.
    *ptr = mdTokenNil;

    // Get count in the hierarchy, the give TypeDef included.
    ulNesters = (ULONG)cqaNesterNames.Size();

    // For each nester try to find the corresponding TypeRef in
    // the emit scope.  For the outermost TypeDef enclosing class is Nil.
    for (ulCurNester = ulNesters-1; ulCurNester != (ULONG) -1; ulCurNester--)
    {
        IfFailGo(FindTypeRefByName(pMiniMd,
                                   tkResolutionScope,
                                   cqaNesterNamespaces[ulCurNester],
                                   cqaNesterNames[ulCurNester],
                                   &tkResolutionScope));
    }
    *ptr = tkResolutionScope;
ErrExit:
    return hr;
}   // HRESULT ImportHelper::FindNestedTypeRef()


//****************************************************************************
// Given the arrays of names and namespaces for the Nested Type hierarchy,
// find the innermost TypeDef token.  The arrays start with the innermost
// TypeDef and go outwards.
//****************************************************************************
HRESULT ImportHelper::FindNestedTypeDef(
    CMiniMdRW   *pMiniMd,               // [IN] Scope in which to find the TypeRef.
    CQuickArray<LPCUTF8> &cqaNesterNamespaces,   // [IN] Array of Namespaces.
    CQuickArray<LPCUTF8> &cqaNesterNames,    // [IN] Array of Names.
    mdTypeDef   tdNester,               // [IN] Enclosing class for the Outermost TypeDef.
    mdTypeDef   *ptd)                   // [OUT] Inner most TypeRef token.
{
    ULONG       ulNesters;
    ULONG       ulCurNester;
    HRESULT     hr = S_OK;

    _ASSERTE(cqaNesterNames.Size() == cqaNesterNamespaces.Size() &&
             cqaNesterNames.Size());

    // Set the output parameter to Nil token.
    *ptd = mdTokenNil;

    // Get count in the hierarchy, the give TypeDef included.
    ulNesters = (ULONG)cqaNesterNames.Size();

    // For each nester try to find the corresponding TypeRef in
    // the emit scope.  For the outermost TypeDef enclosing class is Nil.
    for (ulCurNester = ulNesters-1; ulCurNester != (ULONG) -1; ulCurNester--)
    {
        IfFailGo(FindTypeDefByName(pMiniMd,
                                   cqaNesterNamespaces[ulCurNester],
                                   cqaNesterNames[ulCurNester],
                                   tdNester,
                                   &tdNester));
    }
    *ptd = tdNester;
ErrExit:
    return hr;
}   // ImportHelper::FindNestedTypeDef

#ifdef FEATURE_METADATA_EMIT

//****************************************************************************
// Given the TypeDef and the corresponding assembly and module import scopes,
// create a corresponding TypeRef in the given emit scope.
//****************************************************************************
HRESULT 
ImportHelper::ImportTypeDef(
    CMiniMdRW *        pMiniMdAssemEmit,    // [IN] Assembly emit scope.
    CMiniMdRW *        pMiniMdEmit,         // [IN] Module emit scope.
    IMetaModelCommon * pCommonAssemImport,  // [IN] Assembly import scope.
    const void *       pbHashValue,         // [IN] Hash value for import assembly.
    ULONG              cbHashValue,         // [IN] Size in bytes of hash value.
    IMetaModelCommon * pCommonImport,       // [IN] Module import scope.
    mdTypeDef          tdImport,            // [IN] Imported TypeDef.
    bool               bReturnTd,           // [IN] If the import and emit scopes are identical, return the TypeDef.
    mdToken *          ptkType)             // [OUT] Output token for the imported type in the emit scope.
{
    CQuickArray<mdTypeDef>  cqaNesters;
    CQuickArray<LPCUTF8> cqaNesterNames;
    CQuickArray<LPCUTF8> cqaNesterNamespaces;
    GUID        nullguid = GUID_NULL;
    GUID        MvidAssemImport = nullguid;
    GUID        MvidAssemEmit = nullguid;
    GUID        MvidImport = nullguid;
    GUID        MvidEmit = nullguid;
    GUID        GuidImport = GUID_NULL;
    LPCUTF8     szModuleImport;
    mdToken     tkOuterRes = mdTokenNil;
    HRESULT     hr = S_OK;
    BOOL        bBCL = false;

    _ASSERTE(pMiniMdEmit && pCommonImport && ptkType);
    _ASSERTE(TypeFromToken(tdImport) == mdtTypeDef && tdImport != mdTypeDefNil);

    // Get MVIDs for import and emit, assembly and module scopes.
    if (pCommonAssemImport != NULL)
    {
        IfFailGo(pCommonAssemImport->CommonGetScopeProps(0, &MvidAssemImport));
    }
    IfFailGo(pCommonImport->CommonGetScopeProps(&szModuleImport, &MvidImport));
    if (pMiniMdAssemEmit != NULL)
    {
        IfFailGo(static_cast<IMetaModelCommon*>(pMiniMdAssemEmit)->CommonGetScopeProps(0, &MvidAssemEmit));
    }
    IfFailGo(static_cast<IMetaModelCommon*>(pMiniMdEmit)->CommonGetScopeProps(0, &MvidEmit));

    if (pCommonAssemImport == NULL && strcmp(szModuleImport, COM_RUNTIME_LIBRARY) == 0) 
    {
        const BYTE      *pBlob;                 // Blob with dispid.
        ULONG           cbBlob;                 // Length of blob.
        WCHAR           wzBlob[40];             // Wide char format of guid.
        int             ix;                     // Loop control.

        hr = pCommonImport->CommonGetCustomAttributeByName(1, INTEROP_GUID_TYPE, (const void **)&pBlob, &cbBlob);
        if (hr != S_FALSE)
        {
            // Should be in format.  Total length == 41
            // <0x0001><0x24>01234567-0123-0123-0123-001122334455<0x0000>
            if ((cbBlob == 41) || (GET_UNALIGNED_VAL16(pBlob) == 1))
            {
                for (ix=1; ix<=36; ++ix)
                    wzBlob[ix] = pBlob[ix+2];
                wzBlob[0] = '{';
                wzBlob[37] = '}';
                wzBlob[38] = 0;
                // It's ok that we ignore the hr here. It's not needed, but I
                // don't want to remove it in case a code analysis tool will complain
                // about not capturing return codes.
                hr = IIDFromString(wzBlob, &GuidImport);
            }
        }
        bBCL = (GuidImport == LIBID_ComPlusRuntime);
    }

    // Compute the ResolutionScope for the imported type.
    if (bBCL)
    {
        // This is the case that we are referring to mscorlib.dll but client does not provide the manifest for
        // mscorlib.dll!! Do not generate ModuleRef to the mscorlib.dll. But instead we should just leave the
        // ResolutionScope empty
        tkOuterRes = mdTokenNil;
    }
    else if (MvidAssemImport == MvidAssemEmit && MvidImport == MvidEmit)
    {
        // The TypeDef is in the same Assembly and the Same scope.
        if (bReturnTd)
        {
            *ptkType = tdImport;
            goto ErrExit;
        }
        else
            tkOuterRes = TokenFromRid(1, mdtModule);
    }
    else if (MvidAssemImport == MvidAssemEmit && MvidImport != MvidEmit)
    {
        // The TypeDef is in the same Assembly but a different module.
        
        // Create a ModuleRef corresponding to the import scope.
        IfFailGo(CreateModuleRefFromScope(pMiniMdEmit, pCommonImport, &tkOuterRes));
    }
    else if (MvidAssemImport != MvidAssemEmit)
    {
        if (pCommonAssemImport)
        {
            // The TypeDef is from a different Assembly.

            // Import and Emit scopes can't be identical and be from different
            // Assemblies at the same time.
            _ASSERTE(MvidImport != MvidEmit &&
                     "Import scope can't be identical to the Emit scope and be from a different Assembly at the same time.");

            _ASSERTE(pCommonAssemImport);

            // Create an AssemblyRef corresponding to the import scope.
            IfFailGo(CreateAssemblyRefFromAssembly(pMiniMdAssemEmit,
                                                   pMiniMdEmit,
                                                   pCommonAssemImport,
                                                   pbHashValue,
                                                   cbHashValue,
                                                   &tkOuterRes));
        }
        else
        {
            // <REVISIT_TODO>@FUTURE: review this fix! We may want to return error in the future.
            // This is to enable smc to reference mscorlib.dll while it does not have the manifest for mscorlib.dll opened.</REVISIT_TODO>
            // Create a Nil ResolutionScope to the TypeRef.
            tkOuterRes = mdTokenNil;
        }
    }

    // Get the nesting hierarchy for the Type from the import scope and create
    // the corresponding Type hierarchy in the emit scope.  Note that the non-
    // nested class case simply folds into this scheme.

    IfFailGo(GetNesterHierarchy(pCommonImport,
                                tdImport,
                                cqaNesters,
                                cqaNesterNamespaces,
                                cqaNesterNames));

    IfFailGo(CreateNesterHierarchy(pMiniMdEmit,
                                   cqaNesterNamespaces,
                                   cqaNesterNames,
                                   tkOuterRes,
                                   ptkType));
ErrExit:
    return hr;
} // ImportHelper::ImportTypeDef

//****************************************************************************
// Given the TypeRef and the corresponding assembly and module import scopes,
// return the corresponding token in the given emit scope.
// <REVISIT_TODO>@FUTURE:  Should we look at visibility flags on ExportedTypes and TypeDefs when
// handling references across Assemblies?</REVISIT_TODO>
//****************************************************************************
HRESULT ImportHelper::ImportTypeRef(
    CMiniMdRW   *pMiniMdAssemEmit,      // [IN] Assembly emit scope.
    CMiniMdRW   *pMiniMdEmit,           // [IN] Module emit scope.
    IMetaModelCommon *pCommonAssemImport, // [IN] Assembly import scope.
    const void  *pbHashValue,           // [IN] Hash value for import assembly.
    ULONG       cbHashValue,            // [IN] Size in bytes of hash value.
    IMetaModelCommon *pCommonImport,    // [IN] Module import scope.
    mdTypeRef   trImport,               // [IN] Imported TypeRef.
    mdToken     *ptkType)               // [OUT] Output token for the imported type in the emit scope.
{
    CQuickArray<mdTypeDef>  cqaNesters;
    CQuickArray<LPCUTF8> cqaNesterNames;
    CQuickArray<LPCUTF8> cqaNesterNamespaces;
    LPCUTF8     szScopeNameEmit;
    GUID        nullguid = GUID_NULL;
    GUID        MvidAssemImport = nullguid;
    GUID        MvidAssemEmit = nullguid;
    GUID        MvidImport = nullguid;
    GUID        MvidEmit = nullguid;
    mdToken     tkOuterImportRes;               // ResolutionScope for the outermost TypeRef in import scope.
    mdToken     tkOuterEmitRes = mdTokenNil;    // ResolutionScope for outermost TypeRef in emit scope.
    HRESULT     hr = S_OK;
    bool        bAssemblyRefFromAssemScope = false;

    _ASSERTE(pMiniMdEmit && pCommonImport && ptkType);
    _ASSERTE(TypeFromToken(trImport) == mdtTypeRef);

    // Get MVIDs for import and emit, assembly and module scopes.
    if (pCommonAssemImport != NULL)
    {
        IfFailGo(pCommonAssemImport->CommonGetScopeProps(0, &MvidAssemImport));
    }
    IfFailGo(pCommonImport->CommonGetScopeProps(0, &MvidImport));
    if (pMiniMdAssemEmit != NULL)
    {
        IfFailGo(static_cast<IMetaModelCommon*>(pMiniMdAssemEmit)->CommonGetScopeProps(
            0, 
            &MvidAssemEmit));
    }
    IfFailGo(static_cast<IMetaModelCommon*>(pMiniMdEmit)->CommonGetScopeProps(
        &szScopeNameEmit, 
        &MvidEmit));

    // Get the outermost resolution scope for the TypeRef being imported.
    IfFailGo(GetNesterHierarchy(pCommonImport,
                                trImport,
                                cqaNesters,
                                cqaNesterNamespaces,
                                cqaNesterNames));
    IfFailGo(pCommonImport->CommonGetTypeRefProps(
        cqaNesters[cqaNesters.Size() - 1], 
        0, 
        0, 
        &tkOuterImportRes));
    
    // Compute the ResolutionScope for the imported type.
    if (MvidAssemImport == MvidAssemEmit && MvidImport == MvidEmit)
    {
        *ptkType = trImport;
        goto ErrExit;
    }
    else if (MvidAssemImport == MvidAssemEmit && MvidImport != MvidEmit)
    {
        // The TypeRef is in the same Assembly but a different module.

        if (IsNilToken(tkOuterImportRes))
        {
            tkOuterEmitRes = tkOuterImportRes;
        }
        else if (TypeFromToken(tkOuterImportRes) == mdtModule)
        {
            // TypeRef resolved to the import module in which its defined.

            // 
            if (pMiniMdAssemEmit == NULL && pCommonAssemImport == NULL)
            {
                tkOuterEmitRes = TokenFromRid(1, mdtModule);
            }
            else
            {
                // Create a ModuleRef corresponding to the import scope.
                IfFailGo(CreateModuleRefFromScope(pMiniMdEmit,
                                                  pCommonImport,
                                                  &tkOuterEmitRes));
            }
        }
        else if (TypeFromToken(tkOuterImportRes) == mdtAssemblyRef)
        {
            // TypeRef is from a different Assembly.

            // Create a corresponding AssemblyRef in the emit scope.
            IfFailGo(CreateAssemblyRefFromAssemblyRef(pMiniMdAssemEmit,
                                                      pMiniMdEmit,
                                                      pCommonImport,
                                                      tkOuterImportRes,
                                                      &tkOuterEmitRes));
        }
        else if (TypeFromToken(tkOuterImportRes) == mdtModuleRef)
        {
            // Get Name of the ModuleRef.
            LPCUTF8     szMRName;
            IfFailGo(pCommonImport->CommonGetModuleRefProps(tkOuterImportRes, &szMRName));

            if (!strcmp(szMRName, szScopeNameEmit))
            {
                // ModuleRef from import scope resolves to the emit scope.
                tkOuterEmitRes = TokenFromRid(1, mdtModule);
            }
            else
            {
                // ModuleRef does not correspond to the emit scope.
                // Create a corresponding ModuleRef.
                IfFailGo(CreateModuleRefFromModuleRef(pMiniMdEmit,
                                                      pCommonImport,
                                                      tkOuterImportRes,
                                                      &tkOuterEmitRes));
            }
        }
    }
    else if (MvidAssemImport != MvidAssemEmit)
    {
        // The TypeDef is from a different Assembly.

        // Import and Emit scopes can't be identical and be from different
        // Assemblies at the same time.
        _ASSERTE(MvidImport != MvidEmit &&
                 "Import scope can't be identical to the Emit scope and be from a different Assembly at the same time.");

        mdToken     tkImplementation;       // Implementation token for ExportedType.
        if (IsNilToken(tkOuterImportRes))
        {
            // <REVISIT_TODO>BUG FIX:: URT 13626
            // Well, before all of the clients generate AR for mscorlib.dll reference, it is not true
            // that tkOuterImportRes == nil will imply that we have to find such an entry in the import manifest!!</REVISIT_TODO>

            // Look for a ExportedType entry in the import Assembly.  Its an error
            // if we don't find a ExportedType entry.
            mdExportedType   tkExportedType;
            hr = pCommonAssemImport->CommonFindExportedType(
                                    cqaNesterNamespaces[cqaNesters.Size() - 1],
                                    cqaNesterNames[cqaNesters.Size() - 1],
                                    mdTokenNil,
                                    &tkExportedType);
            if (SUCCEEDED(hr))
            {
                IfFailGo(pCommonAssemImport->CommonGetExportedTypeProps(
                    tkExportedType, 
                    NULL, 
                    NULL, 
                    &tkImplementation));
                if (TypeFromToken(tkImplementation) == mdtFile)
                {
                    // Type is from a different Assembly.
                    IfFailGo(CreateAssemblyRefFromAssembly(pMiniMdAssemEmit,
                                                           pMiniMdEmit,
                                                           pCommonAssemImport,
                                                           pbHashValue,
                                                           cbHashValue,
                                                           &tkOuterEmitRes));
                }
                else if (TypeFromToken(tkImplementation) == mdtAssemblyRef)
                {
                    // This folds into the case where the Type is AssemblyRef.  So
                    // let it fall through to that case.

                    // Remember that this AssemblyRef token is actually from the Manifest scope not
                    // the module scope!!!
                    bAssemblyRefFromAssemScope = true;
                    tkOuterImportRes = tkImplementation;
                }
                else
                    _ASSERTE(!"Unexpected ExportedType implementation token.");
            }
            else
            {
                // In this case, we will just move over the TypeRef with Nil ResolutionScope.
                hr = NOERROR;
                tkOuterEmitRes = mdTokenNil;
            }
        }
        else if (TypeFromToken(tkOuterImportRes) == mdtModule)
        {
            // Type is from a different Assembly.
            IfFailGo(CreateAssemblyRefFromAssembly(pMiniMdAssemEmit,
                                                   pMiniMdEmit,
                                                   pCommonAssemImport,
                                                   pbHashValue,
                                                   cbHashValue,
                                                   &tkOuterEmitRes));
        }
        // Not else if, because mdtModule case above could change
        // tkOuterImportRes to an AssemblyRef.
        if (TypeFromToken(tkOuterImportRes) == mdtAssemblyRef)
        {
            // If there is an emit assembly, see if the import assembly ref points to 
            //  it.  If there is no emit assembly, the import assembly, by definition,
            //  does not point to this one.
            if (pMiniMdAssemEmit == NULL  || !pMiniMdAssemEmit->getCountAssemblys())
                hr = S_FALSE;
            else
            {
                if (bAssemblyRefFromAssemScope)
                {
                    // Check to see if the AssemblyRef resolves to the emit assembly.
                    IfFailGo(CompareAssemblyRefToAssembly(pCommonAssemImport,
                                                          tkOuterImportRes,
                                    static_cast<IMetaModelCommon*>(pMiniMdAssemEmit)));

                }
                else
                {
                    // Check to see if the AssemblyRef resolves to the emit assembly.
                    IfFailGo(CompareAssemblyRefToAssembly(pCommonImport,
                                                          tkOuterImportRes,
                                    static_cast<IMetaModelCommon*>(pMiniMdAssemEmit)));
                }
            }
            if (hr == S_OK)
            {
                // The TypeRef being imported is defined in the current Assembly.

                // Find the ExportedType for the outermost TypeRef in the Emit assembly.
                mdExportedType   tkExportedType;

                hr = FindExportedType(pMiniMdAssemEmit,
                                 cqaNesterNamespaces[cqaNesters.Size() - 1],
                                 cqaNesterNames[cqaNesters.Size() - 1],
                                 mdTokenNil,    // Enclosing ExportedType.
                                 &tkExportedType);
                if (hr == S_OK)
                {
                    // Create a ModuleRef based on the File name for the ExportedType.
                    // If the ModuleRef corresponds to pMiniMdEmit, the function
                    // will return S_FALSE, in which case set tkOuterEmitRes to
                    // the Module token.
                    hr = CreateModuleRefFromExportedType(pMiniMdAssemEmit,
                                                    pMiniMdEmit,
                                                    tkExportedType,
                                                    &tkOuterEmitRes);
                    if (hr == S_FALSE)
                        tkOuterEmitRes = TokenFromRid(1, mdtModule);
                    else
                        IfFailGo(hr);
                }
                else if (hr == CLDB_E_RECORD_NOTFOUND)
                {
                    // Find the Type in the Assembly emit scope to cover the
                    // case where ExportedTypes may be implicitly defined.  Its an
                    // error if we can't find the Type at this point.
                    IfFailGo(FindTypeDefByName(pMiniMdAssemEmit,
                                               cqaNesterNamespaces[cqaNesters.Size() - 1],
                                               cqaNesterNames[cqaNesters.Size() - 1],
                                               mdTokenNil,  // Enclosing Type.
                                               &tkOuterEmitRes));
                    tkOuterEmitRes = TokenFromRid(1, mdtModule);
                }
                else
                {
                    _ASSERTE(FAILED(hr));
                    IfFailGo(hr);
                }
            }
            else if (hr == S_FALSE)
            {
                // The TypeRef being imported is from a different Assembly.

                if (bAssemblyRefFromAssemScope)
                {
                    // Create a corresponding AssemblyRef.
                    IfFailGo(CreateAssemblyRefFromAssemblyRef(pMiniMdAssemEmit,
                                                              pMiniMdEmit,
                                                              pCommonAssemImport,
                                                              tkOuterImportRes,
                                                              &tkOuterEmitRes));
                }
                else
                {
                    // Create a corresponding AssemblyRef.
                    IfFailGo(CreateAssemblyRefFromAssemblyRef(pMiniMdAssemEmit,
                                                              pMiniMdEmit,
                                                              pCommonImport,
                                                              tkOuterImportRes,
                                                              &tkOuterEmitRes));
                }
            }
            else
            {
                _ASSERTE(FAILED(hr));
                IfFailGo(hr);
            }
        }
        else if (TypeFromToken(tkOuterImportRes) == mdtModuleRef)
        {
            // Type is from a different Assembly.
            IfFailGo(CreateAssemblyRefFromAssembly(pMiniMdAssemEmit,
                                                   pMiniMdEmit,
                                                   pCommonAssemImport,
                                                   pbHashValue,
                                                   cbHashValue,
                                                   &tkOuterEmitRes));
        }
    }

    // Try to find the TypeDef in the emit scope. If we cannot find the
    // typedef, we need to introduce a typeref.

    // See if the Nested TypeDef is present in the Emit scope.
    hr = CLDB_E_RECORD_NOTFOUND;
    if (TypeFromToken(tkOuterEmitRes) == mdtModule && !IsNilToken(tkOuterEmitRes))
    {
        hr = FindNestedTypeDef(pMiniMdEmit,
                               cqaNesterNamespaces,
                               cqaNesterNames,
                               mdTokenNil,
                               ptkType);

        // <REVISIT_TODO>cannot assert now!! Due to the IJW workaround!
        // _ASSERTE(SUCCEEDED(hr));</REVISIT_TODO>
    }

    if (hr == CLDB_E_RECORD_NOTFOUND)
    {
        IfFailGo(CreateNesterHierarchy(pMiniMdEmit,
                                       cqaNesterNamespaces,
                                       cqaNesterNames,
                                       tkOuterEmitRes,
                                       ptkType));
    }
    else
        IfFailGo(hr);
ErrExit:
    return hr;
} // ImportHelper::ImportTypeRef

//******************************************************************************
// Given import scope, create a corresponding ModuleRef.
//******************************************************************************
HRESULT ImportHelper::CreateModuleRefFromScope( // S_OK or error.
    CMiniMdRW   *pMiniMdEmit,           // [IN] Emit scope in which the ModuleRef is to be created.
    IMetaModelCommon *pCommonImport,    // [IN] Import scope.
    mdModuleRef *ptkModuleRef)          // [OUT] Output token for ModuleRef.
{
    HRESULT     hr = S_OK;
    LPCSTR      szName;
    ModuleRefRec *pRecordEmit;
    RID         iRecordEmit;

    // Set output to nil.
    *ptkModuleRef = mdTokenNil;

    // Get name of import scope.
    IfFailGo(pCommonImport->CommonGetScopeProps(&szName, 0));

    // See if the ModuleRef exists in the Emit scope.
    hr = FindModuleRef(pMiniMdEmit, szName, ptkModuleRef);

    if (hr == CLDB_E_RECORD_NOTFOUND)
    {
        if (szName[0] == '\0')
        {
            // It the referenced Module does not have a proper name, use the nil token instead.
            LOG((LOGMD, "WARNING!!! MD ImportHelper::CreatemoduleRefFromScope but scope does not have a proper name!!!!"));

            // clear the error
            hr = NOERROR;

            // It is a bug to create an ModuleRef to an empty name!!!
            *ptkModuleRef = mdTokenNil;
        }
        else
        {
            // Create ModuleRef record and set the output parameter.
            IfFailGo(pMiniMdEmit->AddModuleRefRecord(&pRecordEmit, &iRecordEmit));
            *ptkModuleRef = TokenFromRid(iRecordEmit, mdtModuleRef);
            IfFailGo(pMiniMdEmit->UpdateENCLog(*ptkModuleRef));

            // It is a bug to create an ModuleRef to mscorlib.dll
            _ASSERTE(strcmp(szName, COM_RUNTIME_LIBRARY) != 0);

            // Set the name of ModuleRef.
            IfFailGo(pMiniMdEmit->PutString(TBL_ModuleRef, ModuleRefRec::COL_Name,
                                                  pRecordEmit, szName));
        }
    }
    else
        IfFailGo(hr);
ErrExit:
    return hr;
} // ImportHelper::CreateModuleRefFromScope


//******************************************************************************
// Given an import scope and a ModuleRef, create a corresponding ModuleRef in
// the given emit scope.
//******************************************************************************
HRESULT ImportHelper::CreateModuleRefFromModuleRef(    // S_OK or error.
    CMiniMdRW   *pMiniMdEmit,           // [IN] Emit scope.
    IMetaModelCommon *pCommon,              // [IN] Import scope.
    mdModuleRef tkModuleRef,            // [IN] ModuleRef token.
    mdModuleRef *ptkModuleRef)          // [OUT] ModuleRef token in the emit scope.
{
    HRESULT     hr = S_OK;
    LPCSTR      szName;
    ModuleRefRec *pRecord;
    RID         iRecord;

    // Set output to Nil.
    *ptkModuleRef = mdTokenNil;

    // Get name of the ModuleRef being imported.
    IfFailGo(pCommon->CommonGetModuleRefProps(tkModuleRef, &szName));

    // See if the ModuleRef exist in the Emit scope.
    hr = FindModuleRef(pMiniMdEmit, szName, ptkModuleRef);

    if (hr == CLDB_E_RECORD_NOTFOUND)
    {
        // Create ModuleRef record and set the output parameter.
        IfFailGo(pMiniMdEmit->AddModuleRefRecord(&pRecord, &iRecord));
        *ptkModuleRef = TokenFromRid(iRecord, mdtModuleRef);
        IfFailGo(pMiniMdEmit->UpdateENCLog(*ptkModuleRef));

        // Set the name of ModuleRef.
        IfFailGo(pMiniMdEmit->PutString(TBL_ModuleRef, ModuleRefRec::COL_Name,
                                              pRecord, szName));
    }
    else
    {
        IfFailGo(hr);
    }
ErrExit:
    return hr;
} // ImportHelper::CreateModuleRefFromModuleRef


//******************************************************************************
// Given a ExportedType and the Assembly emit scope, create a corresponding ModuleRef
// in the give emit scope.  The ExportedType being passed in must belong to the
// Assembly passed in.  Function returns S_FALSE if the ExportedType is implemented
// by the emit scope passed in.
//******************************************************************************
HRESULT ImportHelper::CreateModuleRefFromExportedType(  // S_OK or error.
    CMiniMdRW   *pAssemEmit,            // [IN] Import assembly scope.
    CMiniMdRW   *pMiniMdEmit,           // [IN] Emit scope.
    mdExportedType   tkExportedType,              // [IN] ExportedType token in Assembly emit scope.
    mdModuleRef *ptkModuleRef)          // [OUT] ModuleRef token in the emit scope.
{
    mdFile      tkFile;
    LPCUTF8     szFile;
    LPCUTF8     szScope;
    FileRec     *pFileRec;
    HRESULT     hr = S_OK;

    // Set output to nil.
    *ptkModuleRef = mdTokenNil;

    // Get the implementation token for the ExportedType.  It must be a File token
    // since the caller should call this function only on ExportedTypes that resolve
    // to the same Assembly.
    IfFailGo(static_cast<IMetaModelCommon*>(pAssemEmit)->CommonGetExportedTypeProps(
        tkExportedType, 
        NULL, 
        NULL, 
        &tkFile));
    _ASSERTE(TypeFromToken(tkFile) == mdtFile);

    // Get the name of the file.
    IfFailGo(pAssemEmit->GetFileRecord(RidFromToken(tkFile), &pFileRec));
    IfFailGo(pAssemEmit->getNameOfFile(pFileRec, &szFile));

    // Get the name of the emit scope.
    IfFailGo(static_cast<IMetaModelCommon*>(pMiniMdEmit)->CommonGetScopeProps(
        &szScope, 
        0));

    // If the file corresponds to the emit scope, return S_FALSE;
    if (!strcmp(szFile, szScope))
        return S_FALSE;

    // See if a ModuleRef exists with this name.
    hr = FindModuleRef(pMiniMdEmit, szFile, ptkModuleRef);

    if (hr == CLDB_E_RECORD_NOTFOUND)
    {
        // Create ModuleRef record and set the output parameter.

        ModuleRefRec    *pRecord;
        RID             iRecord;

        IfFailGo(pMiniMdEmit->AddModuleRefRecord(&pRecord, &iRecord));
        *ptkModuleRef = TokenFromRid(iRecord, mdtModuleRef);
        IfFailGo(pMiniMdEmit->UpdateENCLog(*ptkModuleRef));

        // Set the name of ModuleRef.
        IfFailGo(pMiniMdEmit->PutString(TBL_ModuleRef, ModuleRefRec::COL_Name,
                                              pRecord, szFile));
    }
    else
        IfFailGo(hr);
ErrExit:
    return hr;
}   // ImportHelper::CreateModuleRefFromExportedType

//******************************************************************************
// Given an AssemblyRef and the corresponding scope, create an AssemblyRef in
// the given Module scope and Assembly scope.
//******************************************************************************
HRESULT ImportHelper::CreateAssemblyRefFromAssemblyRef(
    CMiniMdRW   *pMiniMdAssemEmit,      // [IN] Assembly emit scope.
    CMiniMdRW   *pMiniMdModuleEmit,     // [IN] Module emit scope
    IMetaModelCommon *pCommonImport,    // [IN] Scope to import the assembly ref from.
    mdAssemblyRef tkAssemRef,           // [IN] Assembly ref to be imported.
    mdAssemblyRef *ptkAssemblyRef)      // [OUT] AssemblyRef in the emit scope.
{
    AssemblyRefRec *pRecordEmit;
    CMiniMdRW   *rMiniMdRW[2];
    CMiniMdRW   *pMiniMdEmit;
    RID         iRecordEmit;
    USHORT      usMajorVersion;
    USHORT      usMinorVersion;
    USHORT      usBuildNumber;
    USHORT      usRevisionNumber;
    DWORD       dwFlags;
    const void  *pbPublicKeyOrToken;
    ULONG       cbPublicKeyOrToken;
    LPCUTF8     szName;
    LPCUTF8     szLocale;
    const void  *pbHashValue;
    ULONG       cbHashValue;
    HRESULT     hr = S_OK;

    // Set output to Nil.
    *ptkAssemblyRef = mdTokenNil;

    // Get import AssemblyRef props.
    IfFailGo(pCommonImport->CommonGetAssemblyRefProps(
        tkAssemRef, 
        &usMajorVersion, &usMinorVersion, &usBuildNumber, &usRevisionNumber, 
        &dwFlags, &pbPublicKeyOrToken, &cbPublicKeyOrToken, 
        &szName, &szLocale, 
        &pbHashValue, &cbHashValue));
    
    // Create the AssemblyRef in both the Assembly and Module emit scopes.
    rMiniMdRW[0] = pMiniMdAssemEmit;
    rMiniMdRW[1] = pMiniMdModuleEmit;

    for (ULONG i = 0; i < 2; i++)
    {
        pMiniMdEmit = rMiniMdRW[i];

        if (!pMiniMdEmit)
            continue;

        // See if the AssemblyRef already exists in the emit scope.
        hr = FindAssemblyRef(pMiniMdEmit, szName, szLocale, pbPublicKeyOrToken,
                             cbPublicKeyOrToken, usMajorVersion, usMinorVersion,
                             usBuildNumber, usRevisionNumber, dwFlags, &tkAssemRef);
        if (hr == CLDB_E_RECORD_NOTFOUND)
        {
            // Create the AssemblyRef record and set the output parameter.
            IfFailGo(pMiniMdEmit->AddAssemblyRefRecord(&pRecordEmit, &iRecordEmit));
            tkAssemRef = TokenFromRid(iRecordEmit, mdtAssemblyRef);
            IfFailGo(pMiniMdEmit->UpdateENCLog(tkAssemRef));

            // Set parameters derived from the import Assembly.
            pRecordEmit->SetMajorVersion(usMajorVersion);
            pRecordEmit->SetMinorVersion(usMinorVersion);
            pRecordEmit->SetBuildNumber(usBuildNumber);
            pRecordEmit->SetRevisionNumber(usRevisionNumber);
            pRecordEmit->SetFlags(dwFlags);

            IfFailGo(pMiniMdEmit->PutBlob(TBL_AssemblyRef, AssemblyRefRec::COL_PublicKeyOrToken,
                                          pRecordEmit, pbPublicKeyOrToken, cbPublicKeyOrToken));
            IfFailGo(pMiniMdEmit->PutString(TBL_AssemblyRef, AssemblyRefRec::COL_Name,
                                          pRecordEmit, szName));
            IfFailGo(pMiniMdEmit->PutString(TBL_AssemblyRef, AssemblyRefRec::COL_Locale,
                                          pRecordEmit, szLocale));

            // Set the parameters passed in for the AssemblyRef.
            IfFailGo(pMiniMdEmit->PutBlob(TBL_AssemblyRef, AssemblyRefRec::COL_HashValue,
                                          pRecordEmit, pbHashValue, cbHashValue));
        }
        else
            IfFailGo(hr);

        // Set the output parameter for the AssemblyRef emitted in Module emit scope.
        if (i)
            *ptkAssemblyRef = tkAssemRef;
    }
ErrExit:
    return hr;
} // ImportHelper::CreateAssemblyRefFromAssemblyRef

//******************************************************************************
// Given the Assembly Import scope, hash value and execution location, create
// a corresponding AssemblyRef in the given assembly and module emit scope.
// Set the output parameter to the AssemblyRef token emitted in the module emit
// scope.
//******************************************************************************
HRESULT 
ImportHelper::CreateAssemblyRefFromAssembly(
    CMiniMdRW *        pMiniMdAssemEmit,    // [IN] Emit assembly scope.
    CMiniMdRW *        pMiniMdModuleEmit,   // [IN] Emit module scope.
    IMetaModelCommon * pCommonAssemImport,  // [IN] Assembly import scope.
    const void *       pbHashValue,         // [IN] Hash Blob for Assembly.
    ULONG              cbHashValue,         // [IN] Count of bytes.
    mdAssemblyRef *    ptkAssemblyRef)      // [OUT] AssemblyRef token.
{
#ifdef FEATURE_METADATA_EMIT_IN_DEBUGGER
    return E_NOTIMPL;
#else //!FEATURE_METADATA_EMIT_IN_DEBUGGER
    AssemblyRefRec *pRecordEmit;
    CMiniMdRW   *rMiniMdRW[2];
    CMiniMdRW   *pMiniMdEmit;
    RID         iRecordEmit;
    USHORT      usMajorVersion;
    USHORT      usMinorVersion;
    USHORT      usBuildNumber;
    USHORT      usRevisionNumber;
    DWORD       dwFlags;
    const void  *pbPublicKey;
    ULONG       cbPublicKey;
    LPCUTF8     szName;
    LPCUTF8     szLocale;
    mdAssemblyRef tkAssemRef;
    HRESULT     hr = S_OK;
    const void  *pbToken = NULL;
    ULONG       cbToken = 0;
    ULONG       i;

    // Set output to Nil.
    *ptkAssemblyRef = mdTokenNil;

    // Get the Assembly props.
    IfFailGo(pCommonAssemImport->CommonGetAssemblyProps(
        &usMajorVersion, &usMinorVersion, &usBuildNumber, &usRevisionNumber, 
        &dwFlags, &pbPublicKey, &cbPublicKey,
        &szName, &szLocale));
    
    // Compress the public key into a token.
    if ((pbPublicKey != NULL) && (cbPublicKey != 0))
    {
        _ASSERTE(IsAfPublicKey(dwFlags));
        dwFlags &= ~afPublicKey;
        if (!StrongNameTokenFromPublicKey((BYTE*)pbPublicKey,
                                          cbPublicKey,
                                          (BYTE**)&pbToken,
                                          &cbToken))
            IfFailGo(StrongNameErrorInfo());
    }
    else
        _ASSERTE(!IsAfPublicKey(dwFlags));

    // Create the AssemblyRef in both the Assembly and Module emit scopes.
    rMiniMdRW[0] = pMiniMdAssemEmit;
    rMiniMdRW[1] = pMiniMdModuleEmit;

    for (i = 0; i < 2; i++)
    {
        pMiniMdEmit = rMiniMdRW[i];

        if (!pMiniMdEmit)
            continue;

        // See if the AssemblyRef already exists in the emit scope.
        hr = FindAssemblyRef(pMiniMdEmit, szName, szLocale, pbToken,
                             cbToken, usMajorVersion, usMinorVersion,
                             usBuildNumber, usRevisionNumber, dwFlags,
                             &tkAssemRef);
        if (hr == CLDB_E_RECORD_NOTFOUND)
        {
            // Create the AssemblyRef record and set the output parameter.
            IfFailGo(pMiniMdEmit->AddAssemblyRefRecord(&pRecordEmit, &iRecordEmit));
            tkAssemRef = TokenFromRid(iRecordEmit, mdtAssemblyRef);
            IfFailGo(pMiniMdEmit->UpdateENCLog(tkAssemRef));

            // Set parameters derived from the import Assembly.
            pRecordEmit->SetMajorVersion(usMajorVersion);
            pRecordEmit->SetMinorVersion(usMinorVersion);
            pRecordEmit->SetBuildNumber(usBuildNumber);
            pRecordEmit->SetRevisionNumber(usRevisionNumber);
            pRecordEmit->SetFlags(dwFlags);

            IfFailGo(pMiniMdEmit->PutBlob(TBL_AssemblyRef, AssemblyRefRec::COL_PublicKeyOrToken,
                                          pRecordEmit, pbToken, cbToken));
            IfFailGo(pMiniMdEmit->PutString(TBL_AssemblyRef, AssemblyRefRec::COL_Name,
                                          pRecordEmit, szName));
            IfFailGo(pMiniMdEmit->PutString(TBL_AssemblyRef, AssemblyRefRec::COL_Locale,
                                          pRecordEmit, szLocale));

            // Set the parameters passed in for the AssemblyRef.
            IfFailGo(pMiniMdEmit->PutBlob(TBL_AssemblyRef, AssemblyRefRec::COL_HashValue,
                                          pRecordEmit, pbHashValue, cbHashValue));
        }
        else
            IfFailGo(hr);

        // Set the output parameter for the AssemblyRef emitted in Module emit scope.
        if (i)
            *ptkAssemblyRef = tkAssemRef;
    }
ErrExit:
    if (pbToken)
        StrongNameFreeBuffer((BYTE*)pbToken);
    return hr;
#endif //!FEATURE_METADATA_EMIT_IN_DEBUGGER
} // ImportHelper::CreateAssemblyRefFromAssembly

//******************************************************************************
// Given an AssemblyRef and the corresponding scope, compare it to see if it
// refers to the given Assembly.
//******************************************************************************
HRESULT ImportHelper::CompareAssemblyRefToAssembly(    // S_OK, S_FALSE or error.
    IMetaModelCommon *pCommonAssem1,    // [IN] Scope that defines the AssemblyRef.
    mdAssemblyRef tkAssemRef,           // [IN] AssemblyRef.
    IMetaModelCommon *pCommonAssem2)    // [IN] Assembly against which the Ref is compared.
{
#ifdef FEATURE_METADATA_EMIT_IN_DEBUGGER
    return E_NOTIMPL;
#else //!FEATURE_METADATA_EMIT_IN_DEBUGGER
    HRESULT     hr;
    
    USHORT      usMajorVersion1;
    USHORT      usMinorVersion1;
    USHORT      usBuildNumber1;
    USHORT      usRevisionNumber1;
    const void  *pbPublicKeyOrToken1;
    ULONG       cbPublicKeyOrToken1;
    LPCUTF8     szName1;
    LPCUTF8     szLocale1;
    DWORD       dwFlags1;
    
    USHORT      usMajorVersion2;
    USHORT      usMinorVersion2;
    USHORT      usBuildNumber2;
    USHORT      usRevisionNumber2;
    const void  *pbPublicKey2;
    ULONG       cbPublicKey2;
    LPCUTF8     szName2;
    LPCUTF8     szLocale2;
    const void  *pbToken = NULL;
    ULONG       cbToken = 0;
    bool        fMatch;

    // Get the AssemblyRef props.
    IfFailRet(pCommonAssem1->CommonGetAssemblyRefProps(
        tkAssemRef, 
        &usMajorVersion1, &usMinorVersion1, &usBuildNumber1, &usRevisionNumber1, 
        &dwFlags1, &pbPublicKeyOrToken1, &cbPublicKeyOrToken1, 
        &szName1, &szLocale1, 
        NULL, NULL));
    // Get the Assembly props.
    IfFailRet(pCommonAssem2->CommonGetAssemblyProps(
        &usMajorVersion2, &usMinorVersion2, &usBuildNumber2, &usRevisionNumber2, 
        0, &pbPublicKey2, &cbPublicKey2,
        &szName2, &szLocale2));
    
    // Compare.
    if (usMajorVersion1 != usMajorVersion2 ||
        usMinorVersion1 != usMinorVersion2 ||
        usBuildNumber1 != usBuildNumber2 ||
        usRevisionNumber1 != usRevisionNumber2 ||
        strcmp(szName1, szName2) ||
        strcmp(szLocale1, szLocale2))
    {
        return S_FALSE;
    }

    // Defs always contain a full public key (or no key at all). Refs may have
    // no key, a full public key or a tokenized key.
    if ((cbPublicKeyOrToken1 && !cbPublicKey2) ||
        (!cbPublicKeyOrToken1 && cbPublicKey2))
        return S_FALSE;

    if (cbPublicKeyOrToken1)
    {
        // If ref contains a full public key we can just directly compare.
        if (IsAfPublicKey(dwFlags1) &&
            (cbPublicKeyOrToken1 != cbPublicKey2 ||
             memcmp(pbPublicKeyOrToken1, pbPublicKey2, cbPublicKeyOrToken1)))
            return S_FALSE;

        // Otherwise we need to compress the def public key into a token.
        if (!StrongNameTokenFromPublicKey((BYTE*)pbPublicKey2,
                                          cbPublicKey2,
                                          (BYTE**)&pbToken,
                                          &cbToken))
            return StrongNameErrorInfo();

        fMatch = cbPublicKeyOrToken1 == cbToken &&
            !memcmp(pbPublicKeyOrToken1, pbToken, cbPublicKeyOrToken1);

        StrongNameFreeBuffer((BYTE*)pbToken);

        if (!fMatch)
            return S_FALSE;
    }

    return S_OK;
#endif //!FEATURE_METADATA_EMIT_IN_DEBUGGER
} // ImportHelper::CompareAssemblyRefToAssembly

#endif //FEATURE_METADATA_EMIT