summaryrefslogtreecommitdiff
path: root/src/zap/zapimage.cpp
blob: 073367d2698a487ad1b0d56d0e231e0aee56d994 (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
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// ZapImage.cpp
//

//
// NGEN-specific infrastructure for writing PE files.
// 
// ======================================================================================

#include "common.h"
#include "strsafe.h"

#include "zaprelocs.h"

#include "zapinnerptr.h"
#include "zapwrapper.h"

#include "zapheaders.h"
#include "zapmetadata.h"
#include "zapcode.h"
#include "zapimport.h"

#ifdef FEATURE_READYTORUN_COMPILER
#include "zapreadytorun.h"
#endif

#include "md5.h"

// This is RTL_CONTAINS_FIELD from ntdef.h
#define CONTAINS_FIELD(Struct, Size, Field) \
    ( (((PCHAR)(&(Struct)->Field)) + sizeof((Struct)->Field)) <= (((PCHAR)(Struct))+(Size)) )

/* --------------------------------------------------------------------------- *
 * Destructor wrapper objects
 * --------------------------------------------------------------------------- */

ZapImage::ZapImage(Zapper *zapper)
  : m_zapper(zapper),
    m_stats(new ZapperStats())
    /* Everything else is initialized to 0 by default */
{
}

ZapImage::~ZapImage()
{
#ifdef ZAP_HASHTABLE_TUNING
    // If ZAP_HASHTABLE_TUNING is defined, preallocate is overloaded to print the tunning constants
    Preallocate();
#endif

    //
    // Clean up.
    //
    if (m_stats != NULL)
	    delete m_stats;

    if (m_pModuleFileName != NULL)
        delete [] m_pModuleFileName;

    if (m_pMDImport != NULL)
        m_pMDImport->Release();

    if (m_pAssemblyEmit != NULL)
        m_pAssemblyEmit->Release();

    if (m_profileDataFile != NULL)
        UnmapViewOfFile(m_profileDataFile);

    if (m_pPreloader)
        m_pPreloader->Release();

    if (m_pImportSectionsTable != NULL)
        m_pImportSectionsTable->~ZapImportSectionsTable();

    if (m_pGCInfoTable != NULL)
        m_pGCInfoTable->~ZapGCInfoTable();

#ifdef WIN64EXCEPTIONS
    if (m_pUnwindDataTable != NULL)
        m_pUnwindDataTable->~ZapUnwindDataTable();
#endif

    if (m_pStubDispatchDataTable != NULL)
        m_pStubDispatchDataTable->~ZapImportSectionSignatures();

    if (m_pExternalMethodDataTable != NULL)
        m_pExternalMethodDataTable->~ZapImportSectionSignatures();

    if (m_pDynamicHelperDataTable != NULL)
        m_pDynamicHelperDataTable->~ZapImportSectionSignatures();

    if (m_pDebugInfoTable != NULL)
        m_pDebugInfoTable->~ZapDebugInfoTable();

    if (m_pVirtualSectionsTable != NULL)
        m_pVirtualSectionsTable->~ZapVirtualSectionsTable();

    if (m_pILMetaData != NULL)
        m_pILMetaData->~ZapILMetaData();

    if (m_pBaseRelocs != NULL)
        m_pBaseRelocs->~ZapBaseRelocs();

    if (m_pAssemblyMetaData != NULL)
        m_pAssemblyMetaData->~ZapMetaData();

    //
    // Destruction of auxiliary tables in alphabetical order
    //

    if (m_pImportTable != NULL) 
        m_pImportTable->~ZapImportTable();

    if (m_pInnerPtrs != NULL) 
        m_pInnerPtrs->~ZapInnerPtrTable();

    if (m_pMethodEntryPoints != NULL)
        m_pMethodEntryPoints->~ZapMethodEntryPointTable();

    if (m_pWrappers != NULL) 
        m_pWrappers->~ZapWrapperTable();
}

void ZapImage::InitializeSections()
{
    AllocateVirtualSections();

    m_pCorHeader = new (GetHeap()) ZapCorHeader(this);
    m_pHeaderSection->Place(m_pCorHeader);

    SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_COMHEADER, m_pCorHeader);

    m_pNativeHeader = new (GetHeap()) ZapNativeHeader(this);
    m_pHeaderSection->Place(m_pNativeHeader);

    m_pCodeManagerEntry = new (GetHeap()) ZapCodeManagerEntry(this);
    m_pHeaderSection->Place(m_pCodeManagerEntry);

    m_pImportSectionsTable = new (GetHeap()) ZapImportSectionsTable(this);
    m_pImportTableSection->Place(m_pImportSectionsTable);

    m_pExternalMethodDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pExternalMethodThunkSection, m_pGCSection);
    m_pExternalMethodDataSection->Place(m_pExternalMethodDataTable);

    m_pStubDispatchDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pStubDispatchCellSection, m_pGCSection);
    m_pStubDispatchDataSection->Place(m_pStubDispatchDataTable);

    m_pImportTable = new (GetHeap()) ZapImportTable(this);
    m_pImportTableSection->Place(m_pImportTable);

    m_pGCInfoTable = new (GetHeap()) ZapGCInfoTable(this);
    m_pExceptionInfoLookupTable = new (GetHeap()) ZapExceptionInfoLookupTable(this);

#ifdef WIN64EXCEPTIONS
    m_pUnwindDataTable = new (GetHeap()) ZapUnwindDataTable(this);
#endif

    m_pEEInfoTable = ZapBlob::NewAlignedBlob(this, NULL, sizeof(CORCOMPILE_EE_INFO_TABLE), TARGET_POINTER_SIZE);
    m_pEETableSection->Place(m_pEEInfoTable);

    //
    // Allocate Helper table, and fill it out
    //

    m_pHelperThunks = new (GetHeap()) ZapNode * [CORINFO_HELP_COUNT];

    if (!m_zapper->m_pOpt->m_fNoMetaData)
    {
        m_pILMetaData = new (GetHeap()) ZapILMetaData(this);
        m_pILMetaDataSection->Place(m_pILMetaData);
    }

    m_pDebugInfoTable = new (GetHeap()) ZapDebugInfoTable(this);
    m_pDebugSection->Place(m_pDebugInfoTable);

    m_pBaseRelocs = new (GetHeap()) ZapBaseRelocs(this);
    m_pBaseRelocsSection->Place(m_pBaseRelocs);

    SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_BASERELOC, m_pBaseRelocsSection);

    //
    // Initialization of auxiliary tables in alphabetical order
    //
    m_pInnerPtrs = new (GetHeap()) ZapInnerPtrTable(this);
    m_pMethodEntryPoints = new (GetHeap()) ZapMethodEntryPointTable(this);
    m_pWrappers = new (GetHeap()) ZapWrapperTable(this);

    // Place the virtual sections tables in debug section. It exists for diagnostic purposes
    // only and should not be touched under normal circumstances    
    m_pVirtualSectionsTable = new (GetHeap()) ZapVirtualSectionsTable(this);
    m_pDebugSection->Place(m_pVirtualSectionsTable);

#ifndef ZAP_HASHTABLE_TUNING
    Preallocate();
#endif
}

#ifdef FEATURE_READYTORUN_COMPILER
void ZapImage::InitializeSectionsForReadyToRun()
{
    AllocateVirtualSections();

    // Preload sections are not used for ready to run. Clear the pointers to them to catch accidental use.
    for (int i = 0; i < CORCOMPILE_SECTION_COUNT; i++)
        m_pPreloadSections[i] = NULL;

    m_pCorHeader = new (GetHeap()) ZapCorHeader(this);
    m_pHeaderSection->Place(m_pCorHeader);

    SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_COMHEADER, m_pCorHeader);

    m_pNativeHeader = new (GetHeap()) ZapReadyToRunHeader(this);
    m_pHeaderSection->Place(m_pNativeHeader);

    m_pImportSectionsTable = new (GetHeap()) ZapImportSectionsTable(this);
    m_pHeaderSection->Place(m_pImportSectionsTable);

    {
#define COMPILER_NAME "CoreCLR"

        const char * pCompilerIdentifier = COMPILER_NAME " " FX_FILEVERSION_STR " " QUOTE_MACRO(__BUILDMACHINE__);
        ZapBlob * pCompilerIdentifierBlob = new (GetHeap()) ZapBlobPtr((PVOID)pCompilerIdentifier, strlen(pCompilerIdentifier) + 1);

        GetReadyToRunHeader()->RegisterSection(READYTORUN_SECTION_COMPILER_IDENTIFIER, pCompilerIdentifierBlob);
        m_pHeaderSection->Place(pCompilerIdentifierBlob);
    }

    m_pImportTable = new (GetHeap()) ZapImportTable(this);
    m_pImportTableSection->Place(m_pImportTable);

    for (int i=0; i<ZapImportSectionType_Total; i++)
    {
        ZapVirtualSection * pSection;
        if (i == ZapImportSectionType_Eager)
            pSection = m_pDelayLoadInfoDelayListSectionEager;
        else
        if (i < ZapImportSectionType_Cold)
            pSection = m_pDelayLoadInfoDelayListSectionHot;
        else
            pSection = m_pDelayLoadInfoDelayListSectionCold;

        m_pDelayLoadInfoDataTable[i] = new (GetHeap()) ZapImportSectionSignatures(this, m_pDelayLoadInfoTableSection[i]);
        pSection->Place(m_pDelayLoadInfoDataTable[i]);
    }

    m_pDynamicHelperDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pDynamicHelperCellSection);
    m_pDynamicHelperDataSection->Place(m_pDynamicHelperDataTable);

    m_pExternalMethodDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pExternalMethodCellSection, m_pGCSection);
    m_pExternalMethodDataSection->Place(m_pExternalMethodDataTable);

    m_pStubDispatchDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pStubDispatchCellSection, m_pGCSection);
    m_pStubDispatchDataSection->Place(m_pStubDispatchDataTable);

    m_pGCInfoTable = new (GetHeap()) ZapGCInfoTable(this);

#ifdef WIN64EXCEPTIONS
    m_pUnwindDataTable = new (GetHeap()) ZapUnwindDataTable(this);
#endif

    m_pILMetaData = new (GetHeap()) ZapILMetaData(this);
    m_pILMetaDataSection->Place(m_pILMetaData);

    m_pBaseRelocs = new (GetHeap()) ZapBaseRelocs(this);
    m_pBaseRelocsSection->Place(m_pBaseRelocs);

    SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_BASERELOC, m_pBaseRelocsSection);

    //
    // Initialization of auxiliary tables in alphabetical order
    //
    m_pInnerPtrs = new (GetHeap()) ZapInnerPtrTable(this);

    m_pExceptionInfoLookupTable = new (GetHeap()) ZapExceptionInfoLookupTable(this);

    //
    // Always allocate slot for module - it is used to determine that the image is used
    //
    m_pImportTable->GetPlacedHelperImport(READYTORUN_HELPER_Module);

    //
    // Make sure the import sections table is in the image, so we can find the slot for module
    //
    _ASSERTE(m_pImportSectionsTable->GetSize() != 0);
    GetReadyToRunHeader()->RegisterSection(READYTORUN_SECTION_IMPORT_SECTIONS, m_pImportSectionsTable);
}
#endif // FEATURE_READYTORUN_COMPILER


#define DATA_MEM_READONLY IMAGE_SCN_MEM_READ
#define DATA_MEM_WRITABLE IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
#define XDATA_MEM         IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
#define TEXT_MEM          IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ

void ZapImage::AllocateVirtualSections()
{
    //
    // Allocate all virtual sections in the order they will appear in the final image
    //
    // To maximize packing of the data in the native image, the number of named physical sections is minimized -  
    // the named physical sections are used just for memory protection control. All items with the same memory
    // protection are packed together in one physical section.
    //

    {
        //
        // .data section
        //
        DWORD access = DATA_MEM_WRITABLE;

#ifdef FEATURE_LAZY_COW_PAGES
        // READYTORUN: FUTURE: Optional support for COW pages
        if (!IsReadyToRunCompilation() && CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ZapLazyCOWPagesEnabled))
            access = DATA_MEM_READONLY;
#endif

        ZapPhysicalSection * pDataSection = NewPhysicalSection(".data", IMAGE_SCN_CNT_INITIALIZED_DATA | access);

        m_pPreloadSections[CORCOMPILE_SECTION_MODULE] = NewVirtualSection(pDataSection, IBCUnProfiledSection | HotRange | ModuleSection);

        m_pEETableSection = NewVirtualSection(pDataSection, IBCUnProfiledSection | HotRange | EETableSection); // Could be marked bss if it makes sense

        // These are all known to be hot or writeable
        m_pPreloadSections[CORCOMPILE_SECTION_WRITE] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | WriteDataSection);
        m_pPreloadSections[CORCOMPILE_SECTION_HOT_WRITEABLE] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | WriteableDataSection); // hot for reading, potentially written to 
        m_pPreloadSections[CORCOMPILE_SECTION_WRITEABLE] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | WriteableDataSection); // Cold based on IBC profiling data.
        m_pPreloadSections[CORCOMPILE_SECTION_HOT] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | DataSection);

        m_pPreloadSections[CORCOMPILE_SECTION_RVA_STATICS_HOT] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | RVAStaticsSection);

        m_pDelayLoadInfoTableSection[ZapImportSectionType_Eager] = NewVirtualSection(pDataSection, IBCUnProfiledSection | HotRange | DelayLoadInfoTableEagerSection, TARGET_POINTER_SIZE);

        //
        // Allocate dynamic info tables
        //

        // Place the HOT CorCompileTables now, the cold ones would be placed later in this routine (after other HOT sections)
        for (int i=0; i<ZapImportSectionType_Count; i++)
        {
            m_pDelayLoadInfoTableSection[i] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | DelayLoadInfoTableSection, TARGET_POINTER_SIZE);
        }

        m_pDynamicHelperCellSection = NewVirtualSection(pDataSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodDataSection, TARGET_POINTER_SIZE);

        m_pExternalMethodCellSection = NewVirtualSection(pDataSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodThunkSection, TARGET_POINTER_SIZE);

        // m_pStubDispatchCellSection is  deliberately placed  directly after
        // the last m_pDelayLoadInfoTableSection (all .data sections go together in the order indicated).
        // We do this to place it as the last "hot, written" section.  Why? Because
        // we don't split the dispatch cells into hot/cold sections (We probably should),
        // and so the section is actually half hot and half cold.
        // But it turns out that the hot dispatch cells always come
        // first (because the code that uses them is hot and gets compiled first).
        // Thus m_pStubDispatchCellSection contains all hot cells at the front of
        // this blob of data.  By making them last in a grouping of written data we
        // make sure the hot data is grouped with hot data in the
        // m_pDelayLoadInfoTableSection sections.

        m_pStubDispatchCellSection = NewVirtualSection(pDataSection, IBCProfiledSection | HotColdSortedRange | StubDispatchDataSection, TARGET_POINTER_SIZE);

        // Earlier we placed the HOT corCompile tables. Now place the cold ones after the stub dispatch cell section. 
        for (int i=0; i<ZapImportSectionType_Count; i++)
        {
            m_pDelayLoadInfoTableSection[ZapImportSectionType_Cold + i] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | DelayLoadInfoTableSection, TARGET_POINTER_SIZE);
        }

        //
        // Virtual sections that are moved to .cdata when we have profile data.
        //

        // This is everyhing that is assumed to be warm in the first strata
        // of non-profiled scenarios.  MethodTables related to objects etc.
        m_pPreloadSections[CORCOMPILE_SECTION_WARM] = NewVirtualSection(pDataSection, IBCProfiledSection | WarmRange | EEDataSection, TARGET_POINTER_SIZE);

        m_pPreloadSections[CORCOMPILE_SECTION_RVA_STATICS_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | RVAStaticsSection);

        // In an ideal world these are cold in both profiled and the first strata
        // of non-profiled scenarios (i.e. no reflection, etc. )  The sections at the
        // bottom correspond to further strata of non-profiled scenarios.
        m_pPreloadSections[CORCOMPILE_SECTION_CLASS_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | ClassSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_CROSS_DOMAIN_INFO] = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | CrossDomainInfoSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_DESC_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | MethodDescSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_DESC_COLD_WRITEABLE] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | MethodDescWriteableSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_MODULE_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | ModuleSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_DEBUG_COLD] = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | DebugSection, TARGET_POINTER_SIZE);

        //
        // If we're instrumenting allocate a section for writing profile data
        //
        if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_BBINSTR))
        {
            m_pInstrumentSection = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | InstrumentSection, TARGET_POINTER_SIZE);
        }
    }

    // No RWX pages in ready to run images
    if (!IsReadyToRunCompilation())
    {
        DWORD access = XDATA_MEM;

#ifdef FEATURE_LAZY_COW_PAGES
        if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ZapLazyCOWPagesEnabled))
            access = TEXT_MEM;
#endif            

        //
        // .xdata section
        //
        ZapPhysicalSection * pXDataSection  = NewPhysicalSection(".xdata", IMAGE_SCN_CNT_INITIALIZED_DATA | access);

        // Some sections are placed in a sorted order. Hot items are placed first,
        // then cold items. These sections are marked as HotColdSortedRange since
        // they are neither completely hot, nor completely cold. 
        m_pVirtualImportThunkSection        = NewVirtualSection(pXDataSection, IBCProfiledSection | HotColdSortedRange | VirtualImportThunkSection, HELPER_TABLE_ALIGN);
        m_pExternalMethodThunkSection       = NewVirtualSection(pXDataSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodThunkSection, HELPER_TABLE_ALIGN);
        m_pHelperTableSection               = NewVirtualSection(pXDataSection, IBCProfiledSection | HotColdSortedRange| HelperTableSection, HELPER_TABLE_ALIGN);

        // hot for writing, i.e. profiling has indicated a write to this item, so at least one write likely per item at some point
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_WRITE] = NewVirtualSection(pXDataSection, IBCProfiledSection | HotRange | MethodPrecodeWriteSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_HOT] = NewVirtualSection(pXDataSection, IBCProfiledSection | HotRange | MethodPrecodeSection, TARGET_POINTER_SIZE);

        //
        // cold sections
        //
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_COLD] = NewVirtualSection(pXDataSection, IBCProfiledSection | ColdRange | MethodPrecodeSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_COLD_WRITEABLE] = NewVirtualSection(pXDataSection, IBCProfiledSection | ColdRange | MethodPrecodeWriteableSection, TARGET_POINTER_SIZE);
    }

    {
        // code:NativeUnwindInfoLookupTable::LookupUnwindInfoForMethod and code:NativeImageJitManager::GetFunctionEntry expects 
        // sentinel value right after end of .pdata section. 
        static const DWORD dwRuntimeFunctionSectionSentinel = (DWORD)-1;


        //
        // .text section
        //
#if defined(_TARGET_ARM_)
        // for ARM, put the resource section at the end if it's very large - this
        // is because b and bl instructions have a limited distance range of +-16MB
        // which we should not exceed if we can avoid it.
        // we draw the limit at 1 MB resource size, somewhat arbitrarily
        COUNT_T resourceSize;
        m_ModuleDecoder.GetResources(&resourceSize);
        BOOL bigResourceSection = resourceSize >= 1024*1024;
#endif
        ZapPhysicalSection * pTextSection = NewPhysicalSection(".text", IMAGE_SCN_CNT_CODE | TEXT_MEM);
        m_pTextSection = pTextSection;

        // Marked as HotRange since it contains items that are always touched by
        // the OS during NGEN image loading (i.e. VersionInfo) 
        m_pWin32ResourceSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | Win32ResourcesSection);

        // Marked as a HotRange since it is always touched during Ngen image load. 
        m_pHeaderSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | HeaderSection);

        // Marked as a HotRange since it is always touched during Ngen image binding.
        m_pMetaDataSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | MetadataSection);

        m_pImportTableSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | ImportTableSection, sizeof(DWORD));

        m_pDelayLoadInfoDelayListSectionEager = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | DelayLoadInfoDelayListSection, sizeof(DWORD));

        //
        // GC Info for methods which were profiled hot AND had their GC Info touched during profiling
        //
        m_pHotTouchedGCSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | GCInfoSection, sizeof(DWORD));

        m_pLazyHelperSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | HelperTableSection, MINIMUM_CODE_ALIGN);
        m_pLazyHelperSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);

        m_pLazyMethodCallHelperSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | HelperTableSection, MINIMUM_CODE_ALIGN);
        m_pLazyMethodCallHelperSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);

        int codeSectionAlign = DEFAULT_CODE_ALIGN;

        m_pHotCodeSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | CodeSection, codeSectionAlign);
        m_pHotCodeSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);

#if defined(WIN64EXCEPTIONS)
        m_pHotUnwindDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | UnwindDataSection, sizeof(DWORD)); // .rdata area

        // All RuntimeFunctionSections have to be together for WIN64EXCEPTIONS
        m_pHotRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD));  // .pdata area
        m_pRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange  | ColdRange | RuntimeFunctionSection, sizeof(DWORD));
        m_pColdRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD));

        // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification 
        NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD))
            ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
#endif  // defined(WIN64EXCEPTIONS)

        m_pStubsSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | StubsSection);
        m_pReadOnlyDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ReadonlyDataSection);

        m_pDynamicHelperDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodDataSection, sizeof(DWORD));
        m_pExternalMethodDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodDataSection, sizeof(DWORD));
        m_pStubDispatchDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | StubDispatchDataSection, sizeof(DWORD));

        m_pHotRuntimeFunctionLookupSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD));
#if !defined(WIN64EXCEPTIONS)
        m_pHotRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD));

        // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification 
        NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD))
            ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
#endif
        m_pHotCodeMethodDescsSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | CodeManagerSection, sizeof(DWORD));

        m_pDelayLoadInfoDelayListSectionHot = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | DelayLoadInfoDelayListSection, sizeof(DWORD));

        //
        // The hot set of read-only data structures.  Note that read-only data structures are the things that we can (and aggressively do) intern
        // to share between different owners.  However, this can have a bad interaction with IBC, which performs its ordering optimizations without
        // knowing that NGen may jumble around layout with interning.  Thankfully, it is a relatively small percentage of the items that are duplicates
        // (many of them used a great deal to add up to large interning savings).  This means that we can track all of the interned items for which we
        // actually find any duplicates and put those in a small section.  For the rest, where there wasn't a duplicate in the entire image, we leave the
        // singleton in its normal place in the READONLY_HOT section, which was selected carefully by IBC.
        //
        m_pPreloadSections[CORCOMPILE_SECTION_READONLY_SHARED_HOT] = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | ReadonlySharedSection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_READONLY_HOT] = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | ReadonlySection, TARGET_POINTER_SIZE);

        //
        // GC Info for methods which were touched during profiling but didn't explicitly have
        // their GC Info touched during profiling
        //
        m_pHotGCSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | GCInfoSection, sizeof(DWORD));

#if !defined(_TARGET_ARM_)
        // For ARM, put these sections more towards the end because bl/b instructions have limited diplacement

        // IL
        m_pILSection  = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILSection, sizeof(DWORD));

        //ILMetadata/Resources sections are reported as a statically known warm ranges for now.
        m_pILMetaDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILMetadataSection, sizeof(DWORD));
#endif  // _TARGET_ARM_

#if defined(_TARGET_ARM_)
        if (!bigResourceSection) // for ARM, put the resource section at the end if it's very large - see comment above
#endif
            m_pResourcesSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | WarmRange | ResourcesSection);

        //
        // Allocate the unprofiled code section and code manager nibble map here
        //
        m_pCodeSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | CodeSection, codeSectionAlign);
        m_pCodeSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);

        m_pRuntimeFunctionLookupSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | RuntimeFunctionSection, sizeof(DWORD));
#if !defined(WIN64EXCEPTIONS)
        m_pRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange  | ColdRange | RuntimeFunctionSection, sizeof(DWORD));

        // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification 
        NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange  | ColdRange | RuntimeFunctionSection, sizeof(DWORD))
            ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
#endif
        m_pCodeMethodDescsSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | CodeHeaderSection,sizeof(DWORD));

#ifdef FEATURE_READYTORUN_COMPILER
        if (IsReadyToRunCompilation())
        {
            m_pAvailableTypesSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | WarmRange | ReadonlySection);
        }
#endif    

#if defined(WIN64EXCEPTIONS)
        m_pUnwindDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | UnwindDataSection, sizeof(DWORD));
#endif // defined(WIN64EXCEPTIONS)

        m_pPreloadSections[CORCOMPILE_SECTION_READONLY_WARM] = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ReadonlySection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_READONLY_VCHUNKS] = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ReadonlySection, TARGET_POINTER_SIZE);
        m_pPreloadSections[CORCOMPILE_SECTION_READONLY_DICTIONARY] = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ReadonlySection, TARGET_POINTER_SIZE);

        //
        // GC Info for methods which were not touched in profiling
        //
        m_pGCSection = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | GCInfoSection, sizeof(DWORD));

        m_pDelayLoadInfoDelayListSectionCold = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | DelayLoadInfoDelayListSection, sizeof(DWORD));

        m_pPreloadSections[CORCOMPILE_SECTION_READONLY_COLD] = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | ReadonlySection, TARGET_POINTER_SIZE);

        //
        // Allocate the cold code section near the end of the image
        //
        m_pColdCodeSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | CodeSection, codeSectionAlign);
        m_pColdCodeSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);

#if defined(_TARGET_ARM_)
        // For ARM, put these sections more towards the end because bl/b instructions have limited diplacement

        // IL
        m_pILSection  = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILSection, sizeof(DWORD));

        //ILMetadata/Resources sections are reported as a statically known warm ranges for now.
        m_pILMetaDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILMetadataSection, sizeof(DWORD));

        if (bigResourceSection) // for ARM, put the resource section at the end if it's very large - see comment above
            m_pResourcesSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | WarmRange | ResourcesSection);
#endif // _TARGET_ARM_
        m_pColdCodeMapSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | CodeManagerSection, sizeof(DWORD));

#if !defined(WIN64EXCEPTIONS)
        m_pColdRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD));

        // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification 
        NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD))
            ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
#endif

#if defined(WIN64EXCEPTIONS)
        m_pColdUnwindDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | UnwindDataSection, sizeof(DWORD));
#endif // defined(WIN64EXCEPTIONS)

        //
        // Allocate space for compressed LookupMaps (ridmaps). This needs to come after the .data physical
        // section (which is currently true for the .text section) and late enough in the .text section to be
        // after any structure referenced by the LookupMap (current MethodTables and MethodDescs). This is a
        // hard requirement since the compression algorithm requires that all referenced data structures have
        // been laid out by the time we come to lay out the compressed nodes.
        //
        m_pPreloadSections[CORCOMPILE_SECTION_COMPRESSED_MAPS] = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | CompressedMapsSection, sizeof(DWORD));

        m_pExceptionSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ExceptionSection, sizeof(DWORD));

        //
        // Debug info is sometimes used during exception handling to build stacktrace
        //
        m_pDebugSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | ColdRange | DebugSection, sizeof(DWORD));
    }

    {
        //
        // .reloc section
        //

        ZapPhysicalSection * pRelocSection = NewPhysicalSection(".reloc", IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ);

        // .reloc section is always read by the OS when the image is opted in ASLR
        // (Vista+ default behavior). 
        m_pBaseRelocsSection = NewVirtualSection(pRelocSection, IBCUnProfiledSection | HotRange | BaseRelocsSection);

    }
}

void ZapImage::Preallocate()
{
    COUNT_T cbILImage = m_ModuleDecoder.GetSize();

    // Curb the estimate to handle corner cases gracefuly
    cbILImage = min(cbILImage, 50000000);

    PREALLOCATE_HASHTABLE(ZapImage::m_CompiledMethods, 0.0050, cbILImage);
    PREALLOCATE_HASHTABLE(ZapImage::m_ClassLayoutOrder, 0.0003, cbILImage);

    //
    // Preallocation of auxiliary tables in alphabetical order
    //
    m_pImportTable->Preallocate(cbILImage);
    m_pInnerPtrs->Preallocate(cbILImage);
    m_pMethodEntryPoints->Preallocate(cbILImage);
    m_pWrappers->Preallocate(cbILImage);

    if (m_pILMetaData != NULL)
        m_pILMetaData->Preallocate(cbILImage);
    m_pGCInfoTable->Preallocate(cbILImage);
#ifdef WIN64EXCEPTIONS
    m_pUnwindDataTable->Preallocate(cbILImage);
#endif // WIN64EXCEPTIONS
    m_pDebugInfoTable->Preallocate(cbILImage);
}

void ZapImage::SetVersionInfo(CORCOMPILE_VERSION_INFO * pVersionInfo)
{
    m_pVersionInfo = new (GetHeap()) ZapVersionInfo(pVersionInfo);
    m_pHeaderSection->Place(m_pVersionInfo);
}

void ZapImage::SetDependencies(CORCOMPILE_DEPENDENCY *pDependencies, DWORD cDependencies)
{
    m_pDependencies = new (GetHeap()) ZapDependencies(pDependencies, cDependencies);
    m_pHeaderSection->Place(m_pDependencies);
}

void ZapImage::SetPdbFileName(const SString &strFileName)
{
    m_pdbFileName.Set(strFileName);
}

#ifdef WIN64EXCEPTIONS
void ZapImage::SetRuntimeFunctionsDirectoryEntry()
{
    //
    // Runtime functions span multiple virtual sections and so there is no natural ZapNode * to cover them all.
    // Create dummy ZapNode * that covers them all for IMAGE_DIRECTORY_ENTRY_EXCEPTION directory entry.
    //
    ZapVirtualSection * rgRuntimeFunctionSections[] = {
        m_pHotRuntimeFunctionSection,
        m_pRuntimeFunctionSection,
        m_pColdRuntimeFunctionSection
    };

    DWORD dwTotalSize = 0, dwStartRVA = (DWORD)-1, dwEndRVA = 0;

    for (size_t i = 0; i < _countof(rgRuntimeFunctionSections); i++)
    {
        ZapVirtualSection * pSection = rgRuntimeFunctionSections[i];

        DWORD dwSize = pSection->GetSize();
        if (dwSize == 0)
            continue;

        DWORD dwRVA = pSection->GetRVA();

        dwTotalSize += dwSize;

        dwStartRVA = min(dwStartRVA, dwRVA);
        dwEndRVA = max(dwEndRVA, dwRVA + dwSize);
    }

    if (dwTotalSize != 0)
    {
        // Verify that there are no holes between the sections
        _ASSERTE(dwStartRVA + dwTotalSize == dwEndRVA);

        ZapNode * pAllRuntimeFunctionSections = new (GetHeap()) ZapDummyNode(dwTotalSize);
        pAllRuntimeFunctionSections->SetRVA(dwStartRVA);

        // Write the address of the sorted pdata to the optionalHeader.DataDirectory
        SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXCEPTION, pAllRuntimeFunctionSections);
    }
}
#endif // WIN64EXCEPTIONS

// Assign RVAs to all ZapNodes
void ZapImage::ComputeRVAs()
{
    ZapWriter::ComputeRVAs();

    if (!IsReadyToRunCompilation())
    {
        m_pMethodEntryPoints->Resolve();
        m_pWrappers->Resolve();
    }

    m_pInnerPtrs->Resolve();

#ifdef WIN64EXCEPTIONS
    SetRuntimeFunctionsDirectoryEntry();
#endif

#if defined(_DEBUG) 
#ifdef FEATURE_SYMDIFF
    if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SymDiffDump))
    {
        COUNT_T curMethod = 0;
        COUNT_T numMethods = m_MethodCompilationOrder.GetCount();

        for (; curMethod < numMethods; curMethod++)
        {
            bool fCold = false;
            //if(curMethod >= m_iUntrainedMethod) fCold = true;
    		
            ZapMethodHeader * pMethod = m_MethodCompilationOrder[curMethod];

            ZapBlobWithRelocs * pCode = fCold ? pMethod->m_pColdCode : pMethod->m_pCode;
            if (pCode == NULL)
            {            
                continue;
            }
            CORINFO_METHOD_HANDLE handle = pMethod->GetHandle();
            mdMethodDef token;
            GetCompileInfo()->GetMethodDef(handle, &token);
            GetSvcLogger()->Printf(W("(EntryPointRVAMap (MethodToken %0X) (RVA %0X) (SIZE %0X))\n"), token, pCode->GetRVA(), pCode->GetSize()); 
        }

    }
#endif // FEATURE_SYMDIFF 
#endif //_DEBUG
}

class ZapFileStream : public IStream
{
    HANDLE  m_hFile;
    MD5 m_hasher;

public:
    ZapFileStream()
        : m_hFile(INVALID_HANDLE_VALUE)
    {
        m_hasher.Init();
    }

    ~ZapFileStream()
    {
        Close();
    }

    void SetHandle(HANDLE hFile)
    {
        _ASSERTE(m_hFile == INVALID_HANDLE_VALUE);
        m_hFile = hFile;
    }

    // IUnknown methods:
    STDMETHODIMP_(ULONG) AddRef()
    {
        return 1;
    }

    STDMETHODIMP_(ULONG) Release()
    {
        return 1;
    }

    STDMETHODIMP QueryInterface(REFIID riid, LPVOID *ppv)
    {
        HRESULT hr = S_OK;
        if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IStream)) {
            *ppv = static_cast<IStream *>(this);
        }
        else {
            hr = E_NOINTERFACE;
        }
        return hr;
    }

    // ISequentialStream methods:
    STDMETHODIMP Read(void *pv, ULONG cb, ULONG *pcbRead)
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    STDMETHODIMP Write(void const *pv, ULONG cb, ULONG *pcbWritten)
    {
        HRESULT hr = S_OK;

        _ASSERTE(m_hFile != INVALID_HANDLE_VALUE);

        m_hasher.HashMore(pv, cb);

        // We are calling with lpOverlapped == NULL so pcbWritten has to be present
        // to prevent crashes in Win7 and below.
        _ASSERTE(pcbWritten);

        if (!::WriteFile(m_hFile, pv, cb, pcbWritten, NULL))
        {
            hr = HRESULT_FROM_GetLastError();
            goto Exit;
        }

    Exit:
        return hr;
    }

    // IStream methods:
    STDMETHODIMP Seek(LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition)
    {
        HRESULT hr = S_OK;        

        _ASSERTE(m_hFile != INVALID_HANDLE_VALUE);

        DWORD dwFileOrigin;
        switch (dwOrigin) {
            case STREAM_SEEK_SET:
                dwFileOrigin = FILE_BEGIN;
                break;
                
            case STREAM_SEEK_CUR:
                dwFileOrigin = FILE_CURRENT;
                break;
                
            case STREAM_SEEK_END:
                dwFileOrigin = FILE_END;
                break;
                
            default:
                hr = E_UNEXPECTED;
                goto Exit;
        }
        if (!::SetFilePointerEx(m_hFile, dlibMove, (LARGE_INTEGER *)plibNewPosition, dwFileOrigin))
        {
            hr = HRESULT_FROM_GetLastError();
            goto Exit;
        }

    Exit:
        return hr;
    }

    STDMETHODIMP SetSize(ULARGE_INTEGER libNewSize)
    {
        HRESULT hr = S_OK;

        _ASSERTE(m_hFile != INVALID_HANDLE_VALUE);

        hr = Seek(*(LARGE_INTEGER *)&libNewSize, FILE_BEGIN, NULL);
        if (FAILED(hr))
        {
            goto Exit;
        }

        if (!::SetEndOfFile(m_hFile))
        {
            hr = HRESULT_FROM_GetLastError();
            goto Exit;
        }

    Exit:
        return hr;
    }

    STDMETHODIMP CopyTo(IStream *pstm, ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten)
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    STDMETHODIMP Commit(DWORD grfCommitFlags)
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    STDMETHODIMP Revert()
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    STDMETHODIMP LockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    STDMETHODIMP UnlockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    STDMETHODIMP Stat(STATSTG *pstatstg, DWORD grfStatFlag)
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    STDMETHODIMP Clone(IStream **ppIStream)
    {
        _ASSERTE(false);
        return E_NOTIMPL;
    }

    HRESULT Close()
    {
        HRESULT hr = S_OK;

        HANDLE hFile = m_hFile;
        if (hFile != INVALID_HANDLE_VALUE)
        {
            m_hFile = INVALID_HANDLE_VALUE;

            if (!::CloseHandle(hFile))
            {
                hr = HRESULT_FROM_GetLastError();
                goto Exit;
            }
        }

    Exit:
        return hr;
    }

    void SuppressClose()
    {
        m_hFile = INVALID_HANDLE_VALUE;
    }

    void GetHash(MD5HASHDATA* pHash)
    {
        m_hasher.GetHashValue(pHash);
    }
};

HANDLE ZapImage::GenerateFile(LPCWSTR wszOutputFileName, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig)
{
    ZapFileStream outputStream;

    HANDLE hFile = WszCreateFile(wszOutputFileName,
                        GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_DELETE,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
                        NULL);

    if (hFile == INVALID_HANDLE_VALUE)
        ThrowLastError();

    outputStream.SetHandle(hFile);

    Save(&outputStream);

    LARGE_INTEGER filePos;

    if (m_pNativeHeader != NULL)
    {
        // Write back the updated CORCOMPILE_HEADER (relocs and guid is not correct the first time around)
        filePos.QuadPart = m_pTextSection->GetFilePos() + 
            (m_pNativeHeader->GetRVA() - m_pTextSection->GetRVA());
        IfFailThrow(outputStream.Seek(filePos, STREAM_SEEK_SET, NULL));
        m_pNativeHeader->Save(this);
        FlushWriter();
    }

    GUID signature = {0};

    static_assert_no_msg(sizeof(GUID) == sizeof(MD5HASHDATA));
    outputStream.GetHash((MD5HASHDATA*)&signature);

    {    
        // Write the debug directory entry for the NGEN PDB
        RSDS rsds = {0};
        
        rsds.magic = 'SDSR';
        rsds.age = 1;
        // our PDB signature will be the same as our NGEN signature.  
        // However we want the printed version of the GUID to be be the same as the
        // byte dump of the signature so we swap bytes to make this work.  
        // 
        // * See code:CCorSvcMgr::CreatePdb for where this is used.
        BYTE* asBytes = (BYTE*) &signature;
        rsds.signature.Data1 = ((asBytes[0] * 256 + asBytes[1]) * 256 + asBytes[2]) * 256 + asBytes[3];
        rsds.signature.Data2 = asBytes[4] * 256 + asBytes[5];
        rsds.signature.Data3 = asBytes[6] * 256 + asBytes[7];
        memcpy(&rsds.signature.Data4, &asBytes[8], 8);

        _ASSERTE(!m_pdbFileName.IsEmpty());
        ZeroMemory(&rsds.path[0], sizeof(rsds.path));
        if (WideCharToMultiByte(CP_UTF8, 
                                0, 
                                m_pdbFileName.GetUnicode(),
                                m_pdbFileName.GetCount(), 
                                &rsds.path[0], 
                                sizeof(rsds.path) - 1, // -1 to keep the buffer zero terminated
                                NULL, 
                                NULL) == 0)
            ThrowHR(E_FAIL);
        
        ULONG cbWritten = 0;
        filePos.QuadPart = m_pTextSection->GetFilePos() + (m_pNGenPdbDebugData->GetRVA() - m_pTextSection->GetRVA());
        IfFailThrow(outputStream.Seek(filePos, STREAM_SEEK_SET, NULL));
        IfFailThrow(outputStream.Write(&rsds, sizeof rsds, &cbWritten));
    }

    if (m_pVersionInfo != NULL)
    {
        ULONG cbWritten;

        filePos.QuadPart = m_pTextSection->GetFilePos() + 
            (m_pVersionInfo->GetRVA() - m_pTextSection->GetRVA()) + 
            offsetof(CORCOMPILE_VERSION_INFO, signature);
        IfFailThrow(outputStream.Seek(filePos, STREAM_SEEK_SET, NULL));
        IfFailThrow(outputStream.Write(&signature, sizeof(signature), &cbWritten));

        if (pNativeImageSig != NULL)
            *pNativeImageSig = signature;
    }
    else
    {
        _ASSERTE(pNativeImageSig == NULL);
    }

    outputStream.SuppressClose();
    return hFile;
}


HANDLE ZapImage::SaveImage(LPCWSTR wszOutputFileName, LPCWSTR wszDllPath, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig)
{
    if (!IsReadyToRunCompilation())
    {
        OutputManifestMetadata();
    }

    OutputTables();

    // Create a empty export table.  This makes tools like symchk not think
    // that native images are resoure-only DLLs.  It is important to NOT
    // be a resource-only DLL because those DLL's PDBS are not put up on the
    // symbol server and we want NEN PDBS to be placed there.  
    ZapPEExports* exports = new(GetHeap()) ZapPEExports(wszDllPath);
    m_pDebugSection->Place(exports);
    SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXPORT, exports);
    
    ComputeRVAs();

    if (!IsReadyToRunCompilation())
    {
        m_pPreloader->FixupRVAs();
    }

    HANDLE hFile = GenerateFile(wszOutputFileName, pNativeImageSig);

    if (m_zapper->m_pOpt->m_verbose)
    {
        PrintStats(wszOutputFileName);
    }

    return hFile;
}

void ZapImage::PrintStats(LPCWSTR wszOutputFileName)
{
#define ACCUM_SIZE(dest, src) if( src != NULL ) dest+= src->GetSize()
    ACCUM_SIZE(m_stats->m_gcInfoSize, m_pHotTouchedGCSection);
    ACCUM_SIZE(m_stats->m_gcInfoSize, m_pHotGCSection);
    ACCUM_SIZE(m_stats->m_gcInfoSize, m_pGCSection);
#if defined(WIN64EXCEPTIONS)
    ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pUnwindDataSection);
    ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pHotRuntimeFunctionSection);
    ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pRuntimeFunctionSection);
    ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pColdRuntimeFunctionSection);
#endif // defined(WIN64EXCEPTIONS)

    //
    // Get the size of the input & output files
    //

    {
        WIN32_FIND_DATA inputData;
        FindHandleHolder inputHandle = WszFindFirstFile(m_pModuleFileName, &inputData);
        if (inputHandle != INVALID_HANDLE_VALUE)
            m_stats->m_inputFileSize = inputData.nFileSizeLow;
    }

    {
        WIN32_FIND_DATA outputData;
        FindHandleHolder outputHandle = WszFindFirstFile(wszOutputFileName, &outputData);
        if (outputHandle != INVALID_HANDLE_VALUE)
            m_stats->m_outputFileSize = outputData.nFileSizeLow;
    }

    ACCUM_SIZE(m_stats->m_metadataSize, m_pAssemblyMetaData);

    DWORD dwPreloadSize = 0;
    for (int iSection = 0; iSection < CORCOMPILE_SECTION_COUNT; iSection++)
        ACCUM_SIZE(dwPreloadSize, m_pPreloadSections[iSection]);
    m_stats->m_preloadImageSize = dwPreloadSize;

    ACCUM_SIZE(m_stats->m_hotCodeMgrSize, m_pHotCodeMethodDescsSection);
    ACCUM_SIZE(m_stats->m_unprofiledCodeMgrSize, m_pCodeMethodDescsSection);
    ACCUM_SIZE(m_stats->m_coldCodeMgrSize, m_pHotRuntimeFunctionLookupSection);

    ACCUM_SIZE(m_stats->m_eeInfoTableSize, m_pEEInfoTable);
    ACCUM_SIZE(m_stats->m_helperTableSize, m_pHelperTableSection);
    ACCUM_SIZE(m_stats->m_dynamicInfoTableSize, m_pImportSectionsTable);

    ACCUM_SIZE(m_stats->m_dynamicInfoDelayListSize, m_pDelayLoadInfoDelayListSectionEager);
    ACCUM_SIZE(m_stats->m_dynamicInfoDelayListSize, m_pDelayLoadInfoDelayListSectionHot);
    ACCUM_SIZE(m_stats->m_dynamicInfoDelayListSize, m_pDelayLoadInfoDelayListSectionCold);

    ACCUM_SIZE(m_stats->m_importTableSize, m_pImportTable);

    ACCUM_SIZE(m_stats->m_debuggingTableSize, m_pDebugSection);
    ACCUM_SIZE(m_stats->m_headerSectionSize, m_pGCSection);
    ACCUM_SIZE(m_stats->m_codeSectionSize, m_pHotCodeSection);
    ACCUM_SIZE(m_stats->m_coldCodeSectionSize, m_pColdCodeSection);
    ACCUM_SIZE(m_stats->m_exceptionSectionSize, m_pExceptionSection);
    ACCUM_SIZE(m_stats->m_readOnlyDataSectionSize, m_pReadOnlyDataSection);
    ACCUM_SIZE(m_stats->m_relocSectionSize, m_pBaseRelocsSection);
    ACCUM_SIZE(m_stats->m_ILMetadataSize, m_pILMetaData);
    ACCUM_SIZE(m_stats->m_virtualImportThunkSize, m_pVirtualImportThunkSection);
    ACCUM_SIZE(m_stats->m_externalMethodThunkSize, m_pExternalMethodThunkSection);
    ACCUM_SIZE(m_stats->m_externalMethodDataSize, m_pExternalMethodDataSection);
#undef ACCUM_SIZE

    if (m_stats->m_failedMethods)
        m_zapper->Warning(W("Warning: %d methods (%d%%) could not be compiled.\n"),
                          m_stats->m_failedMethods, (m_stats->m_failedMethods*100) / m_stats->m_methods);
    if (m_stats->m_failedILStubs)
        m_zapper->Warning(W("Warning: %d IL STUB methods could not be compiled.\n"),
                          m_stats->m_failedMethods);
    m_stats->PrintStats();
}

// Align native images to 64K
const SIZE_T BASE_ADDRESS_ALIGNMENT  = 0xffff;
const double CODE_EXPANSION_FACTOR   =  3.6;

void ZapImage::CalculateZapBaseAddress()
{
    static SIZE_T nextBaseAddressForMultiModule;

    SIZE_T baseAddress = 0;

    {
        // Read the actual preferred base address from the disk

        // Note that we are reopening the file here. We are not guaranteed to get the same file.
        // The worst thing that can happen is that we will read a bogus preferred base address from the file.
        HandleHolder hFile(WszCreateFile(m_pModuleFileName,
                                            GENERIC_READ,
                                            FILE_SHARE_READ|FILE_SHARE_DELETE,
                                            NULL,
                                            OPEN_EXISTING,
                                            FILE_ATTRIBUTE_NORMAL,
                                            NULL));
        if (hFile == INVALID_HANDLE_VALUE)
            ThrowLastError();

        HandleHolder hFileMap(WszCreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL));
        if (hFileMap == NULL)
            ThrowLastError();

        MapViewHolder base(MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0));
        if (base == NULL)
            ThrowLastError();
    
        DWORD dwFileLen = SafeGetFileSize(hFile, 0);
        if (dwFileLen == INVALID_FILE_SIZE)
            ThrowLastError();

        PEDecoder peFlat((void *)base, (COUNT_T)dwFileLen);

        baseAddress = (SIZE_T) peFlat.GetPreferredBase();
    }

    // See if the header has the linker's default preferred base address
    if (baseAddress == (SIZE_T) 0x00400000)
    {
        if (m_fManifestModule)
        {
            // Set the base address for the main assembly with the manifest
        
            if (!m_ModuleDecoder.IsDll())
            {
#if defined(_TARGET_X86_)
                // We use 30000000 for an exe
                baseAddress = 0x30000000;
#elif defined(_TARGET_64BIT_)
                // We use 04000000 for an exe
                // which is remapped to 0x642`88000000 on x64
                baseAddress = 0x04000000;
#endif
            }
            else
            {
#if defined(_TARGET_X86_)
                // We start a 31000000 for the main assembly with the manifest
                baseAddress = 0x31000000;
#elif defined(_TARGET_64BIT_)
                // We start a 05000000 for the main assembly with the manifest
                // which is remapped to 0x642`8A000000 on x64
                baseAddress = 0x05000000;
#endif
            }
        }
        else // is dependent assembly of a multi-module assembly
        {
            // Set the base address for a dependant multi module assembly
                
            // We should have already set the nextBaseAddressForMultiModule
            // when we compiled the manifest module
            _ASSERTE(nextBaseAddressForMultiModule != 0);
            baseAddress = nextBaseAddressForMultiModule;
        }
    }
    else 
    {
        //
        // For some assemblies we have to move the ngen image base address up
        // past the end of IL image so that that we don't have a conflict.
        //
        // CoreCLR currently always loads both the IL and the native image, so
        // move the native image out of the way.
        {
            baseAddress += m_ModuleDecoder.GetVirtualSize();
        }
    }

    // Round to a multiple of 64K
    // 64K is the allocation granularity of VirtualAlloc. (Officially this number is not a constant -
    // we should be querying the system for its allocation granularity, but we do this all over the place
    // currently.)

    baseAddress = (baseAddress + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;

    //
    // Calculate the nextBaseAddressForMultiModule
    //
    SIZE_T tempBaseAddress = baseAddress;
    tempBaseAddress += (SIZE_T) (CODE_EXPANSION_FACTOR * (double) m_ModuleDecoder.GetVirtualSize());
    tempBaseAddress += BASE_ADDRESS_ALIGNMENT;
    tempBaseAddress = (tempBaseAddress + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
    
    nextBaseAddressForMultiModule = tempBaseAddress;

    //
    // Now we remap the 32-bit address range used for x86 and PE32 images into thre
    // upper address range used on 64-bit platforms
    //
#if USE_UPPER_ADDRESS
#if defined(_TARGET_64BIT_)
    if (baseAddress < 0x80000000)
    {
        if (baseAddress < 0x40000000)
            baseAddress += 0x40000000; // We map [00000000..3fffffff] to [642'80000000..642'ffffffff]
        else
            baseAddress -= 0x40000000; // We map [40000000..7fffffff] to [642'00000000..642'7fffffff]

        baseAddress *= UPPER_ADDRESS_MAPPING_FACTOR;
        baseAddress += CLR_UPPER_ADDRESS_MIN;
    }
#endif
#endif


    // Apply the calculated base address.
    SetBaseAddress(baseAddress);

    m_NativeBaseAddress = baseAddress;
}

void ZapImage::Open(CORINFO_MODULE_HANDLE hModule,
                        IMetaDataAssemblyEmit *pEmit)
{
    m_hModule   = hModule;
    m_fManifestModule = (hModule == m_zapper->m_pEECompileInfo->GetAssemblyModule(m_zapper->m_hAssembly));

    m_ModuleDecoder = *m_zapper->m_pEECompileInfo->GetModuleDecoder(hModule);


    //
    // Get file name, and base address from module
    //

    StackSString moduleFileName;
    m_zapper->m_pEECompileInfo->GetModuleFileName(hModule, moduleFileName);

    DWORD fileNameLength = moduleFileName.GetCount();
    m_pModuleFileName = new WCHAR[fileNameLength+1];
    wcscpy_s(m_pModuleFileName, fileNameLength+1, moduleFileName.GetUnicode());

    //
    // Load the IBC Profile data for the assembly if it exists
    // 
    LoadProfileData();

    //
    // Get metadata of module to be compiled
    //
    m_pMDImport = m_zapper->m_pEECompileInfo->GetModuleMetaDataImport(m_hModule);
    _ASSERTE(m_pMDImport != NULL);

    //
    // Open new assembly metadata data for writing.  We may not use it,
    // if so we'll just discard it at the end.
    //
    if (pEmit != NULL)
    {
        pEmit->AddRef();
        m_pAssemblyEmit = pEmit;
    }
    else
    {
        // Hardwire the metadata version to be the current runtime version so that the ngen image
        // does not change when the directory runtime is installed in different directory (e.g. v2.0.x86chk vs. v2.0.80826).
        BSTRHolder strVersion(SysAllocString(W("v")VER_PRODUCTVERSION_NO_QFE_STR_L));
        VARIANT versionOption;
        V_VT(&versionOption) = VT_BSTR;
        V_BSTR(&versionOption) = strVersion;
        IfFailThrow(m_zapper->m_pMetaDataDispenser->SetOption(MetaDataRuntimeVersion, &versionOption));

        IfFailThrow(m_zapper->m_pMetaDataDispenser->
                    DefineScope(CLSID_CorMetaDataRuntime, 0, IID_IMetaDataAssemblyEmit,
                                (IUnknown **) &m_pAssemblyEmit));
    }

#ifdef FEATURE_READYTORUN_COMPILER
    if (IsReadyToRunCompilation())
    {
        InitializeSectionsForReadyToRun();
    }
    else
#endif
    {
        InitializeSections();
    }

    // Set the module base address for the ngen native image
    CalculateZapBaseAddress();
}




//
// Load the module and populate all the data-structures
//

void ZapImage::Preload()
{

    CorProfileData *  pProfileData = NewProfileData();
    m_pPreloader = m_zapper->m_pEECompileInfo->PreloadModule(m_hModule, this, pProfileData);
}

//
// Store the module
//

void ZapImage::LinkPreload()
{
    m_pPreloader->Link();
}

void ZapImage::OutputManifestMetadata()
{
    //
    // Write out manifest metadata
    //

    //
    // First, see if we have useful metadata to store
    //

    BOOL fMetadata = FALSE;

    if (m_pAssemblyEmit != NULL)
    {
        //
        // We may have added some assembly refs for exports.
        //

        NonVMComHolder<IMetaDataAssemblyImport> pAssemblyImport;
        IfFailThrow(m_pAssemblyEmit->QueryInterface(IID_IMetaDataAssemblyImport,
                                                    (void **)&pAssemblyImport));

        NonVMComHolder<IMetaDataImport> pImport;
        IfFailThrow(m_pAssemblyEmit->QueryInterface(IID_IMetaDataImport,
                                                    (void **)&pImport));

        HCORENUM hEnum = 0;
        ULONG cRefs;
        IfFailThrow(pAssemblyImport->EnumAssemblyRefs(&hEnum, NULL, 0, &cRefs));
        IfFailThrow(pImport->CountEnum(hEnum, &cRefs));
        pImport->CloseEnum(hEnum);

        if (cRefs > 0)
            fMetadata = TRUE;

        //
        // If we are the main module, we have the assembly def for the zap file.
        //

        mdAssembly a;
        if (pAssemblyImport->GetAssemblyFromScope(&a) == S_OK)
            fMetadata = TRUE;
    }

    if (fMetadata)
    {
        // Metadata creates a new MVID for every instantiation.
        // However, we want the generated ngen image to always be the same
        // for the same input. So set the metadata MVID to NGEN_IMAGE_MVID.

        NonVMComHolder<IMDInternalEmit> pMDInternalEmit;
        IfFailThrow(m_pAssemblyEmit->QueryInterface(IID_IMDInternalEmit,
                                                  (void**)&pMDInternalEmit));

        IfFailThrow(pMDInternalEmit->ChangeMvid(NGEN_IMAGE_MVID));

        m_pAssemblyMetaData = new (GetHeap()) ZapMetaData();
        m_pAssemblyMetaData->SetMetaData(m_pAssemblyEmit);

        m_pMetaDataSection->Place(m_pAssemblyMetaData);
    }
}

void ZapImage::OutputTables()
{
    //
    // Copy over any resources to the native image
    //

    COUNT_T size;
    PVOID resource = (PVOID)m_ModuleDecoder.GetResources(&size);

    if (size != 0)
    {
        m_pResources = new (GetHeap()) ZapBlobPtr(resource, size);
        m_pResourcesSection->Place(m_pResources);
    }

    CopyDebugDirEntry();
    CopyWin32VersionResource();

    if (m_pILMetaData != NULL)
    {
        m_pILMetaData->CopyIL();
        m_pILMetaData->CopyMetaData();
    }

    if (IsReadyToRunCompilation())
    {
        m_pILMetaData->CopyRVAFields();
    }

    // Copy over the timestamp from IL image for determinism
    SetTimeDateStamp(m_ModuleDecoder.GetTimeDateStamp());

    SetSubsystem(m_ModuleDecoder.GetSubsystem());

    {
        USHORT dllCharacteristics = 0;

#ifndef _TARGET_64BIT_
        dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_NO_SEH;
#endif

#ifdef _TARGET_ARM_
        // Images without NX compat bit set fail to load on ARM
        dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
#endif

        // Copy over selected DLL characteristics bits from IL image
        dllCharacteristics |= (m_ModuleDecoder.GetDllCharacteristics() & 
            (IMAGE_DLLCHARACTERISTICS_NX_COMPAT | IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE | IMAGE_DLLCHARACTERISTICS_APPCONTAINER));

#ifdef _DEBUG
        if (0 == CLRConfig::GetConfigValue(CLRConfig::INTERNAL_NoASLRForNgen))
#endif // _DEBUG
        {
            dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
#ifdef _TARGET_64BIT_
            // Large address aware, required for High Entry VA, is always enabled for 64bit native images.
            dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA;
#endif
        }

        SetDllCharacteristics(dllCharacteristics);
    }

    if (IsReadyToRunCompilation())
    {

        SetSizeOfStackReserve(m_ModuleDecoder.GetSizeOfStackReserve());
        SetSizeOfStackCommit(m_ModuleDecoder.GetSizeOfStackCommit());
    }

#if defined(FEATURE_PAL) && !defined(_TARGET_64BIT_)
    // To minimize wasted VA space on 32 bit systems align file to page bounaries (presumed to be 4K).
    SetFileAlignment(0x1000);
#elif defined(_TARGET_ARM_) && defined(FEATURE_CORESYSTEM)
    if (!IsReadyToRunCompilation())
    {
        // On ARM CoreSys builds, crossgen will use 4k file alignment, as requested by Phone perf team
        // to improve perf on phones with compressed system partitions.
        SetFileAlignment(0x1000);
    }
#endif
}

ZapImage::CompileStatus ZapImage::CompileProfileDataWorker(mdToken token, unsigned methodProfilingDataFlags)
{
    if ((TypeFromToken(token) != mdtMethodDef) ||
        (!m_pMDImport->IsValidToken(token)))
    {
        m_zapper->Info(W("Warning: Invalid method token %08x in profile data.\n"), token);
        return NOT_COMPILED;
    }

#ifdef _DEBUG
    static ConfigDWORD g_NgenOrder;

    if ((g_NgenOrder.val(CLRConfig::INTERNAL_NgenOrder) & 2) == 2)
    {
        const ProfileDataHashEntry * foundEntry = profileDataHashTable.LookupPtr(token);
    
        if (foundEntry == NULL)
            return NOT_COMPILED;

        // The md must match.
        _ASSERTE(foundEntry->md == token); 
        // The target position cannot be 0.
        _ASSERTE(foundEntry->pos > 0);
    }
#endif

    // Now compile the method
    return TryCompileMethodDef(token, methodProfilingDataFlags);
}

//  ProfileDisableInlining
//     Before we start compiling any methods we may need to suppress the inlining
//     of certain methods based upon our profile data.
//     This method will arrange to disable this inlining.
//
void ZapImage::ProfileDisableInlining()
{
    // We suppress the inlining of any Hot methods that have the ExcludeHotMethodCode flag.
    // We want such methods to be Jitted at runtime rather than compiled in the AOT native image.
    // The inlining of such a method also need to be suppressed.
    //
    ProfileDataSection* methodProfileData = &(m_profileDataSections[MethodProfilingData]);
    if (methodProfileData->tableSize > 0)
    {
        for (DWORD i = 0; i < methodProfileData->tableSize; i++)
        {
            CORBBTPROF_TOKEN_INFO * pTokenInfo = &(methodProfileData->pTable[i]);
            unsigned methodProfilingDataFlags = pTokenInfo->flags;

            // Hot methods can be marked to be excluded from the AOT native image.
            // We also need to disable inlining of such methods.
            //
            if ((methodProfilingDataFlags & (1 << DisableInlining)) != 0)
            {
                // Disable the inlining of this method
                //
                // @ToDo: Figure out how to disable inlining for this method.               
            }
        }
    }
}

//  CompileHotRegion
//     Performs the compilation and placement for all methods in the the "Hot" code region
//     Methods placed in this region typically correspond to all of the methods that were
//     executed during any of the profiling scenarios.
//
void ZapImage::CompileHotRegion()
{
    // Compile all of the methods that were executed during profiling into the "Hot" code region.
    //
    BeginRegion(CORINFO_REGION_HOT);

    CorProfileData* pProfileData = GetProfileData();
        
    ProfileDataSection* methodProfileData = &(m_profileDataSections[MethodProfilingData]);
    if (methodProfileData->tableSize > 0)
    {
        // record the start of hot IBC methods.
        m_iIBCMethod = m_MethodCompilationOrder.GetCount();

        //
        // Compile the hot methods in the order specified in the MethodProfilingData
        //
        for (DWORD i = 0; i < methodProfileData->tableSize; i++)
        {
            CompileStatus compileResult = NOT_COMPILED;
            CORBBTPROF_TOKEN_INFO * pTokenInfo = &(methodProfileData->pTable[i]);

            mdToken token = pTokenInfo->token;
            unsigned methodProfilingDataFlags = pTokenInfo->flags;
            _ASSERTE(methodProfilingDataFlags != 0);

            if (TypeFromToken(token) == mdtMethodDef)
            {
                //
                // Compile a non-generic method
                // 
                compileResult = CompileProfileDataWorker(token, methodProfilingDataFlags);
            }
            else if (TypeFromToken(token) == ibcMethodSpec)
            {
                //
                //  compile a generic/parameterized method
                // 
                CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = pProfileData->GetBlobSigEntry(token);
                
                if (pBlobSigEntry == NULL)
                {
                    m_zapper->Info(W("Warning: Did not find definition for method token %08x in profile data.\n"), token);
                }
                else // (pBlobSigEntry  != NULL)
                {
                    _ASSERTE(pBlobSigEntry->blob.token == token);

                    // decode method desc
                    CORINFO_METHOD_HANDLE pMethod = m_pPreloader->FindMethodForProfileEntry(pBlobSigEntry);
                   
                    if (pMethod)
                    {
                        m_pPreloader->AddMethodToTransitiveClosureOfInstantiations(pMethod);

                        compileResult = TryCompileInstantiatedMethod(pMethod, methodProfilingDataFlags);
                    }
                    else
                    {
                        // This generic/parameterized method is not part of the native image
                        // Either the IBC type  specified no longer exists or it is a SIMD types
                        // or the type can't be loaded in a ReadyToRun native image because of
                        // a cross-module type dependencies.
                        //
                        compileResult = COMPILE_EXCLUDED;
                    }
                }
            }

            // Update the 'flags' and 'compileResult' saved in the profileDataHashTable hash table.
            //
            hashBBUpdateFlagsAndCompileResult(token, methodProfilingDataFlags, compileResult);
        }
        // record the start of hot Generics methods.
        m_iGenericsMethod = m_MethodCompilationOrder.GetCount();
    }

    // record the start of untrained code
    m_iUntrainedMethod = m_MethodCompilationOrder.GetCount();

    EndRegion(CORINFO_REGION_HOT);
}

//  CompileColdRegion
//     Performs the compilation and placement for all methods in the the "Cold" code region
//     Methods placed in this region typically correspond to all of the methods that were
//     NOT executed during any of the profiling scenarios.
//
void ZapImage::CompileColdRegion()
{
    // Compile all of the methods that were NOT executed during profiling into the "Cold" code region.
    //

    BeginRegion(CORINFO_REGION_COLD);
    
    IMDInternalImport * pMDImport = m_pMDImport;
    
    HENUMInternalHolder hEnum(pMDImport);
    hEnum.EnumAllInit(mdtMethodDef);
    
    mdMethodDef md;
    while (pMDImport->EnumNext(&hEnum, &md))
    {
        //
        // Compile the remaining methods that weren't compiled during the CompileHotRegion phase
        //
        TryCompileMethodDef(md, 0);
    }

    // Compile any generic code which lands in this LoaderModule
    // that resulted from the above compilations
    CORINFO_METHOD_HANDLE handle = m_pPreloader->NextUncompiledMethod();
    while (handle != NULL)
    {
        TryCompileInstantiatedMethod(handle, 0);
        handle = m_pPreloader->NextUncompiledMethod();
    }
    
    EndRegion(CORINFO_REGION_COLD);
}

//  PlaceMethodIL
//     Copy the IL for all method into the AOT native image
//
void ZapImage::PlaceMethodIL()
{
    // Place the IL for all of the methods 
    //
    IMDInternalImport * pMDImport = m_pMDImport;
    HENUMInternalHolder hEnum(pMDImport);
    hEnum.EnumAllInit(mdtMethodDef);
    
    mdMethodDef md;
    while (pMDImport->EnumNext(&hEnum, &md))
    {
        if (m_pILMetaData != NULL)
        {
            // Copy IL for all methods. We treat errors during copying IL 
            // over as fatal error. These errors are typically caused by 
            // corrupted IL images.
            // 
            m_pILMetaData->EmitMethodIL(md);
        }
    }
}

void ZapImage::Compile()
{
    //
    // Compile all of the methods for our AOT native image
    //

    bool doNothingNgen = false;
#ifdef _DEBUG
    static ConfigDWORD fDoNothingNGen;
    doNothingNgen = !!fDoNothingNGen.val(CLRConfig::INTERNAL_ZapDoNothing);
#endif

    ProfileDisableInlining();

    if (!doNothingNgen)
    {
        CompileHotRegion();

        CompileColdRegion();
    }

    PlaceMethodIL();

    // Compute a preferred class layout order based on analyzing the graph
    // of which classes contain calls to other classes.
    ComputeClassLayoutOrder();

    // Sort the unprofiled methods by this preferred class layout, if available
    if (m_fHasClassLayoutOrder)
    {
        SortUnprofiledMethodsByClassLayoutOrder();
    }

    if (IsReadyToRunCompilation())
    {
        // Pretend that no methods are trained, so that everything is in single code section
        // READYTORUN: FUTURE: More than one code section
        m_iUntrainedMethod = 0;
    }

    OutputCode(ProfiledHot);
    OutputCode(Unprofiled);
    OutputCode(ProfiledCold);

    OutputCodeInfo(ProfiledHot);
    OutputCodeInfo(ProfiledCold);  // actually both Unprofiled and ProfiledCold

    OutputGCInfo();
    OutputProfileData();

#ifdef FEATURE_READYTORUN_COMPILER
    if (IsReadyToRunCompilation())
    {
        OutputEntrypointsTableForReadyToRun();
        OutputDebugInfoForReadyToRun();
        OutputTypesTableForReadyToRun(m_pMDImport);
        OutputInliningTableForReadyToRun();
        OutputProfileDataForReadyToRun();
    }
    else
#endif
    {
        OutputDebugInfo();
    }
}

struct CompileMethodStubContext
{
    ZapImage *                  pImage;
    unsigned                    methodProfilingDataFlags;
    ZapImage::CompileStatus     enumCompileStubResult;

    CompileMethodStubContext(ZapImage * _image, unsigned _methodProfilingDataFlags)
    {
        pImage                   = _image;
        methodProfilingDataFlags = _methodProfilingDataFlags;
        enumCompileStubResult    = ZapImage::NOT_COMPILED;
    }
};

//-----------------------------------------------------------------------------
// This method is a callback function use to compile any IL_STUBS that are
// associated with a normal IL method.  It is called from CompileMethodStubIfNeeded
// via the function pointer stored in the CompileMethodStubContext.
// It handles the temporary change to the m_compilerFlags and removes any flags
// that we don't want set when compiling IL_STUBS.
//-----------------------------------------------------------------------------

// static void __stdcall 
void ZapImage::TryCompileMethodStub(LPVOID pContext, CORINFO_METHOD_HANDLE hStub, CORJIT_FLAGS jitFlags)
{
    STANDARD_VM_CONTRACT;

    // The caller must always set the IL_STUB flag
    _ASSERTE(jitFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB));

    CompileMethodStubContext *pCompileContext = reinterpret_cast<CompileMethodStubContext *>(pContext);
    ZapImage *pImage = pCompileContext->pImage;

    CORJIT_FLAGS oldFlags = pImage->m_zapper->m_pOpt->m_compilerFlags;

    CORJIT_FLAGS* pCompilerFlags = &pImage->m_zapper->m_pOpt->m_compilerFlags;
    pCompilerFlags->Add(jitFlags);
    pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_PROF_ENTERLEAVE);
    pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_DEBUG_CODE);
    pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_DEBUG_EnC);
    pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_DEBUG_INFO);

    mdMethodDef md = mdMethodDefNil;

    pCompileContext->enumCompileStubResult = pImage->TryCompileMethodWorker(hStub, md,
                                                         pCompileContext->methodProfilingDataFlags);

    pImage->m_zapper->m_pOpt->m_compilerFlags = oldFlags;
}

//-----------------------------------------------------------------------------
// Helper for ZapImage::TryCompileMethodDef that indicates whether a given method def token refers to a
// "vtable gap" method. These are pseudo-methods used to lay out the vtable for COM interop and as such don't
// have any associated code (or even a method handle).
//-----------------------------------------------------------------------------
BOOL ZapImage::IsVTableGapMethod(mdMethodDef md)
{
#ifdef FEATURE_COMINTEROP 
    HRESULT hr;
    DWORD dwAttributes;

    // Get method attributes and check that RTSpecialName was set for the method (this means the name has
    // semantic import to the runtime and must be formatted rigorously with one of a few well known rules).
    // Note that we just return false on any failure path since this will just lead to our caller continuing
    // to throw the exception they were about to anyway.
    hr = m_pMDImport->GetMethodDefProps(md, &dwAttributes);
    if (FAILED(hr) || !IsMdRTSpecialName(dwAttributes))
        return FALSE;

    // Now check the name of the method. All vtable gap methods will have a prefix of "_VtblGap".
    LPCSTR szMethod;
    PCCOR_SIGNATURE pvSigBlob;
    ULONG cbSigBlob;    
    hr = m_pMDImport->GetNameAndSigOfMethodDef(md, &pvSigBlob, &cbSigBlob, &szMethod);
    if (FAILED(hr) || (strncmp(szMethod, "_VtblGap", 8) != 0))
        return FALSE;

    // If we make it to here we have a vtable gap method.
    return TRUE;
#else
    return FALSE;
#endif // FEATURE_COMINTEROP
}

//-----------------------------------------------------------------------------
// This function is called for non-generic methods in the current assembly,
// and for the typical "System.__Canon" instantiations of generic methods
// in the current assembly.
//-----------------------------------------------------------------------------

ZapImage::CompileStatus ZapImage::TryCompileMethodDef(mdMethodDef md, unsigned methodProfilingDataFlags)
{
    _ASSERTE(!IsNilToken(md));

    CORINFO_METHOD_HANDLE handle = NULL;
    CompileStatus         result = NOT_COMPILED;

    if (ShouldCompileMethodDef(md))
    {
        handle = m_pPreloader->LookupMethodDef(md);
        if (handle == nullptr)
        {
            result = LOOKUP_FAILED;
        }
    }
    else
    {
        result = COMPILE_EXCLUDED;
    }

    if (handle == NULL)
        return result;

    // compile the method
    //
    CompileStatus methodCompileStatus = TryCompileMethodWorker(handle, md, methodProfilingDataFlags);

    // Don't bother compiling the IL_STUBS if we failed to compile the parent IL method
    //
    if (methodCompileStatus == COMPILE_SUCCEED)
    {
        CompileMethodStubContext context(this, methodProfilingDataFlags);

        // compile stubs associated with the method
        m_pPreloader->GenerateMethodStubs(handle, m_zapper->m_pOpt->m_ngenProfileImage,
                                          &TryCompileMethodStub,
                                          &context);
    }

    return methodCompileStatus;
}


//-----------------------------------------------------------------------------
// This function is called for non-"System.__Canon" instantiations of generic methods.
// These could be methods defined in other assemblies too.
//-----------------------------------------------------------------------------

ZapImage::CompileStatus ZapImage::TryCompileInstantiatedMethod(CORINFO_METHOD_HANDLE handle, 
                                                               unsigned methodProfilingDataFlags)
{
    if (IsReadyToRunCompilation())
    {
        if (!GetCompileInfo()->IsInCurrentVersionBubble(m_zapper->m_pEEJitInfo->getMethodModule(handle)))
            return COMPILE_EXCLUDED;
    }

    if (!ShouldCompileInstantiatedMethod(handle))
        return COMPILE_EXCLUDED;

    // If we compiling this method because it was specified by the IBC profile data
    // then issue an warning if this method is not on our uncompiled method list
    // 
    if (methodProfilingDataFlags != 0)
    {
        if (methodProfilingDataFlags & (1 << ReadMethodCode))
        {
            // When we have stale IBC data the method could have been rejected from this image.
            if (!m_pPreloader->IsUncompiledMethod(handle))
            {
                const char* szClsName;
                const char* szMethodName = m_zapper->m_pEEJitInfo->getMethodName(handle, &szClsName);

                SString fullname(SString::Utf8, szClsName);
                fullname.AppendUTF8(NAMESPACE_SEPARATOR_STR);
                fullname.AppendUTF8(szMethodName);

                m_zapper->Info(W("Warning: Invalid method instantiation in profile data: %s\n"), fullname.GetUnicode());

                return NOT_COMPILED;
            }
        }
    }
   
    CompileStatus methodCompileStatus = TryCompileMethodWorker(handle, mdMethodDefNil, methodProfilingDataFlags);

    // Don't bother compiling the IL_STUBS if we failed to compile the parent IL method
    //
    if (methodCompileStatus == COMPILE_SUCCEED)
    {
        CompileMethodStubContext context(this, methodProfilingDataFlags);

        // compile stubs associated with the method
        m_pPreloader->GenerateMethodStubs(handle, m_zapper->m_pOpt->m_ngenProfileImage,
                                          &TryCompileMethodStub, 
                                          &context);
    }

    return methodCompileStatus;
}

//-----------------------------------------------------------------------------

ZapImage::CompileStatus ZapImage::TryCompileMethodWorker(CORINFO_METHOD_HANDLE handle, mdMethodDef md, 
                                                         unsigned methodProfilingDataFlags)
{
    _ASSERTE(handle != NULL);

    if (m_zapper->m_pOpt->m_onlyOneMethod && (m_zapper->m_pOpt->m_onlyOneMethod != md))
        return NOT_COMPILED;

    if (GetCompileInfo()->HasCustomAttribute(handle, "System.Runtime.BypassNGenAttribute"))
        return NOT_COMPILED;

#ifdef FEATURE_READYTORUN_COMPILER
    // This is a quick workaround to opt specific methods out of ReadyToRun compilation to work around bugs.
    if (IsReadyToRunCompilation())
    {
        if (GetCompileInfo()->HasCustomAttribute(handle, "System.Runtime.BypassReadyToRunAttribute"))
            return NOT_COMPILED;
    }
#endif

    // Do we have a profile entry for this method?
    //
    if (methodProfilingDataFlags != 0)
    {
        // Report the profiling data flags for layout of the EE datastructures
        m_pPreloader->SetMethodProfilingFlags(handle, methodProfilingDataFlags);

        // Hot methods can be marked to be excluded from the AOT native image.
        // A Jitted method executes faster than a ReadyToRun compiled method.
        //
        if ((methodProfilingDataFlags & (1 << ExcludeHotMethodCode)) != 0)
        {
            // returning COMPILE_HOT_EXCLUDED excludes this method from the AOT native image
            return COMPILE_HOT_EXCLUDED;
        }

        // Cold methods can be marked to be excluded from the AOT native image.
        // We can reduced the size of the AOT native image by selectively
        // excluding the code for some of the cold methods.
        //
        if ((methodProfilingDataFlags & (1 << ExcludeColdMethodCode)) != 0)
        {
            // returning COMPILE_COLD_EXCLUDED excludes this method from the AOT native image
            return COMPILE_COLD_EXCLUDED;
        }

        // If the code was never executed based on the profile data
        // then don't compile this method now. Wait until until later
        // when we are compiling the methods in the cold section.
        //
        if ((methodProfilingDataFlags & (1 << ReadMethodCode)) == 0)
        {
            // returning NOT_COMPILED will defer until later the compilation of this method
            return NOT_COMPILED;
        }
    }
    else  // we are compiling methods for the cold region
    {
        // Retrieve any information that we have about a previous compilation attempt of this method
        const ProfileDataHashEntry* pEntry = profileDataHashTable.LookupPtr(md);
        
        // When Partial Ngen is specified we will omit the AOT native code for every
        // method that does not have profile data
        //
        if (pEntry == nullptr && m_zapper->m_pOpt->m_fPartialNGen)
        {
            // returning COMPILE_COLD_EXCLUDED excludes this method from the AOT native image
            return COMPILE_COLD_EXCLUDED;
        }

        if (pEntry != nullptr)
        { 
            if ((pEntry->status == COMPILE_HOT_EXCLUDED) || (pEntry->status == COMPILE_COLD_EXCLUDED))
            {
                // returning COMPILE_HOT_EXCLUDED excludes this method from the AOT native image
                return pEntry->status;
            }
        }
    }

    // Have we already compiled it?
    if (GetCompiledMethod(handle) != NULL)
        return ALREADY_COMPILED;

    _ASSERTE(m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB) || IsNilToken(md) || handle == m_pPreloader->LookupMethodDef(md));

    CompileStatus result = NOT_COMPILED;
    
    // This is an entry point into the JIT which can call back into the VM. There are methods in the
    // JIT that will swallow exceptions and only the VM guarentees that exceptions caught or swallowed
    // with restore the debug state of the stack guards. So it is necessary to ensure that the status
    // is restored on return from the call into the JIT, which this light-weight transition macro
    // will do.
    REMOVE_STACK_GUARD;

    CORINFO_MODULE_HANDLE module;

    // We only compile IL_STUBs from the current assembly
    if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB))
        module = m_hModule;
    else
        module = m_zapper->m_pEEJitInfo->getMethodModule(handle);

    ZapInfo zapInfo(this, md, handle, module, methodProfilingDataFlags);

    EX_TRY
    {
        zapInfo.CompileMethod();
        result = COMPILE_SUCCEED;
    }
    EX_CATCH
    {
        // Continue unwinding if fatal error was hit.
        if (FAILED(g_hrFatalError))
            ThrowHR(g_hrFatalError);

        Exception *ex = GET_EXCEPTION();
        HRESULT hrException = ex->GetHR();

        CorZapLogLevel level;

#ifdef CROSSGEN_COMPILE
        // Warnings should not go to stderr during crossgen
        level = CORZAP_LOGLEVEL_WARNING;
#else
        level = CORZAP_LOGLEVEL_ERROR;

        m_zapper->m_failed = TRUE;
#endif

        result = COMPILE_FAILED;

#ifdef FEATURE_READYTORUN_COMPILER
        // NYI features in R2R - Stop crossgen from spitting unnecessary
        //     messages to the console
        if (IsReadyToRunCompilation())
        {
            // When compiling the method we may recieve an exeception when the
            // method uses a feature that is Not Implemented for ReadyToRun 
            // or a Type Load exception if the method uses for a SIMD type.
            //
            // We skip the compilation of such methods and we don't want to
            // issue a warning or error
            //
            if ((hrException == E_NOTIMPL) || (hrException == IDS_CLASSLOAD_GENERAL))
            {
                result = NOT_COMPILED;
                level = CORZAP_LOGLEVEL_INFO;
            }
        }
#endif
        {
            StackSString message;
            ex->GetMessage(message);

            // FileNotFound errors here can be converted into a single error string per ngen compile, 
            //  and the detailed error is available with verbose logging
            if (hrException == COR_E_FILENOTFOUND)
            {
                StackSString logMessage(W("System.IO.FileNotFoundException: "));
                logMessage.Append(message);
                FileNotFoundError(logMessage.GetUnicode());
                level = CORZAP_LOGLEVEL_INFO;
            }

            m_zapper->Print(level, W("%s while compiling method %s\n"), message.GetUnicode(), zapInfo.m_currentMethodName.GetUnicode());

            if ((result == COMPILE_FAILED) && (m_stats != NULL))
            {
                if (!m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB))
                    m_stats->m_failedMethods++;
                else
                    m_stats->m_failedILStubs++;
            }
        }
    }
    EX_END_CATCH(SwallowAllExceptions);
    
    return result;
}


// Should we compile this method, defined in the ngen'ing module?
// Result is FALSE if any of the controls (only used by prejit.exe) exclude the method
BOOL ZapImage::ShouldCompileMethodDef(mdMethodDef md)
{
    DWORD partialNGenStressVal = PartialNGenStressPercentage();
    if (partialNGenStressVal &&
        // Module::AddCerListToRootTable has problems if mscorlib.dll is
        // a partial ngen image
        m_hModule != m_zapper->m_pEECompileInfo->GetLoaderModuleForMscorlib())
    {
        _ASSERTE(partialNGenStressVal <= 100);
        DWORD methodPercentageVal = (md % 100) + 1;
        if (methodPercentageVal <= partialNGenStressVal)
            return FALSE;
    }
    
    mdTypeDef td;
    IfFailThrow(m_pMDImport->GetParentToken(md, &td));
    
#ifdef FEATURE_COMINTEROP
    mdToken tkExtends;
    if (td != mdTypeDefNil)
    {
        m_pMDImport->GetTypeDefProps(td, NULL, &tkExtends);
        
        mdAssembly tkAssembly;
        DWORD dwAssemblyFlags;
        
        m_pMDImport->GetAssemblyFromScope(&tkAssembly);
        if (TypeFromToken(tkAssembly) == mdtAssembly)
        {
            m_pMDImport->GetAssemblyProps(tkAssembly,
                                            NULL, NULL,     // Public Key
                                            NULL,           // Hash Algorithm
                                            NULL,           // Name
                                            NULL,           // MetaData
                                            &dwAssemblyFlags);
            
            if (IsAfContentType_WindowsRuntime(dwAssemblyFlags))
            {
                if (TypeFromToken(tkExtends) == mdtTypeRef)
                {
                    LPCSTR szNameSpace = NULL;
                    LPCSTR szName = NULL;
                    m_pMDImport->GetNameOfTypeRef(tkExtends, &szNameSpace, &szName);
                    
                    if (!strcmp(szNameSpace, "System") && !_stricmp((szName), "Attribute"))
                    {
                        return FALSE;
                    }
                }
            }
        }
    }
#endif

#ifdef _DEBUG
    static ConfigMethodSet fZapOnly;
    fZapOnly.ensureInit(CLRConfig::INTERNAL_ZapOnly);

    static ConfigMethodSet fZapExclude;
    fZapExclude.ensureInit(CLRConfig::INTERNAL_ZapExclude);

    PCCOR_SIGNATURE pvSigBlob;
    ULONG cbSigBlob;

    // Get the name of the current method and its class
    LPCSTR szMethod;
    IfFailThrow(m_pMDImport->GetNameAndSigOfMethodDef(md, &pvSigBlob, &cbSigBlob, &szMethod));
    
    LPCWSTR wszClass = W("");
    SString sClass;

    if (td != mdTypeDefNil)
    {
        LPCSTR szNameSpace = NULL;
        LPCSTR szName = NULL;
        
        IfFailThrow(m_pMDImport->GetNameOfTypeDef(td, &szName, &szNameSpace));
        
        const SString nameSpace(SString::Utf8, szNameSpace);
        const SString name(SString::Utf8, szName);
        sClass.MakeFullNamespacePath(nameSpace, name);
        wszClass = sClass.GetUnicode();
    }

    MAKE_UTF8PTR_FROMWIDE(szClass,  wszClass);

    if (!fZapOnly.isEmpty() && !fZapOnly.contains(szMethod, szClass, pvSigBlob))
    {
        LOG((LF_ZAP, LL_INFO1000, "Rejecting compilation of method %08x, %s::%s\n", md, szClass, szMethod));
        return FALSE;
    }

    if (fZapExclude.contains(szMethod, szClass, pvSigBlob))
    {
        LOG((LF_ZAP, LL_INFO1000, "Rejecting compilation of method %08x, %s::%s\n", md, szClass, szMethod));
        return FALSE;
    }

    LOG((LF_ZAP, LL_INFO1000, "Compiling method %08x, %s::%s\n", md, szClass, szMethod));
#endif    
    
    return TRUE;
}


BOOL ZapImage::ShouldCompileInstantiatedMethod(CORINFO_METHOD_HANDLE handle)
{
    DWORD partialNGenStressVal = PartialNGenStressPercentage();
    if (partialNGenStressVal &&
        // Module::AddCerListToRootTable has problems if mscorlib.dll is
        // a partial ngen image
        m_hModule != m_zapper->m_pEECompileInfo->GetLoaderModuleForMscorlib())
    {
        _ASSERTE(partialNGenStressVal <= 100);
        DWORD methodPercentageVal = (m_zapper->m_pEEJitInfo->getMethodHash(handle) % 100) + 1;
        if (methodPercentageVal <= partialNGenStressVal)
            return FALSE;
    }

    return TRUE;
}

HRESULT ZapImage::PrintTokenDescription(CorZapLogLevel level, mdToken token)
{
    HRESULT hr;

    if (RidFromToken(token) == 0)
        return S_OK;

    LPCSTR szNameSpace = NULL;
    LPCSTR szName = NULL;

    if (m_pMDImport->IsValidToken(token))
    {
        switch (TypeFromToken(token))
        {
            case mdtMemberRef:
            {
                mdToken parent;
                IfFailRet(m_pMDImport->GetParentOfMemberRef(token, &parent));
                if (RidFromToken(parent) != 0)
                {
                    PrintTokenDescription(level, parent);
                    m_zapper->Print(level, W("."));
                }
                IfFailRet(m_pMDImport->GetNameAndSigOfMemberRef(token, NULL, NULL, &szName));
                break;
            }

            case mdtMethodDef:
            {
                mdToken parent;
                IfFailRet(m_pMDImport->GetParentToken(token, &parent));
                if (RidFromToken(parent) != 0)
                {
                    PrintTokenDescription(level, parent);
                    m_zapper->Print(level, W("."));
                }
                IfFailRet(m_pMDImport->GetNameOfMethodDef(token, &szName));
                break;
            }

            case mdtTypeRef:
            {   
                IfFailRet(m_pMDImport->GetNameOfTypeRef(token, &szNameSpace, &szName));
                break;
            }

            case mdtTypeDef:
            {
                IfFailRet(m_pMDImport->GetNameOfTypeDef(token, &szName, &szNameSpace));
                break;
            }

            default:
                break;
        }      
    }
    else
    {
        szName = "InvalidToken";
    }

    SString fullName;

    if (szNameSpace != NULL)
    {
        const SString nameSpace(SString::Utf8, szNameSpace);
        const SString name(SString::Utf8, szName);
        fullName.MakeFullNamespacePath(nameSpace, name);
    }
    else
    {
        fullName.SetUTF8(szName);
    }

    m_zapper->Print(level, W("%s"), fullName.GetUnicode());

    return S_OK;
}


HRESULT ZapImage::LocateProfileData()
{
    if (m_zapper->m_pOpt->m_ignoreProfileData)
    {
        return S_FALSE;
    }

    //
    // In the past, we have ignored profile data when instrumenting the assembly.
    // However, this creates significant differences between the tuning image and the eventual
    // optimized image (e.g. generic instantiations) which in turn leads to missed data during
    // training and cold touches during execution.  Instead, we take advantage of any IBC data
    // the assembly already has and attempt to make the tuning image as close as possible to
    // the final image.
    //
#if 0
    if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_BBINSTR))
        return S_FALSE;
#endif

    //
    // Don't use IBC data from untrusted assemblies--this allows us to assume that
    // the IBC data is not malicious
    //
    if (m_zapper->m_pEEJitInfo->canSkipVerification(m_hModule) != CORINFO_VERIFICATION_CAN_SKIP)
    {
        return S_FALSE;
    }

#if !defined(FEATURE_PAL)
    //
    // See if there's profile data in the resource section of the PE
    //
    m_pRawProfileData = (BYTE*)m_ModuleDecoder.GetWin32Resource(W("PROFILE_DATA"), W("IBC"), &m_cRawProfileData);

    if ((m_pRawProfileData != NULL) && (m_cRawProfileData != 0))
    {
        m_zapper->Info(W("Found embedded profile resource in %s.\n"), m_pModuleFileName);
        return S_OK;
    }

    static ConfigDWORD g_UseIBCFile;
    if (g_UseIBCFile.val(CLRConfig::EXTERNAL_UseIBCFile) != 1)
        return S_OK;
#endif

    //
    // Couldn't find profile resource--let's see if there's an ibc file to use instead
    //

    SString path(m_pModuleFileName);

    SString::Iterator dot = path.End();
    if (path.FindBack(dot, '.'))
    {
        SString slName(SString::Literal, "ibc");
        path.Replace(dot+1, path.End() - (dot+1), slName);

        HandleHolder hFile = WszCreateFile(path.GetUnicode(),
                                     GENERIC_READ,
                                     FILE_SHARE_READ,
                                     NULL,
                                     OPEN_EXISTING,
                                     FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
                                     NULL);
        if (hFile != INVALID_HANDLE_VALUE)
        {
            HandleHolder hMapFile = WszCreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
            DWORD dwFileLen = SafeGetFileSize(hFile, 0);
            if (dwFileLen != INVALID_FILE_SIZE)
            {
                if (hMapFile == NULL)
                {
                    m_zapper->Warning(W("Found profile data file %s, but could not open it"), path.GetUnicode());
                }
                else
                {
                    m_zapper->Info(W("Found ibc file %s.\n"), path.GetUnicode());

                    m_profileDataFile  = (BYTE*) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);

                    m_pRawProfileData  = m_profileDataFile;
                    m_cRawProfileData  = dwFileLen;
                }
            }
        }
    }

    return S_OK;
}


bool ZapImage::CanConvertIbcData()
{
    static ConfigDWORD g_iConvertIbcData;
    DWORD val = g_iConvertIbcData.val(CLRConfig::UNSUPPORTED_ConvertIbcData);
    return (val != 0);
}

HRESULT ZapImage::parseProfileData()
{
    if (m_pRawProfileData == NULL)
    {
        return S_FALSE;
    }

    ProfileReader profileReader(m_pRawProfileData, m_cRawProfileData);

    CORBBTPROF_FILE_HEADER *fileHeader;

    READ(fileHeader, CORBBTPROF_FILE_HEADER);
    if (fileHeader->HeaderSize < sizeof(CORBBTPROF_FILE_HEADER))
    {
        _ASSERTE(!"HeaderSize is too small");
        return E_FAIL;
    }

    // Read any extra header data. It will be needed for V3 files.

    DWORD extraHeaderDataSize = fileHeader->HeaderSize - sizeof(CORBBTPROF_FILE_HEADER);
    void *extraHeaderData = profileReader.Read(extraHeaderDataSize);

    bool convertFromV1 = false;
    bool minified = false;

    if (fileHeader->Magic != CORBBTPROF_MAGIC) 
    {
        _ASSERTE(!"ibcHeader contains bad values");
        return E_FAIL;
    }

    // CoreCLR should never be presented with V1 IBC data.
    if (fileHeader->Version == CORBBTPROF_V3_VERSION)
    {
        CORBBTPROF_FILE_OPTIONAL_HEADER *optionalHeader =
            (CORBBTPROF_FILE_OPTIONAL_HEADER *)extraHeaderData;

        if (!optionalHeader ||
            !CONTAINS_FIELD(optionalHeader, extraHeaderDataSize, Size) ||
            (optionalHeader->Size > extraHeaderDataSize))
        {
            m_zapper->Info(W("Optional header missing or corrupt."));
            return E_FAIL;
        }

        if (CONTAINS_FIELD(optionalHeader, optionalHeader->Size, FileFlags))
        {
            minified = !!(optionalHeader->FileFlags & CORBBTPROF_FILE_FLAG_MINIFIED);

            if (!m_zapper->m_pOpt->m_fPartialNGenSet)
            {
                m_zapper->m_pOpt->m_fPartialNGen = !!(optionalHeader->FileFlags & CORBBTPROF_FILE_FLAG_PARTIAL_NGEN);
            }
        }
    }
    else if (fileHeader->Version != CORBBTPROF_V2_VERSION)
    {
        m_zapper->Info(W("Discarding profile data with unknown version."));
        return S_FALSE;
    }

    // This module has profile data (this ends up controling the layout of physical and virtual
    // sections within the image, see ZapImage::AllocateVirtualSections.
    m_fHaveProfileData = true;
    m_zapper->m_pOpt->m_fHasAnyProfileData = true;

    CORBBTPROF_SECTION_TABLE_HEADER *sectionHeader;
    READ(sectionHeader, CORBBTPROF_SECTION_TABLE_HEADER);

    //
    // Parse the section table
    //

    for (ULONG i = 0; i < sectionHeader->NumEntries; i++)
    {
        CORBBTPROF_SECTION_TABLE_ENTRY *entry;
        READ(entry,CORBBTPROF_SECTION_TABLE_ENTRY);

        SectionFormat format = sectionHeader->Entries[i].FormatID;
        _ASSERTE(format >= 0);
        if (format < 0)
        {
            continue;
        }

        if (convertFromV1)
        {
            if (format < LastTokenFlagSection)
            {
                format = (SectionFormat) (format + 1);
            }
        }

        _ASSERTE(format < SectionFormatCount);

        if (format < SectionFormatCount)
        {
            BYTE *start = m_pRawProfileData + sectionHeader->Entries[i].Data.Offset;
            BYTE *end   = start             + sectionHeader->Entries[i].Data.Size;

            if ((start > m_pRawProfileData)                     &&
                (end   < m_pRawProfileData + m_cRawProfileData) &&
                (start < end))
            {
                _ASSERTE(m_profileDataSections[format].pData  == 0);
                _ASSERTE(m_profileDataSections[format].dataSize == 0);

                m_profileDataSections[format].pData     = start;
                m_profileDataSections[format].dataSize  = (DWORD) (end - start);
            }
            else
            {
                _ASSERTE(!"Invalid profile section offset or size");
                return E_FAIL;
            }
        }
    }

    HRESULT hr = S_OK;

    if (convertFromV1)
    {
        hr = convertProfileDataFromV1();
        if (FAILED(hr))
        {
            return hr;
        }
    }
    else if (minified)
    {
        hr = RehydrateProfileData();
        if (FAILED(hr))
        {
            return hr;
        }
    }
    else
    {
        //
        // For those sections that are collections of tokens, further parse that format to get
        // the token pointer and number of tokens
        //

        for (int format = FirstTokenFlagSection; format < SectionFormatCount; format++)
        {
            if (m_profileDataSections[format].pData)
            {
                SEEK(((ULONG) (m_profileDataSections[format].pData - m_pRawProfileData)));

                CORBBTPROF_TOKEN_LIST_SECTION_HEADER *header;
                READ(header, CORBBTPROF_TOKEN_LIST_SECTION_HEADER);

                DWORD tableSize = header->NumTokens;
                DWORD dataSize  = (m_profileDataSections[format].dataSize - sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER));
                DWORD expectedSize = tableSize * sizeof (CORBBTPROF_TOKEN_INFO);

                if (dataSize == expectedSize)
                {
                    BYTE * startOfTable = m_profileDataSections[format].pData + sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER);
                    m_profileDataSections[format].tableSize = tableSize;
                    m_profileDataSections[format].pTable = (CORBBTPROF_TOKEN_INFO *) startOfTable;
                }
                else
                {
                    _ASSERTE(!"Invalid CORBBTPROF_TOKEN_LIST_SECTION_HEADER header");
                    return E_FAIL;
                }
            }
        }
    }

    ZapImage::ProfileDataSection * DataSection_ScenarioInfo = & m_profileDataSections[ScenarioInfo];
    if (DataSection_ScenarioInfo->pData != NULL)
    {
        CORBBTPROF_SCENARIO_INFO_SECTION_HEADER * header = (CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *) DataSection_ScenarioInfo->pData;
        m_profileDataNumRuns = header->TotalNumRuns;
    }

    return S_OK;
}


HRESULT ZapImage::convertProfileDataFromV1()
{
    if (m_pRawProfileData == NULL)
    {
        return S_FALSE;
    }

    //
    // For those sections that are collections of tokens, further parse that format to get
    // the token pointer and number of tokens
    //

    ProfileReader profileReader(m_pRawProfileData, m_cRawProfileData);

    for (SectionFormat format = FirstTokenFlagSection; format < SectionFormatCount; format = (SectionFormat) (format + 1))
    {
        if (m_profileDataSections[format].pData)
        {
            SEEK(((ULONG) (m_profileDataSections[format].pData - m_pRawProfileData)));

            CORBBTPROF_TOKEN_LIST_SECTION_HEADER *header;
            READ(header, CORBBTPROF_TOKEN_LIST_SECTION_HEADER);

            DWORD tableSize = header->NumTokens;

            if (tableSize == 0)
            {
                m_profileDataSections[format].tableSize = 0;
                m_profileDataSections[format].pTable    = NULL;
                continue;
            }

            DWORD dataSize  = (m_profileDataSections[format].dataSize - sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER));
            DWORD expectedSize = tableSize * sizeof (CORBBTPROF_TOKEN_LIST_ENTRY_V1);

            if (dataSize == expectedSize)
            {
                DWORD  newDataSize  = tableSize * sizeof (CORBBTPROF_TOKEN_INFO);

                if (newDataSize < dataSize)
                    return E_FAIL;

                BYTE * startOfTable = new (GetHeap()) BYTE[newDataSize];

                CORBBTPROF_TOKEN_LIST_ENTRY_V1 * pOldEntry;
                CORBBTPROF_TOKEN_INFO *    pNewEntry;

                pOldEntry = (CORBBTPROF_TOKEN_LIST_ENTRY_V1 *) (m_profileDataSections[format].pData + sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER));
                pNewEntry = (CORBBTPROF_TOKEN_INFO *)    startOfTable;

                for (DWORD i=0; i<tableSize; i++)
                {
                    pNewEntry->token = pOldEntry->token;
                    pNewEntry->flags = pOldEntry->flags;
                    pNewEntry->scenarios = 1;

                    pOldEntry++;
                    pNewEntry++;
                }
                m_profileDataSections[format].tableSize = tableSize;
                m_profileDataSections[format].pTable    = (CORBBTPROF_TOKEN_INFO *) startOfTable;
            }
            else
            {
                _ASSERTE(!"Invalid CORBBTPROF_TOKEN_LIST_SECTION_HEADER header");
                return E_FAIL;
            }
        }
    }

    _ASSERTE(m_profileDataSections[ScenarioInfo].pData == 0);
    _ASSERTE(m_profileDataSections[ScenarioInfo].dataSize == 0);

    //
    // Convert the MethodBlockCounts format from V1 to V2
    //
    CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1 * mbcSectionHeader = NULL;
    if (m_profileDataSections[MethodBlockCounts].pData)
    {
        //
        // Compute the size of the method block count stream
        // 
        BYTE *  dstPtr           = NULL;
        BYTE *  srcPtr           = m_profileDataSections[MethodBlockCounts].pData;
        DWORD   maxSizeToRead    = m_profileDataSections[MethodBlockCounts].dataSize;
        DWORD   totalSizeNeeded  = 0; 
        DWORD   totalSizeRead    = 0;
       
        mbcSectionHeader = (CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1 *) srcPtr;

        totalSizeRead   += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1);
        totalSizeNeeded += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER); 
        srcPtr          += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1);

        if (totalSizeRead > maxSizeToRead)
        {
            return E_FAIL;
        }
       
        for (DWORD i=0; (i < mbcSectionHeader->NumMethods); i++)
        {
            CORBBTPROF_METHOD_HEADER_V1* methodEntry = (CORBBTPROF_METHOD_HEADER_V1 *) srcPtr;
            DWORD sizeRead   = 0;
            DWORD sizeWrite  = 0;

            sizeRead  += methodEntry->HeaderSize;
            sizeRead  += methodEntry->Size;
            sizeWrite += sizeof(CORBBTPROF_METHOD_HEADER);
            sizeWrite += methodEntry->Size;

            totalSizeRead   += sizeRead;
            totalSizeNeeded += sizeWrite;            

            if (totalSizeRead > maxSizeToRead)
            {
                return E_FAIL;
            }

            srcPtr += sizeRead;
        }
        assert(totalSizeRead == maxSizeToRead);

        // Reset the srcPtr
        srcPtr = m_profileDataSections[MethodBlockCounts].pData;
       
        BYTE * newMethodData = new (GetHeap()) BYTE[totalSizeNeeded];

        dstPtr = newMethodData;

        memcpy(dstPtr, srcPtr, sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER));
        srcPtr += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1);
        dstPtr += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER);
        
        for (DWORD i=0; (i < mbcSectionHeader->NumMethods); i++)
        {
            CORBBTPROF_METHOD_HEADER_V1 *  methodEntryV1 = (CORBBTPROF_METHOD_HEADER_V1 *) srcPtr;
            CORBBTPROF_METHOD_HEADER *     methodEntry   = (CORBBTPROF_METHOD_HEADER *)    dstPtr;
            DWORD sizeRead   = 0;
            DWORD sizeWrite  = 0;

            methodEntry->method.token   = methodEntryV1->MethodToken;
            methodEntry->method.ILSize  = 0;
            methodEntry->method.cBlock  = (methodEntryV1->Size / sizeof(CORBBTPROF_BLOCK_DATA));
            sizeRead  += methodEntryV1->HeaderSize; 
            sizeWrite += sizeof(CORBBTPROF_METHOD_HEADER);

            memcpy( dstPtr + sizeof(CORBBTPROF_METHOD_HEADER),
                    srcPtr + sizeof(CORBBTPROF_METHOD_HEADER_V1), 
                    (methodEntry->method.cBlock * sizeof(CORBBTPROF_BLOCK_DATA)));
            sizeRead  += methodEntryV1->Size; 
            sizeWrite += (methodEntry->method.cBlock * sizeof(CORBBTPROF_BLOCK_DATA));

            methodEntry->size    = sizeWrite;
            methodEntry->cDetail = 0;
            srcPtr += sizeRead;
            dstPtr += sizeWrite;
        }
       
        m_profileDataSections[MethodBlockCounts].pData    = newMethodData;
        m_profileDataSections[MethodBlockCounts].dataSize = totalSizeNeeded;
    }

    //
    // Allocate the scenario info section
    //
    {
        DWORD   sizeNeeded  = sizeof(CORBBTPROF_SCENARIO_INFO_SECTION_HEADER) + sizeof(CORBBTPROF_SCENARIO_HEADER);
        BYTE *  newData     = new (GetHeap()) BYTE[sizeNeeded];
        BYTE *  dstPtr      = newData;
        {
            CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *siHeader = (CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *) dstPtr;
            
            if (mbcSectionHeader != NULL)
                siHeader->TotalNumRuns = mbcSectionHeader->NumRuns;
            else
                siHeader->TotalNumRuns = 1;

            siHeader->NumScenarios = 1;

            dstPtr += sizeof(CORBBTPROF_SCENARIO_INFO_SECTION_HEADER);
        }
        {
            CORBBTPROF_SCENARIO_HEADER *sHeader = (CORBBTPROF_SCENARIO_HEADER *) dstPtr;

            sHeader->scenario.ordinal  = 1;
            sHeader->scenario.mask     = 1;
            sHeader->scenario.priority = 0;
            sHeader->scenario.numRuns  = 0;
            sHeader->scenario.cName    = 0; 

            sHeader->size = sHeader->Size();

            dstPtr += sizeof(CORBBTPROF_SCENARIO_HEADER);
        }
        m_profileDataSections[ScenarioInfo].pData = newData;
        m_profileDataSections[ScenarioInfo].dataSize = sizeNeeded;
    }

    //
    // Convert the BlobStream format from V1 to V2 
    //   
    if (m_profileDataSections[BlobStream].dataSize > 0)
    {
        //
        // Compute the size of the blob stream
        // 
        
        BYTE *  srcPtr           = m_profileDataSections[BlobStream].pData;
        BYTE *  dstPtr           = NULL;
        DWORD   maxSizeToRead    = m_profileDataSections[BlobStream].dataSize;
        DWORD   totalSizeNeeded  = 0;
        DWORD   totalSizeRead    = 0;
        bool    done             = false;
        
        while (!done)
        {
            CORBBTPROF_BLOB_ENTRY_V1* blobEntry = (CORBBTPROF_BLOB_ENTRY_V1 *) srcPtr;
            DWORD sizeWrite  = 0;
            DWORD sizeRead   = 0;

            if ((blobEntry->blobType >= MetadataStringPool) && (blobEntry->blobType <= MetadataUserStringPool))
            {
                sizeWrite += sizeof(CORBBTPROF_BLOB_POOL_ENTRY);
                sizeWrite += blobEntry->cBuffer;
                sizeRead  += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
                sizeRead  += blobEntry->cBuffer;
            }
            else if ((blobEntry->blobType >= ParamTypeSpec) && (blobEntry->blobType <= ParamMethodSpec))
            {
                sizeWrite += sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY);
                sizeWrite += blobEntry->cBuffer;
                if (blobEntry->blobType == ParamMethodSpec)
                {
                    sizeWrite -= 1;  // Adjust for 
                }
                sizeRead  += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
                sizeRead  += blobEntry->cBuffer;
            }
            else if (blobEntry->blobType == EndOfBlobStream)
            {
                sizeWrite += sizeof(CORBBTPROF_BLOB_ENTRY);
                sizeRead  += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
                done = true;
            }
            else
            {
                return E_FAIL;
            }
            
            totalSizeNeeded += sizeWrite;
            totalSizeRead   += sizeRead;
            
            if (sizeRead > maxSizeToRead)
            {
                return E_FAIL;
            }
            
            srcPtr += sizeRead;
        }

        assert(totalSizeRead == maxSizeToRead);

        // Reset the srcPtr
        srcPtr = m_profileDataSections[BlobStream].pData;
        
        BYTE * newBlobData = new (GetHeap()) BYTE[totalSizeNeeded];

        dstPtr = newBlobData;
        done = false;
        
        while (!done)
        {
            CORBBTPROF_BLOB_ENTRY_V1* blobEntryV1 = (CORBBTPROF_BLOB_ENTRY_V1 *) srcPtr;
            DWORD sizeWrite  = 0;
            DWORD sizeRead   = 0;
            
            if ((blobEntryV1->blobType >= MetadataStringPool) && (blobEntryV1->blobType <= MetadataUserStringPool))
            {
                CORBBTPROF_BLOB_POOL_ENTRY* blobPoolEntry = (CORBBTPROF_BLOB_POOL_ENTRY*) dstPtr;
                
                blobPoolEntry->blob.type = blobEntryV1->blobType;
                blobPoolEntry->blob.size = sizeof(CORBBTPROF_BLOB_POOL_ENTRY) + blobEntryV1->cBuffer;
                blobPoolEntry->cBuffer   = blobEntryV1->cBuffer;
                memcpy(blobPoolEntry->buffer, blobEntryV1->pBuffer, blobEntryV1->cBuffer);
                
                sizeWrite += sizeof(CORBBTPROF_BLOB_POOL_ENTRY);
                sizeWrite += blobEntryV1->cBuffer;
                sizeRead  += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
                sizeRead  += blobEntryV1->cBuffer;
            }
            else if ((blobEntryV1->blobType >= ParamTypeSpec) && (blobEntryV1->blobType <= ParamMethodSpec))
            {
                CORBBTPROF_BLOB_PARAM_SIG_ENTRY* blobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY*) dstPtr;

                blobSigEntry->blob.type  = blobEntryV1->blobType;
                blobSigEntry->blob.size  = sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY) + blobEntryV1->cBuffer;
                blobSigEntry->blob.token = 0;
                blobSigEntry->cSig       = blobEntryV1->cBuffer; 

                if (blobEntryV1->blobType == ParamMethodSpec)
                {
                    // Adjust cSig and blob.size
                    blobSigEntry->cSig--; 
                    blobSigEntry->blob.size--;
                }
                memcpy(blobSigEntry->sig, blobEntryV1->pBuffer, blobSigEntry->cSig);
                
                sizeWrite += sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY);
                sizeWrite += blobSigEntry->cSig;
                sizeRead  += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
                sizeRead  += blobEntryV1->cBuffer;
            }
            else if (blobEntryV1->blobType == EndOfBlobStream)
            {
                CORBBTPROF_BLOB_ENTRY* blobEntry = (CORBBTPROF_BLOB_ENTRY*) dstPtr;

                blobEntry->type = blobEntryV1->blobType;
                blobEntry->size = sizeof(CORBBTPROF_BLOB_ENTRY);
                
                sizeWrite += sizeof(CORBBTPROF_BLOB_ENTRY);
                sizeRead  += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
                done = true;
            }
            else
            {
                return E_FAIL;
            }
            srcPtr += sizeRead;
            dstPtr += sizeWrite;
        }
       
        m_profileDataSections[BlobStream].pData    = newBlobData;
        m_profileDataSections[BlobStream].dataSize = totalSizeNeeded;
    }
    else
    {
        m_profileDataSections[BlobStream].pData    = NULL;
        m_profileDataSections[BlobStream].dataSize = 0;
    }

    return S_OK;
}

void ZapImage::RehydrateBasicBlockSection()
{
    ProfileDataSection &section = m_profileDataSections[MethodBlockCounts];
    if (!section.pData)
    {
        return;
    }

    ProfileReader reader(section.pData, section.dataSize);

    m_profileDataNumRuns = reader.Read<unsigned int>();

    // The IBC data provides a hint to the number of basic blocks, which is
    // used here to determine how much space to allocate for the rehydrated
    // data.
    unsigned int blockCountHint = reader.Read<unsigned int>();

    unsigned int numMethods = reader.Read<unsigned int>();

    unsigned int expectedLength =
        sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER) +
        sizeof(CORBBTPROF_METHOD_HEADER) * numMethods +
        sizeof(CORBBTPROF_BLOCK_DATA) * blockCountHint;

    BinaryWriter writer(expectedLength, GetHeap());

    writer.Write(numMethods);

    mdToken lastMethodToken = 0x06000000;

    CORBBTPROF_METHOD_HEADER methodHeader;
    methodHeader.cDetail = 0;
    methodHeader.method.ILSize = 0;

    for (unsigned int i = 0; i < numMethods; ++i)
    {
        // Translate the method header
        unsigned int size = reader.Read7BitEncodedInt();
        unsigned int startPosition = reader.GetCurrentPos();

        mdToken token = reader.ReadTokenWithMemory(lastMethodToken);
        unsigned int ilSize = reader.Read7BitEncodedInt();
        unsigned int firstBlockHitCount = reader.Read7BitEncodedInt();

        unsigned int numOtherBlocks = reader.Read7BitEncodedInt();

        methodHeader.method.cBlock = 1 + numOtherBlocks;
        methodHeader.method.token = token;
        methodHeader.method.ILSize = ilSize;
        methodHeader.size = (DWORD)methodHeader.Size();

        writer.Write(methodHeader);

        CORBBTPROF_BLOCK_DATA blockData;

        // The first block is handled specially.
        blockData.ILOffset = 0;
        blockData.ExecutionCount = firstBlockHitCount;

        writer.Write(blockData);

        // Translate the rest of the basic blocks
        for (unsigned int j = 0; j < numOtherBlocks; ++j)
        {
            blockData.ILOffset = reader.Read7BitEncodedInt();
            blockData.ExecutionCount = reader.Read7BitEncodedInt();

            writer.Write(blockData);
        }

        if (!reader.Seek(startPosition + size))
        {
            ThrowHR(E_FAIL);
        }
    }

    // If the expected and actual lengths differ, the result will still be
    // correct but performance may suffer slightly because of reallocations.
    _ASSERTE(writer.GetWrittenSize() == expectedLength);

    section.pData = writer.GetBuffer();
    section.dataSize = writer.GetWrittenSize();
}

void ZapImage::RehydrateTokenSection(int sectionFormat, unsigned int flagTable[255])
{
    ProfileDataSection &section = m_profileDataSections[sectionFormat];
    ProfileReader reader(section.pData, section.dataSize);

    unsigned int numTokens = reader.Read<unsigned int>();

    unsigned int dataLength = sizeof(unsigned int) +
                              numTokens * sizeof(CORBBTPROF_TOKEN_INFO);
    BinaryWriter writer(dataLength, GetHeap());

    writer.Write(numTokens);

    mdToken lastToken = (sectionFormat - FirstTokenFlagSection) << 24;

    CORBBTPROF_TOKEN_INFO tokenInfo;
    tokenInfo.scenarios = 1;

    for (unsigned int i = 0; i < numTokens; ++i)
    {
        tokenInfo.token = reader.ReadTokenWithMemory(lastToken);
        tokenInfo.flags = reader.ReadFlagWithLookup(flagTable);

        writer.Write(tokenInfo);
    }

    _ASSERTE(writer.GetWrittenSize() == dataLength);
    
    section.pData = writer.GetBuffer();
    section.dataSize = writer.GetWrittenSize();
    section.pTable = (CORBBTPROF_TOKEN_INFO *)(section.pData + sizeof(unsigned int));
    section.tableSize = numTokens;
}

void ZapImage::RehydrateBlobStream()
{
    ProfileDataSection &section = m_profileDataSections[BlobStream];

    ProfileReader reader(section.pData, section.dataSize);

    // Evidence suggests that rehydrating the blob stream in Framework binaries
    // increases the size from 1.5-2x. When this was written, 1.85x minimized
    // the amount of extra memory allocated (about 48K in the worst case).
    BinaryWriter writer((DWORD)(section.dataSize * 1.85f), GetHeap());

    mdToken LastBlobToken = 0;
    mdToken LastAssemblyToken = 0x23000000;
    mdToken LastExternalTypeToken = 0x62000000;
    mdToken LastExternalNamespaceToken = 0x61000000;
    mdToken LastExternalSignatureToken = 0x63000000;

    int blobType = 0;
    do
    {
        // Read the blob header.

        unsigned int sizeToRead = reader.Read7BitEncodedInt();
        unsigned int startPositionRead = reader.GetCurrentPos();
    
        blobType = reader.Read7BitEncodedInt();
        mdToken token = reader.ReadTokenWithMemory(LastBlobToken);

        // Write out the blob header.

        // Note the location in the write stream, and write a 0 there. Once
        // this blob has been written in its entirety, this location can be
        // used to calculate the real size and to go back to the right place
        // to write it.

        unsigned int startPositionWrite = writer.GetWrittenSize();
        writer.Write(0U);

        writer.Write(blobType);
        writer.Write(token);

        // All blobs (except the end-of-stream indicator) end as:
        //     <data length> <data>
        // Two blob types (handled immediately below) include tokens as well.
        // Handle those first, then handle the common case.

        if (blobType == ExternalTypeDef)
        {
            writer.Write(reader.ReadTokenWithMemory(LastAssemblyToken));
            writer.Write(reader.ReadTokenWithMemory(LastExternalTypeToken));
            writer.Write(reader.ReadTokenWithMemory(LastExternalNamespaceToken));
        }
        else if (blobType == ExternalMethodDef)
        {
            writer.Write(reader.ReadTokenWithMemory(LastExternalTypeToken));
            writer.Write(reader.ReadTokenWithMemory(LastExternalSignatureToken));
        }

        if ((blobType >= MetadataStringPool) && (blobType < IllegalBlob))
        {
            // This blob is of known type and ends with data.
            unsigned int dataLength = reader.Read7BitEncodedInt();
            char *data = (char *)reader.Read(dataLength);

            if (!data)
            {
                ThrowHR(E_FAIL);
            }

            writer.Write(dataLength);
            writer.Write(data, dataLength);
        }

        // Write the size for this blob.

        writer.WriteAt(startPositionWrite,
                       writer.GetWrittenSize() - startPositionWrite);

        // Move to the next blob.

        if (!reader.Seek(startPositionRead + sizeToRead))
        {
            ThrowHR(E_FAIL);
        }
    }
    while (blobType != EndOfBlobStream);

    section.pData = writer.GetBuffer();
    section.dataSize = writer.GetWrittenSize();
}

HRESULT ZapImage::RehydrateProfileData()
{
    HRESULT hr = S_OK;
    unsigned int flagTable[255];
    memset(flagTable, 0xFF, sizeof(flagTable));
    
    EX_TRY
    {
        RehydrateBasicBlockSection();
        RehydrateBlobStream();
        for (int format = FirstTokenFlagSection;
             format < SectionFormatCount;
             ++format)
        {
            if (m_profileDataSections[format].pData)
            {
                RehydrateTokenSection(format, flagTable);
            }
        }
    }
    EX_CATCH_HRESULT_NO_ERRORINFO(hr);

    return hr;
}

HRESULT ZapImage::hashBBProfileData ()
{
    ProfileDataSection * DataSection_MethodBlockCounts = & m_profileDataSections[MethodBlockCounts];

    if (!DataSection_MethodBlockCounts->pData)
    {
        return E_FAIL;
    }

    ProfileReader profileReader(DataSection_MethodBlockCounts->pData, DataSection_MethodBlockCounts->dataSize);

    CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER *mbcHeader;
    READ(mbcHeader,CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER);

    for (ULONG i = 0; i < mbcHeader->NumMethods; i++)
    {
        ProfileDataHashEntry newEntry;
        newEntry.pos = profileReader.GetCurrentPos();
        
        CORBBTPROF_METHOD_HEADER *methodHeader;
        READ(methodHeader,CORBBTPROF_METHOD_HEADER);
        newEntry.md   = methodHeader->method.token;
        newEntry.size = methodHeader->size;
        newEntry.flags = 0;
        newEntry.status = NOT_COMPILED;

        // Add the new entry to the table
        profileDataHashTable.Add(newEntry);

        // Skip the profileData so we can read the next method.
        void *profileData;
        READ_SIZE(profileData, void, (methodHeader->size - sizeof(CORBBTPROF_METHOD_HEADER)));
    }

    return S_OK;
}

void ZapImage::hashBBUpdateFlagsAndCompileResult(mdToken token, unsigned methodProfilingDataFlags, ZapImage::CompileStatus compileResult)
{
    // SHash only supports replacing an entry so we setup our newEntry and then perform a lookup
    //
    ProfileDataHashEntry newEntry;
    newEntry.md = token;
    newEntry.flags = methodProfilingDataFlags;
    newEntry.status = compileResult;

    const ProfileDataHashEntry* pEntry = profileDataHashTable.LookupPtr(token);
    if (pEntry != nullptr)
    {
        assert(pEntry->md == newEntry.md);
        assert(pEntry->flags == 0);   // the flags should not be set at this point.

        // Copy and keep the two fleids that were previously set
        newEntry.size = pEntry->size;
        newEntry.pos = pEntry->pos;
    }
    else // We have a method that doesn't have basic block counts
    {
        newEntry.size = 0;
        newEntry.pos = 0;
    }
    profileDataHashTable.AddOrReplace(newEntry);
}

void ZapImage::LoadProfileData()
{
    HRESULT hr = E_FAIL;

    m_fHaveProfileData = false;
    m_pRawProfileData  = NULL;
    m_cRawProfileData  = 0;

    EX_TRY
    {
        hr = LocateProfileData();
        
        if (hr == S_OK)
        {
            hr = parseProfileData();
            if (hr == S_OK)
            {
                hr = hashBBProfileData();
            }
        }
    }
    EX_CATCH
    {
        hr = E_FAIL;
    }
    EX_END_CATCH(SwallowAllExceptions);
    
    if (hr != S_OK)
    {
        m_fHaveProfileData = false;
        m_pRawProfileData = NULL;
        m_cRawProfileData = 0;

        if (FAILED(hr))
        {
            m_zapper->Warning(W("Warning: Invalid profile data was ignored for %s\n"), m_pModuleFileName);
        }
    }
}

// Initializes our form of the profile data stored in the assembly.

CorProfileData *  ZapImage::NewProfileData()
{
    this->m_pCorProfileData = new CorProfileData(&m_profileDataSections[0]);

    return this->m_pCorProfileData;
}

// Returns the profile data stored in the assembly.

CorProfileData *  ZapImage::GetProfileData()
{
    _ASSERTE(this->m_pCorProfileData != NULL);

    return this->m_pCorProfileData;
}

CorProfileData::CorProfileData(void *  rawProfileData)
{
    ZapImage::ProfileDataSection * profileData =  (ZapImage::ProfileDataSection *) rawProfileData;

    for (DWORD format = 0; format < SectionFormatCount; format++)
    {
        this->profilingTokenFlagsData[format].count = profileData[format].tableSize;
        this->profilingTokenFlagsData[format].data  = profileData[format].pTable;
    }

    this->blobStream = (CORBBTPROF_BLOB_ENTRY *) profileData[BlobStream].pData;
}


// Determines whether a method can be called directly from another method (without
// going through the prestub) in the current module.
// callerFtn=NULL implies any/unspecified caller in the current module.
//
// Returns NULL if 'calleeFtn' cannot be called directly *at the current time*
// Else returns the direct address that 'calleeFtn' can be called at.


bool ZapImage::canIntraModuleDirectCall(
                        CORINFO_METHOD_HANDLE callerFtn,
                        CORINFO_METHOD_HANDLE targetFtn,
                        CorInfoIndirectCallReason *pReason,
                        CORINFO_ACCESS_FLAGS  accessFlags/*=CORINFO_ACCESS_ANY*/)
{
    CorInfoIndirectCallReason reason;
    if (pReason == NULL)
        pReason = &reason;
    *pReason = CORINFO_INDIRECT_CALL_UNKNOWN;

    // The caller should have checked that the method is in current loader module
    _ASSERTE(m_hModule == m_zapper->m_pEECompileInfo->GetLoaderModuleForEmbeddableMethod(targetFtn));

    // No direct calls at all under some circumstances

    if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_PROF_ENTERLEAVE)
        && !m_pPreloader->IsDynamicMethod(callerFtn))
    {
        *pReason = CORINFO_INDIRECT_CALL_PROFILING;
        goto CALL_VIA_ENTRY_POINT;
    }

    // Does the methods's class have a cctor, etc?

    if (!m_pPreloader->CanSkipMethodPreparation(callerFtn, targetFtn, pReason, accessFlags))
        goto CALL_VIA_ENTRY_POINT;

    ZapMethodHeader * pMethod;
    pMethod = GetCompiledMethod(targetFtn);

    // If we have not compiled the method then we can't call direct

    if (pMethod == NULL)
    {
        *pReason = CORINFO_INDIRECT_CALL_NO_CODE;
        goto CALL_VIA_ENTRY_POINT;
    }

    // Does the method have fixups?

    if (pMethod->HasFixups() != NULL)
    {
        *pReason = CORINFO_INDIRECT_CALL_FIXUPS;
        goto CALL_VIA_ENTRY_POINT;
    }

#ifdef _DEBUG
    const char* clsName, * methodName;
    methodName = m_zapper->m_pEEJitInfo->getMethodName(targetFtn, &clsName);
    LOG((LF_ZAP, LL_INFO10000, "getIntraModuleDirectCallAddr: Success %s::%s\n",
        clsName, methodName));
#endif

    return true;

CALL_VIA_ENTRY_POINT:

#ifdef _DEBUG
    methodName = m_zapper->m_pEEJitInfo->getMethodName(targetFtn, &clsName);
    LOG((LF_ZAP, LL_INFO10000, "getIntraModuleDirectCallAddr: Via EntryPoint %s::%s\n",
         clsName, methodName));
#endif

    return false;
}

//
// Relocations
//

void ZapImage::WriteReloc(PVOID pSrc, int offset, ZapNode * pTarget, int targetOffset, ZapRelocationType type)
{
    _ASSERTE(!IsWritingRelocs());

    _ASSERTE(m_pBaseRelocs != NULL);
    m_pBaseRelocs->WriteReloc(pSrc, offset, pTarget, targetOffset, type);
}

ZapImage * ZapImage::GetZapImage()
{
    return this;
}

void ZapImage::FileNotFoundError(LPCWSTR pszMessage)
{
    SString message(pszMessage);

    for (COUNT_T i = 0; i < fileNotFoundErrorsTable.GetCount(); i++)
    {
        // Check to see if same error has already been displayed for this ngen operation
        if (message.Equals(fileNotFoundErrorsTable[i]))
            return;
    }

    CorZapLogLevel level;

#ifdef CROSSGEN_COMPILE
    // Warnings should not go to stderr during crossgen
    level = CORZAP_LOGLEVEL_WARNING;
#else
    level = CORZAP_LOGLEVEL_ERROR;
#endif

    m_zapper->Print(level, W("Warning: %s.\n"), pszMessage);

    fileNotFoundErrorsTable.Append(message);
}

void ZapImage::Error(mdToken token, HRESULT hr, UINT resID,  LPCWSTR message)
{
    // Missing dependencies are reported as fatal errors in code:CompilationDomain::BindAssemblySpec.
    // Avoid printing redundant error message for them.
    if (FAILED(g_hrFatalError))
        ThrowHR(g_hrFatalError);

    // COM introduces the notion of a vtable gap method, which is not a real method at all but instead
    // aids in the explicit layout of COM interop vtables. These methods have no implementation and no
    // direct runtime state tracking them. Trying to lookup a method handle for a vtable gap method will
    // throw an exception but we choose to let that happen and filter out the warning here in the
    // handler because (a) vtable gap methods are rare and (b) it's not all that cheap to identify them
    // beforehand.
    if ((TypeFromToken(token) == mdtMethodDef) && IsVTableGapMethod(token))
    {
        return;
    }

    CorZapLogLevel level = CORZAP_LOGLEVEL_ERROR;

    // Some warnings are demoted to informational level
    if (resID == IDS_EE_SIMD_NGEN_DISALLOWED)
    {
        // Supress printing of "Target-dependent SIMD vector types may not be used with ngen."
        level = CORZAP_LOGLEVEL_INFO;
    }

    if (resID == IDS_EE_HWINTRINSIC_NGEN_DISALLOWED)
    {
        // Supress printing of "Hardware intrinsics may not be used with ngen."
        level = CORZAP_LOGLEVEL_INFO;
    }

#ifdef CROSSGEN_COMPILE
    if ((resID == IDS_IBC_MISSING_EXTERNAL_TYPE) ||
        (resID == IDS_IBC_MISSING_EXTERNAL_METHOD))
    {
        // Supress printing of "The generic type/method specified by the IBC data is not available to this assembly"
        level = CORZAP_LOGLEVEL_INFO;
    }   
#endif        

    if (m_zapper->m_pOpt->m_ignoreErrors)
    {
#ifdef CROSSGEN_COMPILE
        // Warnings should not go to stderr during crossgen
        if (level == CORZAP_LOGLEVEL_ERROR)
        {
            level = CORZAP_LOGLEVEL_WARNING;
        }
#endif
        m_zapper->Print(level, W("Warning: "));
    }
    else
    {
        m_zapper->Print(level, W("Error: "));
    }

    if (message != NULL)
        m_zapper->Print(level, W("%s"), message);
    else
        m_zapper->PrintErrorMessage(level, hr);

    m_zapper->Print(level, W(" while resolving 0x%x - "), token);
    PrintTokenDescription(level, token);
    m_zapper->Print(level, W(".\n"));

    if (m_zapper->m_pOpt->m_ignoreErrors)
        return;

    IfFailThrow(hr);
}

ZapNode * ZapImage::GetInnerPtr(ZapNode * pNode, SSIZE_T offset)
{
    return m_pInnerPtrs->Get(pNode, offset);
}

ZapNode * ZapImage::GetHelperThunk(CorInfoHelpFunc ftnNum)
{
    ZapNode * pHelperThunk = m_pHelperThunks[ftnNum];

    if (pHelperThunk == NULL)
    {
        pHelperThunk = new (GetHeap()) ZapHelperThunk(ftnNum);
#ifdef _TARGET_ARM_
        pHelperThunk = GetInnerPtr(pHelperThunk, THUMB_CODE);
#endif
        m_pHelperThunks[ftnNum] = pHelperThunk;
    }

    // Ensure that the thunk is placed
    ZapNode * pTarget = pHelperThunk;
    if (pTarget->GetType() == ZapNodeType_InnerPtr)
        pTarget = ((ZapInnerPtr *)pTarget)->GetBase();
    if (!pTarget->IsPlaced())
        m_pHelperTableSection->Place(pTarget);

    return pHelperThunk;
}

//
// Compute a class-layout order based on a breadth-first traversal of 
// the class graph (based on what classes contain calls to other classes).
// We cannot afford time or space to build the graph, so we do processing
// in place.
// 
void ZapImage::ComputeClassLayoutOrder()
{
    // In order to make the computation efficient, we need to store per-class 
    // intermediate values in the class layout field.  These come in two forms:
    // 
    //   - An entry with the UNSEEN_CLASS_FLAG set is one that is yet to be encountered.
    //   - An entry with METHOD_INDEX_FLAG set is an index into the m_MethodCompilationOrder list
    //     indicating where the unprofiled methods of this class begin
    //   
    // Both flags begin set (by InitializeClassLayoutOrder) since the value initialized is
    // the method index and the class has not been encountered by the algorithm.
    // When a class layout has been computed, both of these flags will have been stripped.


    // Early-out in the (probably impossible) case that these bits weren't available
    if (m_MethodCompilationOrder.GetCount() >= UNSEEN_CLASS_FLAG ||
        m_MethodCompilationOrder.GetCount() >= METHOD_INDEX_FLAG)
    {
        return;
    }

    // Allocate the queue for the breadth-first traversal.
    // Note that the use of UNSEEN_CLASS_FLAG ensures that no class is enqueued more
    // than once, so we can use that bound for the size of the queue.
    CORINFO_CLASS_HANDLE * classQueue = new CORINFO_CLASS_HANDLE[m_ClassLayoutOrder.GetCount()];

    unsigned classOrder = 0;
    for (COUNT_T i = m_iUntrainedMethod; i < m_MethodCompilationOrder.GetCount(); i++)
    {
        unsigned classQueueNext = 0;
        unsigned classQueueEnd = 0;
        COUNT_T  methodIndex = 0;

        //
        // Find an unprocessed method to seed the next breadth-first traversal.
        //

        ZapMethodHeader * pMethod = m_MethodCompilationOrder[i];
        const ClassLayoutOrderEntry * pEntry = m_ClassLayoutOrder.LookupPtr(pMethod->m_classHandle);
        _ASSERTE(pEntry);
        
        if ((pEntry->m_order & UNSEEN_CLASS_FLAG) == 0)
        {
            continue;
        }

        //
        // Enqueue the method's class and start the traversal.
        //

        classQueue[classQueueEnd++] = pMethod->m_classHandle;
        ((ClassLayoutOrderEntry *)pEntry)->m_order &= ~UNSEEN_CLASS_FLAG;

        while (classQueueNext < classQueueEnd)
        {
            //
            // Dequeue a class and pull out the index of its first method
            //
            
            CORINFO_CLASS_HANDLE dequeuedClassHandle = classQueue[classQueueNext++];
            _ASSERTE(dequeuedClassHandle != NULL);

            pEntry = m_ClassLayoutOrder.LookupPtr(dequeuedClassHandle);
            _ASSERTE(pEntry);
            _ASSERTE((pEntry->m_order & UNSEEN_CLASS_FLAG) == 0);
            _ASSERTE((pEntry->m_order & METHOD_INDEX_FLAG) != 0);

            methodIndex = pEntry->m_order & ~METHOD_INDEX_FLAG;
            _ASSERTE(methodIndex < m_MethodCompilationOrder.GetCount());

            //
            // Set the real layout order of the class, and examine its unprofiled methods
            //
            
            ((ClassLayoutOrderEntry *)pEntry)->m_order = ++classOrder;
                
            pMethod = m_MethodCompilationOrder[methodIndex];
            _ASSERTE(pMethod->m_classHandle == dequeuedClassHandle);

            while (pMethod->m_classHandle == dequeuedClassHandle)
            {

                //
                // For each unprofiled method, find target classes and enqueue any that haven't been seen
                //

                ZapMethodHeader::PartialTargetMethodIterator it(pMethod);

                CORINFO_METHOD_HANDLE targetMethodHandle;
                while (it.GetNext(&targetMethodHandle))
                {
                    CORINFO_CLASS_HANDLE targetClassHandle = GetJitInfo()->getMethodClass(targetMethodHandle);
                    if (targetClassHandle != pMethod->m_classHandle)
                    {
                        pEntry = m_ClassLayoutOrder.LookupPtr(targetClassHandle);

                        if (pEntry && (pEntry->m_order & UNSEEN_CLASS_FLAG) != 0)
                        {
                            _ASSERTE(classQueueEnd < m_ClassLayoutOrder.GetCount());
                            classQueue[classQueueEnd++] = targetClassHandle;

                            ((ClassLayoutOrderEntry *)pEntry)->m_order &= ~UNSEEN_CLASS_FLAG;
                        }
                    }
                }

                if (++methodIndex == m_MethodCompilationOrder.GetCount())
                {
                    break;
                }
                    
                pMethod = m_MethodCompilationOrder[methodIndex];
            }
        }
    }

    for (COUNT_T i = m_iUntrainedMethod; i < m_MethodCompilationOrder.GetCount(); i++)
    {
        ZapMethodHeader * pMethod = m_MethodCompilationOrder[i];
        pMethod->m_cachedLayoutOrder = LookupClassLayoutOrder(pMethod->m_classHandle);
    }

    m_fHasClassLayoutOrder = true;

    delete [] classQueue;
}

static int __cdecl LayoutOrderCmp(const void* a_, const void* b_)
{
    ZapMethodHeader * a = *((ZapMethodHeader**)a_);
    ZapMethodHeader * b = *((ZapMethodHeader**)b_);

    int layoutDiff = a->GetCachedLayoutOrder() - b->GetCachedLayoutOrder();
    if (layoutDiff != 0)
        return layoutDiff;

    // Use compilation order as secondary key to get predictable ordering within the bucket
    return a->GetCompilationOrder() - b->GetCompilationOrder();
}

void ZapImage::SortUnprofiledMethodsByClassLayoutOrder()
{
    qsort(&m_MethodCompilationOrder[m_iUntrainedMethod], m_MethodCompilationOrder.GetCount() - m_iUntrainedMethod, sizeof(ZapMethodHeader *), LayoutOrderCmp);
}