summaryrefslogtreecommitdiff
path: root/src/zap/zapimage.cpp
blob: a7723c74d08192ca8b663c39d1a480e29638c49a (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
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license 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"

#ifdef  MDIL
#include "WellKnownTypes.h"
struct GuidInfo;
class MethodDesc;
class MethodTable;
#include "CompactLayoutWriter.h"
#endif

// 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)
    /* Everything else is initialized to 0 by default */
{
#ifndef FEATURE_CORECLR
    if (m_zapper->m_pOpt->m_statOptions)
        m_stats = new ZapperStats();
#endif
}

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

    //
    // Clean up.
    //
#ifndef FEATURE_CORECLR
    if (m_stats != NULL)
        delete m_stats;
#endif

    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();

#ifdef MDIL
    if (m_pMdilDebugInfoTable != NULL)
        m_pMdilDebugInfoTable->~MdilDebugInfoTable();
#endif

    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), sizeof(TADDR));
    m_pEETableSection->Place(m_pEEInfoTable);

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

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

#ifdef MDIL
    if (m_zapper->m_fEmbedMDIL)
    {
        if (m_cbMdilPESectionData != NULL)
        {
            ZapBlob *mdilData = ZapBlob::NewAlignedBlob(this, m_pMdilPESectionData, m_cbMdilPESectionData, sizeof(TADDR));
            m_pMDILSection->Place(mdilData);
        }
        else
        {
            m_zapper->Error(W("Could not embed mdil data in ni image. MDIL data not present in IL file.\n"));
            IfFailThrow(E_INVALIDARG);
        }
    }
#endif // MDIL

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

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

#ifdef MDIL
    m_pMdilDebugInfoTable = new (GetHeap()) MdilDebugInfoTable(this);
#endif

    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);

    {
#ifdef FEATURE_CORECLR
#define COMPILER_NAME "CoreCLR"
#else
#define COMPILER_NAME "CLR"
#endif

        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);
}
#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, sizeof(TADDR));

        //
        // 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, sizeof(TADDR));
        }

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

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

        // 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, sizeof(TADDR));

        // 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, sizeof(TADDR));
        }

        //
        // 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, sizeof(TADDR));

        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, sizeof(TADDR));
        m_pPreloadSections[CORCOMPILE_SECTION_CROSS_DOMAIN_INFO] = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | CrossDomainInfoSection, sizeof(TADDR));
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_DESC_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | MethodDescSection, sizeof(TADDR));
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_DESC_COLD_WRITEABLE] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | MethodDescWriteableSection, sizeof(TADDR));
        m_pPreloadSections[CORCOMPILE_SECTION_MODULE_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | ModuleSection, sizeof(TADDR));
        m_pPreloadSections[CORCOMPILE_SECTION_DEBUG_COLD] = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | DebugSection, sizeof(TADDR));

        //
        // If we're instrumenting allocate a section for writing profile data
        //
        if (m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_BBINSTR)
        {
            m_pInstrumentSection = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | InstrumentSection, sizeof(TADDR));
        }
    }

    // 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, sizeof(TADDR));
        m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_HOT] = NewVirtualSection(pXDataSection, IBCProfiledSection | HotRange | MethodPrecodeSection, sizeof(TADDR));

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

    {
        // 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, sizeof(TADDR));
        m_pPreloadSections[CORCOMPILE_SECTION_READONLY_HOT] = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | ReadonlySection, sizeof(TADDR));

        //
        // 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));

#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, sizeof(TADDR));

        //
        // 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, sizeof(TADDR));

        //
        // 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));
    }

#ifdef MDIL
    {
        //
        // .mdil section
        //
        m_pMDILSection = NULL;
        if (m_zapper->m_fEmbedMDIL)
        {
            ZapPhysicalSection * pMDILSection = NewPhysicalSection(".mdil", IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ);
            m_pMDILSection = NewVirtualSection(pMDILSection, IBCUnProfiledSection | ColdRange | MDILDataSection);
        }
    }
#endif

    {
        //
        // .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);

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

#ifdef BINDER
void ZapImage::SetNativeVersionResource(PVOID pvVersionResourceBlob, SIZE_T cbVersionResource)
{
    ZapNode* pBlob = ZapBlob::NewAlignedBlob(this, pvVersionResourceBlob, cbVersionResource, sizeof(TADDR));
    ZapVersionResource * pWin32VersionResource = new (GetHeap()) ZapVersionResource(pBlob);
    m_pWin32ResourceSection->Place(pWin32VersionResource);
    m_pWin32ResourceSection->Place(pBlob);

    SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_RESOURCE, m_pWin32ResourceSection);
}
#endif
#ifdef CLR_STANDALONE_BINDER
void ZapImage::EmitMethodIL(mdToken methodDefToken)
{
    if (m_pILMetaData != NULL)
        m_pILMetaData->EmitMethodIL(methodDefToken);
}
void ZapImage::EmitFieldRVA(mdToken fieldDefToken, RVA fieldRVA)
{
    if (m_pILMetaData != NULL)
        m_pILMetaData->EmitFieldRVA(fieldDefToken, fieldRVA);
}
#endif

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);

        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;
}

#ifdef FEATURE_FUSION
#define WOF_PROVIDER_FILE           (0x00000002)

typedef BOOL (WINAPI *WofShouldCompressBinaries_t) (
    __in LPCWSTR Volume,
    __out PULONG Algorithm
    );

typedef HRESULT (WINAPI *WofSetFileDataLocation_t) (
    __in HANDLE hFile,
    __out ULONG Provider,
    __in PVOID FileInfo,
    __in ULONG Length
    );

typedef struct _WOF_FILE_COMPRESSION_INFO {
    ULONG Algorithm;
} WOF_FILE_COMPRESSION_INFO, *PWOF_FILE_COMPRESSION_INFO;

// Check if files on the volume identified by volumeLetter should be compressed.
// If yes, compress the file associated with hFile.
static void CompressFile(WCHAR volumeLetter, HANDLE hFile)
{
    if (IsNgenOffline())
    {
        return;
    }

    // Wofutil.dll is available on Windows 8.1 and above. Return on platforms without wofutil.dll.
    HModuleHolder wofLibrary(WszLoadLibraryEx(L"wofutil.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32));
    if (wofLibrary == nullptr)
    {
        return;
    }

    // WofShouldCompressBinaries is available on Windows 10 and above.
    // Windows 8.1 version of wofutil.dll does not have this function.
    WofShouldCompressBinaries_t WofShouldCompressBinaries
        = (WofShouldCompressBinaries_t)GetProcAddress(wofLibrary, "WofShouldCompressBinaries");
    if (WofShouldCompressBinaries == nullptr)
    {
        return;
    }

    WCHAR volume[4] = L"X:\\";
    volume[0] = volumeLetter;
    ULONG algorithm = 0;

    bool compressionSuitable = (WofShouldCompressBinaries(volume, &algorithm) == TRUE);
    if (compressionSuitable)
    {
        // WofSetFileDataLocation is available on Windows 8.1 and above, however, Windows 8.1 version
        // of WofSetFileDataLocation works for WIM only, and Windows 10 is required for compression of
        // normal files.  This isn't a problem for us, since the check for WofShouldCompressBinaries
        // above should have already returned on Windows 8.1.
        WofSetFileDataLocation_t WofSetFileDataLocation = 
            (WofSetFileDataLocation_t)GetProcAddress(wofLibrary, "WofSetFileDataLocation");
        if (WofSetFileDataLocation == nullptr)
        {
            return;
        }

        WOF_FILE_COMPRESSION_INFO fileInfo;
        fileInfo.Algorithm = algorithm;

        WofSetFileDataLocation(hFile, WOF_PROVIDER_FILE, &fileInfo, sizeof(WOF_FILE_COMPRESSION_INFO));
    }
}
#endif

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

    OutputTables();

    ComputeRVAs();

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

#ifdef CLR_STANDALONE_BINDER
        m_pDataImage->FixupRVAs();
#endif
    }

    HANDLE hFile = GenerateFile(wszOutputFileName, pNativeImageSig);

#ifndef FEATURE_CORECLR
    if (m_stats != NULL)
        PrintStats(wszOutputFileName);
#endif

#ifdef FEATURE_FUSION
    CompressFile(wszOutputFileName[0], hFile);
#endif

    return hFile;
}

void ZapImage::PrintStats(LPCWSTR wszOutputFileName)
{
    m_stats->m_gcInfoSize = m_pHotTouchedGCSection->GetSize() + m_pHotGCSection->GetSize() + m_pGCSection->GetSize();
#if defined(WIN64EXCEPTIONS)
    m_stats->m_unwindInfoSize = m_pUnwindDataSection->GetSize() + 
        m_pHotRuntimeFunctionSection->GetSize() + m_pRuntimeFunctionSection->GetSize() + m_pColdRuntimeFunctionSection->GetSize();
#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;
    }

    if (m_pAssemblyMetaData != NULL)
        m_stats->m_metadataSize = m_pAssemblyMetaData->GetSize();

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

    m_stats->m_hotCodeMgrSize = m_pHotCodeMethodDescsSection->GetSize();
    m_stats->m_unprofiledCodeMgrSize = m_pCodeMethodDescsSection->GetSize();
    m_stats->m_coldCodeMgrSize = m_pHotRuntimeFunctionLookupSection->GetSize();

    m_stats->m_eeInfoTableSize = m_pEEInfoTable->GetSize();
    m_stats->m_helperTableSize = m_pHelperTableSection->GetSize();	
    m_stats->m_dynamicInfoTableSize = m_pImportSectionsTable->GetSize();
    m_stats->m_dynamicInfoDelayListSize = m_pDelayLoadInfoDelayListSectionEager->GetSize() + m_pDelayLoadInfoDelayListSectionHot->GetSize() + m_pDelayLoadInfoDelayListSectionCold->GetSize();
    m_stats->m_importTableSize = m_pImportTable->GetSize();

    m_stats->m_debuggingTableSize = m_pDebugSection->GetSize();
    m_stats->m_headerSectionSize = m_pGCSection->GetSize();
    m_stats->m_codeSectionSize = m_pHotCodeSection->GetSize();
    m_stats->m_coldCodeSectionSize = m_pColdCodeSection->GetSize();
    m_stats->m_exceptionSectionSize = m_pExceptionSection->GetSize();
    m_stats->m_readOnlyDataSectionSize = m_pReadOnlyDataSection->GetSize();
    m_stats->m_relocSectionSize =  m_pBaseRelocsSection->GetSize();
    if (m_pILMetaData != NULL)
        m_stats->m_ILMetadataSize = m_pILMetaData->GetSize();
    m_stats->m_virtualImportThunkSize = m_pVirtualImportThunkSection->GetSize();
    m_stats->m_externalMethodThunkSize = m_pExternalMethodThunkSection->GetSize();
    m_stats->m_externalMethodDataSize = m_pExternalMethodDataSection->GetSize();

    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;

#ifndef BINDER // TritonTBD
    {
        // 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(_WIN64)
                // 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(_WIN64)
                // 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.
#ifndef FEATURE_CORECLR
        if (!m_ModuleDecoder.IsDll() ||     // exes always get loaded to their preferred base address
            !m_ModuleDecoder.IsILOnly())    // since the IL (IJW) image will be loaded first
#endif // !FEATURE_CORECLR
        {
            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(_WIN64)
    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
#endif // TritonTBD


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

    m_NativeBaseAddress = baseAddress;
}

#ifdef  MDIL
static WORD ReadWord(BYTE *p)
{
    return  p[0] +
            p[1]*256;
}

static DWORD ReadDWord(BYTE *p)
{
    return  p[0] + 
            p[1]*256 +
            p[2]*(256*256) +
            p[3]*(256*256*256);
}

#ifdef CLR_STANDALONE_BINDER
#include "mdil.h"
#else
#define CLR_STANDALONE_BINDER
#include "mdil.h"
#undef CLR_STANDALONE_BINDER
#endif

bool ReadMemory(BYTE *&dataPtr, COUNT_T &dataSize, void *dest, COUNT_T size)
{
    if (dataSize < size)
        return false;

    if (dest != NULL)
        memcpy(dest, dataPtr, size);

    dataPtr += size;
    dataSize -= size;

    return true;
}

void ZapImage::LoadMDILSection()
{
#ifdef BINDER
    _ASSERTE(!"intentionally unreachable");
#else
    IMAGE_SECTION_HEADER *pMDILSection = m_ModuleDecoder.FindSection(".mdil");
    m_cbMdilPESectionData = 0;
    if (pMDILSection)
    {
        // We got our section - get the start of the section
        BYTE* pStartOfMDILSection = static_cast<BYTE*>(m_ModuleDecoder.GetBase())+pMDILSection->VirtualAddress;
        BYTE* pEndOfMDILSection = pStartOfMDILSection + pMDILSection->Misc.VirtualSize;
        if (m_ModuleDecoder.PointerInPE(pEndOfMDILSection - 1))
        {
            m_pMdilPESectionData = pStartOfMDILSection;
            m_cbMdilPESectionData = pMDILSection->Misc.VirtualSize;
        }
    }
#endif
}

#endif // ifdef MDIL

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);

#ifdef FEATURE_FUSION
    // If TranslatePEToArchitectureType fails then we have an invalid format
    DWORD dwPEKind, dwMachine;
    m_ModuleDecoder.GetPEKindAndMachine(&dwPEKind, &dwMachine);

    PEKIND PeKind;
    IfFailThrow(TranslatePEToArchitectureType((CorPEKind)dwPEKind, dwMachine, &PeKind));
    
    // Valid images for this platform are peMSIL and the native image for the platform
    if (!(PeKind == peMSIL
#if defined(_TARGET_AMD64_)
          || PeKind == peAMD64
#elif defined(_TARGET_X86_)
          || PeKind == peI386
#elif defined(_TARGET_ARM_)
          || PeKind == peARM
#endif
        ))
    {
        ThrowHR(NGEN_E_EXE_MACHINE_TYPE_MISMATCH);
    }
#endif // FEATURE_FUSION

    //
    // 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();

#ifdef  MDIL
#ifndef BINDER
    LoadMDILSection();
#endif
#endif
    //
    // Get metadata of module to be compiled
    //
    m_pMDImport = m_zapper->m_pEECompileInfo->GetModuleMetaDataImport(m_hModule);
#ifndef BINDER
    _ASSERTE(m_pMDImport != NULL);
#endif // !BINDER

    //
    // 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();
}

#if !defined(FEATURE_CORECLR)

#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)

typedef struct _WIN32_MEMORY_RANGE_ENTRY {

    PVOID VirtualAddress;
    SIZE_T NumberOfBytes;

} WIN32_MEMORY_RANGE_ENTRY, *PWIN32_MEMORY_RANGE_ENTRY;

#endif

typedef BOOL  
(WINAPI *PfnPrefetchVirtualMemory)(  
    _In_ HANDLE hProcess,  
    _In_ ULONG_PTR NumberOfEntries,  
    _In_reads_(NumberOfEntries) PWIN32_MEMORY_RANGE_ENTRY VirtualAddresses,  
    _In_ ULONG Flags  
    );  
  

void PrefetchVM(void * pStartAddress, SIZE_T size)
{
    static PfnPrefetchVirtualMemory s_pfnPrefetchVirtualMemory = NULL;  

    if (s_pfnPrefetchVirtualMemory == NULL)
    {
        s_pfnPrefetchVirtualMemory = (PfnPrefetchVirtualMemory) GetProcAddress(WszGetModuleHandle(WINDOWS_KERNEL32_DLLNAME_W), "PrefetchVirtualMemory");  

        if (s_pfnPrefetchVirtualMemory == NULL)
        {
            s_pfnPrefetchVirtualMemory = (PfnPrefetchVirtualMemory) (1);
        }
    }

    if (s_pfnPrefetchVirtualMemory > (PfnPrefetchVirtualMemory) (1))
    {
        WIN32_MEMORY_RANGE_ENTRY range;

        range.VirtualAddress = pStartAddress;
        range.NumberOfBytes  = size;

        s_pfnPrefetchVirtualMemory(GetCurrentProcess(), 1, & range, 0);
    }
}

#endif



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

void ZapImage::Preload()
{
#if !defined(FEATURE_CORECLR)
    // Prefetch the whole IL image into memory to avoid small reads (usually 16kb blocks)
    PrefetchVM(m_ModuleDecoder.GetBase(), m_ModuleDecoder.GetSize());
#endif

    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;
    }

#ifdef CLR_STANDALONE_BINDER
    // TritonTBD:  A workaround to place a copy of metadata into hello.ni.exe.
    fMetadata = TRUE;
#endif

    if (fMetadata)
    {
#ifndef CLR_STANDALONE_BINDER
        // 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));
#endif

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

#ifdef CLR_STANDALONE_BINDER

        // now generate the NativeAssembyManifest
        // push down first the assembly references
        // we can do this only AFTER we have an instance of ZapMetadata (see a few lines above)
        // the order of assembly references is/needs to be in sync with those in CORCOMPILE_DEPENDENCIES
        
        for (COUNT_T cnt = 0; cnt < m_pNativeManifestData.GetCount(); cnt++) {
            m_pAssemblyMetaData->SetAssemblyReference(
                     m_pNativeManifestData[cnt].m_AssemblyName,
                     NULL,
                     m_pNativeManifestData[cnt].m_pNad);
        }

        // now provide the assembly/module def relevant data
        // please note that his assumes/knows that the last assemblyRef is "self-referential"
        m_pAssemblyMetaData->SetAssembly(m_pNativeManifestData[(COUNT_T)m_selfIndex].m_AssemblyName,
                                         NULL,
                                         m_pNativeManifestData[(COUNT_T)m_selfIndex].m_pNad);

#endif

        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 _WIN64
        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;
        }

        SetDllCharacteristics(dllCharacteristics);
    }

    if (IsReadyToRunCompilation())
    {
        SetIsDll(m_ModuleDecoder.IsDll());

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

#if defined(_TARGET_ARM_) && defined(FEATURE_CORECLR) && defined(FEATURE_CORESYSTEM) && !defined(BINDER)
    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.  MDIL binder will continue to use
        // 512 byte alignment, since there is no plan to compress data partitions.
        SetFileAlignment(0x1000);
    }
#elif defined(FEATURE_PAL)
    // PAL library requires native image sections to align to page bounaries.
    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);
}

void ZapImage::CompileProfileData()
{
    BeginRegion(CORINFO_REGION_HOT);

    CorProfileData* pProfileData = GetProfileData();
        
    if (m_profileDataSections[MethodProfilingData].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 < m_profileDataSections[MethodProfilingData].tableSize; i++)
        {
            unsigned methodProfilingDataFlags = m_profileDataSections[MethodProfilingData].pTable[i].flags;
            _ASSERTE(methodProfilingDataFlags != 0);

            mdToken token = m_profileDataSections[MethodProfilingData].pTable[i].token;

            if (TypeFromToken(token) == mdtMethodDef)
            {
                //
                // Compile a non-generic method
                // 
                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);

                        TryCompileInstantiatedMethod(pMethod, methodProfilingDataFlags);
                    }
                }
            }
        }
        // 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);
}

#ifdef  MDIL
static COUNT_T OutputDWord(BYTE *p, DWORD d)
{
    if (p)
    {
        p[0] = (BYTE)d;
        p[1] = (BYTE)(d>>8);
        p[2] = (BYTE)(d>>16);
        p[3] = (BYTE)(d>>24);
    }
    return 4;
}

void ZapImage::UnifyGenericInstances_MDIL(ZapInfo::MDILGenericMethodDesc *pMD)
{
    // we have unified on the last arg during generation - now we do the rest
    bool change;
    do
    {
        change = false;
        for (int argToUnify = 0; argToUnify < pMD->arity; argToUnify++)
        {
            for (ZapInfo::MDILGenericMethodDesc *p = pMD; p != NULL; p = p->next)
            {
                ZapInfo::MDILGenericMethodDesc *prev = p;
                for (ZapInfo::MDILGenericMethodDesc *q = p->next; q != NULL; q = q->next)
                {
                    // we have grouped identical bodies together in the list, so if the body is
                    // not the same, we can give up - no more identical bodies will be encountered
                    if (q->mdilCodeOffs != p->mdilCodeOffs || q->debugInfoOffs != p->debugInfoOffs)
                        break;

                    // if the flavors of p and q agree except for one position, we can merge q into p
                    if (ZapInfo::ArgFlavorsMatchExcept(q->flavorSet, p->flavorSet, pMD->arity, argToUnify))
                    {
//                        GetSvcLogger()->Printf(W("merged generic bodies %08x + %08x\n"), p->flavorSet[argToUnify], q->flavorSet[argToUnify]);
                        p->flavorSet[argToUnify] |= q->flavorSet[argToUnify];

                        // delete q from the list
                        _ASSERT(prev->next == q);
                        prev->next = q->next;
                        q = prev;
                        change = true;
                    }
                    else
                    {
                        prev = q;
                    }
                }
            }
        }
    }
    while (change);
}

COUNT_T ZapImage::EncodeGenericInstance_MDIL(ZapInfo::MDILGenericMethodDesc *pMD)
{
    // count how many instances we have
    COUNT_T count = 0;
    for (ZapInfo::MDILGenericMethodDesc *p = pMD; p != NULL; p = p->next)
    {
        count++;
    }

    // compute the size to allocate in m_genericInstPool
    size_t size = sizeof(ZapInfo::MDILInstHeader) + 2*count*sizeof(DWORD) + count*pMD->arity*sizeof(ZapInfo::FlavorSet);
    size = AlignUp(size, sizeof(DWORD));

    // as usual, we put some dummy stuff at the very beginning
    if (m_genericInstPool.GetCount() == 0)
    {
        m_genericInstPool.SetCount(sizeof(DWORD));
        OutputDWord(&m_genericInstPool[0], 'MDGI');
    }
    COUNT_T genericInstOffs = m_genericInstPool.GetCount();
    m_genericInstPool.SetCount(genericInstOffs + (COUNT_T)size);

    ZapInfo::MDILInstHeader *pMIH = (ZapInfo::MDILInstHeader *)&m_genericInstPool[genericInstOffs];
    pMIH->m_arity = pMD->arity;
    pMIH->m_flags = 0;
    pMIH->m_instCount = count;

    DWORD *mdilCodeOffsets = (DWORD *)(pMIH + 1);

    ZapInfo::FlavorSet *flavorSets = (ZapInfo::FlavorSet *)(mdilCodeOffsets + 2*count);
    
    for (ZapInfo::MDILGenericMethodDesc *p = pMD; p != NULL; p = p->next)
    {
        _ASSERTE(p->mdilCodeOffs  < m_codeBuffer     [GENERIC_CODE].GetCount());
        _ASSERTE(p->debugInfoOffs < m_debugInfoBuffer[GENERIC_CODE].GetCount());

        *mdilCodeOffsets++ = p->mdilCodeOffs;
        *mdilCodeOffsets++ = p->debugInfoOffs;
        for (int i = 0; i < pMD->arity; i++)
            *flavorSets++ = p->flavorSet[i];
    }
    return genericInstOffs;
}

int ZapImage::CheckForUnmerged(ZapInfo::MDILGenericMethodDesc tab[], int last, ZapInfo::FlavorSet flavorsToMatch, WCHAR *message)
{
    int arity = tab[last].arity;
    if (flavorsToMatch == 0)
    {
        for (int i = 0; i < last; i++)
        {
            if (ZapInfo::ArgFlavorsMatchExcept(tab[last].flavorSet, tab[i].flavorSet, arity, arity))
            {
                GetSvcLogger()->Printf(W("%s"), message);
                return 1;
            }
        }
    }
    else
    {
        for (int j = 0; j < arity; j++)
        {
            for (int i = 0; i < last; i++)
            {
                if (ZapInfo::ArgFlavorsMatchExcept(tab[last].flavorSet, tab[i].flavorSet, arity, j) &&
                    tab[last].flavorSet[j] != tab[i].flavorSet[j] && (tab[last].flavorSet[j] & flavorsToMatch) && (tab[i].flavorSet[j] & flavorsToMatch))
                {
                    GetSvcLogger()->Printf(W("%s"), message);
                    return 1;
                }
            }
        }
    }
    return 0;
}

void ZapImage::EncodeGenericInstances_MDIL()
{
    // make sure m_methodRidCount and m_mapMethodRidToOffs are big enough
    COUNT_T mappingCount = m_mapGenericMethodToDesc.GetCount();
    if (m_methodRidCount < mappingCount)
        m_methodRidCount = mappingCount;
    if (m_mapMethodRidToOffs.GetCount() < mappingCount)
    {
        COUNT_T oldCount = m_mapMethodRidToOffs.GetCount();
        m_mapMethodRidToOffs.SetCount(mappingCount);
        for (COUNT_T i = oldCount; i < mappingCount; i++)
            m_mapMethodRidToOffs[i] = 0;
    }

    COUNT_T methodCount = 0;
    COUNT_T instanceCount = 0;
    COUNT_T uniqueBodyCount = 0;
    COUNT_T uniqueBodySize = 0;
    COUNT_T unmergedInstances = 0;
    COUNT_T unmergedFloatDoubleInstances = 0;
    COUNT_T unmergedSmallIntInstances = 0;
    COUNT_T unmergedIntUIntInstances = 0;
    COUNT_T unmergedIntInstances = 0;
    COUNT_T unmergedLongULongInstances = 0;
    COUNT_T unmergedFloatStructInstances = 0;
    COUNT_T unmergedLongStructInstances = 0;
    COUNT_T unmergedLongFloatInstances = 0;
    COUNT_T unmergedNullableInstances = 0;
    COUNT_T unmergedSharedStructInstances = 0;
    COUNT_T unmergedStructInstances = 0;

    for (COUNT_T i = 0; i < m_mapGenericMethodToDesc.GetCount(); i++)
    {
        ZapInfo::MDILGenericMethodDesc *pMD = m_mapGenericMethodToDesc[i];
        if (pMD == NULL)
            continue;

        methodCount++;

        UnifyGenericInstances_MDIL(pMD);

#if 0 // def _DEBUG
        DWORD prevMdilCodeOffs = 0;
        COUNT_T uniqueBodyCountForThisMethod = 0;
        COUNT_T uniqueBodySizeForThisMethod = 0;
        COUNT_T instanceCountForThisMethod = 0;
        for (ZapInfo::MDILGenericMethodDesc *p = pMD; p != NULL; p = p->next)
        {
            instanceCountForThisMethod++;
            if (prevMdilCodeOffs != p->mdilCodeOffs)
            {
                uniqueBodyCountForThisMethod++;
                uniqueBodySizeForThisMethod += p->mdilCodeSize;
                prevMdilCodeOffs = p->mdilCodeOffs;
            }
        }
        GetSvcLogger()->Printf(W("%u Instances for generic method %08x - %u unique bodies totalling %u bytes\n"),
                instanceCountForThisMethod,      TokenFromRid(i, mdtMethodDef),
                                                        uniqueBodyCountForThisMethod,
                                                                                  uniqueBodySizeForThisMethod);

        instanceCount += instanceCountForThisMethod;
        uniqueBodyCount += uniqueBodyCountForThisMethod;
        uniqueBodySize += uniqueBodySizeForThisMethod;
        const size_t MD_TABLE_SIZE = 256;
        ZapInfo::MDILGenericMethodDesc mdTab[MD_TABLE_SIZE];
        COUNT_T mdCount = 0;
        for (ZapInfo::MDILGenericMethodDesc *p = pMD; p != NULL; p = p->next)
        {
            if (mdCount < MD_TABLE_SIZE)
            {
                mdTab[mdCount] = *p;
                mdCount++;
            }
        }
        qsort(mdTab, mdCount, sizeof(mdTab[0]), ZapInfo::CmpMDILGenericMethodDesc);

        for (COUNT_T mdInx = 0; mdInx < mdCount; mdInx++)
        {
            if (mdInx >= 1 && !ZapInfo::ArgFlavorsMatchExcept(mdTab[mdInx-1].flavorSet, mdTab[mdInx].flavorSet, mdTab[mdInx].arity, mdTab[mdInx].arity-1))
                GetSvcLogger()->Printf(W("\n"));

            GetSvcLogger()->Printf(W("  %08x(%4u): "), mdTab[mdInx].mdilCodeOffs, mdTab[mdInx].mdilCodeSize);
            for (int j = 0; j < mdTab[mdInx].arity; j++)
            {
                GetSvcLogger()->Printf(W(" %08x"), mdTab[mdInx].flavorSet[j]);
            }
            unmergedInstances += CheckForUnmerged(mdTab, mdInx, 0, W(" - unmerged instance"));

            const ZapInfo::FlavorSet FLOAT_DOUBLE = (1 << ELEMENT_TYPE_R4)|(1 << ELEMENT_TYPE_R8);
            unmergedFloatDoubleInstances += CheckForUnmerged(mdTab, mdInx, FLOAT_DOUBLE, W(" - unmerged float/double instance"));

            const ZapInfo::FlavorSet SMALL_INT = (1 << ELEMENT_TYPE_BOOLEAN)|(1 << ELEMENT_TYPE_CHAR)|(1 << ELEMENT_TYPE_I1)|(1 << ELEMENT_TYPE_U1)|(1 << ELEMENT_TYPE_I2)|(1 << ELEMENT_TYPE_U2);
            unmergedSmallIntInstances += CheckForUnmerged(mdTab, mdInx, SMALL_INT, W(" - unmerged small int instance"));

            const ZapInfo::FlavorSet REGULAR_INT = (1 << ELEMENT_TYPE_I4)|(1 << ELEMENT_TYPE_U4)|(1 << ELEMENT_TYPE_I)|(1 << ELEMENT_TYPE_U);
            unmergedIntUIntInstances += CheckForUnmerged(mdTab, mdInx, REGULAR_INT, W(" - unmerged int/uint instance"));

            const ZapInfo::FlavorSet REGISTER_INT = SMALL_INT|REGULAR_INT;
            unmergedIntInstances += CheckForUnmerged(mdTab, mdInx, REGISTER_INT, W(" - unmerged int instance"));

            const ZapInfo::FlavorSet LONG_INT = (1 << ELEMENT_TYPE_I8)|(1 << ELEMENT_TYPE_U8);
            unmergedLongULongInstances += CheckForUnmerged(mdTab, mdInx, LONG_INT, W(" - unmerged long/ulong instance"));

            const ZapInfo::FlavorSet LONG_STRUCT = LONG_INT|(1 << ELEMENT_TYPE_VALUETYPE);
            unmergedLongStructInstances += CheckForUnmerged(mdTab, mdInx, LONG_STRUCT, W(" - unmerged long/struct instance"));

            const ZapInfo::FlavorSet LONG_FLOAT = LONG_INT|FLOAT_DOUBLE;
            unmergedLongFloatInstances += CheckForUnmerged(mdTab, mdInx, LONG_FLOAT, W(" - unmerged long/float instance"));

            const ZapInfo::FlavorSet FLOAT_STRUCT = FLOAT_DOUBLE|(1 << ELEMENT_TYPE_VALUETYPE);
            unmergedFloatStructInstances += CheckForUnmerged(mdTab, mdInx, FLOAT_STRUCT, W(" - unmerged float/struct instance"));

            const ZapInfo::FlavorSet NULLABLE_STRUCT = (1 << ELEMENT_TYPE_VALUETYPE)|(1 << 0x17);
            unmergedNullableInstances += CheckForUnmerged(mdTab, mdInx, NULLABLE_STRUCT, W(" - unmerged nullable instance"));

            const ZapInfo::FlavorSet SHARED_STRUCT = (1 << ELEMENT_TYPE_VALUETYPE)|(1 << 0x1e);
            unmergedSharedStructInstances += CheckForUnmerged(mdTab, mdInx, SHARED_STRUCT, W(" - unmerged shared struct instance"));

            const ZapInfo::FlavorSet STRUCT = (1 << ELEMENT_TYPE_VALUETYPE)|(1 << 0x17)|(1 << 0x1e)|(1 << 0x1f);
            unmergedStructInstances += CheckForUnmerged(mdTab, mdInx, STRUCT, W(" - unmerged struct instance"));

            GetSvcLogger()->Printf(W("\n"));
        }
#endif
        COUNT_T genericInstOffs = EncodeGenericInstance_MDIL(pMD);

        _ASSERT(m_mapMethodRidToOffs[i] == 0);
        m_mapMethodRidToOffs[i] = GENERIC_METHOD_REF | genericInstOffs;
    }

#if 0 //def _DEBUG
    for (COUNT_T i = 0; i < m_mapGenericMethodToDesc.GetCount(); i++)
    {
        ZapInfo::MDILGenericMethodDesc *pMD = m_mapGenericMethodToDesc[i];
        if (pMD == NULL)
            continue;

        // 0 the mdilCodeOffs and unify - the result tells us what we have covered...
        for (ZapInfo::MDILGenericMethodDesc *p = pMD; p != NULL; p = p->next)
            p->mdilCodeOffs = 0;

        UnifyGenericInstances_MDIL(pMD);

        GetSvcLogger()->Printf(W("Instances for generic method %08x\n"), TokenFromRid(i, mdtMethodDef));

        const size_t MD_TABLE_SIZE = 256;
        ZapInfo::MDILGenericMethodDesc mdTab[MD_TABLE_SIZE];
        COUNT_T mdCount = 0;
        for (ZapInfo::MDILGenericMethodDesc *p = pMD; p != NULL; p = p->next)
        {
            if (mdCount < MD_TABLE_SIZE)
            {
                mdTab[mdCount] = *p;
                mdCount++;
            }
        }
        qsort(mdTab, mdCount, sizeof(mdTab[0]), ZapInfo::CmpMDILGenericMethodDesc);

        for (COUNT_T mdInx = 0; mdInx < mdCount; mdInx++)
        {
            if (mdInx >= 1 && !ZapInfo::ArgFlavorsMatchExcept(mdTab[mdInx-1].flavorSet, mdTab[mdInx].flavorSet, mdTab[mdInx].arity, mdTab[mdInx].arity-1))
                GetSvcLogger()->Printf(W("\n"));

            for (int j = 0; j < mdTab[mdInx].arity; j++)
            {
                GetSvcLogger()->Printf(W(" %08x"), mdTab[mdInx].flavorSet[j]);
            }

            GetSvcLogger()->Printf(W("\n"));
        }
    }

    GetSvcLogger()->Printf(W("%u instances and %u unique bodies for %u generic methods\n"), instanceCount, uniqueBodyCount, methodCount);
    GetSvcLogger()->Printf(W("%u unmerged instances\n"), unmergedInstances);
    GetSvcLogger()->Printf(W("%u unmerged float/double instances\n"), unmergedFloatDoubleInstances);
    GetSvcLogger()->Printf(W("%u unmerged small int instances\n"), unmergedSmallIntInstances);
    GetSvcLogger()->Printf(W("%u unmerged int/uint instances\n"), unmergedIntUIntInstances);
    GetSvcLogger()->Printf(W("%u unmerged int instances\n"), unmergedIntInstances);
    GetSvcLogger()->Printf(W("%u unmerged long/ulong instances\n"), unmergedLongULongInstances);
    GetSvcLogger()->Printf(W("%u unmerged long/struct instances\n"), unmergedLongStructInstances);
    GetSvcLogger()->Printf(W("%u unmerged long/float instances\n"), unmergedLongFloatInstances);
    GetSvcLogger()->Printf(W("%u unmerged float/struct instances\n"), unmergedFloatStructInstances);
    GetSvcLogger()->Printf(W("%u unmerged nullable instances\n"), unmergedNullableInstances);
    GetSvcLogger()->Printf(W("%u unmerged shared struct instances\n"), unmergedSharedStructInstances);
    GetSvcLogger()->Printf(W("%u unmerged struct instances\n"), unmergedStructInstances);

    GetSvcLogger()->Printf(W("%u unique generic body size\n"), uniqueBodySize);

    GetSvcLogger()->Printf(W("%u unmerged generic methods\n"), m_unmergedGenericCount);
    GetSvcLogger()->Printf(W("%u   merged generic methods\n"), m_mergedGenericCount);
    GetSvcLogger()->Printf(W("%u unmerged generic code size\n"), m_unmergedGenericSize);
    GetSvcLogger()->Printf(W("%u   merged generic code size\n"), m_mergedGenericSize);
#endif
}



//----------------------------------------------------------------------------------
// Copies the specified number of bytes from fpIn to fpOut.
//----------------------------------------------------------------------------------
static bool fcopy(FILE *fpIn, FILE *fpOut, size_t cbBytes)
{
    size_t cbNumBytesLeft = cbBytes;

    while (cbNumBytesLeft)
    {
        byte buffer[PAGE_SIZE];
        size_t cbNumBytesForThisPass = min(cbNumBytesLeft, sizeof(buffer));
        if (1 != fread(buffer, cbNumBytesForThisPass, 1, fpIn))
            return false;
        if (1 != fwrite(buffer, cbNumBytesForThisPass, 1, fpOut))
            return false;
        cbNumBytesLeft -= cbNumBytesForThisPass;
    }
    return true;
}


//----------------------------------------------------------------------------------
// Writes the specified number of bytes at a specific position in the output file.
//----------------------------------------------------------------------------------
static bool fwriteat(FILE *fpOut, ULONG position, const void *pBytes, size_t cbBytes)
{
    if (0 != fseek(fpOut, position, SEEK_SET))
        return false;
    if (1 != fwrite(pBytes, cbBytes, 1, fpOut))
        return false;
    return true;
}

//----------------------------------------------------------------------------------
// Writes out zeroes to "fp" until the file position is a multiple of "align".
//----------------------------------------------------------------------------------
static bool fzerofilluntilaligned(LONG align, FILE *fp)
{
    LONG pos = ftell(fp);
    LONG endpoint = (LONG)ALIGN_UP(pos, align);
    for (LONG i = pos; i < endpoint; i++)
    {
        BYTE zero = 0;
        if (1 != fwrite(&zero, 1, 1, fp))
            return false;
    }
    return true;
}


//----------------------------------------------------------------------------------
// When we insert the .MDIL section, we insert bytes into two portions of the IL image.
//
// - Insertion point #1 starts at the end of the original section table (we need a new
//   entry for the .MDIL section.) In practice, this always pushes the section table
//   into a new FileAlignment page and thus requires bumping everything below
//   by other (FileAlignment - sizeof(IMAGE_SECTION_HEADER)) bytes to preserve alignment.
//
//   For simplicity, we do this whether or not the section table actually spilled over.
//
//
// - Insertion point #2 starts after the last original section contents. We insert
//   the contents of the .MDIL section here.
//
// The bytes in between the insertion points are blitted to the output file
// (except for a few needed fixups.)
//
// It was also attempted to reduce the number of insertion points to 1 by
// inserting the .MDIL contents before the other sections. But PEDecoder boots
// any PE whose section table isn't sorted by both RawData and RVA addresses so
// this pulled the cord on that idea.
//----------------------------------------------------------------------------------
enum FIXUPREGIONID
{
    FIXUPREGIONID_SECTIONCONTENTS = 0,  // region from end of original section table to end of final original section contents.
    FIXUPREGIONID_CERTIFICATES    = 1,  // region from end of section contents to end of file (WIN_CERTIFICATE stuff goes here.)
    FIXUPREGIONID_COUNT           = 2,

};


//----------------------------------------------------------------------------------
// We create an array of these, sorted by m_start. The array is terminated by
// an entry whose m_start is the size of the input file.
//----------------------------------------------------------------------------------
struct FixupRegion
{
    ULONG m_start;    // Position of first byte of region (in the input file)
    ULONG m_delta;    // Amount to add to make it correct for the output file.
};

static DWORD FixupPosition(const FixupRegion *pFixupRegions, ULONG inputPosition, ULONG *pOutputPosition)
{
    ULONG delta = 0;
    while (inputPosition >= pFixupRegions->m_start)
    {
        delta = pFixupRegions->m_delta;
        if (delta == ((ULONG)(-1)))
            return ERROR_BAD_FORMAT;  // A FilePointer read from the input file is out of range.

        pFixupRegions++;
    }
    *pOutputPosition = inputPosition + delta;
    return ERROR_SUCCESS;
}


//----------------------------------------------------------------------------------
// Creates a copy of the input IL file with a new ".mdil" section attached.
//----------------------------------------------------------------------------------
static DWORD EmbedMdilIntoILFile(FILE *inputFile, FILE *outputFile, LPCWSTR inputFileName, ZapImage *pZapImage)
{
#ifdef BINDER
    _ASSERTE(!"intentionally unreachable");
    return E_NOTIMPL;
#else

    _ASSERTE(0 == ftell(inputFile));
    _ASSERTE(0 == ftell(outputFile));


    static const BYTE aMDILSectionName[IMAGE_SIZEOF_SHORT_NAME] = {'.','m','d','i','l',0,0,0};

    NewHolder<IMAGE_SECTION_HEADER> oldImageSectionHeaders;

    //-----------------------------------------------------------------------------------------
    // Read the PE headers.
    //-----------------------------------------------------------------------------------------
    IMAGE_DOS_HEADER dosHeader;
    if (fread(&dosHeader, sizeof(dosHeader), 1, inputFile) != 1) goto ioerror;
    if (dosHeader.e_magic != IMAGE_DOS_SIGNATURE)
    {
        pZapImage->GetZapper()->Error(W("Error: \"%ws\": Expected 'MZ' at offset 0.\n"), inputFileName);
        goto error;  // No 'MZ'
    }

    size_t cbPEOffset = dosHeader.e_lfanew;
    if (0 != fseek(inputFile, cbPEOffset, SEEK_SET)) goto ioerror;
    DWORD peSignature;
    if (1 != fread(&peSignature, sizeof(peSignature), 1, inputFile)) goto ioerror;
    if (peSignature != IMAGE_NT_SIGNATURE) 
    {
        pZapImage->GetZapper()->Error(W("Error: \"%ws\": Expected 'PE\\0\\0' at offset 0x%x.\n"), inputFileName, ftell(inputFile) - sizeof(peSignature));
        goto error; // No 'PE\0\0'
    }

    ULONG positionOfImageFileHeader = ftell(inputFile);
    IMAGE_FILE_HEADER imageFileHeader;
    if (1 != fread(&imageFileHeader, sizeof(imageFileHeader), 1, inputFile)) goto ioerror;
    const int numberOfSections = imageFileHeader.NumberOfSections;

    if (numberOfSections <= 0 || numberOfSections > 2048)  // crude buffer overflow guard
    {
        pZapImage->GetZapper()->Error(W("Error: \"%ws\": Suspicious value for IMAGE_FILE_HEADER.NumberOfSections: %d.\n"), inputFileName, numberOfSections);
        goto error; // No 'PE\0\0'
    }

    ULONG positionOfImageOptionalHeader = ftell(inputFile);
    IMAGE_OPTIONAL_HEADER32 imageOptionalHeader;
    if (1 != fread(&imageOptionalHeader, sizeof(imageOptionalHeader), 1, inputFile)) goto error;
    if (imageOptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) //0x10b
    {
        // No 0x10b magic. Thus, not a 32-bit header. (If you saw 0x20b here, this is a PE with a 64-bit header.)
        if (imageOptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
        {
            pZapImage->GetZapper()->Error(W("Error: \"%ws\": This is a 64-bit image.\n"), inputFileName);
        }
        else
        {
            pZapImage->GetZapper()->Error(W("Error: \"%ws\": Unexpected IMAGE_OPTIONAL_HEADER.Magic value: 0x%x.\n"),
                                          inputFileName,
                                          (unsigned int)(imageOptionalHeader.Magic));        }

        goto error;
    }

    if (imageOptionalHeader.NumberOfRvaAndSizes != IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
    {
        // Expected 16 IMAGE_DATA_DIRECTORY entries (an assumption hard-coded into the struct definition of IMAGE_OPTIONAL_HEADER32)
        pZapImage->GetZapper()->Error(W("Error: \"%ws\": Unexpected IMAGE_OPTIONAL_HEADER.NumberOfRvaAndSizes value: 0x%x.\n"),
                                      inputFileName,
                                      (unsigned int)(imageOptionalHeader.NumberOfRvaAndSizes));
        goto error;   
    }

    
    //-----------------------------------------------------------------------------------------
    // Read the IMAGE_SECTION_HEADER array.
    //-----------------------------------------------------------------------------------------
    if (NULL == (oldImageSectionHeaders = new (nothrow) IMAGE_SECTION_HEADER[numberOfSections])) goto oomerror;
    size_t rvaForNewSection = 0;
    int sectionIndexOfPreexistingMidlSection = -1;
    ULONG endOfLastOriginalPhysicalSector = 0;
    ULONG positionOfOriginalSectionTable = ftell(inputFile);
    for (int sidx = 0; sidx < numberOfSections; sidx++)
    {
        ULONG positionOfSectionHeader = ftell(inputFile);
        if (1 != fread(&oldImageSectionHeaders[sidx], sizeof(IMAGE_SECTION_HEADER), 1, inputFile)) goto ioerror;
        if (0 == memcmp(aMDILSectionName, oldImageSectionHeaders[sidx].Name, IMAGE_SIZEOF_SHORT_NAME))
        {
            // If we are asked to generate MDIL, but the current file already has MDIL section,
            // we change the section name, and then put in new MDIL section.  The old MDIL section will not
            // be put into final ni image.
            // This is support phone build which puts IL with MDIL on device.
            sectionIndexOfPreexistingMidlSection = sidx;
        }

        // Pointer and Size of RawData must be aligned.
        if (0 != oldImageSectionHeaders[sidx].PointerToRawData % imageOptionalHeader.FileAlignment)
        {
            pZapImage->GetZapper()->Error(W("Error: \"%ws\": Section #%d: PointerToRawData not aligned with IMAGE_OPTIONAL_HEADER.FileAlignment.\n"), inputFileName, (sidx + 1));
            goto error;
        }
        if (0 != oldImageSectionHeaders[sidx].SizeOfRawData % imageOptionalHeader.FileAlignment)
        {
            pZapImage->GetZapper()->Error(W("Error: \"%ws\": Section #%d: SizeOfRawData not aligned with IMAGE_OPTIONAL_HEADER.FileAlignment.\n"), inputFileName, (sidx + 1));
            goto error;
        }

        endOfLastOriginalPhysicalSector = max(endOfLastOriginalPhysicalSector, oldImageSectionHeaders[sidx].PointerToRawData + oldImageSectionHeaders[sidx].SizeOfRawData);

        size_t spaceNeededForThisSection = ALIGN_UP(oldImageSectionHeaders[sidx].Misc.VirtualSize, imageOptionalHeader.SectionAlignment);
        size_t nextFreeRva = oldImageSectionHeaders[sidx].VirtualAddress + spaceNeededForThisSection;
        if (nextFreeRva > rvaForNewSection)
            rvaForNewSection = nextFreeRva;
    }
    ULONG positionOfFirstByteAfterOriginalSectionTable = ftell(inputFile);

    //-----------------------------------------------------------------------------------------
    // Block copy everything to the end of the original section table.
    //-----------------------------------------------------------------------------------------
    if (0 != fseek(inputFile, 0, SEEK_SET)) goto ioerror;
    if (!fcopy(inputFile, outputFile, positionOfFirstByteAfterOriginalSectionTable)) goto ioerror;

    //-----------------------------------------------------------------------------------------
    // Write out the new .mdil section header. (It is not quite filled out yet so this
    // is simply the easiest way to advance the file pointer.)
    //-----------------------------------------------------------------------------------------
    IMAGE_SECTION_HEADER mdilSectionHeader;
    memset(&mdilSectionHeader, 0, sizeof(mdilSectionHeader));
    memcpy(mdilSectionHeader.Name, aMDILSectionName, IMAGE_SIZEOF_SHORT_NAME);
    mdilSectionHeader.VirtualAddress = rvaForNewSection;
    mdilSectionHeader.SizeOfRawData = 0xcccccccc; // Will need fixup later
    mdilSectionHeader.PointerToRawData = 0xcccccccc; // Will need fixup later
    mdilSectionHeader.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;

    ULONG outputPositionOfMdilSectionHeader = ftell(outputFile);
    if (1 != fwrite(&mdilSectionHeader, sizeof(mdilSectionHeader), 1, outputFile)) goto ioerror;

    //-----------------------------------------------------------------------------------------
    // Adding the extra section header can (and usually does) cause the section table to spill
    // over into a new FileAlignment page. In such a case, we have to bump all the section contents
    // by FileAlignment bytes.
    //
    // For simplicity (and since C# always ends up on this case anyway), always bump even if not
    // necessary.
    //-----------------------------------------------------------------------------------------
    for (ULONG i = 0; i < imageOptionalHeader.FileAlignment - sizeof(IMAGE_SECTION_HEADER); i++)
    {
        BYTE zero = 0;
        if (1 != fwrite(&zero, sizeof(zero), 1, outputFile)) goto ioerror;
    }

    //-----------------------------------------------------------------------------------------
    // Block copy everything from the end of the original section table to the end of the section contents.
    //-----------------------------------------------------------------------------------------
    ULONG sizeOfOriginalSectionContents = endOfLastOriginalPhysicalSector - positionOfFirstByteAfterOriginalSectionTable;
    if (0 != fseek(inputFile, positionOfFirstByteAfterOriginalSectionTable, SEEK_SET)) goto error;
    if (!fcopy(inputFile, outputFile, sizeOfOriginalSectionContents)) goto ioerror;

    
    //-----------------------------------------------------------------------------------------
    // Write out the actual MDIL
    //-----------------------------------------------------------------------------------------
    mdilSectionHeader.PointerToRawData = ftell(outputFile);
    // Our previous alignment checks on the section's PointerToRawData and SizeOfRawData should guarantee this assert
    _ASSERTE(0 == (mdilSectionHeader.PointerToRawData % imageOptionalHeader.FileAlignment));  
    DWORD errorCode = pZapImage->Write_MDIL(outputFile);
    if (errorCode != ERROR_SUCCESS)
        return errorCode;

    //-----------------------------------------------------------------------------------------
    // Add pad bytes after the MDIL to satisfy the section alignment requirement.
    //-----------------------------------------------------------------------------------------
    mdilSectionHeader.Misc.VirtualSize = ftell(outputFile) - mdilSectionHeader.PointerToRawData;
    mdilSectionHeader.SizeOfRawData = (DWORD)ALIGN_UP(mdilSectionHeader.Misc.VirtualSize, imageOptionalHeader.FileAlignment);
    if (!fzerofilluntilaligned(imageOptionalHeader.FileAlignment, outputFile)) goto ioerror;

    //-----------------------------------------------------------------------------------------
    // Copy out any stuff after the section contents (e.g. WIN_CERTIFICATE)
    //-----------------------------------------------------------------------------------------
    if (0 != fseek(inputFile, 0, SEEK_END)) goto ioerror;
    ULONG inputFileSize = ftell(inputFile);
    ULONG sizeOfStuffAfterSectionContents = inputFileSize - endOfLastOriginalPhysicalSector;
    if (0 != fseek(inputFile, endOfLastOriginalPhysicalSector, SEEK_SET)) goto ioerror;
    if (!fcopy(inputFile, outputFile, sizeOfStuffAfterSectionContents)) goto ioerror;
    ULONG outputFileSize = ftell(outputFile);


    //=========================================================================================
    // End of pass 1. Now do fixups.
    //=========================================================================================

    //-----------------------------------------------------------------------------------------
    // Record the various regions and their fixup data for easy lookup.
    //-----------------------------------------------------------------------------------------
    FixupRegion aFixupRegions[FIXUPREGIONID_COUNT + 1];
    memset(&aFixupRegions, 0xcc, sizeof(aFixupRegions));

    aFixupRegions[FIXUPREGIONID_SECTIONCONTENTS].m_start = positionOfFirstByteAfterOriginalSectionTable;
    aFixupRegions[FIXUPREGIONID_SECTIONCONTENTS].m_delta = imageOptionalHeader.FileAlignment; 


    aFixupRegions[FIXUPREGIONID_CERTIFICATES].m_start = endOfLastOriginalPhysicalSector;
    aFixupRegions[FIXUPREGIONID_CERTIFICATES].m_delta = outputFileSize - inputFileSize; 

    aFixupRegions[FIXUPREGIONID_COUNT].m_start = inputFileSize;
    aFixupRegions[FIXUPREGIONID_COUNT].m_delta = (ULONG)(-1);


    //-----------------------------------------------------------------------------------------
    // IMAGE_FILE_HEADER.NumberOfSections is one bigger. Duh.
    //-----------------------------------------------------------------------------------------
    WORD newNumberOfSections = imageFileHeader.NumberOfSections + 1;
    if (!fwriteat(outputFile,
                  positionOfImageFileHeader + offsetof(IMAGE_FILE_HEADER, NumberOfSections),
                  &newNumberOfSections,
                  sizeof(newNumberOfSections)))
        goto ioerror;

    //-----------------------------------------------------------------------------------------
    // We added a new .MDIL section so add its size to IMAGE_OPTIONAL_HEADER.SizeOfInitializedData.
    //-----------------------------------------------------------------------------------------
    DWORD newSizeOfInitializedData = imageOptionalHeader.SizeOfInitializedData + mdilSectionHeader.SizeOfRawData;
    if (!fwriteat(outputFile,
                  positionOfImageOptionalHeader + offsetof(IMAGE_OPTIONAL_HEADER, SizeOfInitializedData),
                  &newSizeOfInitializedData,
                  sizeof(newSizeOfInitializedData)))
        goto ioerror;

    if (0 != (imageOptionalHeader.SizeOfImage % imageOptionalHeader.SectionAlignment))
    {
        pZapImage->GetZapper()->Error(W("Error: \"%ws\": IMAGE_OPTIONAL_HEADER.SizeOfImage not aligned with IMAGE_OPTIONAL_HEADER.SectionAlignment.\n"), inputFileName);
        goto error;   // Incoming PE format violation: SizeOfImage not a multple of SectionAlignment
    }

    //-----------------------------------------------------------------------------------------
    // We added a new .MDIL section so add its in-memory size requirements to IMAGE_OPTIONAL_HEADER.SizeOfImage.
    //-----------------------------------------------------------------------------------------
    DWORD newSizeOfImage = imageOptionalHeader.SizeOfImage + (DWORD)ALIGN_UP(mdilSectionHeader.Misc.VirtualSize, imageOptionalHeader.SectionAlignment);
    if (!fwriteat(outputFile,
                  positionOfImageOptionalHeader + offsetof(IMAGE_OPTIONAL_HEADER, SizeOfImage),
                  &newSizeOfImage,
                  sizeof(newSizeOfImage)))
        goto ioerror;

    //-----------------------------------------------------------------------------------------
    // We added a new IMAGE_SECTION_HEADER so recompute IMAGE_OPTIONAL_HEADER.SizeOfHeaders
    //-----------------------------------------------------------------------------------------
    ULONG newSizeOfHeaders = (ULONG)(ALIGN_UP(outputPositionOfMdilSectionHeader + sizeof(IMAGE_SECTION_HEADER), imageOptionalHeader.FileAlignment));

    if (newSizeOfHeaders > oldImageSectionHeaders[0].VirtualAddress)
    {
        // A corner case that can only come up if the input file has a ridiculously low SectionAlignment (512 bytes) or
        // a ridiculous number of sections (50).
        pZapImage->GetZapper()->Error(
            W("Tool limitation: \"%ws\": Could not embed MDIL into image as there is not enough room to grow the section header table without ")
            W("modifying the section RVAs. Modifying section RVAs is not supported by this tool. It may be possible to avoid this ")
            W("by rebuilding the input image with a smaller FileAlignment or a larger SectionAlignment. We are sorry for the inconvenience.\n"),
            inputFileName);
        goto error;
    }

    if (!fwriteat(outputFile,
                  positionOfImageOptionalHeader + offsetof(IMAGE_OPTIONAL_HEADER, SizeOfHeaders),
                  &newSizeOfHeaders,
                  sizeof(newSizeOfHeaders)))
        goto ioerror;

    //-----------------------------------------------------------------------------------------
    // We bumped the section contents by FileAlignment so add that to the original section headers PointerToRawData values.
    //-----------------------------------------------------------------------------------------
    for (int sidx = 0; sidx < imageFileHeader.NumberOfSections; sidx++)
    {
        DWORD newPointerToRawData = oldImageSectionHeaders[sidx].PointerToRawData + aFixupRegions[FIXUPREGIONID_SECTIONCONTENTS].m_delta;
        if (!fwriteat(outputFile,
                      positionOfOriginalSectionTable + sidx * sizeof(IMAGE_SECTION_HEADER) + offsetof(IMAGE_SECTION_HEADER, PointerToRawData),
                      &newPointerToRawData,
                      sizeof(newPointerToRawData)))

            goto ioerror;
    }


    //-----------------------------------------------------------------------------------------
    // We've now fully filled in the .MDIL section header. Rewrite it.
    //-----------------------------------------------------------------------------------------
    if (!fwriteat(outputFile,
                  outputPositionOfMdilSectionHeader,
                  &mdilSectionHeader,
                  sizeof(mdilSectionHeader)))
        goto ioerror;

    //-----------------------------------------------------------------------------------------
    // Some joker gave us an input with a .MDIL section already in it. Rename it
    // and the binder will drop it over the side.
    //-----------------------------------------------------------------------------------------
    if (sectionIndexOfPreexistingMidlSection != -1)
    {
        BYTE nameMangler = '0' + sectionIndexOfPreexistingMidlSection;
        if (!fwriteat(outputFile,
                      positionOfOriginalSectionTable +
                      sectionIndexOfPreexistingMidlSection * sizeof(IMAGE_SECTION_HEADER)
                      + offsetof(IMAGE_SECTION_HEADER, Name)
                      + 4,
                      &nameMangler,
                      sizeof(nameMangler)))
            goto ioerror;
    }


    //-----------------------------------------------------------------------------------------
    // IMAGE_FILE_HEADER.PointerToSymbolTable is always supposed to be 0 for managed PE's.
    // If you remove this restriction, you'll need to add fixup code.
    //-----------------------------------------------------------------------------------------
    if (imageFileHeader.PointerToSymbolTable != 0)
    {
        pZapImage->GetZapper()->Error(W("Error: \"%ws\": IMAGE_FILE_HEADER.PointerToSymbolTable expected to be 0.\n"), inputFileName);
        goto error;
    }

    //-----------------------------------------------------------------------------------------
    // IMAGE_DEBUG_DIRECTORY if present has an absolute file pointer to RSDS structure. Fix it up.
    //-----------------------------------------------------------------------------------------
    ULONG rvaOfOldImageDebugDirectory = imageOptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
    if (rvaOfOldImageDebugDirectory != 0)
    {
        if (0 != (imageOptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size % sizeof(IMAGE_DEBUG_DIRECTORY)))
        {
            // Yes, we have real MP apps that trigger this...
            pZapImage->GetZapper()->Warning(W("Warning: \"%ws\": DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size expected to be a multiple of %d.\n"), inputFileName, sizeof(IMAGE_DEBUG_DIRECTORY));
        }
        else
        {
            int sidx;
            for (sidx = 0; sidx < numberOfSections; sidx++)
            {
                if (rvaOfOldImageDebugDirectory >= oldImageSectionHeaders[sidx].VirtualAddress &&
                    rvaOfOldImageDebugDirectory < oldImageSectionHeaders[sidx].VirtualAddress + oldImageSectionHeaders[sidx].Misc.VirtualSize)
                {
                    ULONG positionOfOldImageDebugDirectory =
                                oldImageSectionHeaders[sidx].PointerToRawData +
                                rvaOfOldImageDebugDirectory -
                                oldImageSectionHeaders[sidx].VirtualAddress;
    
                    ULONG positionOfNewImageDebugDirectory;
                    DWORD errorResult = FixupPosition(aFixupRegions, positionOfOldImageDebugDirectory, &positionOfNewImageDebugDirectory);
                    if (errorResult != ERROR_SUCCESS)
                        goto error;
    
                    DWORD numImageDebugDirectories = imageOptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size / sizeof(IMAGE_DEBUG_DIRECTORY); 
                    for (DWORD i = 0; i < numImageDebugDirectories; i++)
                    {
                        if (0 != fseek(inputFile, positionOfOldImageDebugDirectory, SEEK_SET)) goto ioerror;
                        IMAGE_DEBUG_DIRECTORY imageDebugDirectory;
                        if (1 != fread(&imageDebugDirectory, sizeof(imageDebugDirectory), 1, inputFile)) goto ioerror;
        
                        ULONG positionOfNewDebugRawData = 0xcccccccc;
                        errorResult = FixupPosition(aFixupRegions, imageDebugDirectory.PointerToRawData, &positionOfNewDebugRawData);
                        if (errorResult != ERROR_SUCCESS)
                        {
                            if (errorResult != ERROR_BAD_FORMAT)
                                goto error;
    
                            // Don't make this a fatal error: not everyone sets IMAGE_DEBUG_DIRECTORY.PointerToRawData correctly.
                            pZapImage->GetZapper()->Warning(W("Warning: \"%ws\": IMAGE_DEBUG_DIRECTORY.PointerToRawData has an out of range value: 0x%x.\n"), inputFileName, imageDebugDirectory.PointerToRawData);
                        }
                        else
                        {
                            if (!fwriteat(outputFile, positionOfNewImageDebugDirectory + offsetof(IMAGE_DEBUG_DIRECTORY, PointerToRawData), &positionOfNewDebugRawData, sizeof(positionOfNewDebugRawData)))
                                goto error;
                        }
    
                        positionOfOldImageDebugDirectory += sizeof(IMAGE_DEBUG_DIRECTORY);
                        positionOfNewImageDebugDirectory += sizeof(IMAGE_DEBUG_DIRECTORY);
                    }
                    break;
                }
            }
            if (sidx == numberOfSections)
            {
                pZapImage->GetZapper()->Error(W("Error: \"%ws\": DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress points outside the bounds of the image: 0x%x.\n"), inputFileName, rvaOfOldImageDebugDirectory);
                goto error;  // Could not resolve IMAGE_DEBUG_DIRECTORY rva.
            }
        }
    }


    //-----------------------------------------------------------------------------------------
    // The WIN_CERTIFICATE structure, if present, is stored at the end of the PE file outside of
    // any section. The so-called "rva" at IMAGE_DATA_DIRECTORY[4] is actually an absolute file position.
    //-----------------------------------------------------------------------------------------
    ULONG oldPositionOfWinCertificate = imageOptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress;
    if (oldPositionOfWinCertificate != 0)
    {
        ULONG newPositionOfWinCertificate;
        DWORD errorCode = FixupPosition(aFixupRegions, oldPositionOfWinCertificate, &newPositionOfWinCertificate);
        if (errorCode != ERROR_SUCCESS)
        {
            pZapImage->GetZapper()->Error(W("Error: \"%ws\": DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress points outside the bounds of the image: 0x%x.\n"), inputFileName, oldPositionOfWinCertificate);
            goto error;
        }

        if (!fwriteat(outputFile,
                      positionOfImageOptionalHeader
                      + offsetof(IMAGE_OPTIONAL_HEADER, DataDirectory)
                      + sizeof(IMAGE_DATA_DIRECTORY) * IMAGE_DIRECTORY_ENTRY_SECURITY
                      + offsetof(IMAGE_DATA_DIRECTORY, VirtualAddress),
                      &newPositionOfWinCertificate,
                      sizeof(newPositionOfWinCertificate)))
        {
            goto ioerror;
        }
    }
    
    //-----------------------------------------------------------------------------------------
    // Force NX_COMPAT and DYNAMIC_BASE so secure OS loaders can load the image (obfuscators 
    // tend to strip these off)
    //-----------------------------------------------------------------------------------------
    DWORD newDllCharacteristics = imageOptionalHeader.DllCharacteristics | IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
    if (!fwriteat(outputFile,
                  positionOfImageOptionalHeader + offsetof(IMAGE_OPTIONAL_HEADER, DllCharacteristics),
                  &newDllCharacteristics,
                  sizeof(newDllCharacteristics)))
        goto error;

    //=========================================================================================
    // End of final pass. Output complete.
    //=========================================================================================

    return ERROR_SUCCESS;

ioerror:
    pZapImage->GetZapper()->Error(W("Error: \"%ws\": Unexpected end of file.\n"), inputFileName);
    return E_FAIL;

oomerror:
    return E_OUTOFMEMORY;

error:
    return ERROR_BAD_FORMAT;
#endif // BINDER
}



void ZapImage::Output_MDIL()
{
#ifdef BINDER
    _ASSERTE(!"intentionally unreachable");
#else


    StackSString outputFileName(m_zapper->GetOutputFileName());
    FILE *outputFile = _wfopen(outputFileName.GetUnicode(), W("wb"));
    if (outputFile == NULL)
        return;

    FILE *inputFile = _wfopen(m_pModuleFileName, W("rb"));
    if (!inputFile) goto error;

    DWORD errorCode = EmbedMdilIntoILFile(inputFile, outputFile, m_pModuleFileName, this);
    if (errorCode != ERROR_SUCCESS)
    {
        SetLastError(errorCode);
        goto error;
    }

    fclose(inputFile);
    fclose(outputFile);
    
    //    GetSvcLogger()->Printf(W("finished generating %s file\n"), outputFileName.GetUnicode());
    return;
    

error:
    DWORD dwLastError = GetLastError();
    fclose(inputFile);
    fclose(outputFile);
    WszDeleteFile(outputFileName.GetUnicode());
    m_zapper->Error(W("Could not create %ls file\n"), outputFileName.GetUnicode());
    SetLastError(dwLastError);
    ThrowLastError();
#endif // BINDER
}


//----------------------------------------------------------------------------------
// Writes out the MDIL blob.
//----------------------------------------------------------------------------------
DWORD ZapImage::Write_MDIL(FILE *outputFile)
{
#ifdef BINDER
    _ASSERTE(!"intentionally unreachable");
    return E_NOTIMPL;
#else

    if (m_pICLW != NULL)
    {
        delete m_pICLW;
        m_pICLW = NULL;
    }
    MDILHeader mdilHeader;
    memset(&mdilHeader, 0, sizeof(mdilHeader));

    if (m_methodRidCount == 0)
    {
        m_mapMethodRidToOffs.SetCount(1);
		m_mapMethodRidToOffs[0] = 0xcafedead;
        m_methodRidCount = 1;
    }

    DWORD totalCodeSize = 0;
    DWORD totalDebugInfoSize = 0;
    for (int codeKind = GENERIC_CODE; codeKind < CODE_KIND_COUNT; codeKind++)
    {
        if (m_codeOffs[codeKind] < sizeof(DWORD) && codeKind == GENERIC_CODE)
        {
            _ASSERTE(m_codeOffs[codeKind] == 0);
            m_codeBuffer[codeKind].SetCount(sizeof(DWORD));
            m_codeOffs[codeKind] = sizeof(DWORD);

            OutputDWord(&m_codeBuffer[codeKind][0], 'MDCD');

        }
        totalCodeSize += m_codeOffs[codeKind];
        totalDebugInfoSize += m_debugInfoBuffer[codeKind].GetCount();
    }

    EncodeGenericInstances_MDIL();

    // turns out we actually need an exact method count
    IMDInternalImport * pMDImport = m_pMDImport;
    HENUMInternalHolder hEnum(pMDImport);
    hEnum.EnumAllInit(mdtMethodDef);
    m_methodRidCount = hEnum.EnumGetCount() + m_stubMethodCount + 1;
    if (m_methodRidCount  < m_mapMethodRidToOffs.GetCount())
    {
        for (COUNT_T i = m_methodRidCount; i < m_mapMethodRidToOffs.GetCount(); i++)
            _ASSERTE(m_mapMethodRidToOffs[i] == 0);
    }
    else if (m_mapMethodRidToOffs.GetCount() < m_methodRidCount)
    {
        COUNT_T oldCount = m_mapMethodRidToOffs.GetCount();
        m_mapMethodRidToOffs.SetCount(m_methodRidCount);
        for (COUNT_T i = oldCount; i < m_methodRidCount; i++)
            m_mapMethodRidToOffs[i] = 0;
    }


    // conceptually, the code buffers for generic and non-generic code should be treated as one buffer
    // that implies that we need to add the size of the generic code buffer to offsets in the non-generic code
    // buffer
    for (COUNT_T methodRid = 0; methodRid < m_mapMethodRidToOffs.GetCount(); methodRid++)
    {
        if ((m_mapMethodRidToOffs[methodRid] != 0) &&
            ((m_mapMethodRidToOffs[methodRid] & GENERIC_METHOD_REF) == 0))
        {
            m_mapMethodRidToOffs[methodRid] += m_codeOffs[GENERIC_CODE];
        }
    }

    for (COUNT_T methodRid = 0; methodRid < m_mapMethodRidToDebug.GetCount(); methodRid++)
    {
        if (m_mapMethodRidToDebug[methodRid] != 0xFFFFFFFF)
            m_mapMethodRidToDebug[methodRid] += m_debugInfoBuffer[GENERIC_CODE].GetCount();
        else
            m_mapMethodRidToDebug[methodRid] = 0;
    }


    mdilHeader.hdrSize              = sizeof(mdilHeader);
    mdilHeader.magic                = 'MDIL';
    mdilHeader.version              = MDIL_VERSION_CURRENT;
    mdilHeader.methodMapCount       = m_methodRidCount;
    mdilHeader.extModuleCount       = m_extModRef.GetCount();
    mdilHeader.genericInstSize      = m_genericInstPool.GetCount();
    mdilHeader.extTypeCount         = m_extTypeRef.GetCount();
    mdilHeader.extMemberCount       = m_extMemberRef.GetCount();
    mdilHeader.namePoolSize         = m_namePool.GetCount();
    mdilHeader.codeSize             = totalCodeSize;
    mdilHeader.typeMapCount         = m_typeRidCount;
    mdilHeader.typeSpecCount        = m_typeSpecToOffs.GetCount();
    mdilHeader.methodSpecCount      = m_methodSpecToOffs.GetCount();
    mdilHeader.signatureCount       = m_signatureToOffs.GetCount();
    mdilHeader.typeSize             = m_compactLayoutOffs;
    mdilHeader.userStringPoolSize   = m_userStringPool.GetCount();
    mdilHeader.stubSize             = m_stubBuffer.GetCount();
    mdilHeader.stubAssocSize        = m_stubAssocBuffer.GetCount();
    mdilHeader.debugMapCount        = m_mapMethodRidToDebug.GetCount();
    mdilHeader.debugInfoSize        = totalDebugInfoSize;

    mdilHeader.genericCodeSize      = m_codeOffs[GENERIC_CODE];
    mdilHeader.genericDebugInfoSize = m_debugInfoBuffer[GENERIC_CODE].GetCount();

    mdilHeader.compilerVersionMajor = VER_MAJORVERSION;
    mdilHeader.compilerVersionMinor = VER_MINORVERSION;
    mdilHeader.compilerVersionBuildNumber = VER_PRODUCTBUILD;
    mdilHeader.compilerVersionPrivateBuildNumber = VER_PRODUCTBUILD_QFE;

    mdilHeader.subVersion           = MDIL_SUB_VERSION_CURRENT;

    if (m_wellKnownTypesTable.GetCount() != 0)
    {
        assert(m_wellKnownTypesTable.GetCount() == WKT_COUNT);
        mdilHeader.flags |= MDILHeader::WellKnownTypesPresent;
    }

    LoadHintEnum loadHint = LoadDefault;
    LoadHintEnum defaultLoadHint = LoadDefault;
    GetCompileInfo()->GetLoadHint(m_zapper->m_hAssembly,
                                  m_zapper->m_hAssembly,
                                  &loadHint,
                                  &defaultLoadHint);
    if (defaultLoadHint == LoadAlways)
    {
        mdilHeader.flags |= MDILHeader::IsEagerlyLoaded;
    }

    mdilHeader.flags |= GetCompileInfo()->GetMdilModuleSecurityFlags(m_zapper->m_hAssembly);

    if (GetCompileInfo()->CompilerRelaxationNoStringInterningPermitted(m_zapper->m_hAssembly))
    {
        mdilHeader.flags |= MDILHeader::CompilerRelaxationNoStringInterning;
    }

    if (GetCompileInfo()->CompilerRelaxationNoStringInterningPermitted(m_zapper->m_hAssembly))
    {
        mdilHeader.flags |= MDILHeader::RuntimeCompatibilityRuntimeWrappedExceptions;
    }

    if (m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_MINIMAL_MDIL)
    {
        mdilHeader.flags |= MDILHeader::MinimalMDILImage;
    }

    if (m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_NO_MDIL)
    {
        mdilHeader.flags |= MDILHeader::NoMDILImage;
    }

    mdilHeader.cerReliabilityContract = GetCompileInfo()->CERReliabilityContract(m_zapper->m_hAssembly);

    // reset architecture mask
    mdilHeader.flags &= ~MDILHeader::TargetArch_Mask;

#if defined(_TARGET_X86_)
    mdilHeader.flags |= MDILHeader::TargetArch_X86;
#elif defined(_TARGET_ARM_)
    mdilHeader.flags |= MDILHeader::TargetArch_ARM;
#elif defined(_TARGET_AMD64_)
    mdilHeader.flags |= MDILHeader::TargetArch_AMD64;
#else
#error unexpected target architecture (neither x86, ARM, or AMD64)
#endif //_TARGET_X86_

    mdilHeader.entryPointToken = m_ModuleDecoder.GetEntryPointToken();
    mdilHeader.subsystem = m_ModuleDecoder.GetSubsystem();
    {
        // 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);

        mdilHeader.baseAddress = peFlat.GetPreferredBase();
    }

    mdilHeader.platformID = MDILHeader::PlatformID_Triton;
    
    ClrCtlData clrCtlData;
    SArray<BYTE> blobData;
    const void *pPublicKey = NULL;
    ULONG cbPublicKey = 0;
    ULONG cbPublicKeyToken = 0;
    BYTE* pKeyToken = NULL;

    AssemblyMetaDataInternal metaData;
    LPCSTR pModuleName;
    LPCSTR pAssemblyName;
    DWORD flags;
    memset(&clrCtlData, 0, sizeof(clrCtlData));
    clrCtlData.hdrSize = sizeof(clrCtlData);

    m_pMDImport->GetScopeProps(&pModuleName, &clrCtlData.MVID);
    m_pMDImport->GetAssemblyProps(
            TokenFromRid(1, mdtAssembly),       // [IN] The Assembly for which to get the properties.
            &pPublicKey,
            &cbPublicKey,
            NULL,                               // [OUT] Hash Algorithm
            &pAssemblyName,                     // [OUT] Buffer to fill with name
            &metaData,                          // [OUT] Assembly Metadata (version, locale, etc.)
            &flags);                            // [OUT] Flags

    clrCtlData.assemblyName = m_assemblyName;
    clrCtlData.locale = m_locale;
    clrCtlData.majorVersion = metaData.usMajorVersion;
    clrCtlData.minorVersion = metaData.usMinorVersion;
    clrCtlData.buildNumber = metaData.usBuildNumber;
    clrCtlData.revisionNumber = metaData.usRevisionNumber;
    if (cbPublicKey > 0) {
        if ((flags & afPublicKey)!= 0) {
            clrCtlData.hasPublicKey = 1;
        }
        clrCtlData.cbPublicKey = cbPublicKey;
        clrCtlData.publicKeyBlob = blobData.GetCount();
        blobData.SetCount(clrCtlData.publicKeyBlob + clrCtlData.cbPublicKey);
        memcpy_s(&blobData[(COUNT_T)clrCtlData.publicKeyBlob], clrCtlData.cbPublicKey, pPublicKey, cbPublicKey);

        if (StrongNameTokenFromPublicKey((BYTE*)pPublicKey, cbPublicKey,
                                     &pKeyToken, &cbPublicKeyToken))
        {
            if (cbPublicKeyToken > 0 && cbPublicKeyToken == sizeof(clrCtlData.publicKeyToken)) {
                memcpy(&clrCtlData.publicKeyToken, pKeyToken, cbPublicKeyToken);
                clrCtlData.cbPublicKeyToken = cbPublicKeyToken;
                clrCtlData.hasPublicKeyToken = true;
            }
        }

    }

    CORCOMPILE_VERSION_INFO versionInfo;
    IfFailThrow(m_zapper->m_pEECompileInfo->GetAssemblyVersionInfo(m_zapper->m_hAssembly, &versionInfo));

    mdilHeader.timeDateStamp = versionInfo.sourceAssembly.timeStamp;
    clrCtlData.ilImageSize = versionInfo.sourceAssembly.ilImageSize;
    clrCtlData.wcbSNHash = 0;
    clrCtlData.snHashBlob = blobData.GetCount();
    
    clrCtlData.cbTPBandName = 0;
    clrCtlData.tpBandNameBlob = blobData.GetCount();

    clrCtlData.extTypeRefExtendCount        = m_extTypeRefExtend.GetCount();
    clrCtlData.extMemberRefExtendCount      = m_extMemberRefExtend.GetCount();
    
    clrCtlData.neutralResourceCultureNameLen   = m_neutralResourceCultureNameLen;
    clrCtlData.neutralResourceCultureName      = m_cultureName;
    clrCtlData.neutralResourceFallbackLocation = m_neutralResourceFallbackLocation;

    mdilHeader.blobDataSize = blobData.GetCount() * sizeof(blobData[0]);

    if ((versionInfo.wConfigFlags & CORCOMPILE_CONFIG_DEBUG) != 0)
    {
        mdilHeader.flags |= MDILHeader::DebuggableMDILCode;
        if ((versionInfo.wConfigFlags & CORCOMPILE_CONFIG_DEBUG_DEFAULT) != 0)
            mdilHeader.flags |= MDILHeader::DebuggableILAssembly;
    }
    else
    {
        // Current CLR doesn't allow non-debuggable native image to be generated from debuggable assembly.
        _ASSERTE((versionInfo.wConfigFlags & CORCOMPILE_CONFIG_DEBUG_DEFAULT) != 0);
    }

    //-----------------------------------------------------------------------------------------
    // Write out the MDIL blob.
    //-----------------------------------------------------------------------------------------
    if (fwrite(&mdilHeader,               sizeof(mdilHeader),                                        1, outputFile) != 1) goto error;
    m_pMDImport->GetRvaOffsetData(&clrCtlData.firstMethodRvaOffset, &clrCtlData.methodDefRecordSize, &clrCtlData.methodDefCount,
        &clrCtlData.firstFieldRvaOffset, &clrCtlData.fieldRvaRecordSize, &clrCtlData.fieldRvaCount);
    if (fwrite(&clrCtlData,               sizeof(clrCtlData),                                        1, outputFile) != 1) goto error;

    if (m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_NO_MDIL)
    {   
        // If this is a no MDIL image, we are already done.
        goto success;
    }

    if (blobData.GetCount() > 0)
    {
        if(fwrite(&blobData[0], blobData.GetCount() * sizeof(blobData[0]), 1, outputFile) != 1) goto error;
    }

    if (mdilHeader.flags & MDILHeader::WellKnownTypesPresent
     && fwrite(&m_wellKnownTypesTable[0], m_wellKnownTypesTable.GetCount()*sizeof(m_wellKnownTypesTable[0]), 1, outputFile) != 1) goto error;
    if (m_typeRidCount != 0
     && fwrite(&m_mapTypeRidToOffs[0],    m_typeRidCount           *sizeof(m_mapTypeRidToOffs[0]),   1, outputFile) != 1) goto error;
    if (fwrite(&m_mapMethodRidToOffs[0],  m_methodRidCount         *sizeof(m_mapMethodRidToOffs[0]), 1, outputFile) != 1) goto error;
    if (mdilHeader.genericInstSize != 0
     && fwrite(&m_genericInstPool[0],     mdilHeader.genericInstSize*sizeof(m_genericInstPool[0]), 1, outputFile) != 1) goto error;
    if (fwrite(&m_extModRef[0],           m_extModRef.GetCount()   *sizeof(m_extModRef[0]),          1, outputFile) != 1) goto error;
    if (fwrite(&m_extTypeRef[0],          m_extTypeRef.GetCount()  *sizeof(m_extTypeRef[0]),         1, outputFile) != 1) goto error;
    if (fwrite(&m_extMemberRef[0],        m_extMemberRef.GetCount()*sizeof(m_extMemberRef[0]),       1, outputFile) != 1) goto error;
    if (mdilHeader.typeSpecCount > 0
     && fwrite(&m_typeSpecToOffs[0],      m_typeSpecToOffs.GetCount()*sizeof(m_typeSpecToOffs[0]),   1, outputFile) != 1) goto error;
    if (mdilHeader.methodSpecCount > 0
     && fwrite(&m_methodSpecToOffs[0],    m_methodSpecToOffs.GetCount()*sizeof(m_methodSpecToOffs[0]),1,outputFile) != 1) goto error;
    if (mdilHeader.signatureCount > 0
     && fwrite(&m_signatureToOffs[0],     m_signatureToOffs.GetCount()*sizeof(m_signatureToOffs[0]), 1,outputFile) != 1) goto error;
    if (fwrite(&m_namePool[0],            sizeof(m_namePool[0]),   m_namePool.GetCount(),               outputFile) != m_namePool.GetCount()) goto error;
    if (m_compactLayoutOffs > 0
     && fwrite(&m_compactLayoutBuffer[0], m_compactLayoutOffs      *sizeof(m_compactLayoutBuffer[0]),1, outputFile) != 1) goto error;
    if (mdilHeader.userStringPoolSize > 0
     && fwrite(&m_userStringPool[0],      sizeof(m_userStringPool[0]),m_userStringPool.GetCount(),      outputFile) != m_userStringPool.GetCount()) goto error;
    if (fwrite(&m_codeBuffer[GENERIC_CODE][0], m_codeOffs[GENERIC_CODE],                             1, outputFile) != 1) goto error;
    //write out the non-generic code immediatly after the generic code.
    if (m_codeOffs[NON_GENERIC_CODE] != 0 && fwrite(&m_codeBuffer[NON_GENERIC_CODE][0], m_codeOffs[NON_GENERIC_CODE],                       1, outputFile) != 1) goto error;    
    if (mdilHeader.stubSize > 0
     && fwrite(&m_stubBuffer[0],          mdilHeader.stubSize*sizeof(m_stubBuffer[0]),               1, outputFile) != 1) goto error;
    if (mdilHeader.stubAssocSize > 0
     && fwrite(&m_stubAssocBuffer[0],     mdilHeader.stubAssocSize*sizeof(m_stubAssocBuffer[0]),     1, outputFile) != 1) goto error;
    if (mdilHeader.debugMapCount > 0
     && fwrite(&m_mapMethodRidToDebug[0], mdilHeader.debugMapCount*sizeof(m_mapMethodRidToDebug[0]), 1, outputFile) != 1) goto error;
    if (m_debugInfoBuffer[GENERIC_CODE].GetCount() > 0
     && fwrite(&m_debugInfoBuffer[GENERIC_CODE][0], m_debugInfoBuffer[GENERIC_CODE].GetCount(),      1, outputFile) != 1) goto error;
    //write out the non-generic debug info immediately after the generic debug info
    if (m_debugInfoBuffer[NON_GENERIC_CODE].GetCount() > 0
     && fwrite(&m_debugInfoBuffer[NON_GENERIC_CODE][0], m_debugInfoBuffer[NON_GENERIC_CODE].GetCount(),1, outputFile) != 1) goto error;


    if (m_extTypeRefExtend.GetCount() > 0) 
    {
        if (fwrite(&m_extTypeRefExtend[0], m_extTypeRefExtend.GetCount()*sizeof(m_extTypeRefExtend[0]), 1, outputFile) != 1) goto error;
    }
    if (m_extMemberRefExtend.GetCount() > 0) 
    {
        if (fwrite(&m_extMemberRefExtend[0], m_extMemberRefExtend.GetCount()*sizeof(m_extMemberRefExtend[0]), 1, outputFile) != 1) goto error;
    }

    
success:
    return ERROR_SUCCESS;

error:
    DWORD dwLastError = GetLastError();
    if (dwLastError == ERROR_SUCCESS)
        dwLastError = E_FAIL;
    return dwLastError;
#endif // BINDER
}

void ZapImage::FlushCompactLayoutData(mdToken typeToken, BYTE *pData, ULONG cData)
{
#ifndef BINDER
    // Save the data in m_compactLayoutBuffer
    COUNT_T dataSize = m_compactLayoutBuffer.GetCount();
    if (dataSize < sizeof(DWORD))
    {
        assert(dataSize == 0);
        m_compactLayoutBuffer.SetCount(10000);
        memcpy(&m_compactLayoutBuffer[0], "CMPL", sizeof(DWORD));
        m_compactLayoutOffs = sizeof(DWORD);
    }
    COUNT_T desiredSize = m_compactLayoutOffs + cData;
    while (m_compactLayoutBuffer.GetCount() < desiredSize)
        m_compactLayoutBuffer.SetCount(m_compactLayoutBuffer.GetCount()*2);
    memcpy(&m_compactLayoutBuffer[(COUNT_T)m_compactLayoutOffs], pData, cData);

    COUNT_T rid = RidFromToken(typeToken);
    if (TypeFromToken(typeToken) == mdtTypeSpec)
    {
        assert(rid < m_typeSpecToOffs.GetCount());
        m_typeSpecToOffs[rid] = m_compactLayoutOffs;
    }
    else if (TypeFromToken(typeToken) == mdtMethodSpec)
    {
        assert(rid < m_methodSpecToOffs.GetCount());
        m_methodSpecToOffs[rid] = m_compactLayoutOffs;
    }
    else if (TypeFromToken(typeToken) == mdtSignature)
    {
        assert(rid < m_signatureToOffs.GetCount());
        m_signatureToOffs[rid] = m_compactLayoutOffs;
    }
    else if (TypeFromToken(typeToken) == mdtMemberRef)
    {
        assert(rid < m_extMemberRefExtend.GetCount());
        m_extMemberRefExtend[rid].signature = m_compactLayoutOffs;
    }
    else
    {
        assert(TypeFromToken(typeToken) == mdtTypeDef);
        // Remember the offset in m_mapTypeRidToOffs
        COUNT_T mappingCount = m_mapTypeRidToOffs.GetCount();
        if (mappingCount <= rid)
        {
            if (mappingCount == 0)
            {
                m_typeRidCount = 0;
                m_mapTypeRidToOffs.SetCount(1000);
            }
            while (m_mapTypeRidToOffs.GetCount() <= rid)
                m_mapTypeRidToOffs.SetCount(m_mapTypeRidToOffs.GetCount()*2);
            COUNT_T newMappingCount = m_mapTypeRidToOffs.GetCount();
            for (COUNT_T i = mappingCount; i < newMappingCount; i++)
                m_mapTypeRidToOffs[i] = 0;
            m_typeRidCount = rid+1;
        }
        if (m_typeRidCount < rid+1)
            m_typeRidCount = rid+1;
        m_mapTypeRidToOffs[rid] = m_compactLayoutOffs;
    }
    m_compactLayoutOffs += cData;
#endif // !BINDER
}

void ZapImage::FlushStubData(BYTE *pStubSize, ULONG cStubSize,
                             BYTE *pStubData, ULONG cStubData,
                             BYTE *pStubAssocData, ULONG cStubAssocData)
{
    // Save the data in m_stubBuffer and m_stubAssocBuffer
    m_stubBuffer.SetCount(cStubSize + cStubData);
    memcpy(&m_stubBuffer[0], pStubSize, cStubSize);
    memcpy(&m_stubBuffer[(COUNT_T)cStubSize], pStubData, cStubData);

    m_stubAssocBuffer.SetCount(cStubAssocData);
    memcpy(&m_stubAssocBuffer[0], pStubAssocData, cStubAssocData);
}

// Flush the user string pool
void ZapImage::FlushUserStringPool(BYTE *pData, ULONG cData)
{
    m_userStringPool.SetCount(AlignUp(cData, sizeof(DWORD)));
    memcpy(&m_userStringPool[0], pData, cData);
}

void ZapImage::FlushWellKnownTypes(DWORD *wellKnownTypesTable, SIZE_T count)
{
    m_wellKnownTypesTable.SetCount((DWORD)count);
    memcpy(&m_wellKnownTypesTable[0], wellKnownTypesTable, count*sizeof(wellKnownTypesTable[0]));
}
#endif

void ZapImage::Compile()
{
    //
    // First, compile methods in the load order array.
    //
    bool doNothingNgen = false;
#ifdef _DEBUG
    static ConfigDWORD fDoNothingNGen;
    doNothingNgen = !!fDoNothingNGen.val(CLRConfig::INTERNAL_ZapDoNothing);
#endif

#ifdef MDIL
    // Reset stream (buffer) only when we are really generating MDIL (instead of just an empty MDIL section)
    if ((m_zapper->m_pOpt->m_compilerFlags & (CORJIT_FLG_MDIL|CORJIT_FLG_NO_MDIL)) == CORJIT_FLG_MDIL)
    {
        GetCompactLayoutWriter()->Reset();
    }
#endif

    if (!doNothingNgen)
    {
        //
        // Compile the methods specified by the IBC profile data
        // 
        CompileProfileData();

        BeginRegion(CORINFO_REGION_COLD);


        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);
            }

            //
            // Compile the remaining methods that weren't compiled during the CompileProfileData 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);

        // If we want ngen to fail when we create partial ngen images we can
        // throw an NGEN failure HRESULT here.
#if 0
        if (m_zapper->m_failed)
        {
            ThrowHR(NGEN_E_TP_PARTIAL_IMAGE); 
        }
#endif

    }

    // 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();
    }

#ifdef MDIL
    if (m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_MDIL)
    {
        if (!(m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_NO_MDIL))
        {
            GetCompactLayoutWriter()->FlushStubData();
        }
        Output_MDIL();
    }
    else
#endif
    {
        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();
        }
        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, DWORD dwJitFlags)
{
    STANDARD_VM_CONTRACT;

    // The caller must always set the IL_STUB flag
    _ASSERTE((dwJitFlags & CORJIT_FLG_IL_STUB) != 0);

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

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

    pImage->m_zapper->m_pOpt->m_compilerFlags |= dwJitFlags;
    pImage->m_zapper->m_pOpt->m_compilerFlags &= ~(CORJIT_FLG_PROF_ENTERLEAVE | 
                                                   CORJIT_FLG_DEBUG_CODE | 
                                                   CORJIT_FLG_DEBUG_EnC | 
                                                   CORJIT_FLG_DEBUG_INFO);

    mdMethodDef md = mdMethodDefNil;
#ifdef MDIL
    if (pImage->m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_MDIL)
    {
        md = pImage->GetCompactLayoutWriter()->GetNextStubToken();
        if (md == mdMethodDefNil)
            return;

        pImage->m_stubMethodCount++;
    }
#endif // MDIL

    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;

    EX_TRY
    {
        if (ShouldCompileMethodDef(md))
            handle = m_pPreloader->LookupMethodDef(md);
        else
            result = COMPILE_EXCLUDED;
    }
    EX_CATCH
    {
        // Continue unwinding if fatal error was hit.
        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 (IsVTableGapMethod(md))
        {
            handle = NULL;
        }
        else
        {
#ifndef BINDER
            Exception *ex = GET_EXCEPTION();
            HRESULT hrException = ex->GetHR();

            StackSString message;
            if (hrException != COR_E_UNSUPPORTEDMDIL)
                ex->GetMessage(message);

            CorZapLogLevel level;

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

            // 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;
            }

            if (hrException != COR_E_UNSUPPORTEDMDIL)
                m_zapper->Print(level, W("%s while compiling method token 0x%x\n"), message.GetUnicode(), md);
#else
            m_zapper->PrintErrorMessage(CORZAP_LOGLEVEL_ERROR, GET_EXCEPTION());
            m_zapper->Error(W(" while compiling method token 0x%x\n"), md);
#endif

            result = LOOKUP_FAILED;

            m_zapper->m_failed = TRUE;
            if (m_stats)
                m_stats->m_failedMethods++;
        }
    }
    EX_END_CATCH(SwallowAllExceptions);

    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);

#ifdef  MDIL
        if (m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_MDIL)
            m_pPreloader->AddMDILCodeFlavorsToUncompiledMethods(handle);
#endif

    }

    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)
{
    // READYTORUN: FUTURE: Generics
    if (IsReadyToRunCompilation())
        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;

#ifdef MDIL
    // This is a quick workaround to opt specific methods out of MDIL generation to work around bugs.
    if (m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_MDIL)
    {
        HRESULT hr = m_pMDImport->GetCustomAttributeByName(md, "System.Runtime.BypassMdilAttribute", NULL, NULL);
        if (hr == S_OK)
            return NOT_COMPILED;
    }
#endif

#ifdef FEATURE_READYTORUN_COMPILER
    // This is a quick workaround to opt specific methods out of ReadyToRun compilation to work around bugs.
    if (IsReadyToRunCompilation())
    {
        HRESULT hr = m_pMDImport->GetCustomAttributeByName(md, "System.Runtime.BypassReadyToRun", NULL, NULL);
        if (hr == S_OK)
            return NOT_COMPILED;
    }
#endif

    if (methodProfilingDataFlags != 0)
    {
        // Report the profiling data flags for layout of the EE datastructures
        m_pPreloader->SetMethodProfilingFlags(handle, methodProfilingDataFlags);

        // Only proceed with compilation if the code is hot
        //
        if ((methodProfilingDataFlags & (1 << ReadMethodCode)) == 0)
            return NOT_COMPILED;
    }
    else
    {
        if (m_zapper->m_pOpt->m_fPartialNGen)
            return COMPILE_EXCLUDED;
    }

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

    _ASSERTE((m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_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 & CORJIT_FLG_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
    {
#ifndef BINDER
        // Continue unwinding if fatal error was hit.
        if (FAILED(g_hrFatalError))
            ThrowHR(g_hrFatalError);

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

        StackSString message;
        if (hrException != COR_E_UNSUPPORTEDMDIL)
            ex->GetMessage(message);

        CorZapLogLevel level;

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

        // 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;
        }

        if (hrException != COR_E_UNSUPPORTEDMDIL)
            m_zapper->Print(level, W("%s while compiling method %s\n"), message.GetUnicode(), zapInfo.m_currentMethodName.GetUnicode());
#else
        m_zapper->PrintErrorMessage(CORZAP_LOGLEVEL_ERROR, GET_EXCEPTION());
        m_zapper->Error(W(" while compiling method %s\n"), zapInfo.m_currentMethodName.GetUnicode());
#endif
        result = COMPILE_FAILED;
        m_zapper->m_failed = TRUE;

        if (m_stats != NULL)
        {
            if ((m_zapper->m_pOpt->m_compilerFlags & CORJIT_FLG_IL_STUB) == 0)
                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);
    }

#ifdef BINDER
    m_zapper->Error(W("%s"), fullName.GetUnicode());
#else
    m_zapper->Print(level, W("%s"), fullName.GetUnicode());
#endif

    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 & CORJIT_FLG_BBINSTR) != 0)
        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.
#ifndef FEATURE_CORECLR
    if ((fileHeader->Version == CORBBTPROF_V1_VERSION) && CanConvertIbcData())
    {
        // Read and convert V1 data
        m_zapper->Info(W("Converting V1 IBC data to latest format.\n"));
        convertFromV1 = true;
    }
    else
#endif
    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
    //

#ifndef BINDER
    _ASSERTE(TypeProfilingData   == FirstTokenFlagSection + TBL_TypeDef);
    _ASSERTE(MethodProfilingData == FirstTokenFlagSection + TBL_Method);
    _ASSERTE(SectionFormatCount  >= FirstTokenFlagSection + TBL_COUNT + 4);
#endif

    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;
        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;

        // 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::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 & CORJIT_FLG_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;
}

#ifndef BINDER
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

#ifndef FEATURE_CORECLR
    m_zapper->Print(level, W("Warning: %s. If this assembly is found during runtime of an application, then the native image currently being generated will not be used.\n"), pszMessage);
#else
    m_zapper->Print(level, W("Warning: %s.\n"), pszMessage);
#endif

    fileNotFoundErrorsTable.Append(message);
}
#endif

void ZapImage::Error(mdToken token, HRESULT hr, LPCWSTR message)
{
#if defined(FEATURE_CORECLR) || defined(CROSSGEN_COMPILE)
    // 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);
#endif

    CorZapLogLevel level = CORZAP_LOGLEVEL_ERROR;

#ifndef BINDER
    if (RuntimeFileNotFound(hr) || (hr == CORSEC_E_INVALID_STRONGNAME))
    {
        // FileNotFound errors here can be converted into a single error string per ngen compile, 
        // and the detailed error is available with verbose logging
        if (m_zapper->m_pOpt->m_ignoreErrors && message != NULL)
        {
            FileNotFoundError(message);
            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);
#ifndef BINDER
#ifdef _TARGET_ARM_
        pHelperThunk = GetInnerPtr(pHelperThunk, THUMB_CODE);
#endif
#endif // !BINDER
        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);
}