1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
/*
 * COPYRIGHT:       See COPYING in the top level directory
 * PROJECT:         ReactOS system libraries
 * FILE:            dll/win32/kernel32/client/proc.c
 * PURPOSE:         Process functions
 * PROGRAMMERS:     Ariadne (ariadne@xs4all.nl)
 * UPDATE HISTORY:
 *                  Created 01/11/98
 */

/* INCLUDES ****************************************************************/

#include <k32.h>

#define NDEBUG
#include <debug.h>

/* GLOBALS *******************************************************************/

WaitForInputIdleType UserWaitForInputIdleRoutine;
UNICODE_STRING BaseUnicodeCommandLine;
ANSI_STRING BaseAnsiCommandLine;
UNICODE_STRING BasePathVariableName = RTL_CONSTANT_STRING(L"PATH");
LPSTARTUPINFOA BaseAnsiStartupInfo = NULL;
PLDR_DATA_TABLE_ENTRY BasepExeLdrEntry;
BOOLEAN g_AppCertInitialized;
BOOLEAN g_HaveAppCerts;
LIST_ENTRY BasepAppCertDllsList;
RTL_CRITICAL_SECTION gcsAppCert;
PBASEP_APPCERT_EMBEDDED_FUNC fEmbeddedCertFunc;
NTSTATUS g_AppCertStatus;
RTL_QUERY_REGISTRY_TABLE BasepAppCertTable[2] =
{
    {
        BasepConfigureAppCertDlls,
        1,
        L"AppCertDlls",
        &BasepAppCertDllsList,
        0,
        NULL,
        0
    }
};

PSAFER_REPLACE_PROCESS_THREAD_TOKENS g_SaferReplaceProcessThreadTokens;
HMODULE gSaferHandle = (HMODULE)-1;

VOID WINAPI
RegisterWaitForInputIdle(WaitForInputIdleType lpfnRegisterWaitForInputIdle);

#define CMD_STRING L"cmd /c "

/* FUNCTIONS ****************************************************************/

VOID
WINAPI
StuffStdHandle(IN HANDLE ProcessHandle,
               IN HANDLE StandardHandle,
               IN PHANDLE Address)
{
    NTSTATUS Status;
    HANDLE DuplicatedHandle;
    SIZE_T NumberOfBytesWritten;

    /* If there is no handle to duplicate, return immediately */
    if (!StandardHandle) return;

    /* Duplicate the handle */
    Status = NtDuplicateObject(NtCurrentProcess(),
                               StandardHandle,
                               ProcessHandle,
                               &DuplicatedHandle,
                               0,
                               0,
                               DUPLICATE_SAME_ACCESS |
                               DUPLICATE_SAME_ATTRIBUTES);
    if (!NT_SUCCESS(Status)) return;

    /* Write it */
    NtWriteVirtualMemory(ProcessHandle,
                         Address,
                         &DuplicatedHandle,
                         sizeof(HANDLE),
                         &NumberOfBytesWritten);
}

BOOLEAN
WINAPI
BuildSubSysCommandLine(IN LPCWSTR SubsystemName,
                       IN LPCWSTR ApplicationName,
                       IN LPCWSTR CommandLine,
                       OUT PUNICODE_STRING SubsysCommandLine)
{
    UNICODE_STRING CommandLineString, ApplicationNameString;
    PWCHAR Buffer;
    ULONG Length;

    /* Convert to unicode strings */
    RtlInitUnicodeString(&CommandLineString, ApplicationName);
    RtlInitUnicodeString(&ApplicationNameString, CommandLine);

    /* Allocate buffer for the output string */
    Length = CommandLineString.MaximumLength + ApplicationNameString.MaximumLength + 32;
    Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, Length);
    RtlInitEmptyUnicodeString(SubsysCommandLine, Buffer, (USHORT)Length);
    if (!Buffer)
    {
        /* Fail, no memory */
        BaseSetLastNTError(STATUS_NO_MEMORY);
        return FALSE;
    }

    /* Build the final subsystem command line */
    RtlAppendUnicodeToString(SubsysCommandLine, SubsystemName);
    RtlAppendUnicodeStringToString(SubsysCommandLine, &CommandLineString);
    RtlAppendUnicodeToString(SubsysCommandLine, L" /C ");
    RtlAppendUnicodeStringToString(SubsysCommandLine, &ApplicationNameString);
    return TRUE;
}

BOOLEAN
WINAPI
BasepIsImageVersionOk(IN ULONG ImageMajorVersion,
                      IN ULONG ImageMinorVersion)
{
    /* Accept images for NT 3.1 or higher */
    if (ImageMajorVersion > 3 ||
        (ImageMajorVersion == 3 && ImageMinorVersion >= 10))
    {
        /* ReactOS-specific: Accept images even if they are newer than our internal NT version. */
        if (ImageMajorVersion > SharedUserData->NtMajorVersion ||
            (ImageMajorVersion == SharedUserData->NtMajorVersion && ImageMinorVersion > SharedUserData->NtMinorVersion))
        {
            DPRINT1("Accepting image version %lu.%lu, although ReactOS is an NT %hu.%hu OS!\n",
                ImageMajorVersion,
                ImageMinorVersion,
                SharedUserData->NtMajorVersion,
                SharedUserData->NtMinorVersion);
        }

        return TRUE;
    }

    return FALSE;
}

NTSTATUS
WINAPI
BasepCheckWebBladeHashes(IN HANDLE FileHandle)
{
    NTSTATUS Status;
    CHAR Hash[16];

    /* Get all the MD5 hashes */
    Status = RtlComputeImportTableHash(FileHandle, Hash, 1);
    if (!NT_SUCCESS(Status)) return Status;

    /* Depending on which suite this is, run a bsearch and block the appropriate ones */
    if (SharedUserData->SuiteMask & VER_SUITE_COMPUTE_SERVER)
    {
        DPRINT1("Egad! This is a ReactOS Compute Server and we should prevent you from using certain APIs...but we won't.");
    }
    else if (SharedUserData->SuiteMask & VER_SUITE_STORAGE_SERVER)
    {
        DPRINT1("Gasp! This is a ReactOS Storage Server and we should prevent you from using certain APIs...but we won't.");
    }
    else if (SharedUserData->SuiteMask & VER_SUITE_BLADE)
    {
        DPRINT1("Golly! This is a ReactOS Web Blade Server and we should prevent you from using certain APIs...but we won't.");
    }

    /* Actually, fuck it, don't block anything, we're open source */
    return STATUS_SUCCESS;
}

NTSTATUS
NTAPI
BasepSaveAppCertRegistryValue(IN PLIST_ENTRY List,
                              IN PWCHAR ComponentName,
                              IN PWCHAR DllName)
{
    /* Pretty much the only thing this key is used for, is malware */
    UNIMPLEMENTED;
    return STATUS_NOT_IMPLEMENTED;
}

NTSTATUS
NTAPI
BasepConfigureAppCertDlls(IN PWSTR ValueName,
                          IN ULONG ValueType,
                          IN PVOID ValueData,
                          IN ULONG ValueLength,
                          IN PVOID Context,
                          IN PVOID EntryContext)
{
    /* Add this to the certification list */
    return BasepSaveAppCertRegistryValue(Context, ValueName, ValueData);
}

NTSTATUS
WINAPI
BasepIsProcessAllowed(IN LPWSTR ApplicationName)
{
    NTSTATUS Status, Status1;
    PWCHAR Buffer;
    UINT Length;
    HMODULE TrustLibrary;
    PBASEP_APPCERT_ENTRY Entry;
    ULONG CertFlag;
    PLIST_ENTRY NextEntry;
    HANDLE KeyHandle;
    UNICODE_STRING CertKey = RTL_CONSTANT_STRING(L"\\Registry\\MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\AppCertDlls");
    OBJECT_ATTRIBUTES KeyAttributes = RTL_CONSTANT_OBJECT_ATTRIBUTES(&CertKey, OBJ_CASE_INSENSITIVE);

    /* Try to initialize the certification subsystem */
    while (!g_AppCertInitialized)
    {
        /* Defaults */
        Status = STATUS_SUCCESS;
        Buffer = NULL;

        /* Acquire the lock while initializing and see if we lost a race */
        RtlEnterCriticalSection(&gcsAppCert);
        if (g_AppCertInitialized) break;

        /* On embedded, there is a special DLL */
        if (SharedUserData->SuiteMask & VER_SUITE_EMBEDDEDNT)
        {
            /* Allocate a buffer for the name */
            Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
                                     0,
                                     MAX_PATH * sizeof(WCHAR) +
                                     sizeof(UNICODE_NULL));
            if (!Buffer)
            {
                /* Fail if no memory */
                Status = STATUS_NO_MEMORY;
            }
            else
            {
                /* Now get the system32 directory in our buffer, make sure it fits */
                Length = GetSystemDirectoryW(Buffer, MAX_PATH - sizeof("EmbdTrst.DLL"));
                if ((Length) && (Length <= MAX_PATH - sizeof("EmbdTrst.DLL")))
                {
                    /* Add a slash if needed, and add the embedded cert DLL name */
                    if (Buffer[Length - 1] != '\\') Buffer[Length++] = '\\';
                    RtlCopyMemory(&Buffer[Length],
                                  L"EmbdTrst.DLL",
                                  sizeof(L"EmbdTrst.DLL"));

                    /* Try to load it */
                    TrustLibrary = LoadLibraryW(Buffer);
                    if (TrustLibrary)
                    {
                        /* And extract the special function out of it */
                        fEmbeddedCertFunc = (PVOID)GetProcAddress(TrustLibrary,
                                                                  "ImageOkToRunOnEmbeddedNT");
                    }
                }

                /* If we didn't get this far, set a failure code */
                if (!fEmbeddedCertFunc) Status = STATUS_UNSUCCESSFUL;
            }
        }
        else
        {
            /* Other systems have a registry entry for this */
            Status1 = NtOpenKey(&KeyHandle, KEY_READ, &KeyAttributes);
            if (NT_SUCCESS(Status1))
            {
                /* Close it, we'll query it through Rtl */
                NtClose(KeyHandle);

                /* Do the query, which will call a special callback */
                Status = RtlQueryRegistryValues(RTL_REGISTRY_CONTROL,
                                                L"Session Manager",
                                                BasepAppCertTable,
                                                NULL,
                                                NULL);
                if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
                {
                    Status = STATUS_SUCCESS;
                }
            }
        }

        /* Free any buffer if we had one */
        if (Buffer) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);

        /* Check for errors, or a missing embedded/custom certification DLL */
        if (!NT_SUCCESS(Status) ||
            (!(fEmbeddedCertFunc) && (IsListEmpty(&BasepAppCertDllsList))))
        {
            /* The subsystem is not active on this machine, so give up */
            g_HaveAppCerts = FALSE;
            g_AppCertStatus = Status;
        }
        else
        {
            /* We have certification DLLs active, remember this */
            g_HaveAppCerts = TRUE;
        }

        /* We are done the initialization phase, release the lock */
        g_AppCertInitialized = TRUE;
        RtlLeaveCriticalSection(&gcsAppCert);
    }

    /* If there's no certification DLLs present, return the failure code */
    if (!g_HaveAppCerts) return g_AppCertStatus;

    /* Otherwise, assume success and make sure we have *something* */
    ASSERT(fEmbeddedCertFunc || !IsListEmpty(&BasepAppCertDllsList));
    Status = STATUS_SUCCESS;

    /* If the something is an embedded certification DLL, call it and return */
    if (fEmbeddedCertFunc) return fEmbeddedCertFunc(ApplicationName);

    /* Otherwise we have custom certification DLLs, parse them */
    NextEntry = BasepAppCertDllsList.Flink;
    CertFlag = 2;
    while (NextEntry != &BasepAppCertDllsList)
    {
        /* Make sure the entry has a callback */
        Entry = CONTAINING_RECORD(NextEntry, BASEP_APPCERT_ENTRY, Entry);
        ASSERT(Entry->fPluginCertFunc != NULL);

        /* Call it and check if it failed */
        Status = Entry->fPluginCertFunc(ApplicationName, 1);
        if (!NT_SUCCESS(Status)) CertFlag = 3;

        /* Move on */
        NextEntry = NextEntry->Flink;
    }

    /* Now loop them again */
    NextEntry = BasepAppCertDllsList.Flink;
    while (NextEntry != &BasepAppCertDllsList)
    {
        /* Make sure the entry has a callback */
        Entry = CONTAINING_RECORD(NextEntry, BASEP_APPCERT_ENTRY, Entry);
        ASSERT(Entry->fPluginCertFunc != NULL);

        /* Call it, this time with the flag from the loop above */
        Status = Entry->fPluginCertFunc(ApplicationName, CertFlag);
    }

    /* All done, return the status */
    return Status;
}

NTSTATUS
WINAPI
BasepReplaceProcessThreadTokens(IN HANDLE TokenHandle,
                                IN HANDLE ProcessHandle,
                                IN HANDLE ThreadHandle)
{
    NTSTATUS Status;
    ANSI_STRING SaferiReplaceProcessThreadTokens = RTL_CONSTANT_STRING("SaferiReplaceProcessThreadTokens");

    /* Enter the application certification lock */
    RtlEnterCriticalSection(&gcsAppCert);

    /* Check if we already know the function */
    if (g_SaferReplaceProcessThreadTokens)
    {
        /* Call it */
        Status = g_SaferReplaceProcessThreadTokens(TokenHandle,
                                                   ProcessHandle,
                                                   ThreadHandle) ?
                                                   STATUS_SUCCESS :
                                                   STATUS_UNSUCCESSFUL;
    }
    else
    {
        /* Check if the app certification DLL isn't loaded */
        if (!(gSaferHandle) ||
            (gSaferHandle == (HMODULE)-1) ||
            (gSaferHandle == (HMODULE)-2))
        {
            /* Then we can't call the function */
            Status = STATUS_ENTRYPOINT_NOT_FOUND;
        }
        else
        {
            /* We have the DLL, find the address of the Safer function */
            Status = LdrGetProcedureAddress(gSaferHandle,
                                            &SaferiReplaceProcessThreadTokens,
                                            0,
                                            (PVOID*)&g_SaferReplaceProcessThreadTokens);
            if (NT_SUCCESS(Status))
            {
                /* Found it, now call it */
                Status = g_SaferReplaceProcessThreadTokens(TokenHandle,
                                                           ProcessHandle,
                                                           ThreadHandle) ?
                                                           STATUS_SUCCESS :
                                                           STATUS_UNSUCCESSFUL;
            }
            else
            {
                /* We couldn't find it, so this must be an unsupported DLL */
                LdrUnloadDll(gSaferHandle);
                gSaferHandle = NULL;
                Status = STATUS_ENTRYPOINT_NOT_FOUND;
            }
        }
    }

    /* Release the lock and return the result */
    RtlLeaveCriticalSection(&gcsAppCert);
    return Status;
}

VOID
WINAPI
BasepSxsCloseHandles(IN PBASE_MSG_SXS_HANDLES Handles)
{
    NTSTATUS Status;

    /* Sanity checks */
    ASSERT(Handles != NULL);
    ASSERT(Handles->Process == NULL || Handles->Process == NtCurrentProcess());

    /* Close the file handle */
    if (Handles->File)
    {
        Status = NtClose(Handles->File);
        ASSERT(NT_SUCCESS(Status));
    }

    /* Close the section handle */
    if (Handles->Section)
    {
        Status = NtClose(Handles->Section);
        ASSERT(NT_SUCCESS(Status));
    }

    /* Unmap the section view */
    if (Handles->ViewBase.QuadPart)
    {
        Status = NtUnmapViewOfSection(NtCurrentProcess(),
                                      (PVOID)(ULONG_PTR)Handles->ViewBase.QuadPart);
        ASSERT(NT_SUCCESS(Status));
    }
}

VOID
WINAPI
BaseProcessStartup(PPROCESS_START_ROUTINE lpStartAddress)
{
    DPRINT("BaseProcessStartup(..) - setting up exception frame.\n");

    _SEH2_TRY
    {
        /* Set our Start Address */
        NtSetInformationThread(NtCurrentThread(),
                               ThreadQuerySetWin32StartAddress,
                               &lpStartAddress,
                               sizeof(PPROCESS_START_ROUTINE));

        /* Call the Start Routine */
        ExitThread(lpStartAddress());
    }
    _SEH2_EXCEPT(UnhandledExceptionFilter(_SEH2_GetExceptionInformation()))
    {
        /* Get the Exit code from the SEH Handler */
        if (!BaseRunningInServerProcess)
        {
            /* Kill the whole process, usually */
            ExitProcess(_SEH2_GetExceptionCode());
        }
        else
        {
            /* If running inside CSRSS, kill just this thread */
            ExitThread(_SEH2_GetExceptionCode());
        }
    }
    _SEH2_END;
}

BOOLEAN
WINAPI
BasePushProcessParameters(IN ULONG ParameterFlags,
                          IN HANDLE ProcessHandle,
                          IN PPEB RemotePeb,
                          IN LPCWSTR ApplicationPathName,
                          IN LPWSTR lpCurrentDirectory,
                          IN LPWSTR lpCommandLine,
                          IN LPVOID lpEnvironment,
                          IN LPSTARTUPINFOW StartupInfo,
                          IN DWORD CreationFlags,
                          IN BOOL InheritHandles,
                          IN ULONG ImageSubsystem,
                          IN PVOID AppCompatData,
                          IN ULONG AppCompatDataSize)
{
    WCHAR FullPath[MAX_PATH + 5];
    PWCHAR Remaining, DllPathString, ScanChar;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters, RemoteParameters;
    PVOID RemoteAppCompatData;
    UNICODE_STRING DllPath, ImageName, CommandLine, CurrentDirectory;
    UNICODE_STRING Desktop, Shell, Runtime, Title;
    NTSTATUS Status;
    ULONG EnviroSize;
    SIZE_T Size;
    BOOLEAN HavePebLock = FALSE, Result;
    PPEB Peb = NtCurrentPeb();

    /* Get the full path name */
    Size = GetFullPathNameW(ApplicationPathName,
                            MAX_PATH + 4,
                            FullPath,
                            &Remaining);
    if ((Size) && (Size <= (MAX_PATH + 4)))
    {
        /* Get the DLL Path */
        DllPathString = BaseComputeProcessDllPath(FullPath, lpEnvironment);
        if (!DllPathString)
        {
            /* Fail */
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            return FALSE;
        }

        /* Initialize Strings */
        RtlInitUnicodeString(&DllPath, DllPathString);
        RtlInitUnicodeString(&ImageName, FullPath);
    }
    else
    {
        /* Couldn't get the path name. Just take the original path */
        DllPathString = BaseComputeProcessDllPath((LPWSTR)ApplicationPathName,
                                                  lpEnvironment);
        if (!DllPathString)
        {
            /* Fail */
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            return FALSE;
        }

        /* Initialize Strings */
        RtlInitUnicodeString(&DllPath, DllPathString);
        RtlInitUnicodeString(&ImageName, ApplicationPathName);
    }

    /* Initialize Strings */
    RtlInitUnicodeString(&CommandLine, lpCommandLine);
    RtlInitUnicodeString(&CurrentDirectory, lpCurrentDirectory);

    /* Initialize more Strings from the Startup Info */
    if (StartupInfo->lpDesktop)
    {
        RtlInitUnicodeString(&Desktop, StartupInfo->lpDesktop);
    }
    else
    {
        RtlInitUnicodeString(&Desktop, L"");
    }
    if (StartupInfo->lpReserved)
    {
        RtlInitUnicodeString(&Shell, StartupInfo->lpReserved);
    }
    else
    {
        RtlInitUnicodeString(&Shell, L"");
    }
    if (StartupInfo->lpTitle)
    {
        RtlInitUnicodeString(&Title, StartupInfo->lpTitle);
    }
    else
    {
        RtlInitUnicodeString(&Title, ApplicationPathName);
    }

    /* This one is special because the length can differ */
    Runtime.Buffer = (LPWSTR)StartupInfo->lpReserved2;
    Runtime.MaximumLength = Runtime.Length = StartupInfo->cbReserved2;

    /* Enforce no app compat data if the pointer was NULL */
    if (!AppCompatData) AppCompatDataSize = 0;

    /* Create the Parameter Block */
    ProcessParameters = NULL;
    DPRINT("ImageName: '%wZ'\n", &ImageName);
    DPRINT("DllPath  : '%wZ'\n", &DllPath);
    DPRINT("CurDir   : '%wZ'\n", &CurrentDirectory);
    DPRINT("CmdLine  : '%wZ'\n", &CommandLine);
    DPRINT("Title    : '%wZ'\n", &Title);
    DPRINT("Desktop  : '%wZ'\n", &Desktop);
    DPRINT("Shell    : '%wZ'\n", &Shell);
    DPRINT("Runtime  : '%wZ'\n", &Runtime);
    Status = RtlCreateProcessParameters(&ProcessParameters,
                                        &ImageName,
                                        &DllPath,
                                        lpCurrentDirectory ?
                                        &CurrentDirectory : NULL,
                                        &CommandLine,
                                        lpEnvironment,
                                        &Title,
                                        &Desktop,
                                        &Shell,
                                        &Runtime);
    if (!NT_SUCCESS(Status)) goto FailPath;

    /* Clear the current directory handle if not inheriting */
    if (!InheritHandles) ProcessParameters->CurrentDirectory.Handle = NULL;

    /* Check if the user passed in an environment */
    if (lpEnvironment)
    {
        /* We should've made it part of the parameters block, enforce this */
        ASSERT(ProcessParameters->Environment == lpEnvironment);
        lpEnvironment = ProcessParameters->Environment;
    }
    else
    {
        /* The user did not, so use the one from the current PEB */
        HavePebLock = TRUE;
        RtlAcquirePebLock();
        lpEnvironment = Peb->ProcessParameters->Environment;
    }

    /* Save pointer and start lookup */
    ScanChar = lpEnvironment;
    if (lpEnvironment)
    {
        /* Find the environment size */
        while (*ScanChar++) while (*ScanChar++);
        EnviroSize = (ULONG)((ULONG_PTR)ScanChar - (ULONG_PTR)lpEnvironment);

        /* Allocate and Initialize new Environment Block */
        Size = EnviroSize;
        ProcessParameters->Environment = NULL;
        Status = NtAllocateVirtualMemory(ProcessHandle,
                                         (PVOID*)&ProcessParameters->Environment,
                                         0,
                                         &Size,
                                         MEM_COMMIT,
                                         PAGE_READWRITE);
        if (!NT_SUCCESS(Status)) goto FailPath;

        /* Write the Environment Block */
        Status = NtWriteVirtualMemory(ProcessHandle,
                                      ProcessParameters->Environment,
                                      lpEnvironment,
                                      EnviroSize,
                                      NULL);

        /* No longer need the PEB lock anymore */
        if (HavePebLock)
        {
            /* Release it */
            RtlReleasePebLock();
            HavePebLock = FALSE;
        }

        /* Check if the write failed */
        if (!NT_SUCCESS(Status)) goto FailPath;
    }

    /* Write new parameters */
    ProcessParameters->StartingX = StartupInfo->dwX;
    ProcessParameters->StartingY = StartupInfo->dwY;
    ProcessParameters->CountX = StartupInfo->dwXSize;
    ProcessParameters->CountY = StartupInfo->dwYSize;
    ProcessParameters->CountCharsX = StartupInfo->dwXCountChars;
    ProcessParameters->CountCharsY = StartupInfo->dwYCountChars;
    ProcessParameters->FillAttribute = StartupInfo->dwFillAttribute;
    ProcessParameters->WindowFlags = StartupInfo->dwFlags;
    ProcessParameters->ShowWindowFlags = StartupInfo->wShowWindow;

    /* Write the handles only if we have to */
    if (StartupInfo->dwFlags &
        (STARTF_USESTDHANDLES | STARTF_USEHOTKEY | STARTF_SHELLPRIVATE))
    {
        ProcessParameters->StandardInput = StartupInfo->hStdInput;
        ProcessParameters->StandardOutput = StartupInfo->hStdOutput;
        ProcessParameters->StandardError = StartupInfo->hStdError;
    }

    /* Use Special Flags for ConDllInitialize in Kernel32 */
    if (CreationFlags & DETACHED_PROCESS)
    {
        ProcessParameters->ConsoleHandle = HANDLE_DETACHED_PROCESS;
    }
    else if (CreationFlags & CREATE_NEW_CONSOLE)
    {
        ProcessParameters->ConsoleHandle = HANDLE_CREATE_NEW_CONSOLE;
    }
    else if (CreationFlags & CREATE_NO_WINDOW)
    {
        ProcessParameters->ConsoleHandle = HANDLE_CREATE_NO_WINDOW;
    }
    else
    {
        /* Inherit our Console Handle */
        ProcessParameters->ConsoleHandle = Peb->ProcessParameters->ConsoleHandle;

        /* Make sure that the shell isn't trampling on our handles first */
        if (!(StartupInfo->dwFlags &
             (STARTF_USESTDHANDLES | STARTF_USEHOTKEY | STARTF_SHELLPRIVATE)))
        {
            /* Copy the handle if we are inheriting or if it's a console handle */
            if ((InheritHandles) ||
                (IsConsoleHandle(Peb->ProcessParameters->StandardInput)))
            {
                ProcessParameters->StandardInput = Peb->ProcessParameters->StandardInput;
            }
            if ((InheritHandles) ||
                (IsConsoleHandle(Peb->ProcessParameters->StandardOutput)))
            {
                ProcessParameters->StandardOutput = Peb->ProcessParameters->StandardOutput;
            }
            if ((InheritHandles) ||
                (IsConsoleHandle(Peb->ProcessParameters->StandardError)))
            {
                ProcessParameters->StandardError = Peb->ProcessParameters->StandardError;
            }
        }
    }

    /* Also set the Console Flag */
    if ((CreationFlags & CREATE_NEW_PROCESS_GROUP) &&
        (!(CreationFlags & CREATE_NEW_CONSOLE)))
    {
        ProcessParameters->ConsoleFlags = 1;
    }

    /* Check if there's a .local file present */
    if (ParameterFlags & 1)
    {
        ProcessParameters->Flags |= RTL_USER_PROCESS_PARAMETERS_LOCAL_DLL_PATH;
    }

    /* Check if we failed to open the IFEO key */
    if (ParameterFlags & 2)
    {
        ProcessParameters->Flags |= RTL_USER_PROCESS_PARAMETERS_IMAGE_KEY_MISSING;
    }

    /* Allocate memory for the parameter block */
    Size = ProcessParameters->Length;
    RemoteParameters = NULL;
    Status = NtAllocateVirtualMemory(ProcessHandle,
                                     (PVOID*)&RemoteParameters,
                                     0,
                                     &Size,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);
    if (!NT_SUCCESS(Status)) goto FailPath;

    /* Set the allocated size */
    ProcessParameters->MaximumLength = Size;

    /* Handle some Parameter Flags */
    ProcessParameters->Flags |= (CreationFlags & PROFILE_USER) ?
                                 RTL_USER_PROCESS_PARAMETERS_PROFILE_USER : 0;
    ProcessParameters->Flags |= (CreationFlags & PROFILE_KERNEL) ?
                                 RTL_USER_PROCESS_PARAMETERS_PROFILE_KERNEL : 0;
    ProcessParameters->Flags |= (CreationFlags & PROFILE_SERVER) ?
                                 RTL_USER_PROCESS_PARAMETERS_PROFILE_SERVER : 0;
    ProcessParameters->Flags |= (Peb->ProcessParameters->Flags &
                                 RTL_USER_PROCESS_PARAMETERS_DISABLE_HEAP_CHECKS);

    /* Write the Parameter Block */
    Status = NtWriteVirtualMemory(ProcessHandle,
                                  RemoteParameters,
                                  ProcessParameters,
                                  ProcessParameters->Length,
                                  NULL);
    if (!NT_SUCCESS(Status)) goto FailPath;

    /* Write the PEB Pointer */
    Status = NtWriteVirtualMemory(ProcessHandle,
                                  &RemotePeb->ProcessParameters,
                                  &RemoteParameters,
                                  sizeof(PVOID),
                                  NULL);
    if (!NT_SUCCESS(Status)) goto FailPath;

    /* Check if there's any app compat data to write */
    RemoteAppCompatData = NULL;
    if (AppCompatData)
    {
        /* Allocate some space for the application compatibility data */
        Size = AppCompatDataSize;
        Status = NtAllocateVirtualMemory(ProcessHandle,
                                         &RemoteAppCompatData,
                                         0,
                                         &Size,
                                         MEM_COMMIT,
                                         PAGE_READWRITE);
        if (!NT_SUCCESS(Status)) goto FailPath;

        /* Write the application compatibility data */
        Status = NtWriteVirtualMemory(ProcessHandle,
                                      RemoteAppCompatData,
                                      AppCompatData,
                                      AppCompatDataSize,
                                      NULL);
        if (!NT_SUCCESS(Status)) goto FailPath;
    }

    /* Write the PEB Pointer to the app compat data (might be NULL) */
    Status = NtWriteVirtualMemory(ProcessHandle,
                                  &RemotePeb->pShimData,
                                  &RemoteAppCompatData,
                                  sizeof(PVOID),
                                  NULL);
    if (!NT_SUCCESS(Status)) goto FailPath;

    /* Now write Peb->ImageSubSystem */
    if (ImageSubsystem)
    {
        NtWriteVirtualMemory(ProcessHandle,
                             &RemotePeb->ImageSubsystem,
                             &ImageSubsystem,
                             sizeof(ImageSubsystem),
                             NULL);
    }

    /* Success path */
    Result = TRUE;

Quickie:
    /* Cleanup */
    if (HavePebLock) RtlReleasePebLock();
    RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath.Buffer);
    if (ProcessParameters) RtlDestroyProcessParameters(ProcessParameters);
    return Result;
FailPath:
    DPRINT1("Failure to create process parameters: %lx\n", Status);
    BaseSetLastNTError(Status);
    Result = FALSE;
    goto Quickie;
}

VOID
WINAPI
InitCommandLines(VOID)
{
    NTSTATUS Status;

    /* Read the UNICODE_STRING from the PEB */
    BaseUnicodeCommandLine = NtCurrentPeb()->ProcessParameters->CommandLine;

    /* Convert to ANSI_STRING for the *A callers */
    Status = RtlUnicodeStringToAnsiString(&BaseAnsiCommandLine,
                                          &BaseUnicodeCommandLine,
                                          TRUE);
    if (!NT_SUCCESS(Status)) RtlInitEmptyAnsiString(&BaseAnsiCommandLine, 0, 0);
}

/* PUBLIC FUNCTIONS ***********************************************************/

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessAffinityMask(IN HANDLE hProcess,
                       OUT PDWORD_PTR lpProcessAffinityMask,
                       OUT PDWORD_PTR lpSystemAffinityMask)
{
    PROCESS_BASIC_INFORMATION ProcessInfo;
    NTSTATUS Status;

    /* Query information on the process from the kernel */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessBasicInformation,
                                       &ProcessInfo,
                                       sizeof(ProcessInfo),
                                       NULL);
    if (!NT_SUCCESS(Status))
    {
        /* Fail */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* Copy the affinity mask, and get the system one from our shared data */
    *lpProcessAffinityMask = (DWORD)ProcessInfo.AffinityMask;
    *lpSystemAffinityMask = (DWORD)BaseStaticServerData->SysInfo.ActiveProcessorsAffinityMask;
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
SetProcessAffinityMask(IN HANDLE hProcess,
                       IN DWORD_PTR dwProcessAffinityMask)
{
    NTSTATUS Status;

    /* Directly set the affinity mask */
    Status = NtSetInformationProcess(hProcess,
                                     ProcessAffinityMask,
                                     (PVOID)&dwProcessAffinityMask,
                                     sizeof(DWORD));
    if (!NT_SUCCESS(Status))
    {
        /* Handle failure */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* Everything was ok */
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessShutdownParameters(OUT LPDWORD lpdwLevel,
                             OUT LPDWORD lpdwFlags)
{
    BASE_API_MESSAGE ApiMessage;
    PBASE_GETSET_PROCESS_SHUTDOWN_PARAMS ShutdownParametersRequest = &ApiMessage.Data.ShutdownParametersRequest;

    /* Ask CSRSS for shutdown information */
    CsrClientCallServer((PCSR_API_MESSAGE)&ApiMessage,
                        NULL,
                        CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX, BasepGetProcessShutdownParam),
                        sizeof(*ShutdownParametersRequest));
    if (!NT_SUCCESS(ApiMessage.Status))
    {
        /* Return the failure from CSRSS */
        BaseSetLastNTError(ApiMessage.Status);
        return FALSE;
    }

    /* Get the data back */
    *lpdwLevel = ShutdownParametersRequest->ShutdownLevel;
    *lpdwFlags = ShutdownParametersRequest->ShutdownFlags;
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
SetProcessShutdownParameters(IN DWORD dwLevel,
                             IN DWORD dwFlags)
{
    BASE_API_MESSAGE ApiMessage;
    PBASE_GETSET_PROCESS_SHUTDOWN_PARAMS ShutdownParametersRequest = &ApiMessage.Data.ShutdownParametersRequest;

    /* Write the data into the CSRSS request and send it */
    ShutdownParametersRequest->ShutdownLevel = dwLevel;
    ShutdownParametersRequest->ShutdownFlags = dwFlags;
    CsrClientCallServer((PCSR_API_MESSAGE)&ApiMessage,
                        NULL,
                        CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX, BasepSetProcessShutdownParam),
                        sizeof(*ShutdownParametersRequest));
    if (!NT_SUCCESS(ApiMessage.Status))
    {
        /* Return the failure from CSRSS */
        BaseSetLastNTError(ApiMessage.Status);
        return FALSE;
    }

    /* All went well */
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessWorkingSetSizeEx(IN HANDLE hProcess,
                           OUT PSIZE_T lpMinimumWorkingSetSize,
                           OUT PSIZE_T lpMaximumWorkingSetSize,
                           OUT PDWORD Flags)
{
    QUOTA_LIMITS_EX QuotaLimits;
    NTSTATUS Status;

    /* Query the kernel about this */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessQuotaLimits,
                                       &QuotaLimits,
                                       sizeof(QuotaLimits),
                                       NULL);
    if (!NT_SUCCESS(Status))
    {
        /* Return error */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* Copy the quota information out */
    *lpMinimumWorkingSetSize = QuotaLimits.MinimumWorkingSetSize;
    *lpMaximumWorkingSetSize = QuotaLimits.MaximumWorkingSetSize;
    *Flags = QuotaLimits.Flags;
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessWorkingSetSize(IN HANDLE hProcess,
                         OUT PSIZE_T lpMinimumWorkingSetSize,
                         OUT PSIZE_T lpMaximumWorkingSetSize)
{
    DWORD Dummy;
    return GetProcessWorkingSetSizeEx(hProcess,
                                      lpMinimumWorkingSetSize,
                                      lpMaximumWorkingSetSize,
                                      &Dummy);
}

/*
 * @implemented
 */
BOOL
WINAPI
SetProcessWorkingSetSizeEx(IN HANDLE hProcess,
                           IN SIZE_T dwMinimumWorkingSetSize,
                           IN SIZE_T dwMaximumWorkingSetSize,
                           IN DWORD Flags)
{
    QUOTA_LIMITS_EX QuotaLimits;
    NTSTATUS Status, ReturnStatus;
    BOOL Result;
    PVOID State;
    ULONG Privilege = SE_INC_BASE_PRIORITY_PRIVILEGE;

    /* Zero out the input structure */
    RtlZeroMemory(&QuotaLimits, sizeof(QuotaLimits));

    /* Check if the caller sent any limits */
    if ((dwMinimumWorkingSetSize) && (dwMaximumWorkingSetSize))
    {
        /* Write the quota information */
        QuotaLimits.MinimumWorkingSetSize = dwMinimumWorkingSetSize;
        QuotaLimits.MaximumWorkingSetSize = dwMaximumWorkingSetSize;
        QuotaLimits.Flags = Flags;

        /* Acquire the required privilege */
        Status = RtlAcquirePrivilege(&Privilege, 1, 0, &State);

        /* Request the new quotas */
        ReturnStatus = NtSetInformationProcess(hProcess,
                                               ProcessQuotaLimits,
                                               &QuotaLimits,
                                               sizeof(QuotaLimits));
        Result = NT_SUCCESS(ReturnStatus);
        if (NT_SUCCESS(Status))
        {
            /* Release the privilege and set succes code */
            ASSERT(State != NULL);
            RtlReleasePrivilege(State);
            State = NULL;
        }
    }
    else
    {
        /* No limits, fail the call */
        ReturnStatus = STATUS_INVALID_PARAMETER;
        Result = FALSE;
    }

    /* Return result code, set error code if this was a failure */
    if (!Result) BaseSetLastNTError(ReturnStatus);
    return Result;
}

/*
 * @implemented
 */
BOOL
WINAPI
SetProcessWorkingSetSize(IN HANDLE hProcess,
                         IN SIZE_T dwMinimumWorkingSetSize,
                         IN SIZE_T dwMaximumWorkingSetSize)
{
    /* Call the newer API */
    return SetProcessWorkingSetSizeEx(hProcess,
                                      dwMinimumWorkingSetSize,
                                      dwMaximumWorkingSetSize,
                                      0);
}

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessTimes(IN HANDLE hProcess,
                IN LPFILETIME lpCreationTime,
                IN LPFILETIME lpExitTime,
                IN LPFILETIME lpKernelTime,
                IN LPFILETIME lpUserTime)
{
    KERNEL_USER_TIMES Kut;
    NTSTATUS Status;

    /* Query the times */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessTimes,
                                       &Kut,
                                       sizeof(Kut),
                                       NULL);
    if (!NT_SUCCESS(Status))
    {
        /* Handle failure */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* Copy all the times and return success */
    lpCreationTime->dwLowDateTime = Kut.CreateTime.u.LowPart;
    lpCreationTime->dwHighDateTime = Kut.CreateTime.u.HighPart;
    lpExitTime->dwLowDateTime = Kut.ExitTime.u.LowPart;
    lpExitTime->dwHighDateTime = Kut.ExitTime.u.HighPart;
    lpKernelTime->dwLowDateTime = Kut.KernelTime.u.LowPart;
    lpKernelTime->dwHighDateTime = Kut.KernelTime.u.HighPart;
    lpUserTime->dwLowDateTime = Kut.UserTime.u.LowPart;
    lpUserTime->dwHighDateTime = Kut.UserTime.u.HighPart;
    return TRUE;
}

/*
 * @implemented
 */
HANDLE
WINAPI
GetCurrentProcess(VOID)
{
    return (HANDLE)NtCurrentProcess();
}

/*
 * @implemented
 */
HANDLE
WINAPI
GetCurrentThread(VOID)
{
    return (HANDLE)NtCurrentThread();
}

/*
 * @implemented
 */
DWORD
WINAPI
GetCurrentProcessId(VOID)
{
    return HandleToUlong(NtCurrentTeb()->ClientId.UniqueProcess);
}

/*
 * @implemented
 */
BOOL
WINAPI
GetExitCodeProcess(IN HANDLE hProcess,
                   IN LPDWORD lpExitCode)
{
    PROCESS_BASIC_INFORMATION ProcessBasic;
    NTSTATUS Status;

    /* Ask the kernel */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessBasicInformation,
                                       &ProcessBasic,
                                       sizeof(ProcessBasic),
                                       NULL);
    if (!NT_SUCCESS(Status))
    {
        /* We failed, was this because this is a VDM process? */
        if (BaseCheckForVDM(hProcess, lpExitCode) != FALSE) return TRUE;

        /* Not a VDM process, fail the call */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* Succes case, return the exit code */
    *lpExitCode = (DWORD)ProcessBasic.ExitStatus;
    return TRUE;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetProcessId(IN HANDLE Process)
{
    PROCESS_BASIC_INFORMATION ProcessBasic;
    NTSTATUS Status;

    /* Query the kernel */
    Status = NtQueryInformationProcess(Process,
                                       ProcessBasicInformation,
                                       &ProcessBasic,
                                       sizeof(ProcessBasic),
                                       NULL);
    if (!NT_SUCCESS(Status))
    {
        /* Handle failure */
        BaseSetLastNTError(Status);
        return 0;
    }

    /* Return the PID */
    return (DWORD)ProcessBasic.UniqueProcessId;
}

/*
 * @implemented
 */
HANDLE
WINAPI
OpenProcess(IN DWORD dwDesiredAccess,
            IN BOOL bInheritHandle,
            IN DWORD dwProcessId)
{
    NTSTATUS Status;
    HANDLE ProcessHandle;
    OBJECT_ATTRIBUTES ObjectAttributes;
    CLIENT_ID ClientId;

    /* Setup the input client ID structure */
    ClientId.UniqueProcess = UlongToHandle(dwProcessId);
    ClientId.UniqueThread = 0;

    /* This is needed just to define the inheritance flags */
    InitializeObjectAttributes(&ObjectAttributes,
                               NULL,
                               (bInheritHandle ? OBJ_INHERIT : 0),
                               NULL,
                               NULL);

    /* Now try to open the process */
    Status = NtOpenProcess(&ProcessHandle,
                           dwDesiredAccess,
                           &ObjectAttributes,
                           &ClientId);
    if (!NT_SUCCESS(Status))
    {
        /* Handle failure */
        BaseSetLastNTError(Status);
        return NULL;
    }

    /* Otherwise return a handle to the process */
    return ProcessHandle;
}

/*
 * @implemented
 */
VOID
WINAPI
RegisterWaitForInputIdle(IN WaitForInputIdleType lpfnRegisterWaitForInputIdle)
{
    /* Write the global function pointer */
    UserWaitForInputIdleRoutine = lpfnRegisterWaitForInputIdle;
}

/*
 * @implemented
 */
VOID
WINAPI
GetStartupInfoW(IN LPSTARTUPINFOW lpStartupInfo)
{
    PRTL_USER_PROCESS_PARAMETERS Params;

    /* Get the process parameters */
    Params = NtCurrentPeb()->ProcessParameters;

    /* Copy the data out of there */
    lpStartupInfo->cb = sizeof(STARTUPINFOW);
    lpStartupInfo->lpReserved = Params->ShellInfo.Buffer;
    lpStartupInfo->lpDesktop = Params->DesktopInfo.Buffer;
    lpStartupInfo->lpTitle = Params->WindowTitle.Buffer;
    lpStartupInfo->dwX = Params->StartingX;
    lpStartupInfo->dwY = Params->StartingY;
    lpStartupInfo->dwXSize = Params->CountX;
    lpStartupInfo->dwYSize = Params->CountY;
    lpStartupInfo->dwXCountChars = Params->CountCharsX;
    lpStartupInfo->dwYCountChars = Params->CountCharsY;
    lpStartupInfo->dwFillAttribute = Params->FillAttribute;
    lpStartupInfo->dwFlags = Params->WindowFlags;
    lpStartupInfo->wShowWindow = (WORD)Params->ShowWindowFlags;
    lpStartupInfo->cbReserved2 = Params->RuntimeData.Length;
    lpStartupInfo->lpReserved2 = (LPBYTE)Params->RuntimeData.Buffer;

    /* Check if the standard handles are being used for other features */
    if (lpStartupInfo->dwFlags & (STARTF_USESTDHANDLES |
                                  STARTF_USEHOTKEY |
                                  STARTF_SHELLPRIVATE))
    {
        /* These are, so copy the standard handles too */
        lpStartupInfo->hStdInput = Params->StandardInput;
        lpStartupInfo->hStdOutput = Params->StandardOutput;
        lpStartupInfo->hStdError = Params->StandardError;
    }
}

/*
 * @implemented
 */
VOID
WINAPI
GetStartupInfoA(IN LPSTARTUPINFOA lpStartupInfo)
{
    PRTL_USER_PROCESS_PARAMETERS Params;
    ANSI_STRING TitleString, ShellString, DesktopString;
    LPSTARTUPINFOA StartupInfo;
    NTSTATUS Status;

    /* Get the cached information as well as the PEB parameters */
    StartupInfo = BaseAnsiStartupInfo;
    Params = NtCurrentPeb()->ProcessParameters;

    /* Check if this is the first time we have to get the cached version */
    while (!StartupInfo)
    {
        /* Create new ANSI startup info */
        StartupInfo = RtlAllocateHeap(RtlGetProcessHeap(),
                                      0,
                                      sizeof(*StartupInfo));
        if (StartupInfo)
        {
            /* Zero out string pointers in case we fail to create them */
            StartupInfo->lpReserved = NULL;
            StartupInfo->lpDesktop = NULL;
            StartupInfo->lpTitle = NULL;

            /* Set the size */
            StartupInfo->cb = sizeof(*StartupInfo);

            /* Copy what's already stored in the PEB */
            StartupInfo->dwX = Params->StartingX;
            StartupInfo->dwY = Params->StartingY;
            StartupInfo->dwXSize = Params->CountX;
            StartupInfo->dwYSize = Params->CountY;
            StartupInfo->dwXCountChars = Params->CountCharsX;
            StartupInfo->dwYCountChars = Params->CountCharsY;
            StartupInfo->dwFillAttribute = Params->FillAttribute;
            StartupInfo->dwFlags = Params->WindowFlags;
            StartupInfo->wShowWindow = (WORD)Params->ShowWindowFlags;
            StartupInfo->cbReserved2 = Params->RuntimeData.Length;
            StartupInfo->lpReserved2 = (LPBYTE)Params->RuntimeData.Buffer;
            StartupInfo->hStdInput = Params->StandardInput;
            StartupInfo->hStdOutput = Params->StandardOutput;
            StartupInfo->hStdError = Params->StandardError;

            /* Copy shell info string */
            Status = RtlUnicodeStringToAnsiString(&ShellString,
                                                  &Params->ShellInfo,
                                                  TRUE);
            if (NT_SUCCESS(Status))
            {
                /* Save it */
                StartupInfo->lpReserved = ShellString.Buffer;

                /* Copy desktop info string */
                Status = RtlUnicodeStringToAnsiString(&DesktopString,
                                                      &Params->DesktopInfo,
                                                      TRUE);
                if (NT_SUCCESS(Status))
                {
                    /* Save it */
                    StartupInfo->lpDesktop = DesktopString.Buffer;

                    /* Copy window title string */
                    Status = RtlUnicodeStringToAnsiString(&TitleString,
                                                          &Params->WindowTitle,
                                                          TRUE);
                    if (NT_SUCCESS(Status))
                    {
                        /* Save it */
                        StartupInfo->lpTitle = TitleString.Buffer;

                        /* We finished with the ANSI version, try to cache it */
                        if (!InterlockedCompareExchangePointer((PVOID*)&BaseAnsiStartupInfo,
                                                               StartupInfo,
                                                               NULL))
                        {
                            /* We were the first thread through, use the data */
                            break;
                        }

                        /* Someone beat us to it, use their data instead */
                        StartupInfo = BaseAnsiStartupInfo;
                        Status = STATUS_SUCCESS;

                        /* We're going to free our own stuff, but not raise */
                        RtlFreeAnsiString(&TitleString);
                    }
                    RtlFreeAnsiString(&DesktopString);
                }
                RtlFreeAnsiString(&ShellString);
            }
            RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo);
        }
        else
        {
            /* No memory, fail */
            Status = STATUS_NO_MEMORY;
        }

        /* Raise an error unless we got here due to the race condition */
        if (!NT_SUCCESS(Status)) RtlRaiseStatus(Status);
    }

    /* Now copy from the cached ANSI version */
    lpStartupInfo->cb = StartupInfo->cb;
    lpStartupInfo->lpReserved = StartupInfo->lpReserved;
    lpStartupInfo->lpDesktop = StartupInfo->lpDesktop;
    lpStartupInfo->lpTitle = StartupInfo->lpTitle;
    lpStartupInfo->dwX = StartupInfo->dwX;
    lpStartupInfo->dwY = StartupInfo->dwY;
    lpStartupInfo->dwXSize = StartupInfo->dwXSize;
    lpStartupInfo->dwYSize = StartupInfo->dwYSize;
    lpStartupInfo->dwXCountChars = StartupInfo->dwXCountChars;
    lpStartupInfo->dwYCountChars = StartupInfo->dwYCountChars;
    lpStartupInfo->dwFillAttribute = StartupInfo->dwFillAttribute;
    lpStartupInfo->dwFlags = StartupInfo->dwFlags;
    lpStartupInfo->wShowWindow = StartupInfo->wShowWindow;
    lpStartupInfo->cbReserved2 = StartupInfo->cbReserved2;
    lpStartupInfo->lpReserved2 = StartupInfo->lpReserved2;

    /* Check if the shell is hijacking the handles for other features */
    if (lpStartupInfo->dwFlags &
        (STARTF_USESTDHANDLES | STARTF_USEHOTKEY | STARTF_SHELLPRIVATE))
    {
        /* It isn't, so we can return the raw values */
        lpStartupInfo->hStdInput = StartupInfo->hStdInput;
        lpStartupInfo->hStdOutput = StartupInfo->hStdOutput;
        lpStartupInfo->hStdError = StartupInfo->hStdError;
    }
    else
    {
        /* It is, so make sure nobody uses these as console handles */
        lpStartupInfo->hStdInput = INVALID_HANDLE_VALUE;
        lpStartupInfo->hStdOutput = INVALID_HANDLE_VALUE;
        lpStartupInfo->hStdError = INVALID_HANDLE_VALUE;
    }
}

/*
 * @implemented
 */
BOOL
WINAPI
FlushInstructionCache(IN HANDLE hProcess,
                      IN LPCVOID lpBaseAddress,
                      IN SIZE_T nSize)
{
    NTSTATUS Status;

    /* Call the native function */
    Status = NtFlushInstructionCache(hProcess, (PVOID)lpBaseAddress, nSize);
    if (!NT_SUCCESS(Status))
    {
        /* Handle failure case */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* All good */
    return TRUE;
}

/*
 * @implemented
 */
VOID
WINAPI
ExitProcess(IN UINT uExitCode)
{
    BASE_API_MESSAGE ApiMessage;
    PBASE_EXIT_PROCESS ExitProcessRequest = &ApiMessage.Data.ExitProcessRequest;

    ASSERT(!BaseRunningInServerProcess);

    _SEH2_TRY
    {
        /* Acquire the PEB lock */
        RtlAcquirePebLock();

        /* Kill all the threads */
        NtTerminateProcess(NULL, uExitCode);

        /* Unload all DLLs */
        LdrShutdownProcess();

        /* Notify Base Server of process termination */
        ExitProcessRequest->uExitCode = uExitCode;
        CsrClientCallServer((PCSR_API_MESSAGE)&ApiMessage,
                            NULL,
                            CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX, BasepExitProcess),
                            sizeof(*ExitProcessRequest));

        /* Now do it again */
        NtTerminateProcess(NtCurrentProcess(), uExitCode);
    }
    _SEH2_FINALLY
    {
        /* Release the PEB lock */
        RtlReleasePebLock();
    }
    _SEH2_END;

    /* should never get here */
    ASSERT(0);
    while(1);
}

/*
 * @implemented
 */
BOOL
WINAPI
TerminateProcess(IN HANDLE hProcess,
                 IN UINT uExitCode)
{
    NTSTATUS Status;

    /* Check if no handle was passed in */
    if (!hProcess)
    {
        /* Set error code */
        SetLastError(ERROR_INVALID_HANDLE);
    }
    else
    {
        /* Otherwise, try to terminate the process */
        Status = NtTerminateProcess(hProcess, uExitCode);
        if (NT_SUCCESS(Status)) return TRUE;

        /* It failed, convert error code */
        BaseSetLastNTError(Status);
    }

    /* This is the failure path */
    return FALSE;
}

/*
 * @implemented
 */
VOID
WINAPI
FatalAppExitA(UINT uAction,
              LPCSTR lpMessageText)
{
    PUNICODE_STRING MessageTextU;
    ANSI_STRING MessageText;
    NTSTATUS Status;

    /* Initialize the string using the static TEB pointer */
    MessageTextU = &NtCurrentTeb()->StaticUnicodeString;
    RtlInitAnsiString(&MessageText, (LPSTR)lpMessageText);

    /* Convert to unicode, or just exit normally if this failed */
    Status = RtlAnsiStringToUnicodeString(MessageTextU, &MessageText, FALSE);
    if (!NT_SUCCESS(Status)) ExitProcess(0);

    /* Call the Wide function */
    FatalAppExitW(uAction, MessageTextU->Buffer);
}

/*
 * @implemented
 */
VOID
WINAPI
FatalAppExitW(IN UINT uAction,
              IN LPCWSTR lpMessageText)
{
    UNICODE_STRING UnicodeString;
    ULONG Response;
    NTSTATUS Status;

    /* Setup the string to print out */
    RtlInitUnicodeString(&UnicodeString, lpMessageText);

    /* Display the hard error no matter what */
    Status = NtRaiseHardError(STATUS_FATAL_APP_EXIT | HARDERROR_OVERRIDE_ERRORMODE,
                              1,
                              1,
                              (PULONG_PTR)&UnicodeString,
#if DBG
    /* On Checked builds, Windows allows the user to cancel the operation */
                              OptionOkCancel,
#else
                              OptionOk,
#endif
                              &Response);

#if DBG
    /* Give the user a chance to abort */
    if ((NT_SUCCESS(Status)) && (Response == ResponseCancel)) return;
#endif

    /* Otherwise kill the process */
    ExitProcess(0);
}

/*
 * @implemented
 */
VOID
WINAPI
FatalExit(IN int ExitCode)
{
#if DBG
    /* On Checked builds, Windows gives the user a nice little debugger UI */
    CHAR ch[2];
    DbgPrint("FatalExit...\n");
    DbgPrint("\n");

    while (TRUE)
    {
        DbgPrompt( "A (Abort), B (Break), I (Ignore)? ", ch, sizeof(ch));
        switch (ch[0])
        {
            case 'B': case 'b':
                 DbgBreakPoint();
                 break;

            case 'A': case 'a':
                ExitProcess(ExitCode);

            case 'I': case 'i':
                return;
        }
    }
#endif
    /* On other builds, just kill the process */
    ExitProcess(ExitCode);
}

/*
 * @implemented
 */
DWORD
WINAPI
GetPriorityClass(IN HANDLE hProcess)
{
    NTSTATUS Status;
    PROCESS_PRIORITY_CLASS PriorityClass;

    /* Query the kernel */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessPriorityClass,
                                       &PriorityClass,
                                       sizeof(PriorityClass),
                                       NULL);
    if (NT_SUCCESS(Status))
    {
        /* Handle the conversion from NT to Win32 classes */
        switch (PriorityClass.PriorityClass)
        {
            case PROCESS_PRIORITY_CLASS_IDLE: return IDLE_PRIORITY_CLASS;
            case PROCESS_PRIORITY_CLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
            case PROCESS_PRIORITY_CLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
            case PROCESS_PRIORITY_CLASS_HIGH: return HIGH_PRIORITY_CLASS;
            case PROCESS_PRIORITY_CLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
            case PROCESS_PRIORITY_CLASS_NORMAL: default: return NORMAL_PRIORITY_CLASS;
        }
    }

    /* Failure path */
    BaseSetLastNTError(Status);
    return FALSE;
}

/*
 * @implemented
 */
BOOL
WINAPI
SetPriorityClass(IN HANDLE hProcess,
                 IN DWORD dwPriorityClass)
{
    NTSTATUS Status;
    PVOID State = NULL;
    PROCESS_PRIORITY_CLASS PriorityClass;

    /* Handle conversion from Win32 to NT priority classes */
    switch (dwPriorityClass)
    {
        case IDLE_PRIORITY_CLASS:
            PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_IDLE;
            break;

        case BELOW_NORMAL_PRIORITY_CLASS:
            PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
            break;

        case NORMAL_PRIORITY_CLASS:
            PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_NORMAL;
            break;

        case ABOVE_NORMAL_PRIORITY_CLASS:
            PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
            break;

        case HIGH_PRIORITY_CLASS:
            PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_HIGH;
            break;

        case REALTIME_PRIORITY_CLASS:
            /* Try to acquire the privilege. If it fails, just use HIGH */
            State = BasepIsRealtimeAllowed(TRUE);
            PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_HIGH;
            PriorityClass.PriorityClass += (State != NULL);
            break;

        default:
            /* Unrecognized priority classes don't make it to the kernel */
            SetLastError(ERROR_INVALID_PARAMETER);
            return FALSE;
    }

    /* Send the request to the kernel, and don't touch the foreground flag */
    PriorityClass.Foreground = FALSE;
    Status = NtSetInformationProcess(hProcess,
                                     ProcessPriorityClass,
                                     &PriorityClass,
                                     sizeof(PROCESS_PRIORITY_CLASS));

    /* Release the privilege if we had it */
    if (State) RtlReleasePrivilege(State);
    if (!NT_SUCCESS(Status))
    {
        /* Handle error path */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* All done */
    return TRUE;
}

/*
 * @implemented
 */
DWORD
WINAPI
GetProcessVersion(IN DWORD ProcessId)
{
    DWORD Version = 0;
    PIMAGE_NT_HEADERS NtHeader;
    PIMAGE_DOS_HEADER DosHeader;
    PPEB Peb;
    PROCESS_BASIC_INFORMATION ProcessBasicInfo;
    PVOID BaseAddress;
    ULONG e_lfanew;
    HANDLE ProcessHandle = NULL;
    NTSTATUS Status;
    USHORT VersionData[2];
    BOOLEAN Result;

    /* We'll be accessing stuff that can fault, so protect everything with SEH */
    _SEH2_TRY
    {
        /* It this an in-process or out-of-process request? */
        if (!(ProcessId) || (GetCurrentProcessId() == ProcessId))
        {
            /* It's in-process, so just read our own header */
            NtHeader = RtlImageNtHeader(NtCurrentPeb()->ImageBaseAddress);
            if (!NtHeader)
            {
                /* Unable to read the NT header, something is wrong here... */
                Status = STATUS_INVALID_IMAGE_FORMAT;
                goto Error;
            }

            /* Get the version straight out of the NT header */
            Version = MAKELONG(NtHeader->OptionalHeader.MinorSubsystemVersion,
                               NtHeader->OptionalHeader.MajorSubsystemVersion);
        }
        else
        {
            /* Out-of-process, so open it */
            ProcessHandle = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,
                                        FALSE,
                                        ProcessId);
            if (!ProcessHandle) _SEH2_YIELD(return 0);

            /* Try to find out where its PEB lives */
            Status = NtQueryInformationProcess(ProcessHandle,
                                               ProcessBasicInformation,
                                               &ProcessBasicInfo,
                                               sizeof(ProcessBasicInfo),
                                               NULL);

            if (!NT_SUCCESS(Status)) goto Error;
            Peb = ProcessBasicInfo.PebBaseAddress;

            /* Now that we have the PEB, read the image base address out of it */
            Result = ReadProcessMemory(ProcessHandle,
                                       &Peb->ImageBaseAddress,
                                       &BaseAddress,
                                       sizeof(BaseAddress),
                                       NULL);
            if (!Result) goto Error;

            /* Now read the e_lfanew (offset to NT header) from the base */
            DosHeader = BaseAddress;
            Result = ReadProcessMemory(ProcessHandle,
                                       &DosHeader->e_lfanew,
                                       &e_lfanew,
                                       sizeof(e_lfanew),
                                       NULL);
            if (!Result) goto Error;

            /* And finally, read the NT header itself by adding the offset */
            NtHeader = (PVOID)((ULONG_PTR)BaseAddress + e_lfanew);
            Result = ReadProcessMemory(ProcessHandle,
                                       &NtHeader->OptionalHeader.MajorSubsystemVersion,
                                       &VersionData,
                                       sizeof(VersionData),
                                       NULL);
            if (!Result) goto Error;

            /* Get the version straight out of the NT header */
            Version = MAKELONG(VersionData[0], VersionData[1]);

Error:
            /* If there was an error anywhere, set the last error */
            if (!NT_SUCCESS(Status)) BaseSetLastNTError(Status);
        }
    }
    _SEH2_FINALLY
    {
        /* Close the process handle */
        if (ProcessHandle) CloseHandle(ProcessHandle);
    }
    _SEH2_END;

    /* And return the version data */
    return Version;
}

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessIoCounters(IN HANDLE hProcess,
                     OUT PIO_COUNTERS lpIoCounters)
{
    NTSTATUS Status;

    /* Query the kernel. Structures are identical, so let it do the copy too. */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessIoCounters,
                                       lpIoCounters,
                                       sizeof(IO_COUNTERS),
                                       NULL);
    if (!NT_SUCCESS(Status))
    {
        /* Handle error path */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* All done */
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessPriorityBoost(IN HANDLE hProcess,
                        OUT PBOOL pDisablePriorityBoost)
{
    NTSTATUS Status;
    ULONG PriorityBoost;

    /* Query the kernel */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessPriorityBoost,
                                       &PriorityBoost,
                                       sizeof(PriorityBoost),
                                       NULL);
    if (NT_SUCCESS(Status))
    {
        /* Convert from ULONG to a BOOL */
        *pDisablePriorityBoost = PriorityBoost ? TRUE : FALSE;
        return TRUE;
    }

    /* Handle error path */
    BaseSetLastNTError(Status);
    return FALSE;
}

/*
 * @implemented
 */
BOOL
WINAPI
SetProcessPriorityBoost(IN HANDLE hProcess,
                        IN BOOL bDisablePriorityBoost)
{
    NTSTATUS Status;
    ULONG PriorityBoost;

    /* Enforce that this is a BOOL, and send it to the kernel as a ULONG */
    PriorityBoost = (bDisablePriorityBoost ? TRUE : FALSE);
    Status = NtSetInformationProcess(hProcess,
                                     ProcessPriorityBoost,
                                     &PriorityBoost,
                                     sizeof(ULONG));
    if (!NT_SUCCESS(Status))
    {
        /* Handle error path */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* All done */
    return TRUE;
}

/*
 * @implemented
 */
BOOL
WINAPI
GetProcessHandleCount(IN HANDLE hProcess,
                      OUT PDWORD pdwHandleCount)
{
    ULONG phc;
    NTSTATUS Status;

    /* Query the kernel */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessHandleCount,
                                       &phc,
                                       sizeof(phc),
                                       NULL);
    if (NT_SUCCESS(Status))
    {
        /* Copy the count and return success */
        *pdwHandleCount = phc;
        return TRUE;
    }

    /* Handle error path */
    BaseSetLastNTError(Status);
    return FALSE;
}

/*
 * @implemented
 */
BOOL
WINAPI
IsWow64Process(IN HANDLE hProcess,
               OUT PBOOL Wow64Process)
{
    ULONG_PTR pbi;
    NTSTATUS Status;

    /* Query the kernel */
    Status = NtQueryInformationProcess(hProcess,
                                       ProcessWow64Information,
                                       &pbi,
                                       sizeof(pbi),
                                       NULL);
    if (!NT_SUCCESS(Status))
    {
        /* Handle error path */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* Enforce this is a BOOL, and return success */
    *Wow64Process = (pbi != 0);
    return TRUE;
}

/*
 * @implemented
 */
LPSTR
WINAPI
GetCommandLineA(VOID)
{
    return BaseAnsiCommandLine.Buffer;
}

/*
 * @implemented
 */
LPWSTR
WINAPI
GetCommandLineW(VOID)
{
    return BaseUnicodeCommandLine.Buffer;
}

/*
 * @implemented
 */
BOOL
NTAPI
ReadProcessMemory(IN HANDLE hProcess,
                  IN LPCVOID lpBaseAddress,
                  IN LPVOID lpBuffer,
                  IN SIZE_T nSize,
                  OUT SIZE_T* lpNumberOfBytesRead)
{
    NTSTATUS Status;

    /* Do the read */
    Status = NtReadVirtualMemory(hProcess,
                                 (PVOID)lpBaseAddress,
                                 lpBuffer,
                                 nSize,
                                 &nSize);

    /* In user-mode, this parameter is optional */
    if (lpNumberOfBytesRead) *lpNumberOfBytesRead = nSize;
    if (!NT_SUCCESS(Status))
    {
        /* We failed */
        BaseSetLastNTError(Status);
        return FALSE;
    }

    /* Return success */
    return TRUE;
}

/*
 * @implemented
 */
BOOL
NTAPI
WriteProcessMemory(IN HANDLE hProcess,
                   IN LPVOID lpBaseAddress,
                   IN LPCVOID lpBuffer,
                   IN SIZE_T nSize,
                   OUT SIZE_T *lpNumberOfBytesWritten)
{
    NTSTATUS Status;
    ULONG OldValue;
    SIZE_T RegionSize;
    PVOID Base;
    BOOLEAN UnProtect;

    /* Set parameters for protect call */
    RegionSize = nSize;
    Base = lpBaseAddress;

    /* Check the current status */
    Status = NtProtectVirtualMemory(hProcess,
                                    &Base,
                                    &RegionSize,
                                    PAGE_EXECUTE_READWRITE,
                                    &OldValue);
    if (NT_SUCCESS(Status))
    {
        /* Check if we are unprotecting */
        UnProtect = OldValue & (PAGE_READWRITE |
                                PAGE_WRITECOPY |
                                PAGE_EXECUTE_READWRITE |
                                PAGE_EXECUTE_WRITECOPY) ? FALSE : TRUE;
        if (!UnProtect)
        {
            /* Set the new protection */
            Status = NtProtectVirtualMemory(hProcess,<--- Status is assigned
                                            &Base,
                                            &RegionSize,
                                            OldValue,
                                            &OldValue);

            /* Write the memory */
            Status = NtWriteVirtualMemory(hProcess,<--- Status is overwritten
                                          lpBaseAddress,
                                          (LPVOID)lpBuffer,
                                          nSize,
                                          &nSize);

            /* In Win32, the parameter is optional, so handle this case */
            if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = nSize;

            if (!NT_SUCCESS(Status))
            {
                /* We failed */
                BaseSetLastNTError(Status);
                return FALSE;
            }

            /* Flush the ITLB */
            NtFlushInstructionCache(hProcess, lpBaseAddress, nSize);
            return TRUE;
        }
        else
        {
            /* Check if we were read only */
            if (OldValue & (PAGE_NOACCESS | PAGE_READONLY))
            {
                /* Restore protection and fail */
                NtProtectVirtualMemory(hProcess,
                                       &Base,
                                       &RegionSize,
                                       OldValue,
                                       &OldValue);
                BaseSetLastNTError(STATUS_ACCESS_VIOLATION);

                /* Note: This is what Windows returns and code depends on it */
                return STATUS_ACCESS_VIOLATION;
            }

            /* Otherwise, do the write */
            Status = NtWriteVirtualMemory(hProcess,
                                          lpBaseAddress,
                                          (LPVOID)lpBuffer,
                                          nSize,
                                          &nSize);

            /* In Win32, the parameter is optional, so handle this case */
            if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = nSize;

            /* And restore the protection */
            NtProtectVirtualMemory(hProcess,
                                   &Base,
                                   &RegionSize,
                                   OldValue,
                                   &OldValue);
            if (!NT_SUCCESS(Status))
            {
                /* We failed */
                BaseSetLastNTError(STATUS_ACCESS_VIOLATION);

                /* Note: This is what Windows returns and code depends on it */
                return STATUS_ACCESS_VIOLATION;
            }

            /* Flush the ITLB */
            NtFlushInstructionCache(hProcess, lpBaseAddress, nSize);
            return TRUE;
        }
    }
    else
    {
        /* We failed */
        BaseSetLastNTError(Status);
        return FALSE;
    }
}

/*
 * @implemented
 */
BOOL
WINAPI
ProcessIdToSessionId(IN DWORD dwProcessId,
                     OUT PDWORD pSessionId)
{
    PROCESS_SESSION_INFORMATION SessionInformation;
    OBJECT_ATTRIBUTES ObjectAttributes;
    CLIENT_ID ClientId;
    HANDLE ProcessHandle;
    NTSTATUS Status;

    /* Do a quick check if the pointer is not writable */
    if (IsBadWritePtr(pSessionId, sizeof(DWORD)))
    {
        /* Fail fast */
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    /* Open the process passed in by ID */
    ClientId.UniqueProcess = UlongToHandle(dwProcessId);
    ClientId.UniqueThread = 0;
    InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
    Status = NtOpenProcess(&ProcessHandle,
                           PROCESS_QUERY_INFORMATION,
                           &ObjectAttributes,
                           &ClientId);
    if (NT_SUCCESS(Status))
    {
        /* Query the session ID from the kernel */
        Status = NtQueryInformationProcess(ProcessHandle,
                                           ProcessSessionInformation,
                                           &SessionInformation,
                                           sizeof(SessionInformation),
                                           NULL);

        /* Close the handle and check if we succeeded */
        NtClose(ProcessHandle);
        if (NT_SUCCESS(Status))
        {
            /* Return the session ID */
            *pSessionId = SessionInformation.SessionId;
            return TRUE;
        }
    }

    /* Set error code and fail */
    BaseSetLastNTError(Status);
    return FALSE;
}


#define AddToHandle(x,y)  (x) = (HANDLE)((ULONG_PTR)(x) | (y));
#define RemoveFromHandle(x,y)  (x) = (HANDLE)((ULONG_PTR)(x) & ~(y));
C_ASSERT(PROCESS_PRIORITY_CLASS_REALTIME == (PROCESS_PRIORITY_CLASS_HIGH + 1));

/*
 * @implemented
 */
BOOL
WINAPI
CreateProcessInternalW(IN HANDLE hUserToken,
                       IN LPCWSTR lpApplicationName,
                       IN LPWSTR lpCommandLine,
                       IN LPSECURITY_ATTRIBUTES lpProcessAttributes,
                       IN LPSECURITY_ATTRIBUTES lpThreadAttributes,
                       IN BOOL bInheritHandles,
                       IN DWORD dwCreationFlags,
                       IN LPVOID lpEnvironment,
                       IN LPCWSTR lpCurrentDirectory,
                       IN LPSTARTUPINFOW lpStartupInfo,
                       IN LPPROCESS_INFORMATION lpProcessInformation,
                       OUT PHANDLE hNewToken)
{
    //
    // Core variables used for creating the initial process and thread
    //
    SECURITY_ATTRIBUTES LocalThreadAttributes, LocalProcessAttributes;
    OBJECT_ATTRIBUTES LocalObjectAttributes;
    POBJECT_ATTRIBUTES ObjectAttributes;
    SECTION_IMAGE_INFORMATION ImageInformation;
    IO_STATUS_BLOCK IoStatusBlock;
    CLIENT_ID ClientId;
    ULONG NoWindow, StackSize, ErrorCode, Flags;
    SIZE_T RegionSize;
    USHORT ImageMachine;
    ULONG ParameterFlags, PrivilegeValue, HardErrorMode, ErrorResponse;
    ULONG_PTR ErrorParameters[2];
    BOOLEAN InJob, SaferNeeded, UseLargePages, HavePrivilege;
    BOOLEAN QuerySection, SkipSaferAndAppCompat;
    CONTEXT Context;
    BASE_API_MESSAGE CsrMsg[2];
    PBASE_CREATE_PROCESS CreateProcessMsg;
    PCSR_CAPTURE_BUFFER CaptureBuffer;
    PVOID BaseAddress, PrivilegeState, RealTimePrivilegeState;
    HANDLE DebugHandle, TokenHandle, JobHandle, KeyHandle, ThreadHandle;
    HANDLE FileHandle, SectionHandle, ProcessHandle;
    ULONG ResumeCount;
    PROCESS_PRIORITY_CLASS PriorityClass;
    NTSTATUS Status, AppCompatStatus, SaferStatus, IFEOStatus, ImageDbgStatus;
    PPEB Peb, RemotePeb;
    PTEB Teb;
    INITIAL_TEB InitialTeb;
    PVOID TibValue;
    PIMAGE_NT_HEADERS NtHeaders;
    STARTUPINFOW StartupInfo;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
    UNICODE_STRING DebuggerString;
    BOOL Result;
    //
    // Variables used for command-line and argument parsing
    //
    PCHAR pcScan;
    SIZE_T n;
    WCHAR SaveChar;
    ULONG Length, FileAttribs, CmdQuoteLength;
    ULONG ResultSize;
    SIZE_T EnvironmentLength, CmdLineLength;
    PWCHAR QuotedCmdLine, AnsiCmdCommand, ExtBuffer, CurrentDirectory;
    PWCHAR NullBuffer, ScanString, NameBuffer, SearchPath, DebuggerCmdLine;
    ANSI_STRING AnsiEnv;
    UNICODE_STRING UnicodeEnv, PathName;
    BOOLEAN SearchRetry, QuotesNeeded, CmdLineIsAppName, HasQuotes;

    //
    // Variables used for Fusion/SxS (Side-by-Side Assemblies)
    //
    RTL_PATH_TYPE SxsPathType, PathType;
#if _SXS_SUPPORT_ENABLED_
    PRTL_BUFFER ByteBuffer;
    PRTL_UNICODE_STRING_BUFFER ThisBuffer, Buffer, SxsStaticBuffers[5];<--- Unused variable: Buffer
    PRTL_UNICODE_STRING_BUFFER* BufferHead, SxsStringBuffer;<--- Unused variable: BufferHead<--- Unused variable: SxsStringBuffer
    RTL_UNICODE_STRING_BUFFER SxsWin32ManifestPath, SxsNtManifestPath;
    RTL_UNICODE_STRING_BUFFER SxsWin32PolicyPath, SxsNtPolicyPath;
    RTL_UNICODE_STRING_BUFFER SxsWin32AssemblyDirectory;
    BASE_MSG_SXS_HANDLES MappedHandles, Handles, FileHandles;
    PVOID CapturedStrings[3];
    SXS_WIN32_NT_PATH_PAIR ExePathPair, ManifestPathPair, PolicyPathPair;
    SXS_OVERRIDE_MANIFEST OverrideManifest;<--- Unused variable: OverrideManifest
    UNICODE_STRING FreeString, SxsNtExePath;
    PWCHAR SxsConglomeratedBuffer, StaticBuffer;<--- Unused variable: StaticBuffer
    ULONG ConglomeratedBufferSizeBytes, StaticBufferSize, i;<--- Unused variable: ConglomeratedBufferSizeBytes<--- Unused variable: StaticBufferSize
#endif
    ULONG FusionFlags;

    //
    // Variables used for path conversion (and partially Fusion/SxS)
    //
    PWCHAR FilePart, PathBuffer, FreeBuffer;
    BOOLEAN TranslationStatus;
    RTL_RELATIVE_NAME_U SxsWin32RelativePath;
    UNICODE_STRING PathBufferString, SxsWin32ExePath;

    //
    // Variables used by Application Compatibility (and partially Fusion/SxS)
    //
    PVOID AppCompatSxsData, AppCompatData;
    ULONG AppCompatSxsDataSize, AppCompatDataSize;
    //
    // Variables used by VDM (Virtual Dos Machine) and WOW32 (16-bit Support)
    //
    ULONG BinarySubType, VdmBinaryType, VdmTask, VdmReserve;
    ULONG VdmUndoLevel;
    BOOLEAN UseVdmReserve;
    HANDLE VdmWaitObject;
    ANSI_STRING VdmAnsiEnv;
    UNICODE_STRING VdmString, VdmUnicodeEnv;
    BOOLEAN IsWowApp;
    PBASE_CHECK_VDM CheckVdmMsg;

    /* Zero out the initial core variables and handles */
    QuerySection = FALSE;
    InJob = FALSE;
    SkipSaferAndAppCompat = FALSE;
    ParameterFlags = 0;
    Flags = 0;
    DebugHandle = NULL;
    JobHandle = NULL;
    TokenHandle = NULL;
    FileHandle = NULL;
    SectionHandle = NULL;
    ProcessHandle = NULL;
    ThreadHandle = NULL;
    BaseAddress = (PVOID)1;

    /* Zero out initial SxS and Application Compatibility state */
    AppCompatData = NULL;
    AppCompatDataSize = 0;
    AppCompatSxsData = NULL;
    AppCompatSxsDataSize = 0;
    CaptureBuffer = NULL;
#if _SXS_SUPPORT_ENABLED_
    SxsConglomeratedBuffer = NULL;
#endif
    FusionFlags = 0;

    /* Zero out initial parsing variables -- others are initialized later */
    DebuggerCmdLine = NULL;
    PathBuffer = NULL;
    SearchPath = NULL;
    NullBuffer = NULL;
    FreeBuffer = NULL;
    NameBuffer = NULL;
    CurrentDirectory = NULL;
    FilePart = NULL;
    DebuggerString.Buffer = NULL;
    HasQuotes = FALSE;
    QuotedCmdLine = NULL;

    /* Zero out initial VDM state */
    VdmAnsiEnv.Buffer = NULL;
    VdmUnicodeEnv.Buffer = NULL;
    VdmString.Buffer = NULL;
    VdmTask = 0;
    VdmUndoLevel = 0;
    VdmBinaryType = 0;
    VdmReserve = 0;
    VdmWaitObject = NULL;
    UseVdmReserve = FALSE;
    IsWowApp = FALSE;

    /* Set message structures */
    CreateProcessMsg = &CsrMsg[0].Data.CreateProcessRequest;
    CheckVdmMsg = &CsrMsg[1].Data.CheckVDMRequest;

    /* Clear the more complex structures by zeroing out their entire memory */
    RtlZeroMemory(&Context, sizeof(Context));
#if _SXS_SUPPORT_ENABLED_
    RtlZeroMemory(&FileHandles, sizeof(FileHandles));
    RtlZeroMemory(&MappedHandles, sizeof(MappedHandles));
    RtlZeroMemory(&Handles, sizeof(Handles));
#endif
    RtlZeroMemory(&CreateProcessMsg->Sxs, sizeof(CreateProcessMsg->Sxs));
    RtlZeroMemory(&LocalProcessAttributes, sizeof(LocalProcessAttributes));
    RtlZeroMemory(&LocalThreadAttributes, sizeof(LocalThreadAttributes));

    /* Zero out output arguments as well */
    RtlZeroMemory(lpProcessInformation, sizeof(*lpProcessInformation));
    if (hNewToken) *hNewToken = NULL;

    /* Capture the special window flag */
    NoWindow = dwCreationFlags & CREATE_NO_WINDOW;
    dwCreationFlags &= ~CREATE_NO_WINDOW;

#if _SXS_SUPPORT_ENABLED_
    /* Setup the SxS static string arrays and buffers */
    SxsStaticBuffers[0] = &SxsWin32ManifestPath;<--- Address of variable taken here.<--- Address of variable taken here.<--- Address of variable taken here.<--- Address of variable taken here.<--- Address of variable taken here.
    SxsStaticBuffers[1] = &SxsWin32PolicyPath;<--- The address of local variable 'SxsWin32ManifestPath' is accessed at non-zero index.
    SxsStaticBuffers[2] = &SxsWin32AssemblyDirectory;<--- The address of local variable 'SxsWin32ManifestPath' is accessed at non-zero index.
    SxsStaticBuffers[3] = &SxsNtManifestPath;<--- The address of local variable 'SxsWin32ManifestPath' is accessed at non-zero index.
    SxsStaticBuffers[4] = &SxsNtPolicyPath;<--- The address of local variable 'SxsWin32ManifestPath' is accessed at non-zero index.
    ExePathPair.Win32 = &SxsWin32ExePath;
    ExePathPair.Nt = &SxsNtExePath;
    ManifestPathPair.Win32 = &SxsWin32ManifestPath.String;
    ManifestPathPair.Nt = &SxsNtManifestPath.String;
    PolicyPathPair.Win32 = &SxsWin32PolicyPath.String;
    PolicyPathPair.Nt = &SxsNtPolicyPath.String;
#endif

    DPRINT("CreateProcessInternalW: '%S' '%S' %lx\n", lpApplicationName, lpCommandLine, dwCreationFlags);

    /* Finally, set our TEB and PEB */
    Teb = NtCurrentTeb();
    Peb = NtCurrentPeb();

    /* This combination is illegal (see MSDN) */
    if ((dwCreationFlags & (DETACHED_PROCESS | CREATE_NEW_CONSOLE)) ==
        (DETACHED_PROCESS | CREATE_NEW_CONSOLE))
    {
        DPRINT1("Invalid flag combo used\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    /* Convert the priority class */
    if (dwCreationFlags & IDLE_PRIORITY_CLASS)
    {
        PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_IDLE;
    }
    else if (dwCreationFlags & BELOW_NORMAL_PRIORITY_CLASS)
    {
        PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
    }
    else if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
    {
        PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_NORMAL;
    }
    else if (dwCreationFlags & ABOVE_NORMAL_PRIORITY_CLASS)
    {
        PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
    }
    else if (dwCreationFlags & HIGH_PRIORITY_CLASS)
    {
        PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_HIGH;
    }
    else if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
    {
        PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_HIGH;
        PriorityClass.PriorityClass += (BasepIsRealtimeAllowed(FALSE) != NULL);
    }
    else
    {
        PriorityClass.PriorityClass = PROCESS_PRIORITY_CLASS_INVALID;
    }

    /* Done with the priority masks, so get rid of them */
    PriorityClass.Foreground = FALSE;
    dwCreationFlags &= ~(NORMAL_PRIORITY_CLASS |
                         IDLE_PRIORITY_CLASS |
                         HIGH_PRIORITY_CLASS |
                         REALTIME_PRIORITY_CLASS |
                         BELOW_NORMAL_PRIORITY_CLASS |
                         ABOVE_NORMAL_PRIORITY_CLASS);

    /* You cannot request both a shared and a separate WoW VDM */
    if ((dwCreationFlags & CREATE_SEPARATE_WOW_VDM) &&
        (dwCreationFlags & CREATE_SHARED_WOW_VDM))
    {
        /* Fail such nonsensical attempts */
        DPRINT1("Invalid WOW flags\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    else if (!(dwCreationFlags & CREATE_SHARED_WOW_VDM) &&
             (BaseStaticServerData->DefaultSeparateVDM))
    {
        /* A shared WoW VDM was not requested but system enforces separation */
        dwCreationFlags |= CREATE_SEPARATE_WOW_VDM;
    }

    /* If a shared WoW VDM is used, make sure the process isn't in a job */
    if (!(dwCreationFlags & CREATE_SEPARATE_WOW_VDM) &&
        (NtIsProcessInJob(NtCurrentProcess(), NULL)))
    {
        /* Remove the shared flag and add the separate flag */
        dwCreationFlags = (dwCreationFlags &~ CREATE_SHARED_WOW_VDM) |
                                              CREATE_SEPARATE_WOW_VDM;
    }

    /* Convert the environment */
    if ((lpEnvironment) && !(dwCreationFlags & CREATE_UNICODE_ENVIRONMENT))
    {
        /* Scan the environment to calculate its Unicode size */
        AnsiEnv.Buffer = pcScan = (PCHAR)lpEnvironment;
        while ((*pcScan) || (*(pcScan + 1))) ++pcScan;

        /* Make sure the environment is not too large */
        EnvironmentLength = (pcScan + sizeof(ANSI_NULL) - (PCHAR)lpEnvironment);
        if (EnvironmentLength > MAXUSHORT)
        {
            /* Fail */
            SetLastError(ERROR_INVALID_PARAMETER);
            return FALSE;
        }

        /* Create our ANSI String */
        AnsiEnv.Length = (USHORT)EnvironmentLength;
        AnsiEnv.MaximumLength = AnsiEnv.Length + sizeof(ANSI_NULL);

        /* Allocate memory for the Unicode Environment */
        UnicodeEnv.Buffer = NULL;
        RegionSize = AnsiEnv.MaximumLength * sizeof(WCHAR);
        Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                         (PVOID)&UnicodeEnv.Buffer,
                                         0,
                                         &RegionSize,
                                         MEM_COMMIT,
                                         PAGE_READWRITE);
        if (!NT_SUCCESS(Status))
        {
            /* Fail */
            BaseSetLastNTError(Status);
            return FALSE;
        }

        /* Use the allocated size and convert */
        UnicodeEnv.MaximumLength = (USHORT)RegionSize;
        Status = RtlAnsiStringToUnicodeString(&UnicodeEnv, &AnsiEnv, FALSE);
        if (!NT_SUCCESS(Status))
        {
            /* Fail */
            NtFreeVirtualMemory(NtCurrentProcess(),
                                (PVOID)&UnicodeEnv.Buffer,
                                &RegionSize,
                                MEM_RELEASE);
            BaseSetLastNTError(Status);
            return FALSE;
        }

        /* Now set the Unicode environment as the environment string pointer */
        lpEnvironment = UnicodeEnv.Buffer;
    }

    /* Make a copy of the caller's startup info since we'll modify it */
    StartupInfo = *lpStartupInfo;

    /* Check if private data is being sent on the same channel as std handles */
    if ((StartupInfo.dwFlags & STARTF_USESTDHANDLES) &&
        (StartupInfo.dwFlags & (STARTF_USEHOTKEY | STARTF_SHELLPRIVATE)))
    {
        /* Cannot use the std handles since we have monitor/hotkey values */
        StartupInfo.dwFlags &= ~STARTF_USESTDHANDLES;
    }

    /* If there's a debugger, or we have to launch cmd.exe, we go back here */
AppNameRetry:
    /* New iteration -- free any existing name buffer */
    if (NameBuffer)
    {
        RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer);
        NameBuffer = NULL;
    }

    /* New iteration -- free any existing free buffer */
    if (FreeBuffer)
    {
        RtlFreeHeap(RtlGetProcessHeap(), 0, FreeBuffer);
        FreeBuffer = NULL;
    }

    /* New iteration -- close any existing file handle */
    if (FileHandle)
    {
        NtClose(FileHandle);
        FileHandle = NULL;
    }

    /* Set the initial parsing state. This code can loop -- don't move this! */
    ErrorCode = 0;
    SearchRetry = TRUE;
    QuotesNeeded = FALSE;
    CmdLineIsAppName = FALSE;

    /* First check if we don't have an application name */
    if (!lpApplicationName)
    {
        /* This should be the first time we attempt creating one */
        ASSERT(NameBuffer == NULL);

        /* Allocate a buffer to hold it */
        NameBuffer = RtlAllocateHeap(RtlGetProcessHeap(),
                                     0,
                                     MAX_PATH * sizeof(WCHAR));
        if (!NameBuffer)
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            Result = FALSE;
            goto Quickie;
        }

        /* Initialize the application name and our parsing parameters */
        lpApplicationName = NullBuffer = ScanString = lpCommandLine;<--- lpApplicationName is assigned

        /* Check for an initial quote*/
        if (*lpCommandLine == L'\"')
        {
            /* We found a quote, keep searching for another one */
            SearchRetry = FALSE;
            ScanString++;
            lpApplicationName = ScanString;<--- lpApplicationName is overwritten
            while (*ScanString)
            {
                /* Have we found the terminating quote? */
                if (*ScanString == L'\"')
                {
                    /* We're done, get out of here */
                    NullBuffer = ScanString;
                    HasQuotes = TRUE;
                    break;
                }

                /* Keep searching for the quote */
                ScanString++;
                NullBuffer = ScanString;
            }
        }
        else
        {
StartScan:
            /* We simply make the application name be the command line*/
            lpApplicationName = lpCommandLine;
            while (*ScanString)
            {
                /* Check if it starts with a space or tab */
                if ((*ScanString == L' ') || (*ScanString == L'\t'))
                {
                    /* Break out of the search loop */
                    NullBuffer = ScanString;
                    break;
                }

                /* Keep searching for a space or tab */
                ScanString++;
                NullBuffer = ScanString;
            }
        }

        /* We have found the end of the application name, terminate it */
        SaveChar = *NullBuffer;
        *NullBuffer = UNICODE_NULL;

        /* New iteration -- free any existing saved path */
        if (SearchPath)
        {
            RtlFreeHeap(RtlGetProcessHeap(), 0, SearchPath);
            SearchPath = NULL;
        }

        /* Now compute the final EXE path based on the name */
        SearchPath = BaseComputeProcessExePath((LPWSTR)lpApplicationName);
        DPRINT("Search Path: %S\n", SearchPath);
        if (!SearchPath)
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            Result = FALSE;
            goto Quickie;
        }

        /* And search for the executable in the search path */
        Length = SearchPathW(SearchPath,
                             lpApplicationName,
                             L".exe",
                             MAX_PATH,
                             NameBuffer,
                             NULL);

        /* Did we find it? */
        if ((Length) && (Length < MAX_PATH))
        {
            /* Get file attributes */
            FileAttribs = GetFileAttributesW(NameBuffer);
            if ((FileAttribs != INVALID_FILE_ATTRIBUTES) &&
                (FileAttribs & FILE_ATTRIBUTE_DIRECTORY))
            {
                /* This was a directory, fail later on */
                Length = 0;
            }
            else
            {
                /* It's a file! */
                Length++;
            }
        }

        DPRINT("Length: %lu Buffer: %S\n", Length, NameBuffer);

        /* Check if there was a failure in SearchPathW */
        if ((Length) && (Length < MAX_PATH))
        {
            /* Everything looks good, restore the name */
            *NullBuffer = SaveChar;
            lpApplicationName = NameBuffer;
        }
        else
        {
            /* Check if this was a relative path, which would explain it */
            PathType = RtlDetermineDosPathNameType_U(lpApplicationName);
            if (PathType != RtlPathTypeRelative)
            {
                /* This should fail, and give us a detailed LastError */
                FileHandle = CreateFileW(lpApplicationName,
                                         GENERIC_READ,
                                         FILE_SHARE_READ |
                                         FILE_SHARE_WRITE,
                                         NULL,
                                         OPEN_EXISTING,
                                         FILE_ATTRIBUTE_NORMAL,
                                         NULL);
                if (FileHandle != INVALID_HANDLE_VALUE)
                {
                    /* It worked? Return a generic error */
                    CloseHandle(FileHandle);
                    FileHandle = NULL;
                    BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND);
                }
            }
            else
            {
                /* Path was absolute, which means it doesn't exist */
                BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND);
            }

            /* Did we already fail once? */
            if (ErrorCode)
            {
                /* Set the error code */
                SetLastError(ErrorCode);
            }
            else
            {
                /* Not yet, cache it */
                ErrorCode = GetLastError();
            }

            /* Put back the command line */
            *NullBuffer = SaveChar;
            lpApplicationName = NameBuffer;

            /* It's possible there's whitespace in the directory name */
            if (!(*ScanString) || !(SearchRetry))
            {
                /* Not the case, give up completely */
                Result = FALSE;
                goto Quickie;
            }

            /* There are spaces, so keep trying the next possibility */
            ScanString++;
            NullBuffer = ScanString;

            /* We will have to add a quote, since there is a space */
            QuotesNeeded = TRUE;
            HasQuotes = TRUE;
            goto StartScan;
        }
    }
    else if (!(lpCommandLine) || !(*lpCommandLine))
    {
        /* We don't have a command line, so just use the application name */
        CmdLineIsAppName = TRUE;
        lpCommandLine = (LPWSTR)lpApplicationName;
    }

    /* Convert the application name to its NT path */
    TranslationStatus = RtlDosPathNameToRelativeNtPathName_U(lpApplicationName,
                                                             &PathName,
                                                             NULL,
                                                             &SxsWin32RelativePath);
    if (!TranslationStatus)
    {
        /* Path must be invalid somehow, bail out */
        DPRINT1("Path translation for SxS failed\n");
        SetLastError(ERROR_PATH_NOT_FOUND);
        Result = FALSE;
        goto Quickie;
    }

    /* Setup the buffer that needs to be freed at the end */
    ASSERT(FreeBuffer == NULL);
    FreeBuffer = PathName.Buffer;

    /* Check what kind of path the application is, for SxS (Fusion) purposes */
    RtlInitUnicodeString(&SxsWin32ExePath, lpApplicationName);
    SxsPathType = RtlDetermineDosPathNameType_U(lpApplicationName);
    if ((SxsPathType != RtlPathTypeDriveAbsolute) &&
        (SxsPathType != RtlPathTypeLocalDevice) &&
        (SxsPathType != RtlPathTypeRootLocalDevice) &&
        (SxsPathType != RtlPathTypeUncAbsolute))
    {
        /* Relative-type path, get the full path */
        RtlInitEmptyUnicodeString(&PathBufferString, NULL, 0);
        Status = RtlGetFullPathName_UstrEx(&SxsWin32ExePath,
                                           NULL,
                                           &PathBufferString,
                                           NULL,
                                           NULL,
                                           NULL,
                                           &SxsPathType,
                                           NULL);
        if (!NT_SUCCESS(Status))
        {
            /* Fail the rest of the create */
            RtlReleaseRelativeName(&SxsWin32RelativePath);
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }

        /* Use this full path as the SxS path */
        SxsWin32ExePath = PathBufferString;
        PathBuffer = PathBufferString.Buffer;
        PathBufferString.Buffer = NULL;
        DPRINT("SxS Path: %S\n", PathBuffer);
    }

    /* Also set the .EXE path based on the path name */
#if _SXS_SUPPORT_ENABLED_
    SxsNtExePath = PathName;
#endif
    if (SxsWin32RelativePath.RelativeName.Length)
    {
        /* If it's relative, capture the relative name */
        PathName = SxsWin32RelativePath.RelativeName;
    }
    else
    {
        /* Otherwise, it's absolute, make sure no relative dir is used */
        SxsWin32RelativePath.ContainingDirectory = NULL;
    }

    /* Now use the path name, and the root path, to try opening the app */
    DPRINT("Path: %wZ. Dir: %p\n", &PathName, SxsWin32RelativePath.ContainingDirectory);
    InitializeObjectAttributes(&LocalObjectAttributes,
                               &PathName,
                               OBJ_CASE_INSENSITIVE,
                               SxsWin32RelativePath.ContainingDirectory,
                               NULL);
    Status = NtOpenFile(&FileHandle,
                        SYNCHRONIZE |
                        FILE_READ_ATTRIBUTES |
                        FILE_READ_DATA |
                        FILE_EXECUTE,
                        &LocalObjectAttributes,
                        &IoStatusBlock,
                        FILE_SHARE_READ | FILE_SHARE_DELETE,
                        FILE_SYNCHRONOUS_IO_NONALERT |
                        FILE_NON_DIRECTORY_FILE);
    if (!NT_SUCCESS(Status))
    {
        /* Try to open the app just for execute purposes instead */
        Status = NtOpenFile(&FileHandle,
                            SYNCHRONIZE | FILE_EXECUTE,
                            &LocalObjectAttributes,
                            &IoStatusBlock,
                            FILE_SHARE_READ | FILE_SHARE_DELETE,
                            FILE_SYNCHRONOUS_IO_NONALERT |
                            FILE_NON_DIRECTORY_FILE);
    }

    /* Failure path, display which file failed to open */
    if (!NT_SUCCESS(Status))
        DPRINT1("Open file failed: %lx (%wZ)\n", Status, &PathName);

    /* Cleanup in preparation for failure or success */
    RtlReleaseRelativeName(&SxsWin32RelativePath);

    if (!NT_SUCCESS(Status))
    {
        /* Failure path, try to understand why */
        if (RtlIsDosDeviceName_U(lpApplicationName))
        {
            /* If a device is being executed, return this special error code */
            SetLastError(ERROR_BAD_DEVICE);
            Result = FALSE;
            goto Quickie;
        }
        else
        {
            /* Otherwise return the converted NT error code */
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }
    }

    /* Did the caller specify a desktop? */
    if (!StartupInfo.lpDesktop)
    {
        /* Use the one from the current process */
        StartupInfo.lpDesktop = Peb->ProcessParameters->DesktopInfo.Buffer;
    }

    /* Create a section for this file */
    Status = NtCreateSection(&SectionHandle,
                             SECTION_ALL_ACCESS,
                             NULL,
                             NULL,
                             PAGE_EXECUTE,
                             SEC_IMAGE,
                             FileHandle);
    DPRINT("Section status: %lx\n", Status);
    if (NT_SUCCESS(Status))
    {
        /* Are we running on Windows Embedded, Datacenter, Blade or Starter? */
        if (SharedUserData->SuiteMask & (VER_SUITE_EMBEDDEDNT |
                                         VER_SUITE_DATACENTER |
                                         VER_SUITE_PERSONAL |
                                         VER_SUITE_BLADE))
        {
            /* These SKUs do not allow running certain applications */
            Status = BasepCheckWebBladeHashes(FileHandle);
            if (Status == STATUS_ACCESS_DENIED)
            {
                /* And this is one of them! */
                DPRINT1("Invalid Blade hashes!\n");
                SetLastError(ERROR_ACCESS_DISABLED_WEBBLADE);
                Result = FALSE;
                goto Quickie;
            }

            /* Did we get some other failure? */
            if (!NT_SUCCESS(Status))
            {
                /* If we couldn't check the hashes, assume nefariousness */
                DPRINT1("Tampered Blade hashes!\n");
                SetLastError(ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER);
                Result = FALSE;
                goto Quickie;
            }
        }

        /* Now do Winsafer, etc, checks */
        Status = BasepIsProcessAllowed((LPWSTR)lpApplicationName);
        if (!NT_SUCCESS(Status))
        {
            /* Fail if we're not allowed to launch the process */
            DPRINT1("Process not allowed to launch: %lx\n", Status);
            BaseSetLastNTError(Status);
            if (SectionHandle)
            {
                NtClose(SectionHandle);
                SectionHandle = NULL;
            }
            Result = FALSE;
            goto Quickie;
        }

        /* Is a DOS VDM being forced, but we already have a WOW32 instance ready? */
        if ((dwCreationFlags & CREATE_FORCEDOS) &&
            (BaseStaticServerData->IsWowTaskReady))
        {
            /* This request can't be satisfied, instead, a separate VDM is needed */
            dwCreationFlags &= ~(CREATE_FORCEDOS | CREATE_SHARED_WOW_VDM);
            dwCreationFlags |= CREATE_SEPARATE_WOW_VDM;

            /* Set a failure code, ask for VDM reservation */
            Status = STATUS_INVALID_IMAGE_WIN_16;
            UseVdmReserve = TRUE;

            /* Close the current handle */
            NtClose(SectionHandle);
            SectionHandle = NULL;

            /* Don't query the section later */
            QuerySection = FALSE;
        }
    }

    /* Did we already do these checks? */
    if (!SkipSaferAndAppCompat)
    {
        /* Is everything OK so far, OR do we have an non-MZ, non-DOS app? */
        if ((NT_SUCCESS(Status)) ||
            ((Status == STATUS_INVALID_IMAGE_NOT_MZ) &&
            !(BaseIsDosApplication(&PathName, Status))))
        {
            /* Clear the machine type in case of failure */
            ImageMachine = 0;

            /* Clean any app compat data that may have accumulated */
            BasepFreeAppCompatData(AppCompatData, AppCompatSxsData);
            AppCompatData = NULL;
            AppCompatSxsData = NULL;

            /* Do we have a section? */
            if (SectionHandle)
            {
                /* Have we already queried it? */
                if (QuerySection)
                {
                    /* Nothing to do */
                    AppCompatStatus = STATUS_SUCCESS;
                }
                else
                {
                    /* Get some information about the executable */
                    AppCompatStatus = NtQuerySection(SectionHandle,
                                            SectionImageInformation,
                                            &ImageInformation,
                                            sizeof(ImageInformation),
                                            NULL);
                }

                /* Do we have section information now? */
                if (NT_SUCCESS(AppCompatStatus))
                {
                    /* Don't ask for it again, save the machine type */
                    QuerySection = TRUE;
                    ImageMachine = ImageInformation.Machine;
                }
            }

            /* Is there a reason/Shim we shouldn't run this application? */
            AppCompatStatus = BasepCheckBadapp(FileHandle,
                                      FreeBuffer,
                                      lpEnvironment,
                                      ImageMachine,
                                      &AppCompatData,
                                      &AppCompatDataSize,
                                      &AppCompatSxsData,
                                      &AppCompatSxsDataSize,
                                      &FusionFlags);
            if (!NT_SUCCESS(AppCompatStatus))
            {
                /* This is usually the status we get back */
                DPRINT1("App compat launch failure: %lx\n", AppCompatStatus);
                if (AppCompatStatus == STATUS_ACCESS_DENIED)
                {
                    /* Convert it to something more Win32-specific */
                    SetLastError(ERROR_CANCELLED);
                }
                else
                {
                    /* Some other error */
                    BaseSetLastNTError(AppCompatStatus);
                }

                /* Did we have a section? */
                if (SectionHandle)
                {
                    /* Clean it up */
                    NtClose(SectionHandle);
                    SectionHandle = NULL;
                }

                /* Fail the call */
                Result = FALSE;
                goto Quickie;
            }
        }
    }

    //ASSERT((dwFusionFlags & ~SXS_APPCOMPACT_FLAG_APP_RUNNING_SAFEMODE) == 0);

    /* Have we already done, and do we need to do, SRP (WinSafer) checks? */
    if (!(SkipSaferAndAppCompat) &&
        ~(dwCreationFlags & CREATE_PRESERVE_CODE_AUTHZ_LEVEL))
    {
        /* Assume yes */
        SaferNeeded = TRUE;
        switch (Status)
        {
            case STATUS_INVALID_IMAGE_NE_FORMAT:
            case STATUS_INVALID_IMAGE_PROTECT:
            case STATUS_INVALID_IMAGE_WIN_16:
            case STATUS_FILE_IS_OFFLINE:
                /* For all DOS, 16-bit, OS/2 images, we do*/
                break;

            case STATUS_INVALID_IMAGE_NOT_MZ:
                /* For invalid files, we don't, unless it's a .BAT file */
                if (BaseIsDosApplication(&PathName, Status)) break;

            default:
                /* Any other error codes we also don't */
                if (!NT_SUCCESS(Status))
                {
                    SaferNeeded = FALSE;
                }

                /* But for success, we do */
                break;
        }

        /* Okay, so what did the checks above result in? */
        if (SaferNeeded)
        {
            /* We have to call into the WinSafer library and actually check */
            SaferStatus = BasepCheckWinSaferRestrictions(hUserToken,
                                                    (LPWSTR)lpApplicationName,
                                                    FileHandle,
                                                    &InJob,
                                                    &TokenHandle,
                                                    &JobHandle);
            if (SaferStatus == 0xFFFFFFFF)
            {
                /* Back in 2003, they didn't have an NTSTATUS for this... */
                DPRINT1("WinSafer blocking process launch\n");
                SetLastError(ERROR_ACCESS_DISABLED_BY_POLICY);
                Result = FALSE;
                goto Quickie;
            }

            /* Other status codes are not-Safer related, just convert them */
            if (!NT_SUCCESS(SaferStatus))
            {
                DPRINT1("Error checking WinSafer: %lx\n", SaferStatus);
                BaseSetLastNTError(SaferStatus);
                Result = FALSE;
                goto Quickie;
            }
        }
    }

    /* The last step is to figure out why the section object was not created */
    switch (Status)
    {
        case STATUS_INVALID_IMAGE_WIN_16:
        {
            /* 16-bit binary. Should we use WOW or does the caller force VDM? */
            if (!(dwCreationFlags & CREATE_FORCEDOS))
            {
                /* Remember that we're launching WOW */
                IsWowApp = TRUE;

                /* Create the VDM environment, it's valid for WOW too */
                Result = BaseCreateVDMEnvironment(lpEnvironment,
                                                  &VdmAnsiEnv,
                                                  &VdmUnicodeEnv);
                if (!Result)
                {
                    DPRINT1("VDM environment for WOW app failed\n");
                    goto Quickie;
                }

                /* We're going to try this twice, so do a loop */
                while (TRUE)
                {
                    /* Pick which kind of WOW mode we want to run in */
                    VdmBinaryType = (dwCreationFlags &
                                     CREATE_SEPARATE_WOW_VDM) ?
                                     BINARY_TYPE_SEPARATE_WOW : BINARY_TYPE_WOW;

                    /* Get all the VDM settings and current status */
                    Status = BaseCheckVDM(VdmBinaryType,
                                          lpApplicationName,
                                          lpCommandLine,
                                          lpCurrentDirectory,
                                          &VdmAnsiEnv,
                                          &CsrMsg[1],
                                          &VdmTask,
                                          dwCreationFlags,
                                          &StartupInfo,
                                          hUserToken);

                    /* If it worked, no need to try again */
                    if (NT_SUCCESS(Status)) break;

                    /* Check if it's disallowed or if it's our second time */
                    BaseSetLastNTError(Status);
                    if ((Status == STATUS_VDM_DISALLOWED) ||
                        (VdmBinaryType == BINARY_TYPE_SEPARATE_WOW) ||
                        (GetLastError() == ERROR_ACCESS_DENIED))
                    {
                        /* Fail the call -- we won't try again */
                        DPRINT1("VDM message failure for WOW: %lx\n", Status);
                        Result = FALSE;
                        goto Quickie;
                    }

                    /* Try one more time, but with a separate WOW instance */
                    dwCreationFlags |= CREATE_SEPARATE_WOW_VDM;
                }

                /* Check which VDM state we're currently in */
                switch (CheckVdmMsg->VDMState & (VDM_NOT_LOADED |
                                                 VDM_NOT_READY |
                                                 VDM_READY))
                {
                    case VDM_NOT_LOADED:
                        /* VDM is not fully loaded, so not that much to undo */
                        VdmUndoLevel = VDM_UNDO_PARTIAL;

                        /* Reset VDM reserve if needed */
                        if (UseVdmReserve) VdmReserve = 1;

                        /* Get the required parameters and names for launch */
                        Result = BaseGetVdmConfigInfo(lpCommandLine,
                                                      VdmTask,
                                                      VdmBinaryType,
                                                      &VdmString,
                                                      &VdmReserve);
                        if (!Result)
                        {
                            DPRINT1("VDM Configuration failed for WOW\n");
                            BaseSetLastNTError(Status);
                            goto Quickie;
                        }

                        /* Update the command-line with the VDM one instead */
                        lpCommandLine = VdmString.Buffer;
                        lpApplicationName = NULL;

                        /* We don't want a console, detachment, nor a window */
                        dwCreationFlags |= CREATE_NO_WINDOW;
                        dwCreationFlags &= ~(CREATE_NEW_CONSOLE | DETACHED_PROCESS);

                        /* Force feedback on */
                        StartupInfo.dwFlags |= STARTF_FORCEONFEEDBACK;
                        break;


                    case VDM_READY:
                        /* VDM is ready, so we have to undo everything */
                        VdmUndoLevel = VDM_UNDO_REUSE;

                        /* Check if CSRSS wants us to wait on VDM */
                        VdmWaitObject = CheckVdmMsg->WaitObjectForParent;
                        break;

                    case VDM_NOT_READY:
                        /* Something is wrong with VDM, we'll fail the call */
                        DPRINT1("VDM is not ready for WOW\n");
                        SetLastError(ERROR_NOT_READY);
                        Result = FALSE;
                        goto Quickie;

                    default:
                        break;
                }

                /* Since to get NULL, we allocate from 0x1, account for this */
                VdmReserve--;

                /* This implies VDM is ready, so skip everything else */
                if (VdmWaitObject) goto VdmShortCircuit;

                /* Don't inherit handles since we're doing VDM now */
                bInheritHandles = FALSE;

                /* Had the user passed in environment? If so, destroy it */
                if ((lpEnvironment) &&
                    !(dwCreationFlags & CREATE_UNICODE_ENVIRONMENT))
                {
                    RtlDestroyEnvironment(lpEnvironment);
                }

                /* We've already done all these checks, don't do them again */
                SkipSaferAndAppCompat = TRUE;
                goto AppNameRetry;
            }

            // There is no break here on purpose, so FORCEDOS drops down!
        }

        case STATUS_INVALID_IMAGE_PROTECT:
        case STATUS_INVALID_IMAGE_NOT_MZ:
        case STATUS_INVALID_IMAGE_NE_FORMAT:
        {
            /* We're launching an executable application */
            BinarySubType = BINARY_TYPE_EXE;<--- BinarySubType is assigned

            /* We can drop here from other "cases" above too, so check */
            if ((Status == STATUS_INVALID_IMAGE_PROTECT) ||
                (Status == STATUS_INVALID_IMAGE_NE_FORMAT) ||
                (BinarySubType = BaseIsDosApplication(&PathName, Status)))<--- BinarySubType is overwritten
            {
                /* We're launching a DOS application */
                VdmBinaryType = BINARY_TYPE_DOS;

                /* Based on the caller environment, create a VDM one */
                Result = BaseCreateVDMEnvironment(lpEnvironment,
                                                  &VdmAnsiEnv,
                                                  &VdmUnicodeEnv);
                if (!Result)
                {
                    DPRINT1("VDM environment for DOS failed\n");
                    goto Quickie;
                }

                /* Check the current state of the VDM subsystem */
                Status = BaseCheckVDM(VdmBinaryType | BinarySubType,
                                      lpApplicationName,
                                      lpCommandLine,
                                      lpCurrentDirectory,
                                      &VdmAnsiEnv,
                                      &CsrMsg[1],
                                      &VdmTask,
                                      dwCreationFlags,
                                      &StartupInfo,
                                      NULL);
                if (!NT_SUCCESS(Status))
                {
                    /* Failed to inquire about VDM, fail the call */
                    DPRINT1("VDM message failure for DOS: %lx\n", Status);
                    BaseSetLastNTError(Status);
                    Result = FALSE;
                    goto Quickie;
                };

                /* Handle possible VDM states */
                switch (CheckVdmMsg->VDMState & (VDM_NOT_LOADED |
                                                 VDM_NOT_READY |
                                                 VDM_READY))
                {
                    case VDM_NOT_LOADED:
                        /* If VDM is not loaded, we'll do a partial undo */
                        VdmUndoLevel = VDM_UNDO_PARTIAL;

                        /* A VDM process can't also be detached, so fail */
                        if (dwCreationFlags & DETACHED_PROCESS)
                        {
                            DPRINT1("Detached process but no VDM, not allowed\n");
                            SetLastError(ERROR_ACCESS_DENIED);
                            return FALSE;
                        }

                        /* Get the required parameters and names for launch */
                        Result = BaseGetVdmConfigInfo(lpCommandLine,
                                                      VdmTask,
                                                      VdmBinaryType,
                                                      &VdmString,
                                                      &VdmReserve);
                        if (!Result)
                        {
                            DPRINT1("VDM Configuration failed for DOS\n");
                            BaseSetLastNTError(Status);
                            goto Quickie;
                        }

                        /* Update the command-line to launch VDM instead */
                        lpCommandLine = VdmString.Buffer;
                        lpApplicationName = NULL;
                        break;

                    case VDM_READY:
                        /* VDM is ready, so we have to undo everything */
                        VdmUndoLevel = VDM_UNDO_REUSE;

                        /* Check if CSRSS wants us to wait on VDM */
                        VdmWaitObject = CheckVdmMsg->WaitObjectForParent;
                        break;

                    case VDM_NOT_READY:
                        /* Something is wrong with VDM, we'll fail the call */
                        DPRINT1("VDM is not ready for DOS\n");
                        SetLastError(ERROR_NOT_READY);
                        Result = FALSE;
                        goto Quickie;

                    default:
                        break;
                }

                /* Since to get NULL, we allocate from 0x1, account for this */
                VdmReserve--;

                /* This implies VDM is ready, so skip everything else */
                if (VdmWaitObject) goto VdmShortCircuit;

                /* Don't inherit handles since we're doing VDM now */
                bInheritHandles = FALSE;

                /* Had the user passed in environment? If so, destroy it */
                if ((lpEnvironment) &&
                    !(dwCreationFlags & CREATE_UNICODE_ENVIRONMENT))
                {
                    RtlDestroyEnvironment(lpEnvironment);
                }

                /* Use our VDM Unicode environment instead */
                lpEnvironment = VdmUnicodeEnv.Buffer;
            }
            else
            {
                /* It's a batch file, get the extension */
                ExtBuffer = &PathName.Buffer[PathName.Length / sizeof(WCHAR) - 4];

                /* Make sure the extensions are correct */
                if ((PathName.Length < (4 * sizeof(WCHAR))) ||
                    ((_wcsnicmp(ExtBuffer, L".bat", 4)) &&
                     (_wcsnicmp(ExtBuffer, L".cmd", 4))))
                {
                    DPRINT1("'%wZ': Invalid EXE, and not a batch or script file\n", &PathName);
                    SetLastError(ERROR_BAD_EXE_FORMAT);
                    Result = FALSE;
                    goto Quickie;
                }

                /* Check if we need to account for quotes around the path */
                CmdQuoteLength = CmdLineIsAppName || HasQuotes;
                if (!CmdLineIsAppName)
                {
                    if (HasQuotes) CmdQuoteLength++;
                }
                else
                {
                    CmdQuoteLength++;
                }

                /* Calculate the length of the command line */
                CmdLineLength = wcslen(lpCommandLine);
                CmdLineLength += wcslen(CMD_STRING);
                CmdLineLength += CmdQuoteLength + sizeof(ANSI_NULL);
                CmdLineLength *= sizeof(WCHAR);

                /* Allocate space for the new command line */
                AnsiCmdCommand = RtlAllocateHeap(RtlGetProcessHeap(),
                                                 0,
                                                 CmdLineLength);
                if (!AnsiCmdCommand)
                {
                    BaseSetLastNTError(STATUS_NO_MEMORY);
                    Result = FALSE;
                    goto Quickie;
                }

                /* Build it */
                wcscpy(AnsiCmdCommand, CMD_STRING);
                if ((CmdLineIsAppName) || (HasQuotes))
                {
                    wcscat(AnsiCmdCommand, L"\"");
                }
                wcscat(AnsiCmdCommand, lpCommandLine);
                if ((CmdLineIsAppName) || (HasQuotes))
                {
                    wcscat(AnsiCmdCommand, L"\"");
                }

                /* Create it as a Unicode String */
                RtlInitUnicodeString(&DebuggerString, AnsiCmdCommand);

                /* Set the command line to this */
                lpCommandLine = DebuggerString.Buffer;
                lpApplicationName = NULL;
                DPRINT1("Retrying with: %S\n", lpCommandLine);
            }

            /* We've already done all these checks, don't do them again */
            SkipSaferAndAppCompat = TRUE;
            goto AppNameRetry;
        }

        case STATUS_INVALID_IMAGE_WIN_64:
        {
            /* 64-bit binaries are not allowed to run on 32-bit ReactOS */
            DPRINT1("64-bit binary, failing\n");
            SetLastError(ERROR_EXE_MACHINE_TYPE_MISMATCH);
            Result = FALSE;
            goto Quickie;
        }

        case STATUS_FILE_IS_OFFLINE:
        {
            /* Set the correct last error for this */
            DPRINT1("File is offline, failing\n");
            SetLastError(ERROR_FILE_OFFLINE);
            break;
        }

        default:
        {
            /* Any other error, convert it to a generic Win32 error */
            if (!NT_SUCCESS(Status))
            {
                DPRINT1("Failed to create section: %lx\n", Status);
                SetLastError(ERROR_BAD_EXE_FORMAT);
                Result = FALSE;
                goto Quickie;
            }

            /* Otherwise, this must be success */
            ASSERT(Status == STATUS_SUCCESS);
            break;
        }
    }

    /* Is this not a WOW application, but a WOW32 VDM was requested for it? */
    if (!(IsWowApp) && (dwCreationFlags & CREATE_SEPARATE_WOW_VDM))
    {
        /* Ignore the nonsensical request */
        dwCreationFlags &= ~CREATE_SEPARATE_WOW_VDM;
    }

    /* Did we already check information for the section? */
    if (!QuerySection)
    {
        /* Get some information about the executable */
        Status = NtQuerySection(SectionHandle,
                                SectionImageInformation,
                                &ImageInformation,
                                sizeof(ImageInformation),
                                NULL);
        if (!NT_SUCCESS(Status))
        {
            /* We failed, bail out */
            DPRINT1("Section query failed\n");
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }

        /* Don't check this later */
        QuerySection = TRUE;
    }

    /* Check if this was linked as a DLL */
    if (ImageInformation.ImageCharacteristics & IMAGE_FILE_DLL)
    {
        /* These aren't valid images to try to execute! */
        DPRINT1("Trying to launch a DLL, failing\n");
        SetLastError(ERROR_BAD_EXE_FORMAT);
        Result = FALSE;
        goto Quickie;
    }

    /* Don't let callers pass in this flag -- we'll only get it from IFEO */
    Flags &= ~PROCESS_CREATE_FLAGS_LARGE_PAGES;

    /* Clear the IFEO-missing flag, before we know for sure... */
    ParameterFlags &= ~2;

    /* If the process is being debugged, only read IFEO if the PEB says so */
    if (!(dwCreationFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS)) ||
        (NtCurrentPeb()->ReadImageFileExecOptions))
    {
        /* Let's do this! Attempt to open IFEO */
        IFEOStatus = LdrOpenImageFileOptionsKey(&PathName, 0, &KeyHandle);
        if (!NT_SUCCESS(IFEOStatus))
        {
            /* We failed, set the flag so we store this in the parameters */
            if (IFEOStatus == STATUS_OBJECT_NAME_NOT_FOUND) ParameterFlags |= 2;
        }
        else
        {
            /* Was this our first time going through this path? */
            if (!DebuggerCmdLine)
            {
                /* Allocate a buffer for the debugger path */
                DebuggerCmdLine = RtlAllocateHeap(RtlGetProcessHeap(),
                                                  0,
                                                  MAX_PATH * sizeof(WCHAR));
                if (!DebuggerCmdLine)
                {
                    /* Close IFEO on failure */
                    IFEOStatus = NtClose(KeyHandle);
                    ASSERT(NT_SUCCESS(IFEOStatus));

                    /* Fail the call */
                    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
                    Result = FALSE;
                    goto Quickie;
                }
            }

            /* Now query for the debugger */
            IFEOStatus = LdrQueryImageFileKeyOption(KeyHandle,
                                                 L"Debugger",
                                                 REG_SZ,
                                                 DebuggerCmdLine,
                                                 MAX_PATH * sizeof(WCHAR),
                                                 &ResultSize);
            if (!(NT_SUCCESS(IFEOStatus)) ||
                (ResultSize < sizeof(WCHAR)) ||
                (DebuggerCmdLine[0] == UNICODE_NULL))
            {
                /* If it's not there, or too small, or invalid, ignore it */
                RtlFreeHeap(RtlGetProcessHeap(), 0, DebuggerCmdLine);
                DebuggerCmdLine = NULL;
            }

            /* Also query if we should map with large pages */
            IFEOStatus = LdrQueryImageFileKeyOption(KeyHandle,
                                                 L"UseLargePages",
                                                 REG_DWORD,
                                                 &UseLargePages,
                                                 sizeof(UseLargePages),
                                                 NULL);
            if ((NT_SUCCESS(IFEOStatus)) && (UseLargePages))
            {
                /* Do it! This is the only way this flag can be set */
                Flags |= PROCESS_CREATE_FLAGS_LARGE_PAGES;
            }

            /* We're done with IFEO, can close it now */
            IFEOStatus = NtClose(KeyHandle);
            ASSERT(NT_SUCCESS(IFEOStatus));
        }
    }

    /* Make sure the image was compiled for this processor */
    if ((ImageInformation.Machine < SharedUserData->ImageNumberLow) ||
        (ImageInformation.Machine > SharedUserData->ImageNumberHigh))
    {
        /* It was not -- raise a hard error */
        ErrorResponse = ResponseOk;
        ErrorParameters[0] = (ULONG_PTR)&PathName;
        NtRaiseHardError(STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE,
                         1,
                         1,
                         ErrorParameters,
                         OptionOk,
                         &ErrorResponse);
        if (Peb->ImageSubsystemMajorVersion <= 3)
        {
            /* If it's really old, return this error */
            SetLastError(ERROR_BAD_EXE_FORMAT);
        }
        else
        {
            /* Otherwise, return a more modern error */
            SetLastError(ERROR_EXE_MACHINE_TYPE_MISMATCH);
        }

        /* Go to the failure path */
        DPRINT1("Invalid image architecture: %lx\n", ImageInformation.Machine);
        Result = FALSE;
        goto Quickie;
    }

    /* Check if this isn't a Windows image */
    if ((ImageInformation.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_GUI) &&
        (ImageInformation.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_CUI))
    {
        /* Get rid of section-related information since we'll retry */
        NtClose(SectionHandle);
        SectionHandle = NULL;
        QuerySection = FALSE;

        /* The only other non-Windows image type we support here is POSIX */
        if (ImageInformation.SubSystemType != IMAGE_SUBSYSTEM_POSIX_CUI)
        {
            /* Bail out if it's something else */
            SetLastError(ERROR_CHILD_NOT_COMPLETE);
            Result = FALSE;
            goto Quickie;
        }

        /* Now build the command-line to have posix launch this image */
        Result = BuildSubSysCommandLine(L"POSIX /P ",
                                        lpApplicationName,
                                        lpCommandLine,
                                        &DebuggerString);
        if (!Result)
        {
            /* Bail out if that failed */
            DPRINT1("Subsystem command line failed\n");
            goto Quickie;
        }

        /* And re-try launching the process, with the new command-line now */
        lpCommandLine = DebuggerString.Buffer;
        lpApplicationName = NULL;

        /* We've already done all these checks, don't do them again */
        SkipSaferAndAppCompat = TRUE;
        DPRINT1("Retrying with: %S\n", lpCommandLine);
        goto AppNameRetry;
    }

    /* Was this image built for a version of Windows whose images we can run? */
    Result = BasepIsImageVersionOk(ImageInformation.SubSystemMajorVersion,
                                   ImageInformation.SubSystemMinorVersion);
    if (!Result)
    {
        /* It was not, bail out */
        DPRINT1("Invalid subsystem version: %hu.%hu\n",
                ImageInformation.SubSystemMajorVersion,
                ImageInformation.SubSystemMinorVersion);
        SetLastError(ERROR_BAD_EXE_FORMAT);
        goto Quickie;
    }

    /* Check if there is a debugger associated with the application */
    if (DebuggerCmdLine)
    {
        /* Get the length of the command line */
        n = wcslen(lpCommandLine);
        if (!n)
        {
            /* There's no command line, use the application name instead */
            lpCommandLine = (LPWSTR)lpApplicationName;
            n = wcslen(lpCommandLine);
        }

        /* Protect against overflow */
        if (n > UNICODE_STRING_MAX_CHARS)
        {
            BaseSetLastNTError(STATUS_NAME_TOO_LONG);
            Result = FALSE;
            goto Quickie;
        }

        /* Now add the length of the debugger command-line */
        n += wcslen(DebuggerCmdLine);

        /* Again make sure we don't overflow */
        if (n > UNICODE_STRING_MAX_CHARS)
        {
            BaseSetLastNTError(STATUS_NAME_TOO_LONG);
            Result = FALSE;
            goto Quickie;
        }

        /* Account for the quotes and space between the two */
        n += sizeof("\" \"") - sizeof(ANSI_NULL);

        /* Convert to bytes, and make sure we don't overflow */
        n *= sizeof(WCHAR);
        if (n > UNICODE_STRING_MAX_BYTES)
        {
            BaseSetLastNTError(STATUS_NAME_TOO_LONG);
            Result = FALSE;
            goto Quickie;
        }

        /* Allocate space for the string */
        DebuggerString.Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, n);
        if (!DebuggerString.Buffer)
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            Result = FALSE;
            goto Quickie;
        }

        /* Set the length */
        RtlInitEmptyUnicodeString(&DebuggerString,
                                  DebuggerString.Buffer,
                                  (USHORT)n);

        /* Now perform the command line creation */
        ImageDbgStatus = RtlAppendUnicodeToString(&DebuggerString,
                                                  DebuggerCmdLine);
        ASSERT(NT_SUCCESS(ImageDbgStatus));
        ImageDbgStatus = RtlAppendUnicodeToString(&DebuggerString, L" ");
        ASSERT(NT_SUCCESS(ImageDbgStatus));
        ImageDbgStatus = RtlAppendUnicodeToString(&DebuggerString, lpCommandLine);
        ASSERT(NT_SUCCESS(ImageDbgStatus));

        /* Make sure it all looks nice */
        DbgPrint("BASE: Calling debugger with '%wZ'\n", &DebuggerString);

        /* Update the command line and application name */
        lpCommandLine = DebuggerString.Buffer;
        lpApplicationName = NULL;

        /* Close all temporary state */
        NtClose(SectionHandle);
        SectionHandle = NULL;
        QuerySection = FALSE;

        /* Free all temporary memory */
        RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer);
        NameBuffer = NULL;
        RtlFreeHeap(RtlGetProcessHeap(), 0, FreeBuffer);
        FreeBuffer = NULL;
        RtlFreeHeap(RtlGetProcessHeap(), 0, DebuggerCmdLine);
        DebuggerCmdLine = NULL;
        DPRINT1("Retrying with: %S\n", lpCommandLine);
        goto AppNameRetry;
    }

    /* Initialize the process object attributes */
    ObjectAttributes = BaseFormatObjectAttributes(&LocalObjectAttributes,
                                                  lpProcessAttributes,
                                                  NULL);
    if ((hUserToken) && (lpProcessAttributes))
    {
        /* Augment them with information from the user */

        LocalProcessAttributes = *lpProcessAttributes;
        LocalProcessAttributes.lpSecurityDescriptor = NULL;
        ObjectAttributes = BaseFormatObjectAttributes(&LocalObjectAttributes,
                                                      &LocalProcessAttributes,
                                                      NULL);
    }

    /* Check if we're going to be debugged */
    if (dwCreationFlags & DEBUG_PROCESS)
    {
        /* Set process flag */
        Flags |= PROCESS_CREATE_FLAGS_BREAKAWAY;
    }

    /* Check if we're going to be debugged */
    if (dwCreationFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS))
    {
        /* Connect to DbgUi */
        Status = DbgUiConnectToDbg();
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("Failed to connect to DbgUI!\n");
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }

        /* Get the debug object */
        DebugHandle = DbgUiGetThreadDebugObject();

        /* Check if only this process will be debugged */
        if (dwCreationFlags & DEBUG_ONLY_THIS_PROCESS)
        {
            /* Set process flag */
            Flags |= PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT;
        }
    }

    /* Set inherit flag */
    if (bInheritHandles) Flags |= PROCESS_CREATE_FLAGS_INHERIT_HANDLES;

    /* Check if the process should be created with large pages */
    HavePrivilege = FALSE;
    PrivilegeState = NULL;
    if (Flags & PROCESS_CREATE_FLAGS_LARGE_PAGES)
    {
        /* Acquire the required privilege so that the kernel won't fail the call */
        PrivilegeValue = SE_LOCK_MEMORY_PRIVILEGE;
        Status = RtlAcquirePrivilege(&PrivilegeValue, 1, 0, &PrivilegeState);
        if (NT_SUCCESS(Status))
        {
            /* Remember to release it later */
            HavePrivilege = TRUE;
        }
    }

    /* Save the current TIB value since kernel overwrites it to store PEB */
    TibValue = Teb->NtTib.ArbitraryUserPointer;

    /* Tell the kernel to create the process */
    Status = NtCreateProcessEx(&ProcessHandle,
                               PROCESS_ALL_ACCESS,
                               ObjectAttributes,
                               NtCurrentProcess(),
                               Flags,
                               SectionHandle,
                               DebugHandle,
                               NULL,
                               InJob);

    /* Load the PEB address from the hacky location where the kernel stores it */
    RemotePeb = Teb->NtTib.ArbitraryUserPointer;

    /* And restore the old TIB value */
    Teb->NtTib.ArbitraryUserPointer = TibValue;

    /* Release the large page privilege if we had acquired it */
    if (HavePrivilege) RtlReleasePrivilege(PrivilegeState);

    /* And now check if the kernel failed to create the process */
    if (!NT_SUCCESS(Status))
    {
        /* Go to failure path */
        DPRINT1("Failed to create process: %lx\n", Status);
        BaseSetLastNTError(Status);
        Result = FALSE;
        goto Quickie;
    }

    /* Check if there is a priority class to set */
    if (PriorityClass.PriorityClass)
    {
        /* Reset current privilege state */
        RealTimePrivilegeState = NULL;

        /* Is realtime priority being requested? */
        if (PriorityClass.PriorityClass == PROCESS_PRIORITY_CLASS_REALTIME)
        {
            /* Check if the caller has real-time access, and enable it if so */
            RealTimePrivilegeState = BasepIsRealtimeAllowed(TRUE);
        }

        /* Set the new priority class and release the privilege */
        Status = NtSetInformationProcess(ProcessHandle,
                                         ProcessPriorityClass,
                                         &PriorityClass,
                                         sizeof(PROCESS_PRIORITY_CLASS));
        if (RealTimePrivilegeState) RtlReleasePrivilege(RealTimePrivilegeState);

        /* Check if we failed to set the priority class */
        if (!NT_SUCCESS(Status))
        {
            /* Bail out on failure */
            DPRINT1("Failed to set priority class: %lx\n", Status);
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }
    }

    /* Check if the caller wants the default error mode */
    if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
    {
        /* Set Error Mode to only fail on critical errors */
        HardErrorMode = SEM_FAILCRITICALERRORS;
        NtSetInformationProcess(ProcessHandle,
                                ProcessDefaultHardErrorMode,
                                &HardErrorMode,
                                sizeof(ULONG));
    }

    /* Check if this was a VDM binary */
    if (VdmBinaryType)
    {
        /* Update VDM by telling it the process has now been created */
        VdmWaitObject = ProcessHandle;
        Result = BaseUpdateVDMEntry(VdmEntryUpdateProcess,
                                    &VdmWaitObject,
                                    VdmTask,
                                    VdmBinaryType);

        if (!Result)
        {
            /* Bail out on failure */
            DPRINT1("Failed to update VDM with wait object\n");
            VdmWaitObject = NULL;
            goto Quickie;
        }

        /* At this point, a failure means VDM has to undo all the state */
        VdmUndoLevel |= VDM_UNDO_FULL;
    }

    /* Check if VDM needed reserved low-memory */
    if (VdmReserve)
    {
        /* Reserve the requested allocation */
        RegionSize = VdmReserve;
        Status = NtAllocateVirtualMemory(ProcessHandle,
                                         &BaseAddress,
                                         0,
                                         &RegionSize,
                                         MEM_RESERVE,
                                         PAGE_EXECUTE_READWRITE);
        if (!NT_SUCCESS(Status))
        {
            /* Bail out on failure */
            DPRINT1("Failed to reserve memory for VDM: %lx\n", Status);
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }

        VdmReserve = (ULONG)RegionSize;
    }

    /* Check if we've already queried information on the section */
    if (!QuerySection)
    {
        /* We haven't, so get some information about the executable */
        Status = NtQuerySection(SectionHandle,
                                SectionImageInformation,
                                &ImageInformation,
                                sizeof(ImageInformation),
                                NULL);
        if (!NT_SUCCESS(Status))
        {
            /* Bail out on failure */
            DPRINT1("Failed to query section: %lx\n", Status);
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }

        /* If we encounter a restart, don't re-query this information again */
        QuerySection = TRUE;
    }

    /* Do we need to apply SxS to this image? */
    if (!(ImageInformation.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NO_ISOLATION))
    {
        /* Too bad, we don't support this yet */
        DPRINT1("Image should receive SxS Fusion Isolation\n");
    }

    /* There's some SxS flag that we need to set if fusion flags have 1 set */
    if (FusionFlags & 1) CreateProcessMsg->Sxs.Flags |= 0x10;

    /* Check if we have a current directory */
    if (lpCurrentDirectory)
    {
        /* Allocate a buffer so we can keep a Unicode copy */
        DPRINT("Current directory: %S\n", lpCurrentDirectory);
        CurrentDirectory = RtlAllocateHeap(RtlGetProcessHeap(),
                                           0,
                                           (MAX_PATH * sizeof(WCHAR)) +
                                           sizeof(UNICODE_NULL));
        if (!CurrentDirectory)
        {
            /* Bail out if this failed */
            BaseSetLastNTError(STATUS_NO_MEMORY);
            Result = FALSE;
            goto Quickie;
        }

        /* Get the length in Unicode */
        Length = GetFullPathNameW(lpCurrentDirectory,
                                  MAX_PATH,
                                  CurrentDirectory,
                                  &FilePart);
        if (Length > MAX_PATH)
        {
            /* The directory is too long, so bail out */
            SetLastError(ERROR_DIRECTORY);
            Result = FALSE;
            goto Quickie;
        }

        /* Make sure the directory is actually valid */
        FileAttribs = GetFileAttributesW(CurrentDirectory);
        if ((FileAttribs == INVALID_FILE_ATTRIBUTES) ||
           !(FileAttribs & FILE_ATTRIBUTE_DIRECTORY))
        {
            /* It isn't, so bail out */
            DPRINT1("Current directory is invalid\n");
            SetLastError(ERROR_DIRECTORY);
            Result = FALSE;
            goto Quickie;
        }
    }

    /* Insert quotes if needed */
    if ((QuotesNeeded) || (CmdLineIsAppName))
    {
        /* Allocate our buffer, plus enough space for quotes and a NULL */
        QuotedCmdLine = RtlAllocateHeap(RtlGetProcessHeap(),
                                        0,
                                        (wcslen(lpCommandLine) * sizeof(WCHAR)) +
                                        (2 * sizeof(L'\"') + sizeof(UNICODE_NULL)));
        if (QuotedCmdLine)
        {
            /* Copy the first quote */
            wcscpy(QuotedCmdLine, L"\"");

            /* Save the current null-character */
            if (QuotesNeeded)
            {
                SaveChar = *NullBuffer;
                *NullBuffer = UNICODE_NULL;
            }

            /* Copy the command line and the final quote */
            wcscat(QuotedCmdLine, lpCommandLine);
            wcscat(QuotedCmdLine, L"\"");

            /* Copy the null-char back */
            if (QuotesNeeded)
            {
                *NullBuffer = SaveChar;
                wcscat(QuotedCmdLine, NullBuffer);
            }
        }
        else
        {
            /* We can't put quotes around the thing, so try it anyway */
            if (QuotesNeeded) QuotesNeeded = FALSE;
            if (CmdLineIsAppName) CmdLineIsAppName = FALSE;
        }
    }

    /* Use isolation if needed */
    if (CreateProcessMsg->Sxs.Flags & 1) ParameterFlags |= 1;

    /* Set the new command-line if needed */
    if ((QuotesNeeded) || (CmdLineIsAppName)) lpCommandLine = QuotedCmdLine;

    /* Call the helper function in charge of RTL_USER_PROCESS_PARAMETERS */
    Result = BasePushProcessParameters(ParameterFlags,
                                       ProcessHandle,
                                       RemotePeb,
                                       lpApplicationName,
                                       CurrentDirectory,
                                       lpCommandLine,
                                       lpEnvironment,
                                       &StartupInfo,
                                       dwCreationFlags | NoWindow,
                                       bInheritHandles,
                                       IsWowApp ? IMAGE_SUBSYSTEM_WINDOWS_GUI: 0,
                                       AppCompatData,
                                       AppCompatDataSize);
    if (!Result)
    {
        /* The remote process would have an undefined state, so fail the call */
        DPRINT1("BasePushProcessParameters failed\n");
        goto Quickie;
    }

    /* Free the VDM command line string as it's no longer needed */
    RtlFreeUnicodeString(&VdmString);
    VdmString.Buffer = NULL;

    /* Non-VDM console applications usually inherit handles unless specified */
    if (!(VdmBinaryType) &&
        !(bInheritHandles) &&
        !(StartupInfo.dwFlags & STARTF_USESTDHANDLES) &&
        !(dwCreationFlags & (CREATE_NO_WINDOW |
                             CREATE_NEW_CONSOLE |
                             DETACHED_PROCESS)) &&
        (ImageInformation.SubSystemType == IMAGE_SUBSYSTEM_WINDOWS_CUI))
    {
        /* Get the remote parameters */
        Status = NtReadVirtualMemory(ProcessHandle,
                                     &RemotePeb->ProcessParameters,
                                     &ProcessParameters,
                                     sizeof(PRTL_USER_PROCESS_PARAMETERS),
                                     NULL);
        if (NT_SUCCESS(Status))
        {
            /* Duplicate standard input unless it's a console handle */
            if (!IsConsoleHandle(Peb->ProcessParameters->StandardInput))
            {
                StuffStdHandle(ProcessHandle,
                               Peb->ProcessParameters->StandardInput,
                               &ProcessParameters->StandardInput);
            }

            /* Duplicate standard output unless it's a console handle */
            if (!IsConsoleHandle(Peb->ProcessParameters->StandardOutput))
            {
                StuffStdHandle(ProcessHandle,
                               Peb->ProcessParameters->StandardOutput,
                               &ProcessParameters->StandardOutput);
            }

            /* Duplicate standard error unless it's a console handle */
            if (!IsConsoleHandle(Peb->ProcessParameters->StandardError))
            {
                StuffStdHandle(ProcessHandle,
                               Peb->ProcessParameters->StandardError,
                               &ProcessParameters->StandardError);
            }
        }
    }

    /* Create the Thread's Stack */
    StackSize = max(256 * 1024, ImageInformation.MaximumStackSize);
    Status = BaseCreateStack(ProcessHandle,
                             ImageInformation.CommittedStackSize,
                             StackSize,
                             &InitialTeb);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Creating the thread stack failed: %lx\n", Status);
        BaseSetLastNTError(Status);
        Result = FALSE;
        goto Quickie;
    }

    /* Create the Thread's Context */
    BaseInitializeContext(&Context,
                          Peb,
                          ImageInformation.TransferAddress,
                          InitialTeb.StackBase,
                          0);

    /* Convert the thread attributes */
    ObjectAttributes = BaseFormatObjectAttributes(&LocalObjectAttributes,
                                                  lpThreadAttributes,
                                                  NULL);
    if ((hUserToken) && (lpThreadAttributes))
    {
        /* If the caller specified a user token, zero the security descriptor */
        LocalThreadAttributes = *lpThreadAttributes;
        LocalThreadAttributes.lpSecurityDescriptor = NULL;
        ObjectAttributes = BaseFormatObjectAttributes(&LocalObjectAttributes,
                                                      &LocalThreadAttributes,
                                                      NULL);
    }

    /* Create the Kernel Thread Object */
    Status = NtCreateThread(&ThreadHandle,
                            THREAD_ALL_ACCESS,
                            ObjectAttributes,
                            ProcessHandle,
                            &ClientId,
                            &Context,
                            &InitialTeb,
                            TRUE);
    if (!NT_SUCCESS(Status))
    {
        /* A process is not allowed to exist without a main thread, so fail */
        DPRINT1("Creating the main thread failed: %lx\n", Status);
        BaseSetLastNTError(Status);
        Result = FALSE;
        goto Quickie;
    }

    /* Begin filling out the CSRSS message, first with our IDs and handles */
    CreateProcessMsg->ProcessHandle = ProcessHandle;
    CreateProcessMsg->ThreadHandle = ThreadHandle;
    CreateProcessMsg->ClientId = ClientId;

    /* Write the remote PEB address and clear it locally, we no longer use it */
    CreateProcessMsg->PebAddressNative = RemotePeb;
#ifdef _WIN64
    DPRINT1("TODO: WOW64 is not supported yet\n");
    CreateProcessMsg->PebAddressWow64 = 0;
#else
    CreateProcessMsg->PebAddressWow64 = (ULONG)RemotePeb;
#endif
    RemotePeb = NULL;

    /* Now check what kind of architecture this image was made for */
    switch (ImageInformation.Machine)
    {
        /* IA32, IA64 and AMD64 are supported in Server 2003 */
        case IMAGE_FILE_MACHINE_I386:
            CreateProcessMsg->ProcessorArchitecture = PROCESSOR_ARCHITECTURE_INTEL;
            break;
        case IMAGE_FILE_MACHINE_IA64:
            CreateProcessMsg->ProcessorArchitecture = PROCESSOR_ARCHITECTURE_IA64;
            break;
        case IMAGE_FILE_MACHINE_AMD64:
            CreateProcessMsg->ProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64;
            break;

        /* Anything else results in image unknown -- but no failure */
        default:
            DbgPrint("kernel32: No mapping for ImageInformation.Machine == %04x\n",
                     ImageInformation.Machine);
            CreateProcessMsg->ProcessorArchitecture = PROCESSOR_ARCHITECTURE_UNKNOWN;
            break;
    }

    /* Write the input creation flags except any debugger-related flags */
    CreateProcessMsg->CreationFlags = dwCreationFlags &
                                      ~(DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS);

    /* CSRSS needs to know if this is a GUI app or not */
    if ((ImageInformation.SubSystemType == IMAGE_SUBSYSTEM_WINDOWS_GUI) ||
        (IsWowApp))
    {
        /*
         * For GUI apps we turn on the 2nd bit. This allow CSRSS server dlls
         * (basesrv in particular) to know whether or not this is a GUI or a
         * TUI application.
         */
        AddToHandle(CreateProcessMsg->ProcessHandle, 2);

        /* Also check if the parent is also a GUI process */
        NtHeaders = RtlImageNtHeader(GetModuleHandle(NULL));
        if ((NtHeaders) &&
            (NtHeaders->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI))
        {
            /* Let it know that it should display the hourglass mouse cursor */
            AddToHandle(CreateProcessMsg->ProcessHandle, 1);
        }
    }

    /* For all apps, if this flag is on, the hourglass mouse cursor is shown */
    if (StartupInfo.dwFlags & STARTF_FORCEONFEEDBACK)
    {
        AddToHandle(CreateProcessMsg->ProcessHandle, 1);
    }

    /* Likewise, the opposite holds as well */
    if (StartupInfo.dwFlags & STARTF_FORCEOFFFEEDBACK)
    {
        RemoveFromHandle(CreateProcessMsg->ProcessHandle, 1);
    }

    /* Also store which kind of VDM app (if any) this is */
    CreateProcessMsg->VdmBinaryType = VdmBinaryType;

    /* And if it really is a VDM app... */
    if (VdmBinaryType)
    {
        /* Store the task ID and VDM console handle */
        CreateProcessMsg->hVDM = VdmTask ? 0 : Peb->ProcessParameters->ConsoleHandle;
        CreateProcessMsg->VdmTask = VdmTask;
    }
    else if (VdmReserve)
    {
        /* Extended VDM, set a flag */
        CreateProcessMsg->VdmBinaryType |= BINARY_TYPE_WOW_EX;
    }

    /* Check if there's side-by-side assembly data associated with the process */
    if (CreateProcessMsg->Sxs.Flags)
    {
        /* This should not happen in ReactOS yet */
        DPRINT1("This is an SxS Message -- should not happen yet\n");
        BaseSetLastNTError(STATUS_NOT_IMPLEMENTED);
        NtTerminateProcess(ProcessHandle, STATUS_NOT_IMPLEMENTED);
        Result = FALSE;
        goto Quickie;
    }

    /* We are finally ready to call CSRSS to tell it about our new process! */
    CsrClientCallServer((PCSR_API_MESSAGE)&CsrMsg[0],
                        CaptureBuffer,
                        CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX,
                                              BasepCreateProcess),
                        sizeof(*CreateProcessMsg));

    /* CSRSS has returned, free the capture buffer now if we had one */
    if (CaptureBuffer)
    {
        CsrFreeCaptureBuffer(CaptureBuffer);
        CaptureBuffer = NULL;
    }

    /* Check if CSRSS failed to accept ownership of the new Windows process */
    if (!NT_SUCCESS(CsrMsg[0].Status))
    {
        /* Terminate the process and enter failure path with the CSRSS status */
        DPRINT1("Failed to tell csrss about new process\n");
        BaseSetLastNTError(CsrMsg[0].Status);
        NtTerminateProcess(ProcessHandle, CsrMsg[0].Status);
        Result = FALSE;
        goto Quickie;
    }

    /* Check if we have a token due to Authz/Safer, not passed by the user */
    if ((TokenHandle) && !(hUserToken))
    {
        /* Replace the process and/or thread token with the one from Safer */
        Status = BasepReplaceProcessThreadTokens(TokenHandle,
                                                 ProcessHandle,
                                                 ThreadHandle);
        if (!NT_SUCCESS(Status))
        {
            /* If this failed, kill the process and enter the failure path */
            DPRINT1("Failed to update process token: %lx\n", Status);
            NtTerminateProcess(ProcessHandle, Status);
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }
    }

    /* Check if a job was associated with this process */
    if (JobHandle)
    {
        /* Bind the process and job together now */
        Status = NtAssignProcessToJobObject(JobHandle, ProcessHandle);
        if (!NT_SUCCESS(Status))
        {
            /* Kill the process and enter the failure path if binding failed */
            DPRINT1("Failed to assign process to job: %lx\n", Status);
            NtTerminateProcess(ProcessHandle, STATUS_ACCESS_DENIED);
            BaseSetLastNTError(Status);
            Result = FALSE;
            goto Quickie;
        }
    }

    /* Finally, resume the thread to actually get the process started */
    if (!(dwCreationFlags & CREATE_SUSPENDED))
    {
        NtResumeThread(ThreadHandle, &ResumeCount);
    }

VdmShortCircuit:
    /* We made it this far, meaning we have a fully created process and thread */
    Result = TRUE;

    /* Anyone doing a VDM undo should now undo everything, since we are done */
    if (VdmUndoLevel) VdmUndoLevel |= VDM_UNDO_COMPLETED;

    /* Having a VDM wait object implies this must be a VDM process */
    if (VdmWaitObject)
    {
        /* Check if it's a 16-bit separate WOW process */
        if (VdmBinaryType == BINARY_TYPE_SEPARATE_WOW)
        {
            /* OR-in the special flag to indicate this, and return to caller */
            AddToHandle(VdmWaitObject, 2);
            lpProcessInformation->hProcess = VdmWaitObject;

            /* Check if this was a re-used VDM */
            if (VdmUndoLevel & VDM_UNDO_REUSE)
            {
                /* No Client ID should be returned in this case */
                ClientId.UniqueProcess = 0;
                ClientId.UniqueThread = 0;
            }
        }
        else
        {
            /* OR-in the special flag to indicate this is not a separate VDM */
            AddToHandle(VdmWaitObject, 1);

            /* Return handle to the caller */
            lpProcessInformation->hProcess = VdmWaitObject;
        }

        /* Close the original process handle, since it's not needed for VDM */
        if (ProcessHandle) NtClose(ProcessHandle);
    }
    else
    {
        /* This is a regular process, so return the real process handle */
        lpProcessInformation->hProcess = ProcessHandle;
    }

    /* Return the rest of the process information based on what we have so far */
    lpProcessInformation->hThread = ThreadHandle;
    lpProcessInformation->dwProcessId = HandleToUlong(ClientId.UniqueProcess);
    lpProcessInformation->dwThreadId = HandleToUlong(ClientId.UniqueThread);

    /* NULL these out here so we know to treat this as a success scenario */
    ProcessHandle = NULL;
    ThreadHandle = NULL;

Quickie:
    /* Free the debugger command line if one was allocated */
    if (DebuggerCmdLine) RtlFreeHeap(RtlGetProcessHeap(), 0, DebuggerCmdLine);

    /* Check if an SxS full path as queried */
    if (PathBuffer)
    {
        /* Reinitialize the executable path */
        RtlInitEmptyUnicodeString(&SxsWin32ExePath, NULL, 0);
        SxsWin32ExePath.Length = 0;

        /* Free the path buffer */
        RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer);
    }

#if _SXS_SUPPORT_ENABLED_
    /* Check if this was a non-VDM process */
    if (!VdmBinaryType)
    {
        /* Then it must've had SxS data, so close the handles used for it */
        BasepSxsCloseHandles(&Handles);
        BasepSxsCloseHandles(&FileHandles);

        /* Check if we built SxS byte buffers for this create process request */
        if (SxsConglomeratedBuffer)
        {
            /* Loop all of them */
            for (i = 0; i < 5; i++)
            {
                /* Check if this one was allocated */
                ThisBuffer = SxsStaticBuffers[i];<--- The address of local variable 'SxsWin32ManifestPath' might be accessed at non-zero index.
                if (ThisBuffer)
                {
                    /* Get the underlying RTL_BUFFER structure */
                    ByteBuffer = &ThisBuffer->ByteBuffer;
                    if ((ThisBuffer != (PVOID)-8) && (ByteBuffer->Buffer))
                    {
                        /* Check if it was dynamic */
                        if (ByteBuffer->Buffer != ByteBuffer->StaticBuffer)
                        {
                            /* Free it from the heap */
                            FreeString.Buffer = (PWCHAR)ByteBuffer->Buffer;
                            RtlFreeUnicodeString(&FreeString);
                        }

                        /* Reset the buffer to its static data */
                        ByteBuffer->Buffer = ByteBuffer->StaticBuffer;
                        ByteBuffer->Size = ByteBuffer->StaticSize;
                    }

                    /* Reset the string to the static buffer */
                    RtlInitEmptyUnicodeString(&ThisBuffer->String,
                                              (PWCHAR)ByteBuffer->StaticBuffer,
                                              ByteBuffer->StaticSize);
                    if (ThisBuffer->String.Buffer)
                    {
                        /* Also NULL-terminate it */
                        *ThisBuffer->String.Buffer = UNICODE_NULL;
                    }
                }
            }
        }
    }
#endif
    /* Check if an environment was passed in */
    if ((lpEnvironment) && !(dwCreationFlags & CREATE_UNICODE_ENVIRONMENT))
    {
        /* Destroy it */
        RtlDestroyEnvironment(lpEnvironment);

        /* If this was the VDM environment too, clear that as well */
        if (VdmUnicodeEnv.Buffer == lpEnvironment) VdmUnicodeEnv.Buffer = NULL;
        lpEnvironment = NULL;
    }

    /* Unconditionally free all the name parsing buffers we always allocate */
    RtlFreeHeap(RtlGetProcessHeap(), 0, QuotedCmdLine);
    RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer);
    RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentDirectory);
    RtlFreeHeap(RtlGetProcessHeap(), 0, FreeBuffer);

    /* Close open file/section handles */
    if (FileHandle) NtClose(FileHandle);
    if (SectionHandle) NtClose(SectionHandle);

    /* If we have a thread handle, this was a failure path */
    if (ThreadHandle)
    {
        /* So kill the process and close the thread handle */
        NtTerminateProcess(ProcessHandle, 0);
        NtClose(ThreadHandle);
    }

    /* If we have a process handle, this was a failure path, so close it */
    if (ProcessHandle) NtClose(ProcessHandle);

    /* Thread/process handles, if any, are now processed. Now close this one. */
    if (JobHandle) NtClose(JobHandle);

    /* Check if we had created a token */
    if (TokenHandle)
    {
        /* And if the user asked for one */
        if (hUserToken)
        {
            /* Then return it */
            *hNewToken = TokenHandle;
        }
        else
        {
            /* User didn't want it, so we used it temporarily -- close it */
            NtClose(TokenHandle);
        }
    }

    /* Free any temporary app compatibility data, it's no longer needed */
    BasepFreeAppCompatData(AppCompatData, AppCompatSxsData);

    /* Free a few strings. The API takes care of these possibly being NULL */
    RtlFreeUnicodeString(&VdmString);
    RtlFreeUnicodeString(&DebuggerString);

    /* Check if we had built any sort of VDM environment */
    if ((VdmAnsiEnv.Buffer) || (VdmUnicodeEnv.Buffer))
    {
        /* Free it */
        BaseDestroyVDMEnvironment(&VdmAnsiEnv, &VdmUnicodeEnv);
    }

    /* Check if this was any kind of VDM application that we ended up creating */
    if ((VdmUndoLevel) && (!(VdmUndoLevel & VDM_UNDO_COMPLETED)))
    {
        /* Send an undo */
        BaseUpdateVDMEntry(VdmEntryUndo,
                           (PHANDLE)&VdmTask,
                           VdmUndoLevel,
                           VdmBinaryType);

        /* And close whatever VDM handle we were using for notifications */
        if (VdmWaitObject) NtClose(VdmWaitObject);
    }

    /* Check if we ended up here with an allocated search path, and free it */
    if (SearchPath) RtlFreeHeap(RtlGetProcessHeap(), 0, SearchPath);

    /* Finally, return the API's result */
    return Result;
}

/*
 * @implemented
 */
BOOL
WINAPI
DECLSPEC_HOTPATCH
CreateProcessW(LPCWSTR lpApplicationName,
               LPWSTR lpCommandLine,
               LPSECURITY_ATTRIBUTES lpProcessAttributes,
               LPSECURITY_ATTRIBUTES lpThreadAttributes,
               BOOL bInheritHandles,
               DWORD dwCreationFlags,
               LPVOID lpEnvironment,
               LPCWSTR lpCurrentDirectory,
               LPSTARTUPINFOW lpStartupInfo,
               LPPROCESS_INFORMATION lpProcessInformation)
{
    /* Call the internal (but exported) version */
    return CreateProcessInternalW(NULL,
                                  lpApplicationName,
                                  lpCommandLine,
                                  lpProcessAttributes,
                                  lpThreadAttributes,
                                  bInheritHandles,
                                  dwCreationFlags,
                                  lpEnvironment,
                                  lpCurrentDirectory,
                                  lpStartupInfo,
                                  lpProcessInformation,
                                  NULL);
}

/*
 * @implemented
 */
BOOL
WINAPI
CreateProcessInternalA(HANDLE hToken,
                       LPCSTR lpApplicationName,
                       LPSTR lpCommandLine,
                       LPSECURITY_ATTRIBUTES lpProcessAttributes,
                       LPSECURITY_ATTRIBUTES lpThreadAttributes,
                       BOOL bInheritHandles,
                       DWORD dwCreationFlags,
                       LPVOID lpEnvironment,
                       LPCSTR lpCurrentDirectory,
                       LPSTARTUPINFOA lpStartupInfo,
                       LPPROCESS_INFORMATION lpProcessInformation,
                       PHANDLE hNewToken)
{
    UNICODE_STRING CommandLine;
    UNICODE_STRING ApplicationName;
    UNICODE_STRING CurrentDirectory;
    BOOL bRetVal;
    STARTUPINFOW StartupInfo;

    DPRINT("dwCreationFlags %x, lpEnvironment %p, lpCurrentDirectory %p, "
            "lpStartupInfo %p, lpProcessInformation %p\n",
            dwCreationFlags, lpEnvironment, lpCurrentDirectory,
            lpStartupInfo, lpProcessInformation);

    /* Copy Startup Info */
    RtlMoveMemory(&StartupInfo, lpStartupInfo, sizeof(*lpStartupInfo));

    /* Initialize all strings to nothing */
    CommandLine.Buffer = NULL;
    ApplicationName.Buffer = NULL;
    CurrentDirectory.Buffer = NULL;
    StartupInfo.lpDesktop = NULL;
    StartupInfo.lpReserved = NULL;
    StartupInfo.lpTitle = NULL;

    /* Convert the Command line */
    if (lpCommandLine)
    {
        Basep8BitStringToDynamicUnicodeString(&CommandLine,
                                              lpCommandLine);
    }

    /* Convert the Name and Directory */
    if (lpApplicationName)
    {
        Basep8BitStringToDynamicUnicodeString(&ApplicationName,
                                              lpApplicationName);
    }
    if (lpCurrentDirectory)
    {
        Basep8BitStringToDynamicUnicodeString(&CurrentDirectory,
                                              lpCurrentDirectory);
    }

    /* Now convert Startup Strings */
    if (lpStartupInfo->lpReserved)
    {
        BasepAnsiStringToHeapUnicodeString(lpStartupInfo->lpReserved,
                                           &StartupInfo.lpReserved);
    }
    if (lpStartupInfo->lpDesktop)
    {
        BasepAnsiStringToHeapUnicodeString(lpStartupInfo->lpDesktop,
                                           &StartupInfo.lpDesktop);
    }
    if (lpStartupInfo->lpTitle)
    {
        BasepAnsiStringToHeapUnicodeString(lpStartupInfo->lpTitle,
                                           &StartupInfo.lpTitle);
    }

    /* Call the Unicode function */
    bRetVal = CreateProcessInternalW(hToken,
                                     ApplicationName.Buffer,
                                     CommandLine.Buffer,
                                     lpProcessAttributes,
                                     lpThreadAttributes,
                                     bInheritHandles,
                                     dwCreationFlags,
                                     lpEnvironment,
                                     CurrentDirectory.Buffer,
                                     &StartupInfo,
                                     lpProcessInformation,
                                     hNewToken);

    /* Clean up */
    RtlFreeUnicodeString(&ApplicationName);
    RtlFreeUnicodeString(&CommandLine);
    RtlFreeUnicodeString(&CurrentDirectory);
    RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo.lpDesktop);
    RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo.lpReserved);
    RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo.lpTitle);

    /* Return what Unicode did */
    return bRetVal;
}

/*
 * FUNCTION: The CreateProcess function creates a new process and its
 * primary thread. The new process executes the specified executable file
 * ARGUMENTS:
 *
 *     lpApplicationName = Pointer to name of executable module
 *     lpCommandLine = Pointer to command line string
 *     lpProcessAttributes = Process security attributes
 *     lpThreadAttributes = Thread security attributes
 *     bInheritHandles = Handle inheritance flag
 *     dwCreationFlags = Creation flags
 *     lpEnvironment = Pointer to new environment block
 *     lpCurrentDirectory = Pointer to current directory name
 *     lpStartupInfo = Pointer to startup info
 *     lpProcessInformation = Pointer to process information
 *
 * @implemented
 */
BOOL
WINAPI
DECLSPEC_HOTPATCH
CreateProcessA(LPCSTR lpApplicationName,
               LPSTR lpCommandLine,
               LPSECURITY_ATTRIBUTES lpProcessAttributes,
               LPSECURITY_ATTRIBUTES lpThreadAttributes,
               BOOL bInheritHandles,
               DWORD dwCreationFlags,
               LPVOID lpEnvironment,
               LPCSTR lpCurrentDirectory,
               LPSTARTUPINFOA lpStartupInfo,
               LPPROCESS_INFORMATION lpProcessInformation)
{
    /* Call the internal (but exported) version */
    return CreateProcessInternalA(NULL,
                                  lpApplicationName,
                                  lpCommandLine,
                                  lpProcessAttributes,
                                  lpThreadAttributes,
                                  bInheritHandles,
                                  dwCreationFlags,
                                  lpEnvironment,
                                  lpCurrentDirectory,
                                  lpStartupInfo,
                                  lpProcessInformation,
                                  NULL);
}

/*
 * @implemented
 */
UINT
WINAPI
DECLSPEC_HOTPATCH
WinExec(LPCSTR lpCmdLine,
        UINT uCmdShow)
{
    STARTUPINFOA StartupInfo;
    PROCESS_INFORMATION  ProcessInformation;
    DWORD dosErr;

    RtlZeroMemory(&StartupInfo, sizeof(StartupInfo));
    StartupInfo.cb = sizeof(STARTUPINFOA);
    StartupInfo.wShowWindow = (WORD)uCmdShow;
    StartupInfo.dwFlags = 0;

    if (!CreateProcessA(NULL,
                        (PVOID)lpCmdLine,
                        NULL,
                        NULL,
                        FALSE,
                        0,
                        NULL,
                        NULL,
                        &StartupInfo,
                        &ProcessInformation))
    {
        dosErr = GetLastError();
        return dosErr < 32 ? dosErr : ERROR_BAD_FORMAT;
    }

    if (NULL != UserWaitForInputIdleRoutine)
    {
        UserWaitForInputIdleRoutine(ProcessInformation.hProcess,
                                           10000);
    }

    NtClose(ProcessInformation.hProcess);
    NtClose(ProcessInformation.hThread);

    return 33; /* Something bigger than 31 means success. */
}

/* EOF */