summaryrefslogblamecommitdiffstats
path: root/private/ntos/mm/creasect.c
blob: 504d77b26ca8903a7b166291a9c4cb989d902543 (plain) (tree)
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





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                   
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

   creasect.c

Abstract:

    This module contains the routines which implement the
    NtCreateSection and NtOpenSection.

Author:

    Lou Perazzoli (loup) 22-May-1989

Revision History:

--*/

#include "mi.h"

ULONG MMCONTROL = 'aCmM';
ULONG MMTEMPORARY = 'xxmM';
ULONG MMSECT = 'tSmM';

#define MM_SIZE_OF_LARGEST_IMAGE ((ULONG)0x10000000)

#define MM_MAXIMUM_IMAGE_HEADER (2 * PAGE_SIZE)

#define MM_ALLOCATION_FRAGMENT (64 * 1024)

extern ULONG MmSharedCommit;

//
// The maximum number of image object (object table entries) is
// the number which will fit into the MM_MAXIMUM_IMAGE_HEADER with
// the start of the PE image header in the last word of the first
//

#define MM_MAXIMUM_IMAGE_SECTIONS                       \
     ((MM_MAXIMUM_IMAGE_HEADER - (PAGE_SIZE + sizeof(IMAGE_NT_HEADERS))) /  \
            sizeof(IMAGE_SECTION_HEADER))

#if DBG
extern PEPROCESS MmWatchProcess;
VOID MmFooBar(VOID);
#endif // DBG


extern POBJECT_TYPE IoFileObjectType;

CCHAR MmImageProtectionArray[16] = {
                                    MM_NOACCESS,
                                    MM_EXECUTE,
                                    MM_READONLY,
                                    MM_EXECUTE_READ,
                                    MM_WRITECOPY,
                                    MM_EXECUTE_WRITECOPY,
                                    MM_WRITECOPY,
                                    MM_EXECUTE_WRITECOPY,
                                    MM_NOACCESS,
                                    MM_EXECUTE,
                                    MM_READONLY,
                                    MM_EXECUTE_READ,
                                    MM_READWRITE,
                                    MM_EXECUTE_READWRITE,
                                    MM_READWRITE,
                                    MM_EXECUTE_READWRITE };


CCHAR
MiGetImageProtection (
    IN ULONG SectionCharacteristics
    );

NTSTATUS
MiVerifyImageHeader (
    IN PIMAGE_NT_HEADERS NtHeader,
    IN PIMAGE_DOS_HEADER DosHeader,
    IN ULONG NtHeaderSize
    );

BOOLEAN
MiCheckDosCalls (
    IN PIMAGE_OS2_HEADER Os2Header,
    IN ULONG HeaderSize
    );


#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE,MiCreateImageFileMap)
#pragma alloc_text(PAGE,NtCreateSection)
#pragma alloc_text(PAGE,NtOpenSection)
#pragma alloc_text(PAGE,MiGetImageProtection)
#pragma alloc_text(PAGE,MiVerifyImageHeader)
#pragma alloc_text(PAGE,MiCheckDosCalls)
#pragma alloc_text(PAGE,MiCreatePagingFileMap)
#pragma alloc_text(PAGE,MiCreateDataFileMap)
#endif

#pragma pack (1)
typedef struct _PHARLAP_CONFIG {
    UCHAR  uchCopyRight[0x32];
    USHORT usType;
    USHORT usRsv1;
    USHORT usRsv2;
    USHORT usSign;
} CONFIGPHARLAP, *PCONFIGPHARLAP;
#pragma pack ()


NTSTATUS
NtCreateSection (
    OUT PHANDLE SectionHandle,
    IN ACCESS_MASK DesiredAccess,
    IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
    IN PLARGE_INTEGER MaximumSize OPTIONAL,
    IN ULONG SectionPageProtection,
    IN ULONG AllocationAttributes,
    IN HANDLE FileHandle OPTIONAL
     )

/*++

Routine Description:

    This function creates a section object and opens a handle to the object
    with the specified desired access.

Arguments:

    SectionHandle - A pointer to a variable that will
        receive the section object handle value.

    DesiredAccess - The desired types of access for the section.

    DesiredAccess Flags

         EXECUTE - Execute access to the section is
              desired.

         READ - Read access to the section is desired.

         WRITE - Write access to the section is desired.


    ObjectAttributes - Supplies a pointer to an object attributes structure.

    MaximumSize - Supplies the maximum size of the section in bytes.
         This value is rounded up to the host page size and
         specifies the size of the section (page file
         backed section) or the maximum size to which a
         file can be extended or mapped (file backed
         section).

    SectionPageProtection - Supplies the protection to place on each page
         in the section.  One of PAGE_READ, PAGE_READWRITE, PAGE_EXECUTE,
         or PAGE_WRITECOPY and, optionally, PAGE_NOCACHE may be specified.

    AllocationAttributes - Supplies a set of flags that describe the
         allocation attributes of the section.

        AllocationAttributes Flags

        SEC_BASED - The section is a based section and will be
            allocated at the same virtual address in each process
            address space that receives the section.  This does not
            imply that addresses are reserved for based sections.
            Rather if the section cannot be mapped at the based address
            an error is returned.


        SEC_RESERVE - All pages of the section are set to the
            reserved state.

        SEC_COMMIT - All pages of the section are set to the commit
            state.

        SEC_IMAGE - The file specified by the file handle is an
                    executable image file.

        SEC_FILE - The file specified by the file handle is a mapped
                   file.  If a file handle is supplied and neither
                   SEC_IMAGE or SEC_FILE is supplied, SEC_FILE is
                   assumed.

        SEC_NO_CHANGE - Once the file is mapped, the protection cannot
                        be changed nor can the view be unmapped.  The
                        view is unmapped when the process is deleted.
                        Cannot be used with SEC_IMAGE.

    FileHandle - Supplies an optional handle of an open file object.
         If the value of this handle is null, then the
         section will be backed by a paging file. Otherwise
         the section is backed by the specified data file.

Return Value:

    Returns the status of the operation.

    TBS

--*/

{
    NTSTATUS Status;
    PVOID Section;
    HANDLE Handle;
    LARGE_INTEGER LargeSize;
    LARGE_INTEGER CapturedSize;
    ULONG RetryCount;

    if ((AllocationAttributes & ~(SEC_COMMIT | SEC_RESERVE | SEC_BASED |
            SEC_IMAGE | SEC_NOCACHE | SEC_NO_CHANGE)) != 0) {
        return STATUS_INVALID_PARAMETER_6;
    }

    if ((AllocationAttributes & (SEC_COMMIT | SEC_RESERVE | SEC_IMAGE)) == 0) {
        return STATUS_INVALID_PARAMETER_6;
    }

    if ((AllocationAttributes & SEC_IMAGE) &&
            (AllocationAttributes & (SEC_COMMIT | SEC_RESERVE | SEC_NOCACHE | SEC_NO_CHANGE))) {

        return STATUS_INVALID_PARAMETER_6;
    }

    if ((AllocationAttributes & SEC_COMMIT) &&
            (AllocationAttributes & SEC_RESERVE)) {
        return STATUS_INVALID_PARAMETER_6;
    }

    //
    // Check the SectionProtection Flag.
    //

    if ((SectionPageProtection & PAGE_NOCACHE) ||
        (SectionPageProtection & PAGE_GUARD) ||
        (SectionPageProtection & PAGE_NOACCESS)) {

        //
        // No cache is only specified through SEC_NOCACHE option in the
        // allocation attributes.
        //

        return STATUS_INVALID_PAGE_PROTECTION;
    }


    if (KeGetPreviousMode() != KernelMode) {
        try {
            ProbeForWriteHandle(SectionHandle);
            if (ARGUMENT_PRESENT (MaximumSize)) {
                LargeSize = *MaximumSize;
            } else {
                ZERO_LARGE (LargeSize);
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
            return GetExceptionCode();
        }
    } else {
        if (ARGUMENT_PRESENT (MaximumSize)) {
            LargeSize = *MaximumSize;
        } else {
            ZERO_LARGE (LargeSize);
        }
    }

    RetryCount = 0;

retry:

    CapturedSize = LargeSize;

    ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);
    Status = MmCreateSection ( &Section,
                               DesiredAccess,
                               ObjectAttributes,
                               &CapturedSize,
                               SectionPageProtection,
                               AllocationAttributes,
                               FileHandle,
                               NULL );


    ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);
    if (!NT_SUCCESS(Status)) {
        if ((Status == STATUS_FILE_LOCK_CONFLICT) &&
            (RetryCount < 3)) {

            //
            // The file system may have prevented this from working
            // due to log file flushing.  Delay and try again.
            //

            RetryCount += 1;

            KeDelayExecutionThread (KernelMode,
                                    FALSE,
                                    &MmHalfSecond);

            goto retry;

        }
        return Status;
    }

#if DBG
    if (MmDebug & MM_DBG_SECTIONS) {
        DbgPrint("inserting section %lx control %lx\n",Section,
                    ((PSECTION)Section)->Segment->ControlArea);
    }
#endif

    {
        PCONTROL_AREA ControlArea;
        ControlArea = ((PSECTION)Section)->Segment->ControlArea;
        if ((ControlArea != NULL) && (ControlArea->FilePointer != NULL)) {
            CcZeroEndOfLastPage (ControlArea->FilePointer);
        }
    }

    Status = ObInsertObject (Section,
                             NULL,
                             DesiredAccess,
                             0,
                             (PVOID *)NULL,
                             &Handle);

    try {
        *SectionHandle = Handle;
    } except (EXCEPTION_EXECUTE_HANDLER) {
        return Status;
    }

#if DBG
    if (MmDebug & MM_DBG_SHOW_NT_CALLS) {
        if ( !MmWatchProcess )
            DbgPrint("return crea sect handle %lx status %lx\n",Handle, Status);
    }
#endif

    return Status;
}

NTSTATUS
MmCreateSection (
    OUT PVOID *SectionObject,
    IN ACCESS_MASK DesiredAccess,
    IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
    IN PLARGE_INTEGER MaximumSize,
    IN ULONG SectionPageProtection,
    IN ULONG AllocationAttributes,
    IN HANDLE FileHandle OPTIONAL,
    IN PFILE_OBJECT FileObject OPTIONAL
    )

/*++

Routine Description:

    This function creates a section object and opens a handle to the object
    with the specified desired access.

Arguments:

    Section - A pointer to a variable that will
        receive the section object address.

    DesiredAccess - The desired types of access for the
         section.

    DesiredAccess Flags


         EXECUTE - Execute access to the section is
              desired.

         READ - Read access to the section is desired.

         WRITE - Write access to the section is desired.


    ObjectAttributes - Supplies a pointer to an object attributes structure.

    MaximumSize - Supplies the maximum size of the section in bytes.
         This value is rounded up to the host page size and
         specifies the size of the section (page file
         backed section) or the maximum size to which a
         file can be extended or mapped (file backed
         section).

    SectionPageProtection - Supplies the protection to place on each page
         in the section.  One of PAGE_READ, PAGE_READWRITE, PAGE_EXECUTE,
         or PAGE_WRITECOPY and, optionally, PAGE_NOCACHE may be specified.

    AllocationAttributes - Supplies a set of flags that describe the
         allocation attributes of the section.

        AllocationAttributes Flags

        SEC_BASED - The section is a based section and will be
            allocated at the same virtual address in each process
            address space that receives the section.  This does not
            imply that addresses are reserved for based sections.
            Rather if the section cannot be mapped at the based address
            an error is returned.

        SEC_RESERVE - All pages of the section are set to the
            reserved state.

        SEC_COMMIT - All pages of the section are set to the commit
            state.

        SEC_IMAGE - The file specified by the file handle is an
                    executable image file.

        SEC_FILE - The file specified by the file handle is a mapped
                   file.  If a file handle is supplied and neither
                   SEC_IMAGE or SEC_FILE is supplied, SEC_FILE is
                   assumed.

    FileHandle - Supplies an optional handle of an open file object.
         If the value of this handle is null, then the
         section will be backed by a paging file. Otherwise
         the section is backed by the specified data file.

    FileObject - Supplies an optional pointer to the file object.  If this
           value is NULL and the FileHandle is NULL, then there is
           no file to map (image or mapped file).  If this value
           is specified, then the File is to be mapped as a MAPPED FILE
           and NO file size checking will be performed.

           ONLY THE SYSTEM CACHE SHOULD PROVIDE A FILE OBJECT WITH THE CALL!!
           as this is optimized to not check the size, only do data mapping,
           no protection check, etc.

    Note - Only one of FileHandle or File should be specified!

Return Value:

    Returns the status

    TBS


--*/

{
    SECTION Section;
    PSECTION NewSection;
    PSEGMENT Segment;
    PSEGMENT NewSegment;
    KPROCESSOR_MODE PreviousMode;
    KIRQL OldIrql;
    NTSTATUS Status;
    PCONTROL_AREA ControlArea;
    PCONTROL_AREA NewControlArea;
    PCONTROL_AREA SegmentControlArea;
    ACCESS_MASK FileDesiredAccess;
    PFILE_OBJECT File;
    PEVENT_COUNTER Event;
    ULONG IgnoreFileSizing = FALSE;
    ULONG ProtectionMask;
    ULONG ProtectMaskForAccess;
    ULONG FileAcquired = FALSE;
    PEVENT_COUNTER SegmentEvent;
    BOOLEAN FileSizeChecked = FALSE;
    LARGE_INTEGER TempSectionSize;
    LARGE_INTEGER EndOfFile;
    ULONG IncrementedRefCount = FALSE;
    PFILE_OBJECT ChangeFileReference = NULL;
#if DBG
    PVOID PreviousSectionPointer;
#endif //DBG

    DesiredAccess;

#if DBG
    if (MmDebug & MM_DBG_SHOW_NT_CALLS) {
        if ( !MmWatchProcess ) {
            DbgPrint("crea sect access mask %lx maxsize %lx  page prot %lx\n",
                DesiredAccess, MaximumSize->LowPart, SectionPageProtection);
            DbgPrint("     allocation attributes %lx file handle %lx\n",
                AllocationAttributes, FileHandle);
        }
    }
#endif

    //
    // Check allocation attributes flags.
    //

    File = (PFILE_OBJECT)NULL;

    ASSERT ((AllocationAttributes & ~(SEC_COMMIT | SEC_RESERVE | SEC_BASED |
            SEC_IMAGE | SEC_NOCACHE | SEC_NO_CHANGE)) == 0);

    ASSERT ((AllocationAttributes & (SEC_COMMIT | SEC_RESERVE | SEC_IMAGE)) != 0);

    ASSERT (!((AllocationAttributes & SEC_IMAGE) &&
            (AllocationAttributes & (SEC_COMMIT | SEC_RESERVE | SEC_NOCACHE | SEC_NO_CHANGE))));

    ASSERT (!((AllocationAttributes & SEC_COMMIT) &&
            (AllocationAttributes & SEC_RESERVE)));

    ASSERT (!((SectionPageProtection & PAGE_NOCACHE) ||
        (SectionPageProtection & PAGE_GUARD) ||
        (SectionPageProtection & PAGE_NOACCESS)));

    if (AllocationAttributes & SEC_NOCACHE) {
        SectionPageProtection |= PAGE_NOCACHE;
    }

    //
    // Check the protection field.  This could raise an exception.
    //

    try {
        ProtectionMask = MiMakeProtectionMask (SectionPageProtection);
    } except (EXCEPTION_EXECUTE_HANDLER) {
        return GetExceptionCode();
    }

    ProtectMaskForAccess = ProtectionMask & 0x7;

    FileDesiredAccess = MmMakeFileAccess[ProtectMaskForAccess];

    //
    // Get previous processor mode and probe output arguments if necessary.
    //

    PreviousMode = KeGetPreviousMode();

    Section.InitialPageProtection = SectionPageProtection;
    Section.Segment = (PSEGMENT)NULL;

    if (ARGUMENT_PRESENT(FileHandle) || ARGUMENT_PRESENT(FileObject)) {

        if (ARGUMENT_PRESENT(FileObject)) {
            IgnoreFileSizing = TRUE;
            File = FileObject;

            //
            // Quick check to see if a control area already exists.
            //

            if (File->SectionObjectPointer->DataSectionObject) {

                LOCK_PFN (OldIrql);
                ControlArea =
                    (PCONTROL_AREA)(File->SectionObjectPointer->DataSectionObject);

                if ((ControlArea != NULL) &&
                    (!ControlArea->u.Flags.BeingDeleted) &&
                    (!ControlArea->u.Flags.BeingCreated)) {

                    //
                    // Control area exists and is not being deleted,
                    // reference it.
                    //

                    NewSegment = ControlArea->Segment;
                    if ((ControlArea->NumberOfSectionReferences == 0) &&
                        (ControlArea->NumberOfMappedViews == 0) &&
                        (ControlArea->ModifiedWriteCount == 0)) {

                        //
                        // Dereference the current file object and
                        // reference this one.
                        //

                        ChangeFileReference = ControlArea->FilePointer;
                        ControlArea->FilePointer = FileObject;

                        //
                        // This dereference is purposely at DPC_LEVEL
                        // so the object manager queues it to another
                        // thread thereby eliminating deadlocks with
                        // the redirector.
                        //

                        ObDereferenceObject (ChangeFileReference);
                    }
                    ControlArea->NumberOfSectionReferences += 1;
                    IncrementedRefCount = TRUE;
                    UNLOCK_PFN (OldIrql);
                    Section.SizeOfSection = *MaximumSize;

                    goto ReferenceObject;
                }
                UNLOCK_PFN (OldIrql);
            }

            ObReferenceObject (FileObject);

        } else {

            //
            // Only one of FileHandle or FileObject should be supplied
            // if a FileObject is supplied, this must be from the
            // file system and therefore the file's size should not
            // be checked.
            //

            Status = ObReferenceObjectByHandle ( FileHandle,
                                                 FileDesiredAccess,
                                                 IoFileObjectType,
                                                 PreviousMode,
                                                 (PVOID *)&File,
                                                 NULL );
            if (!NT_SUCCESS(Status)) {
                return Status;
            }

            //
            // If this file doesn't have a section object pointer,
            // return an error.
            //

            if (File->SectionObjectPointer == NULL) {
                ObDereferenceObject (File);
                return STATUS_INVALID_FILE_FOR_SECTION;
            }
        }

        //
        // Check to see if the specified file already has a section.
        // If not, indicate in the file object's pointer to an FCB that
        // a section is being built.  This synchronizes segment creation
        // for the file.
        //

        NewControlArea = ExAllocatePoolWithTag (NonPagedPool,
                                         (ULONG)sizeof(CONTROL_AREA) +
                                                (ULONG)sizeof(SUBSECTION),
                                                MMCONTROL);

        if (NewControlArea == NULL) {
            ObDereferenceObject (File);
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        RtlZeroMemory (NewControlArea,
                       sizeof(CONTROL_AREA) + sizeof(SUBSECTION));
        NewSegment = (PSEGMENT)NULL;

        //
        // We only need the file resource if the was a user request, i.e. not
        // a call from the cache manager or file system.
        //

        if (ARGUMENT_PRESENT(FileHandle)) {

            FsRtlAcquireFileExclusive (File);
            IoSetTopLevelIrp((PIRP)FSRTL_FSP_TOP_LEVEL_IRP);
            FileAcquired = TRUE;
        }

        LOCK_PFN (OldIrql);

        //
        // Allocate an event to wait on in case the segment is in the
        // process of being deleted.  This event cannot be allocated
        // with the PFN database locked as pool expansion would deadlock.
        //

        SegmentEvent = MiGetEventCounter();

RecheckSegment:

        if (AllocationAttributes & SEC_IMAGE) {
            ControlArea =
               (PCONTROL_AREA)(File->SectionObjectPointer->ImageSectionObject);

        } else {
            ControlArea =
               (PCONTROL_AREA)(File->SectionObjectPointer->DataSectionObject);
        }

        if (ControlArea != NULL) {

            //
            // A segment already exists for this file.  Make sure that it
            // is not in the process of being deleted, or being created.
            //


            if ((ControlArea->u.Flags.BeingDeleted) ||
                (ControlArea->u.Flags.BeingCreated)) {

                //
                // The segment object is in the process of being deleted or
                // created.
                // Check to see if another thread is waiting for the deletion,
                // otherwise create and event object to wait upon.
                //

                if (ControlArea->WaitingForDeletion == NULL) {

                    //
                    // Initialize an event a put it's address in the control area.
                    //

                    ControlArea->WaitingForDeletion = SegmentEvent;
                    Event = SegmentEvent;
                    SegmentEvent = NULL;
                } else {
                    Event = ControlArea->WaitingForDeletion;
                    Event->RefCount += 1;
                }

                //
                // Release the pfn lock, the file lock, and wait for the event.
                //

                UNLOCK_PFN (OldIrql);
                if (FileAcquired) {
                    IoSetTopLevelIrp((PIRP)NULL);
                    FsRtlReleaseFile (File);
                }

                KeWaitForSingleObject(&Event->Event,
                                      WrVirtualMemory,
                                      KernelMode,
                                      FALSE,
                                      (PLARGE_INTEGER)NULL);

                if (FileAcquired) {
                    FsRtlAcquireFileExclusive (File);
                    IoSetTopLevelIrp((PIRP)FSRTL_FSP_TOP_LEVEL_IRP);
                }

                LOCK_PFN (OldIrql);
                MiFreeEventCounter (Event, TRUE);

                if (SegmentEvent == NULL) {

                    //
                    // The event was freed from pool, allocate another
                    // event in case we have to synchronize one more time.
                    //

                    SegmentEvent = MiGetEventCounter();
                }
                goto RecheckSegment;

            } else {

                //
                // There is already a segment for this file, have
                // this section refer to that segment.
                // No need to reference the file object any more.
                //

                NewSegment = ControlArea->Segment;
                ControlArea->NumberOfSectionReferences += 1;
                IncrementedRefCount = TRUE;

                //
                // If this reference was not from the cache manager
                // up the count of user references.
                //

                if (IgnoreFileSizing == FALSE) {
                    ControlArea->NumberOfUserReferences += 1;
                }
            }
        } else {

            //
            // There is no segment associated with this file object.
            // Set the file object to refer to the new control area.
            //

            ControlArea = NewControlArea;
            ControlArea->u.Flags.BeingCreated = 1;

            if (AllocationAttributes & SEC_IMAGE) {
                ((PCONTROL_AREA)((File->SectionObjectPointer->ImageSectionObject))) =
                                                                ControlArea;
            } else {
#if DBG
                PreviousSectionPointer = File->SectionObjectPointer;
#endif //DBG
                ((PCONTROL_AREA)((File->SectionObjectPointer->DataSectionObject))) =
                                                                ControlArea;
            }
        }

        if (SegmentEvent != NULL) {
            MiFreeEventCounter (SegmentEvent, TRUE);
        }

        UNLOCK_PFN (OldIrql);

        if (NewSegment != (PSEGMENT)NULL) {

            //
            // Whether we created a segment or not, lets flush the data section
            // if there is one.
            //

            if ((AllocationAttributes & SEC_IMAGE) &&
                (File->SectionObjectPointer->DataSectionObject)) {

                IO_STATUS_BLOCK IoStatus;

                if (((PCONTROL_AREA)((File->SectionObjectPointer->DataSectionObject)))->NumberOfSystemCacheViews) {
                    CcFlushCache (File->SectionObjectPointer,
                                  NULL,
                                  0,
                                  &IoStatus);

                } else {
                    MmFlushSection (File->SectionObjectPointer,
                                    NULL,
                                    0,
                                    &IoStatus,
                                    TRUE);
                }
            }

            //
            // A segment already exists for this file object.
            // Deallocate the new control area as it is no longer required
            // and dereference the file object.
            //

            ExFreePool (NewControlArea);
            ObDereferenceObject (File);

            //
            // The section is in paged pool, this can't be set until
            // the PFN mutex has been released.
            //

            if ((!IgnoreFileSizing) && (ControlArea->u.Flags.Image == 0)) {

                //
                // The file size in the segment may not match the current
                // file size, query the file system and get the file
                // size.
                //

                Status = FsRtlGetFileSize (File, &EndOfFile );

                if (!NT_SUCCESS (Status)) {
                    goto UnrefAndReturn;
                }

                if ((EndOfFile.QuadPart== 0) &&
                    (MaximumSize->QuadPart == 0)) {

                    //
                    // Can't map a zero length without specifying the maximum
                    // size as non-zero.
                    //

                    Status = STATUS_MAPPED_FILE_SIZE_ZERO;
                    goto UnrefAndReturn;
                }
            } else {

                //
                // The size is okay in the segment.
                //

                EndOfFile = NewSegment->SizeOfSegment;
            }

            if (MaximumSize->QuadPart == 0) {

                Section.SizeOfSection = EndOfFile;
                FileSizeChecked = TRUE;

            } else if (EndOfFile.QuadPart >= MaximumSize->QuadPart) {

                //
                // EndOfFile is greater than the MaximumSize,
                // use the specified maximum size.
                //

                Section.SizeOfSection = *MaximumSize;
                FileSizeChecked = TRUE;

            } else {

                //
                // Need to extend the section, make sure the file was
                // opened for write access.
                //

                if (((SectionPageProtection & PAGE_READWRITE) |
                    (SectionPageProtection & PAGE_EXECUTE_READWRITE)) == 0) {

                    Status = STATUS_SECTION_TOO_BIG;
                    goto UnrefAndReturn;
                }
                Section.SizeOfSection = *MaximumSize;
            }

        } else {

            //
            // The file does not have an associated segment, create a segment
            // object.
            //

            if (AllocationAttributes & SEC_IMAGE) {

                Status = MiCreateImageFileMap (File,
                                               &Segment);

            } else {

                Status = MiCreateDataFileMap (File,
                                              &Segment,
                                              MaximumSize,
                                              SectionPageProtection,
                                              AllocationAttributes,
                                              IgnoreFileSizing );
                ASSERT (PreviousSectionPointer == File->SectionObjectPointer);
            }

            if (!NT_SUCCESS(Status)) {

                //
                // Lock the PFN database and check to see if another thread has
                // tried to create a segment to the file object at the same
                // time.
                //

                LOCK_PFN (OldIrql);

                Event = ControlArea->WaitingForDeletion;
                ControlArea->WaitingForDeletion = NULL;
                ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
                ControlArea->u.Flags.FilePointerNull = 1;

                if (AllocationAttributes & SEC_IMAGE) {
                    (PCONTROL_AREA)((File->SectionObjectPointer->ImageSectionObject)) =
                                                                        NULL;
                } else {
                    (PCONTROL_AREA)((File->SectionObjectPointer->DataSectionObject)) =
                                                                        NULL;
                }
                ControlArea->u.Flags.BeingCreated = 0;

                UNLOCK_PFN (OldIrql);

                if (FileAcquired) {
                    IoSetTopLevelIrp((PIRP)NULL);
                    FsRtlReleaseFile (File);
                }

                ExFreePool (NewControlArea);

                ObDereferenceObject (File);

                if (Event != NULL) {

                    //
                    // Signal any waiters that the segment structure exists.
                    //

                    KeSetEvent (&Event->Event, 0, FALSE);
                }

                return Status;
            }

            //
            // If the size was specified as zero, set the section size
            // from the created segment size.  This solves problems with
            // race conditions when multiple sections
            // are created for the same mapped file with varying sizes.
            //

            if (MaximumSize->QuadPart == 0) {
                Section.SizeOfSection = Segment->SizeOfSegment;
            } else {
                Section.SizeOfSection = *MaximumSize;
            }
        }

    } else {

        //
        // No file handle exists, this is a page file backed section.
        //

        if (AllocationAttributes & SEC_IMAGE) {
            return STATUS_INVALID_FILE_FOR_SECTION;
        }

        Status = MiCreatePagingFileMap ( &NewSegment,
                                         MaximumSize,
                                         ProtectionMask,
                                         AllocationAttributes);

        if (!NT_SUCCESS(Status)) {
            return Status;
        }

        //
        // Set the section size from the created segment size.  This
        // solves problems with race conditions when multiple sections
        // are created for the same mapped file with varying sizes.
        //

        Section.SizeOfSection = NewSegment->SizeOfSegment;
        ControlArea = NewSegment->ControlArea;
    }

#if DBG
    if (MmDebug & MM_DBG_SECTIONS) {
        if (NewSegment == (PSEGMENT)NULL) {
            DbgPrint("inserting segment %lx control %lx\n",Segment,
                        Segment->ControlArea);
        } else {
            DbgPrint("inserting segment %lx control %lx\n",NewSegment,
                        NewSegment->ControlArea);
        }
    }
#endif


    if (NewSegment == (PSEGMENT)NULL) {
        NewSegment = Segment;

        //
        // Lock the PFN database and check to see if another thread has
        // tried to create a segment to the file object at the same time.
        //

        SegmentControlArea = Segment->ControlArea;

        ASSERT (File != NULL);

        LOCK_PFN (OldIrql);

        Event = ControlArea->WaitingForDeletion;
        ControlArea->WaitingForDeletion = NULL;

        if (AllocationAttributes & SEC_IMAGE) {

            //
            // Change the control area in the file object pointer.
            //

            ((PCONTROL_AREA)(File->SectionObjectPointer->ImageSectionObject)) =
                                                         SegmentControlArea;

            ControlArea = SegmentControlArea;
        }

        ControlArea->u.Flags.BeingCreated = 0;

        UNLOCK_PFN (OldIrql);

        if (AllocationAttributes & SEC_IMAGE) {

            //
            // Deallocate the pool used for the original control area.
            //

            ExFreePool (NewControlArea);
        }

        if (Event != NULL) {

            //
            // Signal any waiters that the segment structure exists.
            //

            KeSetEvent (&Event->Event, 0, FALSE);
        }
    }

    //
    // Being created has now been cleared allowing other threads
    // to reference the segment.  Release the resource on the file.
    //

    if (FileAcquired) {
        IoSetTopLevelIrp((PIRP)NULL);
        FsRtlReleaseFile (File);
        FileAcquired = FALSE;
    }

ReferenceObject:

    if (ChangeFileReference) {
        ObReferenceObject (FileObject);
    }

    //
    // Now that the segment object is created, make the section object
    // refer to the segment object.
    //

    Section.Segment = NewSegment;
    Section.u.LongFlags = ControlArea->u.LongFlags;

    //
    // Create the section object now.  The section object is created
    // now so that the error handling when the section object cannot
    // be created is simplified.
    //

    Status = ObCreateObject (PreviousMode,
                             MmSectionObjectType,
                             ObjectAttributes,
                             PreviousMode,
                             NULL,
                             sizeof(SECTION),
                             sizeof(SECTION) +
                                 NewSegment->TotalNumberOfPtes * sizeof(MMPTE),
                             sizeof(CONTROL_AREA) +
                                 NewSegment->ControlArea->NumberOfSubsections *
                                   sizeof(SUBSECTION),
                             (PVOID *)&NewSection);

    if (!NT_SUCCESS(Status)) {
        goto UnrefAndReturn;
    }

    RtlMoveMemory (NewSection, &Section, sizeof(SECTION));
    NewSection->Address.StartingVa = NULL;

    if (!IgnoreFileSizing) {

        //
        // Indicate that the cache manager is not the owner of this
        // section.
        //

        NewSection->u.Flags.UserReference = 1;

        if (AllocationAttributes & SEC_NO_CHANGE) {

            //
            // Indicate that once the section is mapped, no protection
            // changes or freeing the mapping is allowed.
            //

            NewSection->u.Flags.NoChange = 1;
        }

        if (((SectionPageProtection & PAGE_READWRITE) |
            (SectionPageProtection & PAGE_EXECUTE_READWRITE)) == 0) {

            //
            // This section does not support WRITE access, indicate
            // that changing the protection to WRITE results in COPY_ON_WRITE.
            //

            NewSection->u.Flags.CopyOnWrite = 1;
        }

        if (AllocationAttributes & SEC_BASED) {

            NewSection->u.Flags.Based = 1;

            //
            // Get the allocation base mutex.
            //

            ExAcquireFastMutex (&MmSectionBasedMutex);

            //
            // This section is based at a unique address system wide.
            //

            try {
                NewSection->Address.StartingVa = (PVOID)MiFindEmptySectionBaseDown (
                                                     NewSection->SizeOfSection.LowPart,
                                                     MmHighSectionBase);
            } except (EXCEPTION_EXECUTE_HANDLER) {
                ExReleaseFastMutex (&MmSectionBasedMutex);
                ObDereferenceObject (NewSection);
                return Status;
            }

            NewSection->Address.EndingVa =
                                (PVOID)((ULONG)NewSection->Address.StartingVa +
                                            NewSection->SizeOfSection.LowPart - 1);

            MiInsertBasedSection (NewSection);
            ExReleaseFastMutex (&MmSectionBasedMutex);
        }
    }

    //
    // If the cache manager is creating the section, set the was
    // purged flag as the file size can change.
    //

    ControlArea->u.Flags.WasPurged |= IgnoreFileSizing;

    //
    // Check to see if the section is for a data file and the size
    // of the section is greater than the current size of the
    // segment.
    //

    if (((ControlArea->u.Flags.WasPurged == 1) && (!IgnoreFileSizing)) &&
                      (!FileSizeChecked)
                            ||
        (NewSection->SizeOfSection.QuadPart >
                                NewSection->Segment->SizeOfSegment.QuadPart)) {

        TempSectionSize = NewSection->SizeOfSection;

        NewSection->SizeOfSection = NewSection->Segment->SizeOfSegment;

        Status = MmExtendSection (NewSection,
                                  &TempSectionSize,
                                  IgnoreFileSizing);

        if (!NT_SUCCESS(Status)) {
            ObDereferenceObject (NewSection);
            return Status;
        }
    }

    *SectionObject = (PVOID)NewSection;

    return Status;

UnrefAndReturn:

    //
    // Unreference the control area, if it was referenced and return
    // the error status.
    //

    if (FileAcquired) {
        IoSetTopLevelIrp((PIRP)NULL);
        FsRtlReleaseFile (File);
    }

    if (IncrementedRefCount) {
        LOCK_PFN (OldIrql);
        ControlArea->NumberOfSectionReferences -= 1;
        if (!IgnoreFileSizing) {
            ASSERT ((LONG)ControlArea->NumberOfUserReferences > 0);
            ControlArea->NumberOfUserReferences -= 1;
        }
        MiCheckControlArea (ControlArea, NULL, OldIrql);
    }
    return Status;
}

NTSTATUS
MiCreateImageFileMap (
    IN PFILE_OBJECT File,
    OUT PSEGMENT *Segment
    )

/*++

Routine Description:

    This function creates the necessary strutures to allow the mapping
    of an image file.

    The image file is opened and verified for correctness, a segment
    object is created and initialized based on data in the image
    header.

Arguments:

    File - Supplies the file object for the image file.

    Segment - Returns the segment object.

Return Value:

    Returns the status value.

    TBS


--*/

{
    NTSTATUS Status;
    ULONG NumberOfPtes;
    ULONG SizeOfSegment;
    ULONG SectionVirtualSize;
    ULONG i;
    PCONTROL_AREA ControlArea;
    PSUBSECTION Subsection;
    PMMPTE PointerPte;
    MMPTE TempPte;
    MMPTE TempPteDemandZero;
    PVOID Base;
    PIMAGE_DOS_HEADER DosHeader;
    PIMAGE_NT_HEADERS NtHeader;
    PIMAGE_SECTION_HEADER SectionTableEntry;
    PSEGMENT NewSegment;
    ULONG SectorOffset;
    ULONG NumberOfSubsections;
    ULONG PageFrameNumber;
    LARGE_INTEGER StartingOffset;
    PCHAR ExtendedHeader = NULL;
    PULONG Page;
    ULONG PreferredImageBase;
    ULONG NextVa;
    PKEVENT InPageEvent;
    PMDL Mdl;
    ULONG ImageFileSize;
    ULONG OffsetToSectionTable;
    ULONG ImageAlignment;
    ULONG FileAlignment;
    BOOLEAN ImageCommit;
    BOOLEAN SectionCommit;
    IO_STATUS_BLOCK IoStatus;
    LARGE_INTEGER EndOfFile;
    ULONG NtHeaderSize;

#if defined (_ALPHA_)
    BOOLEAN InvalidAlignmentAllowed = FALSE;
#endif


    // *************************************************************
    // Create image file file section.
    // *************************************************************

    PAGED_CODE();

    Status = FsRtlGetFileSize (File, &EndOfFile );

    if (Status == STATUS_FILE_IS_A_DIRECTORY) {

        //
        // Can't map a directory as a section. Return error.
        //

        return STATUS_INVALID_FILE_FOR_SECTION;
    }

    if (!NT_SUCCESS (Status)) {
        return Status;
    }

    if (EndOfFile.HighPart != 0) {

        //
        // File too big. Return error.
        //

        return STATUS_INVALID_FILE_FOR_SECTION;
    }

    //
    // Create a segment which maps an image file.
    // For now map a COFF image file with the subsections
    // containing the based address of the file.
    //

    //
    // Read in the file header.
    //

    InPageEvent = ExAllocatePoolWithTag (NonPagedPool,
                                  sizeof(KEVENT) + MmSizeOfMdl (
                                                      NULL,
                                                      MM_MAXIMUM_IMAGE_HEADER),
                                                      MMTEMPORARY);
    if (InPageEvent == NULL) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    Mdl = (PMDL)(InPageEvent + 1);

    //
    // Create an event for the read operation.
    //

    KeInitializeEvent (InPageEvent, NotificationEvent, FALSE);

    //
    // Build an MDL for the operation.
    //

    (VOID) MmCreateMdl( Mdl, NULL, PAGE_SIZE);
    Mdl->MdlFlags |= MDL_PAGES_LOCKED;

    PageFrameNumber = MiGetPageForHeader();

    Page = (PULONG)(Mdl + 1);
    *Page = PageFrameNumber;

    ZERO_LARGE (StartingOffset);

    CcZeroEndOfLastPage (File);

    //
    //  Lets flush the data section if there is one.
    //

    if (File->SectionObjectPointer->DataSectionObject) {
        IO_STATUS_BLOCK IoStatus;
        if (((PCONTROL_AREA)((File->SectionObjectPointer->DataSectionObject)))->NumberOfSystemCacheViews) {
            CcFlushCache (File->SectionObjectPointer,
                          NULL,
                          0,
                          &IoStatus);

        } else {
            MmFlushSection (File->SectionObjectPointer,
                            NULL,
                            0,
                            &IoStatus,
                            TRUE);
        }
    }

    Mdl->MdlFlags |= MDL_PAGES_LOCKED;
    Status = IoPageRead (File,
                         Mdl,
                         &StartingOffset,
                         InPageEvent,
                         &IoStatus
                        );

    if (Status == STATUS_PENDING) {
        KeWaitForSingleObject( InPageEvent,
                               WrPageIn,
                               KernelMode,
                               FALSE,
                               (PLARGE_INTEGER)NULL);
    }

    if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
        MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
    }

    if ((!NT_SUCCESS(Status)) || (!NT_SUCCESS(IoStatus.Status))) {
        if (Status != STATUS_FILE_LOCK_CONFLICT) {
            Status = STATUS_INVALID_FILE_FOR_SECTION;
        }
        goto BadSection;
    }

    Base = MiMapImageHeaderInHyperSpace (PageFrameNumber);
    DosHeader = (PIMAGE_DOS_HEADER)Base;

    if (IoStatus.Information != PAGE_SIZE) {

        //
        // A full page was not read from the file, zero any remaining
        // bytes.
        //

        RtlZeroMemory ((PVOID)((ULONG)Base + IoStatus.Information),
                       PAGE_SIZE - IoStatus.Information);
    }

    //
    // Check to determine if this is an NT image (PE format) or
    // a DOS image, Win-16 image, or OS/2 image.  If the image is
    // not NT format, return an error indicating which image it
    // appears to be.
    //

    if (DosHeader->e_magic != IMAGE_DOS_SIGNATURE) {

        Status = STATUS_INVALID_IMAGE_NOT_MZ;
        goto NeImage;
    }

#ifndef i386
    if (((ULONG)DosHeader->e_lfanew & 3) != 0) {

        //
        // The image header is not aligned on a longword boundary.
        // Report this as an invalid protect mode image.
        //

        Status = STATUS_INVALID_IMAGE_PROTECT;
        goto NeImage;
    }
#endif

    if ((ULONG)DosHeader->e_lfanew > EndOfFile.LowPart) {
        Status = STATUS_INVALID_IMAGE_PROTECT;
        goto NeImage;
    }

    if (((ULONG)DosHeader->e_lfanew +
            sizeof(IMAGE_NT_HEADERS) +
            (16 * sizeof(IMAGE_SECTION_HEADER))) > PAGE_SIZE) {

        //
        // The PE header is not within the page already read or the
        // objects are in another page.
        // Build another MDL and read an additional 8k.
        //

        ExtendedHeader = ExAllocatePoolWithTag (NonPagedPool,
                                         MM_MAXIMUM_IMAGE_HEADER,
                                         MMTEMPORARY);
        if (ExtendedHeader == NULL) {
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto NeImage;
        }

        //
        // Build an MDL for the operation.
        //

        (VOID) MmCreateMdl( Mdl, ExtendedHeader, MM_MAXIMUM_IMAGE_HEADER);

        MmBuildMdlForNonPagedPool (Mdl);

        StartingOffset.LowPart = (ULONG)PAGE_ALIGN ((ULONG)DosHeader->e_lfanew);

        KeClearEvent (InPageEvent);
        Status = IoPageRead (File,
                             Mdl,
                             &StartingOffset,
                             InPageEvent,
                             &IoStatus
                            );

        if (Status == STATUS_PENDING) {
            KeWaitForSingleObject( InPageEvent,
                                   WrPageIn,
                                   KernelMode,
                                   FALSE,
                                   (PLARGE_INTEGER)NULL);
        }

        if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
            MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
        }

        if ((!NT_SUCCESS(Status)) || (!NT_SUCCESS(IoStatus.Status))) {
            if (Status != STATUS_FILE_LOCK_CONFLICT) {
                Status = STATUS_INVALID_FILE_FOR_SECTION;
            }
            goto NeImage;
        }
        NtHeader = (PIMAGE_NT_HEADERS)((ULONG)ExtendedHeader +
                          BYTE_OFFSET((ULONG)DosHeader->e_lfanew));
        NtHeaderSize = MM_MAXIMUM_IMAGE_HEADER -
                            (ULONG)(BYTE_OFFSET((ULONG)DosHeader->e_lfanew));

    } else {
        NtHeader = (PIMAGE_NT_HEADERS)((ULONG)DosHeader +
                                          (ULONG)DosHeader->e_lfanew);
        NtHeaderSize = PAGE_SIZE - (ULONG)DosHeader->e_lfanew;
    }

    //
    // Check to see if this is an NT image or a DOS or OS/2 image.
    //

    Status = MiVerifyImageHeader (NtHeader, DosHeader, NtHeaderSize);
    if (Status != STATUS_SUCCESS) {
        goto NeImage;
    }

    ImageAlignment = NtHeader->OptionalHeader.SectionAlignment;
    FileAlignment = NtHeader->OptionalHeader.FileAlignment - 1;
    NumberOfSubsections = NtHeader->FileHeader.NumberOfSections;

    if (ImageAlignment < PAGE_SIZE) {

        //
        // The image alignment is less than the page size,
        // map the image with a single subsection.
        //

        ControlArea = ExAllocatePoolWithTag (NonPagedPool,
                      (ULONG)(sizeof(CONTROL_AREA) + (sizeof(SUBSECTION))),
                      MMCONTROL);
    } else {

        //
        // Allocate a control area and a subsection for each section
        // header plus one for the image header which has no section.
        //

        ControlArea = ExAllocatePoolWithTag(NonPagedPool,
                                            (ULONG)(sizeof(CONTROL_AREA) +
                                                    (sizeof(SUBSECTION) *
                                                (NumberOfSubsections + 1))),
                                            'iCmM');
    }

    if (ControlArea == NULL) {

        //
        // The requested pool could not be allocated.
        //

        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto NeImage;
    }

    //
    // Zero the control area and the FIRST subsection.
    //

    RtlZeroMemory (ControlArea,
                   sizeof(CONTROL_AREA) + sizeof(SUBSECTION));

    Subsection = (PSUBSECTION)(ControlArea + 1);

    NumberOfPtes = BYTES_TO_PAGES (NtHeader->OptionalHeader.SizeOfImage);

    SizeOfSegment = sizeof(SEGMENT) + sizeof(MMPTE) * (NumberOfPtes - 1);

    NewSegment = ExAllocatePoolWithTag (PagedPool,
                                        SizeOfSegment,
                                        MMSECT);

    if (NewSegment == NULL) {

        //
        // The requested pool could not be allocated.
        //

        ExFreePool (ControlArea);
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto NeImage;
    }
    *Segment = NewSegment;
    RtlZeroMemory (NewSegment, sizeof(SEGMENT));

    //
    // Align the prototype PTEs on the proper boundary.
    //

    PointerPte = &NewSegment->ThePtes[0];
    i = ((ULONG)PointerPte >> PTE_SHIFT) &
                    ((MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - 1);

    if (i != 0) {
        i = (MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - i;
    }

    NewSegment->PrototypePte = &NewSegment->ThePtes[i];

    NewSegment->ControlArea = ControlArea;
    NewSegment->TotalNumberOfPtes = NumberOfPtes;
    NewSegment->NonExtendedPtes = NumberOfPtes;
    NewSegment->SizeOfSegment.LowPart = NumberOfPtes * PAGE_SIZE;

    NewSegment->ImageInformation.TransferAddress =
                    (PVOID)(NtHeader->OptionalHeader.ImageBase +
                            NtHeader->OptionalHeader.AddressOfEntryPoint);
    NewSegment->ImageInformation.MaximumStackSize =
                            NtHeader->OptionalHeader.SizeOfStackReserve;
    NewSegment->ImageInformation.CommittedStackSize =
                            NtHeader->OptionalHeader.SizeOfStackCommit;
    NewSegment->ImageInformation.SubSystemType =
                            NtHeader->OptionalHeader.Subsystem;
    NewSegment->ImageInformation.SubSystemMajorVersion = (USHORT)(NtHeader->OptionalHeader.MajorSubsystemVersion);
    NewSegment->ImageInformation.SubSystemMinorVersion = (USHORT)(NtHeader->OptionalHeader.MinorSubsystemVersion);
    NewSegment->ImageInformation.ImageCharacteristics =
                            NtHeader->FileHeader.Characteristics;
    NewSegment->ImageInformation.DllCharacteristics =
                            NtHeader->OptionalHeader.DllCharacteristics;
    NewSegment->ImageInformation.Machine =
                            NtHeader->FileHeader.Machine;
    NewSegment->ImageInformation.ImageContainsCode =
                            (BOOLEAN)(NtHeader->OptionalHeader.SizeOfCode != 0);
    NewSegment->ImageInformation.Spare1 = FALSE;
    NewSegment->ImageInformation.LoaderFlags = 0;
    NewSegment->ImageInformation.Reserved[0] = 0;
    NewSegment->ImageInformation.Reserved[1] = 0;

    ControlArea->Segment = NewSegment;
    ControlArea->NumberOfSectionReferences = 1;
    ControlArea->NumberOfUserReferences = 1;
    ControlArea->u.Flags.BeingCreated = 1;

    if (ImageAlignment < PAGE_SIZE) {

        //
        // Image alignment is less than a page, the number
        // of subsections is 1.
        //

        ControlArea->NumberOfSubsections = 1;
    } else {
        ControlArea->NumberOfSubsections = (USHORT)NumberOfSubsections;
    }

    ControlArea->u.Flags.Image = 1;
    ControlArea->u.Flags.File = 1;

    if ((FILE_FLOPPY_DISKETTE & File->DeviceObject->Characteristics) ||
        ((NtHeader->FileHeader.Characteristics &
                IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP) &&
         (FILE_REMOVABLE_MEDIA & File->DeviceObject->Characteristics)) ||
        ((NtHeader->FileHeader.Characteristics &
                IMAGE_FILE_NET_RUN_FROM_SWAP) &&
         (FILE_REMOTE_DEVICE & File->DeviceObject->Characteristics))) {

        //
        // This file resides on a floppy disk or a removable media or
        // network with with flags set indicating it should be copied
        // to the paging file.
        //

        ControlArea->u.Flags.FloppyMedia = 1;
    }

    if (FILE_REMOTE_DEVICE & File->DeviceObject->Characteristics) {

        //
        // This file resides on a redirected drive.
        //

        ControlArea->u.Flags.Networked = 1;
    }

    ControlArea->FilePointer = File;

    //
    // Build the subsection and prototype PTEs for the image header.
    //

    Subsection->ControlArea = ControlArea;
    NextVa = NtHeader->OptionalHeader.ImageBase;

    if ((NextVa & (X64K - 1)) != 0) {

        //
        // Image header is not aligned on a 64k boundary.
        //

        goto BadPeImageSegment;
    }

    NewSegment->BasedAddress = (PVOID)NextVa;
    Subsection->PtesInSubsection = MI_ROUND_TO_SIZE (
                                       NtHeader->OptionalHeader.SizeOfHeaders,
                                       ImageAlignment
                                   ) >> PAGE_SHIFT;

    PointerPte = NewSegment->PrototypePte;
    Subsection->SubsectionBase = PointerPte;

    TempPte.u.Long = (ULONG)MiGetSubsectionAddressForPte(Subsection);
    TempPte.u.Soft.Prototype = 1;

    NewSegment->SegmentPteTemplate = TempPte;
    SectorOffset = 0;

    if (ImageAlignment < PAGE_SIZE) {

        //
        // Aligned on less than a page size boundary.
        // Build a single subsection to refer to the image.
        //

        PointerPte = NewSegment->PrototypePte;

        Subsection->PtesInSubsection = NumberOfPtes;
        Subsection->EndingSector =
                            (ULONG)(EndOfFile.QuadPart >> MMSECTOR_SHIFT);
        Subsection->u.SubsectionFlags.SectorEndOffset =
                              EndOfFile.LowPart & MMSECTOR_MASK;
        Subsection->u.SubsectionFlags.Protection = MM_EXECUTE_WRITECOPY;

        //
        // Set all the PTEs to the execute-read-write protection.
        // The section will control access to these and the segment
        // must provide a method to allow other users to map the file
        // for various protections.
        //

        TempPte.u.Soft.Protection = MM_EXECUTE_WRITECOPY;

        NewSegment->SegmentPteTemplate = TempPte;


#if defined (_ALPHA_)
        //
        // Invalid image alignments are supported for cross platform
        // emulation. Only alpha requires extra handling because page
        // size (8k) is larger than other platforms (4k).
        //


        if (KeGetPreviousMode() != KernelMode &&
            (NtHeader->FileHeader.Machine < USER_SHARED_DATA->ImageNumberLow ||
             NtHeader->FileHeader.Machine > USER_SHARED_DATA->ImageNumberHigh))
          {

            InvalidAlignmentAllowed = TRUE;

            TempPteDemandZero.u.Long = 0;
            TempPteDemandZero.u.Soft.Protection = MM_EXECUTE_WRITECOPY;
            SectorOffset = 0;

            for (i = 0; i < NumberOfPtes; i++) {

                //
                // Set prototype PTEs.
                //

                if (SectorOffset < EndOfFile.LowPart) {

                    //
                    // Data resides on the disk, refer to the control section.
                    //

                    *PointerPte = TempPte;

                } else {

                    //
                    // Data does not reside on the disk, use Demand zero pages.
                    //

                    *PointerPte = TempPteDemandZero;
                }

                SectorOffset += PAGE_SIZE;
                PointerPte += 1;
            }

        } else
#endif
           {

            for (i = 0; i < NumberOfPtes; i++) {

                //
                // Set all the prototype PTEs to refer to the control section.
                //

                *PointerPte = TempPte;
                PointerPte += 1;
            }
        }

        NewSegment->ImageCommitment = NumberOfPtes;


        //
        // Indicate alignment is less than a page.
        //

        TempPte.u.Long = 0;

    } else {

        //
        // Aligmment is PAGE_SIZE of greater.
        //

        if (Subsection->PtesInSubsection > NumberOfPtes) {

            //
            // Inconsistent image, size does not agree with header.
            //

            goto BadPeImageSegment;
        }
        NumberOfPtes -= Subsection->PtesInSubsection;

        Subsection->EndingSector =
                      NtHeader->OptionalHeader.SizeOfHeaders >> MMSECTOR_SHIFT;
        Subsection->u.SubsectionFlags.SectorEndOffset =
                      NtHeader->OptionalHeader.SizeOfHeaders & MMSECTOR_MASK;
        Subsection->u.SubsectionFlags.ReadOnly = 1;
        Subsection->u.SubsectionFlags.CopyOnWrite = 1;
        Subsection->u.SubsectionFlags.Protection = MM_READONLY;

        TempPte.u.Soft.Protection = MM_READONLY;
        NewSegment->SegmentPteTemplate = TempPte;

        for (i = 0; i < Subsection->PtesInSubsection; i++) {

            //
            // Set all the prototype PTEs to refer to the control section.
            //

            if (SectorOffset < NtHeader->OptionalHeader.SizeOfHeaders) {
                *PointerPte = TempPte;
            } else {
                *PointerPte = ZeroPte;
            }
            SectorOffset += PAGE_SIZE;
            PointerPte += 1;
            NextVa += PAGE_SIZE;
        }
    }

    //
    // Build the next subsections.
    //

    PreferredImageBase = NtHeader->OptionalHeader.ImageBase;

    //
    // At this point the object table is read in (if it was not
    // already read in) and may displace the image header.
    //

    SectionTableEntry = NULL;
    OffsetToSectionTable = sizeof(ULONG) +
                              sizeof(IMAGE_FILE_HEADER) +
                              NtHeader->FileHeader.SizeOfOptionalHeader;

    if ((BYTE_OFFSET(NtHeader) + OffsetToSectionTable +
                ((NumberOfSubsections + 1) *
                sizeof (IMAGE_SECTION_HEADER))) <= PAGE_SIZE) {

        //
        // Section tables are within the header which was read.
        //

        SectionTableEntry = (PIMAGE_SECTION_HEADER)((ULONG)NtHeader +
                                OffsetToSectionTable);

    } else {

        //
        // Has an extended header been read in and are the object
        // tables resident?
        //

        if (ExtendedHeader != NULL) {

            SectionTableEntry = (PIMAGE_SECTION_HEADER)
                                    ((PUCHAR)NtHeader + OffsetToSectionTable);

            //
            // Is the whole range of object tables mapped by the
            // extended header?
            //

            if ((((ULONG)SectionTableEntry +
                 ((NumberOfSubsections + 1) *
                    sizeof (IMAGE_SECTION_HEADER))) -
                         (ULONG)ExtendedHeader) >
                                            MM_MAXIMUM_IMAGE_HEADER) {
                SectionTableEntry = NULL;

            }
        }
    }

    if (SectionTableEntry == NULL) {

        //
        // The section table entries are not in the same
        // pages as the other data already read in.  Read in
        // the object table entries.
        //

        if (ExtendedHeader == NULL) {
            ExtendedHeader = ExAllocatePoolWithTag (NonPagedPool,
                                             MM_MAXIMUM_IMAGE_HEADER,
                                             MMTEMPORARY);
            if (ExtendedHeader == NULL) {
                ExFreePool (NewSegment);
                ExFreePool (ControlArea);
                Status = STATUS_INSUFFICIENT_RESOURCES;
                goto NeImage;
            }

            //
            // Build an MDL for the operation.
            //

            (VOID) MmCreateMdl( Mdl, ExtendedHeader, MM_MAXIMUM_IMAGE_HEADER);

            MmBuildMdlForNonPagedPool (Mdl);
        }

        StartingOffset.LowPart = (ULONG)PAGE_ALIGN (
                                    (ULONG)DosHeader->e_lfanew +
                                    OffsetToSectionTable);

        SectionTableEntry = (PIMAGE_SECTION_HEADER)((ULONG)ExtendedHeader +
                                BYTE_OFFSET((ULONG)DosHeader->e_lfanew +
                                OffsetToSectionTable));

        KeClearEvent (InPageEvent);
        Status = IoPageRead (File,
                             Mdl,
                             &StartingOffset,
                             InPageEvent,
                             &IoStatus
                            );

        if (Status == STATUS_PENDING) {
            KeWaitForSingleObject( InPageEvent,
                                   WrPageIn,
                                   KernelMode,
                                   FALSE,
                                   (PLARGE_INTEGER)NULL);
        }

        if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
            MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
        }

        if ((!NT_SUCCESS(Status)) || (!NT_SUCCESS(IoStatus.Status))) {
            if (Status != STATUS_FILE_LOCK_CONFLICT) {
                Status = STATUS_INVALID_FILE_FOR_SECTION;
            }
            ExFreePool (NewSegment);
            ExFreePool (ControlArea);
            goto NeImage;
        }

        //
        // From this point on NtHeader is only valid if it
        // was in the first 4k of the image, otherwise reading in
        // the object tables wiped it out.
        //

    }


    if (TempPte.u.Long == 0) {

        // The image header is no longer valid, TempPte is
        // used to indicate that this image alignment is
        // less than a PAGE_SIZE.

        //
        // Loop through all sections and make sure there is no
        // unitialized data.
        //

        Status = STATUS_SUCCESS;

        while (NumberOfSubsections > 0) {
            if (SectionTableEntry->Misc.VirtualSize == 0) {
                SectionVirtualSize = SectionTableEntry->SizeOfRawData;
            } else {
                SectionVirtualSize = SectionTableEntry->Misc.VirtualSize;
            }


            //
            // if the section goes past the end of file return an error
            //
            if ((SectionTableEntry->SizeOfRawData +
                        SectionTableEntry->PointerToRawData) >
                     EndOfFile.LowPart) {

                KdPrint(("MMCREASECT: invalid section/file size %Z\n",
                     &File->FileName));

                Status = STATUS_INVALID_IMAGE_FORMAT;
                break;
            }



            //
            // if the virtual size and address does not match the rawdata
            // and invalid alignments not allowed return error.
            //
            if (((SectionTableEntry->PointerToRawData !=
                  SectionTableEntry->VirtualAddress))
                            ||
                   (SectionVirtualSize > SectionTableEntry->SizeOfRawData)) {

#if defined (_ALPHA_)
                   if (!InvalidAlignmentAllowed)
#endif
                   {
                       KdPrint(("MMCREASECT: invalid BSS/Trailingzero %Z\n",
                              &File->FileName));

                       Status = STATUS_INVALID_IMAGE_FORMAT;
                       break;
                   }
            }


            SectionTableEntry += 1;
            NumberOfSubsections -= 1;
        }


        if (!NT_SUCCESS(Status)) {
            ExFreePool (NewSegment);
            ExFreePool (ControlArea);
            goto NeImage;
        }


        goto PeReturnSuccess;
    }

    while (NumberOfSubsections > 0) {

        //
        // Handle case where virtual size is 0.
        //

        if (SectionTableEntry->Misc.VirtualSize == 0) {
            SectionVirtualSize = SectionTableEntry->SizeOfRawData;
        } else {
            SectionVirtualSize = SectionTableEntry->Misc.VirtualSize;
        }

        //
        // Fix for Borland linker problem.  The SizeOfRawData can
        // be a zero, but the PointerToRawData is not zero.
        // Set it to zero.
        //

        if (SectionTableEntry->SizeOfRawData == 0) {
            SectionTableEntry->PointerToRawData = 0;
        }

        Subsection += 1;
        Subsection->ControlArea = ControlArea;
        Subsection->NextSubsection = (PSUBSECTION)NULL;
        Subsection->UnusedPtes = 0;

        if ((NextVa !=
                (PreferredImageBase + SectionTableEntry->VirtualAddress)) ||
            (SectionVirtualSize == 0)) {

            //
            // The specified virtual address does not align
            // with the next prototype PTE.
            //

            goto BadPeImageSegment;
        }

        Subsection->PtesInSubsection =
            MI_ROUND_TO_SIZE (SectionVirtualSize, ImageAlignment) >> PAGE_SHIFT;

        if (Subsection->PtesInSubsection > NumberOfPtes) {

            //
            // Inconsistent image, size does not agree with object tables.
            //

            goto BadPeImageSegment;
        }
        NumberOfPtes -= Subsection->PtesInSubsection;

        Subsection->u.LongFlags = 0;
        Subsection->StartingSector =
                        SectionTableEntry->PointerToRawData >> MMSECTOR_SHIFT;

        //
        // Align ending sector on file align boundary.
        //

        Subsection->EndingSector =
                         (SectionTableEntry->PointerToRawData +
                                     SectionTableEntry->SizeOfRawData +
                                     FileAlignment) & ~FileAlignment;

        Subsection->u.SubsectionFlags.SectorEndOffset =
                                    Subsection->EndingSector & MMSECTOR_MASK;
        Subsection->EndingSector = Subsection->EndingSector >> MMSECTOR_SHIFT;

        Subsection->SubsectionBase = PointerPte;

        //
        // Build both a demand zero PTE and a PTE pointing to the
        // subsection.
        //
        TempPte.u.Long = 0;
        TempPteDemandZero.u.Long = 0;

        TempPte.u.Long = (ULONG)MiGetSubsectionAddressForPte(Subsection);
        TempPte.u.Soft.Prototype = 1;
        ImageFileSize = SectionTableEntry->PointerToRawData +
                                    SectionTableEntry->SizeOfRawData;

        TempPte.u.Soft.Protection =
                 MiGetImageProtection (SectionTableEntry->Characteristics);
        TempPteDemandZero.u.Soft.Protection = TempPte.u.Soft.Protection;

        if (SectionTableEntry->PointerToRawData == 0) {
            TempPte = TempPteDemandZero;
        }

        Subsection->u.SubsectionFlags.ReadOnly = 1;
        Subsection->u.SubsectionFlags.CopyOnWrite = 1;
        Subsection->u.SubsectionFlags.Protection = TempPte.u.Soft.Protection;

        if (TempPte.u.Soft.Protection & MM_PROTECTION_WRITE_MASK) {
            if ((TempPte.u.Soft.Protection & MM_COPY_ON_WRITE_MASK)
                                            == MM_COPY_ON_WRITE_MASK) {

                //
                // This page is copy on write, charge ImageCommitment
                // for all pages in this subsection.
                //

                ImageCommit = TRUE;
            } else {

                //
                // This page is write shared, charge commitment when
                // the mapping completes.
                //

                SectionCommit = TRUE;
                Subsection->u.SubsectionFlags.GlobalMemory = 1;
                ControlArea->u.Flags.GlobalMemory = 1;
            }
        } else {

            //
            // Not writable, don't charge commitment at all.
            //

            ImageCommit = FALSE;
            SectionCommit = FALSE;
        }

        NewSegment->SegmentPteTemplate = TempPte;
        SectorOffset = 0;

        for (i = 0; i < Subsection->PtesInSubsection; i++) {

            //
            // Set all the prototype PTEs to refer to the control section.
            //

            if (SectorOffset < SectionVirtualSize) {

                //
                // Make PTE accessable.
                //

                if (SectionCommit) {
                    NewSegment->NumberOfCommittedPages += 1;
                }
                if (ImageCommit) {
                    NewSegment->ImageCommitment += 1;
                }

                if (SectorOffset < SectionTableEntry->SizeOfRawData) {

                    //
                    // Data resides on the disk, use the subsection format
                    // pte.
                    //

                    *PointerPte = TempPte;
                } else {

                    //
                    // Demand zero pages.
                    //

                    *PointerPte = TempPteDemandZero;
                }
            } else {

                //
                // No access pages.
                //

                *PointerPte = ZeroPte;
            }
            SectorOffset += PAGE_SIZE;
            PointerPte += 1;
            NextVa += PAGE_SIZE;
        }

        SectionTableEntry += 1;
        NumberOfSubsections -= 1;
    }

    //
    // If the file size is not as big as the image claimed to be,
    // return an error.
    //

    if (ImageFileSize > EndOfFile.LowPart) {

        //
        // Invalid image size.
        //

        KdPrint(("MMCREASECT: invalid image size - file size %lx - image size %lx\n %Z\n",
            EndOfFile.LowPart, ImageFileSize, &File->FileName));
        goto BadPeImageSegment;
    }

    //
    // The total number of PTEs was decremented as sections were built,
    // make sure that there are less than 64ks worth at this point.
    //

    if (NumberOfPtes >= (ImageAlignment >> PAGE_SHIFT)) {

        //
        // Inconsistent image, size does not agree with object tables.
        //

        KdPrint(("MMCREASECT: invalid image - PTE left %lx\n image name %Z\n",
            NumberOfPtes, &File->FileName));

        goto BadPeImageSegment;
    }

    //
    // Set any remaining PTEs to no access.
    //

    while (NumberOfPtes != 0) {
        *PointerPte = ZeroPte;
        PointerPte += 1;
        NumberOfPtes -= 1;
    }

    //
    // Turn the image header page into a transition page within the
    // prototype PTEs.
    //

    if ((ExtendedHeader == NULL) &&
            (NtHeader->OptionalHeader.SizeOfHeaders < PAGE_SIZE)) {

        //
        // Zero remaining portion of header.
        //

        RtlZeroMemory ((PVOID)((ULONG)Base +
                       NtHeader->OptionalHeader.SizeOfHeaders),
                       PAGE_SIZE - NtHeader->OptionalHeader.SizeOfHeaders);
    }


    if (NewSegment->NumberOfCommittedPages != 0) {
        Status = STATUS_SUCCESS;

        //
        // Commit the pages for the image section.
        //

        try {

            MiChargeCommitment (NewSegment->NumberOfCommittedPages, NULL);
            MmSharedCommit += NewSegment->NumberOfCommittedPages;

        } except (EXCEPTION_EXECUTE_HANDLER) {
            Status = GetExceptionCode();
        }

        if (Status != STATUS_SUCCESS) {
            ExFreePool (NewSegment);
            ExFreePool (ControlArea);
            goto NeImage;
        }
    }

PeReturnSuccess:

    MiUnmapImageHeaderInHyperSpace ();

    //
    // Set the PFN database entry for this page to look like a transition
    // page.
    //

    PointerPte = NewSegment->PrototypePte;

    MiUpdateImageHeaderPage (PointerPte, PageFrameNumber, ControlArea);
    if (ExtendedHeader != NULL) {
        ExFreePool (ExtendedHeader);
    }
    ExFreePool (InPageEvent);

    return STATUS_SUCCESS;


        //
        // Error returns from image verification.
        //

BadPeImageSegment:

        ExFreePool (NewSegment);
        ExFreePool (ControlArea);
//BadPeImage:
        Status = STATUS_INVALID_IMAGE_FORMAT;
NeImage:
        MiUnmapImageHeaderInHyperSpace ();
BadSection:
        MiRemoveImageHeaderPage(PageFrameNumber);
        if (ExtendedHeader != NULL) {
            ExFreePool (ExtendedHeader);
        }
        ExFreePool (InPageEvent);
        return Status;
}


BOOLEAN
MiCheckDosCalls (
    IN PIMAGE_OS2_HEADER Os2Header,
    IN ULONG HeaderSize
    )

/*++

Routine Description:


Arguments:

Return Value:

    Returns the status value.

    TBS

--*/
{
    PUCHAR  ImportTable;
    UCHAR   EntrySize;
    USHORT  ModuleCount,ModuleSize,i;
    PUSHORT ModuleTable;

    PAGED_CODE();

    // if there are no modules to check return immidiatly.
    if ((ModuleCount = Os2Header->ne_cmod) == 0)
        return FALSE;

    // exe headers are notorious and sometime have jink values for offsets
    // in  import table and module table. We need to guard against any such
    // bad offset by putting our exception handler.

    try {
        // Find out where the Module ref table is. Mod table has two byte
        // for each entry in import table. These two bytes tell the offset
        // in the import table for that entry.

        ModuleTable = (PUSHORT)((ULONG)Os2Header + (ULONG)Os2Header->ne_modtab);

        // make sure that complete module table is in our pages. Note that each
        // module table entry is 2 bytes long.
        if (((ULONG)Os2Header->ne_modtab + (ModuleCount*2)) > HeaderSize)
                return FALSE;

        // now search individual entries for DOSCALLS.
        for (i=0 ; i<ModuleCount ; i++) {

            ModuleSize = *((UNALIGNED USHORT *)ModuleTable);

            // import table has count byte followed by the string where count
            // is the string length.
            ImportTable = (PUCHAR)((ULONG)Os2Header +
                          (ULONG)Os2Header->ne_imptab + (ULONG)ModuleSize);

            // make sure the offset is within in our valid range.
            if (((ULONG)Os2Header->ne_imptab + (ULONG)ModuleSize)
                            > HeaderSize)
                return FALSE;

            EntrySize = *ImportTable++;

            // 0 is a bad size, bail out.
            if (EntrySize == 0)
                return FALSE;

            // make sure the offset is within our valid range.
            if (((ULONG)Os2Header->ne_imptab + (ULONG)ModuleSize +
                            (ULONG)EntrySize) > HeaderSize)
                return FALSE;

            // If size matches compare DOSCALLS
            if (EntrySize == 8) {
                if (RtlEqualMemory (ImportTable,
                                    "DOSCALLS",
                                    8) ) {
                    return TRUE;
                }
            }
            // move on to next module table entry. Each entry is 2 bytes.
            ModuleTable = (PUSHORT)((ULONG)ModuleTable + 2);
        }
    } except (EXCEPTION_EXECUTE_HANDLER) {
        ASSERT (FALSE);
        return FALSE;
    }

    return FALSE;
}



NTSTATUS
MiVerifyImageHeader (
    IN PIMAGE_NT_HEADERS NtHeader,
    IN PIMAGE_DOS_HEADER DosHeader,
    IN ULONG NtHeaderSize
    )

/*++

Routine Description:


Arguments:

Return Value:

    Returns the status value.

    TBS

--*/



{
    PCONFIGPHARLAP PharLapConfigured;
    PUCHAR         pb;
    LONG           pResTableAddress;

    PAGED_CODE();

    if (NtHeader->Signature != IMAGE_NT_SIGNATURE) {
        if ((USHORT)NtHeader->Signature == (USHORT)IMAGE_OS2_SIGNATURE) {

            //
            // Check to see if this is a win-16 image.
            //

            if ((!MiCheckDosCalls ((PIMAGE_OS2_HEADER)NtHeader, NtHeaderSize)) &&
                ((((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 2)
                                ||
                ((((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 0)  &&
                  (((((PIMAGE_OS2_HEADER)NtHeader)->ne_expver & 0xff00) ==
                        0x200)  ||
                ((((PIMAGE_OS2_HEADER)NtHeader)->ne_expver & 0xff00) ==
                        0x300))))) {

                //
                // This is a win-16 image.
                //

                return STATUS_INVALID_IMAGE_WIN_16;
            }

            // The following os2 hedaers types go to NTDOS
            //
            // - exetype == 5 means binary is for Dos 4.0.
            //                e.g Borland Dos extender type
            //
            // - os2 apps which have no import table entries
            //   cannot be meant for os2ss.
            //                e.g. QuickC for dos binaries
            //
            //  - "old" Borland Dosx BC++ 3.x, Paradox 4.x
            //     exe type == 1
            //     DosHeader->e_cs * 16 + DosHeader->e_ip + 0x200 - 10
            //     contains the string " mode EXE$"
            //     but import table is empty, so we don't make special check
            //

            if (((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 5  ||
                ((PIMAGE_OS2_HEADER)NtHeader)->ne_enttab ==
                  ((PIMAGE_OS2_HEADER)NtHeader)->ne_imptab  )
               {
                return STATUS_INVALID_IMAGE_PROTECT;
            }


            //
            // Borland Dosx types: exe type 1
            //
            //  - "new" Borland Dosx BP7.0
            //     exe type == 1
            //     DosHeader + 0x200 contains the string "16STUB"
            //     0x200 happens to be e_parhdr*16
            //

            if (((PIMAGE_OS2_HEADER)NtHeader)->ne_exetyp == 1 &&
                RtlEqualMemory((PUCHAR)DosHeader + 0x200, "16STUB", 6) )
               {
                return STATUS_INVALID_IMAGE_PROTECT;
            }

            //
            // Check for PharLap extended header which we run as a dos app.
            // The PharLap config block is pointed to by the SizeofHeader
            // field in the DosHdr.
            // The following algorithm for detecting a pharlap exe
            // was recommended by PharLap Software Inc.
            //

            PharLapConfigured =(PCONFIGPHARLAP) ((ULONG)DosHeader +
                                      ((ULONG)DosHeader->e_cparhdr << 4));

            if ((ULONG)PharLapConfigured <
                       (ULONG)DosHeader + PAGE_SIZE - sizeof(CONFIGPHARLAP)) {
                if (RtlEqualMemory(&PharLapConfigured->uchCopyRight[0x18],
                                   "Phar Lap Software, Inc.", 24) &&
                    (PharLapConfigured->usSign == 0x4b50 ||  // stub loader type 2
                     PharLapConfigured->usSign == 0x4f50 ||  // bindable 286|DosExtender
                     PharLapConfigured->usSign == 0x5650  )) // bindable 286|DosExtender (Adv)
                  {
                    return STATUS_INVALID_IMAGE_PROTECT;
                }
            }



            //
            // Check for Rational extended header which we run as a dos app.
            // We look for the rational copyright at:
            //     wCopyRight = *(DosHeader->e_cparhdr*16 + 30h)
            //     pCopyRight = wCopyRight + DosHeader->e_cparhdr*16
            //     "Copyright (C) Rational Systems, Inc."
            //

            pb = (PUCHAR)((ULONG)DosHeader + ((ULONG)DosHeader->e_cparhdr << 4));

            if ((ULONG)pb < (ULONG)DosHeader + PAGE_SIZE - 0x30 - sizeof(USHORT)) {
                pb += *(PUSHORT)(pb + 0x30);
                if ( (ULONG)pb < (ULONG)DosHeader + PAGE_SIZE - 36 &&
                     RtlEqualMemory(pb,
                                    "Copyright (C) Rational Systems, Inc.",
                                    36) )
                   {
                    return STATUS_INVALID_IMAGE_PROTECT;
                }
            }

            //
            // Check for lotus 123 family of applications. Starting
            // with 123 3.0 (till recently shipped 123 3.4), every
            // exe header is bound but is meant for DOS. This can
            // be checked via, a string signature in the extended
            // header. <len byte>"1-2-3 Preloader" is the string
            // at ne_nrestab offset.
            //

            pResTableAddress = ((PIMAGE_OS2_HEADER)NtHeader)->ne_nrestab;
            if (pResTableAddress > DosHeader->e_lfanew &&
                ((ULONG)((pResTableAddress+16) - DosHeader->e_lfanew) <
                            NtHeaderSize) &&
                RtlEqualMemory(
                    (PUCHAR)((ULONG)NtHeader + 1 +
                             (ULONG)(pResTableAddress - DosHeader->e_lfanew)),
                    "1-2-3 Preloader",
                    15) ) {
                    return STATUS_INVALID_IMAGE_PROTECT;
            }

            return STATUS_INVALID_IMAGE_NE_FORMAT;
        }

        if ((USHORT)NtHeader->Signature == (USHORT)IMAGE_OS2_SIGNATURE_LE) {

            //
            // This is a LE (OS/2) image. We dont support it, so give it to
            // DOS subsystem. There are cases (Rbase.exe) which have a LE
            // header but actually it is suppose to run under DOS. When we
            // do support LE format, some work needs to be done here to
            // decide wether to give it to VDM or OS/2.
            //

            return STATUS_INVALID_IMAGE_PROTECT;
        }
        return STATUS_INVALID_IMAGE_PROTECT;
    }

    if ((NtHeader->FileHeader.Machine == 0) &&
        (NtHeader->FileHeader.SizeOfOptionalHeader == 0)) {

        //
        // This is a bogus DOS app which has a 32-bit portion
        // mascarading as a PE image.
        //

        return STATUS_INVALID_IMAGE_PROTECT;
    }

    if (!(NtHeader->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)) {
        return STATUS_INVALID_IMAGE_FORMAT;
    }

#ifdef i386

    //
    // Make sure the image header is aligned on a Long word boundary.
    //

    if (((ULONG)NtHeader & 3) != 0) {
        return STATUS_INVALID_IMAGE_FORMAT;
    }
#endif

    //
    // File aligment must be multiple of 512 and power of 2.
    //

    if (((NtHeader->OptionalHeader.FileAlignment & 511) != 0) &&
        (NtHeader->OptionalHeader.FileAlignment !=
         NtHeader->OptionalHeader.SectionAlignment)) {
        return STATUS_INVALID_IMAGE_FORMAT;
    }

    if (((NtHeader->OptionalHeader.FileAlignment - 1) &
          NtHeader->OptionalHeader.FileAlignment) != 0) {
        return STATUS_INVALID_IMAGE_FORMAT;
    }

    if (NtHeader->OptionalHeader.SectionAlignment < NtHeader->OptionalHeader.FileAlignment) {
        return STATUS_INVALID_IMAGE_FORMAT;
    }

    if (NtHeader->OptionalHeader.SizeOfImage > MM_SIZE_OF_LARGEST_IMAGE) {
        return STATUS_INVALID_IMAGE_FORMAT;
    }

    if (NtHeader->FileHeader.NumberOfSections > MM_MAXIMUM_IMAGE_SECTIONS) {
        return STATUS_INVALID_IMAGE_FORMAT;
    }

    //commented out to map drivers at based addresses.

    //if ((PVOID)NtHeader->OptionalHeader.ImageBase >= MM_HIGHEST_USER_ADDRESS) {
    //    return STATUS_INVALID_IMAGE_FORMAT;
    //}
    return STATUS_SUCCESS;
}

NTSTATUS
MiCreateDataFileMap (
    IN PFILE_OBJECT File,
    OUT PSEGMENT *Segment,
    IN PLARGE_INTEGER MaximumSize,
    IN ULONG SectionPageProtection,
    IN ULONG AllocationAttributes,
    IN ULONG IgnoreFileSizing
    )

/*++

Routine Description:

    This function creates the necessary strutures to allow the mapping
    of a data file.

    The data file is accessed to verify desire access, a segment
    object is created and initialized.

Arguments:

    File - Supplies the file object for the image file.

    Segment - Returns the segment object.

    FileHandle - Supplies the handle to the image file.

    MaximumSize - Supplies the maximum size for the mapping.

    SectionPageProtection - Supplies the initial page protection.

    AllocationAttributes - Supplies the allocation attributes for the
                           mapping.

Return Value:

    Returns the status value.

    TBS


--*/

{

    NTSTATUS Status;
    ULONG NumberOfPtes;
    ULONG SizeOfSegment;
    ULONG j;
    ULONG Size;
    ULONG PartialSize;
    ULONG First;
    PCONTROL_AREA ControlArea;
    PSEGMENT NewSegment;
    PSUBSECTION Subsection;
    PSUBSECTION ExtendedSubsection;
    PMMPTE PointerPte;
    MMPTE TempPte;
    ULONG NumberOfPtesWithAlignment;
    LARGE_INTEGER EndOfFile;
    ULONG ExtendedSubsections = 0;
    PSUBSECTION FirstSubsection = NULL;
    PSUBSECTION Last;
    ULONG NumberOfNewSubsections = 0;

    PAGED_CODE();

    // *************************************************************
    // Create mapped file section.
    // *************************************************************


    if (!IgnoreFileSizing) {

        Status = FsRtlGetFileSize (File, &EndOfFile);

        if (Status == STATUS_FILE_IS_A_DIRECTORY) {

            //
            // Can't map a directory as a section. Return error.
            //

            return STATUS_INVALID_FILE_FOR_SECTION;
        }

        if (!NT_SUCCESS (Status)) {
            return Status;
        }

        if ((EndOfFile.QuadPart == 0) && (MaximumSize->QuadPart == 0)) {

            //
            // Can't map a zero length without specifying the maximum
            // size as non-zero.
            //

            return STATUS_MAPPED_FILE_SIZE_ZERO;
        }

        //
        // Make sure this file is big enough for the section.
        //

        if (MaximumSize->QuadPart > EndOfFile.QuadPart) {

            //
            // If the maximum size is greater than the end-of-file,
            // and the user did not request page_write or page_execte_readwrite
            // to the section, reject the request.
            //

            if (((SectionPageProtection & PAGE_READWRITE) |
                (SectionPageProtection & PAGE_EXECUTE_READWRITE)) == 0) {

                return STATUS_SECTION_TOO_BIG;
            }

            //
            // Check to make sure that the allocation size large enough
            // to contain all the data, if not set a new allocation size.
            //

            EndOfFile = *MaximumSize;

            Status = FsRtlSetFileSize (File, &EndOfFile);

            if (!NT_SUCCESS (Status)) {
                return Status;
            }
        }
    } else {

        //
        // Ignore the file size, this call is from the cache manager.
        //

        EndOfFile = *MaximumSize;
    }

    //
    // Calculate the number of prototype PTEs to build for this section.
    //

    NumberOfPtes = (ULONG)(EndOfFile.QuadPart +
                           (PAGE_SIZE - 1) >> PAGE_SHIFT);

    //
    // Calculate the number of ptes to allocate to maintain the
    // desired alignment.  On x86 and R3000 no additional PTEs are
    // needed, on MIPS, the desired aligment is 64k to avoid cache
    // problems.
    //

    NumberOfPtesWithAlignment = (NumberOfPtes +
            ((MM_PROTO_PTE_ALIGNMENT >> PAGE_SHIFT) - 1)) &
            (~((MM_PROTO_PTE_ALIGNMENT >> PAGE_SHIFT) - 1));

    ASSERT (NumberOfPtes <= NumberOfPtesWithAlignment);

    SizeOfSegment = sizeof(SEGMENT) + sizeof(MMPTE) *
                                        (NumberOfPtesWithAlignment - 1);

    NewSegment = ExAllocatePoolWithTag (PagedPool,
                                        SizeOfSegment,
                                        MMSECT);
    if (NewSegment == NULL) {

        //
        // The requested pool could not be allocated.
        // Try to allocate the memory in smaller sizes.
        //

        if (SizeOfSegment < MM_ALLOCATION_FRAGMENT) {
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        Size = MM_ALLOCATION_FRAGMENT;
        PartialSize = SizeOfSegment;

        do {

            if (PartialSize < MM_ALLOCATION_FRAGMENT) {
                PartialSize = ROUND_TO_PAGES (PartialSize);
                Size = PartialSize;
            }

            NewSegment = ExAllocatePoolWithTag (PagedPool,
                                                Size,
                                                MMSECT);
            ExtendedSubsection = ExAllocatePoolWithTag (NonPagedPool,
                                                   sizeof(SUBSECTION),
                                                   'bSmM');

            if ((NewSegment == NULL) || (ExtendedSubsection == NULL)) {
                if (NewSegment) {
                    ExFreePool (NewSegment);
                }
                if (ExtendedSubsection) {
                    ExFreePool (ExtendedSubsection);
                }

                //
                // Free all the previous allocations and return an error.
                //

                while (FirstSubsection != NULL) {
                    ExFreePool (FirstSubsection->SubsectionBase);
                    Last = FirstSubsection->NextSubsection;
                    ExFreePool (FirstSubsection);
                    FirstSubsection = Last;
                }
                return STATUS_INSUFFICIENT_RESOURCES;
            }

            NumberOfNewSubsections += 1;
            RtlZeroMemory (ExtendedSubsection, sizeof(SUBSECTION));

            if (FirstSubsection == NULL) {
                FirstSubsection = ExtendedSubsection;
                Last = ExtendedSubsection;
                NumberOfNewSubsections = 0;
            } else {
                Last->NextSubsection = ExtendedSubsection;
            }

            ExtendedSubsection->PtesInSubsection = Size / sizeof(MMPTE);
            ExtendedSubsection->SubsectionBase = (PMMPTE)NewSegment;
            Last = ExtendedSubsection;
            PartialSize -= Size;
        } while (PartialSize != 0);

        //
        // Reset new segment and free the first subsection, as
        // the subsection after the control area will become the
        // first subsection.
        //

        NewSegment = (PSEGMENT)FirstSubsection->SubsectionBase;
    }

    *Segment = NewSegment;
    RtlZeroMemory (NewSegment, sizeof(SEGMENT));

    ControlArea =
              (PCONTROL_AREA)File->SectionObjectPointer->DataSectionObject;

    //
    // Control area and first subsection have been zeroed when allocated.
    //

    ControlArea->Segment = NewSegment;
    ControlArea->NumberOfSectionReferences = 1;

    if (IgnoreFileSizing == FALSE) {

        //
        // This reference is not from the cache manager.
        //

        ControlArea->NumberOfUserReferences = 1;
    }

    ControlArea->u.Flags.BeingCreated = 1;
    ControlArea->u.Flags.File = 1;

    if (FILE_REMOTE_DEVICE & File->DeviceObject->Characteristics) {

        //
        // This file resides on a redirected drive.
        //

        ControlArea->u.Flags.Networked = 1;
    }

    if (AllocationAttributes & SEC_NOCACHE) {
        ControlArea->u.Flags.NoCache = 1;
    }

    if (IgnoreFileSizing) {
        // Set the was purged flag to indicate that the
        // file size was not explicitly set.
        //

        ControlArea->u.Flags.WasPurged = 1;
    }

    ControlArea->NumberOfSubsections = 1 + (USHORT)NumberOfNewSubsections;
    ControlArea->FilePointer = File;

    Subsection = (PSUBSECTION)(ControlArea + 1);

    if (FirstSubsection) {

        Subsection->NextSubsection = FirstSubsection->NextSubsection;
        Subsection->PtesInSubsection = FirstSubsection->PtesInSubsection;
        ExFreePool (FirstSubsection);
#if DBG
        FirstSubsection = NULL;
#endif //DBG
    } else {
        ASSERT (Subsection->NextSubsection == NULL);
    }

    First = TRUE;
    PartialSize = 0;

    do {

        //
        // Loop through all the subsections and fill in the PTEs.
        //


        TempPte.u.Long = (ULONG)MiGetSubsectionAddressForPte(Subsection);
        TempPte.u.Soft.Prototype = 1;

        //
        // Set all the PTEs to the execute-read-write protection.
        // The section will control access to these and the segment
        // must provide a method to allow other users to map the file
        // for various protections.
        //

        TempPte.u.Soft.Protection = MM_EXECUTE_READWRITE;

        //
        // Align the prototype PTEs on the proper boundary.
        //

        if (First) {

            PointerPte = &NewSegment->ThePtes[0];
            j = ((ULONG)PointerPte >> PTE_SHIFT) &
                            ((MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - 1);

            if (j != 0) {
                j = (MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - j;
            }

            NewSegment->PrototypePte = &NewSegment->ThePtes[j];
            NewSegment->ControlArea = ControlArea;
            NewSegment->SizeOfSegment = EndOfFile;
            NewSegment->TotalNumberOfPtes = NumberOfPtes;
            NewSegment->SegmentPteTemplate = TempPte;
            PointerPte = NewSegment->PrototypePte;
            Subsection->SubsectionBase = PointerPte;

            if (Subsection->NextSubsection != NULL) {

                //
                // Multiple segments and subsections.
                // Align first so it is a multiple of 64k sizes.
                //
                //

                NewSegment->NonExtendedPtes =
                  (((Subsection->PtesInSubsection * sizeof(MMPTE)) -
                    ((PCHAR)NewSegment->PrototypePte - (PCHAR)NewSegment))
                        / sizeof(MMPTE)) &  ~((X64K >> PAGE_SHIFT) - 1);
            } else {
                NewSegment->NonExtendedPtes = NumberOfPtesWithAlignment;
            }
            Subsection->PtesInSubsection = NewSegment->NonExtendedPtes;

            First = FALSE;
        } else {
            PointerPte = (PMMPTE)Subsection->SubsectionBase;
        }

        Subsection->ControlArea = ControlArea;
        Subsection->StartingSector = PartialSize;
        Subsection->u.SubsectionFlags.Protection = MM_EXECUTE_READWRITE;

        if (Subsection->NextSubsection == NULL) {
            Subsection->EndingSector = (ULONG)(EndOfFile.QuadPart >> MMSECTOR_SHIFT);
            Subsection->u.SubsectionFlags.SectorEndOffset =
                                 EndOfFile.LowPart & MMSECTOR_MASK;
            j = Subsection->PtesInSubsection;
            Subsection->PtesInSubsection = NumberOfPtes -
                                (PartialSize >> (PAGE_SHIFT - MMSECTOR_SHIFT));
            Subsection->UnusedPtes = j - Subsection->PtesInSubsection;
        } else {
            Subsection->EndingSector = PartialSize +
                (Subsection->PtesInSubsection << (PAGE_SHIFT - MMSECTOR_SHIFT));
        }

        RtlFillMemoryUlong (PointerPte,
                            (Subsection->PtesInSubsection +
                                Subsection->UnusedPtes) * sizeof(MMPTE),
                            TempPte.u.Long);

        PartialSize += Subsection->PtesInSubsection <<
                                        (PAGE_SHIFT - MMSECTOR_SHIFT);
        Subsection = Subsection->NextSubsection;
    } while (Subsection != NULL);

    return STATUS_SUCCESS;
}

NTSTATUS
MiCreatePagingFileMap (
    OUT PSEGMENT *Segment,
    IN PLARGE_INTEGER MaximumSize,
    IN ULONG ProtectionMask,
    IN ULONG AllocationAttributes
    )

/*++

Routine Description:

    This function creates the necessary strutures to allow the mapping
    of a paging file.

Arguments:

    Segment - Returns the segment object.

    MaximumSize - Supplies the maximum size for the mapping.

    ProtectionMask - Supplies the initial page protection.

    AllocationAttributes - Supplies the allocation attributes for the
                           mapping.

Return Value:

    Returns the status value.

    TBS


--*/


{

    ULONG NumberOfPtes;
    ULONG SizeOfSegment;
    ULONG i;
    PCONTROL_AREA ControlArea;
    PSEGMENT NewSegment;
    PMMPTE PointerPte;
    PSUBSECTION Subsection;
    MMPTE TempPte;

    PAGED_CODE();

    //*******************************************************************
    // Create a section backed by paging file.
    //*******************************************************************

    if (MaximumSize->QuadPart == 0) {
        return STATUS_INVALID_PARAMETER_4;
    }

    //
    // Limit page file backed sections to 2 gigabytes.
    //

    if ((MaximumSize->HighPart != 0) ||
        (MaximumSize->LowPart > (ULONG)0x7FFFFFFF)) {

        return STATUS_SECTION_TOO_BIG;
    }

    //
    // Create the segment object.
    //

    //
    // Calculate the number of prototype PTEs to build for this segment.
    //

    NumberOfPtes = BYTES_TO_PAGES (MaximumSize->LowPart);

    if (AllocationAttributes & SEC_COMMIT) {

        //
        // Commit the pages for the section.
        //

        try {

            MiChargeCommitment (NumberOfPtes, NULL);

        } except (EXCEPTION_EXECUTE_HANDLER) {
            return GetExceptionCode();
        }
    }

    SizeOfSegment = sizeof(SEGMENT) + sizeof(MMPTE) * (NumberOfPtes - 1);

    NewSegment = ExAllocatePoolWithTag (PagedPool, SizeOfSegment,
                                        MMSECT);

    if (NewSegment == NULL) {

        //
        // The requested pool could not be allocated.
        //

        if (AllocationAttributes & SEC_COMMIT) {
            MiReturnCommitment (NumberOfPtes);
        }
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    *Segment = NewSegment;

    ControlArea = ExAllocatePoolWithTag (NonPagedPool,
                                 (ULONG)sizeof(CONTROL_AREA) +
                                                (ULONG)sizeof(SUBSECTION),
                                         MMCONTROL);

    if (ControlArea == NULL) {

        //
        // The requested pool could not be allocated.
        //

        ExFreePool (NewSegment);

        if (AllocationAttributes & SEC_COMMIT) {
            MiReturnCommitment (NumberOfPtes);
        }
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Zero control area and first subsection.
    //

    RtlZeroMemory (ControlArea,
                   sizeof(CONTROL_AREA) + sizeof(SUBSECTION));

    ControlArea->Segment = NewSegment;
    ControlArea->NumberOfSectionReferences = 1;
    ControlArea->NumberOfUserReferences = 1;
    ControlArea->NumberOfSubsections = 1;

    if (AllocationAttributes & SEC_BASED) {
        ControlArea->u.Flags.Based = 1;
    }

    if (AllocationAttributes & SEC_RESERVE) {
        ControlArea->u.Flags.Reserve = 1;
    }

    if (AllocationAttributes & SEC_COMMIT) {
        ControlArea->u.Flags.Commit = 1;
    }

    Subsection = (PSUBSECTION)(ControlArea + 1);

    Subsection->ControlArea = ControlArea;
    Subsection->PtesInSubsection = NumberOfPtes;
    Subsection->u.SubsectionFlags.Protection = ProtectionMask;

    //
    // Align the prototype PTEs on the proper boundary.
    //

    PointerPte = &NewSegment->ThePtes[0];
    i = ((ULONG)PointerPte >> PTE_SHIFT) &
                    ((MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - 1);

    if (i != 0) {
        i = (MM_PROTO_PTE_ALIGNMENT / PAGE_SIZE) - i;
    }

    //
    // Zero the segment header.
    //

    RtlZeroMemory (NewSegment, sizeof(SEGMENT));

    NewSegment->PrototypePte = &NewSegment->ThePtes[i];

    NewSegment->ControlArea = ControlArea;

    //
    // As size is limited to 2gb, ignore the high part.
    //

    NewSegment->SizeOfSegment.LowPart = NumberOfPtes * PAGE_SIZE;
    NewSegment->TotalNumberOfPtes = NumberOfPtes;
    NewSegment->NonExtendedPtes = NumberOfPtes;

    PointerPte = NewSegment->PrototypePte;
    Subsection->SubsectionBase = PointerPte;
    TempPte = ZeroPte;

    if (AllocationAttributes & SEC_COMMIT) {
        TempPte.u.Soft.Protection = ProtectionMask;
        NewSegment->NumberOfCommittedPages = NumberOfPtes;
        MmSharedCommit += NewSegment->NumberOfCommittedPages;
    }

    NewSegment->SegmentPteTemplate.u.Soft.Protection = ProtectionMask;

    for (i = 0; i < NumberOfPtes; i++) {

        //
        // Set all the prototype PTEs to either no access or demand zero
        // depending on the commit flag.
        //

        *PointerPte = TempPte;
        PointerPte += 1;
    }

    return STATUS_SUCCESS;
}


NTSTATUS
NtOpenSection (
    OUT PHANDLE SectionHandle,
    IN ACCESS_MASK DesiredAccess,
    IN POBJECT_ATTRIBUTES ObjectAttributes
    )

/*++

Routine Description:

    This function opens a handle to a section object with the specified
    desired access.

Arguments:


    Sectionhandle - Supplies a pointer to a variable that will
         receive the section object handle value.

    DesiredAccess - Supplies the desired types of access  for the
         section.

    DesiredAccess Flags


         EXECUTE - Execute access to the section is
              desired.

         READ - Read access to the section is desired.

         WRITE - Write access to the section is desired.

    ObjectAttributes - Supplies a pointer to an object attributes structure.

Return Value:

    Returns the status

    TBS


--*/

{
    HANDLE Handle;
    KPROCESSOR_MODE PreviousMode;
    NTSTATUS Status;

    PAGED_CODE();
    //
    // Get previous processor mode and probe output arguments if necessary.
    //

    PreviousMode = KeGetPreviousMode();
    if (PreviousMode != KernelMode) {
        try {
            ProbeForWriteHandle(SectionHandle);
        } except (EXCEPTION_EXECUTE_HANDLER) {
            return GetExceptionCode();
        }
    }

    //
    // Open handle to the section object with the specified desired
    // access.
    //

    Status = ObOpenObjectByName (ObjectAttributes,
                                 MmSectionObjectType,
                                 PreviousMode,
                                 NULL,
                                 DesiredAccess,
                                 NULL,
                                 &Handle
                                 );

    try {
        *SectionHandle = Handle;
    } except (EXCEPTION_EXECUTE_HANDLER) {
        return Status;
    }

    return Status;
}

CCHAR
MiGetImageProtection (
    IN ULONG SectionCharacteristics
    )

/*++

Routine Description:

    This function takes a section characteristic mask from the
    image and converts it to an PTE protection mask.

Arguments:

    SectionCharacteristics - Supplies the characteristics mask from the
                             image.

Return Value:

    Returns the protection mask for the PTE.

--*/

{
    ULONG Index;
    PAGED_CODE();

    Index = 0;
    if (SectionCharacteristics & IMAGE_SCN_MEM_EXECUTE) {
        Index |= 1;
    }
    if (SectionCharacteristics & IMAGE_SCN_MEM_READ) {
        Index |= 2;
    }
    if (SectionCharacteristics & IMAGE_SCN_MEM_WRITE) {
        Index |= 4;
    }
    if (SectionCharacteristics & IMAGE_SCN_MEM_SHARED) {
        Index |= 8;
    }

    return MmImageProtectionArray[Index];
}

ULONG
MiGetPageForHeader (
    VOID
    )

/*++

Routine Description:

    This non-pagable function acquires the PFN lock, removes
    a page and updates the PFN database as though the page was
    ready to be deleted if the reference count is decremented.

Arguments:

    None.

Return Value:

    Returns the phyiscal page frame number.

--*/

{
    KIRQL OldIrql;
    ULONG PageFrameNumber;
    PMMPFN Pfn1;
    PEPROCESS Process;
    ULONG PageColor;

    Process = PsGetCurrentProcess();
    PageColor = MI_PAGE_COLOR_VA_PROCESS ((PVOID)X64K,
                                          &Process->NextPageColor);

    //
    // Lock the PFN database and get a page.
    //

    LOCK_PFN (OldIrql);

    MiEnsureAvailablePageOrWait (NULL, NULL);

    //
    // Remove page for 64k alignment.
    //

    PageFrameNumber = MiRemoveAnyPage (PageColor);

    UNLOCK_PFN (OldIrql);

    //
    // Increment the reference count for the page so the
    // paging I/O will work.
    //

    Pfn1 = MI_PFN_ELEMENT (PageFrameNumber);
    Pfn1->u3.e2.ReferenceCount += 1;
    Pfn1->OriginalPte = ZeroPte;
    Pfn1->PteAddress = (PVOID) X64K;
    MI_SET_PFN_DELETED (Pfn1);

    return(PageFrameNumber);
}

VOID
MiUpdateImageHeaderPage (
    IN PMMPTE PointerPte,
    IN ULONG PageFrameNumber,
    IN PCONTROL_AREA ControlArea
    )

/*++

Routine Description:

    This non-pagable function acquires the PFN lock, and
    makes the specified protype PTE page a transition PTE
    referring to the specified physical page.  It then
    decrements the reference count causing the page to
    be placed on the standby or modified list.

Arguments:

    PointerPte - Supplies the PTE to set into the transition state.

    PageFrameNumber - Supplies the physical page.

    ControlArea - Supplies the control area for the prototype PTEs.

Return Value:

    None.

--*/

{
    KIRQL OldIrql;

    LOCK_PFN (OldIrql);

    MiMakeSystemAddressValidPfn (PointerPte);

    MiInitializeTransitionPfn (PageFrameNumber, PointerPte, 0xFFFFFFFF);
    ControlArea->NumberOfPfnReferences += 1;

    //
    // Add the page to the standby list.
    //

    MiDecrementReferenceCount (PageFrameNumber);

    UNLOCK_PFN (OldIrql);
    return;
}

VOID
MiRemoveImageHeaderPage (
    IN ULONG PageFrameNumber
    )

/*++

Routine Description:

    This non-pagable function acquires the PFN lock, and decrements
    the reference count thereby causing the phyiscal page to
    be deleted.

Arguments:

    PageFrameNumber - Supplies the PFN to decrement.

Return Value:

    None.

--*/
{
    KIRQL OldIrql;

    LOCK_PFN (OldIrql);
    MiDecrementReferenceCount (PageFrameNumber);
    UNLOCK_PFN (OldIrql);
    return;
}